tts_windows.cpp 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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_requested = true;
  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::process_events() {
  60. if (update_requested && !paused && queue.size() > 0 && !is_speaking()) {
  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. update_requested = false;
  104. }
  105. }
  106. bool TTS_Windows::is_speaking() const {
  107. ERR_FAIL_NULL_V(synth, false);
  108. SPVOICESTATUS status;
  109. synth->GetStatus(&status, nullptr);
  110. return (status.dwRunningState == SPRS_IS_SPEAKING || status.dwRunningState == 0 /* Waiting To Speak */);
  111. }
  112. bool TTS_Windows::is_paused() const {
  113. ERR_FAIL_NULL_V(synth, false);
  114. return paused;
  115. }
  116. Array TTS_Windows::get_voices() const {
  117. Array list;
  118. IEnumSpObjectTokens *cpEnum;
  119. ISpObjectToken *cpVoiceToken;
  120. ISpDataKey *cpDataKeyAttribs;
  121. ULONG ulCount = 0;
  122. ISpObjectTokenCategory *cpCategory;
  123. HRESULT hr = CoCreateInstance(CLSID_SpObjectTokenCategory, nullptr, CLSCTX_INPROC_SERVER, IID_ISpObjectTokenCategory, (void **)&cpCategory);
  124. if (SUCCEEDED(hr)) {
  125. hr = cpCategory->SetId(SPCAT_VOICES, false);
  126. if (SUCCEEDED(hr)) {
  127. hr = cpCategory->EnumTokens(nullptr, nullptr, &cpEnum);
  128. if (SUCCEEDED(hr)) {
  129. hr = cpEnum->GetCount(&ulCount);
  130. while (SUCCEEDED(hr) && ulCount--) {
  131. hr = cpEnum->Next(1, &cpVoiceToken, nullptr);
  132. HRESULT hr_attr = cpVoiceToken->OpenKey(SPTOKENKEY_ATTRIBUTES, &cpDataKeyAttribs);
  133. if (SUCCEEDED(hr_attr)) {
  134. wchar_t *w_id = nullptr;
  135. wchar_t *w_lang = nullptr;
  136. wchar_t *w_name = nullptr;
  137. cpVoiceToken->GetId(&w_id);
  138. cpDataKeyAttribs->GetStringValue(L"Language", &w_lang);
  139. cpDataKeyAttribs->GetStringValue(nullptr, &w_name);
  140. LCID locale = wcstol(w_lang, nullptr, 16);
  141. int locale_chars = GetLocaleInfoW(locale, LOCALE_SISO639LANGNAME, nullptr, 0);
  142. int region_chars = GetLocaleInfoW(locale, LOCALE_SISO3166CTRYNAME, nullptr, 0);
  143. wchar_t *w_lang_code = new wchar_t[locale_chars];
  144. wchar_t *w_reg_code = new wchar_t[region_chars];
  145. GetLocaleInfoW(locale, LOCALE_SISO639LANGNAME, w_lang_code, locale_chars);
  146. GetLocaleInfoW(locale, LOCALE_SISO3166CTRYNAME, w_reg_code, region_chars);
  147. Dictionary voice_d;
  148. voice_d["id"] = String::utf16((const char16_t *)w_id);
  149. if (w_name) {
  150. voice_d["name"] = String::utf16((const char16_t *)w_name);
  151. } else {
  152. voice_d["name"] = voice_d["id"].operator String().replace("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\Voices\\Tokens\\", "");
  153. }
  154. voice_d["language"] = String::utf16((const char16_t *)w_lang_code) + "_" + String::utf16((const char16_t *)w_reg_code);
  155. list.push_back(voice_d);
  156. delete[] w_lang_code;
  157. delete[] w_reg_code;
  158. cpDataKeyAttribs->Release();
  159. }
  160. cpVoiceToken->Release();
  161. }
  162. cpEnum->Release();
  163. }
  164. }
  165. cpCategory->Release();
  166. }
  167. return list;
  168. }
  169. 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) {
  170. ERR_FAIL_NULL(synth);
  171. if (p_interrupt) {
  172. stop();
  173. }
  174. if (p_text.is_empty()) {
  175. DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, p_utterance_id);
  176. return;
  177. }
  178. DisplayServer::TTSUtterance message;
  179. message.text = p_text;
  180. message.voice = p_voice;
  181. message.volume = CLAMP(p_volume, 0, 100);
  182. message.pitch = CLAMP(p_pitch, 0.f, 2.f);
  183. message.rate = CLAMP(p_rate, 0.1f, 10.f);
  184. message.id = p_utterance_id;
  185. queue.push_back(message);
  186. if (is_paused()) {
  187. resume();
  188. } else {
  189. update_requested = true;
  190. }
  191. }
  192. void TTS_Windows::pause() {
  193. ERR_FAIL_NULL(synth);
  194. if (!paused) {
  195. if (synth->Pause() == S_OK) {
  196. paused = true;
  197. }
  198. }
  199. }
  200. void TTS_Windows::resume() {
  201. ERR_FAIL_NULL(synth);
  202. synth->Resume();
  203. paused = false;
  204. }
  205. void TTS_Windows::stop() {
  206. ERR_FAIL_NULL(synth);
  207. SPVOICESTATUS status;
  208. synth->GetStatus(&status, nullptr);
  209. uint32_t current_stream = (uint32_t)status.ulCurrentStream;
  210. if (ids.has(current_stream)) {
  211. DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, ids[current_stream].id);
  212. ids.erase(current_stream);
  213. }
  214. for (DisplayServer::TTSUtterance &message : queue) {
  215. DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServer::TTS_UTTERANCE_CANCELED, message.id);
  216. }
  217. queue.clear();
  218. synth->Speak(nullptr, SPF_PURGEBEFORESPEAK, nullptr);
  219. synth->Resume();
  220. paused = false;
  221. }
  222. TTS_Windows *TTS_Windows::get_singleton() {
  223. return singleton;
  224. }
  225. TTS_Windows::TTS_Windows() {
  226. singleton = this;
  227. if (SUCCEEDED(CoCreateInstance(CLSID_SpVoice, nullptr, CLSCTX_ALL, IID_ISpVoice, (void **)&synth))) {
  228. ULONGLONG event_mask = SPFEI(SPEI_END_INPUT_STREAM) | SPFEI(SPEI_START_INPUT_STREAM) | SPFEI(SPEI_WORD_BOUNDARY);
  229. synth->SetInterest(event_mask, event_mask);
  230. synth->SetNotifyCallbackFunction(&speech_event_callback, (WPARAM)(this), 0);
  231. print_verbose("Text-to-Speech: SAPI initialized.");
  232. } else {
  233. print_verbose("Text-to-Speech: Cannot initialize ISpVoice!");
  234. }
  235. }
  236. TTS_Windows::~TTS_Windows() {
  237. if (synth) {
  238. synth->Release();
  239. }
  240. singleton = nullptr;
  241. }