captions.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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, ...) blog(type, "[Captions] " format, \
  28. ##__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. 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),
  67. ui(new Ui_CaptionsDialog)
  68. {
  69. ui->setupUi(this);
  70. setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
  71. auto cb = [this] (obs_source_t *source)
  72. {
  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([] (void *data, obs_source_t *source) {
  87. return (*static_cast<cb_t*>(data))(source);}, &cb);
  88. ui->source->blockSignals(false);
  89. for (auto &ht : captions->handler_types) {
  90. QString name = ht.second.name().c_str();
  91. QString id = ht.first.c_str();
  92. ui->provider->addItem(name, id);
  93. }
  94. QString qhandler_id = captions->handler_id.c_str();
  95. int idx = ui->provider->findData(qhandler_id);
  96. if (idx != -1)
  97. ui->provider->setCurrentIndex(idx);
  98. ui->enable->blockSignals(true);
  99. ui->enable->setChecked(!!captions->handler);
  100. ui->enable->blockSignals(false);
  101. vector<locale_info> locales;
  102. get_valid_locale_names(locales);
  103. bool set_language = false;
  104. ui->language->blockSignals(true);
  105. for (int idx = 0; idx < (int)locales.size(); idx++) {
  106. locale_info &locale = locales[idx];
  107. ui->language->addItem(locale.name->array, (int)locale.id);
  108. if (locale.id == captions->lang_id) {
  109. ui->language->setCurrentIndex(idx);
  110. set_language = true;
  111. }
  112. }
  113. if (!set_language && locales.size())
  114. ui->language->setCurrentIndex(0);
  115. ui->language->blockSignals(false);
  116. if (!locales.size()) {
  117. ui->source->setEnabled(false);
  118. ui->enable->setEnabled(false);
  119. ui->language->setEnabled(false);
  120. } else if (!set_language) {
  121. bool started = !!captions->handler;
  122. if (started)
  123. captions->stop();
  124. captions->lang_id = locales[0].id;
  125. if (started)
  126. captions->start();
  127. }
  128. }
  129. void CaptionsDialog::on_source_currentIndexChanged(int)
  130. {
  131. bool started = !!captions->handler;
  132. if (started)
  133. captions->stop();
  134. captions->source_name = ui->source->currentText().toUtf8().constData();
  135. captions->source = GetWeakSourceByName(captions->source_name.c_str());
  136. if (started)
  137. captions->start();
  138. }
  139. void CaptionsDialog::on_enable_clicked(bool checked)
  140. {
  141. if (checked) {
  142. captions->start();
  143. if (!captions->handler) {
  144. ui->enable->blockSignals(true);
  145. ui->enable->setChecked(false);
  146. ui->enable->blockSignals(false);
  147. }
  148. } else {
  149. captions->stop();
  150. }
  151. }
  152. void CaptionsDialog::on_language_currentIndexChanged(int)
  153. {
  154. bool started = !!captions->handler;
  155. if (started)
  156. captions->stop();
  157. captions->lang_id = (LANGID)ui->language->currentData().toInt();
  158. if (started)
  159. captions->start();
  160. }
  161. void CaptionsDialog::on_provider_currentIndexChanged(int idx)
  162. {
  163. bool started = !!captions->handler;
  164. if (started)
  165. captions->stop();
  166. captions->handler_id =
  167. ui->provider->itemData(idx).toString().toUtf8().constData();
  168. if (started)
  169. captions->start();
  170. }
  171. /* ------------------------------------------------------------------------- */
  172. static void caption_text(const std::string &text)
  173. {
  174. obs_output *output = obs_frontend_get_streaming_output();
  175. if (output) {
  176. obs_output_output_caption_text1(output, text.c_str());
  177. obs_output_release(output);
  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'",
  192. handler_id.c_str());
  193. return;
  194. }
  195. if (!LCIDToLocaleName(lang_id, wname, 256, 0)) {
  196. warn("Failed to get locale name: %d",
  197. (int)GetLastError());
  198. return;
  199. }
  200. size_t len = (size_t)wcslen(wname);
  201. string lang_name;
  202. lang_name.resize(len);
  203. for (size_t i = 0; i < len; i++)
  204. lang_name[i] = (char)wname[i];
  205. OBSSource s = OBSGetStrongRef(source);
  206. if (!s) {
  207. warn("Source invalid");
  208. return;
  209. }
  210. try {
  211. captions_handler *h = pair->second.create(caption_text,
  212. lang_name);
  213. handler.reset(h);
  214. OBSSource s = OBSGetStrongRef(source);
  215. obs_source_add_audio_capture_callback(s,
  216. audio_capture, nullptr);
  217. } catch (std::string text) {
  218. QWidget *window =
  219. (QWidget*)obs_frontend_get_main_window();
  220. warn("Failed to create handler: %s", text.c_str());
  221. QMessageBox::warning(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,
  232. audio_capture, 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,
  259. 0x0401,
  260. 0x0402,
  261. 0x0403,
  262. 0x0404,
  263. 0x0405,
  264. 0x0406,
  265. 0x0407,
  266. 0x0408,
  267. 0x040a,
  268. 0x040b,
  269. 0x040c,
  270. 0x040d,
  271. 0x040e,
  272. 0x040f,
  273. 0x0410,
  274. 0x0411,
  275. 0x0412,
  276. 0x0413,
  277. 0x0414,
  278. 0x0415,
  279. 0x0416,
  280. 0x0417,
  281. 0x0418,
  282. 0x0419,
  283. 0x041a,
  284. 0
  285. };
  286. /* ---------------------------------- */
  287. LANGID def_id = GetUserDefaultUILanguage();
  288. LANGID id = def_id;
  289. if (valid_lang(id) && get_locale_name(id, locale_name)) {
  290. dstr_copy(cur.name, obs_module_text(
  291. "Captions.CurrentSystemLanguage"));
  292. dstr_replace(cur.name, "%1", locale_name);
  293. cur.id = id;
  294. locales.push_back(std::move(cur));
  295. }
  296. /* ---------------------------------- */
  297. const LANGID *locale = default_locales;
  298. while (*locale) {
  299. id = *locale;
  300. if (id != def_id &&
  301. valid_lang(id) &&
  302. get_locale_name(id, locale_name)) {
  303. dstr_copy(cur.name, locale_name);
  304. cur.id = id;
  305. locales.push_back(std::move(cur));
  306. }
  307. locale++;
  308. }
  309. }
  310. /* ------------------------------------------------------------------------- */
  311. extern captions_handler_info mssapi_info;
  312. obs_captions::obs_captions()
  313. {
  314. register_handler("mssapi", mssapi_info);
  315. }
  316. /* ------------------------------------------------------------------------- */
  317. extern "C" void FreeCaptions()
  318. {
  319. delete captions;
  320. captions = nullptr;
  321. }
  322. static void obs_event(enum obs_frontend_event event, void *)
  323. {
  324. if (event == OBS_FRONTEND_EVENT_EXIT)
  325. FreeCaptions();
  326. }
  327. static void save_caption_data(obs_data_t *save_data, bool saving, void*)
  328. {
  329. if (saving) {
  330. obs_data_t *obj = obs_data_create();
  331. obs_data_set_string(obj, "source",
  332. captions->source_name.c_str());
  333. obs_data_set_bool(obj, "enabled", !!captions->handler);
  334. obs_data_set_int(obj, "lang_id", captions->lang_id);
  335. obs_data_set_string(obj, "provider",
  336. captions->handler_id.c_str());
  337. obs_data_set_obj(save_data, "captions", obj);
  338. obs_data_release(obj);
  339. } else {
  340. captions->stop();
  341. obs_data_t *obj = obs_data_get_obj(save_data, "captions");
  342. if (!obj)
  343. obj = obs_data_create();
  344. obs_data_set_default_int(obj, "lang_id",
  345. GetUserDefaultUILanguage());
  346. obs_data_set_default_string(obj, "provider", DEFAULT_HANDLER);
  347. bool enabled = obs_data_get_bool(obj, "enabled");
  348. captions->source_name = obs_data_get_string(obj, "source");
  349. captions->lang_id = (int)obs_data_get_int(obj, "lang_id");
  350. captions->handler_id = obs_data_get_string(obj, "provider");
  351. captions->source = GetWeakSourceByName(
  352. captions->source_name.c_str());
  353. obs_data_release(obj);
  354. if (enabled)
  355. captions->start();
  356. }
  357. }
  358. extern "C" void InitCaptions()
  359. {
  360. QAction *action = (QAction*)obs_frontend_add_tools_menu_qaction(
  361. obs_module_text("Captions"));
  362. captions = new obs_captions;
  363. auto cb = [] ()
  364. {
  365. obs_frontend_push_ui_translation(obs_module_get_string);
  366. QWidget *window =
  367. (QWidget*)obs_frontend_get_main_window();
  368. CaptionsDialog dialog(window);
  369. dialog.exec();
  370. obs_frontend_pop_ui_translation();
  371. };
  372. obs_frontend_add_save_callback(save_caption_data, nullptr);
  373. obs_frontend_add_event_callback(obs_event, nullptr);
  374. action->connect(action, &QAction::triggered, cb);
  375. }