rift-sdk 0.1.4

High-level SDK for building Rift P2P applications
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
//! Rift SDK: high-level API for embedding Rift VoIP in other applications.
//!
//! This crate wraps mesh, media, discovery, and NAT components into a cohesive
//! runtime with a simpler API surface for native embedding.

use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::net::{SocketAddr, ToSocketAddrs};
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Arc, Mutex as StdMutex,
};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use anyhow::{Context, Result};
use rand::rngs::OsRng;
use rand::RngCore;
use serde::{Deserialize, Serialize};
use serde_json::json;
use tokio::sync::{mpsc, Mutex};
use tokio::time::Instant;

use rift_core::{decode_invite, generate_invite, Identity, Invite, PeerId, KeyStore};
use rift_dht::{DhtConfig as RiftDhtConfig, DhtHandle, PeerEndpointInfo};
use rift_discovery::local_ipv4_addrs;
use rift_media::{
    decode_frame, encode_frame, AudioConfig, AudioIn, AudioMixer, AudioOut, OpusDecoder,
    OpusEncoder,
};
use rift_mesh::{Mesh, MeshConfig, MeshEvent, MeshHandle};
use rift_nat::{
    attempt_hole_punch, gather_local_candidates, gather_public_addrs, parse_turn_server, NatConfig,
    PeerEndpoint,
};
use rift_protocol::{CallState, Capabilities, QosProfile, SessionId};
use rift_rndzv::{
    ChannelKind as RndzvChannelKind, PeerId as RndzvPeerId, RndzvChannel, RndzvConnectTarget,
    RndzvConnector, RndzvListener, Srt as RndzvSrt,
    EscalationPolicy, IdentityConstraints, RendezvousSpaceId, SearchStrategy,
    SemanticRendezvousToken, TimeModel,
};
use hkdf::Hkdf;
use sha2::Sha256;

pub use rift_core::PeerId as RiftPeerId;
pub use rift_protocol::{
    CallState as RiftCallState, ChatMessage, CodecId, FeatureFlag, GroupMode,
    QosProfile as RiftQosProfile, SessionId as RiftSessionId,
};

pub const SDK_VERSION: &str = "0.1.0";
pub const SDK_ABI_VERSION: i32 = 1;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RiftConfig {
    /// Optional path to the identity key.
    pub identity_path: Option<PathBuf>,
    /// UDP listen port.
    pub listen_port: u16,
    /// Whether this node can act as a relay.
    pub relay: bool,
    /// Optional display name for UI surfaces.
    pub user_name: Option<String>,
    /// Preferred codecs for negotiation.
    pub preferred_codecs: Vec<CodecId>,
    /// Preferred feature flags for negotiation.
    pub preferred_features: Vec<FeatureFlag>,
    /// QoS tuning parameters.
    #[serde(default)]
    pub qos: QosProfile,
    /// Whether metrics are enabled.
    #[serde(default)]
    pub metrics_enabled: bool,
    /// Security settings (E2EE, auth, etc).
    #[serde(default)]
    pub security: SecurityConfig,
    /// DHT configuration.
    pub dht: DhtConfigSdk,
    /// Audio configuration.
    pub audio: AudioConfigSdk,
    /// Network configuration.
    pub network: NetworkConfigSdk,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AudioConfigSdk {
    /// Enable audio capture/playback.
    pub enabled: bool,
    /// Optional input device name.
    pub input_device: Option<String>,
    /// Optional output device name.
    pub output_device: Option<String>,
    /// Quality preset identifier.
    pub quality: String,
    /// Push-to-talk enabled.
    pub ptt: bool,
    /// Voice activity detection enabled.
    pub vad: bool,
    /// Mute output playback.
    pub mute_output: bool,
    /// Emit raw voice frames to consumers.
    pub emit_voice_frames: bool,
    /// Allow audio init failures without crashing.
    pub allow_fail: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NetworkConfigSdk {
    /// Prefer direct P2P routes if possible.
    pub prefer_p2p: bool,
    /// Explicit list of local ports to bind.
    pub local_ports: Option<Vec<u16>>,
    /// Explicit peers to contact on startup.
    pub known_peers: Vec<std::net::SocketAddr>,
    pub invite: Option<String>,
    #[serde(default)]
    pub stun_servers: Vec<String>,
    #[serde(default)]
    pub stun_timeout_ms: Option<u64>,
    #[serde(default)]
    pub enable_turn: bool,
    #[serde(default)]
    pub turn_servers: Vec<String>,
    #[serde(default)]
    pub turn_timeout_ms: Option<u64>,
    #[serde(default)]
    pub turn_keepalive_ms: Option<u64>,
    #[serde(default)]
    pub punch_interval_ms: Option<u64>,
    #[serde(default)]
    pub punch_timeout_ms: Option<u64>,
    #[serde(default)]
    pub max_direct_peers: Option<usize>,
    /// Optional Predictive Rendezvous configuration.
    #[serde(default)]
    pub rndzv: Option<RndzvConfigSdk>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RndzvConfigSdk {
    /// SRT URI used for rendezvous.
    pub srt_uri: String,
    /// Role for rendezvous: connector or listener.
    pub role: RndzvRole,
    /// Optional remote address for connector mode.
    pub remote_addr: Option<SocketAddr>,
    /// Optional local bind address for listener mode.
    pub listen_addr: Option<SocketAddr>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RndzvRole {
    Connector,
    Listener,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SrtInvite {
    /// Human-readable label for the invite (e.g. "Alice Voice Call").
    pub label: String,
    /// Encoded SRT URI.
    pub uri: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DhtConfigSdk {
    /// Enable DHT discovery.
    pub enabled: bool,
    /// Bootstrap node addresses (string form).
    pub bootstrap_nodes: Vec<String>,
    /// Optional local listen addr override.
    pub listen_addr: Option<String>,
}

impl Default for RiftConfig {
    fn default() -> Self {
        Self {
            identity_path: None,
            listen_port: 7777,
            relay: false,
            user_name: None,
            preferred_codecs: vec![CodecId::Opus, CodecId::PCM16],
            preferred_features: vec![
                FeatureFlag::Voice,
                FeatureFlag::Text,
                FeatureFlag::Relay,
                FeatureFlag::E2EE,
            ],
            qos: QosProfile::default(),
            metrics_enabled: true,
            security: SecurityConfig::default(),
            dht: DhtConfigSdk::default(),
            audio: AudioConfigSdk::default(),
            network: NetworkConfigSdk::default(),
        }
    }
}

/// Create a voice-call SRT invite targeted at a specific peer.
pub fn create_voice_invite(to: PeerId) -> SrtInvite {
    let mut seed = [0u8; 32];
    OsRng.fill_bytes(&mut seed);
    let space = RendezvousSpaceId(*blake3::hash(b"rift-rndzv-voice-call").as_bytes());
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    let token = SemanticRendezvousToken::new(
        space,
        seed,
        IdentityConstraints {
            allowed_fingerprints: vec![to.0],
        },
        TimeModel {
            t0: now.saturating_add(10),
            window_secs: 120,
            slot_ms: 250,
        },
        SearchStrategy::BasicDeterministic,
        EscalationPolicy::None,
    );
    let uri = token
        .to_uri()
        .expect("SRT URI encoding should succeed for valid inputs");
    SrtInvite {
        label: "Voice Call".to_string(),
        uri,
    }
}

/// Parse an SRT invite into a rendezvous token.
pub fn accept_voice_invite(invite: &SrtInvite) -> Result<RndzvSrt, RiftError> {
    RndzvSrt::from_uri(&invite.uri)
        .map_err(|e| RiftError::Other(format!("rndzv srt decode failed: {e}")))
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SecurityConfig {
    /// Trust first-seen identity keys.
    pub trust_on_first_use: bool,
    /// Optional path for known-hosts storage.
    pub known_hosts_path: Option<PathBuf>,
    /// Reject peers on key mismatch.
    pub reject_on_mismatch: bool,
    /// Optional channel shared secret.
    pub channel_shared_secret: Option<String>,
    /// Optional audit log path.
    pub audit_log_path: Option<PathBuf>,
    /// Rekey interval in seconds.
    pub rekey_interval_secs: Option<u64>,
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            trust_on_first_use: true,
            known_hosts_path: None,
            reject_on_mismatch: false,
            channel_shared_secret: None,
            audit_log_path: None,
            rekey_interval_secs: Some(600),
        }
    }
}

impl Default for AudioConfigSdk {
    fn default() -> Self {
        Self {
            enabled: true,
            input_device: None,
            output_device: None,
            quality: "medium".to_string(),
            ptt: false,
            vad: true,
            mute_output: false,
            emit_voice_frames: false,
            allow_fail: false,
        }
    }
}

impl Default for NetworkConfigSdk {
    fn default() -> Self {
        Self {
            prefer_p2p: true,
            local_ports: None,
            known_peers: Vec::new(),
            invite: None,
            stun_servers: vec![
                "stun.l.google.com:19302".to_string(),
                "stun1.l.google.com:19302".to_string(),
            ],
            stun_timeout_ms: Some(800),
            enable_turn: false,
            turn_servers: Vec::new(),
            turn_timeout_ms: Some(1200),
            turn_keepalive_ms: Some(12000),
            punch_interval_ms: Some(200),
            punch_timeout_ms: Some(5000),
            max_direct_peers: None,
            rndzv: None,
        }
    }
}

impl Default for DhtConfigSdk {
    fn default() -> Self {
        Self {
            enabled: false,
            bootstrap_nodes: Vec::new(),
            listen_addr: None,
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct LinkStats {
    /// Round-trip time in milliseconds.
    pub rtt_ms: f32,
    /// Packet loss fraction.
    pub loss: f32,
    /// Jitter in milliseconds.
    pub jitter_ms: f32,
}

#[derive(Debug, Clone, Copy)]
pub struct GlobalStats {
    /// Connected peers.
    pub num_peers: usize,
    /// Active sessions.
    pub num_sessions: usize,
    /// Packets sent.
    pub packets_sent: u64,
    /// Packets received.
    pub packets_received: u64,
    /// Bytes sent.
    pub bytes_sent: u64,
    /// Bytes received.
    pub bytes_received: u64,
}

#[derive(Debug, Clone)]
pub enum RouteKind {
    Direct,
    Relayed { via: PeerId },
}

#[derive(Debug, Clone)]
pub enum RiftEvent {
    /// Incoming chat message.
    IncomingChat(ChatMessage),
    /// Incoming call invitation.
    IncomingCall {
        session: SessionId,
        from: PeerId,
        rndzv_srt_uri: Option<String>,
    },
    /// Call state changes (ringing/active/ended).
    CallStateChanged { session: SessionId, state: CallState },
    /// A peer joined the channel.
    PeerJoinedChannel { peer: PeerId, channel: String },
    /// A peer left the channel.
    PeerLeftChannel { peer: PeerId, channel: String },
    /// Peer capability advertisement.
    PeerCapabilities { peer: PeerId, capabilities: Capabilities },
    /// Audio level update for UI metering.
    AudioLevel { peer: PeerId, level: f32 },
    /// Codec selection update.
    CodecSelected { codec: CodecId },
    /// Audio bitrate update for diagnostics.
    AudioBitrate { bitrate: u32 },
    /// Periodic stats update.
    StatsUpdate { peer: PeerId, stats: LinkStats, global: GlobalStats },
    /// Routing update for a peer.
    RouteUpdated { peer: PeerId, route: RouteKind },
    /// Group topology update.
    GroupTopology { session: SessionId, mode: GroupMode },
    /// Peer fingerprint for trust UX.
    PeerFingerprint { peer: PeerId, fingerprint: String },
    /// Security-related notice (TOFU, mismatch, etc).
    SecurityNotice { message: String },
    /// Raw voice samples (when enabled).
    VoiceFrame { peer: PeerId, samples: Vec<i16> },
}

#[derive(Debug, thiserror::Error)]
/// High-level SDK error type.
pub enum RiftError {
    /// SDK runtime not initialized.
    #[error("not initialized")]
    NotInitialized,
    /// Channel already joined.
    #[error("channel already joined")]
    AlreadyJoined,
    /// Channel not joined.
    #[error("channel not joined")]
    NotJoined,
    /// Mesh subsystem error.
    #[error("mesh error: {0}")]
    Mesh(String),
    /// Audio subsystem error.
    #[error("audio error: {0}")]
    Audio(String),
    /// Generic failure.
    #[error("other: {0}")]
    Other(String),
}

/// Runtime state for audio capture, mixing, and encoding.
struct VoiceRuntime {
    _audio_in: AudioIn,
    mixer: Arc<StdMutex<AudioMixer>>,
    frame_samples: usize,
    emit_voice: bool,
    audio_config: AudioConfig,
    tuning: Arc<StdMutex<AudioTuning>>,
    rndzv_channel: Arc<StdMutex<Option<RndzvChannel>>>,
    rndzv_remote_peer: Arc<StdMutex<Option<PeerId>>>,
}

impl VoiceRuntime {
    fn set_rndzv_channel(&self, channel: RndzvChannel, remote_peer: PeerId) {
        {
            let mut slot = self.rndzv_channel.lock().unwrap();
            *slot = Some(channel.clone());
        }
        {
            let mut peer_slot = self.rndzv_remote_peer.lock().unwrap();
            *peer_slot = Some(remote_peer);
        }

        let mixer = self.mixer.clone();
        let frame_samples = self.frame_samples;
        let emit_voice = self.emit_voice;
        let audio_config = self.audio_config.clone();
        tokio::spawn(async move {
            let mut decoder = match OpusDecoder::new(&audio_config) {
                Ok(decoder) => decoder,
                Err(err) => {
                    tracing::warn!("rndzv opus decoder init failed: {err}");
                    return;
                }
            };
            loop {
                let payload = match channel.recv().await {
                    Ok(Some(payload)) => payload,
                    Ok(None) => continue,
                    Err(err) => {
                        tracing::warn!("rndzv channel recv failed: {err}");
                        return;
                    }
                };
                if let Ok(out) = decode_frame(CodecId::Opus, &payload, &mut decoder, frame_samples) {
                    let mut mixer = mixer.lock().unwrap();
                    mixer.push(peer_to_stream_id(&remote_peer), out.clone());
                    if emit_voice {
                        let _ = out;
                    }
                }
            }
        });
    }

    fn clear_rndzv_channel(&self) {
        {
            let mut slot = self.rndzv_channel.lock().unwrap();
            *slot = None;
        }
        {
            let mut peer_slot = self.rndzv_remote_peer.lock().unwrap();
            *peer_slot = None;
        }
    }
}

/// Current audio tuning parameters.
#[derive(Debug, Clone)]
struct AudioTuning {
    bitrate: u32,
    fec: bool,
    loss_pct: u8,
}

/// QoS state used to adapt audio settings to current network stats.
struct QosState {
    profile: QosProfile,
    peer_stats: HashMap<PeerId, LinkStats>,
    current: AudioTuning,
    last_adjust: Instant,
}

/// Per-session runtime handle for mesh + audio + DHT.
struct SessionRuntime {
    _channel: String,
    handle: MeshHandle,
    _voice: Option<Arc<VoiceRuntime>>,
    _dht: Option<DhtHandle>,
    pending_call_srt: Arc<StdMutex<HashMap<SessionId, String>>>,
}

/// Primary SDK handle exposed to callers.
pub struct RiftHandle {
    /// Persistent identity (if initialized).
    identity: Mutex<Option<Identity>>,
    /// Local peer id (generated at startup).
    _local_peer_id: PeerId,
    /// Effective runtime configuration.
    config: RiftConfig,
    /// In-memory overrides (PTT, mute, etc).
    overrides: Mutex<RiftConfigOverrides>,
    /// Session runtime (mesh/audio/dht).
    runtime: Mutex<Option<SessionRuntime>>,
    /// Event receiver for consumer-facing events.
    event_rx: Mutex<mpsc::UnboundedReceiver<RiftEvent>>,
    event_tx: mpsc::UnboundedSender<RiftEvent>,
    ptt_active: Arc<AtomicBool>,
    mute_active: Arc<AtomicBool>,
}

#[derive(Debug, Default, Clone)]
/// Runtime configuration overrides applied before joining.
struct RiftConfigOverrides {
    dht_enabled: Option<bool>,
    bootstrap_nodes: Option<Vec<String>>,
    invite: Option<String>,
    turn_servers: Option<Vec<String>>,
    audio_quality: Option<String>,
}

impl RiftHandle {
    /// Initialize the SDK runtime with the given config and identity.
    pub async fn new(config: RiftConfig) -> Result<Self, RiftError> {
        rift_metrics::set_enabled(config.metrics_enabled);
        let (event_tx, event_rx) = mpsc::unbounded_channel();
        let identity_path = config
            .identity_path
            .clone()
            .unwrap_or_else(|| Identity::default_path().unwrap_or_else(|_| PathBuf::from("identity.key")));
        let existed = identity_path.exists();
        let identity = KeyStore::load_or_generate(&identity_path)
            .context("identity load failed")
            .map_err(|e| RiftError::Other(format!("{e}")))?;
        if !existed {
            tracing::info!(path = %identity_path.display(), "new identity generated");
        }
        let local_peer_id = identity.peer_id;
        Ok(Self {
            ptt_active: Arc::new(AtomicBool::new(!config.audio.ptt)),
            identity: Mutex::new(Some(identity)),
            _local_peer_id: local_peer_id,
            config,
            overrides: Mutex::new(RiftConfigOverrides::default()),
            runtime: Mutex::new(None),
            event_rx: Mutex::new(event_rx),
            event_tx,
            mute_active: Arc::new(AtomicBool::new(false)),
        })
    }

    /// Enable or disable DHT discovery for subsequent joins.
    pub async fn set_dht_enabled(&self, enabled: bool) {
        let mut overrides = self.overrides.lock().await;
        overrides.dht_enabled = Some(enabled);
    }

    /// Override DHT bootstrap nodes.
    pub async fn set_bootstrap_nodes(&self, nodes: Vec<String>) {
        let mut overrides = self.overrides.lock().await;
        overrides.bootstrap_nodes = Some(nodes);
    }

    /// Provide an invite link override for joining.
    pub async fn set_invite(&self, invite: Option<String>) {
        let mut overrides = self.overrides.lock().await;
        overrides.invite = invite;
    }

    /// Configure TURN servers for relay fallback.
    pub async fn set_turn_servers(&self, servers: Vec<String>) {
        let mut overrides = self.overrides.lock().await;
        overrides.turn_servers = Some(servers);
    }

    /// Override the audio quality preset.
    pub async fn set_audio_quality(&self, quality: Option<String>) {
        let mut overrides = self.overrides.lock().await;
        overrides.audio_quality = quality;
    }

    /// Join a channel by name/password, optionally using internet mode.
    pub async fn join_channel(
        &self,
        name: &str,
        password: Option<&str>,
        internet: bool,
    ) -> Result<(), RiftError> {
        let mut cfg = self.config.clone();
        {
            let overrides = self.overrides.lock().await;
            if let Some(enabled) = overrides.dht_enabled {
                cfg.dht.enabled = enabled;
            }
            if let Some(nodes) = overrides.bootstrap_nodes.clone() {
                cfg.dht.bootstrap_nodes = nodes;
            }
            if let Some(invite) = overrides.invite.clone() {
                cfg.network.invite = Some(invite);
            }
            if let Some(turn_servers) = overrides.turn_servers.clone() {
                cfg.network.turn_servers = turn_servers;
                cfg.network.enable_turn = !cfg.network.turn_servers.is_empty();
            }
            if let Some(quality) = overrides.audio_quality.clone() {
                cfg.audio.quality = quality;
            }
        }
        let mut runtime_guard = self.runtime.lock().await;
        if runtime_guard.is_some() {
            return Err(RiftError::AlreadyJoined);
        }
        let identity = {
            let mut identity_guard = self.identity.lock().await;
            match identity_guard.take() {
                Some(identity) => identity,
                None => Identity::load(cfg.identity_path.as_deref())
                    .context("identity not found")
                    .map_err(|e| RiftError::Other(format!("{e}")))?,
            }
        };

        let auth_token = self
            .config
            .security
            .channel_shared_secret
            .as_deref()
            .map(|secret| derive_auth_token(secret, name));
        let nat_cfg = if internet {
            Some(default_nat_config(
                cfg.listen_port,
                cfg.network.local_ports.clone(),
                cfg.network.stun_servers.clone(),
                cfg.network.stun_timeout_ms,
                cfg.network.punch_interval_ms,
                cfg.network.punch_timeout_ms,
                cfg.network.enable_turn,
                cfg.network.turn_servers.clone(),
                cfg.network.turn_timeout_ms,
                cfg.network.turn_keepalive_ms,
            ))
        } else {
            None
        };
        let mut known_peers = cfg.network.known_peers.clone();
        if internet && known_peers.is_empty() {
            if let Some(nat_cfg) = nat_cfg.as_ref() {
                if !nat_cfg.stun_servers.is_empty() {
                    if let Ok(public_addrs) = gather_public_addrs(nat_cfg).await {
                        if !public_addrs.is_empty() {
                            known_peers = public_addrs;
                        }
                    }
                }
            }
        }
        let invite_for_key = if let Some(invite_str) = &cfg.network.invite {
            Some(decode_invite(invite_str).map_err(|e| RiftError::Other(format!("{e}")))?)
        } else if internet {
            let mut candidates = gather_local_candidates(cfg.listen_port);
            if let Some(nat_cfg) = nat_cfg.as_ref() {
                if !nat_cfg.stun_servers.is_empty() {
                    if let Ok(public_addrs) = gather_public_addrs(nat_cfg).await {
                        candidates.extend(public_addrs);
                    }
                }
            }
            candidates.sort();
            candidates.dedup();
            Some(generate_invite(
                name,
                password,
                known_peers.clone(),
                candidates,
            ))
        } else {
            None
        };
        let e2ee_key = derive_e2ee_key(
            name,
            password,
            invite_for_key.as_ref(),
            cfg.security.channel_shared_secret.as_deref(),
        );
        let config = MeshConfig {
            channel_name: name.to_string(),
            password: password.map(|v| v.to_string()),
            listen_port: cfg.listen_port,
            relay_capable: cfg.relay,
            qos: cfg.qos.clone(),
            auth_token,
            require_auth: cfg.security.channel_shared_secret.is_some(),
            e2ee_key,
            rekey_interval_secs: cfg.security.rekey_interval_secs,
            max_direct_peers: cfg.network.max_direct_peers,
        };
        let mut mesh = Mesh::new(identity, config)
            .await
            .map_err(|e| RiftError::Mesh(format!("{e}")))?;

        let handle = mesh.handle();
        handle
            .set_preferred_codecs(self.config.preferred_codecs.clone())
            .await;
        handle
            .set_preferred_features(self.config.preferred_features.clone())
            .await;
        let security_handle = handle.clone();

        if internet {
            let nat_cfg = nat_cfg.clone().expect("nat cfg");
            mesh.enable_nat(nat_cfg.clone()).await;
            let invite = invite_for_key.clone().unwrap_or_else(|| Invite {
                channel_name: name.to_string(),
                password: password.map(|v| v.to_string()),
                channel_key: [0u8; 32],
                known_peers: Vec::new(),
                candidates: Vec::new(),
                relay_candidates: Vec::new(),
                version: 2,
                created_at: now_timestamp(),
            });
            mesh.join_invite(invite, nat_cfg)
                .await
                .map_err(|e| RiftError::Mesh(format!("{e}")))?;
        } else {
            mesh.start_lan_discovery()
                .map_err(|e| RiftError::Mesh(format!("{e}")))?;
        }

        let event_tx = self.event_tx.clone();
        let channel = name.to_string();
        let channel_for_task = channel.clone();
        let pending_call_srt: Arc<StdMutex<HashMap<SessionId, String>>> =
            Arc::new(StdMutex::new(HashMap::new()));
        let pending_call_srt_task = pending_call_srt.clone();
        let voice = if cfg.audio.enabled {
            match start_audio_pipeline(
                cfg.clone(),
                handle.clone(),
                self.local_peer_id(),
                self.ptt_active.clone(),
                self.mute_active.clone(),
            ) {
                Ok(voice) => Some(Arc::new(voice)),
                Err(err) => {
                    if cfg.audio.allow_fail {
                        tracing::warn!("audio pipeline failed: {err}");
                        None
                    } else {
                        return Err(err);
                    }
                }
            }
        } else {
            None
        };
        if let Some(voice) = voice.as_ref() {
            let _ = event_tx.send(RiftEvent::AudioBitrate {
                bitrate: voice.audio_config.bitrate,
            });
        }

        let dht = if cfg.dht.enabled {
            let dht_config = RiftDhtConfig {
                bootstrap_nodes: parse_socket_addrs(&cfg.dht.bootstrap_nodes),
                listen_addr: cfg
                    .dht
                    .listen_addr
                    .as_deref()
                    .and_then(parse_socket_addr)
                    .unwrap_or_else(|| {
                        SocketAddr::from(([0, 0, 0, 0], cfg.listen_port.saturating_add(100)))
                    }),
            };
            let handle_dht = DhtHandle::new(dht_config)
                .await
                .map_err(|e| RiftError::Other(format!("{e}")))?;

            let channel_id = rift_core::ChannelId::from_channel(&channel, password);
            let nat_cfg = nat_cfg.clone().unwrap_or_else(|| default_nat_config(
                cfg.listen_port,
                cfg.network.local_ports.clone(),
                cfg.network.stun_servers.clone(),
                cfg.network.stun_timeout_ms,
                cfg.network.punch_interval_ms,
                cfg.network.punch_timeout_ms,
                cfg.network.enable_turn,
                cfg.network.turn_servers.clone(),
                cfg.network.turn_timeout_ms,
                cfg.network.turn_keepalive_ms,
            ));
            let addrs = match gather_public_addrs(&nat_cfg).await {
                Ok(public_addrs) if !public_addrs.is_empty() => public_addrs,
                _ => local_ipv4_addrs()
                    .map_err(|e| RiftError::Other(format!("{e}")))?
                    .into_iter()
                    .map(|ip| SocketAddr::new(ip, cfg.listen_port))
                    .collect::<Vec<_>>(),
            };
            let info = PeerEndpointInfo {
                peer_id: self.local_peer_id(),
                addrs,
            };
            let _ = handle_dht.announce(channel_id, info.clone()).await;

            let announce_handle = handle_dht.clone();
            let announce_info = info.clone();
            tokio::spawn(async move {
                let mut tick = tokio::time::interval(Duration::from_secs(30));
                loop {
                    tick.tick().await;
                    let _ = announce_handle
                        .announce(channel_id, announce_info.clone())
                        .await;
                }
            });

            let lookup_handle = handle_dht.clone();
            let mesh_handle = handle.clone();
            let nat_cfg = default_nat_config(
                self.config.listen_port,
                self.config.network.local_ports.clone(),
                self.config.network.stun_servers.clone(),
                self.config.network.stun_timeout_ms,
                self.config.network.punch_interval_ms,
                self.config.network.punch_timeout_ms,
                self.config.network.enable_turn,
                self.config.network.turn_servers.clone(),
                self.config.network.turn_timeout_ms,
                self.config.network.turn_keepalive_ms,
            );
            tokio::spawn(async move {
                let mut tick = tokio::time::interval(Duration::from_secs(12));
                loop {
                    tick.tick().await;
                    if let Ok(peers) = lookup_handle.lookup(channel_id).await {
                        for peer in peers {
                            if peer.peer_id == info.peer_id {
                                continue;
                            }
                            for addr in peer.addrs.iter().copied() {
                                let endpoint = PeerEndpoint {
                                    peer_id: peer.peer_id,
                                    external_addrs: vec![addr],
                                    punch_ports: vec![addr.port()],
                                };
                                if let Ok((socket, remote)) = attempt_hole_punch(&nat_cfg, &endpoint).await {
                                    let _ = mesh_handle.connect_with_socket(socket, remote).await;
                                } else {
                                    let _ = mesh_handle.connect_addr(addr).await;
                                }
                            }
                        }
                    }
                }
            });

            Some(handle_dht)
        } else {
            None
        };

        let voice_state = voice.as_ref().map(|v| VoiceRuntimeRef {
            mixer: v.mixer.clone(),
            frame_samples: v.frame_samples,
            emit_voice: v.emit_voice,
            audio_config: v.audio_config.clone(),
            tuning: v.tuning.clone(),
        });
        let security_cfg = self.config.security.clone();
        let qos_profile = self.config.qos.clone();
        let mut qos_state = voice_state.as_ref().map(|state| QosState {
            profile: qos_profile,
            peer_stats: HashMap::new(),
            current: AudioTuning {
                bitrate: state.audio_config.bitrate,
                fec: false,
                loss_pct: 0,
            },
            last_adjust: Instant::now() - Duration::from_secs(5),
        });

        tokio::spawn(async move {
            let mut mesh = mesh;
            let mut decoder = if voice_state.is_some() {
                Some(
                    OpusDecoder::new(&voice_state.as_ref().unwrap().audio_config)
                        .expect("opus decoder"),
                )
            } else {
                None
            };
            while let Some(event) = mesh.next_event().await {
                match event {
                    MeshEvent::PeerJoined(peer) => {
                        let _ = event_tx.send(RiftEvent::PeerJoinedChannel {
                            peer,
                            channel: channel_for_task.clone(),
                        });
                    }
                    MeshEvent::PeerLeft(peer) => {
                        let _ = event_tx.send(RiftEvent::PeerLeftChannel {
                            peer,
                            channel: channel_for_task.clone(),
                        });
                    }
                    MeshEvent::ChatReceived(chat) => {
                        let _ = event_tx.send(RiftEvent::IncomingChat(chat));
                    }
                    MeshEvent::IncomingCall {
                        session,
                        from,
                        rndzv_srt_uri,
                    } => {
                        if let Some(uri) = rndzv_srt_uri.clone() {
                            let mut map = pending_call_srt_task.lock().unwrap();
                            map.insert(session, uri);
                        }
                        let _ = event_tx.send(RiftEvent::IncomingCall {
                            session,
                            from,
                            rndzv_srt_uri,
                        });
                    }
                    MeshEvent::CallAccepted { session, .. } => {
                        let _ = event_tx.send(RiftEvent::CallStateChanged {
                            session,
                            state: CallState::Active,
                        });
                    }
                    MeshEvent::CallDeclined { session, .. } => {
                        let _ = event_tx.send(RiftEvent::CallStateChanged {
                            session,
                            state: CallState::Ended,
                        });
                    }
                    MeshEvent::CallEnded { session } => {
                        let _ = event_tx.send(RiftEvent::CallStateChanged {
                            session,
                            state: CallState::Ended,
                        });
                    }
                    MeshEvent::VoiceFrame { from, codec, payload, .. } => {
                        if let (Some(state), Some(decoder)) = (voice_state.as_ref(), decoder.as_mut()) {
                            if let Ok(out) = decode_frame(codec, &payload, decoder, state.frame_samples) {
                                let mut mixer = state.mixer.lock().unwrap();
                                mixer.push(peer_to_stream_id(&from), out.clone());
                                let level = audio_level(&out);
                                let _ = event_tx.send(RiftEvent::AudioLevel { peer: from, level });
                                if state.emit_voice {
                                    let _ = event_tx.send(RiftEvent::VoiceFrame { peer: from, samples: out });
                                }
                            }
                        }
                    }
                    MeshEvent::PeerCapabilities { peer_id, capabilities } => {
                        let _ = event_tx.send(RiftEvent::PeerCapabilities { peer: peer_id, capabilities });
                    }
                    MeshEvent::GroupCodec(codec) => {
                        let _ = event_tx.send(RiftEvent::CodecSelected { codec });
                    }
                    MeshEvent::StatsUpdate { peer, stats, global } => {
                        let sdk_stats = LinkStats {
                            rtt_ms: stats.rtt_ms,
                            loss: stats.loss,
                            jitter_ms: stats.jitter_ms,
                        };
                        let sdk_global = GlobalStats {
                            num_peers: global.num_peers,
                            num_sessions: global.num_sessions,
                            packets_sent: global.packets_sent,
                            packets_received: global.packets_received,
                            bytes_sent: global.bytes_sent,
                            bytes_received: global.bytes_received,
                        };
                        let _ = event_tx.send(RiftEvent::StatsUpdate {
                            peer,
                            stats: sdk_stats,
                            global: sdk_global,
                        });
                        if let (Some(state), Some(qos)) = (voice_state.as_ref(), qos_state.as_mut()) {
                            qos.peer_stats.insert(peer, sdk_stats);
                            if let Some(next) = compute_next_tuning(qos) {
                                let mut tuning = state.tuning.lock().unwrap();
                                let bitrate_changed = tuning.bitrate != next.bitrate;
                                *tuning = next.clone();
                                if bitrate_changed {
                                    let _ = event_tx.send(RiftEvent::AudioBitrate { bitrate: next.bitrate });
                                }
                            }
                        }
                    }
                    MeshEvent::RouteUpdated { peer_id, route } => {
                        let route = match route {
                            rift_mesh::PeerRoute::Direct { .. } => RouteKind::Direct,
                            rift_mesh::PeerRoute::Relayed { via } => RouteKind::Relayed { via },
                        };
                        let _ = event_tx.send(RiftEvent::RouteUpdated {
                            peer: peer_id,
                            route,
                        });
                    }
                    MeshEvent::GroupTopology { session, mode } => {
                        let _ = event_tx.send(RiftEvent::GroupTopology { session, mode });
                    }
                    MeshEvent::PeerIdentity { peer_id, public_key } => {
                        if let Err(err) = handle_peer_identity(
                            &event_tx,
                            &security_handle,
                            &security_cfg,
                            peer_id,
                            &public_key,
                        )
                        .await
                        {
                            tracing::warn!("security check failed: {err}");
                        }
                    }
                    MeshEvent::PeerSessionConfig { .. } | MeshEvent::RouteUpgraded(_) => {}
                }
            }
        });

        *runtime_guard = Some(SessionRuntime {
            _channel: channel,
            handle,
            _voice: voice,
            _dht: dht,
            pending_call_srt,
        });
        Ok(())
    }

    /// Leave the currently joined channel and tear down runtime state.
    pub async fn leave_channel(&self, _name: &str) -> Result<(), RiftError> {
        let mut runtime_guard = self.runtime.lock().await;
        if runtime_guard.is_none() {
            return Err(RiftError::NotJoined);
        }
        *runtime_guard = None;
        Ok(())
    }

    /// Send a chat message to all peers.
    pub async fn send_chat(&self, text: &str) -> Result<(), RiftError> {
        let runtime_guard = self.runtime.lock().await;
        let runtime = runtime_guard.as_ref().ok_or(RiftError::NotJoined)?;
        runtime
            .handle
            .broadcast_chat(text.to_string())
            .await
            .map_err(|e| RiftError::Mesh(format!("{e}")))
    }

    /// Start a call with a specific peer.
    pub async fn start_call(&self, peer: PeerId) -> Result<SessionId, RiftError> {
        self.start_call_with_srt(peer, None).await
    }

    /// Start a call with an optional rndzv SRT URI attached to the invite.
    pub async fn start_call_with_srt(
        &self,
        peer: PeerId,
        rndzv_srt_uri: Option<String>,
    ) -> Result<SessionId, RiftError> {
        let parsed_srt = if let Some(uri) = rndzv_srt_uri.as_ref() {
            Some(
                RndzvSrt::from_uri(uri)
                    .map_err(|e| RiftError::Other(format!("rndzv srt decode failed: {e}")))?,
            )
        } else {
            None
        };
        let (handle, voice) = {
            let runtime_guard = self.runtime.lock().await;
            let runtime = runtime_guard.as_ref().ok_or(RiftError::NotJoined)?;
            (runtime.handle.clone(), runtime._voice.clone())
        };

        let session = handle
            .start_call_with_srt(peer, rndzv_srt_uri.clone())
            .await
            .map_err(|e| RiftError::Mesh(format!("{e}")))?;

        if let (Some(srt), Some(voice)) = (parsed_srt, voice) {
            let local_peer = RndzvPeerId(self.local_peer_id().0);
            let target = RndzvConnectTarget::from_srt(srt, local_peer);
            let connector = RndzvConnector::new().with_timeout(Duration::from_secs(5));
            let outcome = connector
                .connect(target)
                .await
                .map_err(|e| RiftError::Other(format!("rndzv connect failed: {e}")))?;
            let session = outcome.session;

            let channel = session
                .open_channel(RndzvChannelKind::UnreliableDatagram)
                .await
                .map_err(|e| RiftError::Other(format!("rndzv channel open failed: {e}")))?;
            let remote_peer = PeerId((session.remote).0);
            voice.set_rndzv_channel(channel, remote_peer);
        }

        Ok(session)
    }

    /// Accept an incoming call.
    pub async fn accept_call(&self, session: SessionId) -> Result<(), RiftError> {
        let (handle, voice, pending_call_srt) = {
            let runtime_guard = self.runtime.lock().await;
            let runtime = runtime_guard.as_ref().ok_or(RiftError::NotJoined)?;
            (
                runtime.handle.clone(),
                runtime._voice.clone(),
                runtime.pending_call_srt.clone(),
            )
        };
        let srt_uri = {
            let mut map = pending_call_srt.lock().unwrap();
            map.remove(&session)
        };
        let parsed_srt = if let Some(uri) = srt_uri.as_ref() {
            Some(
                RndzvSrt::from_uri(uri)
                    .map_err(|e| RiftError::Other(format!("rndzv srt decode failed: {e}")))?,
            )
        } else {
            None
        };

        handle
            .accept_call(session)
            .await
            .map_err(|e| RiftError::Mesh(format!("{e}")))?;

        if let (Some(srt), Some(voice)) = (parsed_srt, voice) {
            let local_peer = RndzvPeerId(self.local_peer_id().0);
            let listener = RndzvListener::new(srt.space, local_peer).with_srt(srt);
            let outcome = listener
                .accept()
                .await
                .map_err(|e| RiftError::Other(format!("rndzv accept failed: {e}")))?;
            let session = outcome.session;

            let channel = session
                .open_channel(RndzvChannelKind::UnreliableDatagram)
                .await
                .map_err(|e| RiftError::Other(format!("rndzv channel open failed: {e}")))?;
            let remote_peer = PeerId((session.remote).0);
            voice.set_rndzv_channel(channel, remote_peer);
        }

        Ok(())
    }

    /// Decline an incoming call with optional reason.
    pub async fn decline_call(&self, session: SessionId, reason: Option<&str>) -> Result<(), RiftError> {
        let (handle, pending_call_srt) = {
            let runtime_guard = self.runtime.lock().await;
            let runtime = runtime_guard.as_ref().ok_or(RiftError::NotJoined)?;
            (runtime.handle.clone(), runtime.pending_call_srt.clone())
        };
        {
            let mut map = pending_call_srt.lock().unwrap();
            map.remove(&session);
        }
        handle
            .decline_call(session, reason.map(|v| v.to_string()))
            .await
            .map_err(|e| RiftError::Mesh(format!("{e}")))
    }

    /// End an active call session.
    pub async fn end_call(&self, session: SessionId) -> Result<(), RiftError> {
        let (handle, voice) = {
            let runtime_guard = self.runtime.lock().await;
            let runtime = runtime_guard.as_ref().ok_or(RiftError::NotJoined)?;
            (runtime.handle.clone(), runtime._voice.clone())
        };
        if let Some(voice) = voice {
            voice.clear_rndzv_channel();
        }
        handle
            .end_call(session)
            .await
            .map_err(|e| RiftError::Mesh(format!("{e}")))
    }

    /// Await the next event from the SDK.
    pub async fn next_event(&self) -> Option<RiftEvent> {
        let mut rx = self.event_rx.lock().await;
        rx.recv().await
    }

    /// Try to fetch the next event without awaiting.
    pub fn try_next_event(&self) -> Option<RiftEvent> {
        let mut rx = self.event_rx.blocking_lock();
        rx.try_recv().ok()
    }

    /// Set push-to-talk active state.
    pub fn set_ptt_active(&self, active: bool) {
        self.ptt_active.store(active, Ordering::Relaxed);
    }

    /// Mute or unmute microphone capture.
    pub fn set_mute(&self, muted: bool) {
        self.mute_active.store(muted, Ordering::Relaxed);
    }

    /// Return the local peer id.
    pub fn local_peer_id(&self) -> PeerId {
        self._local_peer_id
    }
}

struct VoiceRuntimeRef {
    mixer: Arc<StdMutex<AudioMixer>>,
    frame_samples: usize,
    emit_voice: bool,
    audio_config: AudioConfig,
    tuning: Arc<StdMutex<AudioTuning>>,
}

/// Initialize the audio capture/playback pipeline and spawn processing tasks.
fn start_audio_pipeline(
    config: RiftConfig,
    handle: MeshHandle,
    _local_peer_id: PeerId,
    ptt_active: Arc<AtomicBool>,
    mute_active: Arc<AtomicBool>,
) -> Result<VoiceRuntime, RiftError> {
    let mut audio_config = AudioConfig::default();
    let initial_bitrate = map_quality_to_bitrate(Some(&config.audio.quality));
    audio_config.bitrate = initial_bitrate
        .clamp(config.qos.min_bitrate, config.qos.max_bitrate)
        .max(8_000);
    rift_metrics::set_gauge("rift_audio_bitrate", &[], audio_config.bitrate as f64);
    let (audio_in, mut audio_rx) = AudioIn::new_with_device(&audio_config, config.audio.input_device.as_deref())
        .map_err(|e| RiftError::Audio(format!("{e}")))?;
    let mut encoder = OpusEncoder::new(&audio_config).map_err(|e| RiftError::Audio(format!("{e}")))?;
    let output_device = config.audio.output_device.clone();
    let mixer = Arc::new(StdMutex::new(AudioMixer::with_prebuffer(
        audio_config.frame_samples(),
        8,
    )));

    let ptt_enabled = config.audio.ptt;
    let vad_enabled = config.audio.vad;
    let frame_duration = audio_config.frame_duration();
    let tuning = Arc::new(StdMutex::new(AudioTuning {
        bitrate: audio_config.bitrate,
        fec: false,
        loss_pct: 0,
    }));
    let tuning_for_task = tuning.clone();

    let rndzv_channel: Arc<StdMutex<Option<RndzvChannel>>> = Arc::new(StdMutex::new(None));
    let rndzv_remote_peer: Arc<StdMutex<Option<PeerId>>> = Arc::new(StdMutex::new(None));
    let rndzv_channel_for_task = rndzv_channel.clone();
    tokio::spawn(async move {
        let mut seq: u32 = 0;
        let mut hangover: u8 = 0;
        let mut last_applied = AudioTuning {
            bitrate: audio_config.bitrate,
            fec: false,
            loss_pct: 0,
        };
        let rndzv_sender = rndzv_channel_for_task.clone();
        while let Some(frame) = audio_rx.recv().await {
            let next_tuning = {
                let tuning = tuning_for_task.lock().unwrap();
                tuning.clone()
            };
            if next_tuning.bitrate != last_applied.bitrate
                || next_tuning.fec != last_applied.fec
                || next_tuning.loss_pct != last_applied.loss_pct
            {
                if let Err(err) = encoder.set_bitrate(next_tuning.bitrate) {
                    tracing::debug!("opus bitrate update failed: {err}");
                }
                if let Err(err) = encoder.set_fec(next_tuning.fec) {
                    tracing::debug!("opus fec update failed: {err}");
                }
                if let Err(err) = encoder.set_packet_loss(next_tuning.loss_pct) {
                    tracing::debug!("opus loss update failed: {err}");
                }
                last_applied = next_tuning;
            }
            if ptt_enabled && !ptt_active.load(Ordering::Relaxed) {
                continue;
            }
            if mute_active.load(Ordering::Relaxed) {
                continue;
            }
            if !ptt_enabled && vad_enabled {
                let active = is_frame_active(&frame);
                if active {
                    hangover = 4;
                } else if hangover > 0 {
                    hangover -= 1;
                }
                if !active && hangover == 0 {
                    continue;
                }
            }
            if frame_duration > Duration::from_millis(20) {
                tokio::time::sleep(frame_duration - Duration::from_millis(20)).await;
            }
            let codec = handle.group_codec().await;
            let out = match encode_frame(codec, &frame, &mut encoder) {
                Ok(out) => out,
                Err(_) => continue,
            };
            let timestamp = now_timestamp();
            let maybe_channel = rndzv_sender.lock().unwrap().clone();
            if let Some(channel) = maybe_channel {
                let _ = channel.send(&out).await;
            } else {
                let _ = handle.broadcast_voice(seq, timestamp, out).await;
            }
            seq = seq.wrapping_add(1);
        }
    });

    if !config.audio.mute_output {
        let mixer = mixer.clone();
        let audio_config = audio_config.clone();
        std::thread::spawn(move || {
            let audio_out = match AudioOut::new_with_device(&audio_config, output_device.as_deref()) {
                Ok(out) => out,
                Err(err) => {
                    tracing::warn!("audio output init failed: {err}");
                    return;
                }
            };
            let frame_samples = audio_out.frame_samples();
            let frame_duration = audio_config.frame_duration();
            let target_frames = 6usize;
            let mut last_frame = vec![0i16; frame_samples];
            let mut last_active = Instant::now() - Duration::from_secs(1);
            loop {
                std::thread::sleep(frame_duration);
                while audio_out.queued_samples() < target_frames * frame_samples {
                    let (frame, active) = {
                        let mut mixer = mixer.lock().unwrap();
                        mixer.mix_next_with_activity()
                    };
                    let out_frame = if active {
                        last_active = Instant::now();
                        last_frame.clone_from(&frame);
                        frame
                    } else if last_active.elapsed() <= Duration::from_millis(300) {
                        last_frame.clone()
                    } else {
                        frame
                    };
                    if out_frame.len() == frame_samples {
                        audio_out.push_frame(&out_frame);
                    } else {
                        break;
                    }
                }
            }
        });
    }

    Ok(VoiceRuntime {
        _audio_in: audio_in,
        mixer,
        frame_samples: audio_config.frame_samples(),
        emit_voice: config.audio.emit_voice_frames,
        audio_config,
        tuning,
        rndzv_channel,
        rndzv_remote_peer,
    })
}

fn audio_level(frame: &[i16]) -> f32 {
    let mut sum = 0f32;
    for s in frame {
        sum += (*s as f32).abs();
    }
    (sum / frame.len().max(1) as f32) / i16::MAX as f32
}

fn is_frame_active(frame: &[i16]) -> bool {
    let mut sum = 0i64;
    for s in frame {
        sum += (*s as i64).abs();
    }
    let avg = sum / frame.len().max(1) as i64;
    avg > 250
}

/// Compute the next audio tuning parameters based on current QoS stats.
fn compute_next_tuning(qos: &mut QosState) -> Option<AudioTuning> {
    if qos.peer_stats.is_empty() {
        return None;
    }
    let now = Instant::now();
    if now.duration_since(qos.last_adjust) < Duration::from_secs(2) {
        return None;
    }
    let mut worst_rtt = 0.0f32;
    let mut worst_loss = 0.0f32;
    for stats in qos.peer_stats.values() {
        worst_rtt = worst_rtt.max(stats.rtt_ms);
        worst_loss = worst_loss.max(stats.loss);
    }

    let mut bitrate = qos.current.bitrate;
    let max_latency = qos.profile.max_latency_ms as f32;
    let target_latency = qos.profile.target_latency_ms as f32;
    if worst_loss > qos.profile.packet_loss_tolerance || worst_rtt > max_latency {
        bitrate = ((bitrate as f32) * 0.8) as u32;
    } else if worst_loss < qos.profile.packet_loss_tolerance * 0.5
        && worst_rtt < target_latency
    {
        bitrate = ((bitrate as f32) * 1.1) as u32;
    }
    bitrate = bitrate
        .clamp(qos.profile.min_bitrate, qos.profile.max_bitrate)
        .max(8_000);

    let fec = worst_loss > qos.profile.packet_loss_tolerance * 0.5;
    let loss_pct = (worst_loss * 100.0).round().min(100.0) as u8;

    let next = AudioTuning {
        bitrate,
        fec,
        loss_pct,
    };
    if next.bitrate != qos.current.bitrate
        || next.fec != qos.current.fec
        || next.loss_pct != qos.current.loss_pct
    {
        rift_metrics::set_gauge("rift_audio_bitrate", &[], next.bitrate as f64);
        tracing::info!(
            bitrate = next.bitrate,
            fec = next.fec,
            loss_pct = next.loss_pct,
            "qos audio tuning updated"
        );
        qos.current = next.clone();
        qos.last_adjust = now;
        return Some(next);
    }
    None
}

fn map_quality_to_bitrate(quality: Option<&str>) -> u32 {
    match quality.unwrap_or("medium") {
        "low" => 24_000,
        "high" => 96_000,
        _ => 48_000,
    }
}

fn now_timestamp() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

fn peer_to_stream_id(peer: &PeerId) -> u64 {
    let mut bytes = [0u8; 8];
    bytes.copy_from_slice(&peer.0[..8]);
    u64::from_le_bytes(bytes)
}

fn default_nat_config(
    port: u16,
    ports: Option<Vec<u16>>,
    stun_servers: Vec<String>,
    stun_timeout_ms: Option<u64>,
    punch_interval_ms: Option<u64>,
    punch_timeout_ms: Option<u64>,
    enable_turn: bool,
    turn_servers: Vec<String>,
    turn_timeout_ms: Option<u64>,
    turn_keepalive_ms: Option<u64>,
) -> NatConfig {
    let mut local_ports = ports.unwrap_or_default();
    if local_ports.is_empty() {
        local_ports.push(port);
        local_ports.push(port.saturating_add(1));
        local_ports.push(port.saturating_add(2));
    }
    NatConfig {
        local_ports,
        stun_servers: parse_socket_addrs(&stun_servers),
        stun_timeout_ms: stun_timeout_ms.unwrap_or(800),
        punch_interval_ms: punch_interval_ms.unwrap_or(200),
        punch_timeout_ms: punch_timeout_ms.unwrap_or(5000),
        turn_servers: if enable_turn {
            turn_servers
                .into_iter()
                .filter_map(|s| parse_turn_server(&s).ok())
                .collect()
        } else {
            Vec::new()
        },
        turn_timeout_ms: turn_timeout_ms.unwrap_or(1200),
        turn_keepalive_ms: turn_keepalive_ms.unwrap_or(12000),
    }
}

/// Derive a per-channel auth token from a shared secret.
fn derive_auth_token(secret: &str, channel: &str) -> Vec<u8> {
    let hk = Hkdf::<Sha256>::new(Some(channel.as_bytes()), secret.as_bytes());
    let mut out = [0u8; 32];
    hk.expand(b"rift-auth", &mut out)
        .expect("hkdf expand");
    out.to_vec()
}

fn derive_e2ee_key(
    channel: &str,
    password: Option<&str>,
    invite: Option<&Invite>,
    shared_secret: Option<&str>,
) -> Option<[u8; 32]> {
    if let Some(secret) = shared_secret {
        let hk = Hkdf::<Sha256>::new(Some(channel.as_bytes()), secret.as_bytes());
        let mut out = [0u8; 32];
        hk.expand(b"rift-e2ee", &mut out)
            .expect("hkdf expand");
        return Some(out);
    }
    if let Some(invite) = invite {
        if invite.channel_key.iter().any(|b| *b != 0) {
            return Some(invite.channel_key);
        }
    }
    if let Some(password) = password {
        let mut hasher = blake3::Hasher::new();
        hasher.update(b"rift-e2ee:");
        hasher.update(channel.as_bytes());
        hasher.update(b":");
        hasher.update(password.as_bytes());
        let mut out = [0u8; 32];
        out.copy_from_slice(hasher.finalize().as_bytes());
        return Some(out);
    }
    None
}

fn short_peer(peer_id: &PeerId) -> String {
    let hex = peer_id.to_hex();
    hex.chars().take(8).collect()
}

fn resolve_known_hosts_path(cfg: &SecurityConfig) -> Result<PathBuf, RiftError> {
    if let Some(path) = &cfg.known_hosts_path {
        return Ok(expand_tilde(path));
    }
    let base = dirs::config_dir().ok_or_else(|| RiftError::Other("config dir missing".to_string()))?;
    Ok(base.join("rift").join("known_hosts"))
}

fn expand_tilde(path: &Path) -> PathBuf {
    let path_str = path.to_string_lossy();
    if let Some(rest) = path_str.strip_prefix("~/") {
        if let Some(home) = dirs::home_dir() {
            return home.join(rest);
        }
    }
    path.to_path_buf()
}

fn load_known_hosts(path: &Path) -> HashMap<PeerId, Vec<u8>> {
    let mut map = HashMap::new();
    let Ok(content) = fs::read_to_string(path) else {
        return map;
    };
    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let mut parts = line.split_whitespace();
        let Some(peer_hex) = parts.next() else { continue; };
        let Some(key_hex) = parts.next() else { continue; };
        let Ok(peer_bytes) = hex::decode(peer_hex) else { continue; };
        let Ok(key_bytes) = hex::decode(key_hex) else { continue; };
        if peer_bytes.len() != 32 {
            continue;
        }
        let mut peer = [0u8; 32];
        peer.copy_from_slice(&peer_bytes);
        map.insert(PeerId(peer), key_bytes);
    }
    map
}

fn append_known_host(path: &Path, peer_id: PeerId, public_key: &[u8]) -> Result<(), RiftError> {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).map_err(|e| RiftError::Other(format!("{e}")))?;
    }
    let line = format!("{} {}\n", peer_id.to_hex(), hex::encode(public_key));
    fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)
        .and_then(|mut file| std::io::Write::write_all(&mut file, line.as_bytes()))
        .map_err(|e| RiftError::Other(format!("{e}")))?;
    Ok(())
}

fn fingerprint_key(public_key: &[u8]) -> String {
    let hash = blake3::hash(public_key);
    let hex = hash.to_hex().to_string();
    hex.chars().take(16).collect()
}

/// Verify and record peer identity for trust-on-first-use and mismatch handling.
async fn handle_peer_identity(
    event_tx: &mpsc::UnboundedSender<RiftEvent>,
    handle: &MeshHandle,
    cfg: &SecurityConfig,
    peer_id: PeerId,
    public_key: &[u8],
) -> Result<(), RiftError> {
    let computed = rift_core::peer_id_from_public_key_bytes(public_key)
        .map_err(|e| RiftError::Other(format!("{e}")))?;
    let fingerprint = fingerprint_key(public_key);
    let _ = event_tx.send(RiftEvent::PeerFingerprint {
        peer: peer_id,
        fingerprint: fingerprint.clone(),
    });
    let known_hosts = resolve_known_hosts_path(cfg)?;
    let mut known = load_known_hosts(&known_hosts);

    if computed != peer_id {
        let msg = format!(
            "peer id mismatch for {} (fingerprint {})",
            short_peer(&peer_id),
            fingerprint
        );
        tracing::warn!(peer = %peer_id, "peer id mismatch");
        let _ = event_tx.send(RiftEvent::SecurityNotice { message: msg.clone() });
        audit_log(cfg, "peer_id_mismatch", &peer_id, Some(&fingerprint), &msg);
        if cfg.reject_on_mismatch {
            handle.disconnect_peer(peer_id).await;
        }
        return Ok(());
    }

    if let Some(existing) = known.get(&peer_id) {
        if existing != public_key {
            let msg = format!(
                "peer key mismatch for {} (fingerprint {})",
                short_peer(&peer_id),
                fingerprint
            );
            tracing::warn!(peer = %peer_id, "peer key mismatch");
            let _ = event_tx.send(RiftEvent::SecurityNotice { message: msg.clone() });
            audit_log(cfg, "peer_key_mismatch", &peer_id, Some(&fingerprint), &msg);
            if cfg.reject_on_mismatch {
                handle.disconnect_peer(peer_id).await;
            }
        }
        return Ok(());
    }

    if cfg.trust_on_first_use {
        append_known_host(&known_hosts, peer_id, public_key)?;
        known.insert(peer_id, public_key.to_vec());
        let msg = format!(
            "new peer: {} fingerprint {} (saved to known_hosts)",
            short_peer(&peer_id),
            fingerprint
        );
        tracing::info!(peer = %peer_id, "new peer key stored");
        let _ = event_tx.send(RiftEvent::SecurityNotice { message: msg.clone() });
        audit_log(cfg, "peer_first_seen", &peer_id, Some(&fingerprint), &msg);
    } else {
        let msg = format!(
            "untrusted peer {} fingerprint {} (TOFU disabled)",
            short_peer(&peer_id),
            fingerprint
        );
        tracing::warn!(peer = %peer_id, "untrusted peer (TOFU disabled)");
        let _ = event_tx.send(RiftEvent::SecurityNotice { message: msg.clone() });
        audit_log(cfg, "peer_untrusted", &peer_id, Some(&fingerprint), &msg);
        handle.disconnect_peer(peer_id).await;
    }
    Ok(())
}

fn audit_log(cfg: &SecurityConfig, event: &str, peer_id: &PeerId, fingerprint: Option<&str>, message: &str) {
    let Some(path) = cfg.audit_log_path.as_ref() else { return; };
    let path = expand_tilde(path);
    if let Some(parent) = path.parent() {
        let _ = fs::create_dir_all(parent);
    }
    let entry = json!({
        "ts": now_timestamp(),
        "event": event,
        "peer_id": peer_id.to_hex(),
        "fingerprint": fingerprint.unwrap_or(""),
        "message": message,
    });
    if let Ok(line) = serde_json::to_string(&entry) {
        if let Ok(mut file) = fs::OpenOptions::new().create(true).append(true).open(&path) {
            let _ = std::io::Write::write_all(&mut file, line.as_bytes());
            let _ = std::io::Write::write_all(&mut file, b"\n");
        }
    }
}

fn parse_socket_addr(input: &str) -> Option<SocketAddr> {
    input.parse::<SocketAddr>().ok()
}

fn parse_socket_addrs(inputs: &[String]) -> Vec<SocketAddr> {
    let mut out = Vec::new();
    for input in inputs {
        if let Ok(addr) = input.parse::<SocketAddr>() {
            out.push(addr);
            continue;
        }
        if let Ok(mut iter) = input.to_socket_addrs() {
            if let Some(addr) = iter.next() {
                out.push(addr);
            }
        }
    }
    out
}

#[cfg(feature = "ffi")]
pub mod ffi;
#[cfg(target_os = "android")]
pub mod android_jni;

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    // ---- Config Default Tests ----

    #[test]
    fn rift_config_default_values() {
        let cfg = RiftConfig::default();
        assert_eq!(cfg.listen_port, 7777);
        assert!(!cfg.relay);
        assert!(cfg.user_name.is_none());
        assert!(cfg.metrics_enabled);
        assert_eq!(cfg.preferred_codecs, vec![CodecId::Opus, CodecId::PCM16]);
        assert!(cfg.preferred_features.contains(&FeatureFlag::Voice));
        assert!(cfg.preferred_features.contains(&FeatureFlag::E2EE));
    }

    #[test]
    fn audio_config_sdk_default_values() {
        let cfg = AudioConfigSdk::default();
        assert!(cfg.enabled);
        assert!(cfg.input_device.is_none());
        assert!(cfg.output_device.is_none());
        assert_eq!(cfg.quality, "medium");
        assert!(!cfg.ptt);
        assert!(cfg.vad);
        assert!(!cfg.mute_output);
        assert!(!cfg.emit_voice_frames);
        assert!(!cfg.allow_fail);
    }

    #[test]
    fn network_config_sdk_default_values() {
        let cfg = NetworkConfigSdk::default();
        assert!(cfg.prefer_p2p);
        assert!(cfg.local_ports.is_none());
        assert!(cfg.known_peers.is_empty());
        assert!(cfg.invite.is_none());
        assert!(!cfg.stun_servers.is_empty());
        assert_eq!(cfg.stun_timeout_ms, Some(800));
        assert!(!cfg.enable_turn);
        assert!(cfg.turn_servers.is_empty());
        assert_eq!(cfg.punch_interval_ms, Some(200));
        assert_eq!(cfg.punch_timeout_ms, Some(5000));
    }

    #[test]
    fn dht_config_sdk_default_values() {
        let cfg = DhtConfigSdk::default();
        assert!(!cfg.enabled);
        assert!(cfg.bootstrap_nodes.is_empty());
        assert!(cfg.listen_addr.is_none());
    }

    #[test]
    fn security_config_default_values() {
        let cfg = SecurityConfig::default();
        assert!(cfg.trust_on_first_use);
        assert!(cfg.known_hosts_path.is_none());
        assert!(!cfg.reject_on_mismatch);
        assert!(cfg.channel_shared_secret.is_none());
        assert!(cfg.audit_log_path.is_none());
        assert_eq!(cfg.rekey_interval_secs, Some(600));
    }

    // ---- Helper Function Tests ----

    #[test]
    fn derive_auth_token_deterministic() {
        let token1 = derive_auth_token("secret", "channel");
        let token2 = derive_auth_token("secret", "channel");
        assert_eq!(token1, token2);
        assert_eq!(token1.len(), 32);
    }

    #[test]
    fn derive_auth_token_different_inputs() {
        let token1 = derive_auth_token("secret1", "channel");
        let token2 = derive_auth_token("secret2", "channel");
        assert_ne!(token1, token2);

        let token3 = derive_auth_token("secret", "channel1");
        let token4 = derive_auth_token("secret", "channel2");
        assert_ne!(token3, token4);
    }

    #[test]
    fn derive_e2ee_key_from_shared_secret() {
        let key = derive_e2ee_key("channel", None, None, Some("shared_secret"));
        assert!(key.is_some());
        let key = key.unwrap();
        assert_eq!(key.len(), 32);

        // Deterministic
        let key2 = derive_e2ee_key("channel", None, None, Some("shared_secret"));
        assert_eq!(key, key2.unwrap());
    }

    #[test]
    fn derive_e2ee_key_from_password() {
        let key = derive_e2ee_key("channel", Some("password"), None, None);
        assert!(key.is_some());
        let key = key.unwrap();
        assert_eq!(key.len(), 32);

        // Different password = different key
        let key2 = derive_e2ee_key("channel", Some("other_password"), None, None);
        assert_ne!(key, key2.unwrap());
    }

    #[test]
    fn derive_e2ee_key_from_invite() {
        let invite = Invite {
            channel_name: "test".to_string(),
            password: None,
            channel_key: [42u8; 32],
            known_peers: Vec::new(),
            candidates: Vec::new(),
            relay_candidates: Vec::new(),
            version: 2,
            created_at: 0,
        };
        let key = derive_e2ee_key("channel", None, Some(&invite), None);
        assert_eq!(key, Some([42u8; 32]));
    }

    #[test]
    fn derive_e2ee_key_none_without_inputs() {
        let key = derive_e2ee_key("channel", None, None, None);
        assert!(key.is_none());
    }

    #[test]
    fn derive_e2ee_key_priority_shared_secret_over_password() {
        // Shared secret takes priority over password
        let key_secret = derive_e2ee_key("channel", Some("password"), None, Some("secret"));
        let key_password = derive_e2ee_key("channel", Some("password"), None, None);
        assert_ne!(key_secret, key_password);
    }

    #[test]
    fn fingerprint_key_returns_16_chars() {
        let key = [1u8; 32];
        let fp = fingerprint_key(&key);
        assert_eq!(fp.len(), 16);
        assert!(fp.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[test]
    fn fingerprint_key_different_keys() {
        let fp1 = fingerprint_key(&[1u8; 32]);
        let fp2 = fingerprint_key(&[2u8; 32]);
        assert_ne!(fp1, fp2);
    }

    #[test]
    fn short_peer_returns_8_chars() {
        let peer = PeerId([0xab; 32]);
        let short = short_peer(&peer);
        assert_eq!(short.len(), 8);
        assert_eq!(short, "abababab");
    }

    // ---- Audio Helper Tests ----

    #[test]
    fn audio_level_silent_frame() {
        let frame = vec![0i16; 480];
        let level = audio_level(&frame);
        assert_eq!(level, 0.0);
    }

    #[test]
    fn audio_level_loud_frame() {
        let frame = vec![i16::MAX; 480];
        let level = audio_level(&frame);
        assert!((level - 1.0).abs() < 0.01);
    }

    #[test]
    fn audio_level_mixed_frame() {
        let mut frame = vec![0i16; 480];
        for i in 0..240 {
            frame[i] = i16::MAX / 2;
        }
        let level = audio_level(&frame);
        assert!(level > 0.0 && level < 1.0);
    }

    #[test]
    fn is_frame_active_silent() {
        let frame = vec![0i16; 480];
        assert!(!is_frame_active(&frame));
    }

    #[test]
    fn is_frame_active_low_noise() {
        let frame = vec![100i16; 480];
        assert!(!is_frame_active(&frame));
    }

    #[test]
    fn is_frame_active_loud() {
        let frame = vec![1000i16; 480];
        assert!(is_frame_active(&frame));
    }

    // ---- Quality Mapping Tests ----

    #[test]
    fn map_quality_to_bitrate_low() {
        assert_eq!(map_quality_to_bitrate(Some("low")), 24_000);
    }

    #[test]
    fn map_quality_to_bitrate_medium() {
        assert_eq!(map_quality_to_bitrate(Some("medium")), 48_000);
    }

    #[test]
    fn map_quality_to_bitrate_high() {
        assert_eq!(map_quality_to_bitrate(Some("high")), 96_000);
    }

    #[test]
    fn map_quality_to_bitrate_default() {
        assert_eq!(map_quality_to_bitrate(None), 48_000);
        assert_eq!(map_quality_to_bitrate(Some("unknown")), 48_000);
    }

    // ---- Path Expansion Tests ----

    #[test]
    fn expand_tilde_with_tilde() {
        let path = PathBuf::from("~/test/path");
        let expanded = expand_tilde(&path);
        // Should not start with ~ anymore
        assert!(!expanded.to_string_lossy().starts_with("~/"));
    }

    #[test]
    fn expand_tilde_without_tilde() {
        let path = PathBuf::from("/absolute/path");
        let expanded = expand_tilde(&path);
        assert_eq!(expanded, path);
    }

    #[test]
    fn expand_tilde_relative_path() {
        let path = PathBuf::from("relative/path");
        let expanded = expand_tilde(&path);
        assert_eq!(expanded, path);
    }

    // ---- Socket Addr Parsing Tests ----

    #[test]
    fn parse_socket_addr_valid() {
        let addr = parse_socket_addr("127.0.0.1:8080");
        assert!(addr.is_some());
        assert_eq!(addr.unwrap().port(), 8080);
    }

    #[test]
    fn parse_socket_addr_invalid() {
        let addr = parse_socket_addr("invalid");
        assert!(addr.is_none());
    }

    #[test]
    fn parse_socket_addrs_mixed() {
        let inputs = vec![
            "127.0.0.1:8080".to_string(),
            "invalid".to_string(),
            "192.168.1.1:9000".to_string(),
        ];
        let addrs = parse_socket_addrs(&inputs);
        assert_eq!(addrs.len(), 2);
    }

    #[test]
    fn parse_socket_addrs_empty() {
        let addrs = parse_socket_addrs(&[]);
        assert!(addrs.is_empty());
    }

    // ---- Known Hosts Tests ----

    #[test]
    fn load_known_hosts_empty_file() {
        let tmp = NamedTempFile::new().unwrap();
        let hosts = load_known_hosts(tmp.path());
        assert!(hosts.is_empty());
    }

    #[test]
    fn load_known_hosts_with_entries() {
        let mut tmp = NamedTempFile::new().unwrap();
        let peer_hex = hex::encode([0xab; 32]);
        let key_hex = hex::encode([0xcd; 32]);
        writeln!(tmp, "{} {}", peer_hex, key_hex).unwrap();
        tmp.flush().unwrap();

        let hosts = load_known_hosts(tmp.path());
        assert_eq!(hosts.len(), 1);
        let peer = PeerId([0xab; 32]);
        assert!(hosts.contains_key(&peer));
        assert_eq!(hosts[&peer], vec![0xcd; 32]);
    }

    #[test]
    fn load_known_hosts_with_comments() {
        let mut tmp = NamedTempFile::new().unwrap();
        writeln!(tmp, "# This is a comment").unwrap();
        writeln!(tmp, "").unwrap();
        let peer_hex = hex::encode([0xab; 32]);
        let key_hex = hex::encode([0xcd; 32]);
        writeln!(tmp, "{} {}", peer_hex, key_hex).unwrap();
        tmp.flush().unwrap();

        let hosts = load_known_hosts(tmp.path());
        assert_eq!(hosts.len(), 1);
    }

    #[test]
    fn load_known_hosts_nonexistent() {
        let hosts = load_known_hosts(Path::new("/nonexistent/path"));
        assert!(hosts.is_empty());
    }

    // ---- Peer to Stream ID Tests ----

    #[test]
    fn peer_to_stream_id_deterministic() {
        let peer = PeerId([0x12; 32]);
        let id1 = peer_to_stream_id(&peer);
        let id2 = peer_to_stream_id(&peer);
        assert_eq!(id1, id2);
    }

    #[test]
    fn peer_to_stream_id_different_peers() {
        let peer1 = PeerId([0x12; 32]);
        let peer2 = PeerId([0x34; 32]);
        let id1 = peer_to_stream_id(&peer1);
        let id2 = peer_to_stream_id(&peer2);
        assert_ne!(id1, id2);
    }

    // ---- Timestamp Tests ----

    #[test]
    fn now_timestamp_nonzero() {
        let ts = now_timestamp();
        // Should be a reasonable timestamp (after 2020)
        assert!(ts > 1577836800000);
    }

    // ---- Error Display Tests ----

    #[test]
    fn rift_error_display() {
        assert_eq!(format!("{}", RiftError::NotInitialized), "not initialized");
        assert_eq!(format!("{}", RiftError::AlreadyJoined), "channel already joined");
        assert_eq!(format!("{}", RiftError::NotJoined), "channel not joined");
        assert_eq!(format!("{}", RiftError::Mesh("test".to_string())), "mesh error: test");
        assert_eq!(format!("{}", RiftError::Audio("test".to_string())), "audio error: test");
        assert_eq!(format!("{}", RiftError::Other("test".to_string())), "other: test");
    }

    // ---- LinkStats and GlobalStats Tests ----

    #[test]
    fn link_stats_construction() {
        let stats = LinkStats {
            rtt_ms: 50.0,
            loss: 0.01,
            jitter_ms: 5.0,
        };
        assert_eq!(stats.rtt_ms, 50.0);
        assert_eq!(stats.loss, 0.01);
        assert_eq!(stats.jitter_ms, 5.0);
    }

    #[test]
    fn global_stats_construction() {
        let stats = GlobalStats {
            num_peers: 5,
            num_sessions: 2,
            packets_sent: 1000,
            packets_received: 950,
            bytes_sent: 100_000,
            bytes_received: 95_000,
        };
        assert_eq!(stats.num_peers, 5);
        assert_eq!(stats.packets_sent, 1000);
    }

    // ---- Route Kind Tests ----

    #[test]
    fn route_kind_direct() {
        let route = RouteKind::Direct;
        assert!(matches!(route, RouteKind::Direct));
    }

    #[test]
    fn route_kind_relayed() {
        let via = PeerId([0xab; 32]);
        let route = RouteKind::Relayed { via };
        if let RouteKind::Relayed { via: v } = route {
            assert_eq!(v.0, [0xab; 32]);
        } else {
            panic!("expected relayed route");
        }
    }

    // ---- SDK Version Constants ----

    #[test]
    fn sdk_version_defined() {
        assert_eq!(SDK_VERSION, "0.1.0");
        assert_eq!(SDK_ABI_VERSION, 1);
    }

    // ---- NAT Config Tests ----

    #[test]
    fn default_nat_config_basic() {
        let cfg = default_nat_config(
            7777,
            None,
            vec!["stun.example.com:3478".to_string()],
            Some(1000),
            Some(100),
            Some(3000),
            false,
            Vec::new(),
            Some(2000),
            Some(15000),
        );
        assert_eq!(cfg.local_ports, vec![7777, 7778, 7779]);
        assert_eq!(cfg.stun_timeout_ms, 1000);
        assert_eq!(cfg.punch_interval_ms, 100);
        assert_eq!(cfg.punch_timeout_ms, 3000);
        assert!(cfg.turn_servers.is_empty());
    }

    #[test]
    fn default_nat_config_custom_ports() {
        let cfg = default_nat_config(
            7777,
            Some(vec![8000, 8001]),
            Vec::new(),
            None,
            None,
            None,
            false,
            Vec::new(),
            None,
            None,
        );
        assert_eq!(cfg.local_ports, vec![8000, 8001]);
    }

    // ---- Serialization Tests ----

    #[test]
    fn rift_config_serialization() {
        let cfg = RiftConfig::default();
        let json = serde_json::to_string(&cfg).unwrap();
        let parsed: RiftConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.listen_port, cfg.listen_port);
        assert_eq!(parsed.relay, cfg.relay);
    }

    #[test]
    fn security_config_serialization() {
        let cfg = SecurityConfig {
            trust_on_first_use: false,
            known_hosts_path: Some(PathBuf::from("/test/path")),
            reject_on_mismatch: true,
            channel_shared_secret: Some("secret".to_string()),
            audit_log_path: None,
            rekey_interval_secs: Some(300),
        };
        let json = serde_json::to_string(&cfg).unwrap();
        let parsed: SecurityConfig = serde_json::from_str(&json).unwrap();
        assert!(!parsed.trust_on_first_use);
        assert!(parsed.reject_on_mismatch);
        assert_eq!(parsed.rekey_interval_secs, Some(300));
    }

    #[test]
    fn srt_invite_serialization() {
        let invite = SrtInvite {
            label: "Test Call".to_string(),
            uri: "srt://test".to_string(),
        };
        let json = serde_json::to_string(&invite).unwrap();
        let parsed: SrtInvite = serde_json::from_str(&json).unwrap();
        assert_eq!(parsed.label, "Test Call");
        assert_eq!(parsed.uri, "srt://test");
    }

    // ---- QoS Tuning Tests ----

    #[test]
    fn compute_next_tuning_empty_stats() {
        let mut qos = QosState {
            profile: QosProfile::default(),
            peer_stats: HashMap::new(),
            current: AudioTuning {
                bitrate: 48_000,
                fec: false,
                loss_pct: 0,
            },
            last_adjust: Instant::now() - Duration::from_secs(10),
        };
        let result = compute_next_tuning(&mut qos);
        assert!(result.is_none());
    }

    #[test]
    fn compute_next_tuning_high_loss() {
        let mut qos = QosState {
            profile: QosProfile {
                packet_loss_tolerance: 0.05,
                max_latency_ms: 200,
                target_latency_ms: 100,
                min_bitrate: 16_000,
                max_bitrate: 128_000,
                ..Default::default()
            },
            peer_stats: HashMap::new(),
            current: AudioTuning {
                bitrate: 64_000,
                fec: false,
                loss_pct: 0,
            },
            last_adjust: Instant::now() - Duration::from_secs(10),
        };
        qos.peer_stats.insert(
            PeerId([0; 32]),
            LinkStats {
                rtt_ms: 50.0,
                loss: 0.10,  // 10% loss, above tolerance
                jitter_ms: 5.0,
            },
        );
        let result = compute_next_tuning(&mut qos);
        assert!(result.is_some());
        let tuning = result.unwrap();
        assert!(tuning.bitrate < 64_000); // Should decrease bitrate
        assert!(tuning.fec); // Should enable FEC
    }

    #[test]
    fn compute_next_tuning_good_conditions() {
        let mut qos = QosState {
            profile: QosProfile {
                packet_loss_tolerance: 0.05,
                max_latency_ms: 200,
                target_latency_ms: 100,
                min_bitrate: 16_000,
                max_bitrate: 128_000,
                ..Default::default()
            },
            peer_stats: HashMap::new(),
            current: AudioTuning {
                bitrate: 48_000,
                fec: true,
                loss_pct: 5,
            },
            last_adjust: Instant::now() - Duration::from_secs(10),
        };
        qos.peer_stats.insert(
            PeerId([0; 32]),
            LinkStats {
                rtt_ms: 20.0,
                loss: 0.01,  // 1% loss, below tolerance
                jitter_ms: 2.0,
            },
        );
        let result = compute_next_tuning(&mut qos);
        assert!(result.is_some());
        let tuning = result.unwrap();
        assert!(tuning.bitrate >= 48_000); // Should increase or maintain bitrate
    }

    #[test]
    fn compute_next_tuning_respects_cooldown() {
        let mut qos = QosState {
            profile: QosProfile::default(),
            peer_stats: HashMap::new(),
            current: AudioTuning {
                bitrate: 48_000,
                fec: false,
                loss_pct: 0,
            },
            last_adjust: Instant::now(), // Just adjusted
        };
        qos.peer_stats.insert(
            PeerId([0; 32]),
            LinkStats {
                rtt_ms: 500.0,
                loss: 0.50,
                jitter_ms: 50.0,
            },
        );
        let result = compute_next_tuning(&mut qos);
        assert!(result.is_none()); // Should not adjust due to cooldown
    }
}