-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathTciServer.cpp
More file actions
2074 lines (1874 loc) · 87.1 KB
/
Copy pathTciServer.cpp
File metadata and controls
2074 lines (1874 loc) · 87.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#ifdef HAVE_WEBSOCKETS
#include "TciServer.h"
#include "TciProtocol.h"
#include "StreamStatus.h"
#include "AudioEngine.h"
#include "AppSettings.h"
#include "Resampler.h"
#include "LogManager.h"
#include "models/RadioModel.h"
#include "models/SliceModel.h"
#include "models/PanadapterModel.h"
#include "models/DaxIqModel.h"
#include "models/MeterModel.h"
#include "models/TransmitModel.h"
#include "models/SpotModel.h"
#include <QWebSocketServer>
#include <QWebSocket>
#include <QHostAddress>
#include <QStringList>
#include <QTimer>
#include <QPointer>
#include <QtEndian>
#include <algorithm>
#include <cmath>
#include <cstring>
namespace AetherSDR {
namespace {
// Server-side caps closing the unbounded-frame / unbounded-client surface
// flagged in GHSA-7w4w-wfqm-wh93 (M2). QWebSocket message/frame sizes
// default to 1 GiB in Qt6 — wildly more than any legitimate TCI command
// or audio frame. 64 KiB easily covers the largest legitimate TCI text
// command and is enforced at the framing layer. Eight concurrent clients
// matches the rigctld cap.
constexpr qint64 kMaxWsMessageBytes = 64 * 1024;
constexpr int kMaxClients = 8;
// Grace period before tearing down DAX RX after the last audio client drops.
// A TCP drop is frequently transient (WSJT-X throws on a CAT timeout — e.g. a
// vfo: echo delayed by an ATU tune — then reconnects). Deferring the teardown
// lets the stream survive the blip so audio resumes with no recreate; a
// reconnecting client cancels it. (#3363/#3476 + Tune/ATU)
// Measured drop→audio_start gaps in the field repros: 2.1s / 3.3s / 3.5s —
// and WSJT-X is slowest to reconnect mid-FT8-decode, exactly when these
// throws happen. 10s gives ~3x margin; the cost of lingering after a genuine
// quit is just an unconsumed stream + dax flag for a few extra seconds.
constexpr int kDaxReleaseGraceMs = 10000;
}
// ── TCI binary audio frame header (per ExpertSDR3 TCI spec v2.0) ────────
// 9 × uint32 = 36 bytes, followed by sample payload
// TCI audio header: 16 × uint32 = 64 bytes
// Per ExpertSDR3 TCI spec v2.0 Stream struct
struct TciAudioHeader {
quint32 receiver; // receiver/TRX number
quint32 sampleRate; // Hz
quint32 format; // 0=int16, 1=int24, 2=int32, 3=float32
quint32 codec; // 0 (uncompressed)
quint32 crc; // 0 (unused)
quint32 length; // number of real samples in data
quint32 type; // 0=IQ, 1=RX_AUDIO, 2=TX_AUDIO, 3=TX_CHRONO
quint32 channels; // 1 or 2
quint32 reserved[8]; // zero-filled
};
static_assert(sizeof(TciAudioHeader) == 64, "TCI audio header must be 64 bytes");
namespace {
constexpr int kTxChronoSamples = 2048; // float payload length sent to WSJT-X
constexpr int kTxChronoStereoFrames = kTxChronoSamples / 2;
constexpr qint64 kTxChronoPeriodNs =
(static_cast<qint64>(kTxChronoStereoFrames) * 1000000000LL) / 48000LL;
constexpr int kTxChronoPollMs = 5;
constexpr qint64 kTxSummaryEveryBlocks = 48;
// parseStatusHandle / streamStatusBelongsToUs → StreamStatus.h
// tciTrxForSlice → TciProtocol::tciTrxForSlice
} // namespace
TciServer::TciServer(RadioModel* model, QObject* parent)
: QObject(parent)
, m_model(model)
{
// Load per-channel RX gains from persistence (decoupled from DaxRxGain<n>, #1627).
// Migrate DaxRxGain<n> → TciRxGain<n> on first read so existing users keep
// their current balance when the applets split.
{
auto& s = AppSettings::instance();
for (int ch = 1; ch <= 4; ++ch) {
const QString key = QStringLiteral("TciRxGain%1").arg(ch);
if (!s.contains(key)) {
const QString legacy = s.value(QStringLiteral("DaxRxGain%1").arg(ch), "0.5").toString();
s.setValue(key, legacy);
}
m_rxChannelGain[ch - 1] = std::clamp(
s.value(key, "0.5").toString().toFloat(), 0.0f, 1.0f);
}
s.save();
}
// Cache S-meter values for periodic broadcast (avoid flooding clients)
if (m_model) {
connect(&m_model->meterModel(), &MeterModel::sLevelChanged,
this, [this](int sliceIndex, float dbm) {
if (sliceIndex >= 0 && sliceIndex < 8)
m_cachedSLevel[sliceIndex] = dbm;
});
}
// Cache TX meter values
if (m_model) {
connect(&m_model->meterModel(), &MeterModel::txMetersChanged,
this, [this](float fwd, float swr) {
m_cachedFwdPower = fwd;
m_cachedSwr = swr;
});
connect(&m_model->meterModel(), &MeterModel::micMetersChanged,
this, [this](float micLevel, float, float, float) {
m_cachedMicLevel = micLevel;
});
connect(&m_model->meterModel(), &MeterModel::swAlcChanged,
this, [this](float dbfs) {
m_cachedAlc = dbfs;
});
}
// Capture DAX RX stream creation responses so we can register them
// in PanadapterStream for VITA-49 routing (#1331).
if (m_model) {
// Stream registration + radio-side-removal recovery now live in the
// centralized DAX channel manager (RadioModel::handleDaxRxStreamRegistry
// + PanadapterStream refcounting, #3305). The #3476 "profile load
// destroyed the stream, never came back" recreate is automatic there.
// TCI only keeps its channel→trx routing cache truthful (#3669/#3766).
if (m_model->panStream()) {
connect(m_model->panStream(), &PanadapterStream::daxStreamUnregistered,
this, [this](int ch, quint32) {
m_channelTrx.remove(ch);
});
}
// Re-trigger DAX setup when the radio (re)connects or a slice
// is added AFTER a TCI client has already requested audio. Without
// this, a client that races the radio connect — WSJT-X started
// before AetherSDR finishes its handshake, or before any slice
// exists — sets `audioEnabled=true` but ensureDaxForTci()
// silently no-ops on `!isConnected()` / empty slices, and never
// gets a second chance. Result: CAT and TX audio look fine
// (text channel is alive) but no DAX RX stream is ever created,
// so the radio sends no audio frames and WSJT-X RX stays silent.
// (#3270)
connect(m_model, &RadioModel::connectionStateChanged,
this, [this](bool connected) {
if (!connected) {
// Radio dropped: RadioModel resets the DAX channel manager
// (the radio reaps our streams server-side, #3305). Drop the
// routing cache and the slice-assignment bookkeeping: slices
// are being destroyed with the connection, and a
// releaseDaxForTci() that runs later (e.g. the debounced grace
// timer firing after a quick radio reconnect) must not
// setDaxChannel(0) on the RECREATED slices — that would strip
// a profile-restored DAX assignment from a slice we no longer
// manage.
m_channelTrx.clear();
m_tciDaxSlices.clear();
return;
}
for (const auto& cs : m_clients) {
if (cs.audioEnabled) {
qCInfo(lcCat) << "TCI: radio reconnected — re-arming DAX"
<< "for pending audio client (#3270)";
ensureDaxForTci();
return;
}
}
});
connect(m_model, &RadioModel::sliceAdded,
this, [this](SliceModel*) {
for (const auto& cs : m_clients) {
if (cs.audioEnabled) {
qCInfo(lcCat) << "TCI: slice added — re-arming DAX"
<< "for active audio client (#3270)";
ensureDaxForTci();
return;
}
}
});
// A removed slice never fires daxChannelChanged, so without this the
// Tci hold on its channel stays set forever and the dax_rx stream
// lingers until the TCI client disconnects (pre-existing orphan,
// closed alongside #3305 per PR #4017 review item 4). Release any
// Tci-held channel that no remaining slice carries; the sliceAdded
// re-arm above re-acquires when a replacement slice appears.
connect(m_model, &RadioModel::sliceRemoved,
this, [this](int sliceId) {
m_tciDaxSlices.remove(sliceId);
auto* ps = m_model ? m_model->panStream() : nullptr;
if (!ps) return;
for (int ch = 1; ch <= 4; ++ch) {
if (!ps->daxChannelHeldBy(ch, PanadapterStream::DaxConsumer::Tci))
continue;
bool stillWanted = false;
for (auto* s : m_model->slices()) {
if (s && s->daxChannel() == ch) { stillWanted = true; break; }
}
if (!stillWanted) {
qCInfo(lcCat) << "TCI: releasing DAX channel" << ch
<< "after slice" << sliceId << "removal (#3305)";
ps->releaseDaxChannel(ch, PanadapterStream::DaxConsumer::Tci);
m_channelTrx.remove(ch);
}
}
});
}
// Periodic status broadcast (200ms — S-meter, TX sensors, TX state)
m_meterTimer = new QTimer(this);
m_meterTimer->setInterval(200);
connect(m_meterTimer, &QTimer::timeout, this, &TciServer::broadcastStatus);
// Debounced DAX RX teardown — see scheduleDaxRelease(). Single-shot; a
// reconnecting audio client cancels it before it fires.
m_daxReleaseTimer = new QTimer(this);
m_daxReleaseTimer->setSingleShot(true);
connect(m_daxReleaseTimer, &QTimer::timeout, this, [this]() {
bool anyAudio = false;
for (const auto& cs : m_clients)
if (cs.audioEnabled) { anyAudio = true; break; }
if (anyAudio) {
qCWarning(lcCat) << "TCI: DAX release grace expired but an audio client is active — keeping DAX RX";
return;
}
qCWarning(lcCat) << "TCI: DAX release grace expired, no audio client returned — releasing DAX RX now";
releaseDaxForTci();
});
// TX_CHRONO timer — sends timing frames to TCI client during TX.
// WSJT-X only sends TX audio in response to these frames.
//
// One TCI TX block is 2048 float samples = 1024 stereo frames at 48 kHz,
// or 21.333 ms of audio. A fixed 21 ms timer runs ~1.6% fast and warps
// digital-mode tones, so we poll more frequently and emit frames from a
// monotonic elapsed-time accumulator.
m_txChronoTimer = new QTimer(this);
m_txChronoTimer->setTimerType(Qt::PreciseTimer);
m_txChronoTimer->setInterval(kTxChronoPollMs);
connect(m_txChronoTimer, &QTimer::timeout, this, [this]() {
// Local copy guards against onClientDisconnected nulling the pointer
// between the check and the send.
QWebSocket* client = m_txChronoClient;
if (!client) { m_txChronoTimer->stop(); return; }
if (!m_txChronoClock.isValid()) {
m_txChronoClock.start();
return;
}
m_txChronoAccumNs += m_txChronoClock.nsecsElapsed();
m_txChronoClock.restart();
while (m_txChronoAccumNs >= kTxChronoPeriodNs) {
sendTxChronoFrame(client);
m_txChronoAccumNs -= kTxChronoPeriodNs;
}
});
}
TciServer::~TciServer()
{
stop();
}
bool TciServer::start(quint16 port)
{
if (m_server)
return m_server->isListening();
m_server = new QWebSocketServer(
QStringLiteral("AetherSDR-TCI"),
QWebSocketServer::NonSecureMode, this);
if (!m_server->listen(QHostAddress::Any, port)) {
qCWarning(lcCat) << "TciServer: failed to listen on port" << port
<< m_server->errorString();
delete m_server;
m_server = nullptr;
return false;
}
connect(m_server, &QWebSocketServer::newConnection,
this, &TciServer::onNewConnection);
m_meterTimer->start();
qCInfo(lcCat) << "TciServer: listening on port" << m_server->serverPort();
return true;
}
void TciServer::stop()
{
m_meterTimer->stop();
if (m_daxReleaseTimer) m_daxReleaseTimer->stop(); // immediate teardown below
stopTxChrono();
if (!m_server) return;
for (auto& cs : m_clients) {
cs.socket->disconnect(this); // prevent onClientDisconnected re-entry
cs.socket->close();
cs.socket->deleteLater();
delete cs.protocol;
qDeleteAll(cs.resamplers);
}
m_clients.clear();
releaseDaxForTci();
emit clientCountChanged(0);
m_server->close();
delete m_server;
m_server = nullptr;
qCInfo(lcCat) << "TciServer: stopped";
}
bool TciServer::isRunning() const
{
return m_server && m_server->isListening();
}
quint16 TciServer::port() const
{
return m_server ? m_server->serverPort() : 0;
}
void TciServer::broadcastMasterVolume(int pct)
{
if (pct < 0) pct = 0;
if (pct > 100) pct = 100;
// Wire scale is dB (-60..0) per the TCI spec; pct is the internal
// 0-100 amplitude from the title bar slider / applyMasterVolume.
broadcast(QStringLiteral("volume:%1;")
.arg(TciProtocol::volumeDbFromPercent(pct)));
}
void TciServer::setTxGain(float gain)
{
const float clamped = std::clamp(gain, 0.0f, 1.0f);
if (m_txGain == clamped) return;
m_txGain = clamped;
auto& s = AppSettings::instance();
s.setValue("TciTxGain", QString::number(clamped, 'f', 2));
s.save();
}
void TciServer::setOverflowMode(int mode)
{
if (mode < 0 || mode > 2) return;
auto next = static_cast<OverflowMode>(mode);
if (m_overflowMode == next) return;
m_overflowMode = next;
auto& s = AppSettings::instance();
s.setValue("TciTxOverflowMode", QString::number(mode));
s.save();
}
void TciServer::setRxChannelGain(int channel, float gain)
{
if (channel < 1 || channel > 4) return;
const float clamped = std::clamp(gain, 0.0f, 1.0f);
if (m_rxChannelGain[channel - 1] == clamped) return;
m_rxChannelGain[channel - 1] = clamped;
auto& s = AppSettings::instance();
s.setValue(QStringLiteral("TciRxGain%1").arg(channel),
QString::number(clamped, 'f', 2));
s.save();
}
float TciServer::rxChannelGain(int channel) const
{
if (channel < 1 || channel > 4) return 1.0f;
return m_rxChannelGain[channel - 1];
}
void TciServer::onNewConnection()
{
while (m_server->hasPendingConnections()) {
auto* ws = m_server->nextPendingConnection();
// Refuse new connections once at-capacity (GHSA-7w4w-wfqm-wh93).
if (m_clients.size() >= kMaxClients) {
qCWarning(lcCat) << "TciServer: refusing connection from"
<< ws->peerAddress().toString()
<< "— at max-clients cap (" << kMaxClients << ")";
ws->close(QWebSocketProtocol::CloseCodeTooMuchData,
QStringLiteral("server at max-clients cap"));
ws->deleteLater();
continue;
}
// Cap per-message and per-frame size to refuse OOM-by-huge-frame
// (GHSA-7w4w-wfqm-wh93). Qt6 default is 1 GiB per message; legit
// TCI text commands and audio frames are well under 64 KiB.
ws->setMaxAllowedIncomingMessageSize(kMaxWsMessageBytes);
ws->setMaxAllowedIncomingFrameSize(kMaxWsMessageBytes);
auto* protocol = new TciProtocol(m_model);
ClientState cs;
cs.socket = ws;
cs.protocol = protocol;
// Resamplers are created lazily per-channel in onDaxAudioReady()
// so each DAX channel has its own stateful r8brain instance (#1806).
m_clients.append(cs);
connect(ws, &QWebSocket::textMessageReceived,
this, &TciServer::onTextMessage);
connect(ws, &QWebSocket::binaryMessageReceived,
this, &TciServer::onBinaryMessage);
connect(ws, &QWebSocket::disconnected,
this, &TciServer::onClientDisconnected);
qCInfo(lcCat) << "TciServer: client connected from"
<< ws->peerAddress().toString();
emit clientCountChanged(m_clients.size());
emit clientsChanged();
sendInitBurst(ws);
}
}
void TciServer::onClientDisconnected()
{
auto* ws = qobject_cast<QWebSocket*>(sender());
if (!ws) return;
for (int i = 0; i < m_clients.size(); ++i) {
if (m_clients[i].socket == ws) {
// If this client was driving TX_CHRONO, stop and unkey
if (ws == m_txChronoClient) {
stopTxChrono();
if (m_model) {
QMetaObject::invokeMethod(m_model, [this]() {
m_model->setTransmit(false);
}, Qt::QueuedConnection);
}
}
// Clean up IQ stream if this client started one
if (m_clients[i].iqEnabled && m_model) {
int ch = m_clients[i].iqChannel + 1; // TRX 0 → DAX channel 1
// Only remove if no other client uses the same IQ channel
bool otherUsing = false;
for (int j = 0; j < m_clients.size(); ++j) {
if (j != i && m_clients[j].iqEnabled &&
m_clients[j].iqChannel == m_clients[i].iqChannel) {
otherUsing = true;
break;
}
}
if (!otherUsing) {
QMetaObject::invokeMethod(m_model, [this, ch]() {
m_model->daxIqModel().removeStream(ch);
}, Qt::QueuedConnection);
}
}
delete m_clients[i].protocol;
qDeleteAll(m_clients[i].resamplers);
m_clients.removeAt(i);
// Release DAX if no remaining clients want audio (#1331)
bool anyAudio = false;
for (const auto& cs : m_clients) {
if (cs.audioEnabled) { anyAudio = true; break; }
}
if (!anyAudio) scheduleDaxRelease(); // debounce: survive transient WSJT-X reconnects
break;
}
}
ws->deleteLater();
// DIAG: qCWarning — a TCP-level client drop (WSJT-X threw a rig-control
// error in do_stop()) is the trigger for the DAX RX teardown above. Always
// log it so the cause of mid-session RX loss is visible.
qCWarning(lcCat) << "TciServer: client disconnected (TCP drop),"
<< m_clients.size() << "remaining";
emit clientCountChanged(m_clients.size());
emit clientsChanged();
}
QVector<TciClientInfo> TciServer::connectedClients() const
{
QVector<TciClientInfo> out;
out.reserve(m_clients.size());
for (const auto& cs : m_clients) {
if (!cs.socket)
continue;
TciClientInfo info;
// Normalise the peer address so it is both readable and a STABLE
// alias key: collapse IPv4-mapped IPv6 (::ffff:a.b.c.d) to plain
// IPv4, and IPv6 loopback (::1) to 127.0.0.1. Otherwise the same
// physical client could key its saved Name under two spellings.
QHostAddress ha = cs.socket->peerAddress();
bool isV4 = false;
const quint32 v4 = ha.toIPv4Address(&isV4);
if (isV4)
ha = QHostAddress(v4);
else if (ha.isLoopback())
ha = QHostAddress(QHostAddress::LocalHost);
info.peerAddress = ha.toString();
info.peerPort = cs.socket->peerPort();
info.audio = cs.audioEnabled;
info.audioReceiver= cs.audioReceiver;
info.iq = cs.iqEnabled;
info.rxSensors = cs.rxSensorsEnabled;
info.txSensors = cs.txSensorsEnabled;
out.append(info);
}
return out;
}
void TciServer::onTextMessage(const QString& msg)
{
auto* ws = qobject_cast<QWebSocket*>(sender());
if (!ws) return;
// Find the client state
int clientIdx = -1;
for (int i = 0; i < m_clients.size(); ++i) {
if (m_clients[i].socket == ws) { clientIdx = i; break; }
}
if (clientIdx < 0) return;
auto& client = m_clients[clientIdx];
// Raw inbound log — helps diagnose TCI-variant dialects where WSJT-X
// forks (Improved, Improved Plus, KN4CRD fork…) send commands our
// parser doesn't match. Truncate long ones to keep logs readable.
qCDebug(lcCat) << "TCI rx:" << msg.left(256);
emit tciMessage(QStringLiteral("rx"), msg);
// TCI messages are semicolon-terminated; may contain multiple commands
const QStringList cmds = msg.split(';', Qt::SkipEmptyParts);
for (const auto& cmd : cmds) {
QString trimmed = cmd.trimmed().toLower();
// Handle audio start/stop at server level (affects per-client state)
if (trimmed.startsWith("audio_start")) {
int requestedReceiver = -1;
const int colonIdx2 = trimmed.indexOf(':');
if (colonIdx2 >= 0) {
const QString receiverText = trimmed.mid(colonIdx2 + 1)
.section(QLatin1Char(','), 0, 0)
.trimmed();
bool ok = false;
const int parsedReceiver = receiverText.toInt(&ok);
if (ok)
requestedReceiver = parsedReceiver;
}
client.audioEnabled = true;
client.audioReceiver = requestedReceiver;
cancelDaxRelease(); // a (re)connecting audio client cancels a pending teardown
ensureDaxForTci();
replyText(ws,cmd.trimmed() + ";");
qCDebug(lcCat) << "TCI: audio started"
<< "receiver=" << client.audioReceiver
<< "rate=" << client.audioSampleRate
<< "channels=" << client.audioChannels
<< "format=" << client.audioFormat
<< "peer=" << ws->peerAddress().toString();
qCInfo(lcCat) << "TCI: audio started for client"
<< ws->peerAddress().toString()
<< "rate=" << client.audioSampleRate
<< "ch=" << client.audioChannels
<< "fmt=" << client.audioFormat;
emit clientsChanged();
continue;
}
if (trimmed.startsWith("audio_stop")) {
client.audioEnabled = false;
client.audioReceiver = -1;
// Release DAX if no other clients still want audio
bool anyAudio = false;
for (const auto& cs : m_clients) {
if (cs.audioEnabled) { anyAudio = true; break; }
}
if (!anyAudio) scheduleDaxRelease(); // debounce: audio_stop is often followed by a quick audio_start
replyText(ws,cmd.trimmed() + ";");
qCWarning(lcCat) << "TCI: audio_stop from client"
<< ws->peerAddress().toString()
<< "(anyAudio=" << anyAudio << ")";
emit clientsChanged();
continue;
}
// Audio format negotiation
if (trimmed.startsWith("audio_samplerate:")) {
int colonIdx2 = trimmed.indexOf(':');
int rate = trimmed.mid(colonIdx2 + 1).toInt();
if (rate == 8000 || rate == 12000 || rate == 24000 || rate == 48000) {
client.audioSampleRate = rate;
// Discard all per-channel resamplers — they were built for
// the old rate and carry stale filter history. New instances
// at the correct rate are lazily created in onDaxAudioReady().
qDeleteAll(client.resamplers);
client.resamplers.clear();
qCInfo(lcCat) << "TCI: audio sample rate set to" << rate
<< "for" << ws->peerAddress().toString();
}
replyText(ws,QStringLiteral("audio_samplerate:%1;")
.arg(client.audioSampleRate));
continue;
}
if (trimmed.startsWith("audio_stream_sample_type:")) {
int colonIdx2 = trimmed.indexOf(':');
QString fmtStr = trimmed.mid(colonIdx2 + 1).trimmed();
int fmt;
if (fmtStr == "float32")
fmt = 3;
else if (fmtStr == "int16")
fmt = 0;
else
fmt = fmtStr.toInt(); // numeric value
if (fmt == 0 || fmt == 3) // int16 or float32
client.audioFormat = fmt;
replyText(ws,QStringLiteral("audio_stream_sample_type:%1;")
.arg(client.audioFormat));
continue;
}
// Sensor enable/disable
if (trimmed.startsWith("rx_sensors_enable:")) {
int colonIdx2 = trimmed.indexOf(':');
QString val = trimmed.mid(colonIdx2 + 1).split(',').first();
client.rxSensorsEnabled = (val == "true");
replyText(ws,QStringLiteral("rx_sensors_enable:%1;")
.arg(client.rxSensorsEnabled ? "true" : "false"));
qCInfo(lcCat) << "TCI: rx_sensors" << (client.rxSensorsEnabled ? "enabled" : "disabled");
emit clientsChanged();
continue;
}
if (trimmed.startsWith("tx_sensors_enable:")) {
int colonIdx2 = trimmed.indexOf(':');
QString val = trimmed.mid(colonIdx2 + 1).split(',').first();
client.txSensorsEnabled = (val == "true");
replyText(ws,QStringLiteral("tx_sensors_enable:%1;")
.arg(client.txSensorsEnabled ? "true" : "false"));
qCInfo(lcCat) << "TCI: tx_sensors" << (client.txSensorsEnabled ? "enabled" : "disabled");
emit clientsChanged();
continue;
}
// IQ start/stop — track per-client IQ state, then forward to protocol
if (trimmed.startsWith("iq_start:")) {
int colonIdx2 = trimmed.indexOf(':');
int trx = trimmed.mid(colonIdx2 + 1).trimmed().toInt();
client.iqEnabled = true;
client.iqChannel = trx;
qCInfo(lcCat) << "TCI: IQ started for client"
<< ws->peerAddress().toString()
<< "trx=" << trx;
// Forward to protocol to create DAX IQ stream on the radio
QString response = client.protocol->handleCommand(cmd.trimmed());
if (!response.isEmpty())
replyText(ws,response);
emit clientsChanged();
continue;
}
if (trimmed.startsWith("iq_stop:")) {
int colonIdx2 = trimmed.indexOf(':');
int trx = trimmed.mid(colonIdx2 + 1).trimmed().toInt();
if (client.iqChannel == trx)
client.iqEnabled = false;
qCInfo(lcCat) << "TCI: IQ stopped for client"
<< ws->peerAddress().toString()
<< "trx=" << trx;
QString response = client.protocol->handleCommand(cmd.trimmed());
if (!response.isEmpty())
replyText(ws,response);
emit clientsChanged();
continue;
}
// Spectrum event subscribe/unsubscribe — enables waterfall row forwarding
if (trimmed == "spectrum_event:on") {
client.spectrumEnabled = true;
qCInfo(lcCat) << "TCI: spectrum_event enabled for client"
<< ws->peerAddress().toString();
continue;
}
if (trimmed == "spectrum_event:off") {
client.spectrumEnabled = false;
qCInfo(lcCat) << "TCI: spectrum_event disabled for client"
<< ws->peerAddress().toString();
continue;
}
if (trimmed.startsWith("audio_stream_samples:")) {
// Samples per audio packet — acknowledge but we use fixed packet sizes
replyText(ws,cmd.trimmed() + ";");
continue;
}
if (trimmed.startsWith("tx_stream_audio_buffering:")) {
// TX audio buffering in ms — acknowledge
replyText(ws,cmd.trimmed() + ";");
continue;
}
if (trimmed.startsWith("line_out_start") ||
trimmed.startsWith("line_out_stop") ||
trimmed.startsWith("line_out_recorder")) {
// Line-out recording — not applicable to FlexRadio, acknowledge
replyText(ws,cmd.trimmed() + ";");
continue;
}
if (trimmed.startsWith("audio_stream_channels:")) {
int colonIdx2 = trimmed.indexOf(':');
int ch = trimmed.mid(colonIdx2 + 1).toInt();
if (ch == 1 || ch == 2)
client.audioChannels = ch;
replyText(ws,QStringLiteral("audio_stream_channels:%1;")
.arg(client.audioChannels));
continue;
}
QString response = client.protocol->handleCommand(cmd.trimmed());
if (!response.isEmpty()) {
replyText(ws,response);
qCDebug(lcCat) << "TCI cmd:" << cmd.trimmed()
<< "-> resp:" << response.left(80).trimmed();
}
// If the command changed radio state, broadcast to all other clients
QString notification = client.protocol->pendingNotification();
if (!notification.isEmpty()) {
for (auto& cs : m_clients) {
if (cs.socket != ws)
cs.socket->sendTextMessage(notification);
}
}
// Master volume SET — TciProtocol owns only RadioModel, so it can't
// touch AudioEngine directly. It stashes the requested level and we
// forward to MainWindow via signal, mirroring the title bar slider's
// signal path. The notification (`volume:N;`) was already echoed
// above to the requesting client and broadcast to others.
int mvol = client.protocol->pendingMasterVolume();
if (mvol >= 0) emit masterVolumeRequested(mvol);
// tx_gain SET — same pattern: TciProtocol can't reach TciServer, so it
// stashes the 0-100 value and we apply it here via setTxGain().
int txg = client.protocol->pendingTxGain();
if (txg >= 0) setTxGain(txg / 100.0f);
// Start/stop TX_CHRONO when a TCI client sets trx state.
// WSJT-X only sends TX audio in response to TX_CHRONO (type=3) frames.
if (trimmed.startsWith("trx:")) {
int colonIdx2 = trimmed.indexOf(':');
QStringList parts = trimmed.mid(colonIdx2 + 1).split(',');
if (parts.size() >= 2) {
int trx = parts[0].trimmed().toInt();
bool txOn = (parts[1].trimmed() == "true");
// Parse optional third argument: audio source / keying origin.
// WSJT-X/JTDX running in ExpertSDR3 compatibility mode send
// `trx:<rx>,true,tci`, but they still expect TX_CHRONO timing
// frames and deliver TX audio over the TCI binary stream.
// Treat `tci` the same as the legacy empty / `dax` cases.
//
// Only explicit hardware-style sources should bypass TX_CHRONO
// and key the radio directly.
// Unkey path runs stopTxChrono() + setTransmit(false)
// unconditionally so either flavor of TX cleans up, even if
// the client omits arg3 on the release message (#1534).
QString source;
if (parts.size() >= 3)
source = parts[2].trimmed().toLower().remove(';');
// The default DAX-routed path was unconditionally
// enabling dax=1 on the slice the moment a TCI client
// keyed up. For voice modes (USB / LSB / AM / FM /
// CW) this clobbered the user's PC mic selection and
// they'd lose audio mid-QSO. Restrict the DAX path to
// the modes that actually use it: clients still ask
// for DAX explicitly via `,dax` / `,tci` source args,
// but the empty-source default now picks the route
// based on the slice's mode (issue #2304).
const bool isDigitalMode = [&] {
if (!m_model) return false;
// Same TRX→slice lookup that TciProtocol uses:
// index into m_model->slices() with trx, fall back
// to by-id, then to first slice.
auto sl = m_model->slices();
SliceModel* s = nullptr;
if (trx >= 0 && trx < sl.size()) {
s = sl.at(trx);
} else {
for (auto* cand : sl)
if (cand && cand->sliceId() == trx) { s = cand; break; }
if (!s && !sl.isEmpty()) s = sl.first();
}
if (!s) return false;
const QString m = s->mode();
return m == QStringLiteral("DIGU")
|| m == QStringLiteral("DIGL")
|| m == QStringLiteral("RTTY")
|| m == QStringLiteral("FDV")
|| m == QStringLiteral("FDVU")
|| m == QStringLiteral("FDVL");
}();
const bool wantDax = source == QStringLiteral("dax")
|| source == QStringLiteral("tci")
|| (source.isEmpty() && isDigitalMode);
qCInfo(lcCat) << "TCI: trx request"
<< "trx=" << trx
<< "txOn=" << txOn
<< "source=" << (source.isEmpty() ? QStringLiteral("[default]") : source)
<< "isDigital=" << isDigitalMode
<< "route=" << (wantDax ? QStringLiteral("tci-audio") : QStringLiteral("radio-direct"));
if (txOn) {
if (wantDax) {
startTxChrono(ws, trx);
} else {
if (m_model) {
// Route through the PTT coordinator so
// Quindar tones (#2262) fire on hardware-PTT
// transitions too. Falls back to setMox()
// for non-phone modes; tone is a no-op when
// disabled.
QMetaObject::invokeMethod(m_model, [this]() {
m_model->transmitModel().requestPttOn(
TransmitModel::PttSource::TciHardware);
}, Qt::QueuedConnection);
}
}
} else {
stopTxChrono();
if (m_model) {
QMetaObject::invokeMethod(m_model, [this]() {
m_model->transmitModel().requestPttOff(
TransmitModel::PttSource::TciHardware);
}, Qt::QueuedConnection);
}
}
}
}
}
}
// ── Binary message handler (TX audio from TCI client) ───────────────────
void TciServer::onBinaryMessage(const QByteArray& data)
{
if (!m_audio) return;
if (data.size() < static_cast<int>(sizeof(TciAudioHeader))) return;
// Parse header
TciAudioHeader hdr;
std::memcpy(&hdr, data.constData(), sizeof(hdr));
// Only accept TX_AUDIO_STREAM (type 2)
if (hdr.type != 2) return;
const int payloadBytes = data.size() - static_cast<int>(sizeof(TciAudioHeader));
if (payloadBytes <= 0) return;
const char* payload = data.constData() + sizeof(TciAudioHeader);
// ── Convert TX audio to float32 stereo ─────────────────────────────────
// WSJT-X channels field is garbage (FIFO reuse). readAudioData() writes
// hdr.length floats to data[0..length-1]. Take the first hdr.length floats.
QByteArray pcm;
if (hdr.format == 3) {
int validFloats = static_cast<int>(hdr.length);
int availFloats = payloadBytes / static_cast<int>(sizeof(float));
if (validFloats > availFloats) validFloats = availFloats;
if (validFloats <= 0) return;
pcm = QByteArray(payload,
validFloats * static_cast<int>(sizeof(float)));
} else if (hdr.format == 0) {
int validSamples = static_cast<int>(hdr.length);
int availSamples = payloadBytes / static_cast<int>(sizeof(qint16));
if (validSamples > availSamples) validSamples = availSamples;
if (validSamples <= 0) return;
auto* src = reinterpret_cast<const qint16*>(payload);
pcm.resize(validSamples * static_cast<int>(sizeof(float)));
auto* dst = reinterpret_cast<float*>(pcm.data());
for (int i = 0; i < validSamples; ++i)
dst[i] = src[i] / 32768.0f;
}
if (pcm.isEmpty()) return;
int inputFramesSrcRate = 0; // input frames at the client-declared rate (#3914)
bool duplicatedStereo = false;
// ─── TX resampling: client-declared rate → 24kHz (radio native DAX) ──
// Resample from the rate the client declared in THIS frame (hdr.sampleRate),
// not a hardcoded 48k. WSJT-X sends 48 kHz — the common path, unchanged — but
// a client that negotiated 8/12/24 kHz (audio_samplerate) sends at that rate
// and must be resampled from it, or every tone is mis-pitched and digital
// decodes fail (#3306). Rebuild the per-session resampler only if the
// declared rate changes (rare, mid-stream); a 24 kHz client gets a 1:1
// resampler so the mono/stereo canonicalization below still runs.
{
const int declaredRate = static_cast<int>(hdr.sampleRate);
const int txSrcRate = (declaredRate == 8000 || declaredRate == 12000
|| declaredRate == 24000 || declaredRate == 48000)
? declaredRate
: 48000; // default/garbage -> WSJT-X-compatible 48k
if (!m_txResampler
|| static_cast<int>(m_txResampler->srcRate()) != txSrcRate) {
m_txResampler = std::make_unique<Resampler>(
static_cast<double>(txSrcRate), 24000.0, 4096);
}
}
// Detect mono vs stereo from payload layout.
//
// WSJT-X's TCI modulator writes the first `hdr.length` floats as duplicated
// stereo pairs (L=R), even though the payload buffer it allocates is larger.
// Treating those `hdr.length` floats as true mono doubles the apparent
// duration of every block and destroys digital-mode tones.
if (m_txResampler) {
int totalFloats = pcm.size() / static_cast<int>(sizeof(float));
int declaredSamples = static_cast<int>(hdr.length);
const auto* fSrc = reinterpret_cast<const float*>(pcm.constData());
if (hdr.format == 3 && totalFloats >= 2 && (totalFloats % 2) == 0) {
const int pairsToCheck = std::min(totalFloats / 2, 128);
int duplicatedPairs = 0;
for (int i = 0; i < pairsToCheck; ++i) {
if (std::fabs(fSrc[i * 2] - fSrc[i * 2 + 1]) < 1.0e-6f)
++duplicatedPairs;
}
duplicatedStereo = duplicatedPairs >= (pairsToCheck * 9) / 10;
}
if (duplicatedStereo) {
// WSJT-X fills `length` floats as stereo pairs in-place.
int stereoFrames = totalFloats / 2;
inputFramesSrcRate = stereoFrames;
pcm = m_txResampler->processStereoToStereo(fSrc, stereoFrames);
} else if (totalFloats <= declaredSamples) {
// True mono: upmix to stereo then resample.
int monoFrames = totalFloats;
inputFramesSrcRate = monoFrames;
pcm = m_txResampler->processMonoToStereo(fSrc, monoFrames);
} else {
// Explicit stereo: resample directly.
int stereoFrames = totalFloats / 2;
inputFramesSrcRate = stereoFrames;
pcm = m_txResampler->processStereoToStereo(fSrc, stereoFrames);
}
if (pcm.isEmpty()) return;
}
auto* dst = reinterpret_cast<float*>(pcm.data());
const int outputStereoFrames = pcm.size() / (2 * static_cast<int>(sizeof(float)));
const int outputSamples = pcm.size() / static_cast<int>(sizeof(float));
double sumSq = 0.0;
float peak = 0.0f;
qint64 clipSamples = 0;
// Three overflow regimes selectable via right-click on the TCI TX slider:
// Clip — saturating clamp at ±1.0; cheap defensive limiter,
// introduces harmonics on overshoots but protects the
// radio float→int16 stage from out-of-range input.
// NaNGuard — pass everything except NaN/Inf (which the radio can't
// digest); preserves bit-exact tones for well-formed
// digital clients, accepts that a malformed >1.0 client
// will reach the radio.
// Measure — pure bypass: count overshoots for telemetry but never
// touch sample data. 100% client-side passthrough.
switch (m_overflowMode) {
case OverflowMode::Clip:
for (int i = 0; i < outputSamples; ++i) {
float v = dst[i] * m_txGain;
if (v > 1.0f) { v = 1.0f; ++clipSamples; }
else if (v < -1.0f) { v = -1.0f; ++clipSamples; }
dst[i] = v;
peak = std::max(peak, std::abs(v));
sumSq += static_cast<double>(v) * static_cast<double>(v);
}
break;
case OverflowMode::NaNGuard:
for (int i = 0; i < outputSamples; ++i) {
float v = dst[i] * m_txGain;
if (!std::isfinite(v)) { v = 0.0f; ++clipSamples; }
else if (std::abs(v) > 1.0f) ++clipSamples;
dst[i] = v;
peak = std::max(peak, std::abs(v));
sumSq += static_cast<double>(v) * static_cast<double>(v);
}
break;
case OverflowMode::Measure:
for (int i = 0; i < outputSamples; ++i) {
const float v = dst[i] * m_txGain;
dst[i] = v;
if (!std::isfinite(v) || std::abs(v) > 1.0f) ++clipSamples;
const float absV = std::isfinite(v) ? std::abs(v) : 0.0f;
peak = std::max(peak, absV);
sumSq += std::isfinite(v)