auto-scene-switcher.cpp 12 KB

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