QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
AudioOutput.cc
Go to the documentation of this file.
1#include "AudioOutput.h"
2#include "Fact.h"
3#include "AppMessages.h"
5#ifdef QGC_PIPER_TTS
6#include "PiperTtsEngine.h"
7#endif
8
9#include <QtCore/QRegularExpression>
10#include <QtCore/QApplicationStatic>
11#include <QtCore/QTimer>
12#include <QtTextToSpeech/QTextToSpeech>
13#include <QtTextToSpeech/QVoice>
14
15#include <algorithm>
16
17QGC_LOGGING_CATEGORY(AudioOutputLog, "Utilities.AudioOutput");
18// qt.speech.tts.flite
19// qt.speech.tts.android
20
21// Keys in both tables must not end in a digit: trailing instance digits are split off before lookup.
22const QHash<QString, QString> AudioOutput::_textHash = {
23 {"ERR", "error"},
24 {"POSCTL", "Position Control"},
25 {"ALTCTL", "Altitude Control"},
26 {"AUTO_RTL", "auto return to launch"},
27 {"RTL", "return To launch"},
28 {"ACCEL", "accelerometer"},
29 {"RC_MAP_MODE_SW", "RC mode switch"},
30 {"REJ", "rejected"},
31 {"WP", "waypoint"},
32 {"CMD", "command"},
33 {"COMPID", "component eye dee"},
34 {"PARAMS", "parameters"},
35 {"ID", "I.D."},
36 {"ADSB", "A.D.S.B."},
37 {"EKF", "E.K.F."},
38 {"PREARM", "pre arm"},
39 {"PITOT", "pee toe"},
40 {"SERVOX_FUNCTION", "Servo X Function"},
41 {"CNT", "count"},
42 {"DNST", "density"},
43 {"TKOFF", "takeoff"},
44 {"TERRN", "terrain"},
45 {"AROT", "autorotation"},
46 {"TCAL", "temperature calibration"},
47 {"PWR", "power"},
48 {"PERF", "performance"},
49 {"CFG", "config"},
50 {"FBWA", "fly-by-wire A"},
51};
52
53// Matched case-sensitively so lowercase words ("rc", "ins") are left alone. CAN is omitted: it is spoken as a word.
54const QSet<QString> AudioOutput::_spelledAcronyms = {
55 "GPS", "GNSS", "GCS", "ESC", "VTOL", "RC", "IMU", "AHRS", "INS", "CPU", "RPM", "SD", "USB",
56 "PWM", "PPS", "CRC", "ICAO", "SIH", "HAGL", "FMU", "UTM", "MAV", "FFT", "AFS", "AMSL", "MSL",
57 "HDOP", "GPIO", "SITL", "ODID", "TCP", "UDP", "UART", "I2C", "IOMCU", "FTP", "NACK", "NED", "RSSI",
58 "OSD", "MSP", "DMA", "DFU", "DNA", "EFI", "ISR", "WDG", "NMEA", "RTCM", "VTX", "WMM", "HW",
59 "SW", "FW", "RX", "LLH", "IP", "IO", "RF", "LQ", "DEVID",
60};
61
63
65 : QObject(parent)
66 , _engine(new QTextToSpeech(_engineName(), this))
67{
68 // qCDebug(AudioOutputLog) << this;
69}
70
71QString AudioOutput::_engineName()
72{
73 // The "none" backend avoids probing system plugins (e.g. speechd) that emit critical load errors
74 // and trip the strict log check.
76 return QStringLiteral("none");
77 }
78
79#ifdef QGC_PIPER_TTS
80 // Piper sounds far better than speechd's usual espeak-ng, but is only used if the user installed it.
82 return QStringLiteral("piper");
83 }
84#endif
85
86 return QString();
87}
88
89void AudioOutput::_fallBackToDefaultEngine()
90{
91 if (_engine->engine() != QStringLiteral("piper")) {
92 return;
93 }
94
95 qCWarning(AudioOutputLog) << "Piper failed, falling back to the default TTS engine";
96 _textQueueSize = 0;
97 // The new engine only reports Ready after engineChanged, so its settings are applied then.
98 // QTextToSpeech carries the volume over to the new engine.
99 _engineSwitched = true;
100 (void) _engine->setEngine(QString());
101}
102
104{
105 // qCDebug(AudioOutputLog) << this;
106}
107
109{
110 return _audioOutput();
111}
112
113void AudioOutput::init(Fact* volumeFact, Fact* mutedFact)
114{
115 Q_CHECK_PTR(volumeFact);
116 Q_CHECK_PTR(mutedFact);
117
118 if (_initialized) {
119 return;
120 }
121
122 _volumeFact = volumeFact;
123 _mutedFact = mutedFact;
124
125 // Some QTextToSpeech backends (notably Android) initialize asynchronously, so finalize on Ready rather than bailing (Qt docs).
126 (void) connect(_engine, &QTextToSpeech::stateChanged, this, [this](QTextToSpeech::State state) {
127 if (state == QTextToSpeech::State::Ready) {
128 _textQueueSize = 0;
129 if (!_initialized) {
130 _finishInit();
131 } else if (_engineSwitched) {
132 _engineSwitched = false;
133 _applyEngineSettings();
134 }
135 }
136 qCDebug(AudioOutputLog) << "TTS State changed to:" << state;
137 });
138
139 (void) connect(_engine, &QTextToSpeech::errorOccurred, this, [this](QTextToSpeech::ErrorReason reason, const QString &errorString) {
140 qCWarning(AudioOutputLog) << "TTS error occurred. Reason:" << reason << ", Message:" << errorString;
141 _textQueueSize = 0;
142 // Switching engines from within the engine's own signal is unsafe, so do it afterwards.
143 (void) QMetaObject::invokeMethod(this, &AudioOutput::_fallBackToDefaultEngine, Qt::QueuedConnection);
144 });
145
146 // Decrement as each utterance leaves the queue so the counter tracks live backlog, not cumulative enqueues since drain.
147 (void) connect(_engine, &QTextToSpeech::aboutToSynthesize, this, [this](qsizetype) {
148 if (_textQueueSize > 0) {
149 _textQueueSize--;
150 }
151 });
152
153 (void) connect(_engine, &QTextToSpeech::engineChanged, this, [this](const QString &engine) {
154 qCDebug(AudioOutputLog) << "TTS Engine set to:" << engine;
155 _applyEngineSettings();
156 });
157
158 if (_engine->state() == QTextToSpeech::State::Error) {
159 _fallBackToDefaultEngine();
160 }
161
162 if (_engine->state() == QTextToSpeech::State::Ready) {
163 _finishInit();
164 } else {
165 // Some backends (notably Android) start in Error state while binding to the system TTS
166 // service, then transition to Ready. Defer and only warn if the engine never becomes usable.
167 qCDebug(AudioOutputLog) << "QTextToSpeech engine not ready; deferring init. State:" << _engine->state();
168 if (!QGC::runningUnitTests()) {
169 // Skip under unit tests: the "none" backend never becomes Ready and the warning would trip the strict log check.
170 QTimer::singleShot(kEngineInitWarnTimeout, this, [this]() {
171 if (!_initialized) {
172 qCWarning(AudioOutputLog) << "No usable QTextToSpeech engine available. Engine:" << _engine->engine()
173 << "State:" << _engine->state()
174 << "Reason:" << _engine->errorReason() << _engine->errorString();
175 }
176 });
177 }
178 }
179}
180
181void AudioOutput::_finishInit()
182{
183 _applyEngineSettings();
184
185 (void) connect(_volumeFact, &Fact::valueChanged, this, [this]() {
186 _setVolume();
187 });
188
189 (void) connect(_mutedFact, &Fact::valueChanged, this, [this]() {
190 _setVolume();
191 });
192
193 if (AudioOutputLog().isDebugEnabled()) {
194 (void) connect(_engine, &QTextToSpeech::localeChanged, this, [](const QLocale &locale) {
195 qCDebug(AudioOutputLog) << "TTS Locale change to:" << locale;
196 });
197 (void) connect(_engine, &QTextToSpeech::volumeChanged, this, [](double volume) {
198 qCDebug(AudioOutputLog) << "TTS Volume changed to:" << volume;
199 });
200 (void) connect(_engine, &QTextToSpeech::sayingWord, this, [](const QString &word, qsizetype id, qsizetype start, qsizetype length) {
201 qCDebug(AudioOutputLog) << "TTS Saying:" << word << "ID:" << id << "Start:" << start << "Length:" << length;
202 });
203 }
204
205 _initialized = true;
206 _setVolume();
207
208 qCDebug(AudioOutputLog) << "AudioOutput initialized with volume:" << _volumeSetting() << "%";
209}
210
211double AudioOutput::_volumeSetting() const
212{
213 return std::clamp(_volumeFact->rawValue().toDouble(), 0.0, 100.0);
214}
215
216bool AudioOutput::_mutedSetting() const
217{
218 return _mutedFact->rawValue().toBool();
219}
220
221void AudioOutput::_applyEngineSettings()
222{
223 if (_engine->state() != QTextToSpeech::State::Ready) {
224 return;
225 }
226
227 const QLocale defaultLocale("en_US");
228 if (_engine->availableLocales().contains(defaultLocale)) {
229 _engine->setLocale(defaultLocale);
230 }
231
232 // Pin an explicit voice so output doesn't depend on the engine's per-OS default.
233 const QList<QVoice> voices = _engine->availableVoices();
234 if (!voices.isEmpty()) {
235 _engine->setVoice(voices.constFirst());
236 }
237
238 _speakCapable = _engine->engineCapabilities().testFlag(QTextToSpeech::Capability::Speak);
239}
240
241void AudioOutput::_setVolume()
242{
243 const bool muted = _mutedSetting();
244 const double volume = muted ? 0.0 : _volumeSetting();
245
246 // qFuzzyCompare fails near zero; adding 1.0 shifts values into a safe range
247 if (qFuzzyCompare(1.0 + volume, 1.0 + _lastVolume)) {
248 return;
249 }
250 _lastVolume = volume;
251
252 // Must normalize volume to 0.0 - 1.0 for QTextToSpeech
253 const double normalizedVolume = volume / 100.0;
254 (void) QMetaObject::invokeMethod(_engine, [this, volume, normalizedVolume]() {
255 if (volume == 0.0) {
256 // Prevent any queued text from being spoken once muted
257 _engine->stop(QTextToSpeech::BoundaryHint::Immediate);
258 _textQueueSize = 0;
259 }
260 _engine->setVolume(normalizedVolume);
261 });
262 qCDebug(AudioOutputLog) << "AudioOutput volume set to:" << volume << "%";
263}
264
265void AudioOutput::say(const QString &text, TextMods textMods)
266{
267 if (!_initialized) {
268 if (!QGC::runningUnitTests()) {
269 qCWarning(AudioOutputLog) << "AudioOutput not initialized. Call init() before using say().";
270 }
271 return;
272 }
273
274 if (_volumeSetting() <= 0.0 || _mutedSetting()) {
275 return;
276 }
277
278 if (!_speakCapable) {
279 qCWarning(AudioOutputLog) << "Speech Not Supported:" << text;
280 return;
281 }
282
283 QString outText = _fixTextMessageForAudio(text);
284
285 if (textMods.testFlag(TextMod::Translate)) {
286 outText = tr("%1").arg(outText);
287 }
288
289 if (outText.isEmpty()) {
290 return;
291 }
292
293 // All queue/counter mutation must stay on the engine thread (where stateChanged resets it).
294 (void) QMetaObject::invokeMethod(_engine, [this, outText]() {
295 if (_textQueueSize >= kMaxTextQueueSize) {
296 _engine->stop(QTextToSpeech::BoundaryHint::Immediate);
297 _textQueueSize = 0;
298 qCWarning(AudioOutputLog) << "Text queue exceeded maximum size. Stopped current speech.";
299 }
300
301 const qsizetype index = _engine->enqueue(outText);
302 if (index < 0) {
303 qCWarning(AudioOutputLog) << "Failed to enqueue speech. State:" << _engine->state()
304 << "Reason:" << _engine->errorReason();
305 return;
306 }
307
308 _textQueueSize++;
309 qCDebug(AudioOutputLog) << "Enqueued text with index:" << index << ", Queue Size:" << _textQueueSize;
310 });
311}
312
314{
315 if (!_initialized) {
316 qCWarning(AudioOutputLog) << "AudioOutput not initialized. Call init() before using testAudioOutput().";
317 return;
318 }
319
320 // Main-thread only (QML-invoked): mutates the engine and counter directly without marshaling.
321 _engine->stop(QTextToSpeech::BoundaryHint::Immediate);
322 _textQueueSize = 0;
323
324 const QString testText = tr("Audio test. Volume is %1 percent").arg(_volumeSetting(), 0, 'f', 1);
325 say(testText);
326}
327
328QString AudioOutput::_fixTextMessageForAudio(const QString &string)
329{
330 QString result = string;
331 // Before abbreviations: spelled acronyms end in '.', which would hide the word a hyphen is attached to.
332 result = _replaceNegativeSigns(result);
333 result = _replaceAbbreviations(result);
334 result = _replaceDecimalPoints(result);
335 result = _replaceMeters(result);
336 result = _convertMilliseconds(result);
337 return result;
338}
339
340QString AudioOutput::_spokenAbbreviation(const QString& token)
341{
342 const auto it = _textHash.constFind(token.toUpper());
343 if (it != _textHash.constEnd()) {
344 return it.value();
345 }
346
347 if (!_spelledAcronyms.contains(token)) {
348 return QString();
349 }
350
351 QString spelled;
352 spelled.reserve(token.size() * 2);
353 for (const QChar c : token) {
354 spelled.append(c);
355 spelled.append(QLatin1Char('.'));
356 }
357 return spelled;
358}
359
360QString AudioOutput::_replaceAbbreviations(const QString &input)
361{
362 // Captures a whole identifier-like token, splitting off trailing instance digits ("EKF3" -> "EKF", "3").
363 static const QRegularExpression tokenRegex(
364 QStringLiteral("(?<![A-Za-z0-9_])([A-Za-z][A-Za-z0-9_]*?)([0-9]*)(?![A-Za-z0-9_])"));
365
366 QString output;
367 output.reserve(input.size());
368 qsizetype last = 0;
369
370 QRegularExpressionMatchIterator it = tokenRegex.globalMatch(input);
371 while (it.hasNext()) {
372 const QRegularExpressionMatch match = it.next();
373 const QString spoken = _spokenAbbreviation(match.captured(1));
374 if (spoken.isEmpty()) {
375 continue;
376 }
377
378 output.append(QStringView(input).mid(last, match.capturedStart() - last));
379 output.append(spoken);
380 if (match.capturedLength(2) > 0) {
381 output.append(QLatin1Char(' '));
382 output.append(match.capturedView(2));
383 }
384 last = match.capturedEnd();
385 }
386 output.append(QStringView(input).mid(last));
387
388 return output;
389}
390
391QString AudioOutput::_replaceNegativeSigns(const QString &input)
392{
393 static const QRegularExpression negNumRegex(QStringLiteral("(?<![A-Za-z0-9_])-\\s*(?=\\d)"));
394
395 QString output = input;
396 (void) output.replace(negNumRegex, "negative ");
397 return output;
398}
399
400QString AudioOutput::_replaceDecimalPoints(const QString &input)
401{
402 static const QRegularExpression realNumRegex(QStringLiteral("([0-9]+)(\\.)([0-9]+)"));
403
404 QString output = input;
405 QRegularExpressionMatch realNumRegexMatch = realNumRegex.match(output);
406 while (realNumRegexMatch.hasMatch()) {
407 if (!realNumRegexMatch.captured(2).isNull()) {
408 (void) output.replace(realNumRegexMatch.capturedStart(2), realNumRegexMatch.capturedEnd(2) - realNumRegexMatch.capturedStart(2), QStringLiteral(" point "));
409 }
410 realNumRegexMatch = realNumRegex.match(output);
411 }
412
413 return output;
414}
415
416QString AudioOutput::_replaceMeters(const QString &input)
417{
418 static const QRegularExpression realNumMeterRegex(QStringLiteral("[0-9]*\\.?[0-9]\\s?(m)([^A-Za-z]|$)"));
419
420 QString output = input;
421 QRegularExpressionMatch realNumMeterRegexMatch = realNumMeterRegex.match(output);
422 while (realNumMeterRegexMatch.hasMatch()) {
423 if (!realNumMeterRegexMatch.captured(1).isNull()) {
424 (void) output.replace(realNumMeterRegexMatch.capturedStart(1), realNumMeterRegexMatch.capturedEnd(1) - realNumMeterRegexMatch.capturedStart(1), QStringLiteral(" meters"));
425 }
426 realNumMeterRegexMatch = realNumMeterRegex.match(output);
427 }
428
429 return output;
430}
431
432QString AudioOutput::_convertMilliseconds(const QString &input)
433{
434 QString result = input;
435
436 QString match;
437 int number;
438 if (_getMillisecondString(input, match, number) && (number >= 1000)) {
439 QString newNumber;
440 if (number < 60000) {
441 const int seconds = number / 1000;
442 const int ms = number - (seconds * 1000);
443 newNumber = QStringLiteral("%1 second%2").arg(seconds).arg(seconds > 1 ? "s" : "");
444 if (ms > 0) {
445 (void) newNumber.append(QStringLiteral(" and %1 millisecond").arg(ms));
446 }
447 } else {
448 const int minutes = number / 60000;
449 const int seconds = (number - (minutes * 60000)) / 1000;
450 newNumber = QStringLiteral("%1 minute%2").arg(minutes).arg(minutes > 1 ? "s" : "");
451 if (seconds > 0) {
452 (void) newNumber.append(QStringLiteral(" and %1 second%2").arg(seconds).arg(seconds > 1 ? "s" : ""));
453 }
454 }
455 (void) result.replace(match, newNumber);
456 }
457
458 return result;
459}
460
461bool AudioOutput::_getMillisecondString(const QString &string, QString &match, int &number)
462{
463 static const QRegularExpression msRegex("((?<number>[0-9]+)ms)");
464
465 bool result = false;
466
467 QRegularExpressionMatch regexpMatch = msRegex.match(string);
468 if (regexpMatch.hasMatch()) {
469 match = regexpMatch.captured(0);
470 const QString numberStr = regexpMatch.captured("number");
471 number = numberStr.toInt();
472 result = true;
473 }
474
475 return result;
476}
Q_APPLICATION_STATIC(AudioOutput, _audioOutput)
#define QGC_LOGGING_CATEGORY(name, categoryStr)
The AudioOutput class provides functionality for audio output using text-to-speech.
Definition AudioOutput.h:17
void say(const QString &text, TextMods textMods=TextMod::None)
AudioOutput(QObject *parent=nullptr)
void testAudioOutput()
Tests the audio output. Will stop current output before test.
static AudioOutput * instance()
~AudioOutput()
Destructor for the AudioOutput class.
void init(Fact *volumeFact, Fact *mutedFact)
Initialize the Singleton.
A Fact is used to hold a single value within the system.
Definition Fact.h:15
void valueChanged(const QVariant &value)
This signal is only meant for use by the QT property system. It should not be connected to by client ...
static bool isAvailable()
True if a Piper executable and at least one voice model are installed.
std::optional< T > number(std::string_view field, int base=DECIMAL_BASE)
bool runningUnitTests()