9#include <QtCore/QRegularExpression>
10#include <QtCore/QApplicationStatic>
11#include <QtCore/QTimer>
12#include <QtTextToSpeech/QTextToSpeech>
13#include <QtTextToSpeech/QVoice>
22const QHash<QString, QString> AudioOutput::_textHash = {
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"},
33 {
"COMPID",
"component eye dee"},
34 {
"PARAMS",
"parameters"},
38 {
"PREARM",
"pre arm"},
40 {
"SERVOX_FUNCTION",
"Servo X Function"},
45 {
"AROT",
"autorotation"},
46 {
"TCAL",
"temperature calibration"},
48 {
"PERF",
"performance"},
50 {
"FBWA",
"fly-by-wire A"},
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",
66 , _engine(new QTextToSpeech(_engineName(), this))
71QString AudioOutput::_engineName()
76 return QStringLiteral(
"none");
82 return QStringLiteral(
"piper");
89void AudioOutput::_fallBackToDefaultEngine()
91 if (_engine->engine() != QStringLiteral(
"piper")) {
95 qCWarning(AudioOutputLog) <<
"Piper failed, falling back to the default TTS engine";
99 _engineSwitched =
true;
100 (void) _engine->setEngine(QString());
110 return _audioOutput();
115 Q_CHECK_PTR(volumeFact);
116 Q_CHECK_PTR(mutedFact);
122 _volumeFact = volumeFact;
123 _mutedFact = mutedFact;
126 (void) connect(_engine, &QTextToSpeech::stateChanged,
this, [
this](QTextToSpeech::State state) {
127 if (state == QTextToSpeech::State::Ready) {
131 }
else if (_engineSwitched) {
132 _engineSwitched =
false;
133 _applyEngineSettings();
136 qCDebug(AudioOutputLog) <<
"TTS State changed to:" << state;
139 (void) connect(_engine, &QTextToSpeech::errorOccurred,
this, [
this](QTextToSpeech::ErrorReason reason,
const QString &errorString) {
140 qCWarning(AudioOutputLog) <<
"TTS error occurred. Reason:" << reason <<
", Message:" << errorString;
143 (void) QMetaObject::invokeMethod(
this, &AudioOutput::_fallBackToDefaultEngine, Qt::QueuedConnection);
147 (void) connect(_engine, &QTextToSpeech::aboutToSynthesize,
this, [
this](qsizetype) {
148 if (_textQueueSize > 0) {
153 (void) connect(_engine, &QTextToSpeech::engineChanged,
this, [
this](
const QString &engine) {
154 qCDebug(AudioOutputLog) <<
"TTS Engine set to:" << engine;
155 _applyEngineSettings();
158 if (_engine->state() == QTextToSpeech::State::Error) {
159 _fallBackToDefaultEngine();
162 if (_engine->state() == QTextToSpeech::State::Ready) {
167 qCDebug(AudioOutputLog) <<
"QTextToSpeech engine not ready; deferring init. State:" << _engine->state();
170 QTimer::singleShot(kEngineInitWarnTimeout,
this, [
this]() {
172 qCWarning(AudioOutputLog) <<
"No usable QTextToSpeech engine available. Engine:" << _engine->engine()
173 <<
"State:" << _engine->state()
174 <<
"Reason:" << _engine->errorReason() << _engine->errorString();
181void AudioOutput::_finishInit()
183 _applyEngineSettings();
193 if (AudioOutputLog().isDebugEnabled()) {
194 (void) connect(_engine, &QTextToSpeech::localeChanged,
this, [](
const QLocale &locale) {
195 qCDebug(AudioOutputLog) <<
"TTS Locale change to:" << locale;
197 (void) connect(_engine, &QTextToSpeech::volumeChanged,
this, [](
double volume) {
198 qCDebug(AudioOutputLog) <<
"TTS Volume changed to:" << volume;
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;
208 qCDebug(AudioOutputLog) <<
"AudioOutput initialized with volume:" << _volumeSetting() <<
"%";
211double AudioOutput::_volumeSetting()
const
213 return std::clamp(_volumeFact->rawValue().toDouble(), 0.0, 100.0);
216bool AudioOutput::_mutedSetting()
const
218 return _mutedFact->rawValue().toBool();
221void AudioOutput::_applyEngineSettings()
223 if (_engine->state() != QTextToSpeech::State::Ready) {
227 const QLocale defaultLocale(
"en_US");
228 if (_engine->availableLocales().contains(defaultLocale)) {
229 _engine->setLocale(defaultLocale);
233 const QList<QVoice> voices = _engine->availableVoices();
234 if (!voices.isEmpty()) {
235 _engine->setVoice(voices.constFirst());
238 _speakCapable = _engine->engineCapabilities().testFlag(QTextToSpeech::Capability::Speak);
241void AudioOutput::_setVolume()
243 const bool muted = _mutedSetting();
244 const double volume = muted ? 0.0 : _volumeSetting();
247 if (qFuzzyCompare(1.0 + volume, 1.0 + _lastVolume)) {
250 _lastVolume = volume;
253 const double normalizedVolume = volume / 100.0;
254 (void) QMetaObject::invokeMethod(_engine, [
this, volume, normalizedVolume]() {
257 _engine->stop(QTextToSpeech::BoundaryHint::Immediate);
260 _engine->setVolume(normalizedVolume);
262 qCDebug(AudioOutputLog) <<
"AudioOutput volume set to:" << volume <<
"%";
269 qCWarning(AudioOutputLog) <<
"AudioOutput not initialized. Call init() before using say().";
274 if (_volumeSetting() <= 0.0 || _mutedSetting()) {
278 if (!_speakCapable) {
279 qCWarning(AudioOutputLog) <<
"Speech Not Supported:" << text;
283 QString outText = _fixTextMessageForAudio(text);
286 outText = tr(
"%1").arg(outText);
289 if (outText.isEmpty()) {
294 (void) QMetaObject::invokeMethod(_engine, [
this, outText]() {
295 if (_textQueueSize >= kMaxTextQueueSize) {
296 _engine->stop(QTextToSpeech::BoundaryHint::Immediate);
298 qCWarning(AudioOutputLog) <<
"Text queue exceeded maximum size. Stopped current speech.";
301 const qsizetype index = _engine->enqueue(outText);
303 qCWarning(AudioOutputLog) <<
"Failed to enqueue speech. State:" << _engine->state()
304 <<
"Reason:" << _engine->errorReason();
309 qCDebug(AudioOutputLog) <<
"Enqueued text with index:" << index <<
", Queue Size:" << _textQueueSize;
316 qCWarning(AudioOutputLog) <<
"AudioOutput not initialized. Call init() before using testAudioOutput().";
321 _engine->stop(QTextToSpeech::BoundaryHint::Immediate);
324 const QString testText = tr(
"Audio test. Volume is %1 percent").arg(_volumeSetting(), 0,
'f', 1);
328QString AudioOutput::_fixTextMessageForAudio(
const QString &
string)
330 QString result = string;
332 result = _replaceNegativeSigns(result);
333 result = _replaceAbbreviations(result);
334 result = _replaceDecimalPoints(result);
335 result = _replaceMeters(result);
336 result = _convertMilliseconds(result);
340QString AudioOutput::_spokenAbbreviation(
const QString& token)
342 const auto it = _textHash.constFind(token.toUpper());
343 if (it != _textHash.constEnd()) {
347 if (!_spelledAcronyms.contains(token)) {
352 spelled.reserve(token.size() * 2);
353 for (
const QChar c : token) {
355 spelled.append(QLatin1Char(
'.'));
360QString AudioOutput::_replaceAbbreviations(
const QString &input)
363 static const QRegularExpression tokenRegex(
364 QStringLiteral(
"(?<![A-Za-z0-9_])([A-Za-z][A-Za-z0-9_]*?)([0-9]*)(?![A-Za-z0-9_])"));
367 output.reserve(input.size());
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()) {
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));
384 last = match.capturedEnd();
386 output.append(QStringView(input).mid(last));
391QString AudioOutput::_replaceNegativeSigns(
const QString &input)
393 static const QRegularExpression negNumRegex(QStringLiteral(
"(?<![A-Za-z0-9_])-\\s*(?=\\d)"));
395 QString output = input;
396 (void) output.replace(negNumRegex,
"negative ");
400QString AudioOutput::_replaceDecimalPoints(
const QString &input)
402 static const QRegularExpression realNumRegex(QStringLiteral(
"([0-9]+)(\\.)([0-9]+)"));
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 "));
410 realNumRegexMatch = realNumRegex.match(output);
416QString AudioOutput::_replaceMeters(
const QString &input)
418 static const QRegularExpression realNumMeterRegex(QStringLiteral(
"[0-9]*\\.?[0-9]\\s?(m)([^A-Za-z]|$)"));
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"));
426 realNumMeterRegexMatch = realNumMeterRegex.match(output);
432QString AudioOutput::_convertMilliseconds(
const QString &input)
434 QString result = input;
438 if (_getMillisecondString(input, match, number) && (number >= 1000)) {
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" :
"");
445 (void) newNumber.append(QStringLiteral(
" and %1 millisecond").arg(ms));
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" :
"");
452 (void) newNumber.append(QStringLiteral(
" and %1 second%2").arg(seconds).arg(seconds > 1 ?
"s" :
""));
455 (void) result.replace(match, newNumber);
461bool AudioOutput::_getMillisecondString(
const QString &
string, QString &match,
int &number)
463 static const QRegularExpression msRegex(
"((?<number>[0-9]+)ms)");
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();
Q_APPLICATION_STATIC(AudioOutput, _audioOutput)
#define QGC_LOGGING_CATEGORY(name, categoryStr)
The AudioOutput class provides functionality for audio output using text-to-speech.
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.
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)