sew-call-client 0.9.6

Sew's native voice engine: LiveKit-protocol signalling and reconnect against Sew's media server, str0m transport with TURN over UDP, TCP and TLS (relay-only when asked), MLS call keys with the mandatory E2EE checks over the call credential and the call socket, the device store, and the kessel-audio bridge.
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
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
//! The tokio driver of one call: signalling (through `sew-lk-compat`'s Sans-IO session), the
//! transport, the peer connection, the frame path through the keys, reconnect
//! and the call credential's renewal.
//!
//! Reconnect, as Sew's media server expects it (rewritten from Sew's call recorder's
//! participant task):
//! - the WebSocket drops while the PC is up → **resume**: a new WebSocket with
//!   `JoinRequest.reconnect` and the participant sid, the PC kept, ICE restarted on
//!   `ReconnectResponse`;
//! - the PC fails (ICE down 2 s), the TURN allocation is lost, a resume is refused, or the
//!   engine says `Leave{RECONNECT}` → **full reconnect**: a new WebSocket and a new
//!   JoinResponse (so fresh TURN credentials), a new transport and PC, the microphone
//!   re-published;
//! - both with the engine's refresh token, backing off 250 ms → 4 s, inside the reconnect window
//!   (20 s) from the first loss;
//! - after the window, or when the engine refuses the token: a **re-join** through the
//!   [`JoinProvider`] (a new join answer, credential and key session).
//!
//! A **network change** the host reports ([`crate::Call::network_changed`]) runs the resume
//! on purpose: the WebSocket is replaced at once (resume), a fresh transport is opened on the
//! new network in parallel (the JoinResponse's ICE servers: a new TURN allocation over a new
//! socket, new host candidates), swapped into the kept PC (the old local candidates
//! invalidated), and the resume's ICE restart then runs over it. The old transport's loss
//! meanwhile is expected and does not force a full reconnect; a failed open, or a restart that
//! does not connect within [`RESTART_GRACE`], does.
//!
//! Recording (Sew 0.7.3): a join that Sew refuses `409 recording_consent_required` is **held**
//! ([`hold`]: no media, no keys) until the host answers the notice (the join again, with the
//! answer as `recording_notice`) or leaves; a re-join refused that way holds the same way. In a
//! call, the call's recording as Sew says it (the join answer, a move, the call socket's
//! `recording_updated` and READY, a consent answer) is fed to the keys
//! ([`KeySession::recording`]) and shown to the host; the engine never sets it from its own
//! state.

use std::collections::{BTreeMap, HashMap, VecDeque};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use bytes::Bytes;
use sew_lk_compat::session::LeaveAction;
use sew_lk_compat::{ClientInfoOpts, JoinParams, Session, SessionEvent};
use sew_lkproto::livekit::{
    SignalRequest, SignalResponse, UpdateSubscription, leave_request, signal_request,
    signal_response,
};
use tokio::sync::{broadcast, mpsc, watch};
use tokio::task::JoinHandle;

use crate::api;
use crate::call::{
    BusyGuard, CallCounters, CallError, CallErrorEvent, CallEvent, CallMoved, CallRecording,
    CallSecurity, CallSnapshot, CallState, Cmd, EndReason, OpusFrame, Participant, RecvItem,
    RecvOpus, ServerControls, Speaking,
};
use crate::config::ClientConfig;
use crate::e2ee::{
    CredentialHandle, E2eeContext, E2eeError, E2eeEvent, E2eeEvents, E2eeProvider, KeySession,
    RemoteTrack, Subscribe,
};
use crate::pc::{IceState, Pc, PcEvent};
use crate::provider::{
    CallCredential, ConsentAnswer, ConsentRequired, JoinAnswer, JoinProvider, JoinRequest,
    ProviderError, RecordingControl, RecordingRequest, RejoinReason,
};
use crate::signal::{self, ConnectError, SignalIn, SignalLink};
use crate::stats::{BeaconOutcome, CallStatsReport, Meter, PlayoutStats, StatsWindow};
use crate::transport::{Gather, LocalKind, Transport, TransportError, TransportEvent};
use crate::video::VideoRecvItem;
use crate::video::publish::{Ctx as VideoCtx, LeaseApi, Publisher, VideoStep};
use crate::video::subscribe::{Out as VideoOut, Subscriptions};
use sew_proto::e2ee::ConsentState;
use sew_proto::id::Id;
use sew_proto::recording::{Recording, RecordingControls, RecordingNotice, RecordingRef};

/// First retry delay.
const BACKOFF_MIN: Duration = Duration::from_millis(250);
/// Longest retry delay.
const BACKOFF_MAX: Duration = Duration::from_secs(4);
/// ICE `disconnected` this long → full reconnect.
const PC_FAIL_GRACE: Duration = Duration::from_secs(2);
/// After a network change's transport swap, ICE must connect within this long, else full
/// reconnect.
const RESTART_GRACE: Duration = Duration::from_secs(5);
/// A sequence gap is reported lost after this long.
const LOSS_GRACE: Duration = Duration::from_millis(60);
/// Gaps longer than this are not marked packet by packet (a restart, not loss).
const LOSS_MAX_GAP: u16 = 50;
/// Speaking events at most this often.
const SPEAKING_EVERY: Duration = Duration::from_millis(100);
/// A credential renewal that failed on the network, with a `5xx` or a `429` is retried after
/// this, doubling up to [`RENEW_RETRY_MAX`] and never later than half the time the credential
/// has left. A renewal whose answer was lost may have rotated the secret: the old one works for
/// 30 s more, and these retries fall inside that grace.
const RENEW_RETRY_MIN: Duration = Duration::from_secs(1);
/// Longest wait between renewal retries.
const RENEW_RETRY_MAX: Duration = Duration::from_secs(8);
/// Shortest wait between renewal retries (near the credential's expiry).
const RENEW_RETRY_FLOOR: Duration = Duration::from_millis(200);
/// How long a leave waits for Sew's answer.
const LEAVE_TIMEOUT: Duration = Duration::from_secs(3);
/// The track name of the microphone.
const MIC_NAME: &str = "microphone";
/// How long an engine `Disconnect` or the key group's removal waits for Sew's own reason (the
/// call socket's self copy or `4011`) before the call ends with the key group's reason, else
/// the engine's (`kicked` or `room_closed`): media, the key group and the call socket may
/// arrive in any order (Sew 0.7.2).
pub(crate) const END_REASON_GRACE: Duration = Duration::from_millis(1_500);

/// The engine's own end of a `Disconnect` leave (its `DisconnectReason`): 4
/// PARTICIPANT_REMOVED and 2 DUPLICATE_IDENTITY are `kicked`, 5 ROOM_DELETED and 10
/// ROOM_CLOSED are `room_closed`; `None` for the rest (a server shutdown or a migration may
/// come back, so it reconnects within the window).
fn engine_end_reason(reason: i32) -> Option<EndReason> {
    match reason {
        2 | 4 => Some(EndReason::Kicked),
        5 | 10 => Some(EndReason::RoomClosed),
        _ => None,
    }
}

/// The engine's end in a signalling response from a link the engine has given up on: a
/// `Disconnect` leave that names a removal or a closed room. Not 2 DUPLICATE_IDENTITY: on
/// that link it is this engine's own reconnect taking the participant over.
fn parting_end(r: &SignalResponse) -> Option<EndReason> {
    let Some(signal_response::Message::Leave(l)) = &r.message else {
        return None;
    };
    match leave_request::Action::try_from(l.action) {
        Ok(leave_request::Action::Resume | leave_request::Action::Reconnect) => None,
        _ if l.reason == 2 => None,
        _ => engine_end_reason(l.reason),
    }
}

/// A signalling link given up on because media went (the engine's TURN allocation or ICE),
/// kept reading until it closes or [`END_REASON_GRACE`] passes: an engine that removes this
/// participant or closes the room drops the TURN allocation and sends the `Disconnect` leave
/// at the same moment, so the leave may come after the media's loss.
/// The video publisher's view of the engine for one call (split field borrows).
macro_rules! video_cx {
    ($s:ident, $now:expr) => {{
        let joined = $s.session.joined();
        VideoCtx {
            pc: $s.pc.as_mut(),
            session: &mut $s.session,
            keys: $s.keys.as_ref(),
            stream: $s.sid.as_deref().unwrap_or(""),
            media_up: $s.media_up,
            joined,
            now: $now,
            events: &$s.shared.events,
        }
    }};
}

struct Parting {
    id: u64,
    _link: SignalLink,
    until: Instant,
    /// A re-join held back until the link has had its say.
    rejoin: Option<RejoinReason>,
}

/// What the [`crate::Call`] handle and the engine task share.
pub(crate) struct Shared {
    pub(crate) events: broadcast::Sender<CallEvent>,
    pub(crate) snapshot: Arc<Mutex<CallSnapshot>>,
    pub(crate) send_queue_drops: AtomicU64,
    /// The stats windows and the beacon's terms ([`crate::Call::stats`]).
    pub(crate) stats: Mutex<CallStatsReport>,
    /// The audio pipeline's playout counters ([`crate::Call::set_playout_stats`]).
    pub(crate) playout: Mutex<Option<Arc<dyn PlayoutStats>>>,
    /// The noise removal of the call's audio ([`crate::AudioBridge::start_with_noise`]).
    pub(crate) noise: Mutex<Option<Arc<dyn crate::noise::NoiseSource>>>,
    /// Sew refused a sample with `call_stats_off`: no more samples this call.
    pub(crate) beacon_stopped: AtomicBool,
    /// The join's media policy with the latest hints ([`crate::Call::media_policy`]).
    pub(crate) policy: Mutex<Option<sew_proto::voice::MediaPolicy>>,
    /// The send-side video counters ([`crate::Call::video_stats`]).
    pub(crate) video_stats: Arc<Mutex<crate::video::VideoSendStats>>,
    /// The video codecs the call's media connections offer, fixed at the join
    /// ([`crate::Call::video_codecs`]).
    pub(crate) video_codecs: crate::video::codec_pref::CodecSet,
    /// The engine's codec preference, live ([`crate::Call::video_codec_preference`]).
    pub(crate) codec_settings: Arc<crate::video::codec_pref::CodecSettings>,
}

impl Shared {
    /// The call's noise removal state, while its audio reports one.
    pub(crate) fn noise_removal(&self) -> Option<crate::NoiseRemovalState> {
        let src = self.noise.lock().ok().and_then(|n| n.clone())?;
        src.noise_state()
    }

    /// Records a finished window: [`crate::Call::stats`] and [`CallEvent::Stats`].
    pub(crate) fn record_window(&self, w: StatsWindow) {
        if let BeaconOutcome::Refused {
            reason: Some(r), ..
        } = &w.beacon
            && r == sew_proto::voice::reasons::CALL_STATS_OFF
        {
            self.beacon_stopped.store(true, Ordering::Release);
        }
        if let Ok(mut s) = self.stats.lock() {
            s.push(w.clone());
        }
        let _ = self.events.send(CallEvent::Stats(Box::new(w)));
    }
}

/// Everything the engine task starts with.
pub(crate) struct Start {
    pub(crate) cfg: ClientConfig,
    pub(crate) e2ee: Arc<dyn E2eeProvider>,
    pub(crate) provider: Arc<dyn JoinProvider>,
    pub(crate) req: JoinRequest,
    pub(crate) first: First,
    pub(crate) shared: Arc<Shared>,
    pub(crate) cmd_rx: mpsc::UnboundedReceiver<Cmd>,
    pub(crate) push_rx: mpsc::Receiver<OpusFrame>,
    pub(crate) frames_tx: mpsc::Sender<RecvItem>,
    pub(crate) video_tx: mpsc::Sender<VideoRecvItem>,
    pub(crate) busy: BusyGuard,
}

/// The first join's outcome.
pub(crate) enum First {
    /// Sew's answer: the engine starts.
    Answer(Box<JoinAnswer>),
    /// Sew's `409 recording_consent_required`: the call is held for the person's answer.
    Held(Box<ConsentRequired>),
}

/// What outlives one join: the call's handle side, settings and counters, handed from a held
/// join to the engine and back.
struct Parts {
    cfg: ClientConfig,
    tls: Arc<rustls::ClientConfig>,
    http: reqwest::Client,
    e2ee: Arc<dyn E2eeProvider>,
    provider: Arc<dyn JoinProvider>,
    req: JoinRequest,
    shared: Arc<Shared>,
    cmd_rx: mpsc::UnboundedReceiver<Cmd>,
    push_rx: mpsc::Receiver<OpusFrame>,
    frames_tx: mpsc::Sender<RecvItem>,
    video_tx: mpsc::Sender<VideoRecvItem>,
    /// The video receive side (its sinks outlive a hold).
    video: Subscriptions,
    /// The app's call slot: released the moment the call is over (before a leave answers),
    /// never later than the engine's teardown.
    busy: Option<BusyGuard>,
    counters: CallCounters,
    vpub: Publisher,
}

/// Starts the call's task.
pub(crate) fn spawn(s: Start) -> Result<(), String> {
    let tls = crate::config::tls_config(&s.cfg).map_err(|e| format!("TLS: {e}"))?;
    let http = api::http_client(&tls)?;
    let vpub = Publisher::new(s.shared.video_stats.clone());
    let video_codecs = s.shared.video_codecs;
    let parts = Parts {
        cfg: s.cfg,
        tls,
        http,
        e2ee: s.e2ee,
        provider: s.provider,
        req: s.req,
        shared: s.shared,
        cmd_rx: s.cmd_rx,
        push_rx: s.push_rx,
        frames_tx: s.frames_tx,
        video_tx: s.video_tx,
        video: Subscriptions::new(Instant::now()).decoding(video_codecs),
        busy: Some(s.busy),
        counters: CallCounters::default(),
        vpub,
    };
    tokio::spawn(supervise(parts, s.first));
    Ok(())
}

/// The call: the engine for each answer, a hold for each `409 recording_consent_required`,
/// until it ends.
async fn supervise(mut parts: Parts, mut next: First) {
    loop {
        match next {
            First::Answer(answer) => {
                let mut e = Engine::new(parts, *answer);
                e.run().await;
                match e.into_held() {
                    Some((p, c)) => {
                        parts = p;
                        next = First::Held(c);
                    }
                    None => return,
                }
            }
            First::Held(c) => match hold(&mut parts, *c).await {
                Some(answer) => next = First::Answer(Box::new(answer)),
                None => return,
            },
        }
    }
}

/// A held join (`consent_required`): no media and no keys; frames are dropped. Waits for the
/// host: an answer joins again with it as `recording_notice` (Sew's answer starts the engine; a
/// changed notice holds again with the new one; any other refusal ends the call), a leave
/// ends it. Mute and deafen are kept for the join.
async fn hold(p: &mut Parts, first: ConsentRequired) -> Option<JoinAnswer> {
    let mut c = first;
    let mut frames_open = true;
    held_publish(p, &c);
    loop {
        loop {
            let cmd = tokio::select! {
                biased;
                cmd = p.cmd_rx.recv() => cmd,
                f = p.push_rx.recv(), if frames_open => {
                    match f {
                        Some(_) => p.counters.frames_not_sent += 1,
                        None => frames_open = false,
                    }
                    continue;
                }
            };
            match cmd {
                None | Some(Cmd::Dropped) => {
                    held_end(p, EndReason::Left);
                    p.busy = None;
                    return None;
                }
                Some(Cmd::Leave(reply)) => {
                    held_end(p, EndReason::Left);
                    // The slot is free before the leave answers.
                    p.busy = None;
                    let _ = reply.send(());
                    return None;
                }
                Some(Cmd::NetworkChanged) => {
                    // Held: no connection is open; the join after the answer uses the network
                    // of that moment.
                    p.counters.network_changes += 1;
                }
                Some(Cmd::Video(c)) => {
                    // Held: no tracks; the sinks are kept for the join.
                    let mut out = VideoOut::default();
                    p.video.sink(Instant::now(), c, &mut out);
                }
                // Held: no media, so no video.
                Some(Cmd::Publish(v)) => v.refuse(),
                // Held: the person has no voice entry in the room yet.
                Some(Cmd::Recording { reply, .. }) => {
                    let _ = reply.send(Err(CallError::Provider(ProviderError::Refused {
                        code: sew_proto::recording::reasons::NOT_IN_VOICE.to_owned(),
                        detail: serde_json::Value::Null,
                    })));
                }
                Some(Cmd::Mute {
                    muted,
                    deafened,
                    reply,
                }) => {
                    if let Some(d) = deafened {
                        p.req.deafened = d;
                    }
                    if let Some(m) = muted {
                        p.req.muted = m;
                    }
                    p.req.muted |= p.req.deafened;
                    let _ = reply.send(());
                }
                Some(Cmd::Consent {
                    granted,
                    notice_version,
                    reply,
                }) => {
                    p.req.recording_notice = Some(RecordingNotice {
                        recording_id: c.consent_prompt.recording_id,
                        consent: Some(granted),
                        notice_version: Some(
                            notice_version.unwrap_or(c.consent_prompt.notice_version),
                        ),
                    });
                    tracing::info!(target: "sew_call_client", granted, "joining with the recording notice answered");
                    match p.provider.join(p.req.clone()).await {
                        Ok(a) => {
                            let _ = reply.send(Ok(()));
                            return Some(a);
                        }
                        Err(ProviderError::ConsentRequired(next)) => {
                            // The notice changed meanwhile: hold with the current one, in the
                            // snapshot before the answer, so a host that reads the state after
                            // `consent` returns sees the new notice.
                            c = (*next).clone();
                            held_publish(p, &c);
                            let _ = reply.send(Err(CallError::Provider(
                                ProviderError::ConsentRequired(next),
                            )));
                            break;
                        }
                        Err(e) => {
                            held_failed(p, &e);
                            let _ = reply.send(Err(CallError::Provider(e)));
                            return None;
                        }
                    }
                }
            }
        }
    }
}

/// A word from Sew on the person's Record and Stop, into the call's snapshot: any word says
/// the server computes them; a value for the call's room (`here`) replaces the held one unless
/// its `rev` is older or it says the same. `Some(value)` when the host should hear of it (a new
/// value, or the server's first word), with the value now.
pub(crate) fn merge_controls(
    s: &mut CallSnapshot,
    here: bool,
    controls: Option<&RecordingControls>,
) -> Option<Option<ServerControls>> {
    let first = !s.server_controls;
    s.server_controls = true;
    let next = controls.filter(|_| here).map(ServerControls::from_sew);
    let newer = match (next, s.recording_controls) {
        (Some(n), Some(cur)) => n.rev >= cur.rev && n != cur,
        (Some(_), None) => true,
        (None, _) => false,
    };
    if newer {
        s.recording_controls = next;
    }
    (newer || first).then_some(s.recording_controls)
}

/// The call moved to another room: the held Record and Stop no longer apply. True when there
/// was a value (the host hears `None`).
pub(crate) fn clear_controls_in(s: &mut CallSnapshot) -> bool {
    s.recording_controls.take().is_some()
}

/// The held state and the notice of a join held from the start, in the snapshot (no event:
/// nobody has subscribed yet).
pub(crate) fn preset_held(snapshot: &Mutex<CallSnapshot>, c: &ConsentRequired) {
    if let Ok(mut s) = snapshot.lock() {
        s.state = CallState::ConsentRequired {
            recording_id: c.consent_prompt.recording_id.to_string(),
            notice_version: c.consent_prompt.notice_version,
        };
        s.recording = Some(CallRecording::from_consent_required(c));
    }
}

/// The held state and its notice, to the host.
fn held_publish(p: &Parts, c: &ConsentRequired) {
    let st = CallState::ConsentRequired {
        recording_id: c.consent_prompt.recording_id.to_string(),
        notice_version: c.consent_prompt.notice_version,
    };
    let rec = CallRecording::from_consent_required(c);
    let had_participants = {
        let Ok(mut s) = p.shared.snapshot.lock() else {
            return;
        };
        let had = !s.participants.is_empty();
        s.state = st.clone();
        s.participants.clear();
        s.recording = Some(rec.clone());
        s.counters = p.counters.clone();
        had
    };
    if had_participants {
        let _ = p.shared.events.send(CallEvent::Participants(Vec::new()));
    }
    let _ = p
        .shared
        .events
        .send(CallEvent::Recording(Some(Box::new(rec))));
    let _ = p.shared.events.send(CallEvent::State(st));
}

/// A held call is over.
fn held_end(p: &Parts, reason: EndReason) {
    let st = CallState::Ended { reason };
    let had = {
        let Ok(mut s) = p.shared.snapshot.lock() else {
            return;
        };
        s.state = st.clone();
        s.counters = p.counters.clone();
        s.recording.take().is_some()
    };
    if had {
        let _ = p.shared.events.send(CallEvent::Recording(None));
    }
    let _ = p.shared.events.send(CallEvent::State(st));
}

/// The join with the answer was refused (not for the notice): the call ends as a re-join's
/// refusal would.
fn held_failed(p: &Parts, e: &ProviderError) {
    let reason = match e {
        ProviderError::SigninRequired => EndReason::SigninRequired,
        ProviderError::Refused { code, detail } => {
            let _ = p.shared.events.send(CallEvent::Error(CallErrorEvent {
                code: code.clone(),
                detail: detail.to_string(),
            }));
            EndReason::Refused(code.clone())
        }
        e => {
            let _ = p.shared.events.send(CallEvent::Error(CallErrorEvent {
                code: "network".to_owned(),
                detail: e.to_string(),
            }));
            EndReason::Network
        }
    };
    held_end(p, reason);
}

/// A consent answer, or a Record or Stop (`control`), sent through the host, back to the
/// engine.
struct Consented {
    result: Result<Recording, ProviderError>,
    granted: bool,
    notice_version: Option<u32>,
    /// A Record or Stop's answer (`granted` and `notice_version` unused).
    control: Option<RecordingControl>,
    reply: tokio::sync::oneshot::Sender<Result<(), CallError>>,
}

/// The extended RTP sequence number of the microphone's first packet in a new media session
/// (a new PC: a new DTLS handshake, so a new SRTP context on both ends).
///
/// Its rollover counter is always 0. The media server starts every new SSRC at rollover
/// counter 0 (RFC 3711 §3.3.1: a receiver takes the first packet's sequence number with no
/// rollover unless told otherwise out of band, and nothing here tells it), so a first packet
/// carrying the previous session's extended number (rollover 1 once that session had passed
/// 65535) would fail SRTP authentication there, and so would every later one. The start is
/// random in [0, 2^15), as browsers pick theirs, so a session runs at least 2^15 packets
/// (about 11 minutes of 20 ms audio) before its first wrap, which the receiver then follows.
fn fresh_send_seq(cfg: &ClientConfig) -> u64 {
    #[cfg(feature = "testing")]
    if let Some(s) = cfg.testing.first_seq {
        return u64::from(s);
    }
    let _ = cfg;
    u64::from(rand::random::<u16>() & 0x7fff)
}

impl Engine {
    fn new(p: Parts, answer: JoinAnswer) -> Engine {
        let now = Instant::now();
        let (sig_tx, sig_rx) = mpsc::unbounded_channel();
        let (e2ee_tx, e2ee_rx) = mpsc::unbounded_channel();
        let (consent_tx, consent_rx) = mpsc::unbounded_channel();
        let (cred_tx, _) = watch::channel(answer.call_credential().cloned());
        let relay_only = answer.join.media.as_ref().is_some_and(|m| m.relay_only);
        let self_member = answer.join.state.member_id.to_string();
        let speak_denied = answer.join.state.speak_denied;
        let channel = answer.join.state.channel_id;
        let terms = answer.join.stats;
        if let Ok(mut r) = p.shared.stats.lock() {
            r.terms = terms;
        }
        let req = p.req;
        let mut vpub = p.vpub;
        vpub.joined_with(answer.join.media.as_ref());
        if let Ok(mut m) = p.shared.policy.lock() {
            m.clone_from(&answer.join.media);
        }
        let mut e = Engine {
            cfg: p.cfg,
            tls: p.tls,
            http: p.http,
            e2ee: p.e2ee,
            provider: p.provider,
            req: req.clone(),
            answer,
            shared: p.shared,
            cmd_rx: p.cmd_rx,
            push_rx: p.push_rx,
            frames_tx: p.frames_tx,
            video_tx: p.video_tx,
            video: p.video,
            video_refused: std::collections::HashSet::new(),
            busy: p.busy,
            held: None,
            recording: None,
            channel,
            consent_tx,
            consent_rx,
            cred_tx,
            renew_at: None,
            renewing: None,
            renew_retry: RENEW_RETRY_MIN,
            renew_held_end: None,
            keys: None,
            keys_active: false,
            keys_start: None,
            e2ee_tx,
            e2ee_rx,
            session: Session::new(now),
            link: None,
            link_id: 0,
            parting: None,
            sig_tx,
            sig_rx,
            attempt: None,
            rejoining: None,
            opening: None,
            rebinding: None,
            resume_waits_rebind: false,
            restart_deadline: None,
            ice_servers: Vec::new(),
            transport: None,
            pc: None,
            pc_down_since: None,
            relay_only,
            identity: None,
            sid: None,
            cid: format!("mic-{:08x}", rand::random::<u32>()),
            track_sid: None,
            published: None,
            send: None,
            // Set for each new PC (`on_opened`).
            send_seq: 0,
            media_up: false,
            reconnect: None,
            connect_deadline: now + Duration::from_secs(0),
            moving: false,
            tracks: HashMap::new(),
            next_track_id: 1,
            self_muted: req.muted,
            deafened: req.deafened,
            muted_before_deafen: req.muted,
            server_muted: false,
            self_member,
            joined_speak_denied: speak_denied,
            mic_denied: false,
            speak_was_denied: speak_denied,
            publishing: false,
            cid_on_pc: false,
            pending_end: None,
            members: HashMap::new(),
            voice: HashMap::new(),
            engine_levels: HashMap::new(),
            local_level: 0.0,
            next_speaking: now,
            next_snapshot: now,
            last_speaking: Vec::new(),
            state: CallState::Connecting,
            counters: p.counters,
            ended: None,
            meter: Meter::new(now, terms.as_ref()),
            terms,
            vpub,
        };
        e.connect_deadline = now + e.cfg.connect_timeout;
        e
    }

    /// After [`Engine::run`]: the parts for a hold, when a re-join was refused for the notice.
    fn into_held(self) -> Option<(Parts, Box<ConsentRequired>)> {
        let Engine {
            cfg,
            tls,
            http,
            e2ee,
            provider,
            req,
            shared,
            cmd_rx,
            push_rx,
            frames_tx,
            video_tx,
            video,
            busy,
            counters,
            held,
            mut vpub,
            ..
        } = self;
        let held = held?;
        vpub.close("held");
        Some((
            Parts {
                cfg,
                tls,
                http,
                e2ee,
                provider,
                req,
                shared,
                cmd_rx,
                push_rx,
                frames_tx,
                video_tx,
                video,
                busy,
                counters,
                vpub,
            },
            held,
        ))
    }
}

/// One beacon request (sent off the engine task: a slow door never holds the call up).
struct BeaconPost {
    http: reqwest::Client,
    base: url::Url,
    token: String,
    sample: sew_proto::voice::CallStatsSample,
}

impl BeaconPost {
    async fn send(self) -> BeaconOutcome {
        api::stats(&self.http, &self.base, &self.token, &self.sample).await
    }
}

/// A closed window: to send, or done (nothing to send, and why).
enum Prepared {
    Send(StatsWindow, Box<BeaconPost>),
    Done(StatsWindow),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
    Resume,
    Full,
}

#[derive(Debug)]
struct Reconnect {
    /// The first connect's retries (state stays `connecting`; nothing is counted).
    initial: bool,
    kind: Kind,
    deadline: Instant,
    next_try: Instant,
    backoff: Duration,
    attempt: u32,
}

impl Reconnect {
    /// When the loop must wake for this reconnect: the window's end and the next try, each
    /// only while the loop's timeout can act on it. A re-join under way holds both (its answer
    /// sets a new window, or ends the call), and the next try waits while a connect is under way
    /// (`connecting`). A deadline the timeout can't act on would stay in the past and wake the
    /// loop at once on every turn.
    fn wake(&self, rejoining: bool, connecting: bool) -> Option<Instant> {
        if rejoining {
            return None;
        }
        if connecting {
            Some(self.deadline)
        } else {
            Some(self.deadline.min(self.next_try))
        }
    }
}

struct SendPath {
    mid: String,
    pt: u8,
    ssrc: u32,
}

struct RemoteSlot {
    id: u64,
    identity: String,
    allowed: Subscribe,
    announced: bool,
    unsubscribed: bool,
    highest: Option<u64>,
    gaps: VecDeque<(u64, Instant)>,
}

type Attempt = JoinHandle<Result<SignalLink, ConnectError>>;

struct Engine {
    cfg: ClientConfig,
    tls: Arc<rustls::ClientConfig>,
    http: reqwest::Client,
    e2ee: Arc<dyn E2eeProvider>,
    provider: Arc<dyn JoinProvider>,
    req: JoinRequest,
    answer: JoinAnswer,
    shared: Arc<Shared>,
    cmd_rx: mpsc::UnboundedReceiver<Cmd>,
    push_rx: mpsc::Receiver<OpusFrame>,
    frames_tx: mpsc::Sender<RecvItem>,
    video_tx: mpsc::Sender<VideoRecvItem>,
    /// The remote video tracks, their sinks and pipelines (`video-core` builds receive).
    video: Subscriptions,
    /// Video tracks the keys refused (unsubscribed once).
    video_refused: std::collections::HashSet<String>,
    /// The app's call slot (see [`Parts::busy`]).
    busy: Option<BusyGuard>,
    /// A re-join was refused for the recording notice: the loop stops and the call holds.
    held: Option<Box<ConsentRequired>>,
    /// The call's active recording as Sew said it last (this member's own view).
    recording: Option<Recording>,
    /// The call's channel (the join's, a move's destination): recordings of other rooms are
    /// not this call's.
    channel: Id,
    consent_tx: mpsc::UnboundedSender<Consented>,
    consent_rx: mpsc::UnboundedReceiver<Consented>,
    cred_tx: watch::Sender<Option<CallCredential>>,
    renew_at: Option<Instant>,
    renewing: Option<JoinHandle<Result<api::Renewed, api::ApiError>>>,
    /// The next renewal retry's wait (reset by every new credential).
    renew_retry: Duration,
    /// Sew's end that arrived while a renewal was in flight: the renewal's own answer says why
    /// when it refused (see [`Engine::on_renewed`]).
    renew_held_end: Option<EndReason>,
    keys: Option<Arc<dyn KeySession>>,
    keys_active: bool,
    keys_start: Option<JoinHandle<Result<Arc<dyn KeySession>, E2eeError>>>,
    e2ee_tx: mpsc::UnboundedSender<E2eeEvent>,
    e2ee_rx: mpsc::UnboundedReceiver<E2eeEvent>,
    session: Session,
    link: Option<SignalLink>,
    link_id: u64,
    /// The link before a reconnect for lost media, still read for the engine's leave.
    parting: Option<Parting>,
    sig_tx: mpsc::UnboundedSender<(u64, SignalIn)>,
    sig_rx: mpsc::UnboundedReceiver<(u64, SignalIn)>,
    attempt: Option<(Attempt, Kind)>,
    rejoining: Option<JoinHandle<Result<JoinAnswer, ProviderError>>>,
    opening: Option<JoinHandle<Result<Transport, TransportError>>>,
    /// A network change's fresh transport, opening.
    rebinding: Option<JoinHandle<Result<Transport, TransportError>>>,
    /// The session resumed during a network change before its transport was ready: the ICE
    /// restart waits for the swap.
    resume_waits_rebind: bool,
    /// After a network change's swap: ICE must connect by then.
    restart_deadline: Option<Instant>,
    /// The JoinResponse's ICE servers (a network change opens its transport with them).
    ice_servers: Vec<sew_lkproto::livekit::IceServer>,
    transport: Option<Transport>,
    pc: Option<Pc>,
    pc_down_since: Option<Instant>,
    relay_only: bool,
    identity: Option<String>,
    sid: Option<String>,
    cid: String,
    track_sid: Option<String>,
    /// The server's answer to our publication (the keys confirm it encrypted, the publish check).
    published: Option<sew_lkproto::livekit::TrackInfo>,
    send: Option<SendPath>,
    /// The extended RTP sequence number of the next microphone packet, in the current PC's
    /// SRTP session ([`fresh_send_seq`] for each new PC; a resume keeps the PC and the count).
    send_seq: u64,
    media_up: bool,
    reconnect: Option<Reconnect>,
    connect_deadline: Instant,
    moving: bool,
    /// Remote tracks by track sid.
    tracks: HashMap<String, RemoteSlot>,
    next_track_id: u64,
    self_muted: bool,
    deafened: bool,
    muted_before_deafen: bool,
    server_muted: bool,
    /// This device's member (the join answer's state).
    self_member: String,
    /// The join answer's `speak_denied` (until the call socket sends this member's state).
    joined_speak_denied: bool,
    /// The engine's permission for this participant refuses the microphone (SPEAK lost): the
    /// publication is gone and nothing is published until it allows it again.
    mic_denied: bool,
    /// [`Engine::speak_denied`] as last told to capture and the participants.
    speak_was_denied: bool,
    /// The microphone's AddTrack is out (its TrackPublished not seen yet).
    publishing: bool,
    /// The current PC already carries a send section for `cid` (a re-publication on the same
    /// PC takes a new cid, so a new m-line).
    cid_on_pc: bool,
    /// The engine's `Disconnect` came first: the call ends at this instant with this reason
    /// unless Sew's own reason arrives before.
    pending_end: Option<(Instant, EndReason)>,
    /// Engine identity → member id (from the keys).
    members: HashMap<String, String>,
    /// Member id → voice state (from the call socket).
    voice: HashMap<String, sew_proto::voice::VoiceState>,
    /// Participant sid → the engine's speaker level.
    engine_levels: HashMap<String, f32>,
    local_level: f32,
    next_speaking: Instant,
    next_snapshot: Instant,
    last_speaking: Vec<Speaking>,
    state: CallState,
    counters: CallCounters,
    ended: Option<EndReason>,
    /// The stats windows.
    meter: Meter,
    /// The beacon's terms of the current join (`None`: off).
    terms: Option<sew_proto::voice::CallStatsBeacon>,
    /// The camera and screen-share publications.
    vpub: Publisher,
}

async fn opt_join<T>(h: &mut Option<JoinHandle<T>>) -> Result<T, tokio::task::JoinError> {
    match h {
        Some(j) => {
            let r = j.await;
            *h = None;
            r
        }
        None => std::future::pending().await,
    }
}

async fn opt_attempt(
    h: &mut Option<(Attempt, Kind)>,
) -> (
    Result<Result<SignalLink, ConnectError>, tokio::task::JoinError>,
    Kind,
) {
    match h {
        Some((j, k)) => {
            let k = *k;
            let r = j.await;
            *h = None;
            (r, k)
        }
        None => std::future::pending().await,
    }
}

async fn opt_recv(t: &mut Option<Transport>) -> Option<TransportEvent> {
    match t {
        Some(t) => t.recv().await,
        None => std::future::pending().await,
    }
}

#[allow(clippy::large_enum_variant)]
enum Step {
    Cmd(Option<Cmd>),
    Push(Option<OpusFrame>),
    Signal(Option<(u64, SignalIn)>),
    Transport(Option<TransportEvent>),
    E2ee(Option<E2eeEvent>),
    KeysStarted(Result<Result<Arc<dyn KeySession>, E2eeError>, tokio::task::JoinError>),
    Attempt(
        Result<Result<SignalLink, ConnectError>, tokio::task::JoinError>,
        Kind,
    ),
    Rejoined(Result<Result<JoinAnswer, ProviderError>, tokio::task::JoinError>),
    Opened(Result<Result<Transport, TransportError>, tokio::task::JoinError>),
    Rebound(Result<Result<Transport, TransportError>, tokio::task::JoinError>),
    Renewed(Result<Result<api::Renewed, api::ApiError>, tokio::task::JoinError>),
    Consented(Option<Consented>),
    Publish(VideoStep),
    Timeout,
}

fn rfc6464(level_dbov: f32) -> u8 {
    if level_dbov.is_nan() {
        return 127;
    }
    (-level_dbov).clamp(0.0, 127.0) as u8
}

/// One member's flags from Sew's voice state.
struct Flags {
    self_mute: bool,
    self_deaf: bool,
    server_mute: bool,
    server_deaf: bool,
    speak_denied: bool,
}

/// Sew's reason for ending this join (a voice leave reason: the call socket's self copy or its
/// `4011` close; the key group's removal only as the fallback) as the call's end: passed on
/// unchanged,
/// but `replaced` (another device took the call over) is `credential_lost` and `left` (a leave
/// from elsewhere) is `left`.
pub(crate) fn end_for_sew_reason(reason: &str) -> EndReason {
    match reason {
        "replaced" => EndReason::CredentialLost,
        "left" => EndReason::Left,
        r => EndReason::Removed(r.to_owned()),
    }
}

fn dbov_to_unit(level_dbov: f32) -> f32 {
    // -60 dBov and below reads as silence; 0 dBov as 1.
    ((level_dbov + 60.0) / 60.0).clamp(0.0, 1.0)
}

impl Engine {
    async fn run(&mut self) {
        self.publish_state(CallState::Connecting);
        if self.speak_was_denied {
            // Joined without SPEAK: capture stays off until it is granted.
            self.frames_item(RecvItem::Capture(false));
        }
        // The join answer's recording (this member's view), replacing a held join's notice.
        let joined = self.answer.join.recording.clone();
        self.apply_recording(joined);
        self.sync_recording_view();
        self.start_keys(self.req.rejoin);
        self.start_attempt(Kind::Full);
        self.schedule_renew(Instant::now());
        while self.ended.is_none() && self.held.is_none() {
            self.pump();
            let deadline = self.poll_timeout();
            let sleep = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline));
            let step = tokio::select! {
                biased;
                c = self.cmd_rx.recv() => Step::Cmd(c),
                s = self.sig_rx.recv() => Step::Signal(s),
                t = opt_recv(&mut self.transport) => Step::Transport(t),
                e = self.e2ee_rx.recv() => Step::E2ee(e),
                r = opt_join(&mut self.keys_start) => Step::KeysStarted(r),
                (r, k) = opt_attempt(&mut self.attempt) => Step::Attempt(r, k),
                r = opt_join(&mut self.rejoining) => Step::Rejoined(r),
                r = opt_join(&mut self.opening) => Step::Opened(r),
                r = opt_join(&mut self.rebinding) => Step::Rebound(r),
                r = opt_join(&mut self.renewing) => Step::Renewed(r),
                d = self.consent_rx.recv() => Step::Consented(d),
                p = self.push_rx.recv() => Step::Push(p),
                v = self.vpub.recv() => Step::Publish(v),
                () = sleep => Step::Timeout,
            };
            let now = Instant::now();
            match step {
                Step::Cmd(None | Some(Cmd::Dropped)) => {
                    // The Call handle is gone without a leave: leave.
                    self.leave().await;
                }
                Step::Cmd(Some(Cmd::Mute {
                    muted,
                    deafened,
                    reply,
                })) => {
                    self.set_mute(muted, deafened);
                    let _ = reply.send(());
                }
                Step::Cmd(Some(Cmd::Leave(reply))) => {
                    self.leave().await;
                    // The slot is free before the leave answers: a join right after it is
                    // never `already_in_call`.
                    self.busy = None;
                    let _ = reply.send(());
                }
                Step::Cmd(Some(Cmd::NetworkChanged)) => self.network_changed(now),
                Step::Cmd(Some(Cmd::Video(c))) => {
                    let mut out = VideoOut::default();
                    self.video.sink(now, c, &mut out);
                    self.video_out(out);
                }
                Step::Cmd(Some(Cmd::Publish(cmd))) => {
                    let api = self.lease_api();
                    let mut cx = video_cx!(self, now);
                    self.vpub.command(&mut cx, api, cmd);
                    self.negotiate();
                }
                Step::Publish(VideoStep::Frame(f)) => {
                    let mut cx = video_cx!(self, now);
                    self.vpub.on_frame(&mut cx, f);
                }
                Step::Publish(VideoStep::End(e)) => {
                    let api = self.lease_api();
                    let mut cx = video_cx!(self, now);
                    self.vpub.on_producer_end(&mut cx, api, e);
                    self.negotiate();
                }
                Step::Publish(VideoStep::Lease(d)) => {
                    let mut cx = video_cx!(self, now);
                    self.vpub.on_lease(&mut cx, d);
                    self.negotiate();
                }
                Step::Publish(VideoStep::Fallback(f)) => {
                    let mut cx = video_cx!(self, now);
                    self.vpub.on_producer_fallback(&mut cx, f);
                    self.negotiate();
                }
                Step::Cmd(Some(Cmd::Consent {
                    granted,
                    notice_version,
                    reply,
                })) => self.start_consent(granted, notice_version, reply),
                Step::Cmd(Some(Cmd::Recording { control, reply })) => {
                    self.start_control(control, reply);
                }
                Step::Consented(Some(d)) => self.on_consented(d),
                Step::Consented(None) => {}
                Step::Push(Some(f)) => self.send_frame(now, f),
                Step::Push(None) => {}
                Step::Signal(Some((id, msg)))
                    if self.parting.as_ref().is_some_and(|p| p.id == id) =>
                {
                    self.on_parting(now, msg);
                }
                Step::Signal(Some((id, msg))) => {
                    if id == self.link_id {
                        match msg {
                            SignalIn::Response(r) => {
                                self.session.handle_response(now, r);
                                self.drain_session(now);
                            }
                            SignalIn::Closed(why) => {
                                tracing::info!(target: "sew_call_client", %why, "signalling lost");
                                self.signal_lost(false);
                            }
                        }
                    }
                }
                Step::Signal(None) => {}
                Step::Transport(Some(TransportEvent::Datagram(d))) => {
                    if let Some(pc) = self.pc.as_mut() {
                        pc.handle_datagram(now, &d);
                    }
                }
                Step::Transport(Some(TransportEvent::TurnLost(why))) => {
                    if self.changing_network() {
                        // The old network's allocation: its replacement is on the way.
                        tracing::info!(target: "sew_call_client", %why, "the old network's TURN allocation is gone");
                        self.transport = None;
                    } else {
                        tracing::info!(target: "sew_call_client", %why, "TURN allocation lost; full reconnect");
                        self.signal_lost(true);
                    }
                }
                Step::Transport(None) => {
                    if self.changing_network() {
                        self.transport = None;
                    } else {
                        self.signal_lost(true);
                    }
                }
                Step::E2ee(Some(ev)) => self.on_e2ee(ev),
                Step::E2ee(None) => {}
                Step::KeysStarted(r) => match r {
                    Ok(Ok(k)) => {
                        if let Some(t) = &self.published
                            && !k.published(t)
                        {
                            self.error(
                                "e2ee_refused",
                                "the engine did not confirm the publication encrypted",
                            );
                        }
                        self.keys = Some(k);
                        let mut cx = video_cx!(self, now);
                        self.vpub.on_keys(&mut cx);
                        self.negotiate();
                        self.send_roster();
                        self.feed_recording();
                    }
                    Ok(Err(e)) => {
                        self.error(&e.code, &e.detail);
                        self.end(EndReason::E2eeRefused).await;
                    }
                    Err(e) => {
                        self.error("e2ee_refused", &e.to_string());
                        self.end(EndReason::E2eeRefused).await;
                    }
                },
                Step::Attempt(r, kind) => self.on_attempt(now, r, kind),
                Step::Rejoined(r) => self.on_rejoined(now, r).await,
                Step::Opened(r) => self.on_opened(now, r).await,
                Step::Rebound(r) => self.on_rebound(now, r),
                Step::Renewed(r) => self.on_renewed(now, r).await,
                Step::Timeout => self.on_timeout(now).await,
            }
            if self.video.deadline().is_some_and(|d| d <= now) {
                // A busy socket can keep the timer from winning the select: video's keyframe
                // requests and reorder waits are due whatever woke the loop.
                self.video_tick(now);
            }
            self.stats_tick(now);
            if now >= self.next_snapshot {
                // Counters reach `Call::snapshot` at most 100 ms late.
                self.next_snapshot = now + SPEAKING_EVERY;
                self.snapshot_update();
            }
        }
        if self.held.is_none() {
            // Over (a leave, a kick, a lost admit, an error): the app's slot is free now, not
            // once the engine's parts are dropped.
            self.busy = None;
        }
    }

    // ------------------------------------------------------------------ the loop's helpers

    fn poll_timeout(&self) -> Instant {
        let now = Instant::now();
        let mut t = now + Duration::from_secs(1);
        if let Some(p) = &self.pc {
            t = t.min(p.timeout());
        }
        if let Some(s) = self.session.poll_timeout() {
            t = t.min(s);
        }
        if let Some(r) = &self.reconnect {
            let connecting = self.attempt.is_some() || self.link.is_some();
            if let Some(w) = r.wake(self.rejoining.is_some(), connecting) {
                t = t.min(w);
            }
        }
        if let Some(r) = self.renew_at {
            t = t.min(r);
        }
        if let Some((at, _)) = &self.pending_end {
            t = t.min(*at);
        }
        if let Some(p) = &self.parting {
            t = t.min(p.until);
        }
        if let Some(d) = self.pc_down_since {
            t = t.min(d + PC_FAIL_GRACE);
        }
        if let Some(d) = self.restart_deadline {
            t = t.min(d);
        }
        if let Some(m) = self.meter.deadline() {
            t = t.min(m);
        }
        if let Some(v) = self.vpub.deadline() {
            t = t.min(v);
        }
        for s in self.tracks.values() {
            if let Some((_, at)) = s.gaps.front() {
                t = t.min(*at);
            }
        }
        if let Some(v) = self.video.deadline() {
            t = t.min(v);
        }
        if self.media_up {
            t = t.min(self.next_speaking);
        }
        if self.ended.is_none() {
            t = t.min(self.next_snapshot);
        }
        t.max(now)
    }

    /// Moves the PC's datagrams out and handles its events; sends the session's requests.
    fn pump(&mut self) {
        let now = Instant::now();
        for _ in 0..4 {
            let Some(pc) = self.pc.as_mut() else { break };
            let (datagrams, events) = pc.poll(now);
            if let Some(t) = self.transport.as_mut() {
                for d in datagrams {
                    t.send(d);
                }
            }
            if events.is_empty() {
                break;
            }
            for ev in events {
                self.on_pc(now, ev);
            }
        }
        while let Some(r) = self.session.poll_request() {
            if let Some(l) = &self.link {
                l.send(r);
            }
        }
    }

    fn snapshot_update(&self) {
        let participants = self.participants();
        if let Ok(mut s) = self.shared.snapshot.lock() {
            s.state = self.state.clone();
            s.participants = participants;
            s.relay = self
                .transport
                .as_ref()
                .and_then(Transport::relay_via)
                .map(|v| v.name().to_owned());
            s.relay_only = self.relay_only;
            s.counters = self.counters.clone();
        }
    }

    fn publish_state(&mut self, st: CallState) {
        if self.state == st && st != CallState::Connecting {
            return;
        }
        self.state = st.clone();
        if st == CallState::Connected {
            // The first window starts when the call first connects; what came before it is
            // kept apart, so every counted frame is in a window or in that bucket.
            if let Some(b) = self.meter.start(Instant::now(), &self.counters)
                && let Ok(mut r) = self.shared.stats.lock()
            {
                r.before_first_window = Some(b);
            }
        }
        self.snapshot_update();
        let _ = self.shared.events.send(CallEvent::State(st));
    }

    fn update_state(&mut self) {
        if self.ended.is_some() {
            return;
        }
        let st = match &self.reconnect {
            Some(r) if !self.moving && !r.initial => CallState::Reconnecting { attempt: r.attempt },
            _ if self.media_up && self.keys_active => CallState::Connected,
            _ => match &self.state {
                // A move (or a brief gap) keeps `connected`.
                CallState::Connected if self.moving => CallState::Connected,
                CallState::Reconnecting { attempt } if !self.media_up => {
                    CallState::Reconnecting { attempt: *attempt }
                }
                _ => CallState::Connecting,
            },
        };
        if st != self.state {
            self.publish_state(st);
        } else {
            self.snapshot_update();
        }
    }

    fn error(&self, code: &str, detail: &str) {
        let _ = self.shared.events.send(CallEvent::Error(CallErrorEvent {
            code: code.to_owned(),
            detail: detail.to_owned(),
        }));
    }

    fn emit_participants(&self) {
        let _ = self
            .shared
            .events
            .send(CallEvent::Participants(self.participants()));
        self.snapshot_update();
    }

    fn participants(&self) -> Vec<Participant> {
        let mut out = Vec::new();
        let flags = |identity: &str| -> (Option<String>, Flags) {
            let member = self.members.get(identity).cloned();
            let v = member.as_ref().and_then(|m| self.voice.get(m));
            let f = Flags {
                self_mute: v.is_some_and(|v| v.self_mute),
                self_deaf: v.is_some_and(|v| v.self_deaf),
                server_mute: v.is_some_and(|v| v.server_mute),
                server_deaf: v.is_some_and(|v| v.server_deaf),
                speak_denied: v.is_some_and(|v| v.speak_denied),
            };
            (member, f)
        };
        if let Some(me) = &self.identity {
            let (member, f) = flags(me);
            out.push(Participant {
                identity: me.clone(),
                member_id: member,
                is_self: true,
                muted: self.send_blocked() || f.server_mute,
                deafened: self.deafened,
                server_muted: self.server_muted || f.server_mute,
                server_deafened: f.server_deaf,
                speak_denied: self.speak_denied(),
                recorder: false,
                camera: None,
                screen: None,
            });
        }
        for p in self.session.remotes().values() {
            let (member, f) = flags(&p.identity);
            let (camera, screen) = self.video.views(&p.identity);
            let track_muted =
                !p.tracks.is_empty() && p.tracks.iter().filter(|t| t.r#type == 0).all(|t| t.muted);
            out.push(Participant {
                identity: p.identity.clone(),
                member_id: member,
                is_self: false,
                muted: f.self_mute
                    || f.server_mute
                    || f.speak_denied
                    || track_muted
                    || p.tracks.is_empty(),
                deafened: f.self_deaf,
                server_muted: f.server_mute,
                server_deafened: f.server_deaf,
                speak_denied: f.speak_denied,
                recorder: p.kind == sew_lkproto::livekit::participant_info::Kind::Egress as i32,
                camera,
                screen,
            });
        }
        out
    }

    // ------------------------------------------------------------------ recording

    /// Sew's word on the call's recording (this member's own view; `None`: none active). A
    /// recording of another room is not this call's; a stopped one clears the call's only if
    /// it is the call's. Fed to the keys and shown to the host when it changed.
    fn apply_recording(&mut self, rec: Option<Recording>) {
        // The person's own Record and Stop it carries (a server that computes them).
        if let Some(r) = &rec
            && let Some(c) = &r.my_controls
            && r.channel_id == self.channel
        {
            self.apply_controls(Some(r.channel_id), Some(c.clone()));
        }
        let next = match rec {
            Some(r) if r.channel_id != self.channel => return,
            Some(r) if !r.state.is_active() => match &self.recording {
                Some(cur) if cur.id == r.id => None,
                _ => return,
            },
            other => other,
        };
        if next == self.recording {
            return;
        }
        // The answer kept for re-joins names this recording (or an auto channel's), else it
        // is gone.
        let keep = match (&self.req.recording_notice, &next) {
            (Some(n), Some(r)) => {
                n.recording_id == RecordingRef::Id(r.id) || n.recording_id == RecordingRef::Auto
            }
            _ => false,
        };
        if !keep {
            self.req.recording_notice = None;
        }
        self.recording = next;
        self.feed_recording();
        self.sync_recording_view();
    }

    /// Sew's word on the person's Record and Stop (a server that computes them):
    /// `channel_id` `None` is the call's own room (the call socket's READY). A value for the
    /// call's channel replaces the one held when its `rev` is not older; any word at all says
    /// the server computes them ([`crate::Call::server_controls`]). The host hears of a new
    /// value, and of the server's first word.
    fn apply_controls(&mut self, channel_id: Option<Id>, controls: Option<RecordingControls>) {
        let here = channel_id.is_none_or(|c| c == self.channel);
        let changed = match self.shared.snapshot.lock() {
            Ok(mut s) => merge_controls(&mut s, here, controls.as_ref()),
            Err(_) => None,
        };
        if let Some(value) = changed {
            let _ = self.shared.events.send(CallEvent::RecordingControls(value));
        }
    }

    /// The call is in another room now (a move, a re-join elsewhere): the source room's
    /// Record and Stop no longer apply until the destination's arrive.
    fn clear_controls(&mut self) {
        let cleared = match self.shared.snapshot.lock() {
            Ok(mut s) => clear_controls_in(&mut s),
            Err(_) => false,
        };
        if cleared {
            let _ = self.shared.events.send(CallEvent::RecordingControls(None));
        }
    }

    /// The keys get the call's recording state (Sew's; `pending` until Sew says otherwise).
    fn feed_recording(&self) {
        if let Some(k) = &self.keys {
            let (rid, consent) = self
                .recording
                .as_ref()
                .map_or((None, ConsentState::Pending), Recording::e2ee_input);
            k.recording(rid, consent);
        }
    }

    /// The host's view ([`crate::Call::recording`], the `recording` event) follows the
    /// engine's.
    fn sync_recording_view(&self) {
        let view = self.recording.as_ref().map(CallRecording::from_sew);
        let changed = match self.shared.snapshot.lock() {
            Ok(mut s) if s.recording != view => {
                s.recording.clone_from(&view);
                true
            }
            _ => false,
        };
        if changed {
            let _ = self
                .shared
                .events
                .send(CallEvent::Recording(view.map(Box::new)));
        }
    }

    /// The host's answer to the live recording's notice, sent through the provider off the
    /// loop.
    fn start_consent(
        &mut self,
        granted: bool,
        notice_version: Option<u32>,
        reply: tokio::sync::oneshot::Sender<Result<(), CallError>>,
    ) {
        let Some(rec) = &self.recording else {
            let _ = reply.send(Err(CallError::NoRecording));
            return;
        };
        let answer = ConsentAnswer {
            target: self.req.target.clone(),
            room: self.req.room.clone(),
            recording_id: rec.id,
            consent: granted,
            notice_version,
            device_id: self.keys.as_ref().and_then(|k| k.device_id()),
        };
        let provider = self.provider.clone();
        let tx = self.consent_tx.clone();
        tokio::spawn(async move {
            let result = provider.consent(answer).await;
            let _ = tx.send(Consented {
                result,
                granted,
                notice_version,
                control: None,
                reply,
            });
        });
    }

    /// The person's Record or Stop, sent through the provider off the loop. A Stop needs the
    /// active recording.
    fn start_control(
        &mut self,
        control: RecordingControl,
        reply: tokio::sync::oneshot::Sender<Result<(), CallError>>,
    ) {
        let mut req = match control {
            RecordingControl::Start => {
                RecordingRequest::start(&self.req.target, &self.req.room, self.channel)
            }
            RecordingControl::Stop => {
                let Some(rec) = &self.recording else {
                    let _ = reply.send(Err(CallError::NoRecording));
                    return;
                };
                RecordingRequest::stop(&self.req.target, &self.req.room, rec.channel_id, rec.id)
            }
        };
        req.device_id = self.keys.as_ref().and_then(|k| k.device_id());
        tracing::info!(target: "sew_call_client", ?control, "sending the recording control");
        let provider = self.provider.clone();
        let tx = self.consent_tx.clone();
        tokio::spawn(async move {
            let result = provider.recording(req).await;
            let _ = tx.send(Consented {
                result,
                granted: false,
                notice_version: None,
                control: Some(control),
                reply,
            });
        });
    }

    /// Sew's answer to a consent: its recording view is the call's (a grant releases the key
    /// from here on, a withdrawal rekeys); the answer is kept for re-joins. Sew's answer to a
    /// Record or Stop is the call's recording too (a stopped one clears it).
    fn on_consented(&mut self, d: Consented) {
        if d.control.is_some() {
            let out = match d.result {
                Ok(rec) => {
                    self.apply_recording(Some(rec));
                    Ok(())
                }
                Err(e) => Err(CallError::Provider(e)),
            };
            let _ = d.reply.send(out);
            return;
        }
        match d.result {
            Ok(rec) => {
                match (d.notice_version, &mut self.req.recording_notice) {
                    (Some(v), n) => {
                        *n = Some(RecordingNotice {
                            recording_id: RecordingRef::Id(rec.id),
                            consent: Some(d.granted),
                            notice_version: Some(v),
                        });
                    }
                    (None, Some(n)) if n.recording_id == RecordingRef::Id(rec.id) => {
                        n.consent = Some(d.granted);
                    }
                    (None, _) => {}
                }
                self.apply_recording(Some(rec));
                let _ = d.reply.send(Ok(()));
            }
            Err(ProviderError::ConsentRequired(c)) => {
                // A changed notice: the current one is shown; nothing else changes.
                if let Some(mut r) = c.recording.clone() {
                    if r.consent_prompt.is_none() {
                        r.consent_prompt = Some(c.consent_prompt.clone());
                    }
                    self.apply_recording(Some(r));
                }
                let _ = d
                    .reply
                    .send(Err(CallError::Provider(ProviderError::ConsentRequired(c))));
            }
            Err(e) => {
                let _ = d.reply.send(Err(CallError::Provider(e)));
            }
        }
    }

    /// A re-join was refused for the recording notice: media and keys go and the call holds
    /// ([`hold`]) for the person's answer.
    async fn go_held(&mut self, c: Box<ConsentRequired>) {
        tracing::info!(target: "sew_call_client", "the re-join needs the recording notice answered; holding");
        self.teardown_media();
        if let Some(l) = self.link.take() {
            l.close().await;
        }
        if let Some((a, _)) = self.attempt.take() {
            a.abort();
        }
        if let Some(o) = self.opening.take() {
            o.abort();
        }
        if let Some(r) = self.renewing.take() {
            r.abort();
        }
        if let Some(k) = self.keys_start.take() {
            k.abort();
        }
        if let Some(k) = self.keys.take() {
            k.close().await;
        }
        self.reconnect = None;
        self.recording = None;
        // The join after the answer is this call's re-join, as muted as the call was.
        self.req.rejoin = Some(RejoinReason::AdmitLost);
        self.req.muted = self.effective_muted();
        self.req.deafened = self.deafened;
        self.held = Some(c);
    }

    /// Muted by self, deafened, or muted by a moderator (what Sew's self state and the
    /// track's mute carry).
    fn effective_muted(&self) -> bool {
        self.self_muted || self.deafened || self.server_muted
    }

    /// This member lacks SPEAK: Sew's voice state says so (the call socket's, else the
    /// join answer's), or the engine's permission refuses the microphone.
    fn speak_denied(&self) -> bool {
        let sew = self
            .voice
            .get(&self.self_member)
            .map_or(self.joined_speak_denied, |v| v.speak_denied);
        sew || self.mic_denied
    }

    /// Nothing is captured or sent: muted, or SPEAK denied.
    fn send_blocked(&self) -> bool {
        self.effective_muted() || self.speak_denied()
    }

    /// After a change of [`Engine::speak_denied`]: capture follows and the participants show
    /// it. Self-mute is untouched, so it comes back as it was.
    fn speak_changed(&mut self) {
        let denied = self.speak_denied();
        if denied == self.speak_was_denied {
            return;
        }
        self.speak_was_denied = denied;
        tracing::info!(target: "sew_call_client", denied, "SPEAK changed");
        self.frames_item(RecvItem::Capture(!self.send_blocked()));
        self.emit_participants();
    }

    /// Whether the engine's permission for this participant allows the microphone (no
    /// permission seen yet: the token's grants, which Sew made).
    fn engine_allows_mic(&self) -> bool {
        let Some(p) = self.session.local().and_then(|l| l.permission.as_ref()) else {
            return true;
        };
        let mic = sew_lkproto::livekit::TrackSource::Microphone as i32;
        p.can_publish && (p.can_publish_sources.is_empty() || p.can_publish_sources.contains(&mic))
    }

    /// Publishes the microphone when the PC is up, nothing is published or on its way, and the
    /// engine allows it (the first publication, a full reconnect's, or SPEAK given back).
    fn maybe_publish(&mut self) {
        if self.pc.is_none() || self.track_sid.is_some() || self.publishing {
            return;
        }
        if !self.engine_allows_mic() {
            self.mic_denied = true;
            return;
        }
        if self.cid_on_pc {
            // The old send section stays (the engine marked its mid revoked): a new one.
            self.cid = format!("mic-{:08x}", rand::random::<u32>());
            self.cid_on_pc = false;
        }
        self.publishing = true;
        self.session
            .publish_audio(&self.cid, MIC_NAME, self.effective_muted());
        self.negotiate();
    }

    /// The local participant changed (the engine's ParticipantUpdate): a SPEAK change shows as
    /// its permission. Losing the microphone drops the publication (the engine unpublished it);
    /// getting it back publishes again on the same PC, with no re-join.
    fn local_permission_changed(&mut self) {
        let allowed = self.engine_allows_mic();
        if !allowed && !self.mic_denied {
            tracing::info!(target: "sew_call_client", "the engine revoked the microphone");
            self.mic_denied = true;
            self.send = None;
            self.track_sid = None;
            self.published = None;
            self.publishing = false;
        } else if allowed && self.mic_denied {
            tracing::info!(target: "sew_call_client", "the engine allows the microphone again");
            self.mic_denied = false;
        }
        if allowed {
            self.maybe_publish();
        }
        self.speak_changed();
    }

    fn frames_item(&mut self, item: RecvItem) {
        if self.frames_tx.try_send(item).is_err() {
            self.counters.recv_queue_drops += 1;
        }
    }

    // ------------------------------------------------------------------ keys

    fn start_keys(&mut self, rejoin: Option<RejoinReason>) {
        let ctx = E2eeContext {
            join: self.answer.join.clone(),
            api_base: self.answer.api_base.clone(),
            credential: CredentialHandle(self.cred_tx.subscribe()),
            http: self.http.clone(),
            tls: self.tls.clone(),
            app_id: self.cfg.app_id.clone(),
            data_dir: self.cfg.data_dir.clone(),
            rejoin,
        };
        let e2ee = self.e2ee.clone();
        let events = E2eeEvents(self.e2ee_tx.clone());
        self.keys_active = false;
        self.keys_start = Some(tokio::spawn(async move { e2ee.start(ctx, events).await }));
    }

    fn send_roster(&self) {
        if let Some(k) = &self.keys {
            let ids: Vec<String> = self
                .session
                .remotes()
                .values()
                .map(|p| p.identity.clone())
                .collect();
            k.roster(&ids);
        }
    }

    fn on_e2ee(&mut self, ev: E2eeEvent) {
        match ev {
            E2eeEvent::Active { epoch } => {
                tracing::debug!(target: "sew_call_client", epoch, "key epoch active");
                self.keys_active = true;
                self.update_state();
            }
            E2eeEvent::Refused { code, detail } if self.pending_end.is_some() => {
                // The engine or the key group removed us already; Sew's reason (or the
                // fallback) ends the call.
                tracing::debug!(target: "sew_call_client", %code, %detail, "keys ended while the end waits for Sew's reason");
            }
            E2eeEvent::Refused { code, detail } => {
                self.error(&code, &detail);
                self.ended_soon(EndReason::E2eeRefused);
            }
            E2eeEvent::Warning { code, detail } => self.error(&code, &detail),
            E2eeEvent::Members(m) => {
                for (identity, member) in m {
                    self.members.insert(identity, member);
                }
                self.emit_participants();
            }
            E2eeEvent::VoiceStates(states) => {
                for v in states {
                    self.voice.insert(v.member_id.to_string(), v);
                }
                self.emit_participants();
                self.speak_changed();
            }
            E2eeEvent::ServerUpdated(u) => {
                tracing::info!(target: "sew_call_client", "voice server updated (a move); reconnecting signalling");
                let moved = CallMoved::from_update(&u);
                // A re-join after the move asks the host for the destination, not the source.
                self.req.room = moved.room().to_owned();
                if let Ok(mut s) = self.shared.snapshot.lock() {
                    s.moved = Some(moved.clone());
                }
                let _ = self.shared.events.send(CallEvent::Moved(moved));
                // The destination's recording (`pending` for the moved member), or none.
                if self.channel != u.channel_id {
                    self.channel = u.channel_id;
                    self.clear_controls();
                }
                self.apply_recording(u.recording.clone());
                self.answer.join.url = u.url;
                self.answer.join.token = u.token;
                self.answer.join.room = u.room;
                self.answer.join.expires_at = u.expires_at;
                if let Some(m) = u.media {
                    self.relay_only = m.relay_only;
                    self.answer.join.media = Some(m.clone());
                    self.policy_updated(m);
                }
                self.moving = true;
                // A move re-binds the same credential: its renewal stays as scheduled.
                self.ensure_renew_scheduled(Instant::now());
                self.session.reset(Instant::now());
                // The move's admit takes the new token, not the old refresh token.
                self.session = Session::new(Instant::now());
                self.signal_lost(true);
            }
            E2eeEvent::CredentialLost => {
                // An older Sew's 4011 names no reason: after the engine's Disconnect (or the
                // key group's removal) that wait's reason stands (as before Sew 0.7.2), else
                // the credential was lost.
                let r = self
                    .pending_end
                    .take()
                    .map_or(EndReason::CredentialLost, |(_, r)| r);
                self.ended_soon(r);
            }
            E2eeEvent::Ended { reason } => {
                tracing::info!(target: "sew_call_client", %reason, "Sew ended the join");
                if self.renewing.is_some() {
                    // A renewal Sew refuses can end the credential itself (its login ended), and
                    // the call socket's close may arrive before the renewal's answer: wait for
                    // that answer (at most the request's time limit).
                    let end = end_for_sew_reason(&reason);
                    // A wait for Sew's reason already under way (the key group's removal or
                    // the engine's Disconnect came first) now has it: if that wait runs out
                    // before the renewal answers, the call ends with Sew's reason, not the
                    // wait's fallback.
                    if let Some((_, fallback)) = self.pending_end.as_mut() {
                        *fallback = end.clone();
                    }
                    if self.renew_held_end.is_none() {
                        self.renew_held_end = Some(end);
                    }
                    return;
                }
                self.ended_soon(end_for_sew_reason(&reason));
            }
            E2eeEvent::KeysRemoved { reason } => {
                tracing::info!(target: "sew_call_client", %reason, "the key group removed this device");
                self.keys_removed(Instant::now(), &reason);
            }
            E2eeEvent::Recording(r) => self.apply_recording(r.map(|b| *b)),
            E2eeEvent::RecordingControls {
                channel_id,
                controls,
            } => self.apply_controls(channel_id, controls),
            E2eeEvent::Security(sec) => self.apply_security(sec),
            E2eeEvent::MediaPolicy(m) => self.policy_updated(*m),
        }
    }

    /// A new media policy (`media_policy_updated`, a move): the join's `camera_allowed` and
    /// `screen_allowed` stay; the publications follow the new hints.
    fn policy_updated(&mut self, m: sew_proto::voice::MediaPolicy) {
        if let Ok(mut p) = self.shared.policy.lock() {
            let mut next = m.clone();
            if let Some(old) = p.as_ref() {
                next.camera_allowed = old.camera_allowed;
                next.screen_allowed = old.screen_allowed;
            }
            *p = Some(next.clone());
            let _ = self
                .shared
                .events
                .send(CallEvent::MediaPolicy(Box::new(next)));
        }
        let api = self.lease_api();
        let mut cx = video_cx!(self, Instant::now());
        self.vpub.on_policy(&mut cx, &api, m);
        self.negotiate();
    }

    /// The lease route's client and credential now.
    fn lease_api(&self) -> LeaseApi {
        LeaseApi {
            http: self.http.clone(),
            base: self.answer.api_base.clone(),
            token: self.cred_tx.borrow().clone().map(|c| c.token),
        }
    }

    /// The keys' state and security code: [`crate::Call::snapshot`]'s `security` and a
    /// [`CallEvent::Security`] when it changed.
    fn apply_security(&self, sec: CallSecurity) {
        if let Ok(mut s) = self.shared.snapshot.lock() {
            if s.security.as_ref() == Some(&sec) {
                return;
            }
            s.security = Some(sec.clone());
        }
        let _ = self.shared.events.send(CallEvent::Security(sec));
    }

    /// A message on the link given up on: the engine's `Disconnect` leave ends the call as on
    /// the current link; its close ends the wait.
    fn on_parting(&mut self, now: Instant, msg: SignalIn) {
        match msg {
            SignalIn::Response(r) => {
                if let Some(end) = parting_end(&r) {
                    tracing::info!(target: "sew_call_client", ?end, "the engine's leave on the old link");
                    self.parting = None;
                    self.engine_disconnected(now, end);
                }
            }
            SignalIn::Closed(_) => self.end_parting(),
        }
    }

    /// The old link said nothing more: a re-join held back for it goes now.
    fn end_parting(&mut self) {
        if let Some(p) = self.parting.take()
            && let Some(why) = p.rejoin
        {
            self.start_rejoin(why);
        }
    }

    /// The engine said `Disconnect` (removed, or the room closed): media goes at once, and the
    /// call ends with Sew's reason when the call socket brings it within
    /// [`END_REASON_GRACE`], else with `fallback`.
    fn engine_disconnected(&mut self, now: Instant, fallback: EndReason) {
        if self.ended.is_some() || self.pending_end.is_some() {
            return;
        }
        if self.keys.is_none() && self.keys_start.is_none() {
            // No call socket to wait for.
            self.ended_soon(fallback);
            return;
        }
        self.await_sews_reason(now, fallback);
    }

    /// The key group removed this device: media goes at once, and the call ends with the
    /// reason the call socket brings within [`END_REASON_GRACE`] (the key group names
    /// `disconnected` for a voice leave reason it has no code for, such as
    /// `media_path_down`), else with the key group's. After the engine's `Disconnect` the
    /// key group's reason replaces the engine's as the fallback, and the wait keeps its end.
    fn keys_removed(&mut self, now: Instant, reason: &str) {
        if self.ended.is_some() {
            return;
        }
        let fallback = end_for_sew_reason(reason);
        if let Some((_, r)) = self.pending_end.as_mut() {
            *r = fallback;
            return;
        }
        self.await_sews_reason(now, fallback);
    }

    /// Media and signalling go now; the call ends at the next of Sew's reasons, or with
    /// `fallback` after [`END_REASON_GRACE`].
    fn await_sews_reason(&mut self, now: Instant, fallback: EndReason) {
        self.teardown_media();
        self.link = None;
        self.parting = None;
        if let Some((a, _)) = self.attempt.take() {
            a.abort();
        }
        if let Some(r) = self.rejoining.take() {
            r.abort();
        }
        self.reconnect = None;
        self.pending_end = Some((now + END_REASON_GRACE, fallback));
        self.snapshot_update();
    }

    /// Ends at the next loop turn (from sync code).
    fn ended_soon(&mut self, reason: EndReason) {
        if self.ended.is_none() {
            self.teardown_media();
            self.vpub.close("ended");
            self.link = None;
            self.recording = None;
            self.sync_recording_view();
            self.ended = Some(reason.clone());
            self.publish_state(CallState::Ended { reason });
            if let Some(k) = self.keys.take() {
                tokio::spawn(async move { k.close().await });
            }
        }
    }

    async fn end(&mut self, reason: EndReason) {
        if self.ended.is_some() {
            return;
        }
        self.teardown_media();
        self.vpub.close("ended");
        if let Some(l) = self.link.take() {
            l.close().await;
        }
        if let Some(k) = self.keys.take()
            && tokio::time::timeout(LEAVE_TIMEOUT, k.close())
                .await
                .is_err()
        {
            tracing::warn!(target: "sew_call_client", "the call keys did not close in time; the call ends without them");
        }
        self.recording = None;
        self.sync_recording_view();
        self.ended = Some(reason.clone());
        self.publish_state(CallState::Ended { reason });
    }

    async fn leave(&mut self) {
        if self.ended.is_some() {
            return;
        }
        // The leave sample first: Sew takes samples only from a caller still in voice.
        if self.meter.started() {
            let src = self.playout_source();
            let mut w = self
                .meter
                .close(Instant::now(), &self.counters, src.as_deref(), true);
            w.noise_removal = self.shared.noise_removal();
            let w = match self.beacon_prepare(w) {
                Prepared::Send(mut w, post) => {
                    w.beacon = tokio::time::timeout(LEAVE_TIMEOUT, post.send())
                        .await
                        .unwrap_or_else(|_| BeaconOutcome::Failed {
                            error: "timed out".to_owned(),
                        });
                    w
                }
                Prepared::Done(w) => w,
            };
            self.shared.record_window(w);
        }
        let cred = self.cred_tx.borrow().clone();
        if let Some(c) = cred {
            let http = self.http.clone();
            let base = self.answer.api_base.clone();
            let r = tokio::time::timeout(LEAVE_TIMEOUT, api::leave(&http, &base, &c.token)).await;
            if let Ok(Err(e)) = r {
                tracing::info!(target: "sew_call_client", ?e, "Sew's leave failed");
            }
        }
        self.session.leave();
        while let Some(r) = self.session.poll_request() {
            if let Some(l) = &self.link {
                l.send(r);
            }
        }
        self.end(EndReason::Left).await;
    }

    // ------------------------------------------------------------------ stats

    /// The host's playout counters, when a pipeline reports them.
    fn playout_source(&self) -> Option<Arc<dyn PlayoutStats>> {
        self.shared.playout.lock().ok().and_then(|p| p.clone())
    }

    /// The beacon's per-loop work: the playout counters once a second, and the window's end.
    fn stats_tick(&mut self, now: Instant) {
        if !self.meter.started() || self.ended.is_some() {
            return;
        }
        let src = self.playout_source();
        self.meter.poll(now, src.as_deref(), false);
        if !self.meter.due(now) {
            return;
        }
        let mut w = self.meter.close(now, &self.counters, src.as_deref(), false);
        w.noise_removal = self.shared.noise_removal();
        match self.beacon_prepare(w) {
            Prepared::Send(mut w, post) => {
                let shared = self.shared.clone();
                tokio::spawn(async move {
                    w.beacon = post.send().await;
                    shared.record_window(w);
                });
            }
            Prepared::Done(w) => self.shared.record_window(w),
        }
    }

    /// The sample of `w` and its request, or `w` with why nothing is sent.
    fn beacon_prepare(&self, mut w: StatsWindow) -> Prepared {
        let Some(terms) = &self.terms else {
            w.beacon = BeaconOutcome::Off;
            return Prepared::Done(w);
        };
        if self.shared.beacon_stopped.load(Ordering::Acquire) {
            w.beacon = BeaconOutcome::Stopped;
            return Prepared::Done(w);
        }
        let Some(cred) = self.cred_tx.borrow().clone() else {
            w.beacon = BeaconOutcome::NoCredential;
            return Prepared::Done(w);
        };
        match crate::stats::sample(&w, terms) {
            Ok(sample) => {
                w.sample = Some(sample.clone());
                let post = BeaconPost {
                    http: self.http.clone(),
                    base: self.answer.api_base.clone(),
                    token: cred.token,
                    sample,
                };
                Prepared::Send(w, Box::new(post))
            }
            Err(error) => {
                tracing::warn!(target: "sew_call_client", %error, "stats sample not sent");
                w.beacon = BeaconOutcome::Failed { error };
                Prepared::Done(w)
            }
        }
    }

    /// The beacon's name for the selected pair's local candidate `addr`.
    fn path_of(&self, addr: std::net::SocketAddr) -> Option<crate::stats::Path> {
        use sew_proto::voice::{CallStatsCandidate as C, CallStatsRelayProtocol as P};
        let t = self.transport.as_ref()?;
        let l = t.local_candidates().iter().find(|l| l.addr == addr)?;
        Some(match &l.kind {
            LocalKind::Host => (C::Host, None),
            LocalKind::Relayed { via, .. } => (
                C::Relay,
                Some(match via {
                    crate::transport::Via::Udp => P::Udp,
                    crate::transport::Via::Tcp => P::Tcp,
                    crate::transport::Via::Tls => P::Tls,
                }),
            ),
        })
    }

    // ------------------------------------------------------------------ credential

    /// How long the current credential has left on the wall clock (`None`: no credential).
    fn credential_left(&self) -> Option<Duration> {
        let c = self.cred_tx.borrow().clone()?;
        // Wall time only through sew-proto's clock (the workspace's time lint).
        let now_ms = {
            use sew_proto::clock::Clock as _;
            sew_proto::clock::SystemClock.now_unix_ms()
        };
        Some(Duration::from_millis(
            u64::try_from(c.expires_at.unix_ms())
                .unwrap_or(0)
                .saturating_sub(now_ms),
        ))
    }

    /// Schedules the renewal of the current credential at half the life it has left: called
    /// for every new token (the join's, each renewal's, each re-join's).
    fn schedule_renew(&mut self, now: Instant) {
        self.renew_retry = RENEW_RETRY_MIN;
        self.renew_at = self.credential_left().map(|left| now + left / 2);
    }

    /// After a move or a reconnect: a credential always has its renewal scheduled, in flight or
    /// waiting for a retry. (Neither changes the token, so its schedule stands.)
    fn ensure_renew_scheduled(&mut self, now: Instant) {
        if self.renew_at.is_none() && self.renewing.is_none() {
            self.schedule_renew(now);
        }
    }

    /// A renewal failed with something worth retrying: again after a backoff, until the
    /// credential runs out.
    async fn retry_renew(&mut self, now: Instant, why: &str) {
        let left = self.credential_left().unwrap_or_default();
        if left.is_zero() {
            tracing::info!(target: "sew_call_client", %why, "the call credential expired before a renewal got through");
            self.error(
                "credential_expired",
                &format!("the call credential expired; the last renewal failed: {why}"),
            );
            self.end(EndReason::CredentialExpired).await;
            return;
        }
        let wait = self.renew_retry.min(left / 2).max(RENEW_RETRY_FLOOR);
        self.renew_retry = (self.renew_retry * 2).min(RENEW_RETRY_MAX);
        tracing::info!(
            target: "sew_call_client",
            %why,
            retry_ms = wait.as_millis() as u64,
            left_ms = left.as_millis() as u64,
            "call credential renewal failed; retrying"
        );
        self.renew_at = Some(now + wait);
    }

    async fn on_renewed(
        &mut self,
        now: Instant,
        r: Result<Result<api::Renewed, api::ApiError>, tokio::task::JoinError>,
    ) {
        let held = self.renew_held_end.take();
        match r {
            Ok(Ok(n)) => {
                self.counters.credential_renewals += 1;
                let next = self.cred_tx.borrow().clone().map(|mut c| {
                    c.token = n.token;
                    c.expires_at = n.expires_at;
                    c
                });
                self.cred_tx.send_replace(next);
                self.schedule_renew(now);
                tracing::info!(
                    target: "sew_call_client",
                    renewals = self.counters.credential_renewals,
                    expires_in_s = self.credential_left().unwrap_or_default().as_secs(),
                    "call credential renewed"
                );
                self.snapshot_update();
                if let Some(e) = held {
                    self.ended_soon(e);
                }
            }
            Ok(Err(api::ApiError::Status {
                status: 401,
                reason,
            })) => {
                // Sew's `401` reasons (`details.reason`) all end the call, each as itself:
                // `signed_out` (the login lineage has no live session) needs a sign-in,
                // `expired` is the credential's own expiry, `call_ended` (or none) is the
                // credential gone with its join. The reason also goes to the host as the
                // `errors` code. Sew's own end that raced this answer names the join's leave
                // reason, which `call_ended` cannot improve on.
                let why = reason.unwrap_or_else(|| "call_ended".to_owned());
                tracing::info!(target: "sew_call_client", reason = %why, "call credential renewal refused");
                self.error(&why, "the call credential was refused");
                let end = match why.as_str() {
                    "signed_out" => EndReason::SigninRequired,
                    "expired" => EndReason::CredentialExpired,
                    _ => held.unwrap_or(EndReason::CredentialLost),
                };
                self.end(end).await;
            }
            Ok(Err(api::ApiError::Status { status: 409, .. })) => {
                self.end(held.unwrap_or(EndReason::CredentialLost)).await
            }
            Ok(Err(e)) => {
                if let Some(h) = held {
                    self.ended_soon(h);
                    return;
                }
                let why = match e {
                    api::ApiError::Status { status, reason } => {
                        format!("{status} {}", reason.unwrap_or_default())
                    }
                    api::ApiError::Io(e) => e,
                };
                self.retry_renew(now, &why).await;
            }
            Err(e) => {
                if let Some(h) = held {
                    self.ended_soon(h);
                    return;
                }
                self.retry_renew(now, &e.to_string()).await;
            }
        }
    }

    // ------------------------------------------------------------------ signalling

    fn join_params(&self, kind: Kind) -> JoinParams {
        let token = self
            .session
            .refresh_token()
            .map(str::to_owned)
            .unwrap_or_else(|| self.answer.join.token.clone());
        let mut client_info = ClientInfoOpts::new();
        client_info.version = concat!("sew-call-client/", env!("CARGO_PKG_VERSION")).to_owned();
        let mut p = JoinParams::new(&token, client_info);
        if kind == Kind::Resume {
            p.reconnect = true;
            p.participant_sid = self.sid.clone();
        }
        p
    }

    fn start_attempt(&mut self, kind: Kind) {
        if kind == Kind::Full {
            let now = Instant::now();
            self.session.reset(now);
        }
        let params = self.join_params(kind);
        let cfg = self.cfg.clone();
        let tls = self.tls.clone();
        let base = self.answer.join.url.clone();
        self.link_id += 1;
        let id = self.link_id;
        let tx = self.sig_tx.clone();
        self.attempt = Some((
            tokio::spawn(async move { signal::connect(&cfg, &tls, &base, &params, id, tx).await }),
            kind,
        ));
    }

    fn on_attempt(
        &mut self,
        now: Instant,
        r: Result<Result<SignalLink, ConnectError>, tokio::task::JoinError>,
        kind: Kind,
    ) {
        match r {
            Ok(Ok(link)) => {
                // Signalling is back: no re-join waits for the old link. It is still read: the
                // engine may remove the old participant (its admit) just after this connect.
                if let Some(p) = self.parting.as_mut() {
                    p.rejoin = None;
                }
                self.link = Some(link);
                tracing::debug!(target: "sew_call_client", ?kind, "signalling connected");
            }
            Ok(Err(e)) => {
                tracing::info!(target: "sew_call_client", ?kind, ?e, "signalling connect failed");
                let refused = matches!(e, ConnectError::Refused { status: 401 | 403 });
                if let ConnectError::BadUrl(why) = &e {
                    self.error("network", why);
                    self.ended_soon(EndReason::Network);
                    return;
                }
                match &mut self.reconnect {
                    Some(r) => {
                        if refused && r.kind == Kind::Full {
                            // The engine no longer knows the token: the admit is gone.
                            self.start_rejoin(RejoinReason::AdmitLost);
                            return;
                        }
                        if refused {
                            r.kind = Kind::Full;
                        }
                        r.next_try = now + r.backoff;
                        r.backoff = (r.backoff * 2).min(BACKOFF_MAX);
                    }
                    None => {
                        // The first connect: retry inside the connect window.
                        if now >= self.connect_deadline || refused {
                            self.error("network", &format!("{e:?}"));
                            self.ended_soon(EndReason::Network);
                            return;
                        }
                        self.reconnect = Some(Reconnect {
                            initial: true,
                            kind: Kind::Full,
                            deadline: self.connect_deadline,
                            next_try: now + BACKOFF_MIN,
                            backoff: BACKOFF_MIN * 2,
                            attempt: 1,
                        });
                    }
                }
            }
            Err(_) => self.signal_lost(true),
        }
    }

    /// The WebSocket is gone (or must go). Resume when the session and PC are up, else
    /// reconnect fully; within a reconnect already running only an upgrade to full changes
    /// anything.
    fn signal_lost(&mut self, force_full: bool) {
        if self.ended.is_some() || self.pending_end.is_some() {
            return;
        }
        let now = Instant::now();
        // Media went (or the engine asked for a fresh join) and the link may still bring the
        // engine's leave; a move's old room is not this call's end.
        if let Some(link) = self.link.take()
            && force_full
            && !self.moving
        {
            self.parting = Some(Parting {
                id: self.link_id,
                _link: link,
                until: now + END_REASON_GRACE,
                rejoin: None,
            });
        }
        self.session.signal_lost();
        let pc_up = self
            .pc
            .as_ref()
            .is_some_and(|p| p.connected && p.ice != IceState::Disconnected);
        let kind = if force_full || self.sid.is_none() || !pc_up {
            Kind::Full
        } else {
            Kind::Resume
        };
        match self.reconnect.as_mut() {
            Some(r) => {
                if kind == Kind::Full {
                    r.kind = Kind::Full;
                }
                r.next_try = r.next_try.min(now);
            }
            None => {
                self.reconnect = Some(Reconnect {
                    initial: self.state == CallState::Connecting && !self.media_up,
                    kind,
                    deadline: now + self.cfg.reconnect_window,
                    next_try: now,
                    backoff: BACKOFF_MIN,
                    attempt: 1,
                });
            }
        }
        if self
            .reconnect
            .as_ref()
            .is_some_and(|r| r.kind == Kind::Full)
        {
            if let Some((a, _)) = self.attempt.take() {
                a.abort();
            }
            self.teardown_media();
        }
        self.update_state();
    }

    /// Drops the PC, the transport and the remote tracks (a full reconnect builds new ones).
    fn teardown_media(&mut self) {
        if let Some(mut pc) = self.pc.take() {
            pc.disconnect();
        }
        if let Some(o) = self.opening.take() {
            o.abort();
        }
        if let Some(o) = self.rebinding.take() {
            o.abort();
        }
        self.resume_waits_rebind = false;
        self.restart_deadline = None;
        self.transport = None;
        self.media_up = false;
        self.send = None;
        self.track_sid = None;
        self.published = None;
        self.publishing = false;
        self.cid_on_pc = false;
        self.pc_down_since = None;
        self.vpub.on_teardown();
        let slots: Vec<(u64, bool)> = self
            .tracks
            .drain()
            .map(|(_, s)| (s.id, s.announced))
            .collect();
        for (id, announced) in slots {
            self.meter.on_removed(id);
            if announced {
                self.frames_item(RecvItem::Removed { participant: id });
            }
        }
        let mut out = VideoOut::default();
        self.video.media_reset(&mut out);
        self.video_out(out);
    }

    fn reconnected(&mut self, kind: Kind) {
        let Some(r) = self.reconnect.take() else {
            return;
        };
        if r.initial {
            self.update_state();
            return;
        }
        match kind {
            Kind::Resume => self.counters.resumes += 1,
            Kind::Full => {
                self.counters.full_reconnects += 1;
                if let Some(k) = &self.keys {
                    k.media_reconnected(true);
                }
            }
        }
        self.moving = false;
        // The server's subscription state may be new (a full reconnect is a new participant):
        // every track's settings again.
        let mut out = VideoOut::default();
        self.video.resend_settings(&mut out);
        self.video_out(out);
        tracing::info!(target: "sew_call_client", ?kind, "reconnected");
        self.ensure_renew_scheduled(Instant::now());
        self.update_state();
    }

    fn start_rejoin(&mut self, why: RejoinReason) {
        if self.rejoining.is_some() || self.ended.is_some() || self.pending_end.is_some() {
            return;
        }
        if let Some(p) = self.parting.as_mut() {
            // The admit may be gone because the engine removed us: its leave decides first.
            tracing::debug!(target: "sew_call_client", ?why, "re-join waits for the old link");
            p.rejoin = Some(why);
            // No connect attempts and no other re-join meanwhile.
            if let Some(r) = self.reconnect.as_mut() {
                r.next_try = r.next_try.max(p.until);
                r.deadline = r.deadline.max(p.until);
            }
            return;
        }
        tracing::info!(target: "sew_call_client", ?why, "re-joining through the provider");
        self.teardown_media();
        self.link = None;
        if let Some((a, _)) = self.attempt.take() {
            a.abort();
        }
        let mut req = self.req.clone();
        req.rejoin = Some(why);
        req.muted = self.effective_muted();
        req.deafened = self.deafened;
        let p = self.provider.clone();
        self.rejoining = Some(tokio::spawn(async move { p.join(req).await }));
        let now = Instant::now();
        let r = self.reconnect.get_or_insert(Reconnect {
            initial: false,
            kind: Kind::Full,
            deadline: now + self.cfg.reconnect_window,
            next_try: now,
            backoff: BACKOFF_MIN,
            attempt: 1,
        });
        r.kind = Kind::Full;
        self.update_state();
    }

    async fn on_rejoined(
        &mut self,
        now: Instant,
        r: Result<Result<JoinAnswer, ProviderError>, tokio::task::JoinError>,
    ) {
        match r {
            Ok(Ok(answer)) => {
                self.counters.rejoins += 1;
                self.terms = answer.join.stats;
                self.meter.set_terms(self.terms.as_ref());
                if let Ok(mut r) = self.shared.stats.lock() {
                    r.terms = self.terms;
                }
                self.relay_only = answer.join.media.as_ref().is_some_and(|m| m.relay_only);
                self.cred_tx.send_replace(answer.call_credential().cloned());
                self.self_member = answer.join.state.member_id.to_string();
                self.joined_speak_denied = answer.join.state.speak_denied;
                if self.channel != answer.join.state.channel_id {
                    self.channel = answer.join.state.channel_id;
                    self.clear_controls();
                }
                let rec = answer.join.recording.clone();
                self.answer = answer;
                if let Ok(mut m) = self.shared.policy.lock() {
                    m.clone_from(&self.answer.join.media);
                }
                let api = self.lease_api();
                self.vpub.on_rejoined(self.answer.join.media.as_ref(), &api);
                self.apply_recording(rec);
                self.schedule_renew(now);
                if let Some(k) = self.keys.take() {
                    k.close().await;
                }
                self.start_keys(Some(RejoinReason::AdmitLost));
                self.session = Session::new(now);
                self.sid = None;
                if let Some(r) = self.reconnect.as_mut() {
                    r.kind = Kind::Full;
                    r.deadline = now + self.cfg.reconnect_window;
                    r.next_try = now;
                    r.backoff = BACKOFF_MIN;
                    r.attempt += 1;
                }
                self.start_attempt(Kind::Full);
                self.update_state();
            }
            Ok(Err(ProviderError::SigninRequired)) => self.end(EndReason::SigninRequired).await,
            Ok(Err(ProviderError::ConsentRequired(c))) => self.go_held(c).await,
            Ok(Err(ProviderError::Refused { code, detail })) => {
                self.error(&code, &detail.to_string());
                self.end(EndReason::Refused(code)).await;
            }
            Ok(Err(e)) => {
                self.error("network", &e.to_string());
                self.end(EndReason::Network).await;
            }
            Err(e) => {
                self.error("network", &e.to_string());
                self.end(EndReason::Network).await;
            }
        }
    }

    async fn on_timeout(&mut self, now: Instant) {
        if let Some((at, r)) = &self.pending_end
            && now >= *at
        {
            let r = r.clone();
            tracing::info!(target: "sew_call_client", ?r, "no reason from Sew's call socket in time");
            self.end(r).await;
            return;
        }
        if self.parting.as_ref().is_some_and(|p| now >= p.until) {
            self.end_parting();
        }
        if let Some(pc) = self.pc.as_mut()
            && pc.timeout() <= now
        {
            pc.handle_timeout(now);
        }
        self.session.handle_timeout(now);
        if self.renew_at.is_some_and(|t| t <= now) && self.renewing.is_none() {
            self.renew_at = None;
            let cred = self.cred_tx.borrow().clone();
            if let Some(c) = cred {
                let http = self.http.clone();
                let base = self.answer.api_base.clone();
                self.renewing = Some(tokio::spawn(async move {
                    api::renew(&http, &base, &c.token).await
                }));
            }
        }
        if let Some(d) = self.pc_down_since
            && now >= d + PC_FAIL_GRACE
        {
            self.pc_down_since = None;
            tracing::info!(target: "sew_call_client", "ICE down; full reconnect");
            self.signal_lost(true);
        }
        if let Some(d) = self.restart_deadline
            && now >= d
        {
            self.restart_deadline = None;
            if self
                .pc
                .as_ref()
                .is_some_and(|p| p.ice != IceState::Connected)
            {
                tracing::info!(target: "sew_call_client", "no ICE on the new network; full reconnect");
                self.signal_lost(true);
            }
        }
        if let Some(r) = &self.reconnect
            && self.rejoining.is_none()
        {
            if now >= r.deadline {
                if r.initial {
                    // Never connected inside the connect window.
                    self.error("network", "the first connect timed out");
                    self.end(EndReason::Network).await;
                    return;
                }
                self.start_rejoin(RejoinReason::AdmitLost);
            } else if self.attempt.is_none() && self.link.is_none() && now >= r.next_try {
                let kind = r.kind;
                self.start_attempt(kind);
            }
        }
        self.expire_gaps(now);
        self.video_tick(now);
        if self.media_up && now >= self.next_speaking {
            self.next_speaking = now + SPEAKING_EVERY;
            self.emit_speaking();
        }
        if self.vpub.deadline().is_some_and(|d| now >= d) {
            let mut cx = video_cx!(self, now);
            self.vpub.on_timeout(&mut cx);
            self.negotiate();
        }
    }

    // ------------------------------------------------------------------ session events

    fn drain_session(&mut self, now: Instant) {
        while let Some(ev) = self.session.poll_event() {
            self.on_session(now, ev);
        }
    }

    // One arm per event: the arms' conditions stay in their bodies rather than becoming guards
    // that fall through to the arm for events sew-lk-compat adds later.
    #[allow(clippy::collapsible_match)]
    fn on_session(&mut self, now: Instant, ev: SessionEvent) {
        match ev {
            SessionEvent::Joined {
                identity,
                sid,
                ice_servers,
                force_relay,
            } => {
                self.identity = Some(identity);
                self.sid = Some(sid);
                if force_relay {
                    self.relay_only = true;
                }
                let gather = if self.relay_only {
                    Gather::RelayOnly
                } else {
                    Gather::All
                };
                let cfg = self.cfg.clone();
                let tls = self.tls.clone();
                self.teardown_media();
                self.ice_servers = ice_servers.clone();
                self.opening = Some(tokio::spawn(async move {
                    Transport::open(&cfg, &tls, &ice_servers, gather).await
                }));
                self.send_roster();
                self.emit_participants();
            }
            SessionEvent::Answer {
                sdp,
                mid_to_track_id,
                ..
            } => self.on_answer(&sdp, &mid_to_track_id),
            SessionEvent::Offer { .. } => {
                tracing::debug!(target: "sew_call_client", "an engine offer on the single PC (ignored)");
            }
            SessionEvent::RemoteCandidate { candidate } => {
                if let Some(pc) = self.pc.as_mut() {
                    pc.add_remote_candidate(&candidate);
                }
            }
            SessionEvent::MediaSections { audios, videos } => {
                if let Some(pc) = self.pc.as_mut() {
                    pc.add_recv_audio(audios);
                    pc.add_recv_video(videos);
                    if audios == 0 && (videos == 0 || !crate::pc::VIDEO) {
                        pc.renegotiate();
                    }
                }
                self.negotiate();
            }
            SessionEvent::TrackPublished { cid, track } => {
                if cid == self.cid && self.publishing {
                    self.publishing = false;
                    self.cid_on_pc = true;
                    let stream = self.sid.clone().unwrap_or_default();
                    if let Some(k) = &self.keys
                        && !k.published(&track)
                    {
                        self.error(
                            "e2ee_refused",
                            "the engine did not confirm the publication encrypted",
                        );
                    }
                    self.track_sid = Some(track.sid.clone());
                    self.published = Some(track);
                    if let Some(pc) = self.pc.as_mut() {
                        pc.add_send_audio(&stream, &cid);
                    }
                    if self.effective_muted() {
                        self.send_mute_signal();
                    }
                    self.negotiate();
                } else if cid != self.cid {
                    let mut cx = video_cx!(self, now);
                    self.vpub.on_track_published(&mut cx, &cid, &track);
                    self.negotiate();
                }
            }
            SessionEvent::SubscribedQuality(u) => {
                let mut cx = video_cx!(self, now);
                self.vpub.on_subscribed_quality(&mut cx, &u);
            }
            SessionEvent::TrackUnpublished { sid } => {
                let mut cx = video_cx!(self, now);
                self.vpub.on_track_unpublished(&mut cx, &sid);
                self.negotiate();
            }
            SessionEvent::Participants => {
                self.roster_changed();
                self.video_roster(now);
                self.send_roster();
                self.emit_participants();
                self.local_permission_changed();
            }
            SessionEvent::Speakers(s) => {
                for sp in s {
                    if sp.active {
                        self.engine_levels.insert(sp.sid, sp.level);
                    } else {
                        self.engine_levels.remove(&sp.sid);
                    }
                }
                let speaking = self.engine_levels.keys().cloned().collect();
                let mut out = VideoOut::default();
                self.video.speakers(now, speaking, &mut out);
                self.video_out(out);
            }
            SessionEvent::StreamStates(states) => {
                let mut out = VideoOut::default();
                self.video.stream_states(&states, &mut out);
                self.video_out(out);
            }
            SessionEvent::Muted { sid, muted } => {
                if self.track_sid.as_deref() == Some(sid.as_str()) {
                    self.server_muted = muted;
                    self.frames_item(RecvItem::Capture(!self.send_blocked()));
                    self.emit_participants();
                }
            }
            SessionEvent::Resumed { .. } => {
                if let Some(pc) = self.pc.as_mut() {
                    pc.forget_pending_offer();
                }
                let mut out = VideoOut::default();
                self.video.resumed(&mut out);
                self.video_out(out);
                if self.rebinding.is_some() {
                    // A network change: the restart runs once the new transport is in.
                    self.resume_waits_rebind = true;
                } else {
                    self.restart_ice();
                }
            }
            SessionEvent::Leave { reason, action } => {
                tracing::info!(target: "sew_call_client", reason, ?action, "engine leave");
                match action {
                    LeaveAction::Resume => self.signal_lost(false),
                    LeaveAction::Reconnect => self.signal_lost(true),
                    LeaveAction::Disconnect => {
                        // DisconnectReason: 4 PARTICIPANT_REMOVED, 2 DUPLICATE_IDENTITY, 5
                        // ROOM_DELETED, 10 ROOM_CLOSED; a server shutdown or a migration may
                        // come back, so it reconnects within the window.
                        match engine_end_reason(reason) {
                            Some(r) => self.engine_disconnected(now, r),
                            None => self.signal_lost(true),
                        }
                    }
                    // An action sew-lk-compat adds later: reconnect within the window.
                    _ => self.signal_lost(true),
                }
            }
            SessionEvent::Refused {
                request_id,
                reason,
                message,
            } => {
                tracing::info!(target: "sew_call_client", request_id, reason, %message, "request refused");
            }
            // An event sew-lk-compat adds later: nothing to do here yet.
            _ => {}
        }
        let _ = now;
    }

    async fn on_opened(
        &mut self,
        now: Instant,
        r: Result<Result<Transport, TransportError>, tokio::task::JoinError>,
    ) {
        match r {
            Ok(Ok(t)) => {
                if t.relay_via().is_some() {
                    self.counters.turn_allocations += 1;
                }
                let mut pc = Pc::new_with(
                    t.local_candidates(),
                    now,
                    self.vpub.may_send(),
                    self.shared.video_codecs,
                );
                pc.handle_timeout(now);
                self.transport = Some(t);
                self.pc = Some(pc);
                // A new SRTP session: never continue the old one's sequence (its rollover).
                self.send_seq = fresh_send_seq(&self.cfg);
                tracing::info!(target: "sew_call_client", first_seq = self.send_seq, "new media session");
                self.publishing = false;
                self.cid_on_pc = false;
                // Without SPEAK nothing is published until the engine allows the microphone.
                self.maybe_publish();
                let mut cx = video_cx!(self, now);
                self.vpub.on_new_pc(&mut cx);
                self.negotiate();
                self.speak_changed();
                self.snapshot_update();
            }
            Ok(Err(TransportError::RelayOnlyNoTurns)) => {
                self.error(
                    "relay_only_no_turns",
                    "relay-only, but the engine offered no turns: server",
                );
                self.end(EndReason::Network).await;
            }
            Ok(Err(e)) => {
                self.error("turn_unreachable", &e.to_string());
                self.signal_lost(true);
            }
            Err(_) => self.signal_lost(true),
        }
    }

    /// The resume's ICE restart (after a network change: over the swapped transport).
    fn restart_ice(&mut self) {
        if let Some(pc) = self.pc.as_mut() {
            pc.ice_restart();
        }
        self.negotiate();
        self.reconnected(Kind::Resume);
    }

    /// A network change is under way (its transport opening, or the resume waiting for it).
    fn changing_network(&self) -> bool {
        self.rebinding.is_some() || self.resume_waits_rebind
    }

    /// The host says the network changed ([`crate::Call::network_changed`]).
    fn network_changed(&mut self, now: Instant) {
        self.counters.network_changes += 1;
        if self.ended.is_some() || self.pending_end.is_some() {
            return;
        }
        if let Some(k) = &self.keys {
            k.network_changed();
        }
        if self.rejoining.is_some() {
            // A re-join through the provider is under way: it connects afresh.
            return;
        }
        let pc_connected = self.pc.as_ref().is_some_and(|p| p.connected);
        let full = self
            .reconnect
            .as_ref()
            .is_some_and(|r| r.kind == Kind::Full);
        if self.sid.is_none() || !pc_connected || full {
            // Not connected yet, or already rebuilding everything: retry the connect now, on
            // the new network.
            tracing::info!(target: "sew_call_client", "network changed; connecting again now");
            if let Some((a, _)) = self.attempt.take() {
                a.abort();
            }
            self.link = None;
            if let Some(r) = self.reconnect.as_mut() {
                r.next_try = now;
                r.backoff = BACKOFF_MIN;
                if r.kind == Kind::Full {
                    self.teardown_media();
                }
            } else {
                self.signal_lost(true);
            }
            self.update_state();
            return;
        }
        tracing::info!(target: "sew_call_client", "network changed; resuming on a fresh transport");
        // The resume: a new WebSocket now (the old one may be dead on the old network).
        if let Some((a, _)) = self.attempt.take() {
            a.abort();
        }
        self.link = None;
        self.session.signal_lost();
        self.pc_down_since = None;
        self.restart_deadline = None;
        match self.reconnect.as_mut() {
            Some(r) => {
                r.next_try = now;
                r.backoff = BACKOFF_MIN;
            }
            None => {
                self.reconnect = Some(Reconnect {
                    initial: false,
                    kind: Kind::Resume,
                    deadline: now + self.cfg.reconnect_window,
                    next_try: now,
                    backoff: BACKOFF_MIN,
                    attempt: 1,
                });
            }
        }
        self.resume_waits_rebind = false;
        // And the transport on the new network, in parallel.
        if let Some(o) = self.rebinding.take() {
            o.abort();
        }
        let gather = if self.relay_only {
            Gather::RelayOnly
        } else {
            Gather::All
        };
        let (cfg, tls, servers) = (self.cfg.clone(), self.tls.clone(), self.ice_servers.clone());
        self.rebinding = Some(tokio::spawn(async move {
            Transport::open(&cfg, &tls, &servers, gather).await
        }));
        self.start_attempt(Kind::Resume);
        self.update_state();
    }

    /// A network change's transport opened: swap it into the PC, then restart ICE once the
    /// session has resumed.
    fn on_rebound(
        &mut self,
        now: Instant,
        r: Result<Result<Transport, TransportError>, tokio::task::JoinError>,
    ) {
        let t = match r {
            Ok(Ok(t)) => t,
            Ok(Err(e)) => {
                tracing::info!(target: "sew_call_client", error = %e, "no transport on the new network; full reconnect");
                self.resume_waits_rebind = false;
                self.signal_lost(true);
                return;
            }
            Err(_) => {
                self.resume_waits_rebind = false;
                self.signal_lost(true);
                return;
            }
        };
        let Some(pc) = self.pc.as_mut() else {
            // A full reconnect replaced the PC meanwhile: it opens its own transport.
            self.resume_waits_rebind = false;
            return;
        };
        if t.relay_via().is_some() {
            self.counters.turn_allocations += 1;
        }
        pc.replace_local_candidates(t.local_candidates());
        // The old transport goes (its TURN allocation is released when it can be).
        self.transport = Some(t);
        self.restart_deadline = Some(now + RESTART_GRACE);
        if std::mem::take(&mut self.resume_waits_rebind) {
            self.restart_ice();
        }
        self.snapshot_update();
    }

    fn negotiate(&mut self) {
        let Some(pc) = self.pc.as_mut() else { return };
        if let Some((sdp, id)) = pc.negotiate() {
            self.session.offer(sdp, id);
        }
    }

    fn on_answer(&mut self, sdp: &str, mid_to_track_id: &BTreeMap<String, String>) {
        let Some(pc) = self.pc.as_mut() else { return };
        if let Err(e) = pc.handle_answer(sdp) {
            tracing::info!(target: "sew_call_client", error = %e, "answer refused; full reconnect");
            self.signal_lost(true);
            return;
        }
        for (mid, track) in mid_to_track_id {
            pc.set_msid(mid, "", track);
        }
        if self.send.is_none()
            && self.track_sid.is_some()
            && let Some(mid) = pc.mid_for_track(&self.cid)
            && let (Some(pt), Some(ssrc)) = (pc.opus_pt(&mid), pc.tx_ssrc(&mid))
        {
            self.send = Some(SendPath { mid, pt, ssrc });
        }
        let mut cx = video_cx!(self, Instant::now());
        self.vpub.on_answer(&mut cx);
        if self.pc.as_ref().is_some_and(Pc::needs_negotiation) {
            self.negotiate();
        }
    }

    // ------------------------------------------------------------------ PC events

    fn on_pc(&mut self, now: Instant, ev: PcEvent) {
        match ev {
            PcEvent::Connected => {
                self.media_up = true;
                self.pc_down_since = None;
                if self
                    .reconnect
                    .as_ref()
                    .is_some_and(|r| r.kind == Kind::Full)
                    && self.link.is_some()
                {
                    self.reconnected(Kind::Full);
                }
                self.update_state();
            }
            PcEvent::Ice(IceState::Disconnected) => {
                // During a network change the old path going down is expected
                // (`restart_deadline` takes over after the swap).
                if !self.changing_network() {
                    self.pc_down_since.get_or_insert(now);
                }
            }
            PcEvent::Ice(IceState::Connected) => {
                self.pc_down_since = None;
                self.restart_deadline = None;
            }
            PcEvent::Ice(IceState::Checking) => {}
            PcEvent::Rtp(r) => self.on_rtp(now, r),
            PcEvent::KeyframeRequest { mid, rid } => {
                self.vpub.on_keyframe_request(now, &mid, rid.as_deref());
            }
            PcEvent::Bwe(bps) => {
                let mut cx = video_cx!(self, now);
                self.vpub.on_estimate(&mut cx, bps);
            }
            PcEvent::Peer { local, rtt } => {
                if let Some(r) = rtt {
                    self.video.set_rtt(r);
                }
                let path = local.and_then(|a| self.path_of(a));
                self.meter.on_peer(path, rtt);
            }
        }
    }

    // ------------------------------------------------------------------ media

    fn send_frame(&mut self, now: Instant, f: OpusFrame) {
        self.local_level = if f.vad {
            dbov_to_unit(f.level_dbov)
        } else {
            0.0
        };
        if self.send_blocked() || !self.media_up || f.payload.is_empty() {
            self.counters.frames_not_sent += 1;
            return;
        }
        let (Some(send), Some(keys), Some(pc)) = (&self.send, &self.keys, self.pc.as_mut()) else {
            self.counters.frames_not_sent += 1;
            return;
        };
        let mut out = Vec::with_capacity(f.payload.len() + 32);
        if keys
            .encrypt(&f.payload, send.ssrc, f.ts48k, &mut out)
            .is_err()
            || out.is_empty()
        {
            // No send key (or the frame did not encrypt): dropped, never sent in the clear.
            self.counters.frames_not_sent += 1;
            return;
        }
        let seq = self.send_seq;
        self.send_seq += 1;
        match pc.write_audio(
            &send.mid,
            send.pt,
            seq,
            f.ts48k,
            now,
            out,
            rfc6464(f.level_dbov),
            f.vad,
        ) {
            Ok(()) => self.counters.frames_sent += 1,
            Err(_) => self.counters.frames_not_sent += 1,
        }
    }

    /// The track sid and publisher identity of a receive section.
    fn sender_of(&self, mid: &str) -> Option<(String, String)> {
        let (stream, track) = self.pc.as_ref()?.msid(mid)?;
        let track_sid = stream
            .split_once('|')
            .map(|(_, t)| t.to_owned())
            .filter(|t| t.starts_with("TR_"))
            .unwrap_or_else(|| track.clone());
        let psid = stream.split_once('|').map(|(p, _)| p.to_owned());
        let remotes = self.session.remotes();
        let identity = psid
            .and_then(|s| remotes.get(&s).map(|p| p.identity.clone()))
            .or_else(|| {
                self.session
                    .publisher_of(&track_sid)
                    .map(|p| p.identity.clone())
            })?;
        Some((track_sid, identity))
    }

    fn remote_track(&self, track_sid: &str) -> Option<RemoteTrack> {
        let p = self.session.publisher_of(track_sid)?;
        let t = p.tracks.iter().find(|t| t.sid == track_sid)?;
        Some(RemoteTrack {
            sid: t.sid.clone(),
            encryption: t.encryption,
            mime: t.mime_type.clone(),
            audio: t.r#type == sew_lkproto::livekit::TrackType::Audio as i32,
        })
    }

    fn on_rtp(&mut self, now: Instant, r: crate::pc::RtpRx) {
        if let Some(codec) = r.video {
            self.on_video_rtp(now, r, codec);
            return;
        }
        let Some((track_sid, identity)) = self.sender_of(&r.mid) else {
            self.counters.refused_frames += 1;
            return;
        };
        let Some(keys) = self.keys.clone() else {
            self.counters.refused_frames += 1;
            return;
        };
        if !self.tracks.contains_key(&track_sid) {
            let id = self.next_track_id;
            self.next_track_id += 1;
            self.tracks.insert(
                track_sid.clone(),
                RemoteSlot {
                    id,
                    identity: identity.clone(),
                    allowed: Subscribe::NotYet,
                    announced: false,
                    unsubscribed: false,
                    highest: None,
                    gaps: VecDeque::new(),
                },
            );
        }
        let verdict = match self.remote_track(&track_sid) {
            Some(t) => keys.may_subscribe(&identity, &t),
            None => Subscribe::NotYet,
        };
        let mut unsubscribe = false;
        let mut items = Vec::new();
        {
            let Some(slot) = self.tracks.get_mut(&track_sid) else {
                return;
            };
            slot.allowed = verdict.clone();
            match verdict {
                Subscribe::Yes => {}
                Subscribe::NotYet => {
                    self.counters.refused_frames += 1;
                    return;
                }
                Subscribe::No { reason } => {
                    self.counters.refused_frames += 1;
                    if !slot.unsubscribed {
                        slot.unsubscribed = true;
                        unsubscribe = true;
                        tracing::warn!(target: "sew_call_client", track = %track_sid, %reason, "refusing a remote track");
                    }
                }
            }
            if !unsubscribe && slot.allowed == Subscribe::Yes {
                self.meter.on_packet(slot.id, r.seq, r.timestamp, now);
                // Loss marks: gaps that do not fill within LOSS_GRACE.
                match slot.highest {
                    None => slot.highest = Some(r.seq),
                    Some(h) if r.seq > h => {
                        let gap = r.seq - h - 1;
                        if gap > 0 && gap <= u64::from(LOSS_MAX_GAP) {
                            for s in (h + 1)..r.seq {
                                slot.gaps.push_back((s, now + LOSS_GRACE));
                            }
                        }
                        slot.highest = Some(r.seq);
                    }
                    Some(_) => slot.gaps.retain(|(s, _)| *s != r.seq),
                }
                let mut out = Vec::with_capacity(r.payload.len());
                match keys.decrypt(&identity, &r.payload, &mut out) {
                    Ok(()) if !out.is_empty() => {
                        if !slot.announced {
                            slot.announced = true;
                            items.push(RecvItem::Added {
                                participant: slot.id,
                                identity: slot.identity.clone(),
                            });
                        }
                        self.counters.frames_received += 1;
                        items.push(RecvItem::Frame(RecvOpus {
                            participant: slot.id,
                            identity: identity.clone(),
                            payload: Bytes::from(out),
                            seq: r.seq as u16,
                            ts48k: r.timestamp,
                            arrival: now,
                        }));
                    }
                    Ok(()) => {}
                    Err(e) => {
                        use crate::e2ee::CryptoError as E;
                        match e {
                            // Crossed a join or a key switch: the key is not installed yet.
                            E::KeyPending => self.counters.frames_before_key += 1,
                            // The sender is no longer a verified publisher: refused, as before
                            // the subscription.
                            E::NoKey => self.counters.refused_frames += 1,
                            _ => self.counters.decrypt_failures += 1,
                        }
                        if slot.announced {
                            self.counters.lost_marks += 1;
                            items.push(RecvItem::Lost {
                                participant: slot.id,
                                seq: r.seq as u16,
                            });
                        }
                    }
                }
            }
        }
        for it in items {
            self.frames_item(it);
        }
        if unsubscribe {
            let req = SignalRequest {
                message: Some(signal_request::Message::Subscription(UpdateSubscription {
                    track_sids: vec![track_sid],
                    subscribe: false,
                    ..UpdateSubscription::default()
                })),
            };
            if let Some(l) = &self.link {
                l.send(req);
            }
        }
    }

    // ------------------------------------------------------------------ video (receive)

    /// One video RTP packet: to its track's pipeline, if the keys allow the track.
    fn on_video_rtp(&mut self, now: Instant, r: crate::pc::RtpRx, codec: crate::video::VideoCodec) {
        if crate::config::drop_video_packet(&self.cfg) {
            // A lane's lost burst (feature `testing` only).
            return;
        }
        let Some((track_sid, identity)) = self.sender_of(&r.mid) else {
            self.counters.video_packets_unwanted += 1;
            return;
        };
        let Some(keys) = self.keys.clone() else {
            self.counters.refused_frames += 1;
            return;
        };
        let verdict = match self.remote_track(&track_sid) {
            Some(t) => keys.may_subscribe(&identity, &t),
            None => Subscribe::NotYet,
        };
        match verdict {
            Subscribe::Yes => {}
            Subscribe::NotYet => {
                self.counters.refused_frames += 1;
                return;
            }
            Subscribe::No { reason } => {
                self.counters.refused_frames += 1;
                if self.video_refused.insert(track_sid.clone()) {
                    tracing::warn!(target: "sew_call_client", track = %track_sid, %reason, "refusing a remote video track");
                    let req = SignalRequest {
                        message: Some(signal_request::Message::Subscription(UpdateSubscription {
                            track_sids: vec![track_sid],
                            subscribe: false,
                            ..UpdateSubscription::default()
                        })),
                    };
                    if let Some(l) = &self.link {
                        l.send(req);
                    }
                }
                return;
            }
        }
        let mut out = VideoOut::default();
        self.video.on_rtp(
            now,
            &track_sid,
            &identity,
            &r,
            codec,
            keys.as_ref(),
            &mut self.counters,
            &mut out,
        );
        self.video_out(out);
    }

    /// The roster changed: the video tracks follow it.
    fn video_roster(&mut self, now: Instant) {
        if !crate::pc::VIDEO {
            // A build without video sends and announces nothing for video tracks: its calls
            // signal as voice-only calls always did.
            return;
        }
        let mut out = VideoOut::default();
        let remotes = self.session.remotes().clone();
        self.video.roster(now, &remotes, &self.members, &mut out);
        let live: std::collections::HashSet<&String> = remotes
            .values()
            .flat_map(|p| p.tracks.iter().map(|t| &t.sid))
            .collect();
        self.video_refused.retain(|s| live.contains(s));
        self.video_out(out);
    }

    /// Time passed for the video pipelines.
    fn video_tick(&mut self, now: Instant) {
        let mut out = VideoOut::default();
        let keys = self.keys.clone();
        self.video
            .tick(now, keys.as_deref(), &mut self.counters, &mut out);
        self.video_out(out);
    }

    /// Carries out what the video side asked for.
    fn video_out(&mut self, out: VideoOut) {
        for r in out.requests {
            if let Some(l) = &self.link {
                l.send(r);
            }
        }
        if let Some(pc) = self.pc.as_mut() {
            for (ssrc, fir) in out.keyframes {
                let sent = pc.request_keyframe(ssrc, fir);
                tracing::debug!(target: "sew_call_client", ssrc, fir, sent, "video keyframe request");
            }
        }
        if !out.events.is_empty() {
            // The snapshot first: a host that reads it on the event sees the change.
            self.snapshot_update();
        }
        for e in out.events {
            let _ = self.shared.events.send(e);
        }
        for sid in out.stalled {
            self.error(
                "video_stalled",
                &format!("no keyframe on video track {sid} 5 s after a FIR"),
            );
        }
        let mut undelivered = Vec::new();
        for it in out.items {
            let track = match &it {
                VideoRecvItem::Frame(f) => Some(f.track),
                _ => None,
            };
            match self.video_tx.try_send(it) {
                Ok(()) => {}
                Err(mpsc::error::TrySendError::Full(_)) => {
                    self.counters.video_recv_queue_drops += 1;
                    if let Some(t) = track {
                        undelivered.push(t);
                    }
                }
                Err(mpsc::error::TrySendError::Closed(_)) => {}
            }
        }
        if !undelivered.is_empty() {
            let mut out = VideoOut::default();
            for t in undelivered {
                self.video.frame_not_delivered(t, &mut out);
            }
            // Only control items, keyframe requests and no frames: no further recursion.
            self.video_out(out);
        }
    }

    fn expire_gaps(&mut self, now: Instant) {
        let mut items = Vec::new();
        for s in self.tracks.values_mut() {
            while let Some((seq, at)) = s.gaps.front().copied() {
                if at > now {
                    break;
                }
                s.gaps.pop_front();
                if s.announced {
                    items.push(RecvItem::Lost {
                        participant: s.id,
                        seq: seq as u16,
                    });
                }
            }
        }
        self.counters.lost_marks += items.len() as u64;
        for it in items {
            self.frames_item(it);
        }
    }

    /// Removes the tracks whose publisher or track left the roster.
    fn roster_changed(&mut self) {
        let live: std::collections::HashSet<String> = self
            .session
            .remotes()
            .values()
            .flat_map(|p| p.tracks.iter().map(|t| t.sid.clone()))
            .collect();
        let gone: Vec<String> = self
            .tracks
            .keys()
            .filter(|k| !live.contains(*k))
            .cloned()
            .collect();
        for k in gone {
            if let Some(s) = self.tracks.remove(&k) {
                self.meter.on_removed(s.id);
                if s.announced {
                    self.frames_item(RecvItem::Removed { participant: s.id });
                }
            }
        }
    }

    fn emit_speaking(&mut self) {
        let mut v = Vec::new();
        if let Some(me) = &self.identity
            && !self.send_blocked()
            && self.local_level > 0.0
        {
            v.push(Speaking {
                identity: me.clone(),
                member_id: self.members.get(me).cloned(),
                level: self.local_level,
            });
        }
        let by_sid: BTreeMap<&String, &String> = self
            .session
            .remotes()
            .iter()
            .map(|(sid, p)| (sid, &p.identity))
            .collect();
        for (sid, level) in &self.engine_levels {
            if let Some(identity) = by_sid.get(sid) {
                v.push(Speaking {
                    identity: (*identity).clone(),
                    member_id: self.members.get(*identity).cloned(),
                    level: *level,
                });
            }
        }
        if v != self.last_speaking {
            self.last_speaking = v.clone();
            let _ = self.shared.events.send(CallEvent::Speaking(v));
        }
    }

    // ------------------------------------------------------------------ mute

    fn send_mute_signal(&mut self) {
        if let Some(sid) = self.track_sid.clone() {
            let m = self.effective_muted();
            self.session.mute(&sid, m);
        }
    }

    fn set_mute(&mut self, muted: Option<bool>, deafened: Option<bool>) {
        let before = (self.self_muted, self.deafened);
        if let Some(d) = deafened {
            if d && !self.deafened {
                self.muted_before_deafen = self.self_muted;
                self.self_muted = true;
            } else if !d && self.deafened {
                self.self_muted = self.muted_before_deafen;
            }
            self.deafened = d;
        }
        if let Some(m) = muted {
            self.self_muted = m || self.deafened;
            if !self.deafened {
                self.muted_before_deafen = self.self_muted;
            }
        }
        if before == (self.self_muted, self.deafened) {
            return;
        }
        // Without SPEAK there is no publication to unmute: capture stays off, and the self-mute
        // is kept for when SPEAK comes back.
        self.send_mute_signal();
        self.frames_item(RecvItem::Capture(!self.send_blocked()));
        self.frames_item(RecvItem::Deafened(self.deafened));
        let cred = self.cred_tx.borrow().clone();
        if let Some(c) = cred {
            let http = self.http.clone();
            let base = self.answer.api_base.clone();
            let (m, d) = (self.self_muted, self.deafened);
            tokio::spawn(async move {
                if let Err(e) = api::self_state(&http, &base, &c.token, m, d).await {
                    tracing::info!(target: "sew_call_client", ?e, "self state not saved");
                }
            });
        }
        self.emit_participants();
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used)]
    use super::*;

    fn controls(can_record: bool, can_stop: bool, rev: u64) -> RecordingControls {
        let mut c = RecordingControls::new(can_record, can_stop);
        c.rev = rev;
        c
    }

    /// An older Sew: its call socket's READY has no `recording_controls` and its recordings no
    /// `my_controls`, so the engine is never told any: the call stays without server controls
    /// (the host works Record and Stop out itself).
    #[test]
    fn an_older_server_sends_no_controls() {
        let recording = serde_json::json!({
            "id": "77", "channel_id": "2002", "state": "recording", "started_by": "1001",
            "started_at": "2026-11-04T10:00:00Z", "auto": false, "message_id": "88",
            "mixed": false, "audio_keep_days": 30, "max_duration_ms": 14400000,
            "participants": [], "my_consent": "granted", "trigger": "manual"
        });
        let ready = serde_json::json!({
            "v": 1, "session_id": "gw_1", "user": {"id": "42"}, "install_id": "9001",
            "recording": recording
        });
        let info = crate::gateway::parse_ready(&ready).unwrap();
        assert_eq!(info.recording_controls, None, "no word from READY");
        let rec = info.recording.unwrap().unwrap();
        assert_eq!(rec.my_controls, None, "no word in the recording");
        assert_eq!(CallRecording::from_sew(&rec).my_controls, None);
        let s = CallSnapshot::default();
        assert!(!s.server_controls);
        assert_eq!(s.recording_controls, None);
        // Its recording_updated reads the same way.
        let ev = crate::gateway::filter_dispatch(
            "recording_updated",
            &serde_json::json!({ "recording": recording_json_without_controls() }),
        );
        match ev {
            Some(crate::gateway::SocketEvent::RecordingUpdated(r)) => {
                assert_eq!(r.my_controls, None);
            }
            other => panic!("recording_updated: {other:?}"),
        }
    }

    fn recording_json_without_controls() -> serde_json::Value {
        serde_json::json!({
            "id": "77", "channel_id": "2002", "state": "recording", "started_by": "1001",
            "started_at": "2026-11-04T10:00:00Z", "auto": false, "message_id": "88",
            "mixed": false, "audio_keep_days": 30, "max_duration_ms": 14400000,
            "participants": []
        })
    }

    /// A server that computes them: READY's `null` turns server controls on with no value
    /// (the host hears `None` once); values follow by `rev`; another room's value only says
    /// the server sends them; a move clears the value.
    #[test]
    fn server_controls_keep_the_newest_for_the_call_room() {
        let mut s = CallSnapshot::default();
        assert_eq!(merge_controls(&mut s, true, None), Some(None));
        assert!(s.server_controls);
        // Nothing new: nothing to tell.
        assert_eq!(merge_controls(&mut s, true, None), None);
        let v = merge_controls(&mut s, true, Some(&controls(true, false, 10)))
            .unwrap()
            .unwrap();
        assert_eq!((v.can_record, v.can_stop, v.rev), (true, false, 10));
        // The same value again (a recording's `my_controls` beside the event): nothing.
        assert_eq!(
            merge_controls(&mut s, true, Some(&controls(true, false, 10))),
            None
        );
        // An older value loses to the newer one.
        assert_eq!(
            merge_controls(&mut s, true, Some(&controls(false, true, 9))),
            None
        );
        assert_eq!(s.recording_controls.unwrap().rev, 10);
        // Another room's value is not this call's.
        assert_eq!(
            merge_controls(&mut s, false, Some(&controls(false, true, 11))),
            None
        );
        assert_eq!(s.recording_controls.unwrap().rev, 10);
        // A newer one with the hint.
        let mut hinted = controls(true, false, 12);
        hinted.record_unavailable =
            Some(sew_proto::recording::RecordUnavailable::RecorderUnavailable);
        let v = merge_controls(&mut s, true, Some(&hinted))
            .unwrap()
            .unwrap();
        assert_eq!(
            v.record_unavailable,
            Some(sew_proto::recording::RecordUnavailable::RecorderUnavailable)
        );
        // A move: cleared once, then the destination's first value is taken whatever its rev.
        assert!(clear_controls_in(&mut s));
        assert!(!clear_controls_in(&mut s));
        assert!(s.server_controls, "the server still sends them");
        let v = merge_controls(&mut s, true, Some(&controls(false, false, 13)))
            .unwrap()
            .unwrap();
        assert_eq!(v.rev, 13);
        // The snapshot carries both, for a late subscriber.
        let json = serde_json::to_value(&s).unwrap();
        assert_eq!(json["server_controls"], serde_json::json!(true));
        assert_eq!(json["recording_controls"]["rev"], serde_json::json!(13));
        assert!(
            serde_json::to_value(CallSnapshot::default())
                .unwrap()
                .get("server_controls")
                .is_none()
        );
    }

    #[test]
    fn levels() {
        assert_eq!(rfc6464(0.0), 0);
        assert_eq!(rfc6464(-30.5), 30);
        assert_eq!(rfc6464(-200.0), 127);
        assert_eq!(rfc6464(f32::NAN), 127);
        assert!((dbov_to_unit(0.0) - 1.0).abs() < 1e-6);
        assert!(dbov_to_unit(-80.0).abs() < 1e-6);
    }

    #[test]
    fn sew_reasons_end_the_call_unchanged() {
        for r in [
            "perms_lost",
            "removed_from_space",
            "timed_out",
            "channel_archived",
            "account_removed",
            "removed_by_moderator",
            "session_revoked",
            "device_revoked",
            "media_path_down",
            "some_reason_from_a_later_sew",
        ] {
            assert_eq!(
                end_for_sew_reason(r),
                EndReason::Removed(r.to_owned()),
                "{r}"
            );
        }
        // A swap is the device takeover; a leave from elsewhere is a leave.
        assert_eq!(end_for_sew_reason("replaced"), EndReason::CredentialLost);
        assert_eq!(end_for_sew_reason("left"), EndReason::Left);
    }

    #[test]
    fn a_move_names_the_destination_room() {
        let mut v = serde_json::json!({
            "channel_id": "48831765147549710",
            "room": "r_bbbbbbbbbbbbbbbbbbbbbbbbbb",
            "url": "wss://voice.sew.invalid",
            "token": "t",
            "expires_at": "2026-11-02T12:02:00.000Z",
            "e2ee": {
                "call_id": "r_bbbbbbbbbbbbbbbbbbbbbbbbbb",
                "join_id": "00112233445566778899aabbccddeeff",
                "key_join": "required"
            },
            "reason": "moved"
        });
        let u: sew_proto::voice::VoiceServerUpdated =
            serde_json::from_value(v.clone()).expect("voice_server_updated");
        let m = CallMoved::from_update(&u);
        assert_eq!(m.channel_id, "48831765147549710");
        assert_eq!(m.call_id, None);
        assert_eq!(m.media_room, "r_bbbbbbbbbbbbbbbbbbbbbbbbbb");
        assert_eq!(m.room(), "48831765147549710");
        // Into a DM call: the DM is the room (`call/join` takes the DM), the call is kept.
        v["channel_id"] = serde_json::json!("48831765147549712");
        v["call_id"] = serde_json::json!("48831765147549711");
        let u: sew_proto::voice::VoiceServerUpdated =
            serde_json::from_value(v).expect("voice_server_updated");
        let m = CallMoved::from_update(&u);
        assert_eq!(m.room(), "48831765147549712");
        assert_eq!(m.call_id.as_deref(), Some("48831765147549711"));
    }

    /// A reconnect whose window ran out starts a re-join and keeps that past window until the
    /// re-join answers. Meanwhile the loop's timeout does nothing for it, so the window must
    /// not wake the loop: it would wake at once on every turn (a busy loop) for as long as the
    /// re-join takes.
    #[test]
    fn a_rejoin_under_way_does_not_wake_the_loop_for_a_past_window() {
        let start = Instant::now();
        let r = Reconnect {
            initial: false,
            kind: Kind::Full,
            deadline: start,
            next_try: start,
            backoff: BACKOFF_MIN,
            attempt: 1,
        };
        // The window's end with nothing under way: due now (the timeout starts the re-join).
        assert_eq!(r.wake(false, false), Some(start));
        // A connect under way: the window still counts (its end starts a re-join).
        assert_eq!(r.wake(false, true), Some(start));
        // A re-join under way, turn after turn with nothing changing: no wake from the reconnect.
        for turn in 1..=50u64 {
            let now = start + Duration::from_millis(turn);
            let woken = r.wake(true, false).is_some_and(|w| w <= now);
            assert!(
                !woken,
                "turn {turn}: a past window woke the loop during a re-join"
            );
            assert_eq!(r.wake(true, true), None, "turn {turn}");
        }
    }

    #[test]
    fn the_end_waits_one_and_a_half_seconds_for_sew() {
        assert_eq!(END_REASON_GRACE, Duration::from_millis(1_500));
    }

    #[test]
    fn the_old_links_leave_ends_only_for_a_removal_or_a_closed_room() {
        use sew_lkproto::livekit::LeaveRequest;
        let leave = |reason: i32, action: leave_request::Action| SignalResponse {
            message: Some(signal_response::Message::Leave(LeaveRequest {
                reason,
                action: action as i32,
                ..LeaveRequest::default()
            })),
        };
        let d = leave_request::Action::Disconnect;
        assert_eq!(parting_end(&leave(4, d)), Some(EndReason::Kicked));
        assert_eq!(parting_end(&leave(5, d)), Some(EndReason::RoomClosed));
        assert_eq!(parting_end(&leave(10, d)), Some(EndReason::RoomClosed));
        // This engine's own reconnect taking the participant over.
        assert_eq!(parting_end(&leave(2, d)), None);
        assert_eq!(
            parting_end(&leave(4, leave_request::Action::Reconnect)),
            None
        );
        assert_eq!(parting_end(&leave(4, leave_request::Action::Resume)), None);
        assert_eq!(parting_end(&leave(1, d)), None);
        assert_eq!(parting_end(&SignalResponse { message: None }), None);
        // The current link's mapping keeps the duplicate as `kicked`.
        assert_eq!(engine_end_reason(2), Some(EndReason::Kicked));
    }
}