1
0

auto-scene-switcher.cpp 12 KB

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