6#include <QtCore/QDirIterator>
8#include <QtCore/QFileInfo>
9#include <QtCore/QJsonDocument>
10#include <QtCore/QJsonObject>
11#include <QtCore/QProcess>
12#include <QtCore/QStandardPaths>
14#include <QtMultimedia/QSoundEffect>
21 : QTextToSpeechEngine(parent)
22 , _executable(_findExecutable())
23 , _voices(_findVoices())
24 , _player(new QSoundEffect(this))
26 (void) connect(_player, &QSoundEffect::statusChanged,
this, [
this]() {
28 if (_playingFile.isEmpty()) {
31 if (_player->status() == QSoundEffect::Ready) {
33 }
else if (_player->status() == QSoundEffect::Error) {
34 qCWarning(PiperTtsEngineLog) <<
"Failed to play" << _playingFile;
38 (void) connect(_player, &QSoundEffect::playingChanged,
this, [
this]() {
39 if (!_player->isPlaying()) {
44 if (_executable.isEmpty() || _voices.isEmpty()) {
45 _setError(QTextToSpeech::ErrorReason::Initialization, tr(
"Piper or a Piper voice is not installed"));
48 if (!_outputDir.isValid()) {
49 _setError(QTextToSpeech::ErrorReason::Initialization, _outputDir.errorString());
53 const auto systemVoice = std::ranges::find(_voices, QLocale::system(), &QVoice::locale);
54 _voice = (systemVoice != _voices.cend()) ? *systemVoice : _voices.constFirst();
65 return !_findExecutable().isEmpty() && !_findVoices().isEmpty();
68QString PiperTtsEngine::_findExecutable()
71 static const QString executable = _searchExecutable();
75QString PiperTtsEngine::_searchExecutable()
78 const QStringList fallbackPaths = {QDir::homePath() + QStringLiteral(
"/.local/bin")};
81 QStringList candidates;
82 for (
const QString& name : {QStringLiteral(
"piper-tts"), QStringLiteral(
"piper")}) {
83 candidates << QStandardPaths::findExecutable(name) << QStandardPaths::findExecutable(name, fallbackPaths);
85 (void) candidates.removeAll(QString());
86 (void) candidates.removeDuplicates();
88 for (
const QString& path : candidates) {
89 if (_isPiperTts(path)) {
92 qCDebug(PiperTtsEngineLog) <<
"Skipping" << path <<
"which is not Piper text-to-speech";
97bool PiperTtsEngine::_isPiperTts(
const QString& path)
100 process.setProcessChannelMode(QProcess::MergedChannels);
101 process.start(path, {QStringLiteral(
"--help")});
102 if (!process.waitForFinished(5000)) {
104 (void) process.waitForFinished(1000);
107 return process.readAll().contains(
"--model");
110QList<QVoice> PiperTtsEngine::_findVoices()
112 QList<QVoice> voices;
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)) {
126 QFile configFile(model.filePath() + QStringLiteral(
".json"));
127 if (!configFile.open(QIODevice::ReadOnly)) {
128 qCDebug(PiperTtsEngineLog) <<
"Skipping voice without config:" << model.filePath();
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();
140 voices.append(createVoice(name, QLocale(languageCode), QVoice::Unknown, QVoice::Other, model.filePath()));
144 std::ranges::sort(voices, {}, &QVoice::name);
148void PiperTtsEngine::_startProcess()
152 _process =
new QProcess(
this);
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());
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));
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()});
168void PiperTtsEngine::_stopProcess()
176 (void) _process->disconnect(
this);
177 _process->closeWriteChannel();
178 if (!_process->waitForFinished(1000)) {
180 (void) _process->waitForFinished(1000);
182 _process->deleteLater();
186void PiperTtsEngine::_readProcessOutput()
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;
196 const QString path =
line.mid(pathStart);
198 if (_discardCount > 0) {
200 (void) QFile::remove(path);
203 if (_pendingCount > 0) {
210void PiperTtsEngine::_playWavFile(
const QString& path)
212 if (!_playingFile.isEmpty()) {
213 (void) QFile::remove(_playingFile);
216 _player->setSource(QUrl::fromLocalFile(path));
219void PiperTtsEngine::_finishUtterance()
221 if (!_playingFile.isEmpty()) {
222 (void) QFile::remove(_playingFile);
223 _playingFile.clear();
225 if ((_state == QTextToSpeech::State::Speaking) && (_pendingCount == 0)) {
226 _setState(QTextToSpeech::State::Ready);
230void PiperTtsEngine::_setState(QTextToSpeech::State state)
232 if (_state !=
state) {
234 emit stateChanged(_state);
238void PiperTtsEngine::_setError(QTextToSpeech::ErrorReason reason,
const QString& errorString)
241 _errorReason = reason;
243 emit errorOccurred(_errorReason, _errorString);
244 _setState(QTextToSpeech::State::Error);
249 return QTextToSpeech::Capability::Speak;
254 QList<QLocale> locales;
255 for (
const QVoice&
voice : _voices) {
256 if (!locales.contains(
voice.locale())) {
257 locales.append(
voice.locale());
265 QList<QVoice> voices;
266 for (
const QVoice&
voice : _voices) {
267 if (
voice.locale() == _voice.locale()) {
268 voices.append(
voice);
276 if (!_process || (_process->state() == QProcess::NotRunning)) {
281 const QString line = text.simplified();
282 _setState(QTextToSpeech::State::Speaking);
283 if (line.isEmpty()) {
284 _setState(QTextToSpeech::State::Ready);
289 (void) _process->write(line.toUtf8() +
'\n');
295 qCWarning(PiperTtsEngineLog) <<
"synthesize() is not supported";
300 Q_UNUSED(boundaryHint);
301 _discardCount += _pendingCount;
309 Q_UNUSED(boundaryHint);
338 return _voice.locale();
343 const auto it = std::ranges::find(_voices,
locale, &QVoice::locale);
344 if (it == _voices.cend()) {
357 _volume = std::clamp(
volume, 0.0, 1.0);
358 _player->setVolume(
static_cast<float>(_volume));
369 if (!_voices.contains(
voice)) {
372 if (
voice == _voice) {
377 stop(QTextToSpeech::BoundaryHint::Immediate);
#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
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.