Path: blob/master/platform/windows/tts_driver_sapi.cpp
46006 views
/**************************************************************************/1/* tts_driver_sapi.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "tts_driver_sapi.h"3132#include "core/object/callable_mp.h"33#include "servers/display/display_server.h"3435TTSDriverSAPI *TTSDriverSAPI::singleton = nullptr;3637void __stdcall TTSDriverSAPI::speech_event_callback(WPARAM wParam, LPARAM lParam) {38SPEVENT event;39while (singleton->synth->GetEvents(1, &event, nullptr) == S_OK) {40uint32_t stream_num = (uint32_t)event.ulStreamNum;41if (singleton->ids.has(stream_num)) {42if (event.eEventId == SPEI_START_INPUT_STREAM) {43DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServerEnums::TTS_UTTERANCE_STARTED, singleton->ids[stream_num].id);44} else if (event.eEventId == SPEI_END_INPUT_STREAM) {45DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServerEnums::TTS_UTTERANCE_ENDED, singleton->ids[stream_num].id);46singleton->ids.erase(stream_num);47singleton->update_requested = true;48} else if (event.eEventId == SPEI_WORD_BOUNDARY) {49const Char16String &string = singleton->ids[stream_num].string;50int pos = 0;51for (int i = 0; i < MIN(event.lParam, string.length()); i++) {52char16_t c = string[i];53if ((c & 0xfffffc00) == 0xd800) {54i++;55}56pos++;57}58DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServerEnums::TTS_UTTERANCE_BOUNDARY, singleton->ids[stream_num].id, pos - singleton->ids[stream_num].offset);59}60}61}62}6364void TTSDriverSAPI::process_events() {65if (update_requested && !paused && queue.size() > 0 && !is_speaking()) {66TTSUtterance &message = queue.front()->get();6768String text;69DWORD flags = SPF_ASYNC | SPF_PURGEBEFORESPEAK | SPF_IS_XML;70String pitch_tag = String("<pitch absmiddle=\"") + String::num_int64(message.pitch * 10 - 10, 10) + String("\">");71text = pitch_tag + message.text + String("</pitch>");7273IEnumSpObjectTokens *cpEnum;74ISpObjectToken *cpVoiceToken;75ULONG ulCount = 0;76ULONG stream_number = 0;77ISpObjectTokenCategory *cpCategory;78HRESULT hr = CoCreateInstance(CLSID_SpObjectTokenCategory, nullptr, CLSCTX_INPROC_SERVER, IID_ISpObjectTokenCategory, (void **)&cpCategory);79if (SUCCEEDED(hr)) {80hr = cpCategory->SetId(SPCAT_VOICES, false);81if (SUCCEEDED(hr)) {82hr = cpCategory->EnumTokens(nullptr, nullptr, &cpEnum);83if (SUCCEEDED(hr)) {84hr = cpEnum->GetCount(&ulCount);85while (SUCCEEDED(hr) && ulCount--) {86wchar_t *w_id = nullptr;87hr = cpEnum->Next(1, &cpVoiceToken, nullptr);88cpVoiceToken->GetId(&w_id);89if (String::utf16((const char16_t *)w_id) == message.voice) {90synth->SetVoice(cpVoiceToken);91cpVoiceToken->Release();92break;93}94cpVoiceToken->Release();95}96cpEnum->Release();97}98}99cpCategory->Release();100}101102UTData ut;103ut.string = text.utf16();104ut.offset = pitch_tag.length(); // Subtract injected <pitch> tag offset.105ut.id = message.id;106107synth->SetVolume(message.volume);108synth->SetRate(10.f * std::log10(message.rate) / std::log10(3.f));109synth->Speak((LPCWSTR)ut.string.get_data(), flags, &stream_number);110111ids[(uint32_t)stream_number] = ut;112113queue.pop_front();114115update_requested = false;116}117}118119bool TTSDriverSAPI::is_speaking() const {120ERR_FAIL_NULL_V(synth, false);121122SPVOICESTATUS status;123synth->GetStatus(&status, nullptr);124return (status.dwRunningState == SPRS_IS_SPEAKING || status.dwRunningState == 0 /* Waiting To Speak */);125}126127bool TTSDriverSAPI::is_paused() const {128ERR_FAIL_NULL_V(synth, false);129return paused;130}131132Array TTSDriverSAPI::get_voices() const {133Array list;134IEnumSpObjectTokens *cpEnum;135ISpObjectToken *cpVoiceToken;136ISpDataKey *cpDataKeyAttribs;137ULONG ulCount = 0;138ISpObjectTokenCategory *cpCategory;139HRESULT hr = CoCreateInstance(CLSID_SpObjectTokenCategory, nullptr, CLSCTX_INPROC_SERVER, IID_ISpObjectTokenCategory, (void **)&cpCategory);140if (SUCCEEDED(hr)) {141hr = cpCategory->SetId(SPCAT_VOICES, false);142if (SUCCEEDED(hr)) {143hr = cpCategory->EnumTokens(nullptr, nullptr, &cpEnum);144if (SUCCEEDED(hr)) {145hr = cpEnum->GetCount(&ulCount);146while (SUCCEEDED(hr) && ulCount--) {147hr = cpEnum->Next(1, &cpVoiceToken, nullptr);148HRESULT hr_attr = cpVoiceToken->OpenKey(SPTOKENKEY_ATTRIBUTES, &cpDataKeyAttribs);149if (SUCCEEDED(hr_attr)) {150wchar_t *w_id = nullptr;151wchar_t *w_lang = nullptr;152wchar_t *w_name = nullptr;153cpVoiceToken->GetId(&w_id);154cpDataKeyAttribs->GetStringValue(L"Language", &w_lang);155cpDataKeyAttribs->GetStringValue(nullptr, &w_name);156LCID locale = wcstol(w_lang, nullptr, 16);157158int locale_chars = GetLocaleInfoW(locale, LOCALE_SISO639LANGNAME, nullptr, 0);159int region_chars = GetLocaleInfoW(locale, LOCALE_SISO3166CTRYNAME, nullptr, 0);160wchar_t *w_lang_code = new wchar_t[locale_chars];161wchar_t *w_reg_code = new wchar_t[region_chars];162GetLocaleInfoW(locale, LOCALE_SISO639LANGNAME, w_lang_code, locale_chars);163GetLocaleInfoW(locale, LOCALE_SISO3166CTRYNAME, w_reg_code, region_chars);164165Dictionary voice_d;166voice_d["id"] = String::utf16((const char16_t *)w_id);167if (w_name) {168voice_d["name"] = String::utf16((const char16_t *)w_name);169} else {170voice_d["name"] = voice_d["id"].operator String().replace("HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech\\Voices\\Tokens\\", "");171}172voice_d["language"] = String::utf16((const char16_t *)w_lang_code) + "_" + String::utf16((const char16_t *)w_reg_code);173list.push_back(voice_d);174175delete[] w_lang_code;176delete[] w_reg_code;177178cpDataKeyAttribs->Release();179}180cpVoiceToken->Release();181}182cpEnum->Release();183}184}185cpCategory->Release();186}187return list;188}189190void 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) {191ERR_FAIL_NULL(synth);192if (p_interrupt) {193stop();194}195196if (p_text.is_empty()) {197DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServerEnums::TTS_UTTERANCE_CANCELED, p_utterance_id);198return;199}200201TTSUtterance message;202message.text = p_text;203message.voice = p_voice;204message.volume = CLAMP(p_volume, 0, 100);205message.pitch = CLAMP(p_pitch, 0.f, 2.f);206message.rate = CLAMP(p_rate, 0.1f, 10.f);207message.id = p_utterance_id;208queue.push_back(message);209210if (is_paused()) {211resume();212} else {213update_requested = true;214}215}216217void TTSDriverSAPI::pause() {218ERR_FAIL_NULL(synth);219if (!paused) {220if (synth->Pause() == S_OK) {221paused = true;222}223}224}225226void TTSDriverSAPI::resume() {227ERR_FAIL_NULL(synth);228synth->Resume();229paused = false;230}231232void TTSDriverSAPI::stop() {233ERR_FAIL_NULL(synth);234235SPVOICESTATUS status;236synth->GetStatus(&status, nullptr);237uint32_t current_stream = (uint32_t)status.ulCurrentStream;238if (ids.has(current_stream)) {239DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServerEnums::TTS_UTTERANCE_CANCELED, ids[current_stream].id);240ids.erase(current_stream);241}242for (TTSUtterance &message : queue) {243DisplayServer::get_singleton()->tts_post_utterance_event(DisplayServerEnums::TTS_UTTERANCE_CANCELED, message.id);244}245queue.clear();246synth->Speak(nullptr, SPF_PURGEBEFORESPEAK, nullptr);247synth->Resume();248paused = false;249}250251bool TTSDriverSAPI::init() {252if (SUCCEEDED(CoCreateInstance(CLSID_SpVoice, nullptr, CLSCTX_ALL, IID_ISpVoice, (void **)&synth))) {253ULONGLONG event_mask = SPFEI(SPEI_END_INPUT_STREAM) | SPFEI(SPEI_START_INPUT_STREAM) | SPFEI(SPEI_WORD_BOUNDARY);254synth->SetInterest(event_mask, event_mask);255synth->SetNotifyCallbackFunction(&speech_event_callback, (WPARAM)(this), 0);256print_verbose("Text-to-Speech: SAPI initialized.");257return true;258} else {259print_verbose("Text-to-Speech: Cannot initialize SAPI driver!");260return false;261}262}263264TTSDriverSAPI::TTSDriverSAPI() {265singleton = this;266}267268TTSDriverSAPI::~TTSDriverSAPI() {269if (synth) {270synth->Release();271}272singleton = nullptr;273}274275276