captions.cpp 10 KB

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