OBSBasic_SceneCollections.cpp 51 KB

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