Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/platform/windows/tts_driver_sapi.cpp
46006 views
1
/**************************************************************************/
2
/* tts_driver_sapi.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
31
#include "tts_driver_sapi.h"
32
33
#include "core/object/callable_mp.h"
34
#include "servers/display/display_server.h"
35
36
TTSDriverSAPI *TTSDriverSAPI::singleton = nullptr;
37
38
void __stdcall TTSDriverSAPI::speech_event_callback(WPARAM wParam, LPARAM lParam) {
39
SPEVENT event;
40
while (singleton->synth->GetEvents(1, &event, nullptr) == S_OK) {
41
uint32_t stream_num = (uint32_t)event.ulStreamNum;
42
if (singleton->ids.has(stream_num)) {
43
if (event.eEventId == SPEI_START_INPUT_STREAM) {
44
DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServerEnums::TTS_UTTERANCE_STARTED, singleton->ids[stream_num].id);
45
} else if (event.eEventId == SPEI_END_INPUT_STREAM) {
46
DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServerEnums::TTS_UTTERANCE_ENDED, singleton->ids[stream_num].id);
47
singleton->ids.erase(stream_num);
48
singleton->update_requested = true;
49
} else if (event.eEventId == SPEI_WORD_BOUNDARY) {
50
const Char16String &string = singleton->ids[stream_num].string;
51
int pos = 0;
52
for (int i = 0; i < MIN(event.lParam, string.length()); i++) {
53
char16_t c = string[i];
54
if ((c & 0xfffffc00) == 0xd800) {
55
i++;
56
}
57
pos++;
58
}
59
DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServerEnums::TTS_UTTERANCE_BOUNDARY, singleton->ids[stream_num].id, pos - singleton->ids[stream_num].offset);
60
}
61
}
62
}
63
}
64
65
void TTSDriverSAPI::process_events() {
66
if (update_requested && !paused && queue.size() > 0 && !is_speaking()) {
67
TTSUtterance &message = queue.front()->get();
68
69
String text;
70
DWORD flags = SPF_ASYNC | SPF_PURGEBEFORESPEAK | SPF_IS_XML;
71
String pitch_tag = String("<pitch absmiddle=\"") + String::num_int64(message.pitch * 10 - 10, 10) + String("\">");
72
text = pitch_tag + message.text + String("</pitch>");
73
74
IEnumSpObjectTokens *cpEnum;
75
ISpObjectToken *cpVoiceToken;
76
ULONG ulCount = 0;
77
ULONG stream_number = 0;
78
ISpObjectTokenCategory *cpCategory;
79
HRESULT hr = CoCreateInstance(CLSID_SpObjectTokenCategory, nullptr, CLSCTX_INPROC_SERVER, IID_ISpObjectTokenCategory, (void **)&cpCategory);
80
if (SUCCEEDED(hr)) {
81
hr = cpCategory->SetId(SPCAT_VOICES, false);
82
if (SUCCEEDED(hr)) {
83
hr = cpCategory->EnumTokens(nullptr, nullptr, &cpEnum);
84
if (SUCCEEDED(hr)) {
85
hr = cpEnum->GetCount(&ulCount);
86
while (SUCCEEDED(hr) && ulCount--) {
87
wchar_t *w_id = nullptr;
88
hr = cpEnum->Next(1, &cpVoiceToken, nullptr);
89
cpVoiceToken->GetId(&w_id);
90
if (String::utf16((const char16_t *)w_id) == message.voice) {
91
synth->SetVoice(cpVoiceToken);
92
cpVoiceToken->Release();
93
break;
94
}
95
cpVoiceToken->Release();
96
}
97
cpEnum->Release();
98
}
99
}
100
cpCategory->Release();
101
}
102
103
UTData ut;
104
ut.string = text.utf16();
105
ut.offset = pitch_tag.length(); // Subtract injected <pitch> tag offset.
106
ut.id = message.id;
107
108
synth->SetVolume(message.volume);
109
synth->SetRate(10.f * std::log10(message.rate) / std::log10(3.f));
110
synth->Speak((LPCWSTR)ut.string.get_data(), flags, &stream_number);
111
112
ids[(uint32_t)stream_number] = ut;
113
114
queue.pop_front();
115
116
update_requested = false;
117
}
118
}
119
120
bool TTSDriverSAPI::is_speaking() const {
121
ERR_FAIL_NULL_V(synth, false);
122
123
SPVOICESTATUS status;
124
synth->GetStatus(&status, nullptr);
125
return (status.dwRunningState == SPRS_IS_SPEAKING || status.dwRunningState == 0 /* Waiting To Speak */);
126
}
127
128
bool TTSDriverSAPI::is_paused() const {
129
ERR_FAIL_NULL_V(synth, false);
130
return paused;
131
}
132
133
Array TTSDriverSAPI::get_voices() const {
134
Array list;
135
IEnumSpObjectTokens *cpEnum;
136
ISpObjectToken *cpVoiceToken;
137
ISpDataKey *cpDataKeyAttribs;
138
ULONG ulCount = 0;
139
ISpObjectTokenCategory *cpCategory;
140
HRESULT hr = CoCreateInstance(CLSID_SpObjectTokenCategory, nullptr, CLSCTX_INPROC_SERVER, IID_ISpObjectTokenCategory, (void **)&cpCategory);
141
if (SUCCEEDED(hr)) {
142
hr = cpCategory->SetId(SPCAT_VOICES, false);
143
if (SUCCEEDED(hr)) {
144
hr = cpCategory->EnumTokens(nullptr, nullptr, &cpEnum);
145
if (SUCCEEDED(hr)) {
146
hr = cpEnum->GetCount(&ulCount);
147
while (SUCCEEDED(hr) && ulCount--) {
148
hr = cpEnum->Next(1, &cpVoiceToken, nullptr);
149
HRESULT hr_attr = cpVoiceToken->OpenKey(SPTOKENKEY_ATTRIBUTES, &cpDataKeyAttribs);
150
if (SUCCEEDED(hr_attr)) {
151
wchar_t *w_id = nullptr;
152
wchar_t *w_lang = nullptr;
153
wchar_t *w_name = nullptr;
154
cpVoiceToken->GetId(&w_id);
155
cpDataKeyAttribs->GetStringValue(L"Language", &w_lang);
156
cpDataKeyAttribs->GetStringValue(nullptr, &w_name);
157
LCID locale = wcstol(w_lang, nullptr, 16);
158
159
int locale_chars = GetLocaleInfoW(locale, LOCALE_SISO639LANGNAME, nullptr, 0);
160
int region_chars = GetLocaleInfoW(locale, LOCALE_SISO3166CTRYNAME, nullptr, 0);
161
wchar_t *w_lang_code = new wchar_t[locale_chars];
162
wchar_t *w_reg_code = new wchar_t[region_chars];
163
GetLocaleInfoW(locale, LOCALE_SISO639LANGNAME, w_lang_code, locale_chars);
164
GetLocaleInfoW(locale, LOCALE_SISO3166CTRYNAME, w_reg_code, region_chars);
165
166
Dictionary voice_d;
167
voice_d["id"] = String::utf16((const char16_t *)w_id);
168
if (w_name) {
169
voice_d["name"] = String::utf16((const char16_t *)w_name);
170
} else {
171
voice_d["name"] = voice_d["id"].operator String().replace("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\Voices\\Tokens\\", "");
172
}
173
voice_d["language"] = String::utf16((const char16_t *)w_lang_code) + "_" + String::utf16((const char16_t *)w_reg_code);
174
list.push_back(voice_d);
175
176
delete[] w_lang_code;
177
delete[] w_reg_code;
178
179
cpDataKeyAttribs->Release();
180
}
181
cpVoiceToken->Release();
182
}
183
cpEnum->Release();
184
}
185
}
186
cpCategory->Release();
187
}
188
return list;
189
}
190
191
void TTSDriverSAPI::speak(const String &p_text, const String &p_voice, int p_volume, float p_pitch, float p_rate, int64_t p_utterance_id, bool p_interrupt) {
192
ERR_FAIL_NULL(synth);
193
if (p_interrupt) {
194
stop();
195
}
196
197
if (p_text.is_empty()) {
198
DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServerEnums::TTS_UTTERANCE_CANCELED, p_utterance_id);
199
return;
200
}
201
202
TTSUtterance message;
203
message.text = p_text;
204
message.voice = p_voice;
205
message.volume = CLAMP(p_volume, 0, 100);
206
message.pitch = CLAMP(p_pitch, 0.f, 2.f);
207
message.rate = CLAMP(p_rate, 0.1f, 10.f);
208
message.id = p_utterance_id;
209
queue.push_back(message);
210
211
if (is_paused()) {
212
resume();
213
} else {
214
update_requested = true;
215
}
216
}
217
218
void TTSDriverSAPI::pause() {
219
ERR_FAIL_NULL(synth);
220
if (!paused) {
221
if (synth->Pause() == S_OK) {
222
paused = true;
223
}
224
}
225
}
226
227
void TTSDriverSAPI::resume() {
228
ERR_FAIL_NULL(synth);
229
synth->Resume();
230
paused = false;
231
}
232
233
void TTSDriverSAPI::stop() {
234
ERR_FAIL_NULL(synth);
235
236
SPVOICESTATUS status;
237
synth->GetStatus(&status, nullptr);
238
uint32_t current_stream = (uint32_t)status.ulCurrentStream;
239
if (ids.has(current_stream)) {
240
DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServerEnums::TTS_UTTERANCE_CANCELED, ids[current_stream].id);
241
ids.erase(current_stream);
242
}
243
for (TTSUtterance &message : queue) {
244
DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServerEnums::TTS_UTTERANCE_CANCELED, message.id);
245
}
246
queue.clear();
247
synth->Speak(nullptr, SPF_PURGEBEFORESPEAK, nullptr);
248
synth->Resume();
249
paused = false;
250
}
251
252
bool TTSDriverSAPI::init() {
253
if (SUCCEEDED(CoCreateInstance(CLSID_SpVoice, nullptr, CLSCTX_ALL, IID_ISpVoice, (void **)&synth))) {
254
ULONGLONG event_mask = SPFEI(SPEI_END_INPUT_STREAM) | SPFEI(SPEI_START_INPUT_STREAM) | SPFEI(SPEI_WORD_BOUNDARY);
255
synth->SetInterest(event_mask, event_mask);
256
synth->SetNotifyCallbackFunction(&speech_event_callback, (WPARAM)(this), 0);
257
print_verbose("Text-to-Speech: SAPI initialized.");
258
return true;
259
} else {
260
print_verbose("Text-to-Speech: Cannot initialize SAPI driver!");
261
return false;
262
}
263
}
264
265
TTSDriverSAPI::TTSDriverSAPI() {
266
singleton = this;
267
}
268
269
TTSDriverSAPI::~TTSDriverSAPI() {
270
if (synth) {
271
synth->Release();
272
}
273
singleton = nullptr;
274
}
275
276