captions.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. #include <QMessageBox>
  2. #include <QAction>
  3. #include <windows.h>
  4. #include <obs-frontend-api.h>
  5. #include "captions.hpp"
  6. #include "captions-handler.hpp"
  7. #include "tool-helpers.hpp"
  8. #include <util/dstr.hpp>
  9. #include <util/platform.h>
  10. #include <util/windows/WinHandle.hpp>
  11. #include <util/windows/ComPtr.hpp>
  12. #include <obs-module.h>
  13. #ifdef _MSC_VER
  14. #pragma warning(push)
  15. #pragma warning(disable : 4996)
  16. #endif
  17. #include <sphelper.h>
  18. #ifdef _MSC_VER
  19. #pragma warning(pop)
  20. #endif
  21. #include <unordered_map>
  22. #include <vector>
  23. #include <string>
  24. #include <thread>
  25. #include <mutex>
  26. #include "captions-mssapi.hpp"
  27. #define do_log(type, format, ...) \
  28. blog(type, "[Captions] " format, ##__VA_ARGS__)
  29. #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__)
  30. #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__)
  31. using namespace std;
  32. #define DEFAULT_HANDLER "mssapi"
  33. struct obs_captions {
  34. string handler_id = DEFAULT_HANDLER;
  35. string source_name;
  36. OBSWeakSource source;
  37. unique_ptr<captions_handler> handler;
  38. LANGID lang_id = GetUserDefaultUILanguage();
  39. std::unordered_map<std::string, captions_handler_info &> handler_types;
  40. inline void register_handler(const char *id,
  41. captions_handler_info &info)
  42. {
  43. handler_types.emplace(id, info);
  44. }
  45. void start();
  46. void stop();
  47. obs_captions();
  48. inline ~obs_captions() { stop(); }
  49. };
  50. static obs_captions *captions = nullptr;
  51. /* ------------------------------------------------------------------------- */
  52. struct locale_info {
  53. DStr name;
  54. LANGID id;
  55. inline locale_info() {}
  56. inline locale_info(const locale_info &) = delete;
  57. inline locale_info(locale_info &&li)
  58. : name(std::move(li.name)), id(li.id)
  59. {
  60. }
  61. };
  62. static void get_valid_locale_names(vector<locale_info> &names);
  63. static bool valid_lang(LANGID id);
  64. /* ------------------------------------------------------------------------- */
  65. CaptionsDialog::CaptionsDialog(QWidget *parent)
  66. : QDialog(parent), ui(new Ui_CaptionsDialog)
  67. {
  68. ui->setupUi(this);
  69. setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
  70. auto cb = [this](obs_source_t *source) {
  71. uint32_t caps = obs_source_get_output_flags(source);
  72. QString name = obs_source_get_name(source);
  73. if (caps & OBS_SOURCE_AUDIO)
  74. ui->source->addItem(name);
  75. OBSWeakSource weak = OBSGetWeakRef(source);
  76. if (weak == captions->source)
  77. ui->source->setCurrentText(name);
  78. return true;
  79. };
  80. using cb_t = decltype(cb);
  81. ui->source->blockSignals(true);
  82. ui->source->addItem(QStringLiteral(""));
  83. ui->source->setCurrentIndex(0);
  84. obs_enum_sources(
  85. [](void *data, obs_source_t *source) {
  86. return (*static_cast<cb_t *>(data))(source);
  87. },
  88. &cb);
  89. ui->source->blockSignals(false);
  90. for (auto &ht : captions->handler_types) {
  91. QString name = ht.second.name().c_str();
  92. QString id = ht.first.c_str();
  93. ui->provider->addItem(name, id);
  94. }
  95. QString qhandler_id = captions->handler_id.c_str();
  96. int idx = ui->provider->findData(qhandler_id);
  97. if (idx != -1)
  98. ui->provider->setCurrentIndex(idx);
  99. ui->enable->blockSignals(true);
  100. ui->enable->setChecked(!!captions->handler);
  101. ui->enable->blockSignals(false);
  102. vector<locale_info> locales;
  103. get_valid_locale_names(locales);
  104. bool set_language = false;
  105. ui->language->blockSignals(true);
  106. for (int idx = 0; idx < (int)locales.size(); idx++) {
  107. locale_info &locale = locales[idx];
  108. ui->language->addItem(locale.name->array, (int)locale.id);
  109. if (locale.id == captions->lang_id) {
  110. ui->language->setCurrentIndex(idx);
  111. set_language = true;
  112. }
  113. }
  114. if (!set_language && locales.size())
  115. ui->language->setCurrentIndex(0);
  116. ui->language->blockSignals(false);
  117. if (!locales.size()) {
  118. ui->source->setEnabled(false);
  119. ui->enable->setEnabled(false);
  120. ui->language->setEnabled(false);
  121. } else if (!set_language) {
  122. bool started = !!captions->handler;
  123. if (started)
  124. captions->stop();
  125. captions->lang_id = locales[0].id;
  126. if (started)
  127. captions->start();
  128. }
  129. }
  130. void CaptionsDialog::on_source_currentIndexChanged(int)
  131. {
  132. bool started = !!captions->handler;
  133. if (started)
  134. captions->stop();
  135. captions->source_name = ui->source->currentText().toUtf8().constData();
  136. captions->source = GetWeakSourceByName(captions->source_name.c_str());
  137. if (started)
  138. captions->start();
  139. }
  140. void CaptionsDialog::on_enable_clicked(bool checked)
  141. {
  142. if (checked) {
  143. captions->start();
  144. if (!captions->handler) {
  145. ui->enable->blockSignals(true);
  146. ui->enable->setChecked(false);
  147. ui->enable->blockSignals(false);
  148. }
  149. } else {
  150. captions->stop();
  151. }
  152. }
  153. void CaptionsDialog::on_language_currentIndexChanged(int)
  154. {
  155. bool started = !!captions->handler;
  156. if (started)
  157. captions->stop();
  158. captions->lang_id = (LANGID)ui->language->currentData().toInt();
  159. if (started)
  160. captions->start();
  161. }
  162. void CaptionsDialog::on_provider_currentIndexChanged(int idx)
  163. {
  164. bool started = !!captions->handler;
  165. if (started)
  166. captions->stop();
  167. captions->handler_id =
  168. ui->provider->itemData(idx).toString().toUtf8().constData();
  169. if (started)
  170. captions->start();
  171. }
  172. /* ------------------------------------------------------------------------- */
  173. static void caption_text(const std::string &text)
  174. {
  175. OBSOutputAutoRelease output = obs_frontend_get_streaming_output();
  176. if (output) {
  177. obs_output_output_caption_text1(output, text.c_str());
  178. }
  179. }
  180. static void audio_capture(void *, obs_source_t *,
  181. const struct audio_data *audio, bool)
  182. {
  183. captions->handler->push_audio(audio);
  184. }
  185. void obs_captions::start()
  186. {
  187. if (!captions->handler && valid_lang(lang_id)) {
  188. wchar_t wname[256];
  189. auto pair = handler_types.find(handler_id);
  190. if (pair == handler_types.end()) {
  191. warn("Failed to find handler '%s'", handler_id.c_str());
  192. return;
  193. }
  194. if (!LCIDToLocaleName(lang_id, wname, 256, 0)) {
  195. warn("Failed to get locale name: %d",
  196. (int)GetLastError());
  197. return;
  198. }
  199. size_t len = (size_t)wcslen(wname);
  200. string lang_name;
  201. lang_name.resize(len);
  202. for (size_t i = 0; i < len; i++)
  203. lang_name[i] = (char)wname[i];
  204. OBSSource s = OBSGetStrongRef(source);
  205. if (!s) {
  206. warn("Source invalid");
  207. return;
  208. }
  209. try {
  210. captions_handler *h =
  211. pair->second.create(caption_text, lang_name);
  212. handler.reset(h);
  213. OBSSource s = OBSGetStrongRef(source);
  214. obs_source_add_audio_capture_callback(s, audio_capture,
  215. nullptr);
  216. } catch (std::string text) {
  217. QWidget *window =
  218. (QWidget *)obs_frontend_get_main_window();
  219. warn("Failed to create handler: %s", text.c_str());
  220. QMessageBox::warning(
  221. window,
  222. obs_module_text("Captions.Error.GenericFail"),
  223. text.c_str());
  224. }
  225. }
  226. }
  227. void obs_captions::stop()
  228. {
  229. OBSSource s = OBSGetStrongRef(source);
  230. if (s)
  231. obs_source_remove_audio_capture_callback(s, audio_capture,
  232. nullptr);
  233. handler.reset();
  234. }
  235. static bool get_locale_name(LANGID id, char *out)
  236. {
  237. wchar_t name[256];
  238. int size = GetLocaleInfoW(id, LOCALE_SENGLISHLANGUAGENAME, name, 256);
  239. if (size <= 0)
  240. return false;
  241. os_wcs_to_utf8(name, 0, out, 256);
  242. return true;
  243. }
  244. static bool valid_lang(LANGID id)
  245. {
  246. ComPtr<ISpObjectToken> token;
  247. wchar_t lang_str[32];
  248. HRESULT hr;
  249. _snwprintf(lang_str, 31, L"language=%x", (int)id);
  250. hr = SpFindBestToken(SPCAT_RECOGNIZERS, lang_str, nullptr, &token);
  251. return SUCCEEDED(hr);
  252. }
  253. static void get_valid_locale_names(vector<locale_info> &locales)
  254. {
  255. locale_info cur;
  256. char locale_name[256];
  257. static const LANGID default_locales[] = {
  258. 0x0409, 0x0401, 0x0402, 0x0403, 0x0404, 0x0405, 0x0406,
  259. 0x0407, 0x0408, 0x040a, 0x040b, 0x040c, 0x040d, 0x040e,
  260. 0x040f, 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415,
  261. 0x0416, 0x0417, 0x0418, 0x0419, 0x041a, 0};
  262. /* ---------------------------------- */
  263. LANGID def_id = GetUserDefaultUILanguage();
  264. LANGID id = def_id;
  265. if (valid_lang(id) && get_locale_name(id, locale_name)) {
  266. dstr_copy(cur.name,
  267. obs_module_text("Captions.CurrentSystemLanguage"));
  268. dstr_replace(cur.name, "%1", locale_name);
  269. cur.id = id;
  270. locales.push_back(std::move(cur));
  271. }
  272. /* ---------------------------------- */
  273. const LANGID *locale = default_locales;
  274. while (*locale) {
  275. id = *locale;
  276. if (id != def_id && valid_lang(id) &&
  277. get_locale_name(id, locale_name)) {
  278. dstr_copy(cur.name, locale_name);
  279. cur.id = id;
  280. locales.push_back(std::move(cur));
  281. }
  282. locale++;
  283. }
  284. }
  285. /* ------------------------------------------------------------------------- */
  286. extern captions_handler_info mssapi_info;
  287. obs_captions::obs_captions()
  288. {
  289. register_handler("mssapi", mssapi_info);
  290. }
  291. /* ------------------------------------------------------------------------- */
  292. extern "C" void FreeCaptions()
  293. {
  294. delete captions;
  295. captions = nullptr;
  296. }
  297. static void obs_event(enum obs_frontend_event event, void *)
  298. {
  299. if (event == OBS_FRONTEND_EVENT_EXIT)
  300. FreeCaptions();
  301. }
  302. static void save_caption_data(obs_data_t *save_data, bool saving, void *)
  303. {
  304. if (saving) {
  305. OBSDataAutoRelease obj = obs_data_create();
  306. obs_data_set_string(obj, "source",
  307. captions->source_name.c_str());
  308. obs_data_set_bool(obj, "enabled", !!captions->handler);
  309. obs_data_set_int(obj, "lang_id", captions->lang_id);
  310. obs_data_set_string(obj, "provider",
  311. captions->handler_id.c_str());
  312. obs_data_set_obj(save_data, "captions", obj);
  313. } else {
  314. captions->stop();
  315. OBSDataAutoRelease obj =
  316. obs_data_get_obj(save_data, "captions");
  317. if (!obj)
  318. obj = obs_data_create();
  319. obs_data_set_default_int(obj, "lang_id",
  320. GetUserDefaultUILanguage());
  321. obs_data_set_default_string(obj, "provider", DEFAULT_HANDLER);
  322. bool enabled = obs_data_get_bool(obj, "enabled");
  323. captions->source_name = obs_data_get_string(obj, "source");
  324. captions->lang_id = (int)obs_data_get_int(obj, "lang_id");
  325. captions->handler_id = obs_data_get_string(obj, "provider");
  326. captions->source =
  327. GetWeakSourceByName(captions->source_name.c_str());
  328. if (enabled)
  329. captions->start();
  330. }
  331. }
  332. extern "C" void InitCaptions()
  333. {
  334. QAction *action = (QAction *)obs_frontend_add_tools_menu_qaction(
  335. obs_module_text("Captions"));
  336. captions = new obs_captions;
  337. auto cb = []() {
  338. obs_frontend_push_ui_translation(obs_module_get_string);
  339. QWidget *window = (QWidget *)obs_frontend_get_main_window();
  340. CaptionsDialog dialog(window);
  341. dialog.exec();
  342. obs_frontend_pop_ui_translation();
  343. };
  344. obs_frontend_add_save_callback(save_caption_data, nullptr);
  345. obs_frontend_add_event_callback(obs_event, nullptr);
  346. action->connect(action, &QAction::triggered, cb);
  347. }