auto-scene-switcher.cpp 11 KB

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