OBSBasic_SceneCollections.cpp 48 KB

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