QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
PiperTtsEngine.cc
Go to the documentation of this file.
1#include "PiperTtsEngine.h"
2
3#include <algorithm>
4
5#include <QtCore/QDir>
6#include <QtCore/QDirIterator>
7#include <QtCore/QFile>
8#include <QtCore/QFileInfo>
9#include <QtCore/QJsonDocument>
10#include <QtCore/QJsonObject>
11#include <QtCore/QProcess>
12#include <QtCore/QStandardPaths>
13#include <QtCore/QUrl>
14#include <QtMultimedia/QSoundEffect>
15
16#include "QGCLoggingCategory.h"
17
18QGC_LOGGING_CATEGORY(PiperTtsEngineLog, "Utilities.PiperTtsEngine")
19
21 : QTextToSpeechEngine(parent)
22 , _executable(_findExecutable())
23 , _voices(_findVoices())
24 , _player(new QSoundEffect(this))
25{
26 (void) connect(_player, &QSoundEffect::statusChanged, this, [this]() {
27 // stop() may have canceled the utterance while its WAV was loading.
28 if (_playingFile.isEmpty()) {
29 return;
30 }
31 if (_player->status() == QSoundEffect::Ready) {
32 _player->play();
33 } else if (_player->status() == QSoundEffect::Error) {
34 qCWarning(PiperTtsEngineLog) << "Failed to play" << _playingFile;
35 _finishUtterance();
36 }
37 });
38 (void) connect(_player, &QSoundEffect::playingChanged, this, [this]() {
39 if (!_player->isPlaying()) {
40 _finishUtterance();
41 }
42 });
43
44 if (_executable.isEmpty() || _voices.isEmpty()) {
45 _setError(QTextToSpeech::ErrorReason::Initialization, tr("Piper or a Piper voice is not installed"));
46 return;
47 }
48 if (!_outputDir.isValid()) {
49 _setError(QTextToSpeech::ErrorReason::Initialization, _outputDir.errorString());
50 return;
51 }
52
53 const auto systemVoice = std::ranges::find(_voices, QLocale::system(), &QVoice::locale);
54 _voice = (systemVoice != _voices.cend()) ? *systemVoice : _voices.constFirst();
55 _startProcess();
56}
57
59{
60 _stopProcess();
61}
62
64{
65 return !_findExecutable().isEmpty() && !_findVoices().isEmpty();
66}
67
68QString PiperTtsEngine::_findExecutable()
69{
70 // Cached because verifying a candidate runs it.
71 static const QString executable = _searchExecutable();
72 return executable;
73}
74
75QString PiperTtsEngine::_searchExecutable()
76{
77 // Desktop launchers often don't have ~/.local/bin in PATH, which is where pip/uv/pipx install Piper.
78 const QStringList fallbackPaths = {QDir::homePath() + QStringLiteral("/.local/bin")};
79
80 // Some distributions name it piper-tts because "piper" is also a mouse configuration tool.
81 QStringList candidates;
82 for (const QString& name : {QStringLiteral("piper-tts"), QStringLiteral("piper")}) {
83 candidates << QStandardPaths::findExecutable(name) << QStandardPaths::findExecutable(name, fallbackPaths);
84 }
85 (void) candidates.removeAll(QString());
86 (void) candidates.removeDuplicates();
87
88 for (const QString& path : candidates) {
89 if (_isPiperTts(path)) {
90 return path;
91 }
92 qCDebug(PiperTtsEngineLog) << "Skipping" << path << "which is not Piper text-to-speech";
93 }
94 return QString();
95}
96
97bool PiperTtsEngine::_isPiperTts(const QString& path)
98{
99 QProcess process;
100 process.setProcessChannelMode(QProcess::MergedChannels);
101 process.start(path, {QStringLiteral("--help")});
102 if (!process.waitForFinished(5000)) {
103 process.kill();
104 (void) process.waitForFinished(1000);
105 return false;
106 }
107 return process.readAll().contains("--model");
108}
109
110QList<QVoice> PiperTtsEngine::_findVoices()
111{
112 QList<QVoice> voices;
113 QStringList names;
114
115 const QStringList voiceDirs = QStandardPaths::locateAll(
116 QStandardPaths::GenericDataLocation, QStringLiteral("piper-voices"), QStandardPaths::LocateDirectory);
117 for (const QString& voiceDir : voiceDirs) {
118 QDirIterator it(voiceDir, {QStringLiteral("*.onnx")}, QDir::Files, QDirIterator::Subdirectories);
119 while (it.hasNext()) {
120 const QFileInfo model(it.next());
121 const QString name = model.completeBaseName();
122 if (names.contains(name)) {
123 continue;
124 }
125
126 QFile configFile(model.filePath() + QStringLiteral(".json"));
127 if (!configFile.open(QIODevice::ReadOnly)) {
128 qCDebug(PiperTtsEngineLog) << "Skipping voice without config:" << model.filePath();
129 continue;
130 }
131 const QJsonObject config = QJsonDocument::fromJson(configFile.readAll()).object();
132 const QString languageCode =
133 config.value(QStringLiteral("language")).toObject().value(QStringLiteral("code")).toString();
134 if (languageCode.isEmpty()) {
135 qCDebug(PiperTtsEngineLog) << "Skipping voice without language code:" << model.filePath();
136 continue;
137 }
138
139 names.append(name);
140 voices.append(createVoice(name, QLocale(languageCode), QVoice::Unknown, QVoice::Other, model.filePath()));
141 }
142 }
143
144 std::ranges::sort(voices, {}, &QVoice::name);
145 return voices;
146}
147
148void PiperTtsEngine::_startProcess()
149{
150 _stopProcess();
151
152 _process = new QProcess(this);
153 // Python Piper logs written files to stderr, the older C++ Piper prints them to stdout.
154 _process->setProcessChannelMode(QProcess::MergedChannels);
155 (void) connect(_process, &QProcess::readyReadStandardOutput, this, &PiperTtsEngine::_readProcessOutput);
156 (void) connect(_process, &QProcess::errorOccurred, this, [this](QProcess::ProcessError) {
157 _setError(QTextToSpeech::ErrorReason::Initialization, _process->errorString());
158 });
159 (void) connect(_process, &QProcess::finished, this, [this](int exitCode, QProcess::ExitStatus) {
160 _setError(QTextToSpeech::ErrorReason::Initialization, tr("Piper exited with code %1").arg(exitCode));
161 });
162
163 const QString modelPath = voiceData(_voice).toString();
164 qCDebug(PiperTtsEngineLog) << "Starting" << _executable << "with voice" << modelPath;
165 _process->start(_executable, {QStringLiteral("-m"), modelPath, QStringLiteral("-d"), _outputDir.path()});
166}
167
168void PiperTtsEngine::_stopProcess()
169{
170 _pendingCount = 0;
171 _discardCount = 0;
172 if (!_process) {
173 return;
174 }
175
176 (void) _process->disconnect(this);
177 _process->closeWriteChannel();
178 if (!_process->waitForFinished(1000)) {
179 _process->kill();
180 (void) _process->waitForFinished(1000);
181 }
182 _process->deleteLater();
183 _process = nullptr;
184}
185
186void PiperTtsEngine::_readProcessOutput()
187{
188 while (_process->canReadLine()) {
189 const QString line = QString::fromUtf8(_process->readLine()).trimmed();
190 const qsizetype pathStart = line.indexOf(_outputDir.path());
191 if ((pathStart < 0) || !line.endsWith(QStringLiteral(".wav"))) {
192 qCDebug(PiperTtsEngineLog) << "Piper:" << line;
193 continue;
194 }
195
196 const QString path = line.mid(pathStart);
197 // Piper answers in order, so canceled utterances come before the current ones.
198 if (_discardCount > 0) {
199 _discardCount--;
200 (void) QFile::remove(path);
201 continue;
202 }
203 if (_pendingCount > 0) {
204 _pendingCount--;
205 }
206 _playWavFile(path);
207 }
208}
209
210void PiperTtsEngine::_playWavFile(const QString& path)
211{
212 if (!_playingFile.isEmpty()) {
213 (void) QFile::remove(_playingFile);
214 }
215 _playingFile = path;
216 _player->setSource(QUrl::fromLocalFile(path));
217}
218
219void PiperTtsEngine::_finishUtterance()
220{
221 if (!_playingFile.isEmpty()) {
222 (void) QFile::remove(_playingFile);
223 _playingFile.clear();
224 }
225 if ((_state == QTextToSpeech::State::Speaking) && (_pendingCount == 0)) {
226 _setState(QTextToSpeech::State::Ready);
227 }
228}
229
230void PiperTtsEngine::_setState(QTextToSpeech::State state)
231{
232 if (_state != state) {
233 _state = state;
234 emit stateChanged(_state);
235 }
236}
237
238void PiperTtsEngine::_setError(QTextToSpeech::ErrorReason reason, const QString& errorString)
239{
240 qCWarning(PiperTtsEngineLog) << errorString;
241 _errorReason = reason;
242 _errorString = errorString;
243 emit errorOccurred(_errorReason, _errorString);
244 _setState(QTextToSpeech::State::Error);
245}
246
247QTextToSpeech::Capabilities PiperTtsEngine::capabilities() const
248{
249 return QTextToSpeech::Capability::Speak;
250}
251
253{
254 QList<QLocale> locales;
255 for (const QVoice& voice : _voices) {
256 if (!locales.contains(voice.locale())) {
257 locales.append(voice.locale());
258 }
259 }
260 return locales;
261}
262
264{
265 QList<QVoice> voices;
266 for (const QVoice& voice : _voices) {
267 if (voice.locale() == _voice.locale()) {
268 voices.append(voice);
269 }
270 }
271 return voices;
272}
273
274void PiperTtsEngine::say(const QString& text)
275{
276 if (!_process || (_process->state() == QProcess::NotRunning)) {
277 return;
278 }
279
280 // Piper treats each line as one utterance.
281 const QString line = text.simplified();
282 _setState(QTextToSpeech::State::Speaking);
283 if (line.isEmpty()) {
284 _setState(QTextToSpeech::State::Ready);
285 return;
286 }
287
288 _pendingCount++;
289 (void) _process->write(line.toUtf8() + '\n');
290}
291
292void PiperTtsEngine::synthesize(const QString& text)
293{
294 Q_UNUSED(text);
295 qCWarning(PiperTtsEngineLog) << "synthesize() is not supported";
296}
297
298void PiperTtsEngine::stop(QTextToSpeech::BoundaryHint boundaryHint)
299{
300 Q_UNUSED(boundaryHint);
301 _discardCount += _pendingCount;
302 _pendingCount = 0;
303 _player->stop();
304 _finishUtterance();
305}
306
307void PiperTtsEngine::pause(QTextToSpeech::BoundaryHint boundaryHint)
308{
309 Q_UNUSED(boundaryHint);
310}
311
313
315{
316 return 0.0;
317}
318
320{
321 Q_UNUSED(rate);
322 return false;
323}
324
326{
327 return 0.0;
328}
329
331{
332 Q_UNUSED(pitch);
333 return false;
334}
335
337{
338 return _voice.locale();
339}
340
342{
343 const auto it = std::ranges::find(_voices, locale, &QVoice::locale);
344 if (it == _voices.cend()) {
345 return false;
346 }
347 return setVoice(*it);
348}
349
351{
352 return _volume;
353}
354
356{
357 _volume = std::clamp(volume, 0.0, 1.0);
358 _player->setVolume(static_cast<float>(_volume));
359 return true;
360}
361
363{
364 return _voice;
365}
366
368{
369 if (!_voices.contains(voice)) {
370 return false;
371 }
372 if (voice == _voice) {
373 return true;
374 }
375
376 _voice = voice;
377 stop(QTextToSpeech::BoundaryHint::Immediate);
378 _startProcess();
379 return true;
380}
381
382QTextToSpeech::State PiperTtsEngine::state() const
383{
384 return _state;
385}
386
387QTextToSpeech::ErrorReason PiperTtsEngine::errorReason() const
388{
389 return _errorReason;
390}
391
393{
394 return _errorString;
395}
#define QGC_LOGGING_CATEGORY(name, categoryStr)
double rate() const override
QTextToSpeech::State state() const override
QList< QVoice > availableVoices() const override
void synthesize(const QString &text) override
QLocale locale() const override
void pause(QTextToSpeech::BoundaryHint boundaryHint) override
static bool isAvailable()
True if a Piper executable and at least one voice model are installed.
bool setPitch(double pitch) override
QList< QLocale > availableLocales() const override
bool setRate(double rate) override
QTextToSpeech::ErrorReason errorReason() const override
bool setVoice(const QVoice &voice) override
bool setLocale(const QLocale &locale) override
PiperTtsEngine(QObject *parent=nullptr)
~PiperTtsEngine() override
void resume() override
double volume() const override
bool setVolume(double volume) override
void stop(QTextToSpeech::BoundaryHint boundaryHint) override
QVoice voice() const override
double pitch() const override
QTextToSpeech::Capabilities capabilities() const override
QString errorString() const override
void say(const QString &text) override
QByteArray line(std::string_view command)
command as one CR/LF-terminated line.