OBSBasic_SceneCollections.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618
  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. {
  611. obs_data_t *saveData = obs_data_create();
  612. vector<OBSSource> audioSources;
  613. audioSources.reserve(6);
  614. SaveAudioDevice(DESKTOP_AUDIO_1, 1, saveData, audioSources);
  615. SaveAudioDevice(DESKTOP_AUDIO_2, 2, saveData, audioSources);
  616. SaveAudioDevice(AUX_AUDIO_1, 3, saveData, audioSources);
  617. SaveAudioDevice(AUX_AUDIO_2, 4, saveData, audioSources);
  618. SaveAudioDevice(AUX_AUDIO_3, 5, saveData, audioSources);
  619. SaveAudioDevice(AUX_AUDIO_4, 6, saveData, audioSources);
  620. /* -------------------------------- */
  621. /* save non-group sources */
  622. auto FilterAudioSources = [&](obs_source_t *source) {
  623. if (obs_source_is_group(source))
  624. return false;
  625. return find(begin(audioSources), end(audioSources), source) == end(audioSources);
  626. };
  627. using FilterAudioSources_t = decltype(FilterAudioSources);
  628. obs_data_array_t *sourcesArray = obs_save_sources_filtered(
  629. [](void *data, obs_source_t *source) {
  630. auto &func = *static_cast<FilterAudioSources_t *>(data);
  631. return func(source);
  632. },
  633. static_cast<void *>(&FilterAudioSources));
  634. /* -------------------------------- */
  635. /* save group sources separately */
  636. /* saving separately ensures they won't be loaded in older versions */
  637. obs_data_array_t *groupsArray = obs_save_sources_filtered(
  638. [](void *, obs_source_t *source) { return obs_source_is_group(source); }, nullptr);
  639. /* -------------------------------- */
  640. OBSSourceAutoRelease transition = obs_get_output_source(0);
  641. obs_source_t *currentScene = obs_scene_get_source(scene);
  642. const char *sceneName = obs_source_get_name(currentScene);
  643. const char *programName = obs_source_get_name(curProgramScene);
  644. const char *sceneCollection = config_get_string(App()->GetUserConfig(), "Basic", "SceneCollection");
  645. obs_data_set_string(saveData, "current_scene", sceneName);
  646. obs_data_set_string(saveData, "current_program_scene", programName);
  647. obs_data_set_array(saveData, "scene_order", sceneOrder);
  648. obs_data_set_string(saveData, "name", sceneCollection);
  649. obs_data_set_array(saveData, "sources", sourcesArray);
  650. obs_data_set_array(saveData, "groups", groupsArray);
  651. obs_data_set_array(saveData, "quick_transitions", quickTransitionData);
  652. obs_data_set_array(saveData, "transitions", transitions);
  653. obs_data_set_array(saveData, "saved_projectors", savedProjectorList);
  654. obs_data_array_release(sourcesArray);
  655. obs_data_array_release(groupsArray);
  656. obs_data_set_string(saveData, "current_transition", obs_source_get_name(transition));
  657. obs_data_set_int(saveData, "transition_duration", transitionDuration);
  658. return saveData;
  659. }
  660. void OBSBasic::Save(SceneCollection &collection)
  661. {
  662. OBSScene scene = GetCurrentScene();
  663. OBSSource curProgramScene = OBSGetStrongRef(programScene);
  664. if (!curProgramScene)
  665. curProgramScene = obs_scene_get_source(scene);
  666. OBSDataArrayAutoRelease sceneOrder = SaveSceneListOrder();
  667. OBSDataArrayAutoRelease transitions = SaveTransitions();
  668. OBSDataArrayAutoRelease quickTrData = SaveQuickTransitions();
  669. OBSDataArrayAutoRelease savedProjectorList = SaveProjectors();
  670. OBSDataAutoRelease saveData = GenerateSaveData(sceneOrder, quickTrData, ui->transitionDuration->value(),
  671. transitions, scene, curProgramScene, savedProjectorList);
  672. obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked());
  673. obs_data_set_bool(saveData, "scaling_enabled", ui->preview->IsFixedScaling());
  674. obs_data_set_int(saveData, "scaling_level", ui->preview->GetScalingLevel());
  675. obs_data_set_double(saveData, "scaling_off_x", ui->preview->GetScrollX());
  676. obs_data_set_double(saveData, "scaling_off_y", ui->preview->GetScrollY());
  677. if (vcamEnabled) {
  678. OBSDataAutoRelease obj = obs_data_create();
  679. obs_data_set_int(obj, "type2", (int)vcamConfig.type);
  680. switch (vcamConfig.type) {
  681. case VCamOutputType::Invalid:
  682. case VCamOutputType::ProgramView:
  683. case VCamOutputType::PreviewOutput:
  684. break;
  685. case VCamOutputType::SceneOutput:
  686. obs_data_set_string(obj, "scene", vcamConfig.scene.c_str());
  687. break;
  688. case VCamOutputType::SourceOutput:
  689. obs_data_set_string(obj, "source", vcamConfig.source.c_str());
  690. break;
  691. }
  692. obs_data_set_obj(saveData, "virtual-camera", obj);
  693. }
  694. if (api) {
  695. if (!collectionModuleData)
  696. collectionModuleData = obs_data_create();
  697. api->on_save(collectionModuleData);
  698. obs_data_set_obj(saveData, "modules", collectionModuleData);
  699. }
  700. if (lastOutputResolution) {
  701. OBSDataAutoRelease res = obs_data_create();
  702. obs_data_set_int(res, "x", lastOutputResolution->first);
  703. obs_data_set_int(res, "y", lastOutputResolution->second);
  704. obs_data_set_obj(saveData, "resolution", res);
  705. }
  706. int sceneCollectionVersion = collection.getVersion();
  707. obs_data_set_int(saveData, "version", sceneCollectionVersion);
  708. OBS::Rect migrationResolution = collection.getMigrationResolution();
  709. SceneCoordinateMode coordinateMode = collection.getCoordinateMode();
  710. if (coordinateMode == SceneCoordinateMode::Absolute) {
  711. removeRelativePositionData(saveData);
  712. }
  713. if (!migrationResolution.isZero() && coordinateMode == SceneCoordinateMode::Relative) {
  714. OBSDataAutoRelease resolutionData = obs_data_create();
  715. obs_data_set_int(resolutionData, "x", migrationResolution.getWidth<long long>());
  716. obs_data_set_int(resolutionData, "y", migrationResolution.getHeight<long long>());
  717. obs_data_set_obj(saveData, DataKeys::MigrationResolution.data(), resolutionData);
  718. }
  719. const std::string collectionFileName = collection.getFilePathString();
  720. bool success = obs_data_save_json_pretty_safe(saveData, collectionFileName.c_str(), "tmp", "bak");
  721. if (!success) {
  722. blog(LOG_ERROR, "Could not save scene data to %s", collectionFileName.c_str());
  723. }
  724. }
  725. void OBSBasic::DeferSaveBegin()
  726. {
  727. os_atomic_inc_long(&disableSaving);
  728. }
  729. void OBSBasic::DeferSaveEnd()
  730. {
  731. long result = os_atomic_dec_long(&disableSaving);
  732. if (result == 0) {
  733. SaveProject();
  734. }
  735. }
  736. static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val);
  737. static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent)
  738. {
  739. OBSDataAutoRelease data = obs_data_get_obj(parent, name);
  740. if (!data)
  741. return;
  742. OBSSourceAutoRelease source = obs_load_source(data);
  743. if (!source)
  744. return;
  745. obs_set_output_source(channel, source);
  746. const char *source_name = obs_source_get_name(source);
  747. blog(LOG_INFO, "[Loaded global audio device]: '%s'", source_name);
  748. obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
  749. obs_monitoring_type monitoring_type = obs_source_get_monitoring_type(source);
  750. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  751. const char *type = (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY) ? "monitor only"
  752. : "monitor and output";
  753. blog(LOG_INFO, " - monitoring: %s", type);
  754. }
  755. }
  756. void OBSBasic::CreateDefaultScene(bool firstStart)
  757. {
  758. disableSaving++;
  759. ClearSceneData();
  760. InitDefaultTransitions();
  761. CreateDefaultQuickTransitions();
  762. ui->transitionDuration->setValue(300);
  763. SetTransition(fadeTransition);
  764. updateRemigrationMenuItem(SceneCoordinateMode::Relative, ui->actionRemigrateSceneCollection);
  765. OBSSceneAutoRelease scene = obs_scene_create(Str("Basic.Scene"));
  766. if (firstStart)
  767. CreateFirstRunSources();
  768. SetCurrentScene(scene, true);
  769. disableSaving--;
  770. }
  771. static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val)
  772. {
  773. const char *name = obs_source_get_name(filter);
  774. const char *id = obs_source_get_id(filter);
  775. int val = (int)(intptr_t)v_val;
  776. string indent;
  777. for (int i = 0; i < val; i++)
  778. indent += " ";
  779. blog(LOG_INFO, "%s- filter: '%s' (%s)", indent.c_str(), name, id);
  780. }
  781. static bool LogSceneItem(obs_scene_t *, obs_sceneitem_t *item, void *v_val)
  782. {
  783. obs_source_t *source = obs_sceneitem_get_source(item);
  784. const char *name = obs_source_get_name(source);
  785. const char *id = obs_source_get_id(source);
  786. int indent_count = (int)(intptr_t)v_val;
  787. string indent;
  788. for (int i = 0; i < indent_count; i++)
  789. indent += " ";
  790. blog(LOG_INFO, "%s- source: '%s' (%s)", indent.c_str(), name, id);
  791. obs_monitoring_type monitoring_type = obs_source_get_monitoring_type(source);
  792. if (monitoring_type != OBS_MONITORING_TYPE_NONE) {
  793. const char *type = (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY) ? "monitor only"
  794. : "monitor and output";
  795. blog(LOG_INFO, " %s- monitoring: %s", indent.c_str(), type);
  796. }
  797. int child_indent = 1 + indent_count;
  798. obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)child_indent);
  799. obs_source_t *show_tn = obs_sceneitem_get_transition(item, true);
  800. obs_source_t *hide_tn = obs_sceneitem_get_transition(item, false);
  801. if (show_tn)
  802. blog(LOG_INFO, " %s- show: '%s' (%s)", indent.c_str(), obs_source_get_name(show_tn),
  803. obs_source_get_id(show_tn));
  804. if (hide_tn)
  805. blog(LOG_INFO, " %s- hide: '%s' (%s)", indent.c_str(), obs_source_get_name(hide_tn),
  806. obs_source_get_id(hide_tn));
  807. if (obs_sceneitem_is_group(item))
  808. obs_sceneitem_group_enum_items(item, LogSceneItem, (void *)(intptr_t)child_indent);
  809. return true;
  810. }
  811. void OBSBasic::LogScenes()
  812. {
  813. blog(LOG_INFO, "------------------------------------------------");
  814. blog(LOG_INFO, "Loaded scenes:");
  815. for (int i = 0; i < ui->scenes->count(); i++) {
  816. QListWidgetItem *item = ui->scenes->item(i);
  817. OBSScene scene = GetOBSRef<OBSScene>(item);
  818. obs_source_t *source = obs_scene_get_source(scene);
  819. const char *name = obs_source_get_name(source);
  820. blog(LOG_INFO, "- scene '%s':", name);
  821. obs_scene_enum_items(scene, LogSceneItem, (void *)(intptr_t)1);
  822. obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1);
  823. }
  824. blog(LOG_INFO, "------------------------------------------------");
  825. }
  826. void OBSBasic::Load(SceneCollection &collection)
  827. {
  828. disableSaving++;
  829. lastOutputResolution.reset();
  830. collection.setMigrationResolution(0, 0);
  831. obs_data_t *data = obs_data_create_from_json_file_safe(collection.getFilePathString().c_str(), "bak");
  832. if (!data) {
  833. disableSaving--;
  834. const std::filesystem::path filePath = collection.getFilePath();
  835. if (std::filesystem::exists(filePath)) {
  836. std::filesystem::path backupFilePath = filePath;
  837. backupFilePath.replace_extension(".json.invalid");
  838. blog(LOG_WARNING,
  839. "File exists but appears to be corrupt, renaming "
  840. "to \"%s\" before continuing.",
  841. backupFilePath.filename().u8string().c_str());
  842. try {
  843. std::filesystem::rename(filePath, backupFilePath);
  844. } catch (const std::filesystem::filesystem_error &error) {
  845. blog(LOG_ERROR, "Failed renaming corrupt file:\n%s", error.what());
  846. }
  847. }
  848. blog(LOG_INFO, "No scene file found, creating default scene");
  849. bool hasFirstRun = config_get_bool(App()->GetUserConfig(), "General", "FirstRun");
  850. CreateDefaultScene(!hasFirstRun);
  851. SaveProject();
  852. return;
  853. }
  854. LoadData(data, collection);
  855. }
  856. static inline void AddMissingFiles(void *data, obs_source_t *source)
  857. {
  858. obs_missing_files_t *f = (obs_missing_files_t *)data;
  859. obs_missing_files_t *sf = obs_source_get_missing_files(source);
  860. obs_missing_files_append(f, sf);
  861. obs_missing_files_destroy(sf);
  862. }
  863. void OBSBasic::LoadData(obs_data_t *data, SceneCollection &collection)
  864. {
  865. ClearSceneData();
  866. ClearContextBar();
  867. /* Exit OBS if clearing scene data failed for some reason. */
  868. if (clearingFailed) {
  869. OBSMessageBox::critical(this, QTStr("SourceLeak.Title"), QTStr("SourceLeak.Text"));
  870. close();
  871. return;
  872. }
  873. InitDefaultTransitions();
  874. if (devicePropertiesThread && devicePropertiesThread->isRunning()) {
  875. devicePropertiesThread->wait();
  876. devicePropertiesThread.reset();
  877. }
  878. QApplication::sendPostedEvents(nullptr);
  879. OBSDataAutoRelease modulesObj = obs_data_get_obj(data, "modules");
  880. if (api)
  881. api->on_preload(modulesObj);
  882. /* Keep a reference to "modules" data so plugins that are not loaded do
  883. * not have their collection specific data lost. */
  884. collectionModuleData = obs_data_get_obj(data, "modules");
  885. OBSDataArrayAutoRelease sceneOrder = obs_data_get_array(data, "scene_order");
  886. OBSDataArrayAutoRelease sources = obs_data_get_array(data, "sources");
  887. OBSDataArrayAutoRelease groups = obs_data_get_array(data, "groups");
  888. OBSDataArrayAutoRelease transitions = obs_data_get_array(data, "transitions");
  889. const char *sceneName = obs_data_get_string(data, "current_scene");
  890. const char *programSceneName = obs_data_get_string(data, "current_program_scene");
  891. const char *transitionName = obs_data_get_string(data, "current_transition");
  892. if (!opt_starting_scene.empty()) {
  893. programSceneName = opt_starting_scene.c_str();
  894. if (!IsPreviewProgramMode())
  895. sceneName = opt_starting_scene.c_str();
  896. }
  897. int newDuration = obs_data_get_int(data, "transition_duration");
  898. if (!newDuration)
  899. newDuration = 300;
  900. if (!transitionName)
  901. transitionName = obs_source_get_name(fadeTransition);
  902. const char *curSceneCollection = config_get_string(App()->GetUserConfig(), "Basic", "SceneCollection");
  903. obs_data_set_default_string(data, "name", curSceneCollection);
  904. const char *name = obs_data_get_string(data, "name");
  905. OBSSourceAutoRelease curScene;
  906. OBSSourceAutoRelease curProgramScene;
  907. obs_source_t *curTransition;
  908. if (!name || !*name)
  909. name = curSceneCollection;
  910. LoadAudioDevice(DESKTOP_AUDIO_1, 1, data);
  911. LoadAudioDevice(DESKTOP_AUDIO_2, 2, data);
  912. LoadAudioDevice(AUX_AUDIO_1, 3, data);
  913. LoadAudioDevice(AUX_AUDIO_2, 4, data);
  914. LoadAudioDevice(AUX_AUDIO_3, 5, data);
  915. LoadAudioDevice(AUX_AUDIO_4, 6, data);
  916. if (!sources) {
  917. sources = std::move(groups);
  918. } else {
  919. obs_data_array_push_back_array(sources, groups);
  920. }
  921. bool resetVideo = false;
  922. obs_video_info ovi;
  923. int64_t version = obs_data_get_int(data, "version");
  924. OBSDataAutoRelease res = obs_data_get_obj(data, "resolution");
  925. OBS::Rect collectionSize{};
  926. if (res) {
  927. collectionSize.setWidth(obs_data_get_int(res, "x"));
  928. collectionSize.setHeight(obs_data_get_int(res, "y"));
  929. }
  930. /* Only migrate legacy collection if resolution is saved. */
  931. if (version < 2 && !collectionSize.isZero()) {
  932. obs_get_video_info(&ovi);
  933. collection.setMigrationResolution(collectionSize);
  934. OBS::Rect outputSize{ovi.base_width, ovi.base_height};
  935. if (outputSize != collectionSize) {
  936. ovi.base_width = collectionSize.getWidth<uint32_t>();
  937. ovi.base_height = collectionSize.getHeight<uint32_t>();
  938. /* Attempt to reset to last known canvas resolution for migration. */
  939. resetVideo = obs_reset_video(&ovi) == OBS_VIDEO_SUCCESS;
  940. if (!resetVideo) {
  941. collection.setCoordinateMode(OBS::SceneCoordinateMode::Absolute);
  942. }
  943. }
  944. // If migration is necessary, attempt to back up version 1 variant of the scene ecollection.
  945. if (collection.getCoordinateMode() == SceneCoordinateMode::Absolute) {
  946. std::filesystem::path backupFilePath = collection.getFilePath();
  947. backupFilePath.replace_extension(".json.v1");
  948. if (!std::filesystem::exists(backupFilePath)) {
  949. bool success = obs_data_save_json_pretty_safe(data, backupFilePath.u8string().c_str(),
  950. "tmp", nullptr);
  951. if (!success) {
  952. blog(LOG_WARNING,
  953. "Failed to create a backup of existing scene collection data");
  954. }
  955. }
  956. }
  957. collection.setCoordinateMode(SceneCoordinateMode::Relative);
  958. } else if (version < 2) {
  959. collection.setCoordinateMode(SceneCoordinateMode::Absolute);
  960. } else {
  961. OBSDataAutoRelease migrationResolution = obs_data_get_obj(data, "migration_resolution");
  962. if (migrationResolution) {
  963. collection.setMigrationResolution(obs_data_get_int(migrationResolution, "x"),
  964. obs_data_get_int(migrationResolution, "y"));
  965. }
  966. }
  967. // FIXME: Migrate to actual SceneCollection container with reference-based API
  968. // The collection passed as function argument might be a copy generated via std::optional and thus
  969. // might not represent the actual collection within the collection, meaning all changes would be lost after
  970. // the function stack is unwound (i.e., the change would not be written into the scene collection file
  971. // during OBS shutdown).
  972. // Explicitly updating the collection inside the container ensures the changes "stick".
  973. collections[collection.getName()] = collection;
  974. updateRemigrationMenuItem(collection.getCoordinateMode(), ui->actionRemigrateSceneCollection);
  975. obs_missing_files_t *files = obs_missing_files_create();
  976. obs_load_sources(sources, AddMissingFiles, files);
  977. if (resetVideo)
  978. ResetVideo();
  979. if (transitions)
  980. LoadTransitions(transitions, AddMissingFiles, files);
  981. if (sceneOrder)
  982. LoadSceneListOrder(sceneOrder);
  983. curTransition = FindTransition(transitionName);
  984. if (!curTransition)
  985. curTransition = fadeTransition;
  986. ui->transitionDuration->setValue(newDuration);
  987. SetTransition(curTransition);
  988. retryScene:
  989. curScene = obs_get_source_by_name(sceneName);
  990. curProgramScene = obs_get_source_by_name(programSceneName);
  991. /* if the starting scene command line parameter is bad at all,
  992. * fall back to original settings */
  993. if (!opt_starting_scene.empty() && (!curScene || !curProgramScene)) {
  994. sceneName = obs_data_get_string(data, "current_scene");
  995. programSceneName = obs_data_get_string(data, "current_program_scene");
  996. opt_starting_scene.clear();
  997. goto retryScene;
  998. }
  999. if (!curScene) {
  1000. auto find_scene_cb = [](void *source_ptr, obs_source_t *scene) {
  1001. *static_cast<OBSSourceAutoRelease *>(source_ptr) = obs_source_get_ref(scene);
  1002. return false;
  1003. };
  1004. obs_enum_scenes(find_scene_cb, &curScene);
  1005. }
  1006. SetCurrentScene(curScene.Get(), true);
  1007. if (!curProgramScene)
  1008. curProgramScene = std::move(curScene);
  1009. if (IsPreviewProgramMode())
  1010. TransitionToScene(curProgramScene.Get(), true);
  1011. /* ------------------- */
  1012. bool projectorSave = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SaveProjectors");
  1013. if (projectorSave) {
  1014. OBSDataArrayAutoRelease savedProjectors = obs_data_get_array(data, "saved_projectors");
  1015. if (savedProjectors) {
  1016. LoadSavedProjectors(savedProjectors);
  1017. activateWindow();
  1018. }
  1019. }
  1020. /* ------------------- */
  1021. config_set_string(App()->GetUserConfig(), "Basic", "SceneCollection", collection.getName().c_str());
  1022. config_set_string(App()->GetUserConfig(), "Basic", "SceneCollectionFile", collection.getFileName().c_str());
  1023. OBSDataArrayAutoRelease quickTransitionData = obs_data_get_array(data, "quick_transitions");
  1024. LoadQuickTransitions(quickTransitionData);
  1025. RefreshQuickTransitions();
  1026. bool previewLocked = obs_data_get_bool(data, "preview_locked");
  1027. ui->preview->SetLocked(previewLocked);
  1028. ui->actionLockPreview->setChecked(previewLocked);
  1029. /* ---------------------- */
  1030. bool fixedScaling = obs_data_get_bool(data, "scaling_enabled");
  1031. int scalingLevel = (int)obs_data_get_int(data, "scaling_level");
  1032. float scrollOffX = (float)obs_data_get_double(data, "scaling_off_x");
  1033. float scrollOffY = (float)obs_data_get_double(data, "scaling_off_y");
  1034. if (fixedScaling) {
  1035. ui->preview->SetScalingLevel(scalingLevel);
  1036. ui->preview->SetScrollingOffset(scrollOffX, scrollOffY);
  1037. }
  1038. ui->preview->SetFixedScaling(fixedScaling);
  1039. emit ui->preview->DisplayResized();
  1040. if (vcamEnabled) {
  1041. OBSDataAutoRelease obj = obs_data_get_obj(data, "virtual-camera");
  1042. vcamConfig.type = (VCamOutputType)obs_data_get_int(obj, "type2");
  1043. if (vcamConfig.type == VCamOutputType::Invalid)
  1044. vcamConfig.type = (VCamOutputType)obs_data_get_int(obj, "type");
  1045. if (vcamConfig.type == VCamOutputType::Invalid) {
  1046. VCamInternalType internal = (VCamInternalType)obs_data_get_int(obj, "internal");
  1047. switch (internal) {
  1048. case VCamInternalType::Default:
  1049. vcamConfig.type = VCamOutputType::ProgramView;
  1050. break;
  1051. case VCamInternalType::Preview:
  1052. vcamConfig.type = VCamOutputType::PreviewOutput;
  1053. break;
  1054. }
  1055. }
  1056. vcamConfig.scene = obs_data_get_string(obj, "scene");
  1057. vcamConfig.source = obs_data_get_string(obj, "source");
  1058. }
  1059. if (!collectionSize.isZero()) {
  1060. lastOutputResolution = {collectionSize.getWidth<uint32_t>(), collectionSize.getHeight<uint32_t>()};
  1061. }
  1062. /* ---------------------- */
  1063. if (api)
  1064. api->on_load(modulesObj);
  1065. obs_data_release(data);
  1066. if (!opt_starting_scene.empty())
  1067. opt_starting_scene.clear();
  1068. if (opt_start_streaming && !safe_mode) {
  1069. blog(LOG_INFO, "Starting stream due to command line parameter");
  1070. QMetaObject::invokeMethod(this, "StartStreaming", Qt::QueuedConnection);
  1071. opt_start_streaming = false;
  1072. }
  1073. if (opt_start_recording && !safe_mode) {
  1074. blog(LOG_INFO, "Starting recording due to command line parameter");
  1075. QMetaObject::invokeMethod(this, "StartRecording", Qt::QueuedConnection);
  1076. opt_start_recording = false;
  1077. }
  1078. if (opt_start_replaybuffer && !safe_mode) {
  1079. QMetaObject::invokeMethod(this, "StartReplayBuffer", Qt::QueuedConnection);
  1080. opt_start_replaybuffer = false;
  1081. }
  1082. if (opt_start_virtualcam && !safe_mode) {
  1083. QMetaObject::invokeMethod(this, "StartVirtualCam", Qt::QueuedConnection);
  1084. opt_start_virtualcam = false;
  1085. }
  1086. LogScenes();
  1087. if (!App()->IsMissingFilesCheckDisabled())
  1088. ShowMissingFilesDialog(files);
  1089. disableSaving--;
  1090. if (vcamEnabled)
  1091. outputHandler->UpdateVirtualCamOutputSource();
  1092. OnEvent(OBS_FRONTEND_EVENT_SCENE_CHANGED);
  1093. OnEvent(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  1094. }
  1095. void OBSBasic::SaveProjectNow()
  1096. {
  1097. if (disableSaving)
  1098. return;
  1099. projectChanged = true;
  1100. SaveProjectDeferred();
  1101. }
  1102. void OBSBasic::SaveProject()
  1103. {
  1104. if (disableSaving)
  1105. return;
  1106. projectChanged = true;
  1107. QMetaObject::invokeMethod(this, "SaveProjectDeferred", Qt::QueuedConnection);
  1108. }
  1109. void OBSBasic::SaveProjectDeferred()
  1110. {
  1111. if (disableSaving)
  1112. return;
  1113. if (!projectChanged)
  1114. return;
  1115. projectChanged = false;
  1116. try {
  1117. OBS::SceneCollection &currentCollection = GetCurrentSceneCollection();
  1118. Save(currentCollection);
  1119. } catch (const std::invalid_argument &error) {
  1120. blog(LOG_ERROR, "%s", error.what());
  1121. }
  1122. }
  1123. void OBSBasic::ClearSceneData()
  1124. {
  1125. disableSaving++;
  1126. setCursor(Qt::WaitCursor);
  1127. CloseDialogs();
  1128. ClearVolumeControls();
  1129. ClearListItems(ui->scenes);
  1130. ui->sources->Clear();
  1131. ClearQuickTransitions();
  1132. ui->transitions->clear();
  1133. ClearProjectors();
  1134. for (int i = 0; i < MAX_CHANNELS; i++)
  1135. obs_set_output_source(i, nullptr);
  1136. /* Reset VCam to default to clear its private scene and any references
  1137. * it holds. It will be reconfigured during loading. */
  1138. if (vcamEnabled) {
  1139. vcamConfig.type = VCamOutputType::ProgramView;
  1140. outputHandler->UpdateVirtualCamOutputSource();
  1141. }
  1142. collectionModuleData = nullptr;
  1143. lastScene = nullptr;
  1144. swapScene = nullptr;
  1145. programScene = nullptr;
  1146. prevFTBSource = nullptr;
  1147. clipboard.clear();
  1148. copyFiltersSource = nullptr;
  1149. copyFilter = nullptr;
  1150. auto cb = [](void *, obs_source_t *source) {
  1151. obs_source_remove(source);
  1152. return true;
  1153. };
  1154. obs_enum_scenes(cb, nullptr);
  1155. obs_enum_sources(cb, nullptr);
  1156. OnEvent(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  1157. undo_s.clear();
  1158. /* using QEvent::DeferredDelete explicitly is the only way to ensure
  1159. * that deleteLater events are processed at this point */
  1160. QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
  1161. do {
  1162. QApplication::sendPostedEvents(nullptr);
  1163. } while (obs_wait_for_destroy_queue());
  1164. /* Pump Qt events one final time to give remaining signals time to be
  1165. * processed (since this happens after the destroy thread finishes and
  1166. * the audio/video threads have processed their tasks). */
  1167. QApplication::sendPostedEvents(nullptr);
  1168. unsetCursor();
  1169. /* If scene data wasn't actually cleared, e.g. faulty plugin holding a
  1170. * reference, they will still be in the hash table, enumerate them and
  1171. * store the names for logging purposes. */
  1172. auto cb2 = [](void *param, obs_source_t *source) {
  1173. auto orphans = static_cast<vector<string> *>(param);
  1174. orphans->push_back(obs_source_get_name(source));
  1175. return true;
  1176. };
  1177. vector<string> orphan_sources;
  1178. obs_enum_sources(cb2, &orphan_sources);
  1179. if (!orphan_sources.empty()) {
  1180. /* Avoid logging list twice in case it gets called after
  1181. * setting the flag the first time. */
  1182. if (!clearingFailed) {
  1183. /* This ugly mess exists to join a vector of strings
  1184. * with a user-defined delimiter. */
  1185. string orphan_names =
  1186. std::accumulate(orphan_sources.begin(), orphan_sources.end(), string(""),
  1187. [](string a, string b) { return std::move(a) + "\n- " + b; });
  1188. blog(LOG_ERROR, "Not all sources were cleared when clearing scene data:\n%s\n",
  1189. orphan_names.c_str());
  1190. }
  1191. /* We do not decrement disableSaving here to avoid OBS
  1192. * overwriting user data with garbage. */
  1193. clearingFailed = true;
  1194. } else {
  1195. disableSaving--;
  1196. blog(LOG_INFO, "All scene data cleared");
  1197. blog(LOG_INFO, "------------------------------------------------");
  1198. }
  1199. }
  1200. void OBSBasic::ShowMissingFilesDialog(obs_missing_files_t *files)
  1201. {
  1202. if (obs_missing_files_count(files) > 0) {
  1203. /* When loading the missing files dialog on launch, the
  1204. * window hasn't fully initialized by this point on macOS,
  1205. * so put this at the end of the current task queue. Fixes
  1206. * a bug where the window is behind OBS on startup. */
  1207. QTimer::singleShot(0, [this, files] {
  1208. missDialog = new OBSMissingFiles(files, this);
  1209. missDialog->setAttribute(Qt::WA_DeleteOnClose, true);
  1210. missDialog->show();
  1211. missDialog->raise();
  1212. });
  1213. } else {
  1214. obs_missing_files_destroy(files);
  1215. /* Only raise dialog if triggered manually */
  1216. if (!disableSaving)
  1217. OBSMessageBox::information(this, QTStr("MissingFiles.NoMissing.Title"),
  1218. QTStr("MissingFiles.NoMissing.Text"));
  1219. }
  1220. }
  1221. void OBSBasic::on_actionShowMissingFiles_triggered()
  1222. {
  1223. obs_missing_files_t *files = obs_missing_files_create();
  1224. auto cb_sources = [](void *data, obs_source_t *source) {
  1225. AddMissingFiles(data, source);
  1226. return true;
  1227. };
  1228. obs_enum_all_sources(cb_sources, files);
  1229. ShowMissingFilesDialog(files);
  1230. }