auto-scene-switcher.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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. connect(this, &QDialog::finished, this, &SceneSwitcher::finished);
  105. }
  106. void SceneSwitcher::finished()
  107. {
  108. obs_frontend_save();
  109. }
  110. int SceneSwitcher::FindByData(const QString &window)
  111. {
  112. int count = ui->switches->count();
  113. int idx = -1;
  114. for (int i = 0; i < count; i++) {
  115. QListWidgetItem *item = ui->switches->item(i);
  116. QString itemWindow = item->data(Qt::UserRole).toString();
  117. if (itemWindow == window) {
  118. idx = i;
  119. break;
  120. }
  121. }
  122. return idx;
  123. }
  124. void SceneSwitcher::on_switches_currentRowChanged(int idx)
  125. {
  126. if (loading)
  127. return;
  128. if (idx == -1)
  129. return;
  130. QListWidgetItem *item = ui->switches->item(idx);
  131. QString window = item->data(Qt::UserRole).toString();
  132. lock_guard<mutex> lock(switcher->m);
  133. for (auto &s : switcher->switches) {
  134. if (window.compare(s.window.c_str()) == 0) {
  135. string name = GetWeakSourceName(s.scene);
  136. ui->scenes->setCurrentText(name.c_str());
  137. ui->windows->setCurrentText(window);
  138. break;
  139. }
  140. }
  141. }
  142. void SceneSwitcher::on_close_clicked()
  143. {
  144. done(0);
  145. }
  146. void SceneSwitcher::on_add_clicked()
  147. {
  148. QString sceneName = ui->scenes->currentText();
  149. QString windowName = ui->windows->currentText();
  150. if (windowName.isEmpty())
  151. return;
  152. OBSWeakSource source = GetWeakSourceByQString(sceneName);
  153. QVariant v = QVariant::fromValue(windowName);
  154. QString text = MakeSwitchName(sceneName, windowName);
  155. int idx = FindByData(windowName);
  156. if (idx == -1) {
  157. try {
  158. lock_guard<mutex> lock(switcher->m);
  159. switcher->switches.emplace_back(
  160. source, windowName.toUtf8().constData());
  161. QListWidgetItem *item =
  162. new QListWidgetItem(text, ui->switches);
  163. item->setData(Qt::UserRole, v);
  164. } catch (const regex_error &) {
  165. QMessageBox::warning(
  166. this, obs_module_text("InvalidRegex.Title"),
  167. obs_module_text("InvalidRegex.Text"));
  168. }
  169. } else {
  170. QListWidgetItem *item = ui->switches->item(idx);
  171. item->setText(text);
  172. string window = windowName.toUtf8().constData();
  173. {
  174. lock_guard<mutex> lock(switcher->m);
  175. for (auto &s : switcher->switches) {
  176. if (s.window == window) {
  177. s.scene = source;
  178. break;
  179. }
  180. }
  181. }
  182. ui->switches->sortItems();
  183. }
  184. }
  185. void SceneSwitcher::on_remove_clicked()
  186. {
  187. QListWidgetItem *item = ui->switches->currentItem();
  188. if (!item)
  189. return;
  190. string window =
  191. item->data(Qt::UserRole).toString().toUtf8().constData();
  192. {
  193. lock_guard<mutex> lock(switcher->m);
  194. auto &switches = switcher->switches;
  195. for (auto it = switches.begin(); it != switches.end(); ++it) {
  196. auto &s = *it;
  197. if (s.window == window) {
  198. switches.erase(it);
  199. break;
  200. }
  201. }
  202. }
  203. delete item;
  204. }
  205. void SceneSwitcher::on_startAtLaunch_toggled(bool value)
  206. {
  207. if (loading)
  208. return;
  209. lock_guard<mutex> lock(switcher->m);
  210. switcher->startAtLaunch = value;
  211. }
  212. void SceneSwitcher::UpdateNonMatchingScene(const QString &name)
  213. {
  214. OBSSourceAutoRelease scene =
  215. obs_get_source_by_name(name.toUtf8().constData());
  216. OBSWeakSourceAutoRelease ws = obs_source_get_weak_source(scene);
  217. switcher->nonMatchingScene = ws.Get();
  218. }
  219. void SceneSwitcher::on_noMatchDontSwitch_clicked()
  220. {
  221. if (loading)
  222. return;
  223. lock_guard<mutex> lock(switcher->m);
  224. switcher->switchIfNotMatching = false;
  225. }
  226. void SceneSwitcher::on_noMatchSwitch_clicked()
  227. {
  228. if (loading)
  229. return;
  230. lock_guard<mutex> lock(switcher->m);
  231. switcher->switchIfNotMatching = true;
  232. UpdateNonMatchingScene(ui->noMatchSwitchScene->currentText());
  233. }
  234. void SceneSwitcher::on_noMatchSwitchScene_currentTextChanged(const QString &text)
  235. {
  236. if (loading)
  237. return;
  238. lock_guard<mutex> lock(switcher->m);
  239. UpdateNonMatchingScene(text);
  240. }
  241. void SceneSwitcher::on_checkInterval_valueChanged(int value)
  242. {
  243. if (loading)
  244. return;
  245. lock_guard<mutex> lock(switcher->m);
  246. switcher->interval = value;
  247. }
  248. void SceneSwitcher::SetStarted()
  249. {
  250. ui->toggleStartButton->setText(obs_module_text("Stop"));
  251. ui->pluginRunningText->setText(obs_module_text("Active"));
  252. }
  253. void SceneSwitcher::SetStopped()
  254. {
  255. ui->toggleStartButton->setText(obs_module_text("Start"));
  256. ui->pluginRunningText->setText(obs_module_text("Inactive"));
  257. }
  258. void SceneSwitcher::on_toggleStartButton_clicked()
  259. {
  260. if (switcher->th.joinable()) {
  261. switcher->Stop();
  262. SetStopped();
  263. } else {
  264. switcher->Start();
  265. SetStarted();
  266. }
  267. }
  268. static void SaveSceneSwitcher(obs_data_t *save_data, bool saving, void *)
  269. {
  270. if (saving) {
  271. lock_guard<mutex> lock(switcher->m);
  272. OBSDataAutoRelease obj = obs_data_create();
  273. OBSDataArrayAutoRelease array = obs_data_array_create();
  274. switcher->Prune();
  275. for (SceneSwitch &s : switcher->switches) {
  276. OBSDataAutoRelease array_obj = obs_data_create();
  277. OBSSourceAutoRelease source =
  278. obs_weak_source_get_source(s.scene);
  279. if (source) {
  280. const char *n = obs_source_get_name(source);
  281. obs_data_set_string(array_obj, "scene", n);
  282. obs_data_set_string(array_obj, "window_title",
  283. s.window.c_str());
  284. obs_data_array_push_back(array, array_obj);
  285. }
  286. }
  287. string nonMatchingSceneName =
  288. GetWeakSourceName(switcher->nonMatchingScene);
  289. obs_data_set_int(obj, "interval", switcher->interval);
  290. obs_data_set_string(obj, "non_matching_scene",
  291. nonMatchingSceneName.c_str());
  292. obs_data_set_bool(obj, "switch_if_not_matching",
  293. switcher->switchIfNotMatching);
  294. obs_data_set_bool(obj, "active", switcher->th.joinable());
  295. obs_data_set_array(obj, "switches", array);
  296. obs_data_set_obj(save_data, "auto-scene-switcher", obj);
  297. } else {
  298. switcher->m.lock();
  299. OBSDataAutoRelease obj =
  300. obs_data_get_obj(save_data, "auto-scene-switcher");
  301. OBSDataArrayAutoRelease array =
  302. obs_data_get_array(obj, "switches");
  303. size_t count = obs_data_array_count(array);
  304. if (!obj)
  305. obj = obs_data_create();
  306. obs_data_set_default_int(obj, "interval", DEFAULT_INTERVAL);
  307. switcher->interval = obs_data_get_int(obj, "interval");
  308. switcher->switchIfNotMatching =
  309. obs_data_get_bool(obj, "switch_if_not_matching");
  310. string nonMatchingScene =
  311. obs_data_get_string(obj, "non_matching_scene");
  312. bool active = obs_data_get_bool(obj, "active");
  313. switcher->nonMatchingScene =
  314. GetWeakSourceByName(nonMatchingScene.c_str());
  315. switcher->switches.clear();
  316. for (size_t i = 0; i < count; i++) {
  317. OBSDataAutoRelease array_obj =
  318. obs_data_array_item(array, i);
  319. const char *scene =
  320. obs_data_get_string(array_obj, "scene");
  321. const char *window =
  322. obs_data_get_string(array_obj, "window_title");
  323. switcher->switches.emplace_back(
  324. GetWeakSourceByName(scene), window);
  325. }
  326. switcher->m.unlock();
  327. if (active)
  328. switcher->Start();
  329. else
  330. switcher->Stop();
  331. }
  332. }
  333. void SwitcherData::Thread()
  334. {
  335. chrono::duration<long long, milli> duration =
  336. chrono::milliseconds(interval);
  337. string lastTitle;
  338. string title;
  339. for (;;) {
  340. unique_lock<mutex> lock(m);
  341. OBSWeakSource scene;
  342. bool match = false;
  343. cv.wait_for(lock, duration);
  344. if (switcher->stop) {
  345. switcher->stop = false;
  346. break;
  347. }
  348. duration = chrono::milliseconds(interval);
  349. GetCurrentWindowTitle(title);
  350. if (lastTitle != title) {
  351. switcher->Prune();
  352. for (SceneSwitch &s : switches) {
  353. if (s.window == title) {
  354. match = true;
  355. scene = s.scene;
  356. break;
  357. }
  358. }
  359. /* try regex */
  360. if (!match) {
  361. for (SceneSwitch &s : switches) {
  362. try {
  363. bool matches = regex_match(
  364. title, s.re);
  365. if (matches) {
  366. match = true;
  367. scene = s.scene;
  368. break;
  369. }
  370. } catch (const regex_error &) {
  371. }
  372. }
  373. }
  374. if (!match && switchIfNotMatching && nonMatchingScene) {
  375. match = true;
  376. scene = nonMatchingScene;
  377. }
  378. if (match) {
  379. OBSSourceAutoRelease source =
  380. obs_weak_source_get_source(scene);
  381. OBSSourceAutoRelease currentSource =
  382. obs_frontend_get_current_scene();
  383. if (source && source != currentSource)
  384. obs_frontend_set_current_scene(source);
  385. }
  386. }
  387. lastTitle = title;
  388. }
  389. }
  390. void SwitcherData::Start()
  391. {
  392. if (!switcher->th.joinable())
  393. switcher->th = thread([]() { switcher->Thread(); });
  394. }
  395. void SwitcherData::Stop()
  396. {
  397. if (th.joinable()) {
  398. {
  399. lock_guard<mutex> lock(m);
  400. stop = true;
  401. }
  402. cv.notify_one();
  403. th.join();
  404. }
  405. }
  406. extern "C" void FreeSceneSwitcher()
  407. {
  408. CleanupSceneSwitcher();
  409. delete switcher;
  410. switcher = nullptr;
  411. }
  412. static void OBSEvent(enum obs_frontend_event event, void *)
  413. {
  414. if (event == OBS_FRONTEND_EVENT_EXIT)
  415. FreeSceneSwitcher();
  416. }
  417. extern "C" void InitSceneSwitcher()
  418. {
  419. QAction *action = (QAction *)obs_frontend_add_tools_menu_qaction(
  420. obs_module_text("SceneSwitcher"));
  421. switcher = new SwitcherData;
  422. auto cb = []() {
  423. obs_frontend_push_ui_translation(obs_module_get_string);
  424. QMainWindow *window =
  425. (QMainWindow *)obs_frontend_get_main_window();
  426. SceneSwitcher ss(window);
  427. ss.exec();
  428. obs_frontend_pop_ui_translation();
  429. };
  430. obs_frontend_add_save_callback(SaveSceneSwitcher, nullptr);
  431. obs_frontend_add_event_callback(OBSEvent, nullptr);
  432. action->connect(action, &QAction::triggered, cb);
  433. }