OBSBasic_SceneCollections.cpp 51 KB

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