OBSBasic_SceneCollections.cpp 51 KB

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