swift
Loading...
Searching...
No Matches
afvclient.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2019 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
5
6#include <algorithm>
7
8#ifdef Q_OS_WIN
9# include "comdef.h"
10#endif
11
12#include "core/application.h"
18#include "misc/stringutils.h"
19#include "misc/threadutils.h"
20#include "misc/verify.h"
22
23using namespace swift::core::context;
24using namespace swift::core::afv::audio;
25using namespace swift::core::afv::connection;
26using namespace swift::misc;
27using namespace swift::misc::audio;
28using namespace swift::misc::physical_quantities;
29using namespace swift::misc::simulation;
30using namespace swift::misc::aviation;
31using namespace swift::sound;
32using namespace swift::sound::sample_provider;
33
34namespace swift::core::afv::clients
35{
37 {
39 return cats;
40 }
41
43 : CContinuousWorker(owner, "CAfvClient"), CIdentifiable("CAfvClient"),
44 m_connection(new CClientConnection(apiServer, this)), m_input(new CInput(SampleRate, this)),
45 m_output(new COutput(this)), m_voiceServerTimer(new QTimer(this))
46 {
47 this->setObjectName("AFV client: " + apiServer);
48 m_connection->setReceiveAudio(false);
49
50 connect(m_input, &CInput::opusDataAvailable, this, &CAfvClient::opusDataAvailable);
51 connect(m_input, &CInput::inputVolumeStream, this, &CAfvClient::inputVolumeStream);
52
53 connect(m_output, &COutput::outputVolumeStream, this, &CAfvClient::outputVolumeStream);
54 connect(m_connection, &CClientConnection::audioReceived, this, &CAfvClient::audioOutDataAvailable);
55 connect(m_voiceServerTimer, &QTimer::timeout, this, &CAfvClient::onTimerUpdate);
56
57 // deferred init - use swift::misc:: singleShot to call in correct thread, "myself" NOT needed
58 swift::misc::singleShot(1000, this, [=, this] { this->deferredInit(); });
59 }
60
62 {
63 QMutexLocker lock(&m_mutexCallsign);
64 return m_callsign;
65 }
66
67 void CAfvClient::setCallsign(const QString &callsign)
68 {
69 QMutexLocker lock(&m_mutexCallsign);
70 m_callsign = callsign;
71 }
72
74 {
75 QMutexLocker lock(&m_mutexConnection);
76 return m_connection->isConnected();
77 }
78
79 void CAfvClient::initTransceivers()
80 {
81 {
82 QMutexLocker lock(&m_mutexTransceivers);
83 m_transceivers = { { .id = 0,
84 .frequencyHz = UniCom,
85 .LatDeg = 48.5,
86 .LonDeg = 11.5,
87 .HeightMslM = 1000.0,
88 .HeightAglM = 1000.0 },
89 { .id = 1,
90 .frequencyHz = UniCom,
91 .LatDeg = 48.5,
92 .LonDeg = 11.5,
93 .HeightMslM = 1000.0,
94 .HeightAglM = 1000.0 } };
95
96 m_enabledTransceivers = { 0, 1 };
97 m_transmittingTransceivers = { { 0 } }; // TxTransceiverDto
98 }
99
100 // init with context values
101 this->connectWithContexts();
102
103 // update from context
104 this->onTimerUpdate();
105 }
106
107 void CAfvClient::connectWithContexts()
108 {
109 if (m_connectedWithContext)
110 {
111 return;
112 }
113 if (!hasContexts())
114 {
115 return;
116 }
117
118 // Disconnect all previously connect signals between the AfvClient and the required contexts
119 for (auto *context : QVector<QObject *> { sApp->getIContextOwnAircraft(), sApp->getIContextNetwork() })
120 {
121 this->disconnect(context);
122 context->disconnect(this);
123 }
124
126 &CAfvClient::onUpdateTransceiversFromContext, Qt::QueuedConnection);
128 &CAfvClient::toggleTransmissionCapability, Qt::QueuedConnection);
129
130 m_connectedWithContext = true;
131 }
132
133 void CAfvClient::fetchSimulatorSettings()
134 {
135 // call that in correct thread
136 if (!hasContexts())
137 {
138 return;
139 }
140
142 {
143 // Method needs to be executed in the context thread
144 QPointer<CAfvClient> myself(this);
146 if (myself)
147 {
148 this->fetchSimulatorSettings();
149 }
150 });
151 return;
152 }
153
154 const bool integrated = sApp->getIContextSimulator()->getSimulatorSettings().isComIntegrated();
155 const bool changed = integrated != m_integratedComUnit;
156
157 m_integratedComUnit = integrated;
158 if (changed)
159 {
160 emit this->updatedFromOwnAircraftCockpit();
161 }
162 }
163
164 void CAfvClient::connectTo(const QString &cid, const QString &password, const QString &callsign,
165 const QString &client)
166 {
168 {
169 // Method needs to be executed in the object thread since it will create new QObject children
170 QPointer<CAfvClient> myself(this);
171 QMetaObject::invokeMethod(this, [=, this]() {
172 if (myself)
173 {
174 connectTo(cid, password, callsign, client);
175 }
176 });
177 return;
178 }
179
180 // called in CAfvClient thread
181 this->connectWithContexts();
182 this->setCallsign(callsign);
183
184 QPointer<CAfvClient> myself(this);
185 if (!this->isConnected() && m_retryConnectAttempt == 0)
186 {
187 // check if connect simply did NOT receive an answer
188 QTimer::singleShot(20 * 1000, this, [=, this] {
189 if (!myself)
190 {
191 return;
192 }
193 if (m_retryConnectAttempt > 0)
194 {
195 return;
196 } // already handled
197
198 // this will reconnect ONLY if not already connected
199 this->retryConnectTo(cid, password, callsign, client, QStringLiteral("No connection afer 20secs"));
200 });
201 }
202
203 // thread safe connect
204 {
205 QMutexLocker lock(&m_mutexConnection);
206
207 // async connection
208 m_connection->connectTo(
209 cid, password, callsign, client,
210 { // this is the callback when the connection has been established
211 this, [=, this](bool authenticated) {
212 if (!myself)
213 {
214 return;
215 } // cppcheck-suppress knownConditionTrueFalse
216
217 // HF stations aliased
218 const QVector<StationDto> aliasedStations = m_connection->getAllAliasedStations();
219 this->setAliasedStations(aliasedStations); // threadsafe
220 this->onTimerUpdate();
221
222 // const bool isConnected = this->isConnected(); // threadsafe
223 if (authenticated)
224 {
225 // restart timer, normally it should be started already, paranoia
226 // as I run in "my thread" starting timer should be OK
227 {
228 QMutexLocker lock2(&m_mutex);
229 if (m_voiceServerTimer)
230 {
231 m_voiceServerTimer->start(PositionUpdatesMs);
232 }
233 }
234 m_retryConnectAttempt = 0;
235 emit this->connectionStatusChanged(Connected);
236 }
237 else
238 {
239 myself->retryConnectTo(
240 cid, password, callsign, client,
241 QStringLiteral("AFV authentication failed for '%1' callsign '%2'").arg(cid, callsign));
242 emit this->connectionStatusChanged(Disconnected);
243 }
244 } });
245 }
246 }
247
249 {
251 {
252 // Method needs to be executed in the object thread since it will create new QObject children
253 QPointer<CAfvClient> myself(this);
254 QMetaObject::invokeMethod(this, [=, this]() {
255 if (myself)
256 {
257 disconnectFrom(stop);
258 }
259 });
260 return;
261 }
262
263 // we intentionally DO NOT STOP the timer here, but keep it for preset (own aircraft pos.)
264 // threadsafe
265 {
266 QMutexLocker lock(&m_mutexConnection);
267 m_connection->disconnectFrom();
268 }
269
270 m_heartBeatFailures = 0;
271 m_retryConnectAttempt = 0;
272 m_fsdConnectMismatches = 0;
273
274 emit connectionStatusChanged(Disconnected);
275
276 if (stop)
277 {
278 this->stopAudio();
279 }
280 }
281
286
291
293 {
294 QMutexLocker lock(&m_mutexSampleProviders);
295 if (m_soundcardSampleProvider)
296 {
297 m_soundcardSampleProvider->setBypassEffects(value);
298 }
299 }
300
302 {
303 const int v = this->getNormalizedMasterOutputVolume();
304 return v < 1;
305 }
306
308 {
309 if (this->isOutputMuted() == mute)
310 {
311 return;
312 }
313 this->setNormalizedMasterOutputVolume(mute ? 0 : 50);
314 emit this->changedOutputMute(mute);
315 }
316
318 {
319 const CAudioDeviceInfo inputDevice = this->getInputDevice();
320 const CAudioDeviceInfo outputDevice = this->getOutputDevice();
321 this->startAudio(inputDevice, outputDevice);
322 }
323
324 void CAfvClient::startAudio(const CAudioDeviceInfo &inputDevice, const CAudioDeviceInfo &outputDevice)
325 {
326 if (QThread::currentThread() != this->thread())
327 {
328 // Method needs to be executed in the object thread since it will create new QObject children
329 QPointer<CAfvClient> myself(this);
330 QMetaObject::invokeMethod(this, [=, this]() {
331 if (myself)
332 {
333 startAudio(inputDevice, outputDevice);
334 }
335 });
336 return;
337 }
338
339 const CAudioDeviceInfo useInputDevice =
340 inputDevice.isValid() ? inputDevice : CAudioDeviceInfo::getDefaultInputDevice();
341 const CAudioDeviceInfo useOutputDevice =
342 outputDevice.isValid() ? outputDevice : CAudioDeviceInfo::getDefaultOutputDevice();
343
344 if (!useOutputDevice.isValid() || !useOutputDevice.isOutputDevice())
345 {
346 CLogMessage(this).error(u"No audio output device found. Audio For VATSIM (AFV) "
347 "is disabled");
348 return;
349 }
350
351 // The input device is allowed to be invalid as AFV is also usable with "receive only".
352
353 if (m_isStarted)
354 {
355 if (this->usesSameDevices(useInputDevice, useOutputDevice))
356 {
357 CLogMessage(this).info(u"Client already started for '%1'/'%2'")
358 << useInputDevice.getName() << useOutputDevice.getName();
359 return;
360 }
361 this->stopAudio();
362 }
363
364 this->initTransceivers();
365
366 // threadsafe block
367 {
368 // lock block 1
369 {
370 QMutexLocker lock { &m_mutexSampleProviders };
371 if (m_soundcardSampleProvider)
372 {
373 m_soundcardSampleProvider->disconnect();
374 m_soundcardSampleProvider->deleteLater();
375 }
376 m_soundcardSampleProvider = new CSoundcardSampleProvider(SampleRate, allTransceiverIds(), this);
377 connect(m_soundcardSampleProvider, &CSoundcardSampleProvider::receivingCallsignsChanged, this,
378 &CAfvClient::onReceivingCallsignsChanged);
379
380 if (m_outputSampleProvider)
381 {
382 m_outputSampleProvider->deleteLater();
383 }
384 m_outputSampleProvider = new CVolumeSampleProvider(m_soundcardSampleProvider, this);
385 // m_outputSampleProvider->setGainRatio(outputVolume); // 2021-09 LT Disabled. Output volume is
386 // controlled independently for COM1/2
387 }
388
389 // lock block 2
390 {
391 QMutexLocker lock(&m_mutex);
392
393 m_output->start(useOutputDevice, m_outputSampleProvider);
394
395 if (useInputDevice.getType() != CAudioDeviceInfo::Unknown)
396 {
397 m_input->start(useInputDevice);
398 }
399 else
400 {
401 CLogMessage(this).warning(
402 u"No audio input device was found. Audio for VATSIM (AFV) will run in receive-only mode.");
403 }
404
405 // runs in correct thread
406 m_voiceServerTimer->start(PositionUpdatesMs); // start for preset values
407 }
408 }
409
410 this->setReceiveAudio(true); // threadsafe
411
412 this->onSettingsChanged(); // make sure all settings are applied
413 m_isStarted = true;
414 CLogMessage(this).info(u"Started [Input: %1] [Output: %2]")
415 << useInputDevice.getName() << useOutputDevice.getName();
416
417 this->onTimerUpdate(); // update values
418
419 emit this->startedAudio(useInputDevice, useOutputDevice);
420
421 if (this->isOutputMuted())
422 {
423 // un-mute after startup
424 this->setOutputMuted(false);
425 }
426 }
427
428 void CAfvClient::startAudio(const QString &inputDeviceName, const QString &outputDeviceName)
429 {
432 this->startAudio(i, o);
433 }
434
436 {
437 if (QThread::currentThread() != this->thread())
438 {
439 // Method needs to be executed in the object thread since it will create new QObject children
440 QPointer<CAfvClient> myself(this);
441 QMetaObject::invokeMethod(this, [=, this]() {
442 if (myself) stopAudio();
443 });
444 return;
445 }
446
447 if (!m_isStarted)
448 {
449 CLogMessage(this).info(u"Client was NOT started, not stopping!");
450 return;
451 }
452
453 m_isStarted = false;
454 this->setReceiveAudio(false); // threadsafe
455
456 // stop input/output
457 {
458 QMutexLocker lock { &m_mutex };
459 m_input->stop();
460 m_output->stop();
461 }
462 CLogMessage(this).info(u"AFV Client stopped");
463
464 if (this->isOutputMuted())
465 {
466 this->setOutputMuted(false);
467 }
468
469 emit this->inputVolumePeakVU(0.0);
470 emit this->outputVolumePeakVU(0.0);
471 emit this->stoppedAudio();
472 }
473
475 {
476 if (!m_isStarted)
477 {
478 // just need to start
479 this->startAudio();
480 return;
481 }
482
483 this->stopAudio();
484 QPointer<CAfvClient> myself(this);
485 QTimer::singleShot(1000, this, [=] {
486 if (myself)
487 {
488 myself->startAudio();
489 }
490 });
491 }
492
493 /* disabled because NOT used
494 double CAfvClient::getDeviceInputVolume() const
495 {
496 if (m_input) { return m_input->getDeviceInputVolume(); }
497 return 0;
498 }
499
500 bool CAfvClient::setDeviceInputVolume(double volume)
501 {
502 if (m_input) { return m_input->setDeviceInputVolume(volume); }
503 return false;
504 }
505
506 double CAfvClient::getDeviceOutputVolume() const
507 {
508 if (m_output) { return m_output->getDeviceOutputVolume(); }
509 return 0;
510 }
511
512 bool CAfvClient::setDeviceOutputVolume(double volume)
513 {
514 if (m_output) { return m_output->setDeviceOutputVolume(volume); }
515 return false;
516 }
517 */
518
520 {
521 QMutexLocker lock(&m_mutexConnection);
522 if (!m_connection)
523 {
524 return;
525 }
526 m_connection->setReceiveAudio(receive);
527 }
528
529 void CAfvClient::enableTransceiver(quint16 id, bool enable)
530 {
531 {
532 QMutexLocker lock(&m_mutexTransceivers);
533 if (enable)
534 {
535 m_enabledTransceivers.insert(id);
536 }
537 else
538 {
539 m_enabledTransceivers.remove(id);
540 }
541 }
542
543 this->updateTransceivers();
544 }
545
547 {
548 this->enableTransceiver(comUnitToTransceiverId(comUnit), enable);
549 }
550
551 bool CAfvClient::isEnabledTransceiver(quint16 id) const
552 {
553 // we double check, enabled and exist!
554 const auto enabledTransceivers = this->getEnabledTransceivers(); // threadsafe
555 if (!enabledTransceivers.contains(id))
556 {
557 return false;
558 }
559
560 const auto transceivers = this->getTransceivers(); // threadsafe
561 return std::ranges::any_of(transceivers, [&id](const TransceiverDto &dto) { return dto.id == id; });
562 }
563
565 {
566 return this->isEnabledTransceiver(comUnitToTransceiverId(comUnit));
567 }
568
569 void CAfvClient::updateComFrequency(quint16 id, quint32 frequencyHz)
570 {
571 if (id != 0 && id != 1)
572 {
573 return;
574 }
575
576 // Fix rounding issues like 128074999 Hz -> 128075000 Hz
577 quint32 roundedFrequencyHz = static_cast<quint32>(qRound(frequencyHz / 1000.0)) * 1000;
578 roundedFrequencyHz = this->getAliasFrequencyHz(roundedFrequencyHz);
579
580 bool update = false;
581 {
582 QMutexLocker lockTransceivers(&m_mutexTransceivers);
583 if (m_transceivers.size() >= id + 1)
584 {
585 if (m_transceivers[id].frequencyHz != roundedFrequencyHz)
586 {
587 update = true;
588 m_transceivers[id].frequencyHz = roundedFrequencyHz;
589 }
590 }
591 }
592
593 // outside lock to avoid deadlock
594 if (update)
595 {
596 this->updateTransceivers(false); // no frequency update
597 }
598 }
599
601 {
602 const auto freqHz = static_cast<quint32>(comFrequency.valueInteger(CFrequencyUnit::Hz()));
603 this->updateComFrequency(comUnitToTransceiverId(comUnit), freqHz);
604 }
605
607 {
608 this->updateComFrequency(comUnit, comSystem.getFrequencyActive());
609 }
610
611 void CAfvClient::updatePosition(double latitudeDeg, double longitudeDeg, double heightMeters)
612 {
613 QMutexLocker lock(&m_mutexTransceivers);
614 for (TransceiverDto &transceiver : m_transceivers)
615 {
616 transceiver.LatDeg = latitudeDeg;
617 transceiver.LonDeg = longitudeDeg;
618 transceiver.HeightAglM = heightMeters;
619 transceiver.HeightMslM = heightMeters;
620 }
621 }
622
623 void CAfvClient::updateTransceivers(bool updateFrequencies)
624 {
625 // also update if NOT connected, values will be preset
626
627 if (hasContexts())
628 {
629 const CSimulatedAircraft ownAircraft = sApp->getIContextOwnAircraft()->getOwnAircraft();
630 this->updatePosition(ownAircraft.latitude().value(CAngleUnit::deg()),
631 ownAircraft.longitude().value(CAngleUnit::deg()),
632 ownAircraft.getAltitude().value(CLengthUnit::ft()));
633
634 if (updateFrequencies)
635 {
636 this->updateComFrequency(CComSystem::Com1, ownAircraft.getCom1System());
637 this->updateComFrequency(CComSystem::Com2, ownAircraft.getCom2System());
638 }
639 }
640
641 // threadsafe copies
642 const auto transceivers = this->getTransceivers();
643 const auto enabledTransceivers = this->getEnabledTransceivers();
644 const QString callsign = this->getCallsign(); // threadsafe
645
646 // transceivers
647 QVector<TransceiverDto> newEnabledTransceivers;
648 for (const TransceiverDto &transceiver : transceivers)
649 {
650 if (enabledTransceivers.contains(transceiver.id))
651 {
652 newEnabledTransceivers.push_back(transceiver);
653 }
654 }
655
656 // in connection and soundcard only use the enabled transceivers
657 {
658 QMutexLocker lock(&m_mutexConnection);
659 if (m_connection)
660 {
661 m_connection->updateTransceivers(callsign, newEnabledTransceivers);
662 }
663 }
664 {
665 QMutexLocker lock(&m_mutexSampleProviders);
666 if (m_soundcardSampleProvider)
667 {
668 m_soundcardSampleProvider->updateRadioTransceivers(newEnabledTransceivers);
669 }
670 }
671 }
672
673 void CAfvClient::setTransmittingTransceiver(quint16 transceiverID)
674 {
675 const TxTransceiverDto tx = { transceiverID };
676 this->setTransmittingTransceivers({ tx });
677 }
678
680 {
681 this->setTransmittingTransceiver(comUnitToTransceiverId(comUnit));
682 }
683
685 {
686 QMutexLocker lock(&m_mutexTransceivers);
687 m_transmittingTransceivers = transceivers;
688 }
689
691 {
692 QMutexLocker lock(&m_mutexTransceivers);
693 return std::ranges::any_of(m_transmittingTransceivers,
694 [&id](const TxTransceiverDto &dto) { return dto.id == id; });
695 }
696
698 {
699 return this->isTransmittingTransceiver(comUnitToTransceiverId(comUnit));
700 }
701
702 void CAfvClient::setRxTx(bool rx1, bool tx1, bool rx2, bool tx2)
703 {
705 if (tx1)
706 {
707 const TxTransceiverDto tx = { comUnitToTransceiverId(CComSystem::Com1) };
708 txs.push_back(tx);
709 }
710 if (tx2)
711 {
712 const TxTransceiverDto tx = { comUnitToTransceiverId(CComSystem::Com2) };
713 txs.push_back(tx);
714 }
716
717 QSet<quint16> enabledTransceivers;
718 if (rx1 || tx1)
719 {
720 enabledTransceivers.insert(comUnitToTransceiverId(CComSystem::Com1));
721 }
722
723 if (rx2 || tx2)
724 {
725 enabledTransceivers.insert(comUnitToTransceiverId(CComSystem::Com2));
726 }
727
728 {
729 QMutexLocker lock(&m_mutexTransceivers);
730 m_enabledTransceivers = enabledTransceivers;
731 }
732
733 // force update
734 this->onTimerUpdate();
735 }
736
737 void CAfvClient::getRxTx(bool &rx1, bool &tx1, bool &rx2, bool &tx2) const
738 {
739 rx1 = false;
740 rx2 = false;
741 tx1 = false;
742 tx2 = false;
743
744 const QSet<quint16> enabled = getEnabledTransceivers();
745 rx1 = enabled.contains(comUnitToTransceiverId(CComSystem::Com1));
746 rx2 = enabled.contains(comUnitToTransceiverId(CComSystem::Com2));
747
749 for (const TxTransceiverDto &dto : transmits)
750 {
751 if (dto.id == comUnitToTransceiverId(CComSystem::Com1))
752 {
753 tx1 = true;
754 }
755 if (dto.id == comUnitToTransceiverId(CComSystem::Com2))
756 {
757 tx2 = true;
758 }
759 }
760 }
761
763 {
764 QMutexLocker lock(&m_mutexTransceivers);
765 return m_transceivers;
766 }
767
769 {
770 QMutexLocker lock(&m_mutexTransceivers);
771 return m_enabledTransceivers;
772 }
773
775 {
776 QMutexLocker lock(&m_mutexTransceivers);
777 return m_transmittingTransceivers;
778 }
779
780 void CAfvClient::setPtt(bool active)
781 {
782 if (!m_isStarted)
783 {
784 CLogMessage(this).info(u"Voice client not started");
785 return;
786 }
787
788 if (active && m_disableTransmissionCapability)
789 {
790 // Block transmissions
791 return;
792 }
793
794 if (m_transmit == active)
795 {
796 return;
797 }
798 m_transmit = active;
799
800 // thread safe block
801 {
802 QMutexLocker lock(&m_mutexSampleProviders);
803 if (m_soundcardSampleProvider)
804 {
805 m_soundcardSampleProvider->pttUpdate(active, m_transmittingTransceivers);
806 }
807
819 }
820
821 emit this->ptt(active, this->identifier());
822 }
823
825 {
826 QMutexLocker lock(&m_mutex);
827 return m_inputVolumeDb;
828 }
829
830 bool CAfvClient::setInputVolumeDb(double valueDb)
831 {
833 {
834 // call in background thread of AFVClient to avoid lock issues
835 QPointer<CAfvClient> myself(this);
836 QTimer::singleShot(0, this, [=] {
837 if (!myself || !CAfvClient::hasContexts())
838 {
839 return;
840 }
841 myself->setInputVolumeDb(valueDb);
842 });
843 return true; // not exactly "true" as we do it async
844 }
845
846 if (valueDb > MaxDbIn)
847 {
848 valueDb = MaxDbIn;
849 }
850 else if (valueDb < MinDbIn)
851 {
852 valueDb = MinDbIn;
853 }
854
855 QMutexLocker lock(&m_mutex);
856 bool changed = !qFuzzyCompare(m_inputVolumeDb, valueDb);
857 if (changed)
858 {
859 m_inputVolumeDb = valueDb;
860 if (m_input)
861 {
862 const double gainRatio = qPow(10, valueDb / 20.0);
863 changed = m_input->setGainRatio(gainRatio);
864 }
865 }
866 return changed;
867 }
868
870 {
871 QMutexLocker lock(&m_mutexVolume);
872 if (comUnit == CComSystem::Com1) return m_outputVolumeDbCom1;
873 if (comUnit == CComSystem::Com2) return m_outputVolumeDbCom2;
874 qFatal("Invalid COM unit");
875 return 0;
876 }
877
879 {
880 QMutexLocker lock(&m_mutexVolume);
881 if (comUnit == CComSystem::Com1) return m_outputGainRatioCom1;
882 if (comUnit == CComSystem::Com2) return m_outputGainRatioCom2;
883 qFatal("Invalid COM unit");
884 return 0;
885 }
886
888 {
889 const double db = this->getInputVolumeDb();
890 const double range = MaxDbIn - MinDbIn;
891 const int i = qRound((db - MinDbIn) / range * 100);
892 return i;
893 }
894
896 {
897 QMutexLocker lock(&m_mutexVolume);
898 return m_outputMasterVolumeNormalized;
899 }
900
902 {
903 QMutexLocker lock(&m_mutexVolume);
904 if (comUnit == CComSystem::Com1)
905 {
906 return m_outputVolumeCom1Normalized;
907 }
908 if (comUnit == CComSystem::Com2)
909 {
910 return m_outputVolumeCom2Normalized;
911 }
912 qFatal("Invalid ComUnit");
913 return 0;
914 }
915
917 {
918 if (volume < 0)
919 {
920 volume = 0;
921 }
922 else if (volume > 100)
923 {
924 volume = 100;
925 }
926 const double range = MaxDbIn - MinDbIn;
927 const double dB = MinDbIn + (volume * range / 100.0);
928
929 // converted to MinDbIn-MaxDbIn
930 return this->setInputVolumeDb(dB);
931 }
932
934 {
936 {
937 // call in background thread of AFVClient to avoid lock issues
938 QPointer<CAfvClient> myself(this);
939 QTimer::singleShot(0, this, [=] {
940 if (!myself || !CAfvClient::hasContexts())
941 {
942 return;
943 }
944 myself->setNormalizedMasterOutputVolume(volume);
945 });
946 return true; // not exactly "true" as we do it async
947 }
948
949 bool changed = false;
950 {
951 QMutexLocker lock(&m_mutexVolume);
952 changed = m_outputMasterVolumeNormalized != volume;
953 if (changed)
954 {
955 m_outputMasterVolumeNormalized = volume;
956 }
957 }
958
959 // Trigger update of com volumes
960 int com1Normalized = getNormalizedComOutputVolume(CComSystem::Com1);
961 int com2Normalized = getNormalizedComOutputVolume(CComSystem::Com2);
962 setNormalizedComOutputVolume(CComSystem::Com1, com1Normalized);
963 setNormalizedComOutputVolume(CComSystem::Com2, com2Normalized);
964
965 return changed;
966 }
967
969 {
970 if (volume < 0)
971 {
972 volume = 0;
973 }
974 else if (volume > 100)
975 {
976 volume = 100;
977 }
978
979 // Save original volume
980 if (comUnit == CComSystem::Com1)
981 {
982 m_outputVolumeCom1Normalized = volume;
983 }
984 else if (comUnit == CComSystem::Com2)
985 {
986 m_outputVolumeCom2Normalized = volume;
987 }
988 else
989 {
990 qFatal("Invalid ComUnit");
991 }
992
993 // Calculate volume relative to master-output volume
994 volume = qRound((double)volume * getNormalizedMasterOutputVolume() / 100);
995
996 // Asymetric
997 double range = MaxDbOut;
998 double dB = 0;
999 if (volume >= 50)
1000 {
1001 volume -= 50;
1002 }
1003 else
1004 {
1005 dB = MinDbOut;
1006 range = qAbs(MinDbOut);
1007 }
1008 dB += (volume * range / 50.0);
1009
1010 // converted to MinDbOut-MaxDbOut
1011 return this->setComOutputVolumeDb(comUnit, dB);
1012 }
1013
1015 {
1016 QMutexLocker lock(&m_mutexInputStream);
1017 return m_inputVolumeStream.PeakVU;
1018 }
1019
1021 {
1022 QMutexLocker lock(&m_mutexOutputStream);
1023 return m_outputVolumeStream.PeakVU;
1024 }
1025
1026 void CAfvClient::opusDataAvailable(const OpusDataAvailableArgs &args)
1027 {
1028 const bool transmit = m_transmit;
1029 const bool loopback = m_loopbackOn;
1030 const bool transmitHistory = m_transmitHistory; // threadsafe
1031 const auto transceivers = this->getTransceivers();
1032
1033 if (loopback && transmit)
1034 {
1035 IAudioDto audioData;
1036 audioData.audio = QByteArray(args.audio.data(), args.audio.size());
1037 audioData.callsign = QStringLiteral("loopback");
1038 audioData.lastPacket = false;
1039 audioData.sequenceCounter = 0;
1040
1041 const RxTransceiverDto com1 = { .id = 0,
1042 .frequency = transceivers.size() > 0 ? transceivers[0].frequencyHz : UniCom,
1043 .distanceRatio = 1.0 };
1044 const RxTransceiverDto com2 = { .id = 1,
1045 .frequency = transceivers.size() > 1 ? transceivers[1].frequencyHz : UniCom,
1046 .distanceRatio = 1.0 };
1047
1048 QMutexLocker lock(&m_mutexSampleProviders);
1049 m_soundcardSampleProvider->addOpusSamples(audioData, { com1, com2 });
1050 return;
1051 }
1052
1053 if (!this->isConnected())
1054 {
1055 return;
1056 } // threadsafe
1057
1058 const QString callsign = this->getCallsign(); // threadsafe
1059 const auto transmittingTransceivers = this->getTransmittingTransceivers(); // threadsafe
1060 if (!transmittingTransceivers.isEmpty())
1061 {
1062 if (transmit)
1063 {
1065 dto.callsign = callsign.toStdString();
1067 dto.audio = std::vector<char>(args.audio.begin(), args.audio.end());
1068 dto.lastPacket = false;
1069 dto.transceivers =
1070 std::vector<TxTransceiverDto>(transmittingTransceivers.begin(), transmittingTransceivers.end());
1071 QMutexLocker lock(&m_mutexConnection);
1072 m_connection->sendToVoiceServer(dto);
1073 }
1074
1075 if (!transmit && transmitHistory)
1076 {
1078 dto.callsign = callsign.toStdString();
1080 dto.audio = std::vector<char>(args.audio.begin(), args.audio.end());
1081 dto.lastPacket = true;
1082 dto.transceivers =
1083 std::vector<TxTransceiverDto>(transmittingTransceivers.begin(), transmittingTransceivers.end());
1084 QMutexLocker lock(&m_mutexConnection);
1085 m_connection->sendToVoiceServer(dto);
1086 }
1087 m_transmitHistory = transmit; // threadsafe
1088 }
1089 }
1090
1091 void CAfvClient::audioOutDataAvailable(const AudioRxOnTransceiversDto &dto)
1092 {
1093 IAudioDto audioData;
1094 audioData.audio = QByteArray(dto.audio.data(), static_cast<int>(dto.audio.size()));
1095 audioData.callsign = QString::fromStdString(dto.callsign);
1096 audioData.lastPacket = dto.lastPacket;
1097 audioData.sequenceCounter = dto.sequenceCounter;
1098
1099 QMutexLocker lock(&m_mutexSampleProviders);
1100 m_soundcardSampleProvider->addOpusSamples(
1101 audioData, QVector<RxTransceiverDto>(dto.transceivers.begin(), dto.transceivers.end()));
1102 }
1103
1104 void CAfvClient::inputVolumeStream(const InputVolumeStreamArgs &args)
1105 {
1106 // thread safe block
1107 {
1108 QMutexLocker lock(&m_mutexInputStream);
1109 m_inputVolumeStream = args;
1110 }
1111 emit inputVolumePeakVU(args.PeakVU);
1112 }
1113
1114 void CAfvClient::outputVolumeStream(const OutputVolumeStreamArgs &args)
1115 {
1116 // thread safe block
1117 {
1118 QMutexLocker lock(&m_mutexOutputStream);
1119 m_outputVolumeStream = args;
1120 }
1121 emit outputVolumePeakVU(args.PeakVU);
1122 }
1123
1125 {
1126 QMutexLocker lock(&m_mutex);
1127 if (!m_soundcardSampleProvider) return {};
1128 return m_soundcardSampleProvider->getReceivingCallsignsString(comUnitToTransceiverId(CComSystem::Com1));
1129 }
1130
1132 {
1133 QMutexLocker lock(&m_mutexSampleProviders);
1134 if (!m_soundcardSampleProvider) return {};
1135 return m_soundcardSampleProvider->getReceivingCallsignsString(comUnitToTransceiverId(CComSystem::Com2));
1136 }
1137
1139 {
1140 QMutexLocker lock(&m_mutexSampleProviders);
1141 if (!m_soundcardSampleProvider) return {};
1142 return m_soundcardSampleProvider->getReceivingCallsigns(comUnitToTransceiverId(CComSystem::Com1));
1143 }
1144
1146 {
1147 QMutexLocker lock(&m_mutexSampleProviders);
1148 if (!m_soundcardSampleProvider) return {};
1149 return m_soundcardSampleProvider->getReceivingCallsigns(comUnitToTransceiverId(CComSystem::Com2));
1150 }
1151
1153 {
1154 QStringList coms;
1155 QMutexLocker lock(&m_mutexSampleProviders);
1156 if (!m_soundcardSampleProvider)
1157 {
1158 return { { QString(), QString() } };
1159 }
1160 coms << m_soundcardSampleProvider->getReceivingCallsignsString(comUnitToTransceiverId(CComSystem::Com1));
1161 coms << m_soundcardSampleProvider->getReceivingCallsignsString(comUnitToTransceiverId(CComSystem::Com2));
1162 return coms;
1163 }
1164
1166 {
1167 QMutexLocker lock(&m_mutexConnection);
1168 if (!m_connection)
1169 {
1170 return false;
1171 }
1172 return m_connection->updateVoiceServerUrl(url);
1173 }
1174
1176 {
1177 this->stopAudio();
1178 this->disconnectFrom();
1179 this->quitAndWait();
1180 Q_ASSERT_X(CThreadUtils::isInThisThread(this), Q_FUNC_INFO, "Needs to be back in current thread");
1181 }
1182
1184 {
1185 CLogMessage(this).info(u"Initialize AFV client in thread %1") << CThreadUtils::currentThreadInfo();
1186 }
1187
1189 {
1190#ifdef Q_OS_WIN
1191 if (m_winCoInitialized)
1192 {
1193 CoUninitialize();
1194 m_winCoInitialized = false;
1195 }
1196#endif
1197 }
1198
1199 void CAfvClient::onTimerUpdate()
1200 {
1201 if (hasContexts())
1202 {
1203 // for pilot client
1204 const CSimulatedAircraft aircraft = sApp->getIContextOwnAircraft()->getOwnAircraft();
1205 this->updateFromOwnAircraft(aircraft, false);
1206
1207 // disconnect if NOT connected
1208 this->autoLogoffWithoutFsdNetwork();
1209
1210 // get the settings in correct thread
1211 this->fetchSimulatorSettings();
1212 }
1213 else
1214 {
1215 // for AFV sample client
1216 this->updateTransceivers();
1217 }
1218
1219 // connection check
1220 this->checkServerHeartbeat();
1221 }
1222
1223 void CAfvClient::checkServerHeartbeat()
1224 {
1225 if (!this->isStarted())
1226 {
1227 return;
1228 }
1229 if (!this->isConnected())
1230 {
1231 return;
1232 }
1233
1234 if (this->isVoiceServerAlive())
1235 {
1236 m_heartBeatFailures = 0;
1237 return;
1238 }
1239
1240 // Heartbeat failure
1241 // it can happen that after connect we see an initial timeout
1242 const int failures = ++m_heartBeatFailures;
1243 if (failures < 2)
1244 {
1245 return;
1246 }
1247
1248 QString un;
1249 QString pw;
1250 QString cs;
1251 QString client;
1252 {
1253 QMutexLocker lock(&m_mutexConnection);
1254 un = m_connection->getUserName();
1255 pw = m_connection->getPassword();
1256 cs = m_connection->getCallsign();
1257 client = m_connection->getClient();
1258 }
1259 if (un.isEmpty() || pw.isEmpty())
1260 {
1261 return;
1262 }
1263
1264 // make sure we are disconnected
1265 if (this->isConnected())
1266 {
1267 this->disconnectFrom(false);
1268 }
1269
1270 QPointer<CAfvClient> myself(this);
1271 QTimer::singleShot(5 * 1000, this, [=, this] {
1272 if (!myself)
1273 {
1274 return;
1275 }
1276 const QString reason = QStringLiteral("Heartbeat failed %1 times").arg(failures);
1277 this->retryConnectTo(un, pw, cs, client, reason);
1278 });
1279 }
1280
1281 void CAfvClient::onSettingsChanged()
1282 {
1283 const CSettings audioSettings = m_audioSettings.get();
1284 const int iv = audioSettings.getInVolume();
1285 const int ov = audioSettings.getOutVolume();
1286 const int ov1 = audioSettings.getOutVolumeCom1();
1287 const int ov2 = audioSettings.getOutVolumeCom2();
1288
1289 this->setNormalizedInputVolume(iv);
1290 this->setNormalizedMasterOutputVolume(ov);
1291 this->setNormalizedComOutputVolume(CComSystem::Com1, ov1);
1292 this->setNormalizedComOutputVolume(CComSystem::Com2, ov2);
1293 this->setBypassEffects(!audioSettings.isAudioEffectsEnabled());
1294 }
1295
1296 void CAfvClient::autoLogoffWithoutFsdNetwork()
1297 {
1298 if (!hasContexts())
1299 {
1300 return;
1301 }
1302 if (!this->isConnected())
1303 {
1304 m_fsdConnectMismatches = 0;
1305 return;
1306 }
1307
1308 // AFV is connected
1310 {
1311 m_fsdConnectMismatches = 0;
1312 return;
1313 }
1314 if (++m_fsdConnectMismatches < 2)
1315 {
1316 return;
1317 } // avoid a single issue causing logoff
1318
1319 CLogMessage(this).warning(u"Auto logoff AFV client because FSD no longer connected");
1320 this->disconnectFrom();
1321 }
1322
1323 void CAfvClient::updateFromOwnAircraft(const CSimulatedAircraft &aircraft, bool withSignals)
1324 {
1325 if (!sApp || sApp->isShuttingDown())
1326 {
1327 return;
1328 }
1329
1330 TransceiverDto transceiverCom1;
1331 TransceiverDto transceiverCom2;
1332 transceiverCom1.id = comUnitToTransceiverId(CComSystem::Com1);
1333 transceiverCom2.id = comUnitToTransceiverId(CComSystem::Com2);
1334
1335 // position
1336 const double latDeg = aircraft.latitude().value(CAngleUnit::deg());
1337 const double lngDeg = aircraft.longitude().value(CAngleUnit::deg());
1338 const double altM = aircraft.getAltitude().value(CLengthUnit::m());
1339
1340 transceiverCom1.LatDeg = transceiverCom2.LatDeg = latDeg;
1341 transceiverCom1.LonDeg = transceiverCom2.LonDeg = lngDeg;
1342 transceiverCom1.HeightAglM = transceiverCom2.HeightAglM = altM;
1343 transceiverCom1.HeightMslM = transceiverCom2.HeightMslM = altM;
1344
1345 // enabled, rx/tx, frequency
1346 const CComSystem com1 = aircraft.getCom1System();
1347 const CComSystem com2 = aircraft.getCom2System();
1348 const quint32 f1 = static_cast<quint32>(com1.getFrequencyActive().valueInteger(CFrequencyUnit::Hz()));
1349 const quint32 f2 = static_cast<quint32>(com2.getFrequencyActive().valueInteger(CFrequencyUnit::Hz()));
1350
1351 transceiverCom1.frequencyHz = this->getAliasFrequencyHz(f1);
1352 transceiverCom2.frequencyHz = this->getAliasFrequencyHz(f2);
1353
1354 QVector<TransceiverDto> newEnabledTransceivers;
1355 if (m_integratedComUnit)
1356 {
1357 const bool tx1 = com1.isTransmitEnabled();
1358 const bool rx1 = com1.isReceiveEnabled();
1359 const bool tx2 = com2.isTransmitEnabled(); // we only allow one (1) transmit
1360 const bool rx2 = com2.isReceiveEnabled();
1361
1362 const int vol1 = com1.getVolumeReceive();
1363 const int vol2 = com2.getVolumeReceive();
1364
1365 this->setNormalizedComOutputVolume(CComSystem::Com1, vol1);
1366 this->setNormalizedComOutputVolume(CComSystem::Com2, vol2);
1367
1368 // enable, we currently treat receive as enable
1369 // flight sim cockpits normally use rx and tx
1370 // AFV uses tx and enable
1371 const bool e1 = rx1;
1372 const bool e2 = rx2;
1373
1374 // transceivers
1375 const QVector<TransceiverDto> newTransceivers { transceiverCom1, transceiverCom2 };
1376 QSet<quint16> newEnabledTransceiverIds;
1377 QVector<TxTransceiverDto> newTransmittingTransceivers;
1378 if (e1)
1379 {
1380 newEnabledTransceivers.push_back(transceiverCom1);
1381 newEnabledTransceiverIds.insert(transceiverCom1.id);
1382 }
1383 if (e2)
1384 {
1385 newEnabledTransceivers.push_back(transceiverCom2);
1386 newEnabledTransceiverIds.insert(transceiverCom2.id);
1387 }
1388
1389 // Transmitting transceivers, currently ALLOW ONLY ONE
1390 if (tx1 && e1)
1391 {
1392 newTransmittingTransceivers.push_back(transceiverCom1);
1393 }
1394 else if (tx2 && e2)
1395 {
1396 newTransmittingTransceivers.push_back(transceiverCom2);
1397 }
1398
1399 // lock and update
1400 {
1401 QMutexLocker lock(&m_mutexTransceivers);
1402 m_transceivers = newTransceivers;
1403 m_enabledTransceivers = newEnabledTransceiverIds;
1404 m_transmittingTransceivers = newTransmittingTransceivers;
1405 }
1406 }
1407 else
1408 {
1409 // update position and frequencies, but keep enabled as it was
1411 if (ids.contains(comUnitToTransceiverId(CComSystem::Com1)))
1412 {
1413 newEnabledTransceivers.push_back(transceiverCom1);
1414 }
1415
1416 if (ids.contains(comUnitToTransceiverId(CComSystem::Com2)))
1417 {
1418 newEnabledTransceivers.push_back(transceiverCom2);
1419 }
1420 }
1421
1422 // in connection and soundcard only use the enabled tarnsceivers
1423 const QString callsign = this->getCallsign(); // threadsafe
1424 {
1425 {
1426 QMutexLocker lock(&m_mutexConnection);
1427 if (m_connection)
1428 {
1429 // fire to network and forget
1430 m_connection->updateTransceivers(callsign, newEnabledTransceivers);
1431 }
1432 }
1433
1434 {
1435 QMutexLocker lock(&m_mutexSampleProviders);
1436 if (m_soundcardSampleProvider)
1437 {
1438 m_soundcardSampleProvider->updateRadioTransceivers(newEnabledTransceivers);
1439 }
1440 }
1441 }
1442
1443 if (withSignals)
1444 {
1445 emit this->updatedFromOwnAircraftCockpit();
1446 }
1447 }
1448
1449 void CAfvClient::onUpdateTransceiversFromContext(const CSimulatedAircraft &aircraft, const CIdentifier &originator)
1450 {
1451 if (originator == this->identifier())
1452 {
1453 return;
1454 }
1455 this->updateFromOwnAircraft(aircraft);
1456 }
1457
1458 void CAfvClient::onReceivingCallsignsChanged(const TransceiverReceivingCallsignsChangedArgs &args)
1459 {
1460 const CComSystem::ComUnit unit = transceiverIdToComUnit(args.transceiverID);
1461 CCallsignSet callsignsCom1;
1462 CCallsignSet callsignsCom2;
1463 switch (unit)
1464 {
1465 case CComSystem::Com1:
1466 default:
1467 callsignsCom1 = CCallsignSet(args.receivingCallsigns);
1468 callsignsCom2 = this->getReceivingCallsignsCom2();
1469 break;
1470
1471 case CComSystem::Com2:
1472 callsignsCom2 = CCallsignSet(args.receivingCallsigns);
1473 callsignsCom1 = this->getReceivingCallsignsCom1();
1474 break;
1475 }
1476
1477 emit this->receivedCallsignsChanged(callsignsCom1, callsignsCom2);
1478 emit this->receivingCallsignsChanged(args);
1479 }
1480
1481 void CAfvClient::retryConnectTo(const QString &cid, const QString &password, const QString &callsign,
1482 const QString &client, const QString &reason)
1483 {
1484 if (this->isConnected())
1485 {
1486 return;
1487 }
1488 m_retryConnectAttempt++;
1489
1490 const int retrySecs = qMin(3 * 60, m_retryConnectAttempt * 30);
1491 const CStatusMessage msg = CStatusMessage(this).validationError(reason + ". Retry in %1secs. Attempt %2.")
1492 << retrySecs << m_retryConnectAttempt;
1493 this->reconnectTo(cid, password, callsign, client, retrySecs * 1000, msg);
1494 }
1495
1496 void CAfvClient::reconnectTo(const QString &cid, const QString &password, const QString &callsign,
1497 const QString &client, int delayMs, const CStatusMessage &msg)
1498 {
1499 if (msg.isFailure())
1500 {
1502 emit this->afvConnectionFailure(msg);
1503 }
1504
1505 QPointer<CAfvClient> myself(this);
1506 QTimer::singleShot(delayMs, this, [=, this] {
1507 if (!myself)
1508 {
1509 return;
1510 }
1511 if (myself->isConnected())
1512 {
1513 return;
1514 }
1515 this->connectTo(cid, password, callsign, client);
1516 });
1517 }
1518
1519 void CAfvClient::toggleTransmissionCapability(bool disableTransmission)
1520 {
1521 if (m_disableTransmissionCapability == disableTransmission)
1522 {
1523 return;
1524 }
1525 m_disableTransmissionCapability = disableTransmission;
1526
1527 if (disableTransmission)
1528 {
1529 // Stop current transmissions
1530 setPtt(false);
1531 }
1532 }
1533
1534 QVector<StationDto> CAfvClient::getAliasedStations() const
1535 {
1536 QMutexLocker lock(&m_mutex);
1537 return m_aliasedStations;
1538 }
1539
1540 void CAfvClient::setAliasedStations(const QVector<StationDto> &stations)
1541 {
1542 QMutexLocker lock(&m_mutex);
1543 m_aliasedStations = stations;
1544 }
1545
1546 quint32 CAfvClient::getAliasFrequencyHz(quint32 frequencyHz) const
1547 {
1548 // void rounding issues from float/double
1549 quint32 roundedFrequencyHz = static_cast<quint32>(qRound(frequencyHz / 1000.0)) * 1000;
1550
1551 // change to aliased frequency if needed
1552 {
1553 QMutexLocker lock(&m_mutex);
1554 CFrequency roundedFrequency(static_cast<int>(roundedFrequencyHz), CFrequencyUnit::Hz());
1555 const auto it = std::find_if(m_aliasedStations.constBegin(), m_aliasedStations.constEnd(),
1556 [roundedFrequency](const StationDto &d) {
1557 if (d.frequencyAliasHz > 100000000 &&
1558 roundedFrequency.value(CFrequencyUnit::Hz()) > 100000000) // both VHF
1559 {
1560 const int aliasedFreqHz = qRound(d.frequencyAliasHz / 1000.0) * 1000;
1561 return CComSystem::isSameFrequency(
1562 CFrequency(aliasedFreqHz, CFrequencyUnit::Hz()), roundedFrequency);
1563 }
1564 return d.frequencyAliasHz == roundedFrequency.value(CFrequencyUnit::Hz());
1565 });
1566
1567 if (it != m_aliasedStations.constEnd())
1568 {
1569 if (sApp && sApp->getIContextNetwork())
1570 {
1571 // Get the callsign for this frequency and fuzzy compare with our alias station
1572 const CFrequency f(static_cast<int>(roundedFrequencyHz), CFrequencyUnit::Hz());
1573 const CAtcStationList matchingAtcStations =
1575 const CAtcStation closest =
1576 matchingAtcStations
1578 .frontOrDefault();
1579
1580 if (fuzzyMatchCallsign(it->name, closest.getCallsign().asString()))
1581 {
1582 // this is how it should be
1583 roundedFrequencyHz = it->frequencyHz;
1584 CLogMessage(this).debug(u"Aliasing '%1' %2Hz [VHF] to %3Hz [HF]")
1585 << closest.getCallsign() << frequencyHz << it->frequencyHz;
1586 }
1587 else
1588 {
1589 // Ups!
1590 CLogMessage(this).debug(
1591 u"Station '%1' NOT found! Candidate was '%2'. Using original frequency %3 Hz")
1592 << it->name << closest.getCallsign().asString() << roundedFrequencyHz;
1593 }
1594 }
1595 else
1596 {
1597 // without contexts always use HF frequency if found
1598 roundedFrequencyHz = it->frequencyHz; // we use this frequency
1599 CLogMessage(this).debug(u"Aliasing %1Hz [VHF] to %2Hz [HF] (no context)")
1600 << frequencyHz << it->frequencyHz;
1601 }
1602 }
1603 }
1604 return roundedFrequencyHz;
1605 }
1606
1607 bool CAfvClient::isVoiceServerAlive() const
1608 {
1609 QMutexLocker lock(&m_mutexConnection);
1610 return m_connection && m_connection->isVoiceServerAlive();
1611 }
1612
1613 const QString &CAfvClient::getVoiceServerUrl() const
1614 {
1615 QMutexLocker lock(&m_mutexConnection);
1616
1617 static const QString e;
1618 if (!m_connection)
1619 {
1620 return e;
1621 }
1622 return m_connection->getVoiceServerUrl();
1623 }
1624
1625 bool CAfvClient::fuzzyMatchCallsign(const QString &callsign, const QString &compareTo) const
1626 {
1627 if (callsign.isEmpty() || compareTo.isEmpty())
1628 {
1629 return false;
1630 } // empty callsigns should NOT match
1631
1632 QString prefixA;
1633 QString suffixA;
1634 QString prefixB;
1635 QString suffixB;
1636 this->getPrefixSuffix(callsign, prefixA, suffixA);
1637 this->getPrefixSuffix(compareTo, prefixB, suffixB);
1638 return (prefixA == prefixB) && (suffixA == suffixB);
1639 }
1640
1641 void CAfvClient::getPrefixSuffix(const QString &callsign, QString &prefix, QString &suffix) const
1642 {
1643 thread_local const QRegularExpression separator("[(\\-|_)]");
1644 const QStringList parts = callsign.split(separator);
1645
1646 // avoid issues if there are no parts, or only one
1647 prefix = parts.size() > 0 ? parts.first() : QString();
1648 suffix = parts.size() > 1 ? parts.last() : QString();
1649 }
1650
1651 quint16 CAfvClient::comUnitToTransceiverId(CComSystem::ComUnit comUnit)
1652 {
1653 switch (comUnit)
1654 {
1655 case CComSystem::Com1: return 0;
1656 case CComSystem::Com2: return 1;
1657 default: break;
1658 }
1659 return 0;
1660 }
1661
1662 CComSystem::ComUnit CAfvClient::transceiverIdToComUnit(quint16 id)
1663 {
1664 if (comUnitToTransceiverId(CComSystem::Com1) == id)
1665 {
1666 return CComSystem::Com1;
1667 }
1668 if (comUnitToTransceiverId(CComSystem::Com2) == id)
1669 {
1670 return CComSystem::Com2;
1671 }
1672 return CComSystem::Com1;
1673 }
1674
1675 void CAfvClient::deferredInit()
1676 {
1677 // transceivers
1678 this->initTransceivers();
1679
1680 // init by settings
1681 this->onSettingsChanged();
1682
1683 // info
1684 CLogMessage(this).info(u"UserClient instantiated (deferred init)");
1685 }
1686
1687 bool CAfvClient::hasContexts()
1688 {
1691 }
1692
1694 {
1696 {
1697 // call in background thread of AFVClient to avoid lock issues
1698 QPointer<CAfvClient> myself(this);
1699 QTimer::singleShot(0, this, [=] {
1700 if (!myself || !CAfvClient::hasContexts())
1701 {
1702 return;
1703 }
1704 myself->setComOutputVolumeDb(comUnit, valueDb);
1705 });
1706 return true; // not exactly "true" as we do it async
1707 }
1708 if (comUnit != CComSystem::Com1 && comUnit != CComSystem::Com2)
1709 {
1710 return false;
1711 }
1712 if (valueDb > MaxDbOut)
1713 {
1714 valueDb = MaxDbOut;
1715 }
1716 else if (valueDb < MinDbOut)
1717 {
1718 valueDb = MinDbOut;
1719 }
1720
1721 const double gainRatio = qPow(10, valueDb / 20.0);
1722 bool changed = false;
1723 {
1724 QMutexLocker lock(&m_mutexVolume);
1725 if (comUnit == CComSystem::Com1)
1726 {
1727 changed = !qFuzzyCompare(m_outputVolumeDbCom1, valueDb);
1728 if (changed)
1729 {
1730 m_outputVolumeDbCom1 = valueDb;
1731 m_outputGainRatioCom1 = gainRatio;
1732 }
1733 }
1734 else
1735 {
1736 changed = !qFuzzyCompare(m_outputVolumeDbCom2, valueDb);
1737 if (changed)
1738 {
1739 m_outputVolumeDbCom2 = valueDb;
1740 m_outputGainRatioCom2 = gainRatio;
1741 }
1742 }
1743 }
1744
1745 // do NOT check on "changed", can be false, but "m_outputSampleProvider" is initialized
1746 // HINT: I do this tryLock here because I had deadlocks here, and I need to further investigate
1747 // As deadlocks mean (for the user) he needs to terminate the client I keep "trylock" that for now
1748 if (!m_mutexSampleProviders.tryLock(1000))
1749 {
1750 return false;
1751 }
1752
1753 if (m_soundcardSampleProvider)
1754 {
1755 changed = m_soundcardSampleProvider->setGainRatioForTransceiver(comUnit, gainRatio);
1756 }
1757 m_mutexSampleProviders.unlock();
1758 return changed;
1759 }
1760
1762 {
1763 QMutexLocker lock(&m_mutex);
1764 if (m_input)
1765 {
1766 return m_input->device();
1767 }
1768 static const CAudioDeviceInfo nullDevice;
1769 return nullDevice;
1770 }
1771
1773 {
1774 QMutexLocker lock(&m_mutex);
1775 if (m_output)
1776 {
1777 return m_output->device();
1778 }
1779 static const CAudioDeviceInfo nullDevice;
1780 return nullDevice;
1781 }
1782
1783 bool CAfvClient::usesSameDevices(const CAudioDeviceInfo &inputDevice, const CAudioDeviceInfo &outputDevice)
1784 {
1785 QMutexLocker lock(&m_mutex);
1786 if (!m_output || !m_input)
1787 {
1788 return false;
1789 }
1790 const CAudioDeviceInfo i = m_input->device();
1791 const CAudioDeviceInfo o = m_output->device();
1792 lock.unlock();
1793
1794 return i.matchesNameTypeMachineName(inputDevice) && o.matchesNameTypeMachineName(outputDevice);
1795 }
1796
1798 {
1799 return this->isConnected() ? Connected : Disconnected;
1800 }
1801} // namespace swift::core::afv::clients
SWIFT_CORE_EXPORT swift::core::CApplication * sApp
Single instance of application object.
static CAngleUnit deg()
Degrees.
Definition units.h:276
static CFrequencyUnit Hz()
Hertz.
Definition units.h:363
const context::IContextOwnAircraft * getIContextOwnAircraft() const
Direct access to contexts if a CCoreFacade has been initialized.
const context::IContextNetwork * getIContextNetwork() const
Direct access to contexts if a CCoreFacade has been initialized.
bool isShuttingDown() const
Is application shutting down?
const context::IContextSimulator * getIContextSimulator() const
Direct access to contexts if a CCoreFacade has been initialized.
void opusDataAvailable(const OpusDataAvailableArgs &args)
OPUS data.
void inputVolumeStream(const InputVolumeStreamArgs &args)
Volume stream data.
void outputVolumeStream(const OutputVolumeStreamArgs &args)
Streaming data.
void receivingCallsignsChanged(const TransceiverReceivingCallsignsChangedArgs &args)
Changed callsigns.
void ptt(bool active, const swift::misc::CIdentifier &identifier)
PTT status in this particular AFV client.
const swift::misc::audio::CAudioDeviceInfo & getInputDevice() const
Recently used device.
void restartAudio()
Start/stop client.
void changedOutputMute(bool muted)
Output mute changed.
QStringList getReceivingCallsignsStringCom1Com2() const
Callsigns currently received.
void startAudio()
Start/stop client.
bool isTransmittingComUnit(swift::misc::aviation::CComSystem::ComUnit comUnit) const
Transmitting transceiver/COM unit.
void setReceiveAudio(bool receive)
Receive audio.
int getNormalizedMasterOutputVolume() const
Normalized volumes 0..100.
Q_INVOKABLE bool setComOutputVolumeDb(swift::misc::aviation::CComSystem::ComUnit comUnit, double valueDb)
Output volume for each COM in dB, [MinDbOut, MaxDbOut]dB.
Q_INVOKABLE QStringList availableOutputDevices() const
Audio devices.
Q_INVOKABLE void updateComFrequency(quint16 id, quint32 frequencyHz)
Update frequency.
QSet< quint16 > getEnabledTransceivers() const
Get transceivers.
void updateFromOwnAircraft(const swift::misc::simulation::CSimulatedAircraft &aircraft, bool withSignals=true)
Update from own aircraft.
int getNormalizedInputVolume() const
Normalized volumes 0..100.
bool isConnected() const
Is connected to network?
Definition afvclient.cpp:73
double getOutputGainRatio(swift::misc::aviation::CComSystem::ComUnit comUnit) const
Gain ratio.
bool isEnabledComUnit(swift::misc::aviation::CComSystem::ComUnit comUnit) const
Enable COM unit/transceiver.
QVector< TransceiverDto > getTransceivers() const
Get transceivers.
bool updateVoiceServerUrl(const QString &url)
Update the voice server URL.
void updatedFromOwnAircraftCockpit()
Client updated from own aicraft data.
Q_INVOKABLE void setPtt(bool active)
Push to talk.
void setTransmittingTransceivers(const QVector< TxTransceiverDto > &transceivers)
Set transmitting transceivers.
void stoppedAudio()
Audio has been stopped.
void setTransmittingComUnit(swift::misc::aviation::CComSystem::ComUnit comUnit)
Set transmitting transceivers.
double getInputVolumeDb() const
Input volume in dB, [MinDbIn, MaxDbIn]dB.
void getRxTx(bool &rx1, bool &tx1, bool &rx2, bool &tx2) const
Simplified enable/disable.
bool isTransmittingTransceiver(quint16 id) const
Transmitting transceiver/COM unit.
CAfvClient(const QString &apiServer, QObject *owner)
Ctor.
Definition afvclient.cpp:42
QVector< TxTransceiverDto > getTransmittingTransceivers() const
Get transceivers.
void startedAudio(const swift::misc::audio::CAudioDeviceInfo &inputDevice, const swift::misc::audio::CAudioDeviceInfo &outputDevice)
Started audio with devices.
Q_INVOKABLE QStringList availableInputDevices() const
Audio devices.
void stopAudio()
Start/stop client.
void setOutputMuted(bool mute)
Muted (output).
double getInputVolumePeakVU() const
VU values, 0..1.
double inputVolumePeakVU
AFV client properties.
Definition afvclient.h:39
bool setNormalizedMasterOutputVolume(int volume)
Normalized volumes 0..100.
Q_INVOKABLE void updatePosition(double latitudeDeg, double longitudeDeg, double heightMeters)
Update own aircraft position.
void initialize()
Called when the thread is started.
Q_INVOKABLE bool setInputVolumeDb(double valueDb)
Input volume in dB, [MinDbIn, MaxDbIn]dB.
void setTransmittingTransceiver(quint16 transceiverID)
Set transmitting transceivers.
double getComOutputVolumeDb(swift::misc::aviation::CComSystem::ComUnit comUnit) const
Output volume for each COM in dB, [MinDbOut, MaxDbOut]dB.
double outputVolumePeakVU
AFV client properties.
Definition afvclient.h:40
bool isEnabledTransceiver(quint16 id) const
Enable COM unit/transceiver.
bool setNormalizedComOutputVolume(swift::misc::aviation::CComSystem::ComUnit comUnit, int volume)
Normalized volumes 0..100.
Q_INVOKABLE void setBypassEffects(bool value)
Enable/disable VHF simulation, true means effects are NOT used.
swift::misc::aviation::CCallsignSet getReceivingCallsignsCom2() const
Callsigns currently received.
void connectionStatusChanged(ConnectionStatus status)
Connection status has been changed.
void gracefulShutdown()
Gracefully shut down AFV client.
swift::misc::aviation::CCallsignSet getReceivingCallsignsCom1() const
Callsigns currently received.
void enableComUnit(swift::misc::aviation::CComSystem::ComUnit comUnit, bool enable)
Enable COM unit/transceiver.
Q_INVOKABLE void connectTo(const QString &cid, const QString &password, const QString &callsign, const QString &client)
Connect to network.
int getNormalizedComOutputVolume(swift::misc::aviation::CComSystem::ComUnit comUnit) const
Normalized volumes 0..100.
static const QStringList & getLogCategories()
Categories.
Definition afvclient.cpp:36
ConnectionStatus getConnectionStatus() const
Connection status.
void disconnectFrom(bool stop)
Disconnect from network.
bool isOutputMuted() const
Muted (output).
void cleanup()
Called when the thread is finished.
Q_INVOKABLE void enableTransceiver(quint16 id, bool enable)
Enable COM unit/transceiver.
double getOutputVolumePeakVU() const
VU values, 0..1.
QString getReceivingCallsignsStringCom1() const
Callsigns currently received.
QString getReceivingCallsignsStringCom2() const
Callsigns currently received.
bool usesSameDevices(const swift::misc::audio::CAudioDeviceInfo &inputDevice, const swift::misc::audio::CAudioDeviceInfo &outputDevice)
Recently used device.
const swift::misc::audio::CAudioDeviceInfo & getOutputDevice() const
Recently used device.
bool setNormalizedInputVolume(int volume)
Normalized volumes 0..100.
void setCallsign(const QString &getCallsign)
Copy operations.
Definition afvclient.cpp:67
void setRxTx(bool rx1, bool tx1, bool rx2, bool tx2)
Simplified enable/disable.
void audioReceived(const AudioRxOnTransceiversDto &dto)
Audio has been received.
void muteRequestReceived(bool mute)
Mute request received.
virtual swift::misc::aviation::CAtcStationList getOnlineStationsForFrequency(const swift::misc::physical_quantities::CFrequency &frequency) const =0
Online stations for frequency.
virtual bool isConnected() const =0
Network connected?
void changedAircraftCockpit(const swift::misc::simulation::CSimulatedAircraft &aircraft, const swift::misc::CIdentifier &originator)
Aircraft cockpit update.
virtual swift::misc::aviation::CAircraftSituation getOwnAircraftSituation() const =0
Get own aircraft.
virtual swift::misc::simulation::settings::CSimulatorSettings getSimulatorSettings() const =0
Get the current simulator settings.
const QObject * owner() const
Owner of the worker.
Definition worker.h:352
void quitAndWait() noexcept final
Calls quit() and blocks until the thread is finished.
Definition worker.cpp:218
CContinuousWorker(QObject *owner, const QString &name)
Constructor.
Definition worker.cpp:168
CIdentifiable(const QString &objectName)
Use literal based object name.
const CIdentifier & identifier() const
Get identifier.
Value object encapsulating information identifying a component of a modular distributed swift process...
Definition identifier.h:29
static const QString & vatsimSpecific()
VATSIM specific.
static const QString & audio()
Audio related.
Class for emitting a log message.
Definition logmessage.h:27
static void preformatted(const CStatusMessage &statusMessage)
Sends a verbatim, preformatted message to the log.
Derived & warning(const char16_t(&format)[N])
Set the severity to warning, providing a format string.
Derived & error(const char16_t(&format)[N])
Set the severity to error, providing a format string.
Derived & info(const char16_t(&format)[N])
Set the severity to info, providing a format string.
const_reference frontOrDefault() const
Access the first element, or a default-initialized value if the sequence is empty.
Definition sequence.h:239
bool isFailure() const
Operation considered unsuccessful.
static QString currentThreadInfo()
Info about current thread, for debug messages.
static bool isInThisThread(const QObject *toBeTested)
Is the current thread the object's thread?
Value object encapsulating information of a audio device.
static CAudioDeviceInfo getDefaultInputDevice()
Default input device.
const QString & getName() const
Get the device name.
bool isOutputDevice() const
Output device.
static CAudioDeviceInfo getDefaultOutputDevice()
Default output device.
bool isValid() const
Valid audio device object?
bool matchesNameTypeMachineName(const CAudioDeviceInfo &device) const
Matching name, type and machine.
static CAudioDeviceInfoList allInputDevices()
Lists of all available devices.
static CAudioDeviceInfoList allOutputDevices()
Lists of all available devices.
CAudioDeviceInfo findByName(const QString &name, bool strict=false) const
Find by name.
int getOutVolumeCom2() const
Get volume for com2 (audio) 0..100.
int getOutVolume() const
Get volume (audio) 0..100.
bool isAudioEffectsEnabled() const
Audio effects enabled?
int getInVolume() const
Get mic.volume (audio 0..100).
int getOutVolumeCom1() const
Get volume for com1 (audio) 0..100.
const geo::CCoordinateGeodetic & getPosition() const
Get position.
const CCallsign & getCallsign() const
Get callsign.
Definition atcstation.h:84
const QString & asString() const
Get callsign (normalized).
Definition callsign.h:96
Value object for a set of callsigns.
Definition callsignset.h:26
COM system (aka "radio").
Definition comsystem.h:37
bool isTransmitEnabled() const
Enabled?
int getVolumeReceive() const
Output volume 0..100.
Definition modulator.cpp:54
bool isReceiveEnabled() const
Enabled?
swift::misc::physical_quantities::CFrequency getFrequencyActive() const
Active frequency.
Definition modulator.cpp:30
CONTAINER findClosest(int number, const ICoordinateGeodetic &coordinate) const
Find 0..n objects closest to the given coordinate.
static CLengthUnit m()
Meter m.
Definition units.h:140
static CLengthUnit ft()
Foot ft.
Definition units.h:157
double value(MU unit) const
Value in given unit.
Comprehensive information of an aircraft.
const aviation::CComSystem & getCom2System() const
Get COM2 system.
const aviation::CComSystem & getCom1System() const
Get COM1 system.
geo::CLongitude longitude() const
Longitude.
geo::CLatitude latitude() const
Latitude.
const aviation::CAltitude & getAltitude() const
Get altitude.
Classes interacting with the swift database (aka "datastore").
Free functions in swift::misc.
auto singleShot(int msec, QObject *target, F &&task)
Starts a single-shot timer which will call a task in the thread of the given object when it times out...
Definition threadutils.h:30
QByteArray::iterator begin()
char * data()
QByteArray::iterator end()
qsizetype size() const const
T & first()
T & last()
void push_back(QList< T >::parameter_type value)
qsizetype size() const const
bool invokeMethod(QObject *context, Functor &&function, Args &&... arguments)
QObject(QObject *parent)
QMetaObject::Connection connect(const QObject *sender, PointerToMemberFunction signal, Functor functor)
bool disconnect(const QMetaObject::Connection &connection)
void setObjectName(QAnyStringView name)
QThread * thread() const const
bool contains(const QSet< T > &other) const const
QSet< T >::iterator insert(QSet< T >::const_iterator it, const T &value)
QString fromStdString(const std::string &str)
bool isEmpty() const const
QStringList split(QChar sep, Qt::SplitBehavior behavior, Qt::CaseSensitivity cs) const const
std::string toStdString() const const
QueuedConnection
QThread * currentThread()
void timeout()
AudioRxOnTransceiversDto.
Definition dto.h:256
std::vector< RxTransceiverDto > transceivers
Properties.
Definition dto.h:269
std::string callsign
Properties.
Definition dto.h:265
std::vector< char > audio
Properties.
Definition dto.h:267
AudioTxOnTransceiversDto.
Definition dto.h:236
std::vector< char > audio
Properties.
Definition dto.h:247
std::vector< TxTransceiverDto > transceivers
Properties.
Definition dto.h:249
std::string callsign
Properties.
Definition dto.h:245
bool lastPacket
Used to indicate to receiver that the sender has stopped sending.
Definition dto.h:280
QByteArray audio
Opus compressed audio.
Definition dto.h:279
QString callsign
Callsign that audio originates from.
Definition dto.h:277
uint sequenceCounter
Receiver optionally uses this in reordering algorithm/gap detection.
Definition dto.h:278
Receive transceiver DTO.
Definition dto.h:206
quint32 frequencyAliasHz
Properties.
Definition dto.h:164
double LonDeg
Properties.
Definition dto.h:123
double LatDeg
Properties.
Definition dto.h:122
double HeightMslM
Properties.
Definition dto.h:124
double HeightAglM
Properties.
Definition dto.h:125
quint32 frequencyHz
Properties.
Definition dto.h:121
quint16 id
Properties.
Definition dto.h:120
Transmit transceiver DTO.
Definition dto.h:220