1
0

captions.cpp 10 KB

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