auto-scene-switcher.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. #include <obs-frontend-api.h>
  2. #include <obs-module.h>
  3. #include <obs.hpp>
  4. #include <util/util.hpp>
  5. #include <QMainWindow>
  6. #include <QMessageBox>
  7. #include <QAction>
  8. #include "auto-scene-switcher.hpp"
  9. #include "tool-helpers.hpp"
  10. #include <condition_variable>
  11. #include <chrono>
  12. #include <string>
  13. #include <vector>
  14. #include <thread>
  15. #include <regex>
  16. #include <mutex>
  17. using namespace std;
  18. #define DEFAULT_INTERVAL 300
  19. struct SceneSwitch {
  20. OBSWeakSource scene;
  21. string window;
  22. regex re;
  23. inline SceneSwitch(OBSWeakSource scene_, const char *window_)
  24. : scene(scene_), window(window_), re(window_)
  25. {
  26. }
  27. };
  28. static inline bool WeakSourceValid(obs_weak_source_t *ws)
  29. {
  30. OBSSourceAutoRelease source = obs_weak_source_get_source(ws);
  31. return !!source;
  32. }
  33. struct SwitcherData {
  34. thread th;
  35. condition_variable cv;
  36. mutex m;
  37. bool stop = false;
  38. vector<SceneSwitch> switches;
  39. OBSWeakSource nonMatchingScene;
  40. int interval = DEFAULT_INTERVAL;
  41. bool switchIfNotMatching = false;
  42. bool startAtLaunch = false;
  43. void Thread();
  44. void Start();
  45. void Stop();
  46. void Prune()
  47. {
  48. for (size_t i = 0; i < switches.size(); i++) {
  49. SceneSwitch &s = switches[i];
  50. if (!WeakSourceValid(s.scene))
  51. switches.erase(switches.begin() + i--);
  52. }
  53. if (nonMatchingScene && !WeakSourceValid(nonMatchingScene)) {
  54. switchIfNotMatching = false;
  55. nonMatchingScene = nullptr;
  56. }
  57. }
  58. inline ~SwitcherData() { Stop(); }
  59. };
  60. static SwitcherData *switcher = nullptr;
  61. static inline QString MakeSwitchName(const QString &scene,
  62. const QString &window)
  63. {
  64. return QStringLiteral("[") + scene + QStringLiteral("]: ") + window;
  65. }
  66. SceneSwitcher::SceneSwitcher(QWidget *parent)
  67. : QDialog(parent), ui(new Ui_SceneSwitcher)
  68. {
  69. ui->setupUi(this);
  70. setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
  71. lock_guard<mutex> lock(switcher->m);
  72. switcher->Prune();
  73. BPtr<char *> scenes = obs_frontend_get_scene_names();
  74. char **temp = scenes;
  75. while (*temp) {
  76. const char *name = *temp;
  77. ui->scenes->addItem(name);
  78. ui->noMatchSwitchScene->addItem(name);
  79. temp++;
  80. }
  81. if (switcher->switchIfNotMatching)
  82. ui->noMatchSwitch->setChecked(true);
  83. else
  84. ui->noMatchDontSwitch->setChecked(true);
  85. ui->noMatchSwitchScene->setCurrentText(
  86. GetWeakSourceName(switcher->nonMatchingScene).c_str());
  87. ui->checkInterval->setValue(switcher->interval);
  88. vector<string> windows;
  89. GetWindowList(windows);
  90. for (string &window : windows)
  91. ui->windows->addItem(window.c_str());
  92. for (auto &s : switcher->switches) {
  93. string sceneName = GetWeakSourceName(s.scene);
  94. QString text =
  95. MakeSwitchName(sceneName.c_str(), s.window.c_str());
  96. QListWidgetItem *item = new QListWidgetItem(text, ui->switches);
  97. item->setData(Qt::UserRole, s.window.c_str());
  98. }
  99. if (switcher->th.joinable())
  100. SetStarted();
  101. else
  102. SetStopped();
  103. loading = false;
  104. }
  105. void SceneSwitcher::closeEvent(QCloseEvent *)
  106. {
  107. obs_frontend_save();
  108. }
  109. int SceneSwitcher::FindByData(const QString &window)
  110. {
  111. int count = ui->switches->count();
  112. int idx = -1;
  113. for (int i = 0; i < count; i++) {
  114. QListWidgetItem *item = ui->switches->item(i);
  115. QString itemWindow = item->data(Qt::UserRole).toString();
  116. if (itemWindow == window) {
  117. idx = i;
  118. break;
  119. }
  120. }
  121. return idx;
  122. }
  123. void SceneSwitcher::on_switches_currentRowChanged(int idx)
  124. {
  125. if (loading)
  126. return;
  127. if (idx == -1)
  128. return;
  129. QListWidgetItem *item = ui->switches->item(idx);
  130. QString window = item->data(Qt::UserRole).toString();
  131. lock_guard<mutex> lock(switcher->m);
  132. for (auto &s : switcher->switches) {
  133. if (window.compare(s.window.c_str()) == 0) {
  134. string name = GetWeakSourceName(s.scene);
  135. ui->scenes->setCurrentText(name.c_str());
  136. ui->windows->setCurrentText(window);
  137. break;
  138. }
  139. }
  140. }
  141. void SceneSwitcher::on_close_clicked()
  142. {
  143. done(0);
  144. }
  145. void SceneSwitcher::on_add_clicked()
  146. {
  147. QString sceneName = ui->scenes->currentText();
  148. QString windowName = ui->windows->currentText();
  149. if (windowName.isEmpty())
  150. return;
  151. OBSWeakSource source = GetWeakSourceByQString(sceneName);
  152. QVariant v = QVariant::fromValue(windowName);
  153. QString text = MakeSwitchName(sceneName, windowName);
  154. int idx = FindByData(windowName);
  155. if (idx == -1) {
  156. try {
  157. lock_guard<mutex> lock(switcher->m);
  158. switcher->switches.emplace_back(
  159. source, windowName.toUtf8().constData());
  160. QListWidgetItem *item =
  161. new QListWidgetItem(text, ui->switches);
  162. item->setData(Qt::UserRole, v);
  163. } catch (const regex_error &) {
  164. QMessageBox::warning(
  165. this, obs_module_text("InvalidRegex.Title"),
  166. obs_module_text("InvalidRegex.Text"));
  167. }
  168. } else {
  169. QListWidgetItem *item = ui->switches->item(idx);
  170. item->setText(text);
  171. string window = windowName.toUtf8().constData();
  172. {
  173. lock_guard<mutex> lock(switcher->m);
  174. for (auto &s : switcher->switches) {
  175. if (s.window == window) {
  176. s.scene = source;
  177. break;
  178. }
  179. }
  180. }
  181. ui->switches->sortItems();
  182. }
  183. }
  184. void SceneSwitcher::on_remove_clicked()
  185. {
  186. QListWidgetItem *item = ui->switches->currentItem();
  187. if (!item)
  188. return;
  189. string window =
  190. item->data(Qt::UserRole).toString().toUtf8().constData();
  191. {
  192. lock_guard<mutex> lock(switcher->m);
  193. auto &switches = switcher->switches;
  194. for (auto it = switches.begin(); it != switches.end(); ++it) {
  195. auto &s = *it;
  196. if (s.window == window) {
  197. switches.erase(it);
  198. break;
  199. }
  200. }
  201. }
  202. delete item;
  203. }
  204. void SceneSwitcher::on_startAtLaunch_toggled(bool value)
  205. {
  206. if (loading)
  207. return;
  208. lock_guard<mutex> lock(switcher->m);
  209. switcher->startAtLaunch = value;
  210. }
  211. void SceneSwitcher::UpdateNonMatchingScene(const QString &name)
  212. {
  213. OBSSourceAutoRelease scene =
  214. obs_get_source_by_name(name.toUtf8().constData());
  215. OBSWeakSourceAutoRelease ws = obs_source_get_weak_source(scene);
  216. switcher->nonMatchingScene = ws.Get();
  217. }
  218. void SceneSwitcher::on_noMatchDontSwitch_clicked()
  219. {
  220. if (loading)
  221. return;
  222. lock_guard<mutex> lock(switcher->m);
  223. switcher->switchIfNotMatching = false;
  224. }
  225. void SceneSwitcher::on_noMatchSwitch_clicked()
  226. {
  227. if (loading)
  228. return;
  229. lock_guard<mutex> lock(switcher->m);
  230. switcher->switchIfNotMatching = true;
  231. UpdateNonMatchingScene(ui->noMatchSwitchScene->currentText());
  232. }
  233. void SceneSwitcher::on_noMatchSwitchScene_currentTextChanged(const QString &text)
  234. {
  235. if (loading)
  236. return;
  237. lock_guard<mutex> lock(switcher->m);
  238. UpdateNonMatchingScene(text);
  239. }
  240. void SceneSwitcher::on_checkInterval_valueChanged(int value)
  241. {
  242. if (loading)
  243. return;
  244. lock_guard<mutex> lock(switcher->m);
  245. switcher->interval = value;
  246. }
  247. void SceneSwitcher::SetStarted()
  248. {
  249. ui->toggleStartButton->setText(obs_module_text("Stop"));
  250. ui->pluginRunningText->setText(obs_module_text("Active"));
  251. }
  252. void SceneSwitcher::SetStopped()
  253. {
  254. ui->toggleStartButton->setText(obs_module_text("Start"));
  255. ui->pluginRunningText->setText(obs_module_text("Inactive"));
  256. }
  257. void SceneSwitcher::on_toggleStartButton_clicked()
  258. {
  259. if (switcher->th.joinable()) {
  260. switcher->Stop();
  261. SetStopped();
  262. } else {
  263. switcher->Start();
  264. SetStarted();
  265. }
  266. }
  267. static void SaveSceneSwitcher(obs_data_t *save_data, bool saving, void *)
  268. {
  269. if (saving) {
  270. lock_guard<mutex> lock(switcher->m);
  271. OBSDataAutoRelease obj = obs_data_create();
  272. OBSDataArrayAutoRelease array = obs_data_array_create();
  273. switcher->Prune();
  274. for (SceneSwitch &s : switcher->switches) {
  275. OBSDataAutoRelease array_obj = obs_data_create();
  276. OBSSourceAutoRelease source =
  277. obs_weak_source_get_source(s.scene);
  278. if (source) {
  279. const char *n = obs_source_get_name(source);
  280. obs_data_set_string(array_obj, "scene", n);
  281. obs_data_set_string(array_obj, "window_title",
  282. s.window.c_str());
  283. obs_data_array_push_back(array, array_obj);
  284. }
  285. }
  286. string nonMatchingSceneName =
  287. GetWeakSourceName(switcher->nonMatchingScene);
  288. obs_data_set_int(obj, "interval", switcher->interval);
  289. obs_data_set_string(obj, "non_matching_scene",
  290. nonMatchingSceneName.c_str());
  291. obs_data_set_bool(obj, "switch_if_not_matching",
  292. switcher->switchIfNotMatching);
  293. obs_data_set_bool(obj, "active", switcher->th.joinable());
  294. obs_data_set_array(obj, "switches", array);
  295. obs_data_set_obj(save_data, "auto-scene-switcher", obj);
  296. } else {
  297. switcher->m.lock();
  298. OBSDataAutoRelease obj =
  299. obs_data_get_obj(save_data, "auto-scene-switcher");
  300. OBSDataArrayAutoRelease array =
  301. obs_data_get_array(obj, "switches");
  302. size_t count = obs_data_array_count(array);
  303. if (!obj)
  304. obj = obs_data_create();
  305. obs_data_set_default_int(obj, "interval", DEFAULT_INTERVAL);
  306. switcher->interval = obs_data_get_int(obj, "interval");
  307. switcher->switchIfNotMatching =
  308. obs_data_get_bool(obj, "switch_if_not_matching");
  309. string nonMatchingScene =
  310. obs_data_get_string(obj, "non_matching_scene");
  311. bool active = obs_data_get_bool(obj, "active");
  312. switcher->nonMatchingScene =
  313. GetWeakSourceByName(nonMatchingScene.c_str());
  314. switcher->switches.clear();
  315. for (size_t i = 0; i < count; i++) {
  316. OBSDataAutoRelease array_obj =
  317. obs_data_array_item(array, i);
  318. const char *scene =
  319. obs_data_get_string(array_obj, "scene");
  320. const char *window =
  321. obs_data_get_string(array_obj, "window_title");
  322. switcher->switches.emplace_back(
  323. GetWeakSourceByName(scene), window);
  324. }
  325. switcher->m.unlock();
  326. if (active)
  327. switcher->Start();
  328. else
  329. switcher->Stop();
  330. }
  331. }
  332. void SwitcherData::Thread()
  333. {
  334. chrono::duration<long long, milli> duration =
  335. chrono::milliseconds(interval);
  336. string lastTitle;
  337. string title;
  338. for (;;) {
  339. unique_lock<mutex> lock(m);
  340. OBSWeakSource scene;
  341. bool match = false;
  342. cv.wait_for(lock, duration);
  343. if (switcher->stop) {
  344. switcher->stop = false;
  345. break;
  346. }
  347. duration = chrono::milliseconds(interval);
  348. GetCurrentWindowTitle(title);
  349. if (lastTitle != title) {
  350. switcher->Prune();
  351. for (SceneSwitch &s : switches) {
  352. if (s.window == title) {
  353. match = true;
  354. scene = s.scene;
  355. break;
  356. }
  357. }
  358. /* try regex */
  359. if (!match) {
  360. for (SceneSwitch &s : switches) {
  361. try {
  362. bool matches = regex_match(
  363. title, s.re);
  364. if (matches) {
  365. match = true;
  366. scene = s.scene;
  367. break;
  368. }
  369. } catch (const regex_error &) {
  370. }
  371. }
  372. }
  373. if (!match && switchIfNotMatching && nonMatchingScene) {
  374. match = true;
  375. scene = nonMatchingScene;
  376. }
  377. if (match) {
  378. OBSSourceAutoRelease source =
  379. obs_weak_source_get_source(scene);
  380. OBSSourceAutoRelease currentSource =
  381. obs_frontend_get_current_scene();
  382. if (source && source != currentSource)
  383. obs_frontend_set_current_scene(source);
  384. }
  385. }
  386. lastTitle = title;
  387. }
  388. }
  389. void SwitcherData::Start()
  390. {
  391. if (!switcher->th.joinable())
  392. switcher->th = thread([]() { switcher->Thread(); });
  393. }
  394. void SwitcherData::Stop()
  395. {
  396. if (th.joinable()) {
  397. {
  398. lock_guard<mutex> lock(m);
  399. stop = true;
  400. }
  401. cv.notify_one();
  402. th.join();
  403. }
  404. }
  405. extern "C" void FreeSceneSwitcher()
  406. {
  407. CleanupSceneSwitcher();
  408. delete switcher;
  409. switcher = nullptr;
  410. }
  411. static void OBSEvent(enum obs_frontend_event event, void *)
  412. {
  413. if (event == OBS_FRONTEND_EVENT_EXIT)
  414. FreeSceneSwitcher();
  415. }
  416. extern "C" void InitSceneSwitcher()
  417. {
  418. QAction *action = (QAction *)obs_frontend_add_tools_menu_qaction(
  419. obs_module_text("SceneSwitcher"));
  420. switcher = new SwitcherData;
  421. auto cb = []() {
  422. obs_frontend_push_ui_translation(obs_module_get_string);
  423. QMainWindow *window =
  424. (QMainWindow *)obs_frontend_get_main_window();
  425. SceneSwitcher ss(window);
  426. ss.exec();
  427. obs_frontend_pop_ui_translation();
  428. };
  429. obs_frontend_add_save_callback(SaveSceneSwitcher, nullptr);
  430. obs_frontend_add_event_callback(OBSEvent, nullptr);
  431. action->connect(action, &QAction::triggered, cb);
  432. }