summaryrefslogtreecommitdiffstats
path: root/src/plugins/tts/speechdispatcher/qtexttospeech_speechd.cpp
blob: df186dd5d3a0100f543c7b01bfad23e09bcafa6d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
/****************************************************************************
**
** Copyright (C) 2021 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt Speech module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:COMM$
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** $QT_END_LICENSE$
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
****************************************************************************/


#include "qtexttospeech_speechd.h"

#include <qdebug.h>
#include <libspeechd.h>

#if LIBSPEECHD_MAJOR_VERSION > 0 || LIBSPEECHD_MINOR_VERSION >= 9
  #define HAVE_SPD_090
#endif

QT_BEGIN_NAMESPACE

QString dummyModule = QStringLiteral("dummy");

typedef QList<QTextToSpeechEngineSpeechd*> QTextToSpeechSpeechDispatcherBackendList;
Q_GLOBAL_STATIC(QTextToSpeechSpeechDispatcherBackendList, backends)

void speech_finished_callback(size_t msg_id, size_t client_id, SPDNotificationType state);

QLocale QTextToSpeechEngineSpeechd::localeForVoice(SPDVoice *voice) const
{
    QString lang_var = QString::fromLatin1(voice->language);
    if (qstrcmp(voice->variant, "none") != 0) {
        QString var = QString::fromLatin1(voice->variant);
        lang_var += QLatin1Char('_') + var;
    }
    return QLocale(lang_var);
}

QTextToSpeechEngineSpeechd::QTextToSpeechEngineSpeechd(const QVariantMap &, QObject *)
    : speechDispatcher(nullptr)
{
    backends->append(this);
    connectToSpeechDispatcher();
}

QTextToSpeechEngineSpeechd::~QTextToSpeechEngineSpeechd()
{
    if (speechDispatcher) {
        if ((m_state != QTextToSpeech::BackendError) && (m_state != QTextToSpeech::Ready))
            spd_cancel_all(speechDispatcher);
        spd_close(speechDispatcher);
    }
    backends->removeAll(this);
}

bool QTextToSpeechEngineSpeechd::connectToSpeechDispatcher()
{
    if (speechDispatcher)
        return true;

    speechDispatcher = spd_open("QTextToSpeech", "main", nullptr, SPD_MODE_THREADED);
    if (speechDispatcher) {
        speechDispatcher->callback_begin = speech_finished_callback;
        spd_set_notification_on(speechDispatcher, SPD_BEGIN);
        speechDispatcher->callback_end = speech_finished_callback;
        spd_set_notification_on(speechDispatcher, SPD_END);
        speechDispatcher->callback_cancel = speech_finished_callback;
        spd_set_notification_on(speechDispatcher, SPD_CANCEL);
        speechDispatcher->callback_resume = speech_finished_callback;
        spd_set_notification_on(speechDispatcher, SPD_RESUME);
        speechDispatcher->callback_pause = speech_finished_callback;
        spd_set_notification_on(speechDispatcher, SPD_PAUSE);

        QStringList availableModules;
        char **modules = spd_list_modules(speechDispatcher);
        int i = 0;
        while (modules && modules[i]) {
            availableModules.append(QString::fromUtf8(modules[i]));
            ++i;
        }

        if (availableModules.length() == 0) {
            qWarning() << "Found no modules in speech-dispatcher. No text to speech possible.";
        } else if (availableModules.length() == 1 && availableModules.at(0) == dummyModule) {
            qWarning() << "Found only the dummy module in speech-dispatcher. No text to speech possible. Install a tts module (e.g. espeak).";
        } else {
            m_state = QTextToSpeech::Ready;
        }

        // Default to system locale, since there's no api to get this from spd yet.
        m_currentLocale = QLocale::system();
        updateVoices();
        return true;
    }

    qWarning() << "Connection to speech-dispatcher failed";
    m_state = QTextToSpeech::BackendError;
    return false;
}

// hack to get state notifications
void QTextToSpeechEngineSpeechd::spdStateChanged(SPDNotificationType state)
{
    QTextToSpeech::State s = QTextToSpeech::BackendError;
    if (state == SPD_EVENT_PAUSE)
        s = QTextToSpeech::Paused;
    else if ((state == SPD_EVENT_BEGIN) || (state == SPD_EVENT_RESUME))
        s = QTextToSpeech::Speaking;
    else if ((state == SPD_EVENT_CANCEL) || (state == SPD_EVENT_END))
        s = QTextToSpeech::Ready;

    if (m_state != s) {
        m_state = s;
        emit stateChanged(m_state);
    }
}

void QTextToSpeechEngineSpeechd::say(const QString &text)
{
    if (text.isEmpty() || !connectToSpeechDispatcher())
        return;

    if (m_state != QTextToSpeech::Ready)
        stop();
    spd_say(speechDispatcher, SPD_MESSAGE, text.toUtf8().constData());
}

void QTextToSpeechEngineSpeechd::stop()
{
    if (!connectToSpeechDispatcher())
        return;

    if (m_state == QTextToSpeech::Paused)
        spd_resume_all(speechDispatcher);
    spd_cancel_all(speechDispatcher);
}

void QTextToSpeechEngineSpeechd::pause()
{
    if (!connectToSpeechDispatcher())
        return;

    if (m_state == QTextToSpeech::Speaking) {
        spd_pause_all(speechDispatcher);
    }
}

void QTextToSpeechEngineSpeechd::resume()
{
    if (!connectToSpeechDispatcher())
        return;

    if (m_state == QTextToSpeech::Paused) {
        spd_resume_all(speechDispatcher);
    }
}

bool QTextToSpeechEngineSpeechd::setPitch(double pitch)
{
    if (!connectToSpeechDispatcher())
        return false;

    int result = spd_set_voice_pitch(speechDispatcher, static_cast<int>(pitch * 100));
    if (result == 0)
        return true;
    return false;
}

double QTextToSpeechEngineSpeechd::pitch() const
{
    double pitch = 0.0;
#ifdef HAVE_SPD_090
    if (speechDispatcher != 0) {
        int result = spd_get_voice_pitch(speechDispatcher);
        pitch = result / 100.0;
    }
#endif
    return pitch;
}

bool QTextToSpeechEngineSpeechd::setRate(double rate)
{
    if (!connectToSpeechDispatcher())
        return false;

    int result = spd_set_voice_rate(speechDispatcher, static_cast<int>(rate * 100));
    return result == 0;
}

double QTextToSpeechEngineSpeechd::rate() const
{
    double rate = 0.0;
#ifdef HAVE_SPD_090
    if (speechDispatcher != 0) {
        int result = spd_get_voice_rate(speechDispatcher);
        rate = result / 100.0;
    }
#endif
    return rate;
}

bool QTextToSpeechEngineSpeechd::setVolume(double volume)
{
    if (!connectToSpeechDispatcher())
        return false;

    // convert from 0.0..1.0 to -100..100
    int result = spd_set_volume(speechDispatcher, (volume - 0.5) * 200);
    return result == 0;
}

double QTextToSpeechEngineSpeechd::volume() const
{
    double volume = 0.0;
#ifdef HAVE_SPD_090
    if (speechDispatcher != 0) {
        int result = spd_get_volume(speechDispatcher);
        // -100..100 to 0.0..1.0
        volume = (result + 100) / 200.0;
    }
#endif
    return volume;
}

bool QTextToSpeechEngineSpeechd::setLocale(const QLocale &locale)
{
    if (!connectToSpeechDispatcher())
        return false;

    int result = spd_set_language(speechDispatcher, locale.uiLanguages().at(0).toUtf8().data());
    if (result == 0) {
        QLocale previousLocale = m_currentLocale;
        QVoice previousVoice = m_currentVoice;
        m_currentLocale = locale;

        QVector<QVoice> voices = availableVoices();
        if (voices.size() > 0 && setVoice(voices.at(0)))
            return true;

        // try to go back to the previous locale/voice
        m_currentLocale = previousLocale;
        setVoice(previousVoice);
    }
    return false;
}

QLocale QTextToSpeechEngineSpeechd::locale() const
{
    return m_currentLocale;
}

bool QTextToSpeechEngineSpeechd::setVoice(const QVoice &voice)
{
    if (!connectToSpeechDispatcher())
        return false;

    const int result = spd_set_output_module(speechDispatcher, voiceData(voice).toString().toUtf8().data());
    if (result != 0)
        return false;
    const int result2 = spd_set_synthesis_voice(speechDispatcher, voice.name().toUtf8().data());
    if (result2 == 0) {
        m_currentVoice = voice;
        return true;
    }
    return false;
}

QVoice QTextToSpeechEngineSpeechd::voice() const
{
    return m_currentVoice;
}

QTextToSpeech::State QTextToSpeechEngineSpeechd::state() const
{
    return m_state;
}

void QTextToSpeechEngineSpeechd::updateVoices()
{
    char **modules = spd_list_modules(speechDispatcher);
#ifdef HAVE_SPD_090
    char *original_module = spd_get_output_module(speechDispatcher);
#else
    char *original_module = modules[0];
#endif
    QVoice originalVoice;
    char **module = modules;
    while (module != nullptr && module[0] != nullptr) {
        spd_set_output_module(speechDispatcher, module[0]);

        SPDVoice **voices = spd_list_synthesis_voices(speechDispatcher);
        int i = 0;
        while (voices != nullptr && voices[i] != nullptr) {
            QLocale locale = localeForVoice(voices[i]);
            if (!m_locales.contains(locale))
                m_locales.append(locale);
            const QString name = QString::fromUtf8(voices[i]->name);
            // iterate over genders and ages, creating a voice for each one
            QVoice voice = createVoice(name, QVoice::Unknown, QVoice::Other, QLatin1String(module[0]));
            m_voices.insert(locale.name(), voice);
            if (module[0] == original_module && i == 0) {
                // in lack of better options, remember the first voice as default
                originalVoice = voice;
            }
            ++i;
        }
        // free voices.
#ifdef HAVE_SPD_090
        free_spd_voices(voices);
#endif
        ++module;
    }

#ifdef HAVE_SPD_090
    // Also free modules.
    free_spd_modules(modules);
#endif
    // Set the output module back to what it was.
    spd_set_output_module(speechDispatcher, original_module);
    setVoice(originalVoice);
#ifdef HAVE_SPD_090
    free(original_module);
#endif
}

QVector<QLocale> QTextToSpeechEngineSpeechd::availableLocales() const
{
    return m_locales;
}

QVector<QVoice> QTextToSpeechEngineSpeechd::availableVoices() const
{
    return m_voices.values(m_currentLocale.name()).toVector();
}

// We have no way of knowing our own client_id since speech-dispatcher seems to be incomplete
// (history functions are just stubs)
void speech_finished_callback(size_t /*msg_id*/, size_t /*client_id*/, SPDNotificationType state)
{
    for (QTextToSpeechEngineSpeechd *backend : qAsConst(*backends))
        backend->spdStateChanged(state);
}

QT_END_NAMESPACE