tts_windows.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. /**************************************************************************/
  2. /* tts_windows.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "tts_windows.h"
  31. TTS_Windows *TTS_Windows::singleton = nullptr;
  32. void __stdcall TTS_Windows::speech_event_callback(WPARAM wParam, LPARAM lParam) {
  33. TTS_Windows *tts = TTS_Windows::get_singleton();
  34. SPEVENT event;
  35. while (tts->synth->GetEvents(1, &event, nullptr) == S_OK) {
  36. uint32_t stream_num = (uint32_t)event.ulStreamNum;
  37. if (tts->ids.has(stream_num)) {
  38. if (event.eEventId == SPEI_START_INPUT_STREAM) {
  39. DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_STARTED, tts->ids[stream_num].id);
  40. } else if (event.eEventId == SPEI_END_INPUT_STREAM) {
  41. DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_ENDED, tts->ids[stream_num].id);
  42. tts->ids.erase(stream_num);
  43. tts->_update_tts();
  44. } else if (event.eEventId == SPEI_WORD_BOUNDARY) {
  45. const Char16String &string = tts->ids[stream_num].string;
  46. int pos = 0;
  47. for (int i = 0; i < MIN(event.lParam, string.length()); i++) {
  48. char16_t c = string[i];
  49. if ((c & 0xfffffc00) == 0xd800) {
  50. i++;
  51. }
  52. pos++;
  53. }
  54. DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_BOUNDARY, tts->ids[stream_num].id, pos - tts->ids[stream_num].offset);
  55. }
  56. }
  57. }
  58. }
  59. void TTS_Windows::_update_tts() {
  60. if (!is_speaking() && !paused && queue.size() > 0) {
  61. DisplayServer::TTSUtterance &message = queue.front()->get();
  62. String text;
  63. DWORD flags = SPF_ASYNC | SPF_PURGEBEFORESPEAK | SPF_IS_XML;
  64. String pitch_tag = String("<pitch absmiddle=\"") + String::num_int64(message.pitch * 10 - 10, 10) + String("\">");
  65. text = pitch_tag + message.text + String("</pitch>");
  66. IEnumSpObjectTokens *cpEnum;
  67. ISpObjectToken *cpVoiceToken;
  68. ULONG ulCount = 0;
  69. ULONG stream_number = 0;
  70. ISpObjectTokenCategory *cpCategory;
  71. HRESULT hr = CoCreateInstance(CLSID_SpObjectTokenCategory, nullptr, CLSCTX_INPROC_SERVER, IID_ISpObjectTokenCategory, (void **)&cpCategory);
  72. if (SUCCEEDED(hr)) {
  73. hr = cpCategory->SetId(SPCAT_VOICES, false);
  74. if (SUCCEEDED(hr)) {
  75. hr = cpCategory->EnumTokens(nullptr, nullptr, &cpEnum);
  76. if (SUCCEEDED(hr)) {
  77. hr = cpEnum->GetCount(&ulCount);
  78. while (SUCCEEDED(hr) && ulCount--) {
  79. wchar_t *w_id = nullptr;
  80. hr = cpEnum->Next(1, &cpVoiceToken, nullptr);
  81. cpVoiceToken->GetId(&w_id);
  82. if (String::utf16((const char16_t *)w_id) == message.voice) {
  83. synth->SetVoice(cpVoiceToken);
  84. cpVoiceToken->Release();
  85. break;
  86. }
  87. cpVoiceToken->Release();
  88. }
  89. cpEnum->Release();
  90. }
  91. }
  92. cpCategory->Release();
  93. }
  94. UTData ut;
  95. ut.string = text.utf16();
  96. ut.offset = pitch_tag.length(); // Subtract injected <pitch> tag offset.
  97. ut.id = message.id;
  98. synth->SetVolume(message.volume);
  99. synth->SetRate(10.f * log10(message.rate) / log10(3.f));
  100. synth->Speak((LPCWSTR)ut.string.get_data(), flags, &stream_number);
  101. ids[(uint32_t)stream_number] = ut;
  102. queue.pop_front();
  103. }
  104. }
  105. bool TTS_Windows::is_speaking() const {
  106. ERR_FAIL_NULL_V(synth, false);
  107. SPVOICESTATUS status;
  108. synth->GetStatus(&status, nullptr);
  109. return (status.dwRunningState == SPRS_IS_SPEAKING || status.dwRunningState == 0 /* Waiting To Speak */);
  110. }
  111. bool TTS_Windows::is_paused() const {
  112. ERR_FAIL_NULL_V(synth, false);
  113. return paused;
  114. }
  115. Array TTS_Windows::get_voices() const {
  116. Array list;
  117. IEnumSpObjectTokens *cpEnum;
  118. ISpObjectToken *cpVoiceToken;
  119. ISpDataKey *cpDataKeyAttribs;
  120. ULONG ulCount = 0;
  121. ISpObjectTokenCategory *cpCategory;
  122. HRESULT hr = CoCreateInstance(CLSID_SpObjectTokenCategory, nullptr, CLSCTX_INPROC_SERVER, IID_ISpObjectTokenCategory, (void **)&cpCategory);
  123. if (SUCCEEDED(hr)) {
  124. hr = cpCategory->SetId(SPCAT_VOICES, false);
  125. if (SUCCEEDED(hr)) {
  126. hr = cpCategory->EnumTokens(nullptr, nullptr, &cpEnum);
  127. if (SUCCEEDED(hr)) {
  128. hr = cpEnum->GetCount(&ulCount);
  129. while (SUCCEEDED(hr) && ulCount--) {
  130. hr = cpEnum->Next(1, &cpVoiceToken, nullptr);
  131. HRESULT hr_attr = cpVoiceToken->OpenKey(SPTOKENKEY_ATTRIBUTES, &cpDataKeyAttribs);
  132. if (SUCCEEDED(hr_attr)) {
  133. wchar_t *w_id = nullptr;
  134. wchar_t *w_lang = nullptr;
  135. wchar_t *w_name = nullptr;
  136. cpVoiceToken->GetId(&w_id);
  137. cpDataKeyAttribs->GetStringValue(L"Language", &w_lang);
  138. cpDataKeyAttribs->GetStringValue(nullptr, &w_name);
  139. LCID locale = wcstol(w_lang, nullptr, 16);
  140. int locale_chars = GetLocaleInfoW(locale, LOCALE_SISO639LANGNAME, nullptr, 0);
  141. int region_chars = GetLocaleInfoW(locale, LOCALE_SISO3166CTRYNAME, nullptr, 0);
  142. wchar_t *w_lang_code = new wchar_t[locale_chars];
  143. wchar_t *w_reg_code = new wchar_t[region_chars];
  144. GetLocaleInfoW(locale, LOCALE_SISO639LANGNAME, w_lang_code, locale_chars);
  145. GetLocaleInfoW(locale, LOCALE_SISO3166CTRYNAME, w_reg_code, region_chars);
  146. Dictionary voice_d;
  147. voice_d["id"] = String::utf16((const char16_t *)w_id);
  148. if (w_name) {
  149. voice_d["name"] = String::utf16((const char16_t *)w_name);
  150. } else {
  151. voice_d["name"] = voice_d["id"].operator String().replace("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\Voices\\Tokens\\", "");
  152. }
  153. voice_d["language"] = String::utf16((const char16_t *)w_lang_code) + "_" + String::utf16((const char16_t *)w_reg_code);
  154. list.push_back(voice_d);
  155. delete[] w_lang_code;
  156. delete[] w_reg_code;
  157. cpDataKeyAttribs->Release();
  158. }
  159. cpVoiceToken->Release();
  160. }
  161. cpEnum->Release();
  162. }
  163. }
  164. cpCategory->Release();
  165. }
  166. return list;
  167. }
  168. void TTS_Windows::speak(const String &p_text, const String &p_voice, int p_volume, float p_pitch, float p_rate, int p_utterance_id, bool p_interrupt) {
  169. ERR_FAIL_NULL(synth);
  170. if (p_interrupt) {
  171. stop();
  172. }
  173. if (p_text.is_empty()) {
  174. DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, p_utterance_id);
  175. return;
  176. }
  177. DisplayServer::TTSUtterance message;
  178. message.text = p_text;
  179. message.voice = p_voice;
  180. message.volume = CLAMP(p_volume, 0, 100);
  181. message.pitch = CLAMP(p_pitch, 0.f, 2.f);
  182. message.rate = CLAMP(p_rate, 0.1f, 10.f);
  183. message.id = p_utterance_id;
  184. queue.push_back(message);
  185. if (is_paused()) {
  186. resume();
  187. } else {
  188. _update_tts();
  189. }
  190. }
  191. void TTS_Windows::pause() {
  192. ERR_FAIL_NULL(synth);
  193. if (!paused) {
  194. if (synth->Pause() == S_OK) {
  195. paused = true;
  196. }
  197. }
  198. }
  199. void TTS_Windows::resume() {
  200. ERR_FAIL_NULL(synth);
  201. synth->Resume();
  202. paused = false;
  203. }
  204. void TTS_Windows::stop() {
  205. ERR_FAIL_NULL(synth);
  206. SPVOICESTATUS status;
  207. synth->GetStatus(&status, nullptr);
  208. uint32_t current_stream = (uint32_t)status.ulCurrentStream;
  209. if (ids.has(current_stream)) {
  210. DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, ids[current_stream].id);
  211. ids.erase(current_stream);
  212. }
  213. for (DisplayServer::TTSUtterance &message : queue) {
  214. DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, message.id);
  215. }
  216. queue.clear();
  217. synth->Speak(nullptr, SPF_PURGEBEFORESPEAK, nullptr);
  218. synth->Resume();
  219. paused = false;
  220. }
  221. TTS_Windows *TTS_Windows::get_singleton() {
  222. return singleton;
  223. }
  224. TTS_Windows::TTS_Windows() {
  225. singleton = this;
  226. if (SUCCEEDED(CoCreateInstance(CLSID_SpVoice, nullptr, CLSCTX_ALL, IID_ISpVoice, (void **)&synth))) {
  227. ULONGLONG event_mask = SPFEI(SPEI_END_INPUT_STREAM) | SPFEI(SPEI_START_INPUT_STREAM) | SPFEI(SPEI_WORD_BOUNDARY);
  228. synth->SetInterest(event_mask, event_mask);
  229. synth->SetNotifyCallbackFunction(&speech_event_callback, (WPARAM)(this), 0);
  230. print_verbose("Text-to-Speech: SAPI initialized.");
  231. } else {
  232. print_verbose("Text-to-Speech: Cannot initialize ISpVoice!");
  233. }
  234. }
  235. TTS_Windows::~TTS_Windows() {
  236. if (synth) {
  237. synth->Release();
  238. }
  239. singleton = nullptr;
  240. }