xphone 0.4.5

SIP telephony library with event-driven API — handles SIP signaling, RTP media, codecs, and call state
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
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
use std::collections::HashMap;
use std::net::UdpSocket;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};

use parking_lot::Mutex;
use tracing::info;

use crate::callback_pool::spawn_callback;
use crate::config::DialOptions;
use crate::dialog::Dialog;
use crate::dtmf;
use crate::error::{Error, Result};
use crate::media::{self, MediaChannels, MediaConfig, MediaTransport};
use crate::sdp;
use crate::srtp::SrtpContext;
use crate::types::*;

/// A pending video upgrade request from the remote party.
///
/// Created when the remote sends a re-INVITE adding video to an existing audio call.
/// The application must call [`accept()`](Self::accept) or [`reject()`](Self::reject)
/// to respond. If dropped without responding, the request is automatically rejected
/// (safe default — no video without explicit consent).
pub struct VideoUpgradeRequest {
    call: Arc<Call>,
    reinvite_dlg: Arc<dyn Dialog>,
    remote_sdp: String,
    sess: sdp::Session,
    video_socket: Option<(UdpSocket, u16)>,
    responded: Arc<AtomicBool>,
}

// SAFETY: All fields are Send+Sync (Dialog is Send+Sync, UdpSocket is Send).
unsafe impl Send for VideoUpgradeRequest {}
unsafe impl Sync for VideoUpgradeRequest {}

impl VideoUpgradeRequest {
    /// Accepts the video upgrade. Allocates video resources, builds an SDP answer
    /// with video, sends 200 OK, starts the video pipeline, and fires the `on_video` callback.
    pub fn accept(&self) {
        if self.responded.swap(true, Ordering::SeqCst) {
            return; // already responded
        }
        self.call.accept_video_internal(
            &self.reinvite_dlg,
            &self.sess,
            &self.remote_sdp,
            &self.video_socket,
        );
    }

    /// Rejects the video upgrade. Sends 200 OK with audio-only SDP (video m= line
    /// set to port 0 per RFC 3264). The audio call continues unchanged.
    pub fn reject(&self) {
        if self.responded.swap(true, Ordering::SeqCst) {
            return; // already responded
        }
        self.call
            .reject_video_internal(&self.reinvite_dlg, &self.sess, &self.remote_sdp);
    }
}

impl Drop for VideoUpgradeRequest {
    fn drop(&mut self) {
        // Auto-reject if the app didn't respond — safe default.
        if !self.responded.load(Ordering::SeqCst) {
            self.responded.store(true, Ordering::SeqCst);
            self.call
                .reject_video_internal(&self.reinvite_dlg, &self.sess, &self.remote_sdp);
        }
    }
}

/// Default codec preference order (payload types).
const DEFAULT_CODEC_PREFS: &[i32] = &[8, 0, 9, 101, 111];

fn new_call_id() -> String {
    let mut buf = [0u8; 16];
    // Use thread_rng for non-crypto random IDs.
    for b in &mut buf {
        *b = rand_byte();
    }
    format!("CA{}", hex::encode(&buf))
}

fn rand_byte() -> u8 {
    use std::cell::Cell;
    thread_local! {
        static RNG: Cell<u64> = Cell::new(
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos() as u64
        );
    }
    RNG.with(|rng| {
        // Simple xorshift64
        let mut s = rng.get();
        s ^= s << 13;
        s ^= s >> 7;
        s ^= s << 17;
        rng.set(s);
        s as u8
    })
}

mod hex {
    pub fn encode(bytes: &[u8]) -> String {
        bytes.iter().map(|b| format!("{b:02x}")).collect()
    }
}

// --- SIP header helpers ---

/// Extracts the SIP URI from a header value.
/// e.g. `"Alice" <sip:1001@host>;tag=xyz` -> `sip:1001@host`
pub fn sip_header_uri(val: &str) -> &str {
    if let (Some(start), Some(end)) = (val.find('<'), val.find('>')) {
        if end > start {
            return &val[start + 1..end];
        }
    }
    val
}

/// Percent-encodes special characters for SIP URI parameters (RFC 3891 Replaces).
fn uri_encode(val: &str) -> String {
    let mut out = String::with_capacity(val.len() * 2);
    for b in val.bytes() {
        match b {
            b'%' => out.push_str("%25"),
            b'@' => out.push_str("%40"),
            b' ' => out.push_str("%20"),
            b';' => out.push_str("%3B"),
            b'?' => out.push_str("%3F"),
            b'&' => out.push_str("%26"),
            b'=' => out.push_str("%3D"),
            b'+' => out.push_str("%2B"),
            b':' => out.push_str("%3A"),
            _ => out.push(b as char),
        }
    }
    out
}

/// Extracts the user part from a SIP header value.
/// e.g. `"Alice" <sip:+15551234567@host>;tag=xyz` -> `+15551234567`
pub fn sip_header_user(val: &str) -> &str {
    let uri = sip_header_uri(val);
    let uri = if let Some(i) = uri.find(':') {
        &uri[i + 1..]
    } else {
        uri
    };
    if let Some(i) = uri.find('@') {
        &uri[..i]
    } else {
        uri
    }
}

/// Extracts the tag parameter from a SIP header value.
/// e.g. `<sip:1001@host>;tag=abc123` -> `abc123`
pub fn sip_header_tag(val: &str) -> &str {
    // Use ASCII lowercase to preserve byte offsets (SIP params are ASCII).
    let lower = val.to_ascii_lowercase();
    if let Some(idx) = lower.find(";tag=") {
        let start = idx + 5;
        let rest = &val[start..];
        let end = rest.find([';', '>', ',']).unwrap_or(rest.len());
        &rest[..end]
    } else {
        ""
    }
}

/// Extracts the display name from a SIP header value.
/// e.g. `"Alice" <sip:1001@host>` -> `Alice`
pub fn sip_header_display_name(val: &str) -> &str {
    let lt = match val.find('<') {
        Some(0) | None => return "",
        Some(i) => i,
    };
    let name = val[..lt].trim();
    if name.len() >= 2 && name.starts_with('"') && name.ends_with('"') {
        &name[1..name.len() - 1]
    } else {
        name
    }
}

// --- Call struct ---

struct CallInner {
    id: String,
    state: CallState,
    direction: Direction,
    opts: DialOptions,
    start_time: Option<Instant>,
    muted: bool,

    codec_prefs: Vec<i32>,
    local_ip: String,
    rtp_port: i32,
    remote_ip: String,
    remote_port: i32,

    local_sdp: String,
    remote_sdp: String,
    codec: Codec,

    media_active: bool,
    /// DTMF transport mode for this call.
    dtmf_mode: crate::config::DtmfMode,
    /// Whether SRTP is enabled for this call.
    srtp_enabled: bool,
    /// Local SRTP keying material (base64 inline key).
    srtp_local_key: String,
    /// Remote SRTP keying material (base64 inline key).
    srtp_remote_key: String,

    rtp_socket: Option<Arc<UdpSocket>>,
    media_streams: Vec<media::MediaStream>,
    media_shared: Option<Arc<media::MediaSharedState>>,

    video_muted: bool,
    video_codec: Option<VideoCodec>,
    video_rtp_port: i32,
    video_rtp_socket: Option<Arc<UdpSocket>>,
    video_rtcp_socket: Option<Arc<UdpSocket>>,
    video_remote_port: i32,
    /// FIR sequence counter, incremented per request_keyframe().
    fir_seq_nr: u8,

    on_ended_fn: Vec<Arc<dyn Fn(EndReason) + Send + Sync>>,
    on_ended_internal: Option<Arc<dyn Fn(EndReason) + Send + Sync>>,
    on_media_fn: Vec<Arc<dyn Fn() + Send + Sync>>,
    on_state_fn: Vec<Arc<dyn Fn(CallState) + Send + Sync>>,
    on_state_internal: Option<Arc<dyn Fn(CallState) + Send + Sync>>,
    on_dtmf_fn: Vec<Arc<dyn Fn(String) + Send + Sync>>,
    on_dtmf_internal: Option<Arc<dyn Fn(String) + Send + Sync>>,
    on_hold_fn: Vec<Arc<dyn Fn() + Send + Sync>>,
    on_resume_fn: Vec<Arc<dyn Fn() + Send + Sync>>,
    on_mute_fn: Vec<Arc<dyn Fn() + Send + Sync>>,
    on_unmute_fn: Vec<Arc<dyn Fn() + Send + Sync>>,
    on_video_fn: Vec<Arc<dyn Fn() + Send + Sync>>,
    on_video_request_fn: Option<Arc<dyn Fn(VideoUpgradeRequest) + Send + Sync>>,

    session_timer: Option<std::thread::JoinHandle<()>>,
    session_timer_cancel: Option<Arc<std::sync::atomic::AtomicBool>>,
}

/// Manages a single SIP call lifecycle including state transitions, media, and callbacks.
///
/// Created via [`Call::new_inbound`] or [`Call::new_outbound`] and returned as `Arc<Call>`.
pub struct Call {
    inner: Mutex<CallInner>,
    pub(crate) dlg: Arc<dyn Dialog>,
}

impl Call {
    /// Creates a new inbound call in the `Ringing` state.
    pub fn new_inbound(dlg: Arc<dyn Dialog>) -> Arc<Self> {
        Arc::new(Call {
            inner: Mutex::new(CallInner {
                id: new_call_id(),
                state: CallState::Ringing,
                direction: Direction::Inbound,
                opts: DialOptions::default(),
                start_time: None,
                muted: false,
                codec_prefs: Vec::new(),
                local_ip: String::new(),
                rtp_port: 0,
                remote_ip: String::new(),
                remote_port: 0,
                local_sdp: String::new(),
                remote_sdp: String::new(),
                codec: Codec::PCMU,
                media_active: false,
                dtmf_mode: crate::config::DtmfMode::Rfc4733,
                srtp_enabled: false,
                srtp_local_key: String::new(),
                srtp_remote_key: String::new(),
                rtp_socket: None,
                media_streams: Vec::new(),
                media_shared: None,
                video_muted: false,
                video_codec: None,
                video_rtp_port: 0,
                video_rtp_socket: None,
                video_rtcp_socket: None,
                video_remote_port: 0,
                fir_seq_nr: 0,
                on_ended_fn: Vec::new(),
                on_ended_internal: None,
                on_media_fn: Vec::new(),
                on_state_fn: Vec::new(),
                on_state_internal: None,
                on_dtmf_fn: Vec::new(),
                on_dtmf_internal: None,
                on_hold_fn: Vec::new(),
                on_resume_fn: Vec::new(),
                on_mute_fn: Vec::new(),
                on_unmute_fn: Vec::new(),
                on_video_fn: Vec::new(),
                on_video_request_fn: None,
                session_timer: None,
                session_timer_cancel: None,
            }),
            dlg,
        })
    }

    /// Creates a new outbound call in the `Dialing` state with the given dial options.
    pub fn new_outbound(dlg: Arc<dyn Dialog>, opts: DialOptions) -> Arc<Self> {
        Arc::new(Call {
            inner: Mutex::new(CallInner {
                id: new_call_id(),
                state: CallState::Dialing,
                direction: Direction::Outbound,
                opts,
                start_time: None,
                muted: false,
                codec_prefs: Vec::new(),
                local_ip: String::new(),
                rtp_port: 0,
                remote_ip: String::new(),
                remote_port: 0,
                local_sdp: String::new(),
                remote_sdp: String::new(),
                codec: Codec::PCMU,
                media_active: false,
                dtmf_mode: crate::config::DtmfMode::Rfc4733,
                srtp_enabled: false,
                srtp_local_key: String::new(),
                srtp_remote_key: String::new(),
                rtp_socket: None,
                media_streams: Vec::new(),
                media_shared: None,
                video_muted: false,
                video_codec: None,
                video_rtp_port: 0,
                video_rtp_socket: None,
                video_rtcp_socket: None,
                video_remote_port: 0,
                fir_seq_nr: 0,
                on_ended_fn: Vec::new(),
                on_ended_internal: None,
                on_media_fn: Vec::new(),
                on_state_fn: Vec::new(),
                on_state_internal: None,
                on_dtmf_fn: Vec::new(),
                on_dtmf_internal: None,
                on_hold_fn: Vec::new(),
                on_resume_fn: Vec::new(),
                on_mute_fn: Vec::new(),
                on_unmute_fn: Vec::new(),
                on_video_fn: Vec::new(),
                on_video_request_fn: None,
                session_timer: None,
                session_timer_cancel: None,
            }),
            dlg,
        })
    }

    // --- Getters ---

    /// Returns the unique internal call identifier.
    pub fn id(&self) -> String {
        self.inner.lock().id.clone()
    }

    /// Returns the SIP Call-ID header value from the underlying dialog.
    pub fn call_id(&self) -> String {
        self.dlg.call_id()
    }

    /// Returns the call direction (inbound or outbound).
    pub fn direction(&self) -> Direction {
        self.inner.lock().direction
    }

    /// Returns the current call state (e.g., Ringing, Active, OnHold, Ended).
    pub fn state(&self) -> CallState {
        self.inner.lock().state
    }

    /// Returns the negotiated audio codec for this call.
    pub fn codec(&self) -> Codec {
        self.inner.lock().codec
    }

    /// Returns the local SDP offer or answer for this call.
    pub fn local_sdp(&self) -> String {
        self.inner.lock().local_sdp.clone()
    }

    /// Returns the remote SDP received from the far end.
    pub fn remote_sdp(&self) -> String {
        self.inner.lock().remote_sdp.clone()
    }

    /// Returns the instant the call became active, or `None` if not yet answered.
    pub fn start_time(&self) -> Option<Instant> {
        self.inner.lock().start_time
    }

    /// Returns the elapsed duration since the call became active, or zero if not yet answered.
    pub fn duration(&self) -> Duration {
        let inner = self.inner.lock();
        match inner.start_time {
            Some(t) => t.elapsed(),
            None => Duration::ZERO,
        }
    }

    /// Returns the full SIP URI of the remote party (e.g., `sip:user@host`).
    pub fn remote_uri(&self) -> String {
        let vals = self.dlg.header("From");
        vals.first()
            .map(|v| sip_header_uri(v).to_string())
            .unwrap_or_default()
    }

    /// Returns the dialog identifiers needed for attended transfer:
    /// `(call_id, local_tag, remote_tag)`.
    pub fn dialog_id(&self) -> (String, String, String) {
        let call_id = self.dlg.call_id();
        let direction = self.inner.lock().direction;

        let from_tag = self
            .dlg
            .header("From")
            .first()
            .map(|v| sip_header_tag(v).to_string())
            .unwrap_or_default();
        let to_tag = self
            .dlg
            .header("To")
            .first()
            .map(|v| sip_header_tag(v).to_string())
            .unwrap_or_default();

        match direction {
            Direction::Outbound => (call_id, from_tag, to_tag),
            Direction::Inbound => (call_id, to_tag, from_tag),
        }
    }

    /// Returns the user part of the SIP From header (e.g., `+15551234567`).
    pub fn from(&self) -> String {
        let vals = self.dlg.header("From");
        vals.first()
            .map(|v| sip_header_user(v).to_string())
            .unwrap_or_default()
    }

    /// Returns the remote party's DID/extension.
    /// For inbound calls this is the From user; for outbound calls it's the To user.
    pub fn remote_did(&self) -> String {
        match self.direction() {
            Direction::Inbound => self.from(),
            Direction::Outbound => self.to(),
        }
    }

    /// Returns the user part of the SIP To header.
    pub fn to(&self) -> String {
        let vals = self.dlg.header("To");
        vals.first()
            .map(|v| sip_header_user(v).to_string())
            .unwrap_or_default()
    }

    /// Returns the display name from the SIP From header (e.g., `Alice`).
    pub fn from_name(&self) -> String {
        let vals = self.dlg.header("From");
        vals.first()
            .map(|v| sip_header_display_name(v).to_string())
            .unwrap_or_default()
    }

    /// Returns the remote media IP address, parsed from the remote SDP.
    pub fn remote_ip(&self) -> String {
        let inner = self.inner.lock();
        if !inner.remote_ip.is_empty() {
            return inner.remote_ip.clone();
        }
        if inner.remote_sdp.is_empty() {
            return String::new();
        }
        sdp::parse(&inner.remote_sdp)
            .map(|s| s.connection.clone())
            .unwrap_or_default()
    }

    /// Returns the remote RTP port, parsed from the remote SDP.
    pub fn remote_port(&self) -> i32 {
        let inner = self.inner.lock();
        if inner.remote_port != 0 {
            return inner.remote_port;
        }
        if inner.remote_sdp.is_empty() {
            return 0;
        }
        sdp::parse(&inner.remote_sdp)
            .map(|s| s.media.first().map(|m| m.port).unwrap_or(0))
            .unwrap_or(0)
    }

    /// Returns the values of a specific SIP header by name.
    pub fn header(&self, name: &str) -> Vec<String> {
        self.dlg.header(name)
    }

    /// Returns all SIP headers from the underlying dialog.
    pub fn headers(&self) -> HashMap<String, Vec<String>> {
        self.dlg.headers()
    }

    /// Returns whether the media session is currently active.
    pub fn media_session_active(&self) -> bool {
        self.inner.lock().media_active
    }

    // --- Codec helpers ---

    fn resolve_codec_prefs(inner: &CallInner) -> &[i32] {
        if !inner.codec_prefs.is_empty() {
            &inner.codec_prefs
        } else {
            DEFAULT_CODEC_PREFS
        }
    }

    fn build_local_sdp(inner: &mut CallInner, direction: &str) -> String {
        if inner.local_ip.is_empty() {
            inner.local_ip = "127.0.0.1".into();
        }
        let prefs = Self::resolve_codec_prefs(inner);
        if inner.srtp_enabled && !inner.srtp_local_key.is_empty() {
            sdp::build_offer_srtp(
                &inner.local_ip,
                inner.rtp_port,
                prefs,
                direction,
                &inner.srtp_local_key,
            )
        } else {
            sdp::build_offer(&inner.local_ip, inner.rtp_port, prefs, direction)
        }
    }

    fn build_answer_sdp(inner: &mut CallInner, remote: &sdp::Session, direction: &str) -> String {
        if inner.local_ip.is_empty() {
            inner.local_ip = "127.0.0.1".into();
        }
        let remote_codecs: &[i32] = remote
            .media
            .first()
            .map(|m| m.codecs.as_slice())
            .unwrap_or(&[]);
        let prefs = Self::resolve_codec_prefs(inner);

        // If remote offers video and we have a video socket, build audio+video answer.
        if remote.has_video() && inner.video_rtp_socket.is_some() {
            let empty_rtpmap: Vec<(i32, String)> = Vec::new();
            let remote_video_rtpmap = remote
                .video_media()
                .map(|vm| vm.rtpmap.as_slice())
                .unwrap_or(&empty_rtpmap);
            let local_video = &[VideoCodec::H264, VideoCodec::VP8];
            return sdp::build_answer_video(
                &inner.local_ip,
                inner.rtp_port,
                prefs,
                remote_codecs,
                inner.video_rtp_port,
                local_video,
                remote_video_rtpmap,
                direction,
            );
        }

        if inner.srtp_enabled && !inner.srtp_local_key.is_empty() {
            sdp::build_answer_srtp(
                &inner.local_ip,
                inner.rtp_port,
                prefs,
                remote_codecs,
                direction,
                &inner.srtp_local_key,
            )
        } else {
            sdp::build_answer(
                &inner.local_ip,
                inner.rtp_port,
                prefs,
                remote_codecs,
                direction,
            )
        }
    }

    fn negotiate_codec(inner: &mut CallInner, sess: &sdp::Session) {
        // Audio codec negotiation.
        let remote_codecs: &[i32] = sess
            .audio_media()
            .map(|m| m.codecs.as_slice())
            .unwrap_or(&[]);
        let prefs = Self::resolve_codec_prefs(inner);
        let pt = sdp::negotiate_codec(prefs, remote_codecs);
        if pt >= 0 {
            if let Some(c) = Codec::from_payload_type(pt) {
                inner.codec = c;
            }
        }
        // Video codec negotiation (skip if remote rejected video with port 0).
        if let Some(vm) = sess.video_media() {
            if vm.port > 0 {
                if let Some(vc) = sess.video_codec() {
                    inner.video_codec = Some(vc);
                }
            }
        }
    }

    fn set_remote_endpoint(inner: &mut CallInner, sess: &sdp::Session) {
        inner.remote_ip = sess.connection.clone();
        if let Some(m) = sess.audio_media() {
            inner.remote_port = m.port;
        }
        if let Some(vm) = sess.video_media() {
            if vm.port > 0 {
                inner.video_remote_port = vm.port;
            }
        }
    }

    // --- Callback dispatch (copy fn under lock, fire outside) ---

    fn fire_on_state(inner: &CallInner, state: CallState) {
        if let Some(ref f) = inner.on_state_internal {
            let f = Arc::clone(f);
            spawn_callback(move || f(state));
        }
        for f in &inner.on_state_fn {
            let f = Arc::clone(f);
            spawn_callback(move || f(state));
        }
    }

    fn fire_on_ended(inner: &mut CallInner, reason: EndReason) {
        // Cancel session timer — thread will exit on next iteration.
        // Cannot join here (holds inner lock, timer thread also locks inner).
        if let Some(ref cancel) = inner.session_timer_cancel {
            cancel.store(true, std::sync::atomic::Ordering::Relaxed);
        }
        if let Some(ref f) = inner.on_ended_internal {
            let f = Arc::clone(f);
            spawn_callback(move || f(reason));
        }
        for f in &inner.on_ended_fn {
            let f = Arc::clone(f);
            spawn_callback(move || f(reason));
        }
        // Clear all callbacks to break circular Arc references (Call → callback → Arc<Call>).
        // Without this, the Call can never be dropped because the callbacks captured Arc<Call>.
        inner.on_ended_internal = None;
        inner.on_ended_fn.clear();
        inner.on_state_internal = None;
        inner.on_state_fn.clear();
        inner.on_dtmf_internal = None;
        inner.on_dtmf_fn.clear();
        inner.on_media_fn.clear();
        inner.on_hold_fn.clear();
        inner.on_resume_fn.clear();
        inner.on_mute_fn.clear();
        inner.on_unmute_fn.clear();
        inner.on_video_fn.clear();
        inner.on_video_request_fn = None;
    }

    // --- Session timer ---

    fn start_session_timer(self: &Arc<Self>) {
        let vals = self.dlg.header("Session-Expires");
        if vals.is_empty() {
            return;
        }
        // Handle parameters like "1800;refresher=uac" by taking text before ';'.
        let raw = vals[0].split(';').next().unwrap_or("").trim();
        let seconds: u64 = match raw.parse() {
            Ok(s) if s > 0 => s,
            _ => return,
        };
        let interval = Duration::from_secs(seconds) / 2;
        let cancel = Arc::new(std::sync::atomic::AtomicBool::new(false));
        let cancel_clone = Arc::clone(&cancel);
        let call = Arc::clone(self);
        let handle = std::thread::spawn(move || loop {
            std::thread::sleep(interval);
            if cancel_clone.load(std::sync::atomic::Ordering::Relaxed) {
                return;
            }
            let refresh_sdp = {
                let mut inner = call.inner.lock();
                if inner.state == CallState::Ended {
                    return;
                }
                Self::build_local_sdp(&mut inner, sdp::DIR_SEND_RECV)
            };
            let _ = call.dlg.send_reinvite(refresh_sdp.as_bytes());
        });
        let mut inner = self.inner.lock();
        inner.session_timer = Some(handle);
        inner.session_timer_cancel = Some(cancel);
    }

    // --- Actions ---

    /// Accepts an inbound call, transitioning from `Ringing` to `Active`.
    ///
    /// Sends a 200 OK with SDP, starts the media pipeline, and fires state/media callbacks.
    pub fn accept(self: &Arc<Self>) -> Result<()> {
        info!(call_id = %self.call_id(), "Call accepting");
        let on_media_fn;
        {
            let mut inner = self.inner.lock();
            if inner.state != CallState::Ringing {
                info!(state = ?inner.state, "Call accept rejected — not in Ringing state");
                return Err(Error::InvalidState);
            }

            if !inner.remote_sdp.is_empty() {
                if let Ok(sess) = sdp::parse(&inner.remote_sdp) {
                    Self::negotiate_codec(&mut inner, &sess);
                    inner.local_sdp = Self::build_answer_sdp(&mut inner, &sess, sdp::DIR_SEND_RECV);
                    Self::set_remote_endpoint(&mut inner, &sess);
                } else {
                    inner.local_sdp = Self::build_local_sdp(&mut inner, sdp::DIR_SEND_RECV);
                }
            } else {
                inner.local_sdp = Self::build_local_sdp(&mut inner, sdp::DIR_SEND_RECV);
            }

            let _ = self.dlg.respond(200, "OK", inner.local_sdp.as_bytes());
            inner.state = CallState::Active;
            inner.start_time = Some(Instant::now());
            inner.media_active = true;
            Self::start_media_pipeline(&mut inner);
            Self::fire_on_state(&inner, CallState::Active);
            on_media_fn = inner.on_media_fn.clone();
        }

        self.start_session_timer();

        for f in on_media_fn {
            spawn_callback(move || f());
        }
        Ok(())
    }

    /// Rejects an inbound call with the given SIP response code and reason.
    pub fn reject(&self, code: u16, reason: &str) -> Result<()> {
        let mut inner = self.inner.lock();
        if inner.state != CallState::Ringing {
            return Err(Error::InvalidState);
        }
        let _ = self.dlg.respond(code, reason, &[]);
        inner.state = CallState::Ended;
        Self::fire_on_state(&inner, CallState::Ended);
        Self::fire_on_ended(&mut inner, EndReason::Rejected);
        Ok(())
    }

    /// Ends the call. Sends CANCEL if dialing, or BYE if active/on-hold.
    pub fn end(&self) -> Result<()> {
        let mut inner = self.inner.lock();
        if let Some(ref cancel) = inner.session_timer_cancel {
            cancel.store(true, std::sync::atomic::Ordering::Relaxed);
        }
        match inner.state {
            CallState::Dialing | CallState::RemoteRinging | CallState::EarlyMedia => {
                let _ = self.dlg.send_cancel();
                inner.state = CallState::Ended;
                for s in &mut inner.media_streams {
                    s.stop();
                }
                Self::fire_on_state(&inner, CallState::Ended);
                Self::fire_on_ended(&mut inner, EndReason::Cancelled);
                Ok(())
            }
            CallState::Active | CallState::OnHold => {
                let _ = self.dlg.send_bye();
                inner.state = CallState::Ended;
                for s in &mut inner.media_streams {
                    s.stop();
                }
                Self::fire_on_state(&inner, CallState::Ended);
                Self::fire_on_ended(&mut inner, EndReason::Local);
                Ok(())
            }
            _ => Err(Error::InvalidState),
        }
    }

    /// Places the call on hold by sending a re-INVITE with `sendonly` SDP.
    pub fn hold(&self) -> Result<()> {
        let mut inner = self.inner.lock();
        if inner.state != CallState::Active {
            return Err(Error::InvalidState);
        }
        inner.local_sdp = Self::build_local_sdp(&mut inner, sdp::DIR_SEND_ONLY);
        let _ = self.dlg.send_reinvite(inner.local_sdp.as_bytes());
        inner.state = CallState::OnHold;
        Self::fire_on_state(&inner, CallState::OnHold);
        Ok(())
    }

    /// Resumes a held call by sending a re-INVITE with `sendrecv` SDP.
    pub fn resume(&self) -> Result<()> {
        let mut inner = self.inner.lock();
        if inner.state != CallState::OnHold {
            return Err(Error::InvalidState);
        }
        inner.local_sdp = Self::build_local_sdp(&mut inner, sdp::DIR_SEND_RECV);
        let _ = self.dlg.send_reinvite(inner.local_sdp.as_bytes());
        inner.state = CallState::Active;
        Self::fire_on_state(&inner, CallState::Active);
        Ok(())
    }

    /// Mutes the local audio. Returns an error if already muted or not active.
    pub fn mute(&self) -> Result<()> {
        let on_mute;
        {
            let mut inner = self.inner.lock();
            if inner.state != CallState::Active {
                return Err(Error::InvalidState);
            }
            if inner.muted {
                return Err(Error::AlreadyMuted);
            }
            inner.muted = true;
            for s in &inner.media_streams {
                s.muted.store(true, std::sync::atomic::Ordering::Relaxed);
            }
            on_mute = inner.on_mute_fn.clone();
        }
        for f in on_mute {
            spawn_callback(move || f());
        }
        Ok(())
    }

    /// Unmutes the local audio. Returns an error if not muted or not active.
    pub fn unmute(&self) -> Result<()> {
        let on_unmute;
        {
            let mut inner = self.inner.lock();
            if inner.state != CallState::Active {
                return Err(Error::InvalidState);
            }
            if !inner.muted {
                return Err(Error::NotMuted);
            }
            inner.muted = false;
            for s in &inner.media_streams {
                s.muted.store(false, std::sync::atomic::Ordering::Relaxed);
            }
            on_unmute = inner.on_unmute_fn.clone();
        }
        for f in on_unmute {
            spawn_callback(move || f());
        }
        Ok(())
    }

    /// Mutes only the audio stream. Returns an error if already muted or not active.
    pub fn mute_audio(&self) -> Result<()> {
        let on_mute;
        {
            let mut inner = self.inner.lock();
            if inner.state != CallState::Active {
                return Err(Error::InvalidState);
            }
            if inner.muted {
                return Err(Error::AlreadyMuted);
            }
            inner.muted = true;
            if let Some(s) = inner.media_streams.first() {
                s.muted.store(true, std::sync::atomic::Ordering::Relaxed);
            }
            on_mute = inner.on_mute_fn.clone();
        }
        for f in on_mute {
            spawn_callback(move || f());
        }
        Ok(())
    }

    /// Unmutes only the audio stream. Returns an error if not muted or not active.
    pub fn unmute_audio(&self) -> Result<()> {
        let on_unmute;
        {
            let mut inner = self.inner.lock();
            if inner.state != CallState::Active {
                return Err(Error::InvalidState);
            }
            if !inner.muted {
                return Err(Error::NotMuted);
            }
            inner.muted = false;
            if let Some(s) = inner.media_streams.first() {
                s.muted.store(false, std::sync::atomic::Ordering::Relaxed);
            }
            on_unmute = inner.on_unmute_fn.clone();
        }
        for f in on_unmute {
            spawn_callback(move || f());
        }
        Ok(())
    }

    /// Sends a re-INVITE to add video to an existing audio call.
    ///
    /// Allocates a video RTP socket, builds an audio+video SDP offer, and sends
    /// a re-INVITE. The remote party's response will negotiate the video codec
    /// and start the video pipeline (handled via the re-INVITE response path).
    pub fn add_video(
        &self,
        video_codecs: &[VideoCodec],
        rtp_port_min: u16,
        rtp_port_max: u16,
    ) -> Result<()> {
        if video_codecs.is_empty() {
            return Err(Error::Other("no video codecs specified".into()));
        }

        // Allocate video socket outside the lock.
        let (vsock, vport) = crate::media::listen_rtp_port(rtp_port_min, rtp_port_max)
            .map_err(|e| Error::Other(format!("failed to allocate video port: {e}")))?;

        let local_sdp;
        {
            let mut inner = self.inner.lock();
            if inner.state != CallState::Active {
                return Err(Error::InvalidState);
            }
            if inner.video_codec.is_some() {
                return Err(Error::Other("video already active".into()));
            }

            inner.video_rtp_port = vport as i32;
            inner.video_rtp_socket = Some(Arc::new(vsock));

            if inner.local_ip.is_empty() {
                inner.local_ip = "127.0.0.1".into();
            }
            let prefs = Self::resolve_codec_prefs(&inner);
            inner.local_sdp = sdp::build_offer_video(
                &inner.local_ip,
                inner.rtp_port,
                prefs,
                inner.video_rtp_port,
                video_codecs,
                sdp::DIR_SEND_RECV,
            );
            local_sdp = inner.local_sdp.clone();
        }

        // Send re-INVITE with video SDP (outside the lock — network I/O).
        self.dlg.send_reinvite(local_sdp.as_bytes())
    }

    /// Returns true if this call has a negotiated video stream.
    pub fn has_video(&self) -> bool {
        self.inner.lock().video_codec.is_some()
    }

    /// Returns the negotiated video codec, if any.
    pub fn video_codec(&self) -> Option<VideoCodec> {
        self.inner.lock().video_codec
    }

    /// Mutes the video stream. Returns an error if already muted or not active.
    pub fn mute_video(&self) -> Result<()> {
        let mut inner = self.inner.lock();
        if inner.state != CallState::Active {
            return Err(Error::InvalidState);
        }
        if inner.video_codec.is_none() {
            return Err(Error::NoVideoStream);
        }
        if inner.video_muted {
            return Err(Error::VideoAlreadyMuted);
        }
        inner.video_muted = true;
        if let Some(s) = inner.media_streams.get(1) {
            s.muted.store(true, std::sync::atomic::Ordering::Relaxed);
        }
        Ok(())
    }

    /// Unmutes the video stream. Returns an error if not muted or not active.
    pub fn unmute_video(&self) -> Result<()> {
        let mut inner = self.inner.lock();
        if inner.state != CallState::Active {
            return Err(Error::InvalidState);
        }
        if inner.video_codec.is_none() {
            return Err(Error::NoVideoStream);
        }
        if !inner.video_muted {
            return Err(Error::VideoNotMuted);
        }
        inner.video_muted = false;
        if let Some(s) = inner.media_streams.get(1) {
            s.muted.store(false, std::sync::atomic::Ordering::Relaxed);
        }
        Ok(())
    }

    /// Sends an RTCP PLI (Picture Loss Indication) to request a keyframe from
    /// the remote video sender (RFC 4585).
    pub fn request_keyframe(&self) -> Result<()> {
        let mut inner = self.inner.lock();
        if inner.state != CallState::Active {
            return Err(Error::InvalidState);
        }
        if inner.video_codec.is_none() {
            return Err(Error::NoVideoStream);
        }
        // Reuse the video RTCP socket created by start_video_pipeline.
        let rtcp_addr: Option<std::net::SocketAddr> = if inner.video_remote_port > 0 {
            format!("{}:{}", inner.remote_ip, inner.video_remote_port + 1)
                .parse()
                .ok()
        } else {
            None
        };
        if let (Some(ref sock), Some(addr)) = (&inner.video_rtcp_socket, rtcp_addr) {
            let local_ssrc = 0; // We don't track our video SSRC here; 0 is acceptable.
            let remote_ssrc = 0; // Will be populated from first inbound video RTP.
                                 // Send PLI.
            let pli = crate::rtcp::build_pli(local_ssrc, remote_ssrc);
            let _ = sock.send_to(&pli, addr);
            // Also send FIR as a fallback.
            let fir = crate::rtcp::build_fir(local_ssrc, remote_ssrc, inner.fir_seq_nr);
            let _ = sock.send_to(&fir, addr);
            inner.fir_seq_nr = inner.fir_seq_nr.wrapping_add(1);
        }
        Ok(())
    }

    /// Returns the raw video RTP reader (post-jitter, but video has no jitter buffer).
    pub fn video_rtp_reader(&self) -> Option<crossbeam_channel::Receiver<RtpPacket>> {
        self.inner
            .lock()
            .media_streams
            .get(1)
            .map(|s| s.channels.rtp_reader.rx.clone())
    }

    /// Returns the raw video RTP writer (for sending encoded video RTP).
    pub fn video_rtp_writer(&self) -> Option<crossbeam_channel::Sender<RtpPacket>> {
        self.inner
            .lock()
            .media_streams
            .get(1)
            .map(|s| s.channels.rtp_writer.tx.clone())
    }

    /// Returns the assembled video frame reader (depacketized from inbound RTP).
    pub fn video_reader(&self) -> Option<crossbeam_channel::Receiver<VideoFrame>> {
        self.inner
            .lock()
            .media_streams
            .get(1)
            .map(|s| s.channels.video_frame_reader.rx.clone())
    }

    /// Returns the assembled video frame writer (packetized into outbound RTP).
    pub fn video_writer(&self) -> Option<crossbeam_channel::Sender<VideoFrame>> {
        self.inner
            .lock()
            .media_streams
            .get(1)
            .map(|s| s.channels.video_frame_writer.tx.clone())
    }

    /// Sets the video RTP port (called during call setup).
    pub(crate) fn set_video_rtp_port(&self, port: i32) {
        self.inner.lock().video_rtp_port = port;
    }

    /// Sets the video RTP socket (called during call setup).
    pub(crate) fn set_video_rtp_socket(&self, socket: UdpSocket) {
        self.inner.lock().video_rtp_socket = Some(Arc::new(socket));
    }

    /// Sets the negotiated video codec (test helper — production path uses negotiate_codec).
    #[cfg(test)]
    pub(crate) fn set_video_codec(&self, codec: VideoCodec) {
        self.inner.lock().video_codec = Some(codec);
    }

    /// Sends a DTMF digit (e.g., `"1"`, `"#"`, `"*"`).
    ///
    /// The transport method depends on the configured [`DtmfMode`](crate::config::DtmfMode):
    /// - `Rfc4733` — RTP telephone-event packets (default)
    /// - `SipInfo` — SIP INFO with `application/dtmf-relay` body
    /// - `Both` — sends via RFC 4733
    pub fn send_dtmf(&self, digit: &str) -> Result<()> {
        let (rtp_socket, remote_ip, remote_port, dtmf_mode) = {
            let inner = self.inner.lock();
            if inner.state != CallState::Active {
                return Err(Error::InvalidState);
            }
            (
                inner.rtp_socket.clone(),
                inner.remote_ip.clone(),
                inner.remote_port,
                inner.dtmf_mode,
            )
        };
        if dtmf::digit_to_code(digit).is_none() {
            return Err(Error::InvalidDtmfDigit);
        }
        match dtmf_mode {
            crate::config::DtmfMode::SipInfo => {
                self.dlg.send_info_dtmf(digit, 160)?;
            }
            crate::config::DtmfMode::Rfc4733 | crate::config::DtmfMode::Both => {
                let pkts = dtmf::encode_dtmf(digit, 0, 0, 0)?;
                if let Some(sock) = rtp_socket {
                    if !remote_ip.is_empty() && remote_port > 0 {
                        if let Ok(addr) =
                            format!("{}:{}", remote_ip, remote_port).parse::<std::net::SocketAddr>()
                        {
                            for pkt in &pkts {
                                let _ = sock.send_to(&pkt.to_bytes(), addr);
                            }
                        }
                    }
                }
            }
        }
        Ok(())
    }

    /// Initiates a blind (unattended) transfer to the given SIP target URI.
    pub fn blind_transfer(self: &Arc<Self>, target: &str) -> Result<()> {
        {
            let inner = self.inner.lock();
            if inner.state != CallState::Active && inner.state != CallState::OnHold {
                return Err(Error::InvalidState);
            }
        }
        let weak = Arc::downgrade(self);
        self.dlg.on_notify(Box::new(move |code| {
            let reason = if (200..300).contains(&code) {
                EndReason::Transfer
            } else if code >= 300 {
                EndReason::TransferFailed
            } else {
                // 1xx provisional — transfer in progress, don't end the call yet.
                return;
            };
            let Some(call) = weak.upgrade() else {
                return;
            };
            let mut inner = call.inner.lock();
            if inner.state == CallState::Ended {
                return;
            }
            inner.state = CallState::Ended;
            Self::fire_on_state(&inner, CallState::Ended);
            Self::fire_on_ended(&mut inner, reason);
        }));
        self.dlg.send_refer(target)?;
        Ok(())
    }

    /// Performs an attended transfer (REFER with Replaces).
    ///
    /// Sends a REFER on this call's dialog with `other`'s dialog identifiers
    /// in the Replaces header (RFC 3891). On success (2xx NOTIFY), both calls
    /// end with `EndReason::Transfer`. On failure (3xx+ NOTIFY), both calls
    /// end with `EndReason::TransferFailed`.
    ///
    /// Works for any call regardless of whether it was created by `Phone` or `Server`.
    pub fn attended_transfer(self: &Arc<Self>, other: &Arc<Call>) -> Result<()> {
        {
            let state_self = self.state();
            if state_self != CallState::Active && state_self != CallState::OnHold {
                return Err(Error::InvalidState);
            }
            let state_other = other.state();
            if state_other != CallState::Active && state_other != CallState::OnHold {
                return Err(Error::InvalidState);
            }
        }

        // Extract other call's dialog identifiers for the Replaces header.
        let (b_call_id, b_local_tag, b_remote_tag) = other.dialog_id();
        if b_call_id.is_empty() || b_local_tag.is_empty() || b_remote_tag.is_empty() {
            return Err(Error::Other(
                "attended transfer: other call dialog missing call-id or tags".into(),
            ));
        }

        // Build the remote party's SIP URI from the other call.
        let remote_uri = match other.direction() {
            Direction::Outbound => other
                .header("To")
                .first()
                .map(|v| sip_header_uri(v).to_string())
                .unwrap_or_default(),
            Direction::Inbound => other
                .header("From")
                .first()
                .map(|v| sip_header_uri(v).to_string())
                .unwrap_or_default(),
        };
        if remote_uri.is_empty() {
            return Err(Error::Other(
                "attended transfer: cannot determine other call remote URI".into(),
            ));
        }

        // Build Refer-To URI with Replaces parameter (URL-encoded per RFC 3891).
        let refer_to = format!(
            "{}?Replaces={}%3Bto-tag%3D{}%3Bfrom-tag%3D{}",
            remote_uri,
            uri_encode(&b_call_id),
            uri_encode(&b_remote_tag),
            uri_encode(&b_local_tag),
        );

        // Wire up NOTIFY handler: on 2xx, end both calls with Transfer reason.
        // On 3xx+, end both with TransferFailed. Ignore 1xx provisionals.
        let weak_self = Arc::downgrade(self);
        let weak_other = Arc::downgrade(other);
        self.dlg.on_notify(Box::new(move |code| {
            let reason = if (200..300).contains(&code) {
                EndReason::Transfer
            } else if code >= 300 {
                EndReason::TransferFailed
            } else {
                return;
            };
            if let Some(a) = weak_self.upgrade() {
                a.end_with_reason(reason);
            }
            if let Some(b) = weak_other.upgrade() {
                b.end_with_reason(reason);
            }
        }));

        self.dlg.send_refer(&refer_to)?;
        Ok(())
    }

    /// Ends the call with a specific reason. Sends BYE if active/on-hold.
    /// Used by attended transfer to end both legs with `EndReason::Transfer`.
    pub(crate) fn end_with_reason(&self, reason: EndReason) {
        let mut inner = self.inner.lock();
        if inner.state == CallState::Ended {
            return;
        }
        if let Some(ref cancel) = inner.session_timer_cancel {
            cancel.store(true, std::sync::atomic::Ordering::Relaxed);
        }
        if inner.state == CallState::Active || inner.state == CallState::OnHold {
            let _ = self.dlg.send_bye();
        }
        inner.state = CallState::Ended;
        for s in &mut inner.media_streams {
            s.stop();
        }
        Self::fire_on_state(&inner, CallState::Ended);
        Self::fire_on_ended(&mut inner, reason);
    }

    // --- Simulation methods (for tests and incoming SIP events) ---

    /// Simulates receiving a SIP response (180, 183, 200) to drive outbound call state transitions.
    pub fn simulate_response(self: &Arc<Self>, code: u16, _reason: &str) {
        let start_timer;
        {
            let mut inner = self.inner.lock();
            start_timer = match code {
                180 => {
                    if inner.state == CallState::Dialing {
                        inner.state = CallState::RemoteRinging;
                        Self::fire_on_state(&inner, CallState::RemoteRinging);
                    }
                    false
                }
                183 => {
                    if inner.opts.early_media
                        && (inner.state == CallState::Dialing
                            || inner.state == CallState::RemoteRinging)
                    {
                        inner.state = CallState::EarlyMedia;
                        inner.media_active = true;
                        Self::start_media_pipeline(&mut inner);
                        Self::fire_on_state(&inner, CallState::EarlyMedia);
                        for f in &inner.on_media_fn {
                            let f = Arc::clone(f);
                            spawn_callback(move || f());
                        }
                    }
                    false
                }
                200 => {
                    if inner.state == CallState::Dialing
                        || inner.state == CallState::RemoteRinging
                        || inner.state == CallState::EarlyMedia
                    {
                        inner.state = CallState::Active;
                        inner.start_time = Some(Instant::now());
                        inner.media_active = true;
                        Self::start_media_pipeline(&mut inner);
                        Self::fire_on_state(&inner, CallState::Active);
                        for f in &inner.on_media_fn {
                            let f = Arc::clone(f);
                            spawn_callback(move || f());
                        }
                        true
                    } else {
                        false
                    }
                }
                _ => false,
            };
        }
        if start_timer {
            self.start_session_timer();
        }
    }

    /// Simulates receiving a remote BYE, ending the call.
    pub fn simulate_bye(&self) {
        let mut inner = self.inner.lock();
        if inner.state == CallState::Ended {
            return;
        }
        // If the call was still ringing (not yet accepted), treat as Cancelled.
        let reason = if inner.state == CallState::Ringing {
            info!(call_id = %self.dlg.call_id(), state = ?inner.state, "Call cancelled by remote (BYE/CANCEL while ringing)");
            EndReason::Cancelled
        } else {
            info!(call_id = %self.dlg.call_id(), state = ?inner.state, "Call ended by remote BYE");
            EndReason::Remote
        };
        inner.state = CallState::Ended;
        for s in &mut inner.media_streams {
            s.stop();
        }
        Self::fire_on_state(&inner, CallState::Ended);
        Self::fire_on_ended(&mut inner, reason);
    }

    /// Fires the dialog's on_notify callback (REFER progress from the network).
    pub fn fire_notify(&self, code: u16) {
        self.dlg.fire_notify(code);
    }

    /// Fires DTMF callbacks for a digit received via SIP INFO (signaling path).
    pub fn fire_dtmf(&self, digit: &str) {
        let (f_int, f_usr) = {
            let inner = self.inner.lock();
            (inner.on_dtmf_internal.clone(), inner.on_dtmf_fn.clone())
        };
        let d = digit.to_string();
        if let Some(f) = f_int {
            f(d.clone());
        }
        for f in f_usr {
            f(d.clone());
        }
    }

    /// Simulates receiving a remote re-INVITE, handling hold/resume based on SDP direction.
    pub fn simulate_reinvite(&self, raw_sdp: &str) {
        let mut inner = self.inner.lock();
        if inner.state == CallState::Ended {
            return;
        }

        let sess = match sdp::parse(raw_sdp) {
            Ok(s) => s,
            Err(_) => return,
        };
        inner.remote_sdp = raw_sdp.to_string();
        Self::set_remote_endpoint(&mut inner, &sess);

        let dir = sess.dir();
        let mut hold_fn = Vec::new();
        let mut resume_fn = Vec::new();
        let mut new_state = None;

        let is_hold_dir =
            dir == sdp::DIR_SEND_ONLY || dir == sdp::DIR_RECV_ONLY || dir == sdp::DIR_INACTIVE;
        match (is_hold_dir, inner.state) {
            (true, CallState::Active) => {
                inner.state = CallState::OnHold;
                hold_fn = inner.on_hold_fn.clone();
                new_state = Some(CallState::OnHold);
            }
            (false, CallState::OnHold) if dir == sdp::DIR_SEND_RECV => {
                inner.state = CallState::Active;
                resume_fn = inner.on_resume_fn.clone();
                new_state = Some(CallState::Active);
            }
            _ => {}
        }

        Self::negotiate_codec(&mut inner, &sess);

        if let Some(s) = new_state {
            Self::fire_on_state(&inner, s);
        }
        drop(inner);

        for f in hold_fn {
            spawn_callback(move || f());
        }
        for f in resume_fn {
            spawn_callback(move || f());
        }
    }

    /// Handles a mid-dialog re-INVITE (video upgrade, video downgrade, or hold/resume).
    ///
    /// - **Video upgrade** (remote adds video): fires `on_video_request` callback with a
    ///   [`VideoUpgradeRequest`] the app must accept or reject. If no callback is registered,
    ///   the upgrade is automatically rejected (safe default — no video without consent).
    /// - **Video downgrade** (remote removes video, port 0): stops the video pipeline.
    /// - **Hold/resume** (audio-only): delegates to `simulate_reinvite`.
    pub(crate) fn handle_reinvite(
        self: &Arc<Self>,
        reinvite_dlg: &Arc<dyn Dialog>,
        remote_sdp: &str,
        rtp_port_min: u16,
        rtp_port_max: u16,
    ) {
        let sess = match sdp::parse(remote_sdp) {
            Ok(s) => s,
            Err(e) => {
                tracing::warn!("failed to parse re-INVITE SDP: {}", e);
                return;
            }
        };

        // Check for video downgrade (m=video 0).
        if let Some(vm) = sess.video_media() {
            if vm.port == 0 && self.has_video() {
                info!(call_id = %self.call_id(), "Video downgrade via re-INVITE");
                self.stop_video_pipeline();
                // Respond with matching audio-only SDP + m=video 0.
                self.reject_video_internal(reinvite_dlg, &sess, remote_sdp);
                return;
            }
        }

        if !sess.has_video() {
            // Audio-only re-INVITE — delegate to hold/resume handling.
            self.simulate_reinvite_parsed(&sess, remote_sdp);
            return;
        }

        // Video upgrade request — check if app registered a handler.
        let (request_fn, need_socket) = {
            let inner = self.inner.lock();
            if inner.state == CallState::Ended {
                return;
            }
            (
                inner.on_video_request_fn.clone(),
                inner.video_rtp_socket.is_none(),
            )
        };

        // Pre-allocate video RTP socket outside the lock (blocking I/O).
        let video_socket = if need_socket {
            match crate::media::listen_rtp_port(rtp_port_min, rtp_port_max) {
                Ok((vsock, vport)) => Some((vsock, vport)),
                Err(e) => {
                    tracing::error!("failed to allocate video RTP socket: {}", e);
                    return;
                }
            }
        } else {
            None
        };

        let request = VideoUpgradeRequest {
            call: Arc::clone(self),
            reinvite_dlg: Arc::clone(reinvite_dlg),
            remote_sdp: remote_sdp.to_string(),
            sess,
            video_socket,
            responded: Arc::new(AtomicBool::new(false)),
        };

        if let Some(f) = request_fn {
            // App decides whether to accept or reject.
            spawn_callback(move || f(request));
        } else {
            // No handler — auto-reject (safe default).
            info!(call_id = %self.call_id(), "No on_video_request handler — rejecting video upgrade");
            request.reject();
        }
    }

    /// Internal: accepts a video upgrade (called by VideoUpgradeRequest::accept).
    fn accept_video_internal(
        &self,
        reinvite_dlg: &Arc<dyn Dialog>,
        sess: &sdp::Session,
        remote_sdp: &str,
        video_socket: &Option<(UdpSocket, u16)>,
    ) {
        let local_sdp;
        {
            let mut inner = self.inner.lock();
            if inner.state == CallState::Ended {
                return;
            }

            // Install pre-allocated video socket.
            if let Some((ref vsock, vport)) = *video_socket {
                match vsock.try_clone() {
                    Ok(cloned) => {
                        inner.video_rtp_port = vport as i32;
                        inner.video_rtp_socket = Some(Arc::new(cloned));
                    }
                    Err(e) => {
                        tracing::error!("failed to clone video socket: {}", e);
                        return;
                    }
                }
            }

            // Update remote SDP and endpoint.
            inner.remote_sdp = remote_sdp.to_string();
            Self::set_remote_endpoint(&mut inner, sess);
            Self::negotiate_codec(&mut inner, sess);

            // Build SDP answer with video.
            inner.local_sdp = Self::build_answer_sdp(&mut inner, sess, sdp::DIR_SEND_RECV);
            local_sdp = inner.local_sdp.clone();

            // Start the video media pipeline (fires on_video callback internally).
            Self::start_video_pipeline(&mut inner);
        }

        // Send 200 OK via the re-INVITE dialog (outside the lock — network I/O).
        if let Err(e) = reinvite_dlg.respond(200, "OK", local_sdp.as_bytes()) {
            tracing::error!("failed to send 200 OK for video re-INVITE: {}", e);
        }
    }

    /// Internal: rejects a video upgrade (called by VideoUpgradeRequest::reject/Drop).
    /// Sends 200 OK with audio-only SDP + `m=video 0` (RFC 3264 rejection).
    fn reject_video_internal(
        &self,
        reinvite_dlg: &Arc<dyn Dialog>,
        sess: &sdp::Session,
        remote_sdp: &str,
    ) {
        let local_sdp;
        {
            let mut inner = self.inner.lock();
            if inner.state == CallState::Ended {
                return;
            }

            // Update remote SDP and endpoint (audio may have changed).
            // Only negotiate audio codec — we're rejecting video.
            inner.remote_sdp = remote_sdp.to_string();
            inner.remote_ip = sess.connection.clone();
            if let Some(m) = sess.audio_media() {
                inner.remote_port = m.port;
            }
            let remote_audio: &[i32] = sess
                .audio_media()
                .map(|m| m.codecs.as_slice())
                .unwrap_or(&[]);
            let prefs_for_negotiate = Self::resolve_codec_prefs(&inner);
            let pt = sdp::negotiate_codec(prefs_for_negotiate, remote_audio);
            if pt >= 0 {
                if let Some(c) = Codec::from_payload_type(pt) {
                    inner.codec = c;
                }
            }

            // Build audio-only answer (build_answer_sdp won't include video
            // because we haven't set a video socket for this call).
            // Append explicit m=video 0 to match the remote's video m= line count.
            let prefs = Self::resolve_codec_prefs(&inner);
            let remote_codecs: &[i32] = sess
                .audio_media()
                .map(|m| m.codecs.as_slice())
                .unwrap_or(&[]);
            let mut answer = sdp::build_answer(
                &inner.local_ip,
                inner.rtp_port,
                prefs,
                remote_codecs,
                sdp::DIR_SEND_RECV,
            );
            if sess.video_media().is_some() {
                answer.push_str("m=video 0 RTP/AVP 0\r\n");
            }
            inner.local_sdp = answer.clone();
            local_sdp = answer;
        }

        // Send 200 OK with audio-only SDP (outside the lock).
        if let Err(e) = reinvite_dlg.respond(200, "OK", local_sdp.as_bytes()) {
            tracing::error!("failed to send 200 OK rejecting video: {}", e);
        }
    }

    /// Stops the video media pipeline (for video downgrade).
    fn stop_video_pipeline(&self) {
        let mut inner = self.inner.lock();
        // Remove video stream (index 1) if present.
        if inner.media_streams.len() >= 2 {
            let mut video_stream = inner.media_streams.remove(1);
            video_stream.stop();
        }
        inner.video_codec = None;
        inner.video_rtp_socket = None;
        inner.video_rtcp_socket = None;
        inner.video_rtp_port = 0;
        inner.video_remote_port = 0;
    }

    /// Internal: simulate_reinvite with an already-parsed SDP session (avoids double parse).
    fn simulate_reinvite_parsed(&self, sess: &sdp::Session, raw_sdp: &str) {
        let mut inner = self.inner.lock();
        if inner.state == CallState::Ended {
            return;
        }

        inner.remote_sdp = raw_sdp.to_string();
        Self::set_remote_endpoint(&mut inner, sess);

        let dir = sess.dir();
        let mut hold_fn = Vec::new();
        let mut resume_fn = Vec::new();
        let mut new_state = None;

        let is_hold_dir =
            dir == sdp::DIR_SEND_ONLY || dir == sdp::DIR_RECV_ONLY || dir == sdp::DIR_INACTIVE;
        match (is_hold_dir, inner.state) {
            (true, CallState::Active) => {
                inner.state = CallState::OnHold;
                hold_fn = inner.on_hold_fn.clone();
                new_state = Some(CallState::OnHold);
            }
            (false, CallState::OnHold) if dir == sdp::DIR_SEND_RECV => {
                inner.state = CallState::Active;
                resume_fn = inner.on_resume_fn.clone();
                new_state = Some(CallState::Active);
            }
            _ => {}
        }

        Self::negotiate_codec(&mut inner, sess);

        if let Some(s) = new_state {
            Self::fire_on_state(&inner, s);
        }
        drop(inner);

        for f in hold_fn {
            spawn_callback(move || f());
        }
        for f in resume_fn {
            spawn_callback(move || f());
        }
    }

    /// Sets the remote SDP, parsing it to extract remote endpoint and codec info.
    pub fn set_remote_sdp(&self, raw_sdp: &str) {
        let mut inner = self.inner.lock();
        inner.remote_sdp = raw_sdp.to_string();
        if let Ok(sess) = sdp::parse(raw_sdp) {
            Self::set_remote_endpoint(&mut inner, &sess);
            Self::negotiate_codec(&mut inner, &sess);
            // Extract remote SRTP key if present and suite is supported.
            if sess.is_srtp() {
                if let Some(crypto) = sess.first_crypto() {
                    if crypto.suite == crate::srtp::SUPPORTED_SUITE {
                        inner.srtp_remote_key = crypto.key_params.clone();
                        inner.srtp_enabled = true;
                    } else {
                        tracing::warn!("remote offered unsupported SRTP suite: {}", crypto.suite);
                    }
                }
            }
        }
    }

    /// Sets the local media address and RTP port for this call.
    /// Required before `accept()` for SDP answer generation.
    pub fn set_local_media(&self, ip: &str, port: i32) {
        let mut inner = self.inner.lock();
        inner.local_ip = ip.to_string();
        inner.rtp_port = port;
    }

    /// Stores the local SDP offer (outbound calls).
    pub(crate) fn set_local_sdp(&self, sdp: &str) {
        self.inner.lock().local_sdp = sdp.to_string();
    }

    /// Sets the RTP socket for this call.
    /// Required before `accept()` for media pipeline to start.
    pub fn set_rtp_socket(&self, socket: UdpSocket) {
        self.inner.lock().rtp_socket = Some(Arc::new(socket));
    }

    /// Sets the DTMF transport mode for this call.
    pub(crate) fn set_dtmf_mode(&self, mode: crate::config::DtmfMode) {
        self.inner.lock().dtmf_mode = mode;
    }

    /// Enables SRTP and stores the local inline key.
    /// The remote key is extracted from remote SDP when available.
    pub(crate) fn set_srtp(&self, local_inline_key: &str) {
        let mut inner = self.inner.lock();
        inner.srtp_enabled = true;
        inner.srtp_local_key = local_inline_key.to_string();
    }

    /// Starts the media pipeline if an RTP socket is available and remote endpoint is known.
    fn start_media_pipeline(inner: &mut CallInner) {
        if !inner.media_streams.is_empty() {
            return; // already started
        }
        let socket = match inner.rtp_socket.as_ref() {
            Some(s) => Arc::clone(s),
            None => return, // no socket — test path, skip media
        };
        if inner.remote_ip.is_empty() || inner.remote_port <= 0 {
            return; // no remote endpoint yet
        }
        let remote_addr: std::net::SocketAddr =
            match format!("{}:{}", inner.remote_ip, inner.remote_port).parse() {
                Ok(a) => a,
                Err(_) => return,
            };

        let transport = Arc::new(MediaTransport::new(
            socket.try_clone().expect("failed to clone RTP socket"),
            remote_addr,
        ));
        let channels = Arc::new(MediaChannels::new());
        let shared = Arc::new(media::MediaSharedState::new(inner.state));
        // Wire DTMF callbacks from Call into the media thread's shared state.
        // Combine internal + user callbacks into a single dispatcher.
        Self::sync_dtmf_to_media(inner, &shared);
        // Create SRTP contexts if enabled and both keys are available.
        let (srtp_in, srtp_out) = if inner.srtp_enabled
            && !inner.srtp_local_key.is_empty()
            && !inner.srtp_remote_key.is_empty()
        {
            let inbound = match SrtpContext::from_sdes_inline(&inner.srtp_remote_key) {
                Ok(ctx) => Some(ctx),
                Err(e) => {
                    tracing::error!("SRTP inbound context creation failed: {}", e);
                    return;
                }
            };
            let outbound =
                match SrtpContext::from_sdes_inline(&format!("inline:{}", inner.srtp_local_key)) {
                    Ok(ctx) => Some(ctx),
                    Err(e) => {
                        tracing::error!("SRTP outbound context creation failed: {}", e);
                        return;
                    }
                };
            (inbound, outbound)
        } else {
            (None, None)
        };
        // Bind RTCP socket (RTP port + 1) if we have an RTP socket.
        let (rtcp_socket, rtcp_remote_addr) = if let Some(ref s) = inner.rtp_socket {
            let rtp_port = s.local_addr().map(|a| a.port()).unwrap_or(0);
            let rsock = match media::listen_rtcp_port(rtp_port) {
                Ok(s) => Some(Arc::new(s)),
                Err(e) => {
                    tracing::warn!(rtp_port, error = %e, "RTCP port bind failed, RTCP disabled");
                    None
                }
            };
            let raddr = if inner.remote_port > 0 {
                format!("{}:{}", inner.remote_ip, inner.remote_port + 1)
                    .parse()
                    .ok()
            } else {
                None
            };
            (rsock, raddr)
        } else {
            (None, None)
        };
        let config = MediaConfig {
            codec: inner.codec,
            srtp_inbound: srtp_in,
            srtp_outbound: srtp_out,
            rtcp_socket,
            rtcp_remote_addr,
            ..MediaConfig::default()
        };
        let muted = Arc::new(std::sync::atomic::AtomicBool::new(inner.muted));
        let stream = media::start_media(
            config,
            Arc::clone(&channels),
            Arc::clone(&shared),
            Some(transport),
            muted,
        );
        inner.media_streams.push(stream);
        inner.media_shared = Some(shared);

        // Start video stream (index 1) if video was negotiated.
        Self::start_video_pipeline(inner);
    }

    /// Starts the video media pipeline if video was negotiated and a video socket is available.
    fn start_video_pipeline(inner: &mut CallInner) {
        if inner.video_codec.is_none() || inner.video_rtp_socket.is_none() {
            return;
        }
        if inner.media_streams.len() >= 2 {
            return; // video stream already started
        }
        let video_socket = inner.video_rtp_socket.as_ref().unwrap();
        if inner.remote_ip.is_empty() || inner.video_remote_port <= 0 {
            return;
        }
        let video_remote_addr: std::net::SocketAddr =
            match format!("{}:{}", inner.remote_ip, inner.video_remote_port).parse() {
                Ok(a) => a,
                Err(_) => return,
            };
        let video_transport = Arc::new(MediaTransport::new(
            video_socket
                .try_clone()
                .expect("failed to clone video RTP socket"),
            video_remote_addr,
        ));
        let video_channels = Arc::new(MediaChannels::new());

        // Video RTCP socket (video RTP port + 1).
        let video_rtp_port = video_socket.local_addr().map(|a| a.port()).unwrap_or(0);
        let video_rtcp_socket = media::listen_rtcp_port(video_rtp_port).ok().map(Arc::new);
        // Store RTCP socket in CallInner so request_keyframe() can reuse it.
        inner.video_rtcp_socket = video_rtcp_socket.clone();
        let video_rtcp_addr: Option<std::net::SocketAddr> = if inner.video_remote_port > 0 {
            format!("{}:{}", inner.remote_ip, inner.video_remote_port + 1)
                .parse()
                .ok()
        } else {
            None
        };

        let (video_srtp_in, video_srtp_out) = if inner.srtp_enabled
            && !inner.srtp_local_key.is_empty()
            && !inner.srtp_remote_key.is_empty()
        {
            let inbound = SrtpContext::from_sdes_inline(&inner.srtp_remote_key)
                .map_err(|e| tracing::error!("Video SRTP inbound context failed: {}", e))
                .ok();
            let outbound =
                SrtpContext::from_sdes_inline(&format!("inline:{}", inner.srtp_local_key))
                    .map_err(|e| tracing::error!("Video SRTP outbound context failed: {}", e))
                    .ok();
            (inbound, outbound)
        } else {
            (None, None)
        };

        let video_config = media::VideoMediaConfig {
            srtp_inbound: video_srtp_in,
            srtp_outbound: video_srtp_out,
            rtcp_socket: video_rtcp_socket,
            rtcp_remote_addr: video_rtcp_addr,
            video_codec: inner.video_codec,
            video_payload_type: inner
                .video_codec
                .map(|c| c.default_payload_type())
                .unwrap_or(96),
        };
        let video_muted = Arc::new(std::sync::atomic::AtomicBool::new(inner.video_muted));
        let video_stream = media::start_video_media(
            video_config,
            video_channels,
            Some(video_transport),
            video_muted,
        );
        inner.media_streams.push(video_stream);

        // Fire on_video callback so the app can start rendering.
        for f in &inner.on_video_fn {
            let f = Arc::clone(f);
            spawn_callback(move || f());
        }
    }

    /// Sends a SIP response via the dialog (e.g., 180 Ringing for inbound calls).
    pub(crate) fn dlg_respond(&self, code: u16, reason: &str) -> Result<()> {
        self.dlg.respond(code, reason, &[])
    }

    // --- Callback setters ---

    /// Registers a callback invoked on every state transition.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_state(&self, f: impl Fn(CallState) + Send + Sync + 'static) {
        self.inner.lock().on_state_fn.push(Arc::new(f));
    }

    /// Registers a callback invoked when the call ends, with the reason.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_ended(&self, f: impl Fn(EndReason) + Send + Sync + 'static) {
        self.inner.lock().on_ended_fn.push(Arc::new(f));
    }

    /// Registers a callback invoked when the media session becomes available.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_media(&self, f: impl Fn() + Send + Sync + 'static) {
        self.inner.lock().on_media_fn.push(Arc::new(f));
    }

    /// Registers a callback invoked when a DTMF digit is received.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_dtmf(&self, f: impl Fn(String) + Send + Sync + 'static) {
        let mut inner = self.inner.lock();
        inner.on_dtmf_fn.push(Arc::new(f));
        if let Some(ref shared) = inner.media_shared {
            Self::sync_dtmf_to_media(&inner, shared);
        }
    }

    /// Registers a callback invoked when the call is placed on hold.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_hold(&self, f: impl Fn() + Send + Sync + 'static) {
        self.inner.lock().on_hold_fn.push(Arc::new(f));
    }

    /// Registers a callback invoked when the call is resumed from hold.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_resume(&self, f: impl Fn() + Send + Sync + 'static) {
        self.inner.lock().on_resume_fn.push(Arc::new(f));
    }

    /// Registers a callback invoked when the call is muted.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_mute(&self, f: impl Fn() + Send + Sync + 'static) {
        self.inner.lock().on_mute_fn.push(Arc::new(f));
    }

    /// Registers a callback invoked when the call is unmuted.
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_unmute(&self, f: impl Fn() + Send + Sync + 'static) {
        self.inner.lock().on_unmute_fn.push(Arc::new(f));
    }

    /// Registers a callback invoked when video is added to the call (e.g., via re-INVITE).
    /// Multiple callbacks can be registered; all will fire.
    pub fn on_video(&self, f: impl Fn() + Send + Sync + 'static) {
        self.inner.lock().on_video_fn.push(Arc::new(f));
    }

    /// Registers a callback invoked when the remote requests a video upgrade via re-INVITE.
    ///
    /// The callback receives a [`VideoUpgradeRequest`] which must be accepted or rejected.
    /// If no callback is registered, video upgrades are automatically rejected (safe default).
    pub fn on_video_request(&self, f: impl Fn(VideoUpgradeRequest) + Send + Sync + 'static) {
        self.inner.lock().on_video_request_fn = Some(Arc::new(f));
    }

    pub(crate) fn on_ended_internal(&self, f: impl Fn(EndReason) + Send + Sync + 'static) {
        self.inner.lock().on_ended_internal = Some(Arc::new(f));
    }

    /// Internal state callback — used by phone layer, not overwritten by user's on_state().
    pub(crate) fn on_state_internal(&self, f: impl Fn(CallState) + Send + Sync + 'static) {
        self.inner.lock().on_state_internal = Some(Arc::new(f));
    }

    /// Internal DTMF callback — used by phone layer, not overwritten by user's on_dtmf().
    pub(crate) fn on_dtmf_internal(&self, f: impl Fn(String) + Send + Sync + 'static) {
        let mut inner = self.inner.lock();
        inner.on_dtmf_internal = Some(Arc::new(f));
        if let Some(ref shared) = inner.media_shared {
            Self::sync_dtmf_to_media(&inner, shared);
        }
    }

    /// Builds a single dispatcher from internal + user DTMF callbacks and sets it on the media shared state.
    fn sync_dtmf_to_media(inner: &CallInner, shared: &Arc<media::MediaSharedState>) {
        let f_int = inner.on_dtmf_internal.clone();
        let f_usr = inner.on_dtmf_fn.clone();
        if f_int.is_none() && f_usr.is_empty() {
            return;
        }
        *shared.on_dtmf_fn.lock() = Some(Arc::new(move |d: String| {
            if let Some(ref a) = f_int {
                a(d.clone());
            }
            for f in &f_usr {
                f(d.clone());
            }
        }));
    }

    // --- Media channel accessors ---

    /// Returns the RTP writer sender (for sending raw RTP packets outbound).
    pub fn rtp_writer(&self) -> Option<crossbeam_channel::Sender<RtpPacket>> {
        self.inner
            .lock()
            .media_streams
            .first()
            .map(|s| s.channels.rtp_writer.tx.clone())
    }

    /// Returns the RTP reader receiver (post-jitter-buffer, reordered).
    pub fn rtp_reader(&self) -> Option<crossbeam_channel::Receiver<RtpPacket>> {
        self.inner
            .lock()
            .media_streams
            .first()
            .map(|s| s.channels.rtp_reader.rx.clone())
    }

    /// Returns the RTP raw reader receiver (pre-jitter-buffer, wire order).
    pub fn rtp_raw_reader(&self) -> Option<crossbeam_channel::Receiver<RtpPacket>> {
        self.inner
            .lock()
            .media_streams
            .first()
            .map(|s| s.channels.rtp_raw_reader.rx.clone())
    }

    /// Returns the PCM writer sender (for sending PCM samples for encoding + sending).
    ///
    /// Each buffer sent is immediately encoded and sent as one RTP packet.
    /// The caller must provide frames at real-time rate (one 160-sample frame
    /// every 20ms for 8kHz codecs). Use [`paced_pcm_writer()`](Self::paced_pcm_writer)
    /// for pre-generated audio (TTS, file playback) that needs internal pacing.
    pub fn pcm_writer(&self) -> Option<crossbeam_channel::Sender<Vec<i16>>> {
        self.inner
            .lock()
            .media_streams
            .first()
            .map(|s| s.channels.pcm_writer.tx.clone())
    }

    /// Returns the paced PCM writer sender for pre-generated audio.
    ///
    /// Unlike [`pcm_writer()`](Self::pcm_writer), this channel accepts arbitrary-length
    /// PCM buffers (e.g. entire TTS utterances), splits them into codec-frame-sized
    /// chunks, and sends them as RTP packets at real-time pace (one frame every 20ms).
    ///
    /// Use this for TTS providers, file playback, or any source that delivers audio
    /// in bursts rather than at real-time rate. Do not use both `pcm_writer()` and
    /// `paced_pcm_writer()` on the same call simultaneously.
    pub fn paced_pcm_writer(&self) -> Option<crossbeam_channel::Sender<Vec<i16>>> {
        self.inner
            .lock()
            .media_streams
            .first()
            .map(|s| s.channels.paced_pcm_writer.tx.clone())
    }

    /// Returns the PCM reader receiver (decoded PCM from inbound RTP).
    pub fn pcm_reader(&self) -> Option<crossbeam_channel::Receiver<Vec<i16>>> {
        self.inner
            .lock()
            .media_streams
            .first()
            .map(|s| s.channels.pcm_reader.rx.clone())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mock::dialog::MockDialog;
    use std::sync::mpsc;
    use std::time::Duration;

    fn mock_dlg() -> Arc<MockDialog> {
        Arc::new(MockDialog::new())
    }

    fn mock_dlg_with_headers(headers: HashMap<String, Vec<String>>) -> Arc<MockDialog> {
        Arc::new(MockDialog::with_headers(headers))
    }

    fn test_sdp(ip: &str, port: i32, dir: &str, codecs: &[i32]) -> String {
        sdp::build_offer(ip, port, codecs, dir)
    }

    // --- Inbound: basic state transitions ---

    #[test]
    fn inbound_initial_state_is_ringing() {
        let call = Call::new_inbound(mock_dlg());
        assert_eq!(call.state(), CallState::Ringing);
    }

    #[test]
    fn accept_transitions_to_active() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        assert_eq!(call.state(), CallState::Active);
    }

    #[test]
    fn accept_sends_sdp_answer() {
        let dlg = mock_dlg();
        let call = Call::new_inbound(dlg.clone());
        call.accept().unwrap();
        assert_eq!(dlg.last_response_code(), 200);
        assert!(!dlg.last_response_body().is_empty());
    }

    #[test]
    fn accept_sets_media_active() {
        let call = Call::new_inbound(mock_dlg());
        assert!(!call.media_session_active());
        call.accept().unwrap();
        assert!(call.media_session_active());
    }

    #[test]
    fn reject_sends_correct_sip_code() {
        let dlg = mock_dlg();
        let call = Call::new_inbound(dlg.clone());
        call.reject(486, "Busy Here").unwrap();
        assert_eq!(dlg.last_response_code(), 486);
        assert_eq!(dlg.last_response_reason(), "Busy Here");
    }

    #[test]
    fn reject_transitions_to_ended() {
        let call = Call::new_inbound(mock_dlg());
        call.reject(486, "Busy Here").unwrap();
        assert_eq!(call.state(), CallState::Ended);
    }

    #[test]
    fn reject_fires_ended_by_rejected() {
        let call = Call::new_inbound(mock_dlg());
        let (tx, rx) = mpsc::channel();
        call.on_ended(move |r| {
            let _ = tx.send(r);
        });
        call.reject(486, "Busy Here").unwrap();
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            EndReason::Rejected
        );
    }

    #[test]
    fn cannot_accept_after_rejected() {
        let call = Call::new_inbound(mock_dlg());
        call.reject(486, "Busy Here").unwrap();
        assert!(call.accept().is_err());
    }

    #[test]
    fn cannot_reject_after_accepted() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        assert!(call.reject(486, "Busy Here").is_err());
    }

    // --- Outbound: state transitions ---

    #[test]
    fn outbound_initial_state_is_dialing() {
        let call = Call::new_outbound(mock_dlg(), DialOptions::default());
        assert_eq!(call.state(), CallState::Dialing);
    }

    #[test]
    fn outbound_transitions_on_remote_ringing() {
        let call = Call::new_outbound(mock_dlg(), DialOptions::default());
        call.simulate_response(180, "Ringing");
        assert_eq!(call.state(), CallState::RemoteRinging);
    }

    #[test]
    fn outbound_transitions_to_active_on_200() {
        let call = Call::new_outbound(mock_dlg(), DialOptions::default());
        call.simulate_response(180, "Ringing");
        call.simulate_response(200, "OK");
        assert_eq!(call.state(), CallState::Active);
    }

    // --- 183 / EarlyMedia ---

    #[test]
    fn early_media_183_transitions() {
        let opts = DialOptions {
            early_media: true,
            ..Default::default()
        };
        let call = Call::new_outbound(mock_dlg(), opts);
        call.simulate_response(183, "Session Progress");
        assert_eq!(call.state(), CallState::EarlyMedia);
    }

    #[test]
    fn no_early_media_183_stays_remote_ringing() {
        let call = Call::new_outbound(mock_dlg(), DialOptions::default());
        call.simulate_response(180, "Ringing");
        call.simulate_response(183, "Session Progress");
        assert_eq!(call.state(), CallState::RemoteRinging);
    }

    #[test]
    fn no_early_media_183_media_not_active() {
        let call = Call::new_outbound(mock_dlg(), DialOptions::default());
        call.simulate_response(183, "Session Progress");
        assert!(!call.media_session_active());
    }

    // --- OnMedia event ---

    #[test]
    fn on_media_fires_after_200() {
        let call = Call::new_outbound(mock_dlg(), DialOptions::default());
        let (tx, rx) = mpsc::channel();
        call.on_media(move || {
            let _ = tx.send(());
        });
        call.simulate_response(200, "OK");
        assert!(rx.recv_timeout(Duration::from_millis(200)).is_ok());
    }

    #[test]
    fn on_media_fires_on_183_with_early_media() {
        let opts = DialOptions {
            early_media: true,
            ..Default::default()
        };
        let call = Call::new_outbound(mock_dlg(), opts);
        let (tx, rx) = mpsc::channel();
        call.on_media(move || {
            let _ = tx.send(());
        });
        call.simulate_response(183, "Session Progress");
        assert!(rx.recv_timeout(Duration::from_millis(200)).is_ok());
    }

    #[test]
    fn on_media_does_not_fire_on_183_without_early_media() {
        let call = Call::new_outbound(mock_dlg(), DialOptions::default());
        let (tx, _rx) = mpsc::channel::<()>();
        call.on_media(move || {
            let _ = tx.send(());
        });
        call.simulate_response(183, "Session Progress");
        std::thread::sleep(Duration::from_millis(50));
        assert!(_rx.try_recv().is_err());
    }

    // --- End() semantics ---

    #[test]
    fn end_before_answer_sends_cancel() {
        let dlg = mock_dlg();
        let call = Call::new_outbound(dlg.clone(), DialOptions::default());
        call.simulate_response(180, "Ringing");
        call.end().unwrap();
        assert!(dlg.cancel_sent());
        assert!(!dlg.bye_sent());
    }

    #[test]
    fn end_before_answer_fires_ended_by_cancelled() {
        let call = Call::new_outbound(mock_dlg(), DialOptions::default());
        call.simulate_response(180, "Ringing");
        let (tx, rx) = mpsc::channel();
        call.on_ended(move |r| {
            let _ = tx.send(r);
        });
        call.end().unwrap();
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            EndReason::Cancelled
        );
    }

    #[test]
    fn end_while_active_sends_bye() {
        let dlg = mock_dlg();
        let call = Call::new_outbound(dlg.clone(), DialOptions::default());
        call.simulate_response(200, "OK");
        call.end().unwrap();
        assert!(dlg.bye_sent());
        assert!(!dlg.cancel_sent());
    }

    #[test]
    fn end_while_active_fires_ended_by_local() {
        let call = Call::new_outbound(mock_dlg(), DialOptions::default());
        call.simulate_response(200, "OK");
        let (tx, rx) = mpsc::channel();
        call.on_ended(move |r| {
            let _ = tx.send(r);
        });
        call.end().unwrap();
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            EndReason::Local
        );
    }

    #[test]
    fn end_while_on_hold_sends_bye() {
        let dlg = mock_dlg();
        let call = Call::new_outbound(dlg.clone(), DialOptions::default());
        call.simulate_response(200, "OK");
        call.hold().unwrap();
        call.end().unwrap();
        assert!(dlg.bye_sent());
    }

    #[test]
    fn remote_bye_fires_ended_by_remote() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        let (tx, rx) = mpsc::channel();
        call.on_ended(move |r| {
            let _ = tx.send(r);
        });
        call.simulate_bye();
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            EndReason::Remote
        );
    }

    #[test]
    fn end_on_already_ended_returns_invalid_state() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.end().unwrap();
        assert!(call.end().is_err());
    }

    #[test]
    fn simulate_bye_on_ended_is_noop() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.end().unwrap();
        // Second simulate_bye should not panic or fire duplicate events.
        call.simulate_bye();
        assert_eq!(call.state(), CallState::Ended);
    }

    // --- Hold / Resume ---

    #[test]
    fn hold_sends_reinvite_with_sendonly() {
        let dlg = mock_dlg();
        let call = Call::new_inbound(dlg.clone());
        call.accept().unwrap();
        call.hold().unwrap();
        assert!(dlg.last_reinvite_sdp().contains("a=sendonly"));
    }

    #[test]
    fn hold_transitions_to_on_hold() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.hold().unwrap();
        assert_eq!(call.state(), CallState::OnHold);
    }

    #[test]
    fn resume_sends_reinvite_with_sendrecv() {
        let dlg = mock_dlg();
        let call = Call::new_inbound(dlg.clone());
        call.accept().unwrap();
        call.hold().unwrap();
        call.resume().unwrap();
        assert!(dlg.last_reinvite_sdp().contains("a=sendrecv"));
    }

    #[test]
    fn resume_transitions_to_active() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.hold().unwrap();
        call.resume().unwrap();
        assert_eq!(call.state(), CallState::Active);
    }

    #[test]
    fn hold_when_not_active_returns_invalid_state() {
        let call = Call::new_inbound(mock_dlg());
        assert!(call.hold().is_err());
    }

    // --- Identity & Headers ---

    #[test]
    fn id_is_unique_per_call() {
        let c1 = Call::new_inbound(mock_dlg());
        let c2 = Call::new_inbound(mock_dlg());
        assert_ne!(c1.id(), c2.id());
    }

    #[test]
    fn call_id_matches_sip_header() {
        let dlg = Arc::new(MockDialog::with_call_id("test-call-id-xyz"));
        let call = Call::new_inbound(dlg);
        assert_eq!(call.call_id(), "test-call-id-xyz");
    }

    #[test]
    fn headers_returns_copy() {
        let mut h = HashMap::new();
        h.insert("X-Custom".into(), vec!["value1".into()]);
        let dlg = mock_dlg_with_headers(h);
        let call = Call::new_inbound(dlg);
        let mut headers = call.headers();
        headers.insert("X-Custom".into(), vec!["mutated".into()]);
        assert_eq!(call.header("X-Custom"), vec!["value1"]);
    }

    #[test]
    fn header_case_insensitive() {
        let mut h = HashMap::new();
        h.insert("P-Asserted-Identity".into(), vec!["sip:1001@pbx".into()]);
        let dlg = mock_dlg_with_headers(h);
        let call = Call::new_inbound(dlg);
        assert_eq!(call.header("p-asserted-identity"), vec!["sip:1001@pbx"]);
    }

    #[test]
    fn direction_inbound() {
        let call = Call::new_inbound(mock_dlg());
        assert_eq!(call.direction(), Direction::Inbound);
    }

    #[test]
    fn direction_outbound() {
        let call = Call::new_outbound(mock_dlg(), DialOptions::default());
        assert_eq!(call.direction(), Direction::Outbound);
    }

    // --- Timing ---

    #[test]
    fn start_time_none_before_active() {
        let call = Call::new_inbound(mock_dlg());
        assert!(call.start_time().is_none());
    }

    #[test]
    fn start_time_set_on_active() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        assert!(call.start_time().is_some());
    }

    #[test]
    fn duration_zero_before_active() {
        let call = Call::new_inbound(mock_dlg());
        assert_eq!(call.duration(), Duration::ZERO);
    }

    #[test]
    fn duration_grows_while_active() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        std::thread::sleep(Duration::from_millis(30));
        assert!(call.duration() > Duration::from_millis(20));
    }

    // --- Blind Transfer ---

    #[test]
    fn blind_transfer_sends_refer() {
        let dlg = mock_dlg();
        let call = Call::new_inbound(dlg.clone());
        call.accept().unwrap();
        call.blind_transfer("sip:1003@pbx").unwrap();
        assert!(dlg.refer_sent());
        assert_eq!(dlg.last_refer_target(), "sip:1003@pbx");
    }

    #[test]
    fn blind_transfer_fires_ended_by_transfer() {
        let dlg = mock_dlg();
        let call = Call::new_inbound(dlg.clone());
        call.accept().unwrap();
        let (tx, rx) = mpsc::channel();
        call.on_ended(move |r| {
            let _ = tx.send(r);
        });
        call.blind_transfer("sip:1003@pbx").unwrap();
        dlg.simulate_notify(200);
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            EndReason::Transfer
        );
    }

    #[test]
    fn blind_transfer_failure_notify_ends_call() {
        let dlg = mock_dlg();
        let call = Call::new_inbound(dlg.clone());
        call.accept().unwrap();
        let (tx, rx) = mpsc::channel();
        call.on_ended(move |r| {
            let _ = tx.send(r);
        });
        call.blind_transfer("sip:1003@pbx").unwrap();
        dlg.simulate_notify(503); // Service Unavailable
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            EndReason::TransferFailed
        );
    }

    #[test]
    fn blind_transfer_1xx_notify_does_not_end_call() {
        let dlg = mock_dlg();
        let call = Call::new_inbound(dlg.clone());
        call.accept().unwrap();
        let (tx, rx) = mpsc::channel();
        call.on_ended(move |r| {
            let _ = tx.send(r);
        });
        call.blind_transfer("sip:1003@pbx").unwrap();
        dlg.simulate_notify(100); // Trying — should not end
        assert!(rx.recv_timeout(Duration::from_millis(100)).is_err());
        assert_eq!(call.state(), CallState::Active);
    }

    #[test]
    fn blind_transfer_when_not_active_returns_invalid_state() {
        let call = Call::new_inbound(mock_dlg());
        assert!(call.blind_transfer("sip:1003@pbx").is_err());
    }

    // --- Attended transfer (Call-level) ---

    fn mock_dlg_with_tags(call_id: &str, from: &str, to: &str) -> Arc<MockDialog> {
        let mut h = std::collections::HashMap::new();
        h.insert("From".into(), vec![from.into()]);
        h.insert("To".into(), vec![to.into()]);
        let dlg = MockDialog::with_headers(h);
        dlg.set_call_id(call_id);
        Arc::new(dlg)
    }

    #[test]
    fn attended_transfer_sends_refer_with_replaces() {
        let dlg_a = mock_dlg_with_tags("call-a", "<sip:1001@pbx>;tag=a1", "<sip:bob@pbx>;tag=b1");
        let dlg_b = mock_dlg_with_tags(
            "call-b@pbx.local",
            "<sip:1001@pbx>;tag=a2",
            "<sip:charlie@pbx>;tag=c2",
        );
        let call_a = Call::new_inbound(dlg_a.clone());
        call_a.accept().unwrap();
        let call_b = Call::new_outbound(dlg_b.clone(), DialOptions::default());
        call_b.simulate_response(200, "OK");

        call_a.attended_transfer(&call_b).unwrap();

        assert!(dlg_a.refer_sent());
        let target = dlg_a.last_refer_target();
        assert!(target.starts_with("sip:charlie@pbx?Replaces="));
        assert!(target.contains("call-b%40pbx.local"));
        assert!(target.contains("to-tag%3Dc2"));
        assert!(target.contains("from-tag%3Da2"));
    }

    #[test]
    fn attended_transfer_success_ends_both() {
        let dlg_a = mock_dlg_with_tags("a", "<sip:1001@pbx>;tag=a1", "<sip:bob@pbx>;tag=b1");
        let dlg_b = mock_dlg_with_tags("b", "<sip:1001@pbx>;tag=a2", "<sip:charlie@pbx>;tag=c2");
        let call_a = Call::new_inbound(dlg_a.clone());
        call_a.accept().unwrap();
        let call_b = Call::new_outbound(dlg_b.clone(), DialOptions::default());
        call_b.simulate_response(200, "OK");

        let (tx_a, rx_a) = mpsc::channel();
        let (tx_b, rx_b) = mpsc::channel();
        call_a.on_ended(move |r| {
            let _ = tx_a.send(r);
        });
        call_b.on_ended(move |r| {
            let _ = tx_b.send(r);
        });

        call_a.attended_transfer(&call_b).unwrap();
        dlg_a.simulate_notify(200);

        assert_eq!(
            rx_a.recv_timeout(Duration::from_millis(200)).unwrap(),
            EndReason::Transfer
        );
        assert_eq!(
            rx_b.recv_timeout(Duration::from_millis(200)).unwrap(),
            EndReason::Transfer
        );
    }

    #[test]
    fn attended_transfer_failure_ends_both() {
        let dlg_a = mock_dlg_with_tags("a", "<sip:1001@pbx>;tag=a1", "<sip:bob@pbx>;tag=b1");
        let dlg_b = mock_dlg_with_tags("b", "<sip:1001@pbx>;tag=a2", "<sip:charlie@pbx>;tag=c2");
        let call_a = Call::new_inbound(dlg_a.clone());
        call_a.accept().unwrap();
        let call_b = Call::new_outbound(dlg_b.clone(), DialOptions::default());
        call_b.simulate_response(200, "OK");

        let (tx_a, rx_a) = mpsc::channel();
        let (tx_b, rx_b) = mpsc::channel();
        call_a.on_ended(move |r| {
            let _ = tx_a.send(r);
        });
        call_b.on_ended(move |r| {
            let _ = tx_b.send(r);
        });

        call_a.attended_transfer(&call_b).unwrap();
        dlg_a.simulate_notify(503);

        assert_eq!(
            rx_a.recv_timeout(Duration::from_millis(200)).unwrap(),
            EndReason::TransferFailed
        );
        assert_eq!(
            rx_b.recv_timeout(Duration::from_millis(200)).unwrap(),
            EndReason::TransferFailed
        );
    }

    #[test]
    fn attended_transfer_1xx_keeps_both_alive() {
        let dlg_a = mock_dlg_with_tags("a", "<sip:1001@pbx>;tag=a1", "<sip:bob@pbx>;tag=b1");
        let dlg_b = mock_dlg_with_tags("b", "<sip:1001@pbx>;tag=a2", "<sip:charlie@pbx>;tag=c2");
        let call_a = Call::new_inbound(dlg_a.clone());
        call_a.accept().unwrap();
        let call_b = Call::new_outbound(dlg_b.clone(), DialOptions::default());
        call_b.simulate_response(200, "OK");

        call_a.attended_transfer(&call_b).unwrap();
        dlg_a.simulate_notify(100);

        assert_eq!(call_a.state(), CallState::Active);
        assert_eq!(call_b.state(), CallState::Active);
    }

    #[test]
    fn attended_transfer_rejects_inactive_calls() {
        let call_a = Call::new_inbound(mock_dlg()); // Ringing
        let call_b = Call::new_inbound(mock_dlg());
        call_b.accept().unwrap();
        assert!(call_a.attended_transfer(&call_b).is_err());

        let call_a2 = Call::new_inbound(mock_dlg());
        call_a2.accept().unwrap();
        let call_b2 = Call::new_inbound(mock_dlg()); // Ringing
        assert!(call_a2.attended_transfer(&call_b2).is_err());
    }

    // --- Tag extraction ---

    #[test]
    fn sip_header_tag_extracts_tag() {
        assert_eq!(sip_header_tag("<sip:1001@host>;tag=abc123"), "abc123");
        assert_eq!(sip_header_tag("\"Alice\" <sip:1001@host>;tag=abc"), "abc");
        assert_eq!(sip_header_tag("<sip:1001@host>"), "");
        assert_eq!(sip_header_tag("<sip:1001@host>;tag=abc;other=1"), "abc");
    }

    // --- Dialog ID ---

    #[test]
    fn dialog_id_outbound_call() {
        let mut h = HashMap::new();
        h.insert("From".into(), vec!["<sip:1001@host>;tag=local1".into()]);
        h.insert("To".into(), vec!["<sip:1002@host>;tag=remote2".into()]);
        let dlg = Arc::new(MockDialog::with_headers(h));
        let call = Call::new_outbound(dlg.clone(), DialOptions::default());
        let (cid, local, remote) = call.dialog_id();
        assert_eq!(cid, dlg.call_id());
        assert_eq!(local, "local1");
        assert_eq!(remote, "remote2");
    }

    #[test]
    fn dialog_id_inbound_call() {
        let mut h = HashMap::new();
        h.insert("From".into(), vec!["<sip:1001@host>;tag=remote1".into()]);
        h.insert("To".into(), vec!["<sip:1002@host>;tag=local2".into()]);
        let dlg = Arc::new(MockDialog::with_headers(h));
        let call = Call::new_inbound(dlg.clone());
        let (cid, local, remote) = call.dialog_id();
        assert_eq!(cid, dlg.call_id());
        assert_eq!(local, "local2");
        assert_eq!(remote, "remote1");
    }

    // --- End with reason ---

    #[test]
    fn end_with_reason_transfer() {
        let dlg = mock_dlg();
        let call = Call::new_inbound(dlg.clone());
        call.accept().unwrap();
        let (tx, rx) = mpsc::channel();
        call.on_ended(move |r| {
            let _ = tx.send(r);
        });
        call.end_with_reason(EndReason::Transfer);
        assert_eq!(call.state(), CallState::Ended);
        assert!(dlg.bye_sent());
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            EndReason::Transfer
        );
    }

    #[test]
    fn end_with_reason_already_ended_is_noop() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.end().unwrap();
        // Should not panic or fire callbacks again.
        call.end_with_reason(EndReason::Transfer);
        assert_eq!(call.state(), CallState::Ended);
    }

    // --- SDP integration ---

    #[test]
    fn local_sdp_empty_before_active() {
        let call = Call::new_inbound(mock_dlg());
        assert_eq!(call.local_sdp(), "");
    }

    #[test]
    fn local_sdp_populated_after_accept() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        assert!(call.local_sdp().contains("v=0"));
    }

    #[test]
    fn codec_negotiated_from_sdp() {
        let remote_sdp = test_sdp("192.168.1.200", 5004, "sendrecv", &[0, 8]);
        let call = Call::new_inbound(mock_dlg());
        call.set_remote_sdp(&remote_sdp);
        call.accept().unwrap();
        // Default prefs are [8, 0, 9, 101, 111], so PCMA (8) wins.
        assert_eq!(call.codec(), Codec::PCMA);
    }

    #[test]
    fn hold_sends_sdp_with_sendonly() {
        let dlg = mock_dlg();
        let call = Call::new_inbound(dlg.clone());
        call.accept().unwrap();
        call.hold().unwrap();
        let raw = dlg.last_reinvite_sdp();
        let s = sdp::parse(&raw).unwrap();
        assert_eq!(s.dir(), "sendonly");
    }

    #[test]
    fn resume_sends_sdp_with_sendrecv() {
        let dlg = mock_dlg();
        let call = Call::new_inbound(dlg.clone());
        call.accept().unwrap();
        call.hold().unwrap();
        call.resume().unwrap();
        let raw = dlg.last_reinvite_sdp();
        let s = sdp::parse(&raw).unwrap();
        assert_eq!(s.dir(), "sendrecv");
    }

    // --- Re-INVITE handling ---

    #[test]
    fn inbound_reinvite_hold() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.simulate_reinvite(&test_sdp("192.168.1.200", 5004, "sendonly", &[0]));
        assert_eq!(call.state(), CallState::OnHold);
    }

    #[test]
    fn inbound_reinvite_resume() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.simulate_reinvite(&test_sdp("192.168.1.200", 5004, "sendonly", &[0]));
        call.simulate_reinvite(&test_sdp("192.168.1.200", 5004, "sendrecv", &[0]));
        assert_eq!(call.state(), CallState::Active);
    }

    #[test]
    fn on_hold_callback_fires() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        let (tx, rx) = mpsc::channel();
        call.on_hold(move || {
            let _ = tx.send(());
        });
        call.simulate_reinvite(&test_sdp("192.168.1.200", 5004, "sendonly", &[0]));
        assert!(rx.recv_timeout(Duration::from_millis(200)).is_ok());
    }

    #[test]
    fn on_resume_callback_fires() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        let (tx, rx) = mpsc::channel();
        call.on_resume(move || {
            let _ = tx.send(());
        });
        call.simulate_reinvite(&test_sdp("192.168.1.200", 5004, "sendonly", &[0]));
        call.simulate_reinvite(&test_sdp("192.168.1.200", 5004, "sendrecv", &[0]));
        assert!(rx.recv_timeout(Duration::from_millis(200)).is_ok());
    }

    #[test]
    fn reinvite_codec_change() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.simulate_reinvite(&test_sdp("192.168.1.200", 5004, "sendrecv", &[9]));
        assert_eq!(call.codec(), Codec::G722);
    }

    #[test]
    fn reinvite_on_ended_call_ignored() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.end().unwrap();
        call.simulate_reinvite(&test_sdp("192.168.1.200", 5004, "sendonly", &[0]));
        assert_eq!(call.state(), CallState::Ended);
    }

    // --- DTMF ---

    #[test]
    fn send_dtmf_invalid_digit_returns_error() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        assert!(call.send_dtmf("X").is_err());
    }

    #[test]
    fn send_dtmf_when_not_active_returns_error() {
        let call = Call::new_inbound(mock_dlg());
        assert!(call.send_dtmf("1").is_err());
    }

    #[test]
    fn send_dtmf_sip_info_mode() {
        let dlg = Arc::new(crate::mock::dialog::MockDialog::new());
        let call = Call::new_inbound(Arc::clone(&dlg) as Arc<dyn Dialog>);
        call.set_dtmf_mode(crate::config::DtmfMode::SipInfo);
        call.accept().unwrap();
        call.send_dtmf("5").unwrap();
        let sent = dlg.info_dtmf_sent();
        assert_eq!(sent.len(), 1);
        assert_eq!(sent[0].0, "5");
        assert_eq!(sent[0].1, 160);
    }

    #[test]
    fn send_dtmf_both_mode_uses_rfc4733() {
        // Both mode should use RFC 4733 (RTP), not SIP INFO.
        let dlg = Arc::new(crate::mock::dialog::MockDialog::new());
        let call = Call::new_inbound(Arc::clone(&dlg) as Arc<dyn Dialog>);
        call.set_dtmf_mode(crate::config::DtmfMode::Both);
        call.accept().unwrap();
        // Without an RTP socket it will fail, but it should NOT use SIP INFO.
        let _ = call.send_dtmf("1");
        assert!(dlg.info_dtmf_sent().is_empty());
    }

    #[test]
    fn fire_dtmf_triggers_callbacks() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        let (tx, rx) = crossbeam_channel::bounded(1);
        call.on_dtmf(move |d| {
            let _ = tx.send(d);
        });
        call.fire_dtmf("7");
        let digit = rx.recv_timeout(std::time::Duration::from_secs(1)).unwrap();
        assert_eq!(digit, "7");
    }

    #[test]
    fn fire_dtmf_triggers_internal_and_user_callbacks() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        let (tx_int, rx_int) = crossbeam_channel::bounded(1);
        let (tx_usr, rx_usr) = crossbeam_channel::bounded(1);
        call.on_dtmf_internal(move |d| {
            let _ = tx_int.send(d);
        });
        call.on_dtmf(move |d| {
            let _ = tx_usr.send(d);
        });
        call.fire_dtmf("#");
        assert_eq!(
            rx_int
                .recv_timeout(std::time::Duration::from_secs(1))
                .unwrap(),
            "#"
        );
        assert_eq!(
            rx_usr
                .recv_timeout(std::time::Duration::from_secs(1))
                .unwrap(),
            "#"
        );
    }

    // --- Session timers ---

    #[test]
    fn session_timer_sends_refresh_reinvite() {
        let dlg = Arc::new(MockDialog::with_session_expires(1));
        let call = Call::new_inbound(dlg.clone());
        call.accept().unwrap();
        // Timer fires at 500ms (half of 1s).
        std::thread::sleep(Duration::from_millis(600));
        assert!(!dlg.last_reinvite_sdp().is_empty());
    }

    #[test]
    fn session_timer_no_header_no_timer() {
        let dlg = mock_dlg();
        let call = Call::new_inbound(dlg.clone());
        call.accept().unwrap();
        std::thread::sleep(Duration::from_millis(100));
        assert!(dlg.last_reinvite_sdp().is_empty());
    }

    #[test]
    fn session_timer_cancelled_on_end() {
        let dlg = Arc::new(MockDialog::with_session_expires(1));
        let call = Call::new_inbound(dlg.clone());
        call.accept().unwrap();
        call.end().unwrap();
        std::thread::sleep(Duration::from_millis(600));
        assert!(dlg.last_reinvite_sdp().is_empty());
    }

    #[test]
    fn session_timer_parses_header_with_params() {
        let mut headers = HashMap::new();
        headers.insert("Session-Expires".into(), vec!["1;refresher=uac".into()]);
        let dlg = Arc::new(MockDialog::with_headers(headers));
        let call = Call::new_inbound(dlg.clone());
        call.accept().unwrap();
        std::thread::sleep(Duration::from_millis(600));
        assert!(!dlg.last_reinvite_sdp().is_empty());
    }

    // --- re-INVITE with recvonly/inactive ---

    #[test]
    fn inbound_reinvite_recvonly_triggers_hold() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.simulate_reinvite(&test_sdp("192.168.1.100", 5000, "recvonly", &[0]));
        assert_eq!(call.state(), CallState::OnHold);
    }

    #[test]
    fn inbound_reinvite_inactive_triggers_hold() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.simulate_reinvite(&test_sdp("192.168.1.100", 5000, "inactive", &[0]));
        assert_eq!(call.state(), CallState::OnHold);
    }

    // --- Mute / Unmute ---

    #[test]
    fn mute_when_not_active_returns_error() {
        let call = Call::new_inbound(mock_dlg());
        assert!(call.mute().is_err());
    }

    #[test]
    fn unmute_when_not_active_returns_error() {
        let call = Call::new_inbound(mock_dlg());
        assert!(call.unmute().is_err());
    }

    #[test]
    fn mute_when_already_muted_returns_error() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.mute().unwrap();
        assert!(call.mute().is_err());
    }

    #[test]
    fn unmute_when_not_muted_returns_error() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        assert!(call.unmute().is_err());
    }

    #[test]
    fn mute_when_on_hold_returns_error() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.hold().unwrap();
        assert!(call.mute().is_err());
    }

    #[test]
    fn unmute_when_ended_returns_error() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.end().unwrap();
        assert!(call.unmute().is_err());
    }

    #[test]
    fn on_mute_callback_fires() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        let (tx, rx) = mpsc::channel();
        call.on_mute(move || {
            let _ = tx.send(());
        });
        call.mute().unwrap();
        assert!(rx.recv_timeout(Duration::from_millis(200)).is_ok());
    }

    #[test]
    fn on_unmute_callback_fires() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        let (tx, rx) = mpsc::channel();
        call.on_unmute(move || {
            let _ = tx.send(());
        });
        call.mute().unwrap();
        call.unmute().unwrap();
        assert!(rx.recv_timeout(Duration::from_millis(200)).is_ok());
    }

    // --- RemoteURI / From / To / FromName ---

    #[test]
    fn remote_uri_from_dialog_header() {
        let mut h = HashMap::new();
        h.insert("From".into(), vec!["<sip:1001@pbx.example.com>".into()]);
        let call = Call::new_inbound(mock_dlg_with_headers(h));
        assert_eq!(call.remote_uri(), "sip:1001@pbx.example.com");
    }

    #[test]
    fn remote_uri_empty_when_no_from_header() {
        let call = Call::new_inbound(mock_dlg());
        assert_eq!(call.remote_uri(), "");
    }

    #[test]
    fn remote_uri_strips_display_name() {
        let mut h = HashMap::new();
        h.insert(
            "From".into(),
            vec!["\"Alice\" <sip:alice@example.com>".into()],
        );
        let call = Call::new_inbound(mock_dlg_with_headers(h));
        assert_eq!(call.remote_uri(), "sip:alice@example.com");
    }

    #[test]
    fn from_extracts_user_part() {
        let mut h = HashMap::new();
        h.insert(
            "From".into(),
            vec!["\"Alice\" <sip:+15551234567@pbx.example.com>;tag=abc".into()],
        );
        let call = Call::new_inbound(mock_dlg_with_headers(h));
        assert_eq!(call.from(), "+15551234567");
    }

    #[test]
    fn from_extension() {
        let mut h = HashMap::new();
        h.insert("From".into(), vec!["<sip:1001@10.200.1.2>".into()]);
        let call = Call::new_inbound(mock_dlg_with_headers(h));
        assert_eq!(call.from(), "1001");
    }

    #[test]
    fn from_empty_when_no_header() {
        let call = Call::new_inbound(mock_dlg());
        assert_eq!(call.from(), "");
    }

    #[test]
    fn to_extracts_user_part() {
        let mut h = HashMap::new();
        h.insert("To".into(), vec!["<sip:1002@pbx.example.com>".into()]);
        let call = Call::new_inbound(mock_dlg_with_headers(h));
        assert_eq!(call.to(), "1002");
    }

    #[test]
    fn to_empty_when_no_header() {
        let call = Call::new_inbound(mock_dlg());
        assert_eq!(call.to(), "");
    }

    #[test]
    fn from_name_quoted_display_name() {
        let mut h = HashMap::new();
        h.insert(
            "From".into(),
            vec!["\"Alice Smith\" <sip:alice@example.com>".into()],
        );
        let call = Call::new_inbound(mock_dlg_with_headers(h));
        assert_eq!(call.from_name(), "Alice Smith");
    }

    #[test]
    fn from_name_unquoted_display_name() {
        let mut h = HashMap::new();
        h.insert("From".into(), vec!["Alice <sip:alice@example.com>".into()]);
        let call = Call::new_inbound(mock_dlg_with_headers(h));
        assert_eq!(call.from_name(), "Alice");
    }

    #[test]
    fn from_name_empty_when_no_display_name() {
        let mut h = HashMap::new();
        h.insert("From".into(), vec!["<sip:1001@pbx.example.com>".into()]);
        let call = Call::new_inbound(mock_dlg_with_headers(h));
        assert_eq!(call.from_name(), "");
    }

    #[test]
    fn from_name_empty_when_no_header() {
        let call = Call::new_inbound(mock_dlg());
        assert_eq!(call.from_name(), "");
    }

    #[test]
    fn remote_ip_from_remote_sdp() {
        let call = Call::new_inbound(mock_dlg());
        call.set_remote_sdp(&test_sdp("192.168.1.200", 5004, "sendrecv", &[0]));
        assert_eq!(call.remote_ip(), "192.168.1.200");
    }

    #[test]
    fn remote_ip_empty_before_sdp() {
        let call = Call::new_inbound(mock_dlg());
        assert_eq!(call.remote_ip(), "");
    }

    #[test]
    fn remote_port_from_remote_sdp() {
        let call = Call::new_inbound(mock_dlg());
        call.set_remote_sdp(&test_sdp("192.168.1.200", 5004, "sendrecv", &[0]));
        assert_eq!(call.remote_port(), 5004);
    }

    #[test]
    fn remote_port_zero_before_sdp() {
        let call = Call::new_inbound(mock_dlg());
        assert_eq!(call.remote_port(), 0);
    }

    #[test]
    fn remote_media_updates_after_reinvite() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.set_remote_sdp(&test_sdp("192.168.1.100", 5000, "sendrecv", &[0]));
        assert_eq!(call.remote_ip(), "192.168.1.100");
        call.simulate_reinvite(&test_sdp("10.0.0.50", 6000, "sendrecv", &[0]));
        assert_eq!(call.remote_ip(), "10.0.0.50");
        assert_eq!(call.remote_port(), 6000);
    }

    // --- OnState callback ---

    #[test]
    fn on_state_fires_on_accept() {
        let call = Call::new_inbound(mock_dlg());
        let (tx, rx) = mpsc::channel();
        call.on_state(move |s| {
            let _ = tx.send(s);
        });
        call.accept().unwrap();
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            CallState::Active
        );
    }

    #[test]
    fn on_state_fires_on_reject() {
        let call = Call::new_inbound(mock_dlg());
        let (tx, rx) = mpsc::channel();
        call.on_state(move |s| {
            let _ = tx.send(s);
        });
        call.reject(486, "Busy Here").unwrap();
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            CallState::Ended
        );
    }

    #[test]
    fn on_state_fires_on_end() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        let (tx, rx) = mpsc::channel();
        call.on_state(move |s| {
            let _ = tx.send(s);
        });
        call.end().unwrap();
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            CallState::Ended
        );
    }

    #[test]
    fn on_state_fires_on_hold() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        let (tx, rx) = mpsc::channel();
        call.on_state(move |s| {
            let _ = tx.send(s);
        });
        call.hold().unwrap();
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            CallState::OnHold
        );
    }

    #[test]
    fn on_state_fires_on_resume() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.hold().unwrap();
        let (tx, rx) = mpsc::channel();
        call.on_state(move |s| {
            let _ = tx.send(s);
        });
        call.resume().unwrap();
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            CallState::Active
        );
    }

    #[test]
    fn on_state_fires_on_remote_bye() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        let (tx, rx) = mpsc::channel();
        call.on_state(move |s| {
            let _ = tx.send(s);
        });
        call.simulate_bye();
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            CallState::Ended
        );
    }

    #[test]
    fn on_state_fires_on_outbound_ringing() {
        let call = Call::new_outbound(mock_dlg(), DialOptions::default());
        let (tx, rx) = mpsc::channel();
        call.on_state(move |s| {
            let _ = tx.send(s);
        });
        call.simulate_response(180, "Ringing");
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            CallState::RemoteRinging
        );
    }

    #[test]
    fn on_state_fires_on_outbound_200() {
        let call = Call::new_outbound(mock_dlg(), DialOptions::default());
        let (tx, rx) = mpsc::channel();
        call.on_state(move |s| {
            let _ = tx.send(s);
        });
        call.simulate_response(200, "OK");
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            CallState::Active
        );
    }

    #[test]
    fn on_state_fires_on_early_media() {
        let opts = DialOptions {
            early_media: true,
            ..Default::default()
        };
        let call = Call::new_outbound(mock_dlg(), opts);
        let (tx, rx) = mpsc::channel();
        call.on_state(move |s| {
            let _ = tx.send(s);
        });
        call.simulate_response(183, "Session Progress");
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            CallState::EarlyMedia
        );
    }

    #[test]
    fn on_state_does_not_fire_on_mute() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        let (tx, rx) = mpsc::channel::<CallState>();
        call.on_state(move |s| {
            let _ = tx.send(s);
        });
        call.mute().unwrap();
        std::thread::sleep(Duration::from_millis(100));
        assert!(rx.try_recv().is_err());
    }

    #[test]
    fn on_state_tracks_full_lifecycle() {
        let call = Call::new_outbound(mock_dlg(), DialOptions::default());
        let (tx, rx) = mpsc::channel();
        call.on_state(move |s| {
            let _ = tx.send(s);
        });

        call.simulate_response(180, "Ringing");
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            CallState::RemoteRinging
        );

        call.simulate_response(200, "OK");
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            CallState::Active
        );

        call.hold().unwrap();
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            CallState::OnHold
        );

        call.resume().unwrap();
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            CallState::Active
        );

        call.end().unwrap();
        assert_eq!(
            rx.recv_timeout(Duration::from_millis(200)).unwrap(),
            CallState::Ended
        );
    }

    // --- Video ---

    #[test]
    fn has_video_false_for_audio_only() {
        let call = Call::new_outbound(mock_dlg(), DialOptions::default());
        assert!(!call.has_video());
        assert!(call.video_codec().is_none());
    }

    #[test]
    fn has_video_true_when_set() {
        let call = Call::new_outbound(mock_dlg(), DialOptions::default());
        call.set_video_codec(VideoCodec::H264);
        assert!(call.has_video());
        assert_eq!(call.video_codec(), Some(VideoCodec::H264));
    }

    #[test]
    fn video_rtp_reader_none_without_video_stream() {
        let call = Call::new_outbound(mock_dlg(), DialOptions::default());
        assert!(call.video_rtp_reader().is_none());
        assert!(call.video_rtp_writer().is_none());
    }

    #[test]
    fn video_reader_writer_none_pr3() {
        let call = Call::new_outbound(mock_dlg(), DialOptions::default());
        assert!(call.video_reader().is_none());
        assert!(call.video_writer().is_none());
    }

    #[test]
    fn mute_video_requires_active() {
        let call = Call::new_outbound(mock_dlg(), DialOptions::default());
        call.set_video_codec(VideoCodec::H264);
        assert!(matches!(call.mute_video(), Err(Error::InvalidState)));
    }

    #[test]
    fn mute_video_requires_video_stream() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        assert!(matches!(call.mute_video(), Err(Error::NoVideoStream)));
    }

    #[test]
    fn mute_video_double_returns_error() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.set_video_codec(VideoCodec::VP8);
        call.mute_video().unwrap();
        assert!(matches!(call.mute_video(), Err(Error::VideoAlreadyMuted)));
    }

    #[test]
    fn unmute_video_when_not_muted_returns_error() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.set_video_codec(VideoCodec::VP8);
        assert!(matches!(call.unmute_video(), Err(Error::VideoNotMuted)));
    }

    #[test]
    fn mute_unmute_video_round_trip() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.set_video_codec(VideoCodec::H264);
        call.mute_video().unwrap();
        call.unmute_video().unwrap();
        // Should be able to mute again.
        call.mute_video().unwrap();
    }

    #[test]
    fn audio_and_video_mute_independent() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.set_video_codec(VideoCodec::H264);

        // Mute audio — video should still work.
        call.mute().unwrap();
        call.mute_video().unwrap();
        call.unmute().unwrap();
        // Video is still muted.
        assert!(matches!(call.mute_video(), Err(Error::VideoAlreadyMuted)));
        call.unmute_video().unwrap();
    }

    #[test]
    fn request_keyframe_requires_active() {
        let call = Call::new_outbound(mock_dlg(), DialOptions::default());
        call.set_video_codec(VideoCodec::H264);
        assert!(matches!(call.request_keyframe(), Err(Error::InvalidState)));
    }

    #[test]
    fn request_keyframe_requires_video() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        assert!(matches!(call.request_keyframe(), Err(Error::NoVideoStream)));
    }

    #[test]
    fn video_codec_from_remote_sdp() {
        let call = Call::new_inbound(mock_dlg());
        // Build a remote SDP with video.
        let sdp = "v=0\r\n\
            o=- 0 0 IN IP4 10.0.0.1\r\n\
            s=-\r\n\
            c=IN IP4 10.0.0.1\r\n\
            t=0 0\r\n\
            m=audio 5000 RTP/AVP 0\r\n\
            a=rtpmap:0 PCMU/8000\r\n\
            m=video 5002 RTP/AVP 96\r\n\
            a=rtpmap:96 H264/90000\r\n\
            a=fmtp:96 profile-level-id=42e01f;packetization-mode=1\r\n";
        call.set_remote_sdp(sdp);
        assert!(call.has_video());
        assert_eq!(call.video_codec(), Some(VideoCodec::H264));
        // Check that video remote port was extracted.
        let inner = call.inner.lock();
        assert_eq!(inner.video_remote_port, 5002);
    }

    fn video_reinvite_sdp() -> &'static str {
        "v=0\r\n\
            o=- 0 0 IN IP4 10.0.0.1\r\n\
            s=-\r\n\
            c=IN IP4 10.0.0.1\r\n\
            t=0 0\r\n\
            m=audio 5000 RTP/AVP 0\r\n\
            a=rtpmap:0 PCMU/8000\r\n\
            a=sendrecv\r\n\
            m=video 5002 RTP/AVP 96\r\n\
            a=rtpmap:96 H264/90000\r\n\
            a=fmtp:96 profile-level-id=42e01f;packetization-mode=1\r\n\
            a=sendrecv\r\n"
    }

    #[test]
    fn handle_reinvite_accepts_video() {
        let call = Call::new_inbound(mock_dlg());
        call.set_local_media("192.168.1.100", 5000);
        call.accept().unwrap();
        assert!(!call.has_video());

        // Register handler that accepts.
        call.on_video_request(|req| req.accept());

        let reinvite_mock = mock_dlg();
        let reinvite_dlg: Arc<dyn Dialog> = Arc::clone(&reinvite_mock) as _;

        call.handle_reinvite(&reinvite_dlg, video_reinvite_sdp(), 10000, 20000);

        // Callback runs on spawn_callback thread — wait briefly.
        std::thread::sleep(Duration::from_millis(100));

        assert!(call.has_video());
        assert_eq!(call.video_codec(), Some(VideoCodec::H264));
        // 200 OK should be sent via the re-INVITE dialog.
        assert_eq!(reinvite_mock.last_response_code(), 200);
        let body_bytes = reinvite_mock.last_response_body();
        let body = String::from_utf8_lossy(&body_bytes);
        assert!(body.contains("m=video"), "SDP should contain video m= line");
        assert!(
            body.contains("H264/90000"),
            "SDP should contain H264 rtpmap"
        );
    }

    #[test]
    fn handle_reinvite_rejects_video_by_default() {
        let call = Call::new_inbound(mock_dlg());
        call.set_local_media("192.168.1.100", 5000);
        call.accept().unwrap();

        // No on_video_request handler — should auto-reject.
        let reinvite_mock = mock_dlg();
        let reinvite_dlg: Arc<dyn Dialog> = Arc::clone(&reinvite_mock) as _;

        call.handle_reinvite(&reinvite_dlg, video_reinvite_sdp(), 10000, 20000);

        assert!(!call.has_video());
        // Should still send 200 OK (with audio + m=video 0).
        assert_eq!(reinvite_mock.last_response_code(), 200);
        let body_bytes = reinvite_mock.last_response_body();
        let body = String::from_utf8_lossy(&body_bytes);
        assert!(
            body.contains("m=video 0"),
            "SDP should reject video with port 0"
        );
    }

    #[test]
    fn handle_reinvite_reject_explicit() {
        let call = Call::new_inbound(mock_dlg());
        call.set_local_media("192.168.1.100", 5000);
        call.accept().unwrap();

        call.on_video_request(|req| req.reject());

        let reinvite_mock = mock_dlg();
        let reinvite_dlg: Arc<dyn Dialog> = Arc::clone(&reinvite_mock) as _;

        call.handle_reinvite(&reinvite_dlg, video_reinvite_sdp(), 10000, 20000);

        std::thread::sleep(Duration::from_millis(100));

        assert!(!call.has_video());
        assert_eq!(reinvite_mock.last_response_code(), 200);
        let body_bytes = reinvite_mock.last_response_body();
        let body = String::from_utf8_lossy(&body_bytes);
        assert!(
            body.contains("m=video 0"),
            "SDP should reject video with port 0"
        );
    }

    #[test]
    fn handle_reinvite_fires_on_video_callback() {
        let call = Call::new_inbound(mock_dlg());
        let reinvite_dlg: Arc<dyn Dialog> = mock_dlg();
        call.set_local_media("192.168.1.100", 5000);
        call.accept().unwrap();

        let (tx_video, rx_video) = mpsc::channel();
        call.on_video(move || {
            let _ = tx_video.send(());
        });
        call.on_video_request(|req| req.accept());

        call.handle_reinvite(&reinvite_dlg, video_reinvite_sdp(), 10000, 20000);

        assert!(
            rx_video.recv_timeout(Duration::from_secs(2)).is_ok(),
            "on_video callback should have fired"
        );
    }

    #[test]
    fn handle_reinvite_hold_delegates() {
        let call = Call::new_inbound(mock_dlg());
        call.set_local_media("192.168.1.100", 5000);
        call.accept().unwrap();

        let reinvite_dlg: Arc<dyn Dialog> = mock_dlg();
        let hold_sdp = "v=0\r\n\
            o=- 0 0 IN IP4 10.0.0.1\r\n\
            s=-\r\n\
            c=IN IP4 10.0.0.1\r\n\
            t=0 0\r\n\
            m=audio 5000 RTP/AVP 0\r\n\
            a=rtpmap:0 PCMU/8000\r\n\
            a=sendonly\r\n";

        call.handle_reinvite(&reinvite_dlg, hold_sdp, 10000, 20000);
        assert_eq!(call.state(), CallState::OnHold);
        assert!(!call.has_video());
    }

    #[test]
    fn handle_reinvite_on_ended_call_is_noop() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.end().unwrap();

        let reinvite_dlg: Arc<dyn Dialog> = mock_dlg();
        call.handle_reinvite(&reinvite_dlg, video_reinvite_sdp(), 10000, 20000);
        assert!(!call.has_video());
    }

    #[test]
    fn video_downgrade_stops_pipeline() {
        let call = Call::new_inbound(mock_dlg());
        call.set_local_media("192.168.1.100", 5000);
        call.accept().unwrap();

        // Set up video via direct mutation (simulates an active video call).
        {
            let mut inner = call.inner.lock();
            inner.video_codec = Some(VideoCodec::H264);
        }
        assert!(call.has_video());

        // Remote sends re-INVITE with m=video 0 (downgrade).
        let reinvite_dlg: Arc<dyn Dialog> = mock_dlg();
        let downgrade_sdp = "v=0\r\n\
            o=- 0 0 IN IP4 10.0.0.1\r\n\
            s=-\r\n\
            c=IN IP4 10.0.0.1\r\n\
            t=0 0\r\n\
            m=audio 5000 RTP/AVP 0\r\n\
            a=rtpmap:0 PCMU/8000\r\n\
            a=sendrecv\r\n\
            m=video 0 RTP/AVP 0\r\n";

        call.handle_reinvite(&reinvite_dlg, downgrade_sdp, 10000, 20000);
        assert!(!call.has_video());
    }

    #[test]
    fn add_video_sends_reinvite() {
        let dlg = mock_dlg();
        let call = Call::new_inbound(dlg.clone());
        call.set_local_media("192.168.1.100", 5000);
        call.accept().unwrap();

        call.add_video(&[VideoCodec::H264], 10000, 20000).unwrap();

        let sdp = dlg.last_reinvite_sdp();
        assert!(
            sdp.contains("m=video"),
            "re-INVITE SDP should have video m= line"
        );
        assert!(sdp.contains("H264/90000"), "re-INVITE SDP should have H264");
    }

    #[test]
    fn add_video_requires_active() {
        let call = Call::new_outbound(mock_dlg(), DialOptions::default());
        assert!(matches!(
            call.add_video(&[VideoCodec::H264], 10000, 20000),
            Err(Error::InvalidState)
        ));
    }

    #[test]
    fn add_video_when_already_active_returns_error() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();
        call.set_video_codec(VideoCodec::H264);
        assert!(call.add_video(&[VideoCodec::VP8], 10000, 20000).is_err());
    }

    #[test]
    fn multiple_on_ended_callbacks_all_fire() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();

        let count = Arc::new(std::sync::atomic::AtomicU32::new(0));

        let c1 = Arc::clone(&count);
        call.on_ended(move |_| {
            c1.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        });
        let c2 = Arc::clone(&count);
        call.on_ended(move |_| {
            c2.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        });

        call.end().unwrap();
        // Callbacks fire via spawn_callback — wait briefly.
        std::thread::sleep(std::time::Duration::from_millis(100));
        assert_eq!(count.load(std::sync::atomic::Ordering::Relaxed), 2);
    }

    #[test]
    fn multiple_on_state_callbacks_all_fire() {
        let call = Call::new_inbound(mock_dlg());

        let count = Arc::new(std::sync::atomic::AtomicU32::new(0));

        let c1 = Arc::clone(&count);
        call.on_state(move |_| {
            c1.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        });
        let c2 = Arc::clone(&count);
        call.on_state(move |_| {
            c2.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        });

        call.accept().unwrap();
        std::thread::sleep(std::time::Duration::from_millis(100));
        // Active state fires both callbacks.
        assert_eq!(count.load(std::sync::atomic::Ordering::Relaxed), 2);
    }

    #[test]
    fn multiple_on_hold_callbacks_all_fire() {
        let call = Call::new_inbound(mock_dlg());
        call.accept().unwrap();

        let count = Arc::new(std::sync::atomic::AtomicU32::new(0));
        let c1 = Arc::clone(&count);
        call.on_hold(move || {
            c1.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        });
        let c2 = Arc::clone(&count);
        call.on_hold(move || {
            c2.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        });

        let hold_sdp = "v=0\r\no=- 1 1 IN IP4 10.0.0.1\r\ns=-\r\nc=IN IP4 10.0.0.1\r\nt=0 0\r\nm=audio 20000 RTP/AVP 0\r\na=sendonly\r\n";
        call.simulate_reinvite(hold_sdp);
        std::thread::sleep(std::time::Duration::from_millis(100));
        assert_eq!(count.load(std::sync::atomic::Ordering::Relaxed), 2);
    }
}