-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinterconnect.h
More file actions
1831 lines (1617 loc) · 71.5 KB
/
Copy pathinterconnect.h
File metadata and controls
1831 lines (1617 loc) · 71.5 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
// interconnect.h — Prodigy shared inter-service communication layer.
//
// Architecture overview:
// All pipeline services communicate exclusively through this header.
// The pipeline is a linear chain of 7 C++ processes:
//
// SIP_CLIENT → IAP → VAD → WHISPER → LLAMA → TTS → OAP → SIP_CLIENT (loop)
//
// Every adjacent pair shares two persistent TCP connections:
// • mgmt channel (base port +0): carries typed control messages
// (CALL_END, SPEECH_ACTIVE/IDLE, PING/PONG, CUSTOM).
// • data channel (base port +1): carries binary Packet frames
// (audio PCM, text payloads, G.711 frames).
//
// InterconnectNode encapsulates both directions for a single service:
// • Listen sockets accept the upstream neighbor's connections.
// • Outbound sockets connect to the downstream neighbor's listen ports.
// • A background reconnect loop retries downstream connections every
// DOWNSTREAM_RECONNECT_MS (200ms) until the neighbor is reachable.
//
// LogForwarder sends structured log entries as UDP datagrams to the
// frontend log server (port 22022). Each datagram is a plain-text line:
// "<SERVICE> <LEVEL> <CALL_ID> <message>"
// The log_level_ gate filters below-threshold messages before send.
//
// Shared utilities (also used by frontend.cpp for the offline IAP quality
// test) include the G.711 μ-law → float32 LUT and the polyphase FIR
// half-band upsample kernel (iap_fir_upsample_frame).
//
// Port map (all on 127.0.0.1):
// SIP_CLIENT (13100/13101/13102), IAP (13110/13111/13112)
// VAD (13115/13116/13117), WHISPER (13120/13121/13122)
// LLAMA (13130/13131/13132), TTS (13140/13141/13142/13143)
// OAP (13150/13151/13152), MOSHI_SERVICE (13155/13156/13157)
// FRONTEND (13160/13161/13162), TOMEDO_CRAWL (13180/13181/13182)
// Log UDP: 22022
//
// Usage pattern for a service:
// 1. Construct InterconnectNode(ServiceType::MY_SERVICE)
// 2. Call initialize() — binds listen ports and starts background threads.
// 3. Call connect_to_downstream() — non-blocking; reconnect loop handles retries.
// 4. Register call_end_handler / speech_signal_handler as needed.
// 5. In processing loop: recv_from_upstream() / send_to_downstream().
// 6. On shutdown: call shutdown() (or let destructor do it).
#pragma once
#include <cstdint>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include <mutex>
#include <thread>
#include <atomic>
#include <optional>
#include <functional>
#include <chrono>
#include <set>
#include <algorithm>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <cerrno>
#include <cstdio>
#include <cstdarg>
#include "tls_cert.h"
namespace whispertalk {
static constexpr uint16_t FRONTEND_LOG_PORT = 22022;
// Half-band FIR low-pass filter for 8kHz → 16kHz upsampling.
// 15-tap Hamming-windowed sinc, cutoff ~3.8kHz, ~40dB stopband attenuation.
// Used by IAP (inbound-audio-processor.cpp) and the offline codec quality test
// (frontend.cpp handle_iap_quality_test). Both must use the same filter to
// ensure test results match real pipeline behaviour.
static constexpr int IAP_FIR_LEN = 15;
static constexpr int IAP_FIR_CENTER = 7;
static constexpr int IAP_ULAW_FRAME = 160;
// 3-phase polyphase FIR for 8kHz → 24kHz upsampling (3× interpolation).
// 24-tap Hamming-windowed sinc, cutoff 4kHz, unity output gain.
// Decomposed into 3 polyphase sub-filters of 8 taps each (each sums to ~1.0).
// IAP_ULAW_OUT_24K: output samples per 160-sample input frame (160 * 3 = 480).
static constexpr int IAP_FIR_24K_LEN = 24;
static constexpr int IAP_FIR_24K_CENTER = 12;
static constexpr int IAP_ULAW_OUT_24K = 480;
inline const float* iap_fir_coeffs() {
static const float coeffs[IAP_FIR_LEN] = {
-0.0076f, 0.0000f, 0.0527f, 0.0000f, -0.1681f, 0.0000f, 0.6230f,
1.0000f,
0.6230f, 0.0000f, -0.1681f, 0.0000f, 0.0527f, 0.0000f, -0.0076f
};
return coeffs;
}
// Polyphase FIR half-band upsample: 8kHz → 16kHz via 2× zero-stuff + 15-tap filter.
// Exploits half-band structure: odd taps (1,3,5,9,11,13) are zero, center tap (7) = 1.0.
// Odd outputs: out[2i+1] = x[i - 3] (delayed passthrough)
// Even outputs: out[2i] = sum of 8 non-zero taps (8 MACs vs 15 branchy iterations)
// Each polyphase branch has DC gain = 1.0 (even coeffs sum to 1.0, odd = center tap 1.0).
// ~3.7× fewer operations than the naive FIR loop.
// `history` must point to IAP_FIR_CENTER floats that persist across calls.
// Returns number of output samples written (= in_len * 2).
inline size_t iap_fir_upsample_frame(const float* in, size_t in_len,
float* out, float* history) {
if (in_len > (size_t)IAP_ULAW_FRAME) in_len = IAP_ULAW_FRAME;
if (in_len == 0) return 0;
static constexpr float H0 = -0.0076f;
static constexpr float H2 = 0.0527f;
static constexpr float H4 = -0.1681f;
static constexpr float H6 = 0.6230f;
float ext[IAP_FIR_CENTER + IAP_ULAW_FRAME];
for (int i = 0; i < IAP_FIR_CENTER; i++) ext[i] = history[i];
for (size_t i = 0; i < in_len; i++) ext[IAP_FIR_CENTER + i] = in[i];
size_t out_len = in_len * 2;
const int N = (int)in_len;
for (int i = 0; i < N; i++) {
const float* x = ext + i;
float even = H0 * x[7] + H2 * x[6] + H4 * x[5] + H6 * x[4]
+ H6 * x[3] + H4 * x[2] + H2 * x[1] + H0 * x[0];
out[2 * i] = even;
out[2 * i + 1] = ext[i + 4];
}
if (in_len >= (size_t)IAP_FIR_CENTER) {
for (int i = 0; i < IAP_FIR_CENTER; i++)
history[i] = in[in_len - IAP_FIR_CENTER + i];
} else {
int shift = (int)in_len;
for (int i = 0; i < IAP_FIR_CENTER - shift; i++) history[i] = history[i + shift];
for (int i = 0; i < shift; i++) history[IAP_FIR_CENTER - shift + i] = in[i];
}
return out_len;
}
// 3-phase polyphase FIR upsample: 8kHz → 24kHz via 3× zero-stuff + 24-tap filter.
// Each input sample produces 3 output samples via 3 polyphase sub-filters.
// Sub-filter p selects coefficients h[p], h[p+3], h[p+6], ..., h[p+21] (8 taps each).
// Each sub-filter sums to ~1.0 so output amplitude matches input (unity DC gain).
// `history` must point to IAP_FIR_24K_CENTER floats that persist across calls.
// Returns number of output samples written (= in_len * 3).
inline size_t iap_fir_upsample_frame_24k(const float* in, size_t in_len,
float* out, float* history) {
if (in_len > (size_t)IAP_ULAW_FRAME) in_len = IAP_ULAW_FRAME;
if (in_len == 0) return 0;
// h[n] = sinc((n - 11.5) / 3) * (0.54 - 0.46 * cos(2πn/23)), n = 0..23
// Symmetric: h[n] == h[23-n]. Phase sums: p0 ≈ 0.997, p1 ≈ 0.996, p2 ≈ 0.997.
static constexpr float H[IAP_FIR_24K_LEN] = {
-0.003321f, -0.008827f, -0.007386f,
0.012696f, 0.041809f, 0.032792f,
-0.049604f, -0.147281f, -0.109854f,
0.171281f, 0.612376f, 0.950838f,
0.950838f, 0.612376f, 0.171281f,
-0.109854f, -0.147281f, -0.049604f,
0.032792f, 0.041809f, 0.012696f,
-0.007386f, -0.008827f, -0.003321f
};
float ext[IAP_FIR_24K_CENTER + IAP_ULAW_FRAME];
for (int i = 0; i < IAP_FIR_24K_CENTER; i++) ext[i] = history[i];
for (size_t i = 0; i < in_len; i++) ext[IAP_FIR_24K_CENTER + i] = in[i];
const int N = (int)in_len;
for (int i = 0; i < N; i++) {
const float* x = ext + i;
for (int p = 0; p < 3; p++) {
float acc = 0.0f;
for (int k = 0; k < 8; k++) {
acc += H[p + 3 * k] * x[IAP_FIR_24K_CENTER - k];
}
out[3 * i + p] = acc;
}
}
if (in_len >= (size_t)IAP_FIR_24K_CENTER) {
for (int i = 0; i < IAP_FIR_24K_CENTER; i++)
history[i] = in[in_len - IAP_FIR_24K_CENTER + i];
} else {
int shift = (int)in_len;
for (int i = 0; i < IAP_FIR_24K_CENTER - shift; i++) history[i] = history[i + shift];
for (int i = 0; i < shift; i++) history[IAP_FIR_24K_CENTER - shift + i] = in[i];
}
return in_len * 3;
}
// ServiceType — identifies each process in the Prodigy system.
//
// Pipeline services (is_pipeline_service() == true):
// SIP_CLIENT, INBOUND_AUDIO_PROCESSOR, VAD_SERVICE, WHISPER_SERVICE,
// LLAMA_SERVICE, TTS_SERVICE, OUTBOUND_AUDIO_PROCESSOR, MOSHI_SERVICE
//
// Sidecar services (is_pipeline_service() == false):
// FRONTEND (13160) — web UI and log aggregator; not in the audio path.
// TOMEDO_CRAWL_SERVICE (13180) — RAG sidecar; connects to the Tomedo EMR
// server and populates a local vector store. llama-service queries it
// via plain HTTP (GET /query, GET /caller/{id}) to retrieve patient context
// before inference. It is NOT wired into the interconnect pipeline graph
// (no up/downstream_of() entry, no Packet frames) — all communication is
// via its own REST API at port 13181.
enum class ServiceType : uint8_t {
SIP_CLIENT = 1,
INBOUND_AUDIO_PROCESSOR = 2,
VAD_SERVICE = 8,
WHISPER_SERVICE = 3,
LLAMA_SERVICE = 4,
TTS_SERVICE = 5, // generic TTS stage/dock; engines (kokoro, neutts, ...) connect via engine-dock port
OUTBOUND_AUDIO_PROCESSOR = 6,
FRONTEND = 7,
MOSHI_SERVICE = 9, // Moshi full-duplex neural voice service; replaces VAD+WHISPER+LLAMA+TTS in moshi mode
TOMEDO_CRAWL_SERVICE = 10 // RAG sidecar; REST API only, not in pipeline graph
};
inline bool is_pipeline_service(ServiceType type) {
switch (type) {
case ServiceType::SIP_CLIENT:
case ServiceType::INBOUND_AUDIO_PROCESSOR:
case ServiceType::VAD_SERVICE:
case ServiceType::WHISPER_SERVICE:
case ServiceType::LLAMA_SERVICE:
case ServiceType::TTS_SERVICE:
case ServiceType::OUTBOUND_AUDIO_PROCESSOR:
case ServiceType::MOSHI_SERVICE:
return true;
default:
return false;
}
}
inline const char* service_type_to_string(ServiceType type) {
switch (type) {
case ServiceType::SIP_CLIENT: return "SIP_CLIENT";
case ServiceType::INBOUND_AUDIO_PROCESSOR: return "INBOUND_AUDIO_PROCESSOR";
case ServiceType::VAD_SERVICE: return "VAD_SERVICE";
case ServiceType::WHISPER_SERVICE: return "WHISPER_SERVICE";
case ServiceType::LLAMA_SERVICE: return "LLAMA_SERVICE";
case ServiceType::TTS_SERVICE: return "TTS_SERVICE";
case ServiceType::OUTBOUND_AUDIO_PROCESSOR: return "OUTBOUND_AUDIO_PROCESSOR";
case ServiceType::FRONTEND: return "FRONTEND";
case ServiceType::MOSHI_SERVICE: return "MOSHI_SERVICE";
case ServiceType::TOMEDO_CRAWL_SERVICE: return "TOMEDO_CRAWL";
default: return "UNKNOWN";
}
}
// Pipeline topology (classic mode):
// SIP_CLIENT -> IAP -> VAD -> WHISPER -> LLAMA -> TTS -> OAP -> SIP_CLIENT (loop)
// Pipeline topology (moshi mode):
// SIP_CLIENT -> IAP -> MOSHI_SERVICE -> OAP -> SIP_CLIENT (loop)
// "downstream" = the service we SEND data TO (next in pipeline)
// "upstream" = the service that sends data TO US (previous in pipeline)
inline ServiceType upstream_of(ServiceType type) {
switch (type) {
case ServiceType::INBOUND_AUDIO_PROCESSOR: return ServiceType::SIP_CLIENT;
case ServiceType::VAD_SERVICE: return ServiceType::INBOUND_AUDIO_PROCESSOR;
case ServiceType::WHISPER_SERVICE: return ServiceType::VAD_SERVICE;
case ServiceType::LLAMA_SERVICE: return ServiceType::WHISPER_SERVICE;
case ServiceType::TTS_SERVICE: return ServiceType::LLAMA_SERVICE;
case ServiceType::OUTBOUND_AUDIO_PROCESSOR: return ServiceType::TTS_SERVICE;
case ServiceType::MOSHI_SERVICE: return ServiceType::INBOUND_AUDIO_PROCESSOR;
case ServiceType::SIP_CLIENT: return ServiceType::OUTBOUND_AUDIO_PROCESSOR;
default: return ServiceType::SIP_CLIENT;
}
}
inline ServiceType downstream_of(ServiceType type) {
switch (type) {
case ServiceType::SIP_CLIENT: return ServiceType::INBOUND_AUDIO_PROCESSOR;
case ServiceType::INBOUND_AUDIO_PROCESSOR: return ServiceType::VAD_SERVICE;
case ServiceType::VAD_SERVICE: return ServiceType::WHISPER_SERVICE;
case ServiceType::WHISPER_SERVICE: return ServiceType::LLAMA_SERVICE;
case ServiceType::LLAMA_SERVICE: return ServiceType::TTS_SERVICE;
case ServiceType::TTS_SERVICE: return ServiceType::OUTBOUND_AUDIO_PROCESSOR;
case ServiceType::MOSHI_SERVICE: return ServiceType::OUTBOUND_AUDIO_PROCESSOR;
case ServiceType::OUTBOUND_AUDIO_PROCESSOR: return ServiceType::SIP_CLIENT;
default: return ServiceType::SIP_CLIENT;
}
}
struct PacketTrace {
static constexpr int MAX_HOPS = 8;
struct Hop {
uint8_t service_id;
uint8_t direction;
uint64_t timestamp_us;
};
Hop hops[MAX_HOPS];
uint8_t hop_count = 0;
void record(ServiceType svc, uint8_t dir) {
if (hop_count < MAX_HOPS) {
hops[hop_count].service_id = static_cast<uint8_t>(svc);
hops[hop_count].direction = dir;
hops[hop_count].timestamp_us = now_us();
hop_count++;
}
}
static uint64_t now_us() {
return static_cast<uint64_t>(
std::chrono::duration_cast<std::chrono::microseconds>(
std::chrono::steady_clock::now().time_since_epoch()).count());
}
double total_ms() const {
if (hop_count < 2) return 0;
return (hops[hop_count - 1].timestamp_us - hops[0].timestamp_us) / 1000.0;
}
double hop_ms(int i) const {
if (i <= 0 || i >= hop_count) return 0;
return (hops[i].timestamp_us - hops[i - 1].timestamp_us) / 1000.0;
}
void print_trace() const {
if (hop_count == 0) return;
std::fprintf(stderr, " TRACE: ");
for (int i = 0; i < hop_count; i++) {
if (i > 0) std::fprintf(stderr, " -> ");
std::fprintf(stderr, "%s[%s](+%.2fms)",
service_type_name(hops[i].service_id),
hops[i].direction == 0 ? "IN" : "OUT",
i > 0 ? hop_ms(i) : 0.0);
}
std::fprintf(stderr, " = %.2fms total\n", total_ms());
}
static const char* service_type_name(uint8_t id) {
switch (id) {
case 1: return "SIP";
case 2: return "IAP";
case 8: return "VAD";
case 3: return "WHI";
case 4: return "LLM";
case 5: return "TTS";
case 6: return "OAP";
case 7: return "FRN";
case 9: return "MSH";
case 10: return "RAG";
default: return "???";
}
}
};
// Fixed port assignment per service. Each service gets a base port.
// From that base: +0 = mgmt listen (from upstream), +1 = data listen (from upstream)
// The service CONNECTS to its downstream neighbor's listen ports.
//
// Port map (all on 127.0.0.1):
// SIP_CLIENT (base 13100): mgmt_listen=13100, data_listen=13101
// IAP (base 13110): mgmt_listen=13110, data_listen=13111
// VAD (base 13115): mgmt_listen=13115, data_listen=13116
// WHISPER (base 13120): mgmt_listen=13120, data_listen=13121
// LLAMA (base 13130): mgmt_listen=13130, data_listen=13131
// TTS (base 13140): mgmt_listen=13140, data_listen=13141, engine_listen=13143
// OAP (base 13150): mgmt_listen=13150, data_listen=13151
// MOSHI (base 13155): mgmt_listen=13155, data_listen=13156, cmd_listen=13157
// FRONTEND (base 13160): mgmt_listen=13160, data_listen=13161
// TOMEDO_CRAWL (base 13180): mgmt_listen=13180, data_listen=13181
//
// Data flow example: SIP sends data to IAP by connecting to IAP's data_listen (13111).
// IAP sends management msgs to SIP by connecting to SIP's mgmt_listen (13100).
inline uint16_t service_base_port(ServiceType type) {
switch (type) {
case ServiceType::SIP_CLIENT: return 13100;
case ServiceType::INBOUND_AUDIO_PROCESSOR: return 13110;
case ServiceType::VAD_SERVICE: return 13115;
case ServiceType::WHISPER_SERVICE: return 13120;
case ServiceType::LLAMA_SERVICE: return 13130;
case ServiceType::TTS_SERVICE: return 13140;
case ServiceType::OUTBOUND_AUDIO_PROCESSOR: return 13150;
case ServiceType::FRONTEND: return 13160;
case ServiceType::MOSHI_SERVICE: return 13155;
case ServiceType::TOMEDO_CRAWL_SERVICE: return 13180;
default: return 0;
}
}
inline uint16_t service_mgmt_port(ServiceType type) { return service_base_port(type); }
inline uint16_t service_data_port(ServiceType type) { return service_base_port(type) + 1; }
// Command port: for out-of-band text commands from the frontend (e.g., ADD_LINE, GET_STATS).
// Only services that need frontend commands use this (+2 offset).
inline uint16_t service_cmd_port(ServiceType type) { return service_base_port(type) + 2; }
// Engine-dock port: TTS_SERVICE only. TTS engines (kokoro, neutts, ...) open a local
// TCP connection to this port and send a HELLO line to dock with the generic TTS
// stage. Returns 0 for services that do not expose an engine-dock listener.
inline uint16_t service_engine_port(ServiceType type) {
switch (type) {
case ServiceType::TTS_SERVICE: return service_base_port(type) + 3;
default: return 0;
}
}
struct Packet {
static constexpr uint32_t MAX_PAYLOAD_SIZE = 1024 * 1024;
uint32_t call_id;
uint32_t payload_size;
std::vector<uint8_t> payload;
PacketTrace trace;
Packet() : call_id(0), payload_size(0) {}
Packet(uint32_t cid, const void* data, uint32_t size)
: call_id(cid), payload_size(std::min(size, MAX_PAYLOAD_SIZE)) {
if (size > MAX_PAYLOAD_SIZE) {
std::fprintf(stderr, "Packet: payload %u exceeds max %u, truncating\n",
size, MAX_PAYLOAD_SIZE);
}
if (payload_size > 0 && data != nullptr) {
payload.resize(payload_size);
memcpy(payload.data(), data, payload_size);
}
}
bool is_valid() const {
return call_id != 0 && payload_size <= MAX_PAYLOAD_SIZE && payload.size() == payload_size;
}
std::vector<uint8_t> serialize() const {
std::vector<uint8_t> buffer(8 + payload_size);
serialize_into(buffer.data());
return buffer;
}
void serialize_into(uint8_t* buffer) const {
uint32_t net_call_id = htonl(call_id);
uint32_t net_size = htonl(payload_size);
memcpy(buffer, &net_call_id, 4);
memcpy(buffer + 4, &net_size, 4);
if (payload_size > 0) {
memcpy(buffer + 8, payload.data(), payload_size);
}
}
size_t serialized_size() const { return 8 + payload_size; }
static bool deserialize(const void* data, size_t len, Packet& out) {
if (len < 8) return false;
const uint8_t* ptr = static_cast<const uint8_t*>(data);
uint32_t net_call_id, net_size;
memcpy(&net_call_id, ptr, 4);
memcpy(&net_size, ptr + 4, 4);
out.call_id = ntohl(net_call_id);
out.payload_size = ntohl(net_size);
if (out.call_id == 0 || out.payload_size > MAX_PAYLOAD_SIZE) {
return false;
}
if (len < 8 + out.payload_size) {
return false;
}
out.payload.resize(out.payload_size);
if (out.payload_size > 0) {
memcpy(out.payload.data(), ptr + 8, out.payload_size);
}
return true;
}
};
enum class ConnectionState {
DISCONNECTED,
CONNECTING,
CONNECTED,
FAILED
};
// Management message types sent over the mgmt channel.
// Format: 1-byte type, then type-specific payload.
enum class MgmtMsgType : uint8_t {
CALL_END = 1, // payload: 4 bytes call_id
SPEECH_ACTIVE = 2, // payload: 4 bytes call_id
SPEECH_IDLE = 3, // payload: 4 bytes call_id
PING = 4, // no payload (keepalive probe)
PONG = 5, // no payload (keepalive response)
CUSTOM = 10, // payload: 2-byte len + string
};
// InterconnectNode — per-service TCP communication hub.
//
// Lifecycle:
// initialize() → bind listen sockets, start 3 background threads.
// connect_to_downstream() → one-shot attempt; reconnect_loop retries forever.
// send_to_downstream(pkt) → send data packet to next service in pipeline.
// recv_from_upstream(pkt) → blocking receive from previous service (with timeout).
// broadcast_call_end(id) → notify downstream chain that a call has terminated.
// broadcast_speech_signal() → propagate VAD SPEECH_ACTIVE/IDLE downstream.
// shutdown() → close all sockets, join threads (idempotent).
//
// Thread model (3 background threads per node):
// accept_thread_: waits for upstream to connect on our listen ports;
// polls for dead connections and resets them.
// downstream_connect_thread_: polls downstream state; reconnects every 200ms on failure.
// mgmt_recv_thread_: reads typed messages from upstream mgmt socket;
// dispatches call_end / speech / ping / custom handlers.
//
// Safety: All socket accesses are guarded by per-direction mutexes. Sockets are
// closed with shutdown(SHUT_RDWR) before close() so blocked threads unblock.
class InterconnectNode {
public:
InterconnectNode(ServiceType type)
: type_(type),
running_(false),
max_known_call_id_(0),
mgmt_listen_sock_(-1),
data_listen_sock_(-1),
upstream_mgmt_accepted_(-1),
upstream_data_accepted_(-1),
downstream_mgmt_sock_(-1),
downstream_data_sock_(-1),
upstream_state_(ConnectionState::DISCONNECTED),
downstream_state_(ConnectionState::DISCONNECTED) {}
~InterconnectNode() {
shutdown();
}
bool initialize() {
if (!is_pipeline_service(type_)) {
running_ = true;
return true;
}
uint16_t mgmt_port = service_mgmt_port(type_);
uint16_t data_port = service_data_port(type_);
mgmt_listen_sock_ = create_listen_socket(mgmt_port);
if (mgmt_listen_sock_ < 0) {
std::fprintf(stderr, "[%s] Failed to bind mgmt port %u\n",
service_type_to_string(type_), mgmt_port);
return false;
}
data_listen_sock_ = create_listen_socket(data_port);
if (data_listen_sock_ < 0) {
close_socket(mgmt_listen_sock_);
std::fprintf(stderr, "[%s] Failed to bind data port %u\n",
service_type_to_string(type_), data_port);
return false;
}
running_ = true;
accept_thread_ = std::thread(&InterconnectNode::accept_loop, this);
if (downstream_connections_.empty() && !connect_disabled_) {
downstream_connect_thread_ = std::thread(&InterconnectNode::downstream_connect_loop, this);
}
mgmt_recv_thread_ = std::thread(&InterconnectNode::mgmt_recv_loop, this);
std::fprintf(stderr, "[%s] Interconnect ready: mgmt=%u data=%u\n",
service_type_to_string(type_), mgmt_port, data_port);
return true;
}
void shutdown() {
if (!running_.exchange(false)) return;
close_socket(upstream_mgmt_accepted_);
close_socket(upstream_data_accepted_);
close_socket(downstream_mgmt_sock_);
close_socket(downstream_data_sock_);
close_socket(mgmt_listen_sock_);
close_socket(data_listen_sock_);
for (auto& dc : downstream_connections_) {
close_socket(dc->data_sock);
close_socket(dc->mgmt_sock);
}
for (auto& dc : downstream_connections_) {
if (dc->reconnect_thread.joinable()) dc->reconnect_thread.join();
}
if (accept_thread_.joinable()) accept_thread_.join();
if (downstream_connect_thread_.joinable()) downstream_connect_thread_.join();
if (mgmt_recv_thread_.joinable()) mgmt_recv_thread_.join();
}
ServiceType type() const { return type_; }
void set_downstream_override(ServiceType override_type) {
std::lock_guard<std::mutex> lock(state_mutex_);
downstream_override_ = override_type;
}
void clear_downstream_override() {
std::lock_guard<std::mutex> lock(state_mutex_);
downstream_override_.reset();
}
ConnectionState upstream_state() const {
std::lock_guard<std::mutex> lock(state_mutex_);
return upstream_state_;
}
ConnectionState downstream_state() const {
std::lock_guard<std::mutex> lock(state_mutex_);
return downstream_state_;
}
// Connect to downstream neighbor's listen ports.
// Called once at startup; reconnect_loop handles retries.
// If set_downstream_override() was called, connects to that service instead.
bool connect_to_downstream() {
if (!is_pipeline_service(type_)) return false;
if (connect_disabled_) return false;
ServiceType ds;
{
std::lock_guard<std::mutex> lock(state_mutex_);
ds = downstream_override_.value_or(downstream_of(type_));
}
uint16_t ds_mgmt = service_mgmt_port(ds);
uint16_t ds_data = service_data_port(ds);
{
std::lock_guard<std::mutex> lock(state_mutex_);
downstream_state_ = ConnectionState::CONNECTING;
}
int mgmt_sock = connect_to_port_with_timeout("127.0.0.1", ds_mgmt, CONNECT_TIMEOUT_MS);
if (mgmt_sock < 0) {
std::lock_guard<std::mutex> lock(state_mutex_);
downstream_state_ = ConnectionState::DISCONNECTED;
return false;
}
int data_sock = connect_to_port_with_timeout("127.0.0.1", ds_data, CONNECT_TIMEOUT_MS);
if (data_sock < 0) {
::close(mgmt_sock);
std::lock_guard<std::mutex> lock(state_mutex_);
downstream_state_ = ConnectionState::DISCONNECTED;
return false;
}
setup_socket_options(mgmt_sock);
setup_socket_options(data_sock);
{
std::lock_guard<std::mutex> lock(downstream_mutex_);
close_socket(downstream_mgmt_sock_);
close_socket(downstream_data_sock_);
downstream_mgmt_sock_ = mgmt_sock;
downstream_data_sock_ = data_sock;
}
{
std::lock_guard<std::mutex> lock(state_mutex_);
downstream_state_ = ConnectionState::CONNECTED;
}
std::fprintf(stderr, "[%s] Connected to downstream %s (mgmt=%u data=%u)\n",
service_type_to_string(type_),
service_type_to_string(ds), ds_mgmt, ds_data);
return true;
}
// Send a data packet to our downstream neighbor (next in pipeline).
// SIP -> IAP: SIP calls send_to_downstream, which writes to IAP's data_listen.
bool send_to_downstream(const Packet& pkt) {
std::lock_guard<std::mutex> lock(send_downstream_mutex_);
int sock;
{
std::lock_guard<std::mutex> dl(downstream_mutex_);
sock = downstream_data_sock_;
}
if (sock < 0) return false;
auto data = pkt.serialize();
if (!send_encrypted(sock, data.data(), data.size(), DATA_SEND_TIMEOUT_MS)) {
mark_downstream_failed();
return false;
}
return true;
}
// Send a data packet back to upstream neighbor (reverse direction, e.g. OAP -> SIP).
bool send_to_upstream(const Packet& pkt) {
std::lock_guard<std::mutex> lock(send_upstream_mutex_);
int sock;
{
std::lock_guard<std::mutex> ul(upstream_mutex_);
sock = upstream_data_accepted_;
}
if (sock < 0) return false;
auto data = pkt.serialize();
if (!send_encrypted(sock, data.data(), data.size(), DATA_SEND_TIMEOUT_MS)) {
mark_upstream_failed();
return false;
}
return true;
}
// Receive data from upstream neighbor (they connected to our data_listen port).
bool recv_from_upstream(Packet& pkt, int timeout_ms = 100) {
int sock;
{
std::lock_guard<std::mutex> lock(upstream_mutex_);
sock = upstream_data_accepted_;
}
if (sock < 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(timeout_ms));
return false;
}
bool ok = recv_packet(sock, pkt, timeout_ms);
if (!ok) {
std::lock_guard<std::mutex> lock(upstream_mutex_);
if (upstream_data_accepted_ == sock && is_socket_dead(sock)) {
mark_upstream_failed_locked();
}
}
return ok;
}
// Receive data from downstream neighbor (we connected to their data_listen, they reply).
bool recv_from_downstream(Packet& pkt, int timeout_ms = 100) {
int sock;
{
std::lock_guard<std::mutex> lock(downstream_mutex_);
sock = downstream_data_sock_;
}
if (sock < 0) {
std::this_thread::sleep_for(std::chrono::milliseconds(timeout_ms));
return false;
}
bool ok = recv_packet(sock, pkt, timeout_ms);
if (!ok) {
std::lock_guard<std::mutex> lock(downstream_mutex_);
if (downstream_data_sock_ == sock && is_socket_dead(sock)) {
mark_downstream_failed_locked();
}
}
return ok;
}
// Call ID management — local only, no master needed.
// Each service can independently assign call IDs since only SIP_CLIENT creates them.
uint32_t reserve_call_id(uint32_t proposed_id) {
std::lock_guard<std::mutex> lock(call_id_mutex_);
uint32_t final_id = (proposed_id > max_known_call_id_) ? proposed_id : max_known_call_id_ + 1;
max_known_call_id_ = final_id;
active_call_ids_.insert(final_id);
return final_id;
}
// Broadcast CALL_END to downstream neighbor via mgmt channel.
void broadcast_call_end(uint32_t call_id) {
bool already_ended = false;
{
std::lock_guard<std::mutex> lock(call_id_mutex_);
if (ended_call_ids_.count(call_id) > 0) {
already_ended = true;
}
ended_call_ids_.insert(call_id);
active_call_ids_.erase(call_id);
prune_ended_call_ids();
}
{
std::lock_guard<std::mutex> lock(speech_mutex_);
speech_active_calls_.erase(call_id);
}
if (!already_ended && call_end_handler_) {
call_end_handler_(call_id);
}
send_mgmt_to_downstream(MgmtMsgType::CALL_END, call_id);
}
void register_call_end_handler(std::function<void(uint32_t)> handler) {
call_end_handler_ = handler;
}
void broadcast_speech_signal(uint32_t call_id, bool active) {
{
std::lock_guard<std::mutex> lock(speech_mutex_);
if (active) speech_active_calls_.insert(call_id);
else speech_active_calls_.erase(call_id);
}
if (speech_signal_handler_) {
speech_signal_handler_(call_id, active);
}
MgmtMsgType msg_type = active ? MgmtMsgType::SPEECH_ACTIVE : MgmtMsgType::SPEECH_IDLE;
send_mgmt_to_downstream(msg_type, call_id);
}
void register_speech_signal_handler(std::function<void(uint32_t, bool)> handler) {
speech_signal_handler_ = handler;
}
void register_custom_negotiation_handler(std::function<std::string(const std::string&)> handler) {
custom_handler_ = handler;
}
bool is_speech_active(uint32_t call_id) const {
std::lock_guard<std::mutex> lock(speech_mutex_);
return speech_active_calls_.count(call_id) > 0;
}
bool has_ended(uint32_t call_id) const {
std::lock_guard<std::mutex> lock(call_id_mutex_);
return ended_call_ids_.count(call_id) > 0;
}
size_t active_call_count() const {
std::lock_guard<std::mutex> lock(call_id_mutex_);
return active_call_ids_.size();
}
size_t ended_call_count() const {
std::lock_guard<std::mutex> lock(call_id_mutex_);
return ended_call_ids_.size();
}
uint16_t frontend_log_port() const { return FRONTEND_LOG_PORT; }
// Send a custom command to our downstream's mgmt channel and wait for response.
std::string send_custom_to_downstream(const std::string& msg, int timeout_ms = CUSTOM_MSG_TIMEOUT_MS) {
int sock;
{
std::lock_guard<std::mutex> lock(downstream_mutex_);
sock = downstream_mgmt_sock_;
}
if (sock < 0) return "";
uint16_t len = static_cast<uint16_t>(std::min(msg.size(), (size_t)65535));
std::vector<uint8_t> buf(3 + len);
buf[0] = static_cast<uint8_t>(MgmtMsgType::CUSTOM);
uint16_t net_len = htons(len);
memcpy(buf.data() + 1, &net_len, 2);
memcpy(buf.data() + 3, msg.data(), len);
std::lock_guard<std::mutex> lock(send_downstream_mgmt_mutex_);
if (!send_encrypted(sock, buf.data(), buf.size(), timeout_ms)) return "";
std::vector<uint8_t> resp_plain;
if (!recv_encrypted(sock, resp_plain, timeout_ms)) return "";
if (resp_plain.size() < 3) return "";
if (resp_plain[0] != static_cast<uint8_t>(MgmtMsgType::CUSTOM)) return "";
uint16_t resp_len;
memcpy(&resp_len, resp_plain.data() + 1, 2);
resp_len = ntohs(resp_len);
if (resp_len == 0 || resp_plain.size() < (size_t)(3 + resp_len)) return "";
return std::string(reinterpret_cast<char*>(resp_plain.data() + 3), resp_len);
}
void add_downstream_target(ServiceType target) {
downstream_connections_.push_back(std::make_unique<DownstreamConnection>(target));
}
void connect_all_downstreams() {
for (auto& dc : downstream_connections_) {
dc->reconnect_thread = std::thread(&InterconnectNode::connect_to_downstream_dc, this, std::ref(*dc));
}
}
bool send_to_downstream(const Packet& pkt, ServiceType target) {
for (auto& dc : downstream_connections_) {
if (dc->target != target) continue;
if (dc->state.load(std::memory_order_relaxed) != ConnectionState::CONNECTED) return false;
std::lock_guard<std::mutex> lock(dc->data_send_mutex);
int sock = dc->data_sock;
if (sock < 0) return false;
auto data = pkt.serialize();
if (!send_encrypted(sock, data.data(), data.size(), DATA_SEND_TIMEOUT_MS)) {
close_socket(dc->data_sock);
dc->state.store(ConnectionState::DISCONNECTED, std::memory_order_relaxed);
return false;
}
return true;
}
return false;
}
void broadcast_mgmt_to_all_downstreams(MgmtMsgType msg_type, uint32_t call_id) {
send_mgmt_to_downstream(msg_type, call_id);
}
std::string send_custom_to_downstream(const std::string& msg, ServiceType target, int timeout_ms = CUSTOM_MSG_TIMEOUT_MS) {
for (auto& dc : downstream_connections_) {
if (dc->target != target) continue;
if (dc->state.load(std::memory_order_relaxed) != ConnectionState::CONNECTED) return "";
uint16_t len = static_cast<uint16_t>(std::min(msg.size(), (size_t)65535));
std::vector<uint8_t> buf(3 + len);
buf[0] = static_cast<uint8_t>(MgmtMsgType::CUSTOM);
uint16_t net_len = htons(len);
memcpy(buf.data() + 1, &net_len, 2);
memcpy(buf.data() + 3, msg.data(), len);
std::lock_guard<std::mutex> lock(dc->mgmt_send_mutex);
int sock = dc->mgmt_sock;
if (sock < 0) return "";
if (!send_encrypted(sock, buf.data(), buf.size(), timeout_ms)) {
close_socket(dc->mgmt_sock);
dc->state.store(ConnectionState::DISCONNECTED, std::memory_order_relaxed);
return "";
}
std::vector<uint8_t> resp_plain;
if (!recv_encrypted(sock, resp_plain, timeout_ms)) {
close_socket(dc->mgmt_sock);
dc->state.store(ConnectionState::DISCONNECTED, std::memory_order_relaxed);
return "";
}
if (resp_plain.size() < 3) return "";
if (resp_plain[0] != static_cast<uint8_t>(MgmtMsgType::CUSTOM)) return "";
uint16_t resp_len;
memcpy(&resp_len, resp_plain.data() + 1, 2);
resp_len = ntohs(resp_len);
if (resp_len == 0 || resp_plain.size() < (size_t)(3 + resp_len)) return "";
return std::string(reinterpret_cast<char*>(resp_plain.data() + 3), resp_len);
}
return "";
}
void disable_downstream_connect() {
connect_disabled_ = true;
}
uint32_t negotiated_sample_rate_for(ServiceType target) const {
for (const auto& dc : downstream_connections_) {
if (dc->target == target) {
uint32_t rate = dc->negotiated_sample_rate.load(std::memory_order_relaxed);
if (rate != 0) return rate;
if (target == ServiceType::VAD_SERVICE) return 16000;
if (target == ServiceType::MOSHI_SERVICE) return 24000;
return 0;
}
}
if (target == ServiceType::VAD_SERVICE) return 16000;
if (target == ServiceType::MOSHI_SERVICE) return 24000;
return 0;
}
std::vector<std::tuple<ServiceType, ConnectionState, uint32_t>> downstream_connection_states() const {
std::vector<std::tuple<ServiceType, ConnectionState, uint32_t>> result;
for (const auto& dc : downstream_connections_) {
result.emplace_back(
dc->target,
dc->state.load(std::memory_order_relaxed),
dc->negotiated_sample_rate.load(std::memory_order_relaxed)
);
}
return result;
}
private:
ServiceType type_;
std::atomic<bool> running_;
std::optional<ServiceType> downstream_override_;
static constexpr size_t SEND_BUF_SIZE = 65536;
static constexpr int DOWNSTREAM_RECONNECT_MS = 200;
static constexpr size_t MAX_ENDED_CALL_IDS = 1000;
static constexpr int ACCEPT_POLL_TIMEOUT_MS = 50;
static constexpr int IDLE_POLL_MS = 100;
static constexpr int MGMT_RECV_TIMEOUT_MS = 500;
static constexpr int MGMT_SEND_TIMEOUT_MS = 100;
static constexpr int DATA_SEND_TIMEOUT_MS = 100;
static constexpr int CONNECT_TIMEOUT_MS = 2000;
static constexpr int CUSTOM_MSG_TIMEOUT_MS = 2000;
static constexpr int PAYLOAD_RECV_TIMEOUT_MS = 5000;
static constexpr int LISTEN_BACKLOG = 4;
static constexpr int TCP_KEEPALIVE_IDLE_S = 2;
static constexpr int TCP_KEEPALIVE_INTVL_S = 1;
static constexpr int TCP_KEEPALIVE_CNT = 2;
mutable std::mutex call_id_mutex_;
uint32_t max_known_call_id_;
std::set<uint32_t> active_call_ids_;
std::set<uint32_t> ended_call_ids_;
int mgmt_listen_sock_;
int data_listen_sock_;
mutable std::mutex upstream_mutex_;