1
0

OBSBasic_SceneCollections.cpp 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565
  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 = OBSBasic::Get();
  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. std::string collectionName = obs_data_get_string(collectionData, "name");
  296. if (collectionName.empty()) {
  297. candidateName = entry.path().stem().u8string();
  298. } else {
  299. candidateName = std::move(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. activateWindow();
  984. }
  985. }
  986. /* ------------------- */
  987. std::string file_base = strrchr(file, '/') + 1;
  988. file_base.erase(file_base.size() - 5, 5);
  989. config_set_string(App()->GetUserConfig(), "Basic", "SceneCollection", name);
  990. config_set_string(App()->GetUserConfig(), "Basic", "SceneCollectionFile", file_base.c_str());
  991. OBSDataArrayAutoRelease quickTransitionData = obs_data_get_array(data, "quick_transitions");
  992. LoadQuickTransitions(quickTransitionData);
  993. RefreshQuickTransitions();
  994. bool previewLocked = obs_data_get_bool(data, "preview_locked");
  995. ui->preview->SetLocked(previewLocked);
  996. ui->actionLockPreview->setChecked(previewLocked);
  997. /* ---------------------- */
  998. bool fixedScaling = obs_data_get_bool(data, "scaling_enabled");
  999. int scalingLevel = (int)obs_data_get_int(data, "scaling_level");
  1000. float scrollOffX = (float)obs_data_get_double(data, "scaling_off_x");
  1001. float scrollOffY = (float)obs_data_get_double(data, "scaling_off_y");
  1002. if (fixedScaling) {
  1003. ui->preview->SetScalingLevel(scalingLevel);
  1004. ui->preview->SetScrollingOffset(scrollOffX, scrollOffY);
  1005. }
  1006. ui->preview->SetFixedScaling(fixedScaling);
  1007. emit ui->preview->DisplayResized();
  1008. if (vcamEnabled) {
  1009. OBSDataAutoRelease obj = obs_data_get_obj(data, "virtual-camera");
  1010. vcamConfig.type = (VCamOutputType)obs_data_get_int(obj, "type2");
  1011. if (vcamConfig.type == VCamOutputType::Invalid)
  1012. vcamConfig.type = (VCamOutputType)obs_data_get_int(obj, "type");
  1013. if (vcamConfig.type == VCamOutputType::Invalid) {
  1014. VCamInternalType internal = (VCamInternalType)obs_data_get_int(obj, "internal");
  1015. switch (internal) {
  1016. case VCamInternalType::Default:
  1017. vcamConfig.type = VCamOutputType::ProgramView;
  1018. break;
  1019. case VCamInternalType::Preview:
  1020. vcamConfig.type = VCamOutputType::PreviewOutput;
  1021. break;
  1022. }
  1023. }
  1024. vcamConfig.scene = obs_data_get_string(obj, "scene");
  1025. vcamConfig.source = obs_data_get_string(obj, "source");
  1026. }
  1027. if (obs_data_has_user_value(data, "resolution")) {
  1028. OBSDataAutoRelease res = obs_data_get_obj(data, "resolution");
  1029. if (obs_data_has_user_value(res, "x") && obs_data_has_user_value(res, "y")) {
  1030. lastOutputResolution = {obs_data_get_int(res, "x"), obs_data_get_int(res, "y")};
  1031. }
  1032. }
  1033. /* ---------------------- */
  1034. if (api)
  1035. api->on_load(modulesObj);
  1036. obs_data_release(data);
  1037. if (!opt_starting_scene.empty())
  1038. opt_starting_scene.clear();
  1039. if (opt_start_streaming && !safe_mode) {
  1040. blog(LOG_INFO, "Starting stream due to command line parameter");
  1041. QMetaObject::invokeMethod(this, "StartStreaming", Qt::QueuedConnection);
  1042. opt_start_streaming = false;
  1043. }
  1044. if (opt_start_recording && !safe_mode) {
  1045. blog(LOG_INFO, "Starting recording due to command line parameter");
  1046. QMetaObject::invokeMethod(this, "StartRecording", Qt::QueuedConnection);
  1047. opt_start_recording = false;
  1048. }
  1049. if (opt_start_replaybuffer && !safe_mode) {
  1050. QMetaObject::invokeMethod(this, "StartReplayBuffer", Qt::QueuedConnection);
  1051. opt_start_replaybuffer = false;
  1052. }
  1053. if (opt_start_virtualcam && !safe_mode) {
  1054. QMetaObject::invokeMethod(this, "StartVirtualCam", Qt::QueuedConnection);
  1055. opt_start_virtualcam = false;
  1056. }
  1057. LogScenes();
  1058. if (!App()->IsMissingFilesCheckDisabled())
  1059. ShowMissingFilesDialog(files);
  1060. disableSaving--;
  1061. if (vcamEnabled)
  1062. outputHandler->UpdateVirtualCamOutputSource();
  1063. OnEvent(OBS_FRONTEND_EVENT_SCENE_CHANGED);
  1064. OnEvent(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED);
  1065. }
  1066. void OBSBasic::SaveProjectNow()
  1067. {
  1068. if (disableSaving)
  1069. return;
  1070. projectChanged = true;
  1071. SaveProjectDeferred();
  1072. }
  1073. void OBSBasic::SaveProject()
  1074. {
  1075. if (disableSaving)
  1076. return;
  1077. projectChanged = true;
  1078. QMetaObject::invokeMethod(this, "SaveProjectDeferred", Qt::QueuedConnection);
  1079. }
  1080. void OBSBasic::SaveProjectDeferred()
  1081. {
  1082. if (disableSaving)
  1083. return;
  1084. if (!projectChanged)
  1085. return;
  1086. projectChanged = false;
  1087. try {
  1088. const OBSSceneCollection &currentCollection = GetCurrentSceneCollection();
  1089. Save(currentCollection.collectionFile.u8string().c_str());
  1090. } catch (const std::invalid_argument &error) {
  1091. blog(LOG_ERROR, "%s", error.what());
  1092. }
  1093. }
  1094. void OBSBasic::ClearSceneData()
  1095. {
  1096. disableSaving++;
  1097. setCursor(Qt::WaitCursor);
  1098. CloseDialogs();
  1099. ClearVolumeControls();
  1100. ClearListItems(ui->scenes);
  1101. ui->sources->Clear();
  1102. ClearQuickTransitions();
  1103. ui->transitions->clear();
  1104. ClearProjectors();
  1105. for (int i = 0; i < MAX_CHANNELS; i++)
  1106. obs_set_output_source(i, nullptr);
  1107. /* Reset VCam to default to clear its private scene and any references
  1108. * it holds. It will be reconfigured during loading. */
  1109. if (vcamEnabled) {
  1110. vcamConfig.type = VCamOutputType::ProgramView;
  1111. outputHandler->UpdateVirtualCamOutputSource();
  1112. }
  1113. collectionModuleData = nullptr;
  1114. lastScene = nullptr;
  1115. swapScene = nullptr;
  1116. programScene = nullptr;
  1117. prevFTBSource = nullptr;
  1118. clipboard.clear();
  1119. copyFiltersSource = nullptr;
  1120. copyFilter = nullptr;
  1121. auto cb = [](void *, obs_source_t *source) {
  1122. obs_source_remove(source);
  1123. return true;
  1124. };
  1125. obs_enum_scenes(cb, nullptr);
  1126. obs_enum_sources(cb, nullptr);
  1127. OnEvent(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP);
  1128. undo_s.clear();
  1129. /* using QEvent::DeferredDelete explicitly is the only way to ensure
  1130. * that deleteLater events are processed at this point */
  1131. QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete);
  1132. do {
  1133. QApplication::sendPostedEvents(nullptr);
  1134. } while (obs_wait_for_destroy_queue());
  1135. /* Pump Qt events one final time to give remaining signals time to be
  1136. * processed (since this happens after the destroy thread finishes and
  1137. * the audio/video threads have processed their tasks). */
  1138. QApplication::sendPostedEvents(nullptr);
  1139. unsetCursor();
  1140. /* If scene data wasn't actually cleared, e.g. faulty plugin holding a
  1141. * reference, they will still be in the hash table, enumerate them and
  1142. * store the names for logging purposes. */
  1143. auto cb2 = [](void *param, obs_source_t *source) {
  1144. auto orphans = static_cast<vector<string> *>(param);
  1145. orphans->push_back(obs_source_get_name(source));
  1146. return true;
  1147. };
  1148. vector<string> orphan_sources;
  1149. obs_enum_sources(cb2, &orphan_sources);
  1150. if (!orphan_sources.empty()) {
  1151. /* Avoid logging list twice in case it gets called after
  1152. * setting the flag the first time. */
  1153. if (!clearingFailed) {
  1154. /* This ugly mess exists to join a vector of strings
  1155. * with a user-defined delimiter. */
  1156. string orphan_names =
  1157. std::accumulate(orphan_sources.begin(), orphan_sources.end(), string(""),
  1158. [](string a, string b) { return std::move(a) + "\n- " + b; });
  1159. blog(LOG_ERROR, "Not all sources were cleared when clearing scene data:\n%s\n",
  1160. orphan_names.c_str());
  1161. }
  1162. /* We do not decrement disableSaving here to avoid OBS
  1163. * overwriting user data with garbage. */
  1164. clearingFailed = true;
  1165. } else {
  1166. disableSaving--;
  1167. blog(LOG_INFO, "All scene data cleared");
  1168. blog(LOG_INFO, "------------------------------------------------");
  1169. }
  1170. }
  1171. void OBSBasic::ShowMissingFilesDialog(obs_missing_files_t *files)
  1172. {
  1173. if (obs_missing_files_count(files) > 0) {
  1174. /* When loading the missing files dialog on launch, the
  1175. * window hasn't fully initialized by this point on macOS,
  1176. * so put this at the end of the current task queue. Fixes
  1177. * a bug where the window is behind OBS on startup. */
  1178. QTimer::singleShot(0, [this, files] {
  1179. missDialog = new OBSMissingFiles(files, this);
  1180. missDialog->setAttribute(Qt::WA_DeleteOnClose, true);
  1181. missDialog->show();
  1182. missDialog->raise();
  1183. });
  1184. } else {
  1185. obs_missing_files_destroy(files);
  1186. /* Only raise dialog if triggered manually */
  1187. if (!disableSaving)
  1188. OBSMessageBox::information(this, QTStr("MissingFiles.NoMissing.Title"),
  1189. QTStr("MissingFiles.NoMissing.Text"));
  1190. }
  1191. }
  1192. void OBSBasic::on_actionShowMissingFiles_triggered()
  1193. {
  1194. obs_missing_files_t *files = obs_missing_files_create();
  1195. auto cb_sources = [](void *data, obs_source_t *source) {
  1196. AddMissingFiles(data, source);
  1197. return true;
  1198. };
  1199. obs_enum_all_sources(cb_sources, files);
  1200. ShowMissingFilesDialog(files);
  1201. }