OBSBasic_SceneCollections.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include "OBSBasic.hpp"
  15. #include <dialogs/OBSMissingFiles.hpp>
  16. #include <importer/OBSImporter.hpp>
  17. #include <models/SceneCollection.hpp>
  18. #include <utility/item-widget-helpers.hpp>
  19. #include <qt-wrappers.hpp>
  20. #include <QDir>
  21. #include <filesystem>
  22. #include <string>
  23. #include <vector>
  24. extern bool safe_mode;
  25. extern bool opt_start_streaming;
  26. extern bool opt_start_recording;
  27. extern bool opt_start_virtualcam;
  28. extern bool opt_start_replaybuffer;
  29. extern std::string opt_starting_scene;
  30. using SceneCoordinateMode = OBS::SceneCoordinateMode;
  31. using SceneCollection = OBS::SceneCollection;
  32. // MARK: Constant Expressions
  33. static constexpr std::string_view SceneCollectionPath = "/obs-studio/basic/scenes/";
  34. namespace DataKeys {
  35. static constexpr std::string_view AbsoluteCoordinates = "AbsoluteCoordinates";
  36. static constexpr std::string_view MigrationResolution = "migration_resolution";
  37. } // namespace DataKeys
  38. namespace L10N {
  39. static constexpr std::string_view Migrate = "Basic.MainMenu.SceneCollection.Migrate";
  40. static constexpr std::string_view Remigrate = "Basic.MainMenu.SceneCollection.Remigrate";
  41. } // namespace L10N
  42. // MARK: - Anonymous Namespace
  43. namespace {
  44. QList<QString> sortedSceneCollections{};
  45. void updateSortedSceneCollections(const OBSSceneCollectionCache &collections)
  46. {
  47. const QLocale locale = QLocale::system();
  48. QList<QString> newList{};
  49. for (auto [collectionName, _] : collections) {
  50. QString entry = QString::fromStdString(collectionName);
  51. newList.append(entry);
  52. }
  53. std::sort(newList.begin(), newList.end(), [&locale](const QString &lhs, const QString &rhs) -> bool {
  54. int result = QString::localeAwareCompare(locale.toLower(lhs), locale.toLower(rhs));
  55. return (result < 0);
  56. });
  57. sortedSceneCollections.swap(newList);
  58. }
  59. void cleanBackupCollision(const SceneCollection &collection)
  60. {
  61. std::filesystem::path backupFilePath = collection.getFilePath();
  62. backupFilePath.replace_extension(".json.bak");
  63. if (std::filesystem::exists(backupFilePath)) {
  64. try {
  65. std::filesystem::remove(backupFilePath);
  66. } catch (std::filesystem::filesystem_error &) {
  67. throw std::logic_error("Failed to remove pre-existing scene collection backup file: " +
  68. backupFilePath.u8string());
  69. }
  70. }
  71. }
  72. void updateRemigrationMenuItem(SceneCoordinateMode mode, QAction *menuItem)
  73. {
  74. bool isAbsoluteCoordinateMode = mode == SceneCoordinateMode::Absolute;
  75. OBSDataAutoRelease privateData = obs_get_private_data();
  76. obs_data_set_bool(privateData, DataKeys::AbsoluteCoordinates.data(), isAbsoluteCoordinateMode);
  77. if (isAbsoluteCoordinateMode) {
  78. menuItem->setText(QTStr(L10N::Migrate.data()));
  79. } else {
  80. menuItem->setText(QTStr(L10N::Remigrate.data()));
  81. }
  82. menuItem->setEnabled(isAbsoluteCoordinateMode);
  83. }
  84. void removeRelativePositionData(obs_data_t *settings)
  85. {
  86. OBSDataArrayAutoRelease sources = obs_data_get_array(settings, "sources");
  87. auto iterateCallback = [](obs_data_t *data, void *) {
  88. const std::string_view id{obs_data_get_string(data, "id")};
  89. if (id != "scene" && id != "group") {
  90. return;
  91. }
  92. OBSDataAutoRelease settings = obs_data_get_obj(data, "settings");
  93. OBSDataArrayAutoRelease items = obs_data_get_array(settings, "items");
  94. auto cleanupCallback = [](obs_data_t *data, void *) {
  95. obs_data_unset_user_value(data, "pos_rel");
  96. obs_data_unset_user_value(data, "scale_rel");
  97. obs_data_unset_user_value(data, "scale_ref");
  98. obs_data_unset_user_value(data, "bounds_rel");
  99. };
  100. obs_data_array_enum(items, cleanupCallback, nullptr);
  101. };
  102. obs_data_array_enum(sources, iterateCallback, nullptr);
  103. }
  104. } // namespace
  105. // MARK: - Main Scene Collection Management Functions
  106. void OBSBasic::SetupNewSceneCollection(const std::string &collectionName)
  107. {
  108. if (collectionName.empty()) {
  109. throw std::logic_error("Cannot create new scene collection with empty collection name");
  110. }
  111. SceneCollection &newCollection = CreateSceneCollection(collectionName);
  112. OnEvent(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CHANGING);
  113. cleanBackupCollision(newCollection);
  114. ActivateSceneCollection(newCollection);
  115. blog(LOG_INFO, "Created scene collection '%s' (clean, %s)", newCollection.getName().c_str(),
  116. newCollection.getFileName().c_str());
  117. blog(LOG_INFO, "------------------------------------------------");
  118. }
  119. void OBSBasic::SetupDuplicateSceneCollection(const std::string &collectionName)
  120. {
  121. const SceneCollection &currentCollection = GetCurrentSceneCollection();
  122. SceneCollection &newCollection = CreateSceneCollection(collectionName);
  123. SaveProjectNow();
  124. const auto copyOptions = std::filesystem::copy_options::overwrite_existing;
  125. try {
  126. std::filesystem::copy(currentCollection.getFilePath(), newCollection.getFilePath(), copyOptions);
  127. } catch (const std::filesystem::filesystem_error &error) {
  128. blog(LOG_DEBUG, "%s", error.what());
  129. throw std::logic_error("Failed to copy file for cloned scene collection: " + newCollection.getName());
  130. }
  131. OBSDataAutoRelease collection = obs_data_create_from_json_file(newCollection.getFileName().c_str());
  132. obs_data_set_string(collection, "name", newCollection.getName().c_str());
  133. OBSDataArrayAutoRelease sources = obs_data_get_array(collection, "sources");
  134. if (sources) {
  135. obs_data_erase(collection, "sources");
  136. obs_data_array_enum(
  137. sources,
  138. [](obs_data_t *data, void *) -> void {
  139. const char *uuid = os_generate_uuid();
  140. obs_data_set_string(data, "uuid", uuid);
  141. bfree((void *)uuid);
  142. },
  143. nullptr);
  144. obs_data_set_array(collection, "sources", sources);
  145. }
  146. obs_data_save_json_safe(collection, newCollection.getFileName().c_str(), "tmp", nullptr);
  147. cleanBackupCollision(newCollection);
  148. ActivateSceneCollection(newCollection);
  149. blog(LOG_INFO, "Created scene collection '%s' (duplicate, %s)", newCollection.getName().c_str(),
  150. newCollection.getFileName().c_str());
  151. blog(LOG_INFO, "------------------------------------------------");
  152. }
  153. void OBSBasic::SetupRenameSceneCollection(const std::string &collectionName)
  154. {
  155. const SceneCollection currentCollection = GetCurrentSceneCollection();
  156. SceneCollection &newCollection = CreateSceneCollection(collectionName);
  157. SaveProjectNow();
  158. const auto copyOptions = std::filesystem::copy_options::overwrite_existing;
  159. try {
  160. std::filesystem::copy(currentCollection.getFilePath(), newCollection.getFilePath(), copyOptions);
  161. } catch (const std::filesystem::filesystem_error &error) {
  162. blog(LOG_DEBUG, "%s", error.what());
  163. throw std::logic_error("Failed to copy file for scene collection: " + currentCollection.getName());
  164. }
  165. collections.erase(currentCollection.getName());
  166. OBSDataAutoRelease collection = obs_data_create_from_json_file(newCollection.getFileName().c_str());
  167. obs_data_set_string(collection, "name", newCollection.getName().c_str());
  168. obs_data_save_json_safe(collection, newCollection.getFileName().c_str(), "tmp", nullptr);
  169. cleanBackupCollision(newCollection);
  170. ActivateSceneCollection(newCollection);
  171. RemoveSceneCollection(currentCollection);
  172. blog(LOG_INFO, "Renamed scene collection '%s' to '%s' (%s)", currentCollection.getName().c_str(),
  173. newCollection.getName().c_str(), newCollection.getFileName().c_str());
  174. blog(LOG_INFO, "------------------------------------------------");
  175. OnEvent(OBS_FRONTEND_EVENT_SCENE_COLLECTION_RENAMED);
  176. }
  177. // MARK: - Scene Collection File Management Functions
  178. SceneCollection &OBSBasic::CreateSceneCollection(const std::string &collectionName)
  179. {
  180. if (const auto &foundCollection = GetSceneCollectionByName(collectionName)) {
  181. throw std::invalid_argument("Scene collection already exists: " + collectionName);
  182. }
  183. std::string fileName;
  184. if (!GetFileSafeName(collectionName.c_str(), fileName)) {
  185. throw std::invalid_argument("Failed to create safe directory for new scene collection: " +
  186. collectionName);
  187. }
  188. std::string collectionFile;
  189. collectionFile.reserve(App()->userScenesLocation.u8string().size() + SceneCollectionPath.size() +
  190. fileName.size());
  191. collectionFile.append(App()->userScenesLocation.u8string()).append(SceneCollectionPath).append(fileName);
  192. if (!GetClosestUnusedFileName(collectionFile, "json")) {
  193. throw std::invalid_argument("Failed to get closest file name for new scene collection: " + fileName);
  194. }
  195. std::filesystem::path collectionFilePath = std::filesystem::u8path(collectionFile);
  196. auto [iterator, success] =
  197. collections.try_emplace(collectionName, collectionName, std::move(collectionFilePath));
  198. return iterator->second;
  199. }
  200. void OBSBasic::RemoveSceneCollection(SceneCollection collection)
  201. {
  202. try {
  203. std::filesystem::remove(collection.getFilePath());
  204. } catch (const std::filesystem::filesystem_error &error) {
  205. blog(LOG_DEBUG, "%s", error.what());
  206. throw std::logic_error("Failed to remove scene collection file: " + collection.getFileName());
  207. }
  208. blog(LOG_INFO, "Removed scene collection '%s' (%s)", collection.getName().c_str(),
  209. collection.getFileName().c_str());
  210. blog(LOG_INFO, "------------------------------------------------");
  211. }
  212. // MARK: - Scene Collection UI Handling Functions
  213. bool OBSBasic::CreateNewSceneCollection(const QString &name)
  214. {
  215. try {
  216. SetupNewSceneCollection(name.toStdString());
  217. return true;
  218. } catch (const std::invalid_argument &error) {
  219. blog(LOG_ERROR, "%s", error.what());
  220. return false;
  221. } catch (const std::logic_error &error) {
  222. blog(LOG_ERROR, "%s", error.what());
  223. return false;
  224. }
  225. }
  226. bool OBSBasic::CreateDuplicateSceneCollection(const QString &name)
  227. {
  228. try {
  229. SetupDuplicateSceneCollection(name.toStdString());
  230. return true;
  231. } catch (const std::invalid_argument &error) {
  232. blog(LOG_ERROR, "%s", error.what());
  233. return false;
  234. } catch (const std::logic_error &error) {
  235. blog(LOG_ERROR, "%s", error.what());
  236. return false;
  237. }
  238. }
  239. void OBSBasic::DeleteSceneCollection(const QString &name)
  240. {
  241. const std::string_view currentCollectionName{
  242. config_get_string(App()->GetUserConfig(), "Basic", "SceneCollection")};
  243. if (currentCollectionName == name.toStdString()) {
  244. on_actionRemoveSceneCollection_triggered();
  245. return;
  246. }
  247. SceneCollection currentCollection = GetCurrentSceneCollection();
  248. RemoveSceneCollection(currentCollection);
  249. collections.erase(name.toStdString());
  250. RefreshSceneCollections();
  251. OnEvent(OBS_FRONTEND_EVENT_SCENE_COLLECTION_LIST_CHANGED);
  252. }
  253. void OBSBasic::ChangeSceneCollection()
  254. {
  255. QAction *action = reinterpret_cast<QAction *>(sender());
  256. if (!action) {
  257. return;
  258. }
  259. const std::string_view currentCollectionName{
  260. config_get_string(App()->GetUserConfig(), "Basic", "SceneCollection")};
  261. const QVariant qCollectionName = action->property("collection_name");
  262. const std::string selectedCollectionName{qCollectionName.toString().toStdString()};
  263. if (currentCollectionName == selectedCollectionName) {
  264. action->setChecked(true);
  265. return;
  266. }
  267. auto foundCollection = GetSceneCollectionByName(selectedCollectionName);
  268. if (!foundCollection) {
  269. const std::string errorMessage{"Selected scene collection not found: "};
  270. throw std::invalid_argument(errorMessage + currentCollectionName.data());
  271. }
  272. SceneCollection &selectedCollection = foundCollection.value();
  273. OnEvent(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CHANGING);
  274. ActivateSceneCollection(selectedCollection);
  275. blog(LOG_INFO, "Switched to scene collection '%s' (%s)", selectedCollection.getName().c_str(),
  276. selectedCollection.getFileName().c_str());
  277. blog(LOG_INFO, "------------------------------------------------");
  278. }
  279. void OBSBasic::RefreshSceneCollections(bool refreshCache)
  280. {
  281. std::string_view currentCollectionName{config_get_string(App()->GetUserConfig(), "Basic", "SceneCollection")};
  282. QList<QAction *> menuActions = ui->sceneCollectionMenu->actions();
  283. for (auto &action : menuActions) {
  284. QVariant variant = action->property("file_name");
  285. if (variant.typeName() != nullptr) {
  286. delete action;
  287. }
  288. }
  289. if (refreshCache) {
  290. RefreshSceneCollectionCache();
  291. }
  292. updateSortedSceneCollections(collections);
  293. size_t numAddedCollections = 0;
  294. for (auto &name : sortedSceneCollections) {
  295. const std::string collectionName = name.toStdString();
  296. try {
  297. const SceneCollection &collection = collections.at(collectionName);
  298. const QString qCollectionName = QString().fromStdString(collectionName);
  299. QAction *action = new QAction(qCollectionName, this);
  300. action->setProperty("collection_name", qCollectionName);
  301. action->setProperty("file_name", QString().fromStdString(collection.getFileName()));
  302. connect(action, &QAction::triggered, this, &OBSBasic::ChangeSceneCollection);
  303. action->setCheckable(true);
  304. action->setChecked(collectionName == currentCollectionName);
  305. ui->sceneCollectionMenu->addAction(action);
  306. numAddedCollections += 1;
  307. } catch (const std::out_of_range &error) {
  308. blog(LOG_ERROR, "No scene collection with name %s found in scene collection cache.\n%s",
  309. collectionName.c_str(), error.what());
  310. }
  311. }
  312. ui->actionRemoveSceneCollection->setEnabled(numAddedCollections > 1);
  313. OBSBasic *main = OBSBasic::Get();
  314. main->ui->actionPasteFilters->setEnabled(false);
  315. main->ui->actionPasteRef->setEnabled(false);
  316. main->ui->actionPasteDup->setEnabled(false);
  317. }
  318. // MARK: - Scene Collection Cache Functions
  319. void OBSBasic::RefreshSceneCollectionCache()
  320. {
  321. OBSSceneCollectionCache foundCollections{};
  322. const std::filesystem::path collectionsPath =
  323. App()->userScenesLocation / std::filesystem::u8path(SceneCollectionPath.substr(1));
  324. if (!std::filesystem::exists(collectionsPath)) {
  325. blog(LOG_WARNING, "Failed to get scene collections config path");
  326. return;
  327. }
  328. for (const auto &entry : std::filesystem::directory_iterator(collectionsPath)) {
  329. if (entry.is_directory()) {
  330. continue;
  331. }
  332. if (entry.path().extension().u8string() != ".json") {
  333. continue;
  334. }
  335. OBSDataAutoRelease collectionData =
  336. obs_data_create_from_json_file_safe(entry.path().u8string().c_str(), "bak");
  337. std::string candidateName;
  338. std::string collectionName = obs_data_get_string(collectionData, "name");
  339. if (collectionName.empty()) {
  340. candidateName = entry.path().stem().u8string();
  341. } else {
  342. candidateName = std::move(collectionName);
  343. }
  344. foundCollections.try_emplace(candidateName, candidateName, entry.path());
  345. }
  346. collections.swap(foundCollections);
  347. }
  348. SceneCollection &OBSBasic::GetCurrentSceneCollection()
  349. {
  350. std::string currentCollectionName{config_get_string(App()->GetUserConfig(), "Basic", "SceneCollection")};
  351. if (currentCollectionName.empty()) {
  352. throw std::invalid_argument("No valid scene collection name in configuration Basic->SceneCollection");
  353. }
  354. const auto &foundCollection = collections.find(currentCollectionName);
  355. if (foundCollection != collections.end()) {
  356. return foundCollection->second;
  357. } else {
  358. throw std::invalid_argument("Scene collection not found in collection list: " + currentCollectionName);
  359. }
  360. }
  361. std::optional<SceneCollection> OBSBasic::GetSceneCollectionByName(const std::string &collectionName) const
  362. {
  363. auto foundCollection = collections.find(collectionName);
  364. if (foundCollection == collections.end()) {
  365. return {};
  366. } else {
  367. return foundCollection->second;
  368. }
  369. }
  370. std::optional<SceneCollection> OBSBasic::GetSceneCollectionByFileName(const std::string &fileName) const
  371. {
  372. for (auto &[iterator, collection] : collections) {
  373. if (collection.getFileName() == fileName) {
  374. return collection;
  375. }
  376. }
  377. return {};
  378. }
  379. // MARK: - Qt Slot Functions
  380. void OBSBasic::on_actionNewSceneCollection_triggered()
  381. {
  382. const OBSPromptCallback sceneCollectionCallback = [this](const OBSPromptResult &result) {
  383. if (GetSceneCollectionByName(result.promptValue)) {
  384. return false;
  385. }
  386. return true;
  387. };
  388. const OBSPromptRequest request{Str("Basic.Main.AddSceneCollection.Title"),
  389. Str("Basic.Main.AddSceneCollection.Text")};
  390. OBSPromptResult result = PromptForName(request, sceneCollectionCallback);
  391. if (!result.success) {
  392. return;
  393. }
  394. try {
  395. SetupNewSceneCollection(result.promptValue);
  396. } catch (const std::invalid_argument &error) {
  397. blog(LOG_ERROR, "%s", error.what());
  398. } catch (const std::logic_error &error) {
  399. blog(LOG_ERROR, "%s", error.what());
  400. }
  401. }
  402. void OBSBasic::on_actionDupSceneCollection_triggered()
  403. {
  404. const OBSPromptCallback sceneCollectionCallback = [this](const OBSPromptResult &result) {
  405. if (GetSceneCollectionByName(result.promptValue)) {
  406. return false;
  407. }
  408. return true;
  409. };
  410. const OBSPromptRequest request{Str("Basic.Main.AddSceneCollection.Title"),
  411. Str("Basic.Main.AddSceneCollection.Text")};
  412. OBSPromptResult result = PromptForName(request, sceneCollectionCallback);
  413. if (!result.success) {
  414. return;
  415. }
  416. try {
  417. SetupDuplicateSceneCollection(result.promptValue);
  418. } catch (const std::invalid_argument &error) {
  419. blog(LOG_ERROR, "%s", error.what());
  420. } catch (const std::logic_error &error) {
  421. blog(LOG_ERROR, "%s", error.what());
  422. }
  423. }
  424. void OBSBasic::on_actionRenameSceneCollection_triggered()
  425. {
  426. const SceneCollection &currentCollection = GetCurrentSceneCollection();
  427. const OBSPromptCallback sceneCollectionCallback = [this](const OBSPromptResult &result) {
  428. if (GetSceneCollectionByName(result.promptValue)) {
  429. return false;
  430. }
  431. return true;
  432. };
  433. const OBSPromptRequest request{Str("Basic.Main.RenameSceneCollection.Title"),
  434. Str("Basic.Main.AddSceneCollection.Text"), currentCollection.getName()};
  435. OBSPromptResult result = PromptForName(request, sceneCollectionCallback);
  436. if (!result.success) {
  437. return;
  438. }
  439. try {
  440. SetupRenameSceneCollection(result.promptValue);
  441. } catch (const std::invalid_argument &error) {
  442. blog(LOG_ERROR, "%s", error.what());
  443. } catch (const std::logic_error &error) {
  444. blog(LOG_ERROR, "%s", error.what());
  445. }
  446. }
  447. void OBSBasic::on_actionRemoveSceneCollection_triggered(bool skipConfirmation)
  448. {
  449. if (collections.size() < 2) {
  450. return;
  451. }
  452. SceneCollection currentCollection;
  453. try {
  454. currentCollection = GetCurrentSceneCollection();
  455. if (!skipConfirmation) {
  456. const QString confirmationText =
  457. QTStr("ConfirmRemove.Text").arg(QString::fromStdString(currentCollection.getName()));
  458. const QMessageBox::StandardButton button =
  459. OBSMessageBox::question(this, QTStr("ConfirmRemove.Title"), confirmationText);
  460. if (button == QMessageBox::No) {
  461. return;
  462. }
  463. }
  464. OnEvent(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CHANGING);
  465. collections.erase(currentCollection.getName());
  466. } catch (const std::invalid_argument &error) {
  467. blog(LOG_ERROR, "%s", error.what());
  468. } catch (const std::logic_error &error) {
  469. blog(LOG_ERROR, "%s", error.what());
  470. }
  471. SceneCollection &newCollection = collections.begin()->second;
  472. ActivateSceneCollection(newCollection);
  473. RemoveSceneCollection(currentCollection);
  474. blog(LOG_INFO, "Switched to scene collection '%s' (%s)", newCollection.getName().c_str(),
  475. newCollection.getFileName().c_str());
  476. blog(LOG_INFO, "------------------------------------------------");
  477. }
  478. void OBSBasic::on_actionImportSceneCollection_triggered()
  479. {
  480. OBSImporter imp(this);
  481. imp.exec();
  482. RefreshSceneCollections(true);
  483. }
  484. void OBSBasic::on_actionExportSceneCollection_triggered()
  485. {
  486. SaveProjectNow();
  487. const SceneCollection &currentCollection = GetCurrentSceneCollection();
  488. const QString home = QDir::homePath();
  489. const QString destinationFileName = SaveFile(this, QTStr("Basic.MainMenu.SceneCollection.Export"),
  490. home + "/" + currentCollection.getFileName().c_str(),
  491. "JSON Files (*.json)");
  492. if (!destinationFileName.isEmpty() && !destinationFileName.isNull()) {
  493. const std::filesystem::path sourceFile = currentCollection.getFilePath();
  494. const std::filesystem::path destinationFile =
  495. std::filesystem::u8path(destinationFileName.toStdString());
  496. OBSDataAutoRelease collection = obs_data_create_from_json_file(sourceFile.u8string().c_str());
  497. OBSDataArrayAutoRelease sources = obs_data_get_array(collection, "sources");
  498. if (!sources) {
  499. blog(LOG_WARNING, "No sources in exported scene collection");
  500. return;
  501. }
  502. obs_data_erase(collection, "sources");
  503. using OBSDataVector = std::vector<OBSData>;
  504. OBSDataVector sourceItems;
  505. obs_data_array_enum(
  506. sources,
  507. [](obs_data_t *data, void *vector) -> void {
  508. OBSDataVector &sourceItems{*static_cast<OBSDataVector *>(vector)};
  509. sourceItems.push_back(data);
  510. },
  511. &sourceItems);
  512. std::sort(sourceItems.begin(), sourceItems.end(), [](const OBSData &a, const OBSData &b) {
  513. return astrcmpi(obs_data_get_string(a, "name"), obs_data_get_string(b, "name")) < 0;
  514. });
  515. OBSDataArrayAutoRelease newSources = obs_data_array_create();
  516. for (auto &item : sourceItems) {
  517. obs_data_array_push_back(newSources, item);
  518. }
  519. obs_data_set_array(collection, "sources", newSources);
  520. obs_data_save_json_pretty_safe(collection, destinationFile.u8string().c_str(), "tmp", "bak");
  521. }
  522. }
  523. void OBSBasic::on_actionRemigrateSceneCollection_triggered()
  524. {
  525. if (Active()) {
  526. OBSMessageBox::warning(this, QTStr("Basic.Main.RemigrateSceneCollection.Title"),
  527. QTStr("Basic.Main.RemigrateSceneCollection.CannotMigrate.Active"));
  528. return;
  529. }
  530. SceneCollection &currentCollection = GetCurrentSceneCollection();
  531. SceneCoordinateMode currentCoordinateMode = currentCollection.getCoordinateMode();
  532. OBS::Rect currentMigrationResolution = currentCollection.getMigrationResolution();
  533. if (currentCoordinateMode == SceneCoordinateMode::Relative && currentMigrationResolution.isZero()) {
  534. OBSMessageBox::warning(
  535. this, QTStr("Basic.Main.RemigrateSceneCollection.Title"),
  536. QTStr("Basic.Main.RemigrateSceneCollection.CannotMigrate.UnknownBaseResolution"));
  537. return;
  538. }
  539. obs_video_info ovi;
  540. obs_get_video_info(&ovi);
  541. OBS::Rect videoResolution = OBS::Rect(ovi.base_width, ovi.base_height);
  542. if (currentCoordinateMode == SceneCoordinateMode::Relative && currentMigrationResolution == videoResolution) {
  543. OBSMessageBox::warning(
  544. this, QTStr("Basic.Main.RemigrateSceneCollection.Title"),
  545. QTStr("Basic.Main.RemigrateSceneCollection.CannotMigrate.BaseResolutionMatches"));
  546. return;
  547. }
  548. QString name = QString::fromStdString(currentCollection.getName());
  549. QString message =
  550. QTStr("Basic.Main.RemigrateSceneCollection.Text").arg(name).arg(ovi.base_width).arg(ovi.base_height);
  551. auto answer = OBSMessageBox::question(this, QTStr("Basic.Main.RemigrateSceneCollection.Title"), message);
  552. if (answer == QMessageBox::No)
  553. return;
  554. lastOutputResolution = {ovi.base_width, ovi.base_height};
  555. if (currentCoordinateMode == SceneCoordinateMode::Relative) {
  556. /* Temporarily change resolution to migration resolution */
  557. ovi.base_width = currentMigrationResolution.getWidth<uint32_t>();
  558. ovi.base_height = currentMigrationResolution.getHeight<uint32_t>();
  559. if (obs_reset_video(&ovi) != OBS_VIDEO_SUCCESS) {
  560. OBSMessageBox::critical(
  561. this, QTStr("Basic.Main.RemigrateSceneCollection.Title"),
  562. QTStr("Basic.Main.RemigrateSceneCollection.CannotMigrate.FailedVideoReset"));
  563. return;
  564. }
  565. }
  566. OnEvent(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CHANGING);
  567. // Temporarily switch the coordinate mode of the current scene collection to "absolute" mode to force the
  568. // collection to be saved as a "version 1" variant. By resetting the coordinate mode to its original mode after
  569. // saving the collection, the activation process will migrate it automatically.
  570. currentCollection.setCoordinateMode(SceneCoordinateMode::Absolute);
  571. SaveProjectNow();
  572. currentCollection.setCoordinateMode(currentCoordinateMode);
  573. /* Reset video if we potentially changed to a temporary resolution */
  574. if (currentCoordinateMode == SceneCoordinateMode::Relative) {
  575. ResetVideo();
  576. }
  577. ActivateSceneCollection(currentCollection);
  578. }
  579. // MARK: - Scene Collection Management Helper Functions
  580. void OBSBasic::ActivateSceneCollection(SceneCollection &collection)
  581. {
  582. const std::string currentCollectionName{config_get_string(App()->GetUserConfig(), "Basic", "SceneCollection")};
  583. if (auto foundCollection = GetSceneCollectionByName(currentCollectionName)) {
  584. if (collection.getName() != foundCollection.value().getName()) {
  585. SaveProjectNow();
  586. }
  587. }
  588. config_set_string(App()->GetUserConfig(), "Basic", "SceneCollection", collection.getName().c_str());
  589. config_set_string(App()->GetUserConfig(), "Basic", "SceneCollectionFile", collection.getFileName().c_str());
  590. Load(collection);
  591. RefreshSceneCollections();
  592. UpdateTitleBar();
  593. OnEvent(OBS_FRONTEND_EVENT_SCENE_COLLECTION_LIST_CHANGED);
  594. OnEvent(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CHANGED);
  595. }
  596. // MARK: - OBSBasic Scene Collection Functions
  597. using namespace std;
  598. static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent, vector<OBSSource> &audioSources)
  599. {
  600. OBSSourceAutoRelease source = obs_get_output_source(channel);
  601. if (!source)
  602. return;
  603. audioSources.push_back(source.Get());
  604. OBSDataAutoRelease data = obs_save_source(source);
  605. obs_data_set_obj(parent, name, data);
  606. }
  607. static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder, obs_data_array_t *quickTransitionData,
  608. int transitionDuration, obs_data_array_t *transitions, OBSScene &scene,
  609. OBSSource &curProgramScene, obs_data_array_t *savedProjectorList,
  610. obs_data_array_t *savedCanvases)
  611. {
  612. obs_data_t *saveData = obs_data_create();
  613. vector<OBSSource> audioSources;
  614. audioSources.reserve(6);
  615. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData, audioSources);
  616. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData, audioSources);
  617. SaveAudioDevice(AUX_AUDIO_1, 3, saveData, audioSources);
  618. SaveAudioDevice(AUX_AUDIO_2, 4, saveData, audioSources);
  619. SaveAudioDevice(AUX_AUDIO_3, 5, saveData, audioSources);
  620. SaveAudioDevice(AUX_AUDIO_4, 6, saveData, audioSources);
  621. /* -------------------------------- */
  622. /* save non-group sources */
  623. auto FilterAudioSources = [&](obs_source_t *source) {
  624. if (obs_source_is_group(source))
  625. return false;
  626. return find(begin(audioSources), end(audioSources), source) == end(audioSources);
  627. };
  628. using FilterAudioSources_t = decltype(FilterAudioSources);
  629. obs_data_array_t *sourcesArray = obs_save_sources_filtered(
  630. [](void *data, obs_source_t *source) {
  631. auto &func = *static_cast<FilterAudioSources_t *>(data);
  632. return func(source);
  633. },
  634. static_cast<void *>(&FilterAudioSources));
  635. /* -------------------------------- */
  636. /* save group sources separately */
  637. /* saving separately ensures they won't be loaded in older versions */
  638. obs_data_array_t *groupsArray = obs_save_sources_filtered(
  639. [](void *, obs_source_t *source) { return obs_source_is_group(source); }, nullptr);
  640. /* -------------------------------- */
  641. OBSSourceAutoRelease transition = obs_get_output_source(0);
  642. obs_source_t *currentScene = obs_scene_get_source(scene);
  643. const char *sceneName = obs_source_get_name(currentScene);
  644. const char *programName = obs_source_get_name(curProgramScene);
  645. const char *sceneCollection = config_get_string(App()->GetUserConfig(), "Basic", "SceneCollection");
  646. obs_data_set_string(saveData, "current_scene", sceneName);
  647. obs_data_set_string(saveData, "current_program_scene", programName);
  648. obs_data_set_array(saveData, "scene_order", sceneOrder);
  649. obs_data_set_string(saveData, "name", sceneCollection);
  650. obs_data_set_array(saveData, "sources", sourcesArray);
  651. obs_data_set_array(saveData, "groups", groupsArray);
  652. obs_data_set_array(saveData, "quick_transitions", quickTransitionData);
  653. obs_data_set_array(saveData, "transitions", transitions);
  654. obs_data_set_array(saveData, "saved_projectors", savedProjectorList);
  655. obs_data_set_array(saveData, "canvases", savedCanvases);
  656. obs_data_array_release(sourcesArray);
  657. obs_data_array_release(groupsArray);
  658. obs_data_set_string(saveData, "current_transition", obs_source_get_name(transition));
  659. obs_data_set_int(saveData, "transition_duration", transitionDuration);
  660. return saveData;
  661. }
  662. void OBSBasic::Save(SceneCollection &collection)
  663. {
  664. OBSScene scene = GetCurrentScene();
  665. OBSSource curProgramScene = OBSGetStrongRef(programScene);
  666. if (!curProgramScene)
  667. curProgramScene = obs_scene_get_source(scene);
  668. OBSDataArrayAutoRelease sceneOrder = SaveSceneListOrder();
  669. OBSDataArrayAutoRelease transitions = SaveTransitions();
  670. OBSDataArrayAutoRelease quickTrData = SaveQuickTransitions();
  671. OBSDataArrayAutoRelease savedProjectorList = SaveProjectors();
  672. OBSDataArrayAutoRelease savedCanvases = OBS::Canvas::SaveCanvases(canvases);
  673. OBSDataAutoRelease saveData = GenerateSaveData(sceneOrder, quickTrData, ui->transitionDuration->value(),
  674. transitions, scene, curProgramScene, savedProjectorList,
  675. savedCanvases);
  676. obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked());
  677. obs_data_set_bool(saveData, "scaling_enabled", ui->preview->IsFixedScaling());
  678. obs_data_set_int(saveData, "scaling_level", ui->preview->GetScalingLevel());
  679. obs_data_set_double(saveData, "scaling_off_x", ui->preview->GetScrollX());
  680. obs_data_set_double(saveData, "scaling_off_y", ui->preview->GetScrollY());
  681. if (vcamEnabled) {
  682. OBSDataAutoRelease obj = obs_data_create();
  683. obs_data_set_int(obj, "type2", (int)vcamConfig.type);
  684. switch (vcamConfig.type) {
  685. case VCamOutputType::Invalid:
  686. case VCamOutputType::ProgramView:
  687. case VCamOutputType::PreviewOutput:
  688. break;
  689. case VCamOutputType::SceneOutput:
  690. obs_data_set_string(obj, "scene", vcamConfig.scene.c_str());
  691. break;
  692. case VCamOutputType::SourceOutput:
  693. obs_data_set_string(obj, "source", vcamConfig.source.c_str());
  694. break;
  695. }
  696. obs_data_set_obj(saveData, "virtual-camera", obj);
  697. }
  698. if (api) {
  699. if (!collectionModuleData)
  700. collectionModuleData = obs_data_create();
  701. api->on_save(collectionModuleData);
  702. obs_data_set_obj(saveData, "modules", collectionModuleData);
  703. }
  704. if (lastOutputResolution) {
  705. OBSDataAutoRelease res = obs_data_create();
  706. obs_data_set_int(res, "x", lastOutputResolution->first);
  707. obs_data_set_int(res, "y", lastOutputResolution->second);
  708. obs_data_set_obj(saveData, "resolution", res);
  709. }
  710. int sceneCollectionVersion = collection.getVersion();
  711. obs_data_set_int(saveData, "version", sceneCollectionVersion);
  712. OBS::Rect migrationResolution = collection.getMigrationResolution();
  713. SceneCoordinateMode coordinateMode = collection.getCoordinateMode();
  714. if (coordinateMode == SceneCoordinateMode::Absolute) {
  715. removeRelativePositionData(saveData);
  716. }
  717. if (!migrationResolution.isZero() && coordinateMode == SceneCoordinateMode::Relative) {
  718. OBSDataAutoRelease resolutionData = obs_data_create();
  719. obs_data_set_int(resolutionData, "x", migrationResolution.getWidth<long long>());
  720. obs_data_set_int(resolutionData, "y", migrationResolution.getHeight<long long>());
  721. obs_data_set_obj(saveData, DataKeys::MigrationResolution.data(), resolutionData);
  722. }
  723. const std::string collectionFileName = collection.getFilePathString();
  724. bool success = obs_data_save_json_pretty_safe(saveData, collectionFileName.c_str(), "tmp", "bak");
  725. if (!success) {
  726. blog(LOG_ERROR, "Could not save scene data to %s", collectionFileName.c_str());
  727. }
  728. }
  729. void OBSBasic::DeferSaveBegin()
  730. {
  731. os_atomic_inc_long(&disableSaving);
  732. }
  733. void OBSBasic::DeferSaveEnd()
  734. {
  735. long result = os_atomic_dec_long(&disableSaving);
  736. if (result == 0) {
  737. SaveProject();
  738. }
  739. }
  740. static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val);
  741. static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
  742. {
  743. OBSDataAutoRelease data = obs_data_get_obj(parent, name);
  744. if (!data)
  745. return;
  746. OBSSourceAutoRelease source = obs_load_source(data);
  747. if (!source)
  748. return;
  749. obs_set_output_source(channel, source);
  750. const char *source_name = obs_source_get_name(source);
  751. blog(LOG_INFO, "[Loaded global audio device]: '%s'", source_name);
  752. obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
  753. obs_monitoring_type monitoring_type = obs_source_get_monitoring_type(source);
  754. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  755. const char *type = (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY) ? "monitor only"
  756. : "monitor and output";
  757. blog(LOG_INFO, " - monitoring: %s", type);
  758. }
  759. }
  760. void OBSBasic::CreateDefaultScene(bool firstStart)
  761. {
  762. disableSaving++;
  763. ClearSceneData();
  764. InitDefaultTransitions();
  765. CreateDefaultQuickTransitions();
  766. ui->transitionDuration->setValue(300);
  767. SetTransition(fadeTransition);
  768. updateRemigrationMenuItem(SceneCoordinateMode::Relative, ui->actionRemigrateSceneCollection);
  769. OBSSceneAutoRelease scene = obs_scene_create(Str("Basic.Scene"));
  770. if (firstStart)
  771. CreateFirstRunSources();
  772. SetCurrentScene(scene, true);
  773. disableSaving--;
  774. }
  775. static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val)
  776. {
  777. const char *name = obs_source_get_name(filter);
  778. const char *id = obs_source_get_id(filter);
  779. int val = (int)(intptr_t)v_val;
  780. string indent;
  781. for (int i = 0; i < val; i++)
  782. indent += " ";
  783. blog(LOG_INFO, "%s- filter: '%s' (%s)", indent.c_str(), name, id);
  784. }
  785. static bool LogSceneItem(obs_scene_t *, obs_sceneitem_t *item, void *v_val)
  786. {
  787. obs_source_t *source = obs_sceneitem_get_source(item);
  788. const char *name = obs_source_get_name(source);
  789. const char *id = obs_source_get_id(source);
  790. int indent_count = (int)(intptr_t)v_val;
  791. string indent;
  792. for (int i = 0; i < indent_count; i++)
  793. indent += " ";
  794. blog(LOG_INFO, "%s- source: '%s' (%s)", indent.c_str(), name, id);
  795. obs_monitoring_type monitoring_type = obs_source_get_monitoring_type(source);
  796. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  797. const char *type = (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY) ? "monitor only"
  798. : "monitor and output";
  799. blog(LOG_INFO, " %s- monitoring: %s", indent.c_str(), type);
  800. }
  801. int child_indent = 1 + indent_count;
  802. obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)child_indent);
  803. obs_source_t *show_tn = obs_sceneitem_get_transition(item, true);
  804. obs_source_t *hide_tn = obs_sceneitem_get_transition(item, false);
  805. if (show_tn)
  806. blog(LOG_INFO, " %s- show: '%s' (%s)", indent.c_str(), obs_source_get_name(show_tn),
  807. obs_source_get_id(show_tn));
  808. if (hide_tn)
  809. blog(LOG_INFO, " %s- hide: '%s' (%s)", indent.c_str(), obs_source_get_name(hide_tn),
  810. obs_source_get_id(hide_tn));
  811. if (obs_sceneitem_is_group(item))
  812. obs_sceneitem_group_enum_items(item, LogSceneItem, (void *)(intptr_t)child_indent);
  813. return true;
  814. }
  815. void OBSBasic::LogScenes()
  816. {
  817. blog(LOG_INFO, "------------------------------------------------");
  818. blog(LOG_INFO, "Loaded scenes:");
  819. for (int i = 0; i < ui->scenes->count(); i++) {
  820. QListWidgetItem *item = ui->scenes->item(i);
  821. OBSScene scene = GetOBSRef<OBSScene>(item);
  822. obs_source_t *source = obs_scene_get_source(scene);
  823. const char *name = obs_source_get_name(source);
  824. blog(LOG_INFO, "- scene '%s':", name);
  825. obs_scene_enum_items(scene, LogSceneItem, (void *)(intptr_t)1);
  826. obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
  827. }
  828. blog(LOG_INFO, "------------------------------------------------");
  829. }
  830. void OBSBasic::Load(SceneCollection &collection)
  831. {
  832. disableSaving++;
  833. lastOutputResolution.reset();
  834. collection.setMigrationResolution(0, 0);
  835. obs_data_t *data = obs_data_create_from_json_file_safe(collection.getFilePathString().c_str(), "bak");
  836. if (!data) {
  837. disableSaving--;
  838. const std::filesystem::path filePath = collection.getFilePath();
  839. if (std::filesystem::exists(filePath)) {
  840. std::filesystem::path backupFilePath = filePath;
  841. backupFilePath.replace_extension(".json.invalid");
  842. blog(LOG_WARNING,
  843. "File exists but appears to be corrupt, renaming "
  844. "to \"%s\" before continuing.",
  845. backupFilePath.filename().u8string().c_str());
  846. try {
  847. std::filesystem::rename(filePath, backupFilePath);
  848. } catch (const std::filesystem::filesystem_error &error) {
  849. blog(LOG_ERROR, "Failed renaming corrupt file:\n%s", error.what());
  850. }
  851. }
  852. blog(LOG_INFO, "No scene file found, creating default scene");
  853. bool hasFirstRun = config_get_bool(App()->GetUserConfig(), "General", "FirstRun");
  854. CreateDefaultScene(!hasFirstRun);
  855. SaveProject();
  856. return;
  857. }
  858. LoadData(data, collection);
  859. }
  860. static inline void AddMissingFiles(void *data, obs_source_t *source)
  861. {
  862. obs_missing_files_t *f = (obs_missing_files_t *)data;
  863. obs_missing_files_t *sf = obs_source_get_missing_files(source);
  864. obs_missing_files_append(f, sf);
  865. obs_missing_files_destroy(sf);
  866. }
  867. void OBSBasic::LoadData(obs_data_t *data, SceneCollection &collection)
  868. {
  869. ClearSceneData();
  870. ClearContextBar();
  871. /* Exit OBS if clearing scene data failed for some reason. */
  872. if (clearingFailed) {
  873. OBSMessageBox::critical(this, QTStr("SourceLeak.Title"), QTStr("SourceLeak.Text"));
  874. close();
  875. return;
  876. }
  877. InitDefaultTransitions();
  878. if (devicePropertiesThread && devicePropertiesThread->isRunning()) {
  879. devicePropertiesThread->wait();
  880. devicePropertiesThread.reset();
  881. }
  882. QApplication::sendPostedEvents(nullptr);
  883. OBSDataAutoRelease modulesObj = obs_data_get_obj(data, "modules");
  884. if (api)
  885. api->on_preload(modulesObj);
  886. /* Keep a reference to "modules" data so plugins that are not loaded do
  887. * not have their collection specific data lost. */
  888. collectionModuleData = obs_data_get_obj(data, "modules");
  889. OBSDataArrayAutoRelease sceneOrder = obs_data_get_array(data, "scene_order");
  890. OBSDataArrayAutoRelease sources = obs_data_get_array(data, "sources");
  891. OBSDataArrayAutoRelease groups = obs_data_get_array(data, "groups");
  892. OBSDataArrayAutoRelease transitions = obs_data_get_array(data, "transitions");
  893. OBSDataArrayAutoRelease collection_canvases = obs_data_get_array(data, "canvases");
  894. const char *sceneName = obs_data_get_string(data, "current_scene");
  895. const char *programSceneName = obs_data_get_string(data, "current_program_scene");
  896. const char *transitionName = obs_data_get_string(data, "current_transition");
  897. if (!opt_starting_scene.empty()) {
  898. programSceneName = opt_starting_scene.c_str();
  899. if (!IsPreviewProgramMode())
  900. sceneName = opt_starting_scene.c_str();
  901. }
  902. int newDuration = obs_data_get_int(data, "transition_duration");
  903. if (!newDuration)
  904. newDuration = 300;
  905. if (!transitionName)
  906. transitionName = obs_source_get_name(fadeTransition);
  907. const char *curSceneCollection = config_get_string(App()->GetUserConfig(), "Basic", "SceneCollection");
  908. obs_data_set_default_string(data, "name", curSceneCollection);
  909. const char *name = obs_data_get_string(data, "name");
  910. OBSSourceAutoRelease curScene;
  911. OBSSourceAutoRelease curProgramScene;
  912. obs_source_t *curTransition;
  913. if (!name || !*name)
  914. name = curSceneCollection;
  915. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  916. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  917. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  918. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  919. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  920. LoadAudioDevice(AUX_AUDIO_4, 6, data);
  921. if (collection_canvases)
  922. canvases = OBS::Canvas::LoadCanvases(collection_canvases);
  923. if (!sources) {
  924. sources = std::move(groups);
  925. } else {
  926. obs_data_array_push_back_array(sources, groups);
  927. }
  928. bool resetVideo = false;
  929. obs_video_info ovi;
  930. int64_t version = obs_data_get_int(data, "version");
  931. OBSDataAutoRelease res = obs_data_get_obj(data, "resolution");
  932. OBS::Rect collectionSize{};
  933. if (res) {
  934. collectionSize.setWidth(obs_data_get_int(res, "x"));
  935. collectionSize.setHeight(obs_data_get_int(res, "y"));
  936. }
  937. /* Only migrate legacy collection if resolution is saved. */
  938. if (version < 2 && !collectionSize.isZero()) {
  939. obs_get_video_info(&ovi);
  940. collection.setMigrationResolution(collectionSize);
  941. OBS::Rect outputSize{ovi.base_width, ovi.base_height};
  942. if (outputSize != collectionSize) {
  943. ovi.base_width = collectionSize.getWidth<uint32_t>();
  944. ovi.base_height = collectionSize.getHeight<uint32_t>();
  945. /* Attempt to reset to last known canvas resolution for migration. */
  946. resetVideo = obs_reset_video(&ovi) == OBS_VIDEO_SUCCESS;
  947. if (!resetVideo) {
  948. collection.setCoordinateMode(OBS::SceneCoordinateMode::Absolute);
  949. }
  950. }
  951. // If migration is necessary, attempt to back up version 1 variant of the scene ecollection.
  952. if (collection.getCoordinateMode() == SceneCoordinateMode::Absolute) {
  953. std::filesystem::path backupFilePath = collection.getFilePath();
  954. backupFilePath.replace_extension(".json.v1");
  955. if (!std::filesystem::exists(backupFilePath)) {
  956. bool success = obs_data_save_json_pretty_safe(data, backupFilePath.u8string().c_str(),
  957. "tmp", nullptr);
  958. if (!success) {
  959. blog(LOG_WARNING,
  960. "Failed to create a backup of existing scene collection data");
  961. }
  962. }
  963. }
  964. collection.setCoordinateMode(SceneCoordinateMode::Relative);
  965. } else if (version < 2) {
  966. collection.setCoordinateMode(SceneCoordinateMode::Absolute);
  967. } else {
  968. OBSDataAutoRelease migrationResolution = obs_data_get_obj(data, "migration_resolution");
  969. if (migrationResolution) {
  970. collection.setMigrationResolution(obs_data_get_int(migrationResolution, "x"),
  971. obs_data_get_int(migrationResolution, "y"));
  972. }
  973. }
  974. // FIXME: Migrate to actual SceneCollection container with reference-based API
  975. // The collection passed as function argument might be a copy generated via std::optional and thus
  976. // might not represent the actual collection within the collection, meaning all changes would be lost after
  977. // the function stack is unwound (i.e., the change would not be written into the scene collection file
  978. // during OBS shutdown).
  979. // Explicitly updating the collection inside the container ensures the changes "stick".
  980. collections[collection.getName()] = collection;
  981. updateRemigrationMenuItem(collection.getCoordinateMode(), ui->actionRemigrateSceneCollection);
  982. obs_missing_files_t *files = obs_missing_files_create();
  983. obs_load_sources(sources, AddMissingFiles, files);
  984. if (resetVideo)
  985. ResetVideo();
  986. if (transitions)
  987. LoadTransitions(transitions, AddMissingFiles, files);
  988. if (sceneOrder)
  989. LoadSceneListOrder(sceneOrder);
  990. curTransition = FindTransition(transitionName);
  991. if (!curTransition)
  992. curTransition = fadeTransition;
  993. ui->transitionDuration->setValue(newDuration);
  994. SetTransition(curTransition);
  995. retryScene:
  996. curScene = obs_get_source_by_name(sceneName);
  997. curProgramScene = obs_get_source_by_name(programSceneName);
  998. /* if the starting scene command line parameter is bad at all,
  999. * fall back to original settings */
  1000. if (!opt_starting_scene.empty() && (!curScene || !curProgramScene)) {
  1001. sceneName = obs_data_get_string(data, "current_scene");
  1002. programSceneName = obs_data_get_string(data, "current_program_scene");
  1003. opt_starting_scene.clear();
  1004. goto retryScene;
  1005. }
  1006. if (!curScene) {
  1007. auto find_scene_cb = [](void *source_ptr, obs_source_t *scene) {
  1008. *static_cast<OBSSourceAutoRelease *>(source_ptr) = obs_source_get_ref(scene);
  1009. return false;
  1010. };
  1011. obs_enum_scenes(find_scene_cb, &curScene);
  1012. }
  1013. SetCurrentScene(curScene.Get(), true);
  1014. if (!curProgramScene)
  1015. curProgramScene = std::move(curScene);
  1016. if (IsPreviewProgramMode())
  1017. TransitionToScene(curProgramScene.Get(), true);
  1018. /* ------------------- */
  1019. bool projectorSave = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SaveProjectors");
  1020. if (projectorSave) {
  1021. OBSDataArrayAutoRelease savedProjectors = obs_data_get_array(data, "saved_projectors");
  1022. if (savedProjectors) {
  1023. LoadSavedProjectors(savedProjectors);
  1024. activateWindow();
  1025. }
  1026. }
  1027. /* ------------------- */
  1028. config_set_string(App()->GetUserConfig(), "Basic", "SceneCollection", collection.getName().c_str());
  1029. config_set_string(App()->GetUserConfig(), "Basic", "SceneCollectionFile", collection.getFileName().c_str());
  1030. OBSDataArrayAutoRelease quickTransitionData = obs_data_get_array(data, "quick_transitions");
  1031. LoadQuickTransitions(quickTransitionData);
  1032. RefreshQuickTransitions();
  1033. bool previewLocked = obs_data_get_bool(data, "preview_locked");
  1034. ui->preview->SetLocked(previewLocked);
  1035. ui->actionLockPreview->setChecked(previewLocked);
  1036. /* ---------------------- */
  1037. bool fixedScaling = obs_data_get_bool(data, "scaling_enabled");
  1038. int scalingLevel = (int)obs_data_get_int(data, "scaling_level");
  1039. float scrollOffX = (float)obs_data_get_double(data, "scaling_off_x");
  1040. float scrollOffY = (float)obs_data_get_double(data, "scaling_off_y");
  1041. if (fixedScaling) {
  1042. ui->preview->SetScalingLevel(scalingLevel);
  1043. ui->preview->SetScrollingOffset(scrollOffX, scrollOffY);
  1044. }
  1045. ui->preview->SetFixedScaling(fixedScaling);
  1046. emit ui->preview->DisplayResized();
  1047. if (vcamEnabled) {
  1048. OBSDataAutoRelease obj = obs_data_get_obj(data, "virtual-camera");
  1049. vcamConfig.type = (VCamOutputType)obs_data_get_int(obj, "type2");
  1050. if (vcamConfig.type == VCamOutputType::Invalid)
  1051. vcamConfig.type = (VCamOutputType)obs_data_get_int(obj, "type");
  1052. if (vcamConfig.type == VCamOutputType::Invalid) {
  1053. VCamInternalType internal = (VCamInternalType)obs_data_get_int(obj, "internal");
  1054. switch (internal) {
  1055. case VCamInternalType::Default:
  1056. vcamConfig.type = VCamOutputType::ProgramView;
  1057. break;
  1058. case VCamInternalType::Preview:
  1059. vcamConfig.type = VCamOutputType::PreviewOutput;
  1060. break;
  1061. }
  1062. }
  1063. vcamConfig.scene = obs_data_get_string(obj, "scene");
  1064. vcamConfig.source = obs_data_get_string(obj, "source");
  1065. }
  1066. if (!collectionSize.isZero()) {
  1067. lastOutputResolution = {collectionSize.getWidth<uint32_t>(), collectionSize.getHeight<uint32_t>()};
  1068. }
  1069. /* ---------------------- */
  1070. if (api)
  1071. api->on_load(modulesObj);
  1072. obs_data_release(data);
  1073. if (!opt_starting_scene.empty())
  1074. opt_starting_scene.clear();
  1075. if (opt_start_streaming && !safe_mode) {
  1076. blog(LOG_INFO, "Starting stream due to command line parameter");
  1077. QMetaObject::invokeMethod(this, "StartStreaming", Qt::QueuedConnection);
  1078. opt_start_streaming = false;
  1079. }
  1080. if (opt_start_recording && !safe_mode) {
  1081. blog(LOG_INFO, "Starting recording due to command line parameter");
  1082. QMetaObject::invokeMethod(this, "StartRecording", Qt::QueuedConnection);
  1083. opt_start_recording = false;
  1084. }
  1085. if (opt_start_replaybuffer && !safe_mode) {
  1086. QMetaObject::invokeMethod(this, "StartReplayBuffer", Qt::QueuedConnection);
  1087. opt_start_replaybuffer = false;
  1088. }
  1089. if (opt_start_virtualcam && !safe_mode) {
  1090. QMetaObject::invokeMethod(this, "StartVirtualCam", Qt::QueuedConnection);
  1091. opt_start_virtualcam = false;
  1092. }
  1093. LogScenes();
  1094. if (!App()->IsMissingFilesCheckDisabled())
  1095. ShowMissingFilesDialog(files);
  1096. disableSaving--;
  1097. if (vcamEnabled)
  1098. outputHandler->UpdateVirtualCamOutputSource();
  1099. OnEvent(OBS_FRONTEND_EVENT_SCENE_CHANGED);
  1100. OnEvent(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  1101. }
  1102. void OBSBasic::SaveProjectNow()
  1103. {
  1104. if (disableSaving)
  1105. return;
  1106. projectChanged = true;
  1107. SaveProjectDeferred();
  1108. }
  1109. void OBSBasic::SaveProject()
  1110. {
  1111. if (disableSaving)
  1112. return;
  1113. projectChanged = true;
  1114. QMetaObject::invokeMethod(this, "SaveProjectDeferred", Qt::QueuedConnection);
  1115. }
  1116. void OBSBasic::SaveProjectDeferred()
  1117. {
  1118. if (disableSaving)
  1119. return;
  1120. if (!projectChanged)
  1121. return;
  1122. projectChanged = false;
  1123. try {
  1124. OBS::SceneCollection &currentCollection = GetCurrentSceneCollection();
  1125. Save(currentCollection);
  1126. } catch (const std::invalid_argument &error) {
  1127. blog(LOG_ERROR, "%s", error.what());
  1128. }
  1129. }
  1130. void OBSBasic::ClearSceneData()
  1131. {
  1132. disableSaving++;
  1133. setCursor(Qt::WaitCursor);
  1134. CloseDialogs();
  1135. ClearVolumeControls();
  1136. ClearListItems(ui->scenes);
  1137. ui->sources->Clear();
  1138. ClearQuickTransitions();
  1139. ui->transitions->clear();
  1140. ClearProjectors();
  1141. for (int i = 0; i < MAX_CHANNELS; i++)
  1142. obs_set_output_source(i, nullptr);
  1143. /* Reset VCam to default to clear its private scene and any references
  1144. * it holds. It will be reconfigured during loading. */
  1145. if (vcamEnabled) {
  1146. vcamConfig.type = VCamOutputType::ProgramView;
  1147. outputHandler->UpdateVirtualCamOutputSource();
  1148. }
  1149. collectionModuleData = nullptr;
  1150. lastScene = nullptr;
  1151. swapScene = nullptr;
  1152. programScene = nullptr;
  1153. prevFTBSource = nullptr;
  1154. clipboard.clear();
  1155. copyFiltersSource = nullptr;
  1156. copyFilter = nullptr;
  1157. auto cb = [](void *, obs_source_t *source) {
  1158. obs_source_remove(source);
  1159. return true;
  1160. };
  1161. obs_enum_scenes(cb, nullptr);
  1162. obs_enum_sources(cb, nullptr);
  1163. for (const auto &canvas : canvases) {
  1164. obs_canvas_enum_scenes(canvas, cb, nullptr);
  1165. }
  1166. canvases.clear();
  1167. OnEvent(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  1168. undo_s.clear();
  1169. /* using QEvent::DeferredDelete explicitly is the only way to ensure
  1170. * that deleteLater events are processed at this point */
  1171. QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
  1172. do {
  1173. QApplication::sendPostedEvents(nullptr);
  1174. } while (obs_wait_for_destroy_queue());
  1175. /* Pump Qt events one final time to give remaining signals time to be
  1176. * processed (since this happens after the destroy thread finishes and
  1177. * the audio/video threads have processed their tasks). */
  1178. QApplication::sendPostedEvents(nullptr);
  1179. unsetCursor();
  1180. /* If scene data wasn't actually cleared, e.g. faulty plugin holding a
  1181. * reference, they will still be in the hash table, enumerate them and
  1182. * store the names for logging purposes. */
  1183. auto cb2 = [](void *param, obs_source_t *source) {
  1184. auto orphans = static_cast<vector<string> *>(param);
  1185. orphans->push_back(obs_source_get_name(source));
  1186. return true;
  1187. };
  1188. vector<string> orphan_sources;
  1189. obs_enum_sources(cb2, &orphan_sources);
  1190. if (!orphan_sources.empty()) {
  1191. /* Avoid logging list twice in case it gets called after
  1192. * setting the flag the first time. */
  1193. if (!clearingFailed) {
  1194. /* This ugly mess exists to join a vector of strings
  1195. * with a user-defined delimiter. */
  1196. string orphan_names =
  1197. std::accumulate(orphan_sources.begin(), orphan_sources.end(), string(""),
  1198. [](string a, string b) { return std::move(a) + "\n- " + b; });
  1199. blog(LOG_ERROR, "Not all sources were cleared when clearing scene data:\n%s\n",
  1200. orphan_names.c_str());
  1201. }
  1202. /* We do not decrement disableSaving here to avoid OBS
  1203. * overwriting user data with garbage. */
  1204. clearingFailed = true;
  1205. } else {
  1206. disableSaving--;
  1207. blog(LOG_INFO, "All scene data cleared");
  1208. blog(LOG_INFO, "------------------------------------------------");
  1209. }
  1210. }
  1211. void OBSBasic::ShowMissingFilesDialog(obs_missing_files_t *files)
  1212. {
  1213. if (obs_missing_files_count(files) > 0) {
  1214. /* When loading the missing files dialog on launch, the
  1215. * window hasn't fully initialized by this point on macOS,
  1216. * so put this at the end of the current task queue. Fixes
  1217. * a bug where the window is behind OBS on startup. */
  1218. QTimer::singleShot(0, [this, files] {
  1219. missDialog = new OBSMissingFiles(files, this);
  1220. missDialog->setAttribute(Qt::WA_DeleteOnClose, true);
  1221. missDialog->show();
  1222. missDialog->raise();
  1223. });
  1224. } else {
  1225. obs_missing_files_destroy(files);
  1226. /* Only raise dialog if triggered manually */
  1227. if (!disableSaving)
  1228. OBSMessageBox::information(this, QTStr("MissingFiles.NoMissing.Title"),
  1229. QTStr("MissingFiles.NoMissing.Text"));
  1230. }
  1231. }
  1232. void OBSBasic::on_actionShowMissingFiles_triggered()
  1233. {
  1234. obs_missing_files_t *files = obs_missing_files_create();
  1235. auto cb_sources = [](void *data, obs_source_t *source) {
  1236. AddMissingFiles(data, source);
  1237. return true;
  1238. };
  1239. obs_enum_all_sources(cb_sources, files);
  1240. ShowMissingFilesDialog(files);
  1241. }