crispasr 0.8.26

Safe Rust wrapper for CrispASR — lightweight on-device speech recognition (Whisper, Qwen3-ASR, FastConformer, and more).
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
//! Safe Rust wrapper for CrispASR speech recognition.
//!
//! # Quick start
//!
//! ```no_run
//! use crispasr::Session;
//!
//! let sess = Session::open("model.gguf").unwrap();
//! let pcm = vec![0.0f32; 16000]; // 1s of silence
//! let segments = sess.transcribe(&pcm).unwrap();
//! for seg in &segments {
//!     println!("[{:.1}s - {:.1}s] {}", seg.start, seg.end, seg.text);
//! }
//! ```

use std::ffi::{CStr, CString};
use std::os::raw::{c_char, c_float, c_int};

/// A transcription segment with timing information.
#[derive(Debug, Clone)]
pub struct Segment {
    pub text: String,
    pub start: f64, // seconds
    pub end: f64,   // seconds
    pub no_speech_prob: f32,
}

/// Options for `transcribe_pcm_with_options`. Leave defaults for standard
/// Whisper behaviour; set `vad: true` + `vad_model_path` for built-in
/// Silero VAD, or `tdrz: true` with a `.en.tdrz` model for speaker-turn
/// markers.
#[derive(Debug, Clone, Default)]
pub struct TranscribeOptions {
    pub strategy: Option<i32>,
    pub vad: bool,
    pub vad_model_path: Option<String>,
    pub vad_threshold: Option<f32>,
    pub vad_min_speech_ms: Option<i32>,
    pub vad_min_silence_ms: Option<i32>,
    pub tdrz: bool,
}

/// A loaded CrispASR model (whisper-only, legacy API).
///
/// **Deprecated:** Use [`Session`] instead. `CrispASR` wraps `whisper_full()`
/// directly without exception safety — C++ exceptions from ggml/whisper will
/// abort the process. `Session` uses the C-ABI wrapper which catches exceptions.
///
/// Not `Sync` — do not share between threads.
#[deprecated(
    since = "0.1.6",
    note = "Use Session::open() instead — CrispASR can abort on C++ exceptions"
)]
pub struct CrispASR {
    ctx: *mut crispasr_sys::WhisperContext,
}

unsafe impl Send for CrispASR {}

impl CrispASR {
    /// Load a GGUF/GGML whisper model file.
    pub fn new(model_path: &str) -> Result<Self, String> {
        let path = CString::new(model_path).map_err(|e| format!("invalid path: {e}"))?;
        let cparams = unsafe { crispasr_sys::whisper_context_default_params_by_ref() };
        let ctx =
            unsafe { crispasr_sys::whisper_init_from_file_with_params(path.as_ptr(), cparams) };
        unsafe { crispasr_sys::whisper_free_context_params(cparams) };
        if ctx.is_null() {
            return Err(format!("failed to load model: {model_path}"));
        }
        Ok(Self { ctx })
    }

    /// Transcribe raw PCM audio (float32, mono, 16kHz).
    ///
    /// Returns a list of segments with text and timing.
    pub fn transcribe_pcm(&self, pcm: &[f32]) -> Result<Vec<Segment>, String> {
        self.transcribe_pcm_with_strategy(pcm, crispasr_sys::CRISPASR_SAMPLING_GREEDY)
    }

    /// Transcribe with a specific sampling strategy.
    pub fn transcribe_pcm_with_strategy(
        &self,
        pcm: &[f32],
        strategy: i32,
    ) -> Result<Vec<Segment>, String> {
        self.transcribe_pcm_with_options(
            pcm,
            &TranscribeOptions {
                strategy: Some(strategy),
                ..Default::default()
            },
        )
    }

    /// Transcribe with full option control — VAD, tinydiarize, and future
    /// knobs as they land upstream. Safe against older dylibs: setters
    /// that the loaded library doesn't expose are no-ops.
    pub fn transcribe_pcm_with_options(
        &self,
        pcm: &[f32],
        opts: &TranscribeOptions,
    ) -> Result<Vec<Segment>, String> {
        let strategy = opts
            .strategy
            .unwrap_or(crispasr_sys::CRISPASR_SAMPLING_GREEDY);
        let params = unsafe { crispasr_sys::whisper_full_default_params_by_ref(strategy) };

        // VAD
        if opts.vad {
            unsafe {
                crispasr_sys::crispasr_params_set_vad(params, 1);
                if let Some(t) = opts.vad_threshold {
                    crispasr_sys::crispasr_params_set_vad_threshold(params, t);
                }
                if let Some(ms) = opts.vad_min_speech_ms {
                    crispasr_sys::crispasr_params_set_vad_min_speech_ms(params, ms);
                }
                if let Some(ms) = opts.vad_min_silence_ms {
                    crispasr_sys::crispasr_params_set_vad_min_silence_ms(params, ms);
                }
            }
            // Keep the CString alive until after whisper_full returns.
            let vad_path_cstr = opts
                .vad_model_path
                .as_ref()
                .map(|s| CString::new(s.as_str()).ok())
                .flatten();
            if let Some(cs) = &vad_path_cstr {
                unsafe {
                    crispasr_sys::crispasr_params_set_vad_model_path(params, cs.as_ptr());
                }
            }
            // vad_path_cstr stays in scope for the whisper_full call below.
            return self.run_full(pcm, params, vad_path_cstr);
        }
        if opts.tdrz {
            unsafe { crispasr_sys::crispasr_params_set_tdrz(params, 1) };
        }

        self.run_full(pcm, params, None)
    }

    fn run_full(
        &self,
        pcm: &[f32],
        params: *mut crispasr_sys::WhisperFullParams,
        _keep_alive_vad_path: Option<CString>,
    ) -> Result<Vec<Segment>, String> {
        let ret =
            unsafe { crispasr_sys::whisper_full(self.ctx, params, pcm.as_ptr(), pcm.len() as i32) };
        unsafe { crispasr_sys::whisper_free_params(params) };

        if ret != 0 {
            return Err(format!("transcription failed (error code {ret})"));
        }

        let n = unsafe { crispasr_sys::whisper_full_n_segments(self.ctx) };
        let mut segments = Vec::with_capacity(n as usize);

        for i in 0..n {
            let text_ptr = unsafe { crispasr_sys::whisper_full_get_segment_text(self.ctx, i) };
            let text = if text_ptr.is_null() {
                String::new()
            } else {
                unsafe { CStr::from_ptr(text_ptr) }
                    .to_string_lossy()
                    .into_owned()
            };
            let t0 = unsafe { crispasr_sys::whisper_full_get_segment_t0(self.ctx, i) };
            let t1 = unsafe { crispasr_sys::whisper_full_get_segment_t1(self.ctx, i) };
            let nsp = unsafe { crispasr_sys::whisper_full_get_segment_no_speech_prob(self.ctx, i) };

            segments.push(Segment {
                text,
                start: t0 as f64 / 100.0,
                end: t1 as f64 / 100.0,
                no_speech_prob: nsp,
            });
        }

        Ok(segments)
    }

    /// Get the detected language from the last transcription.
    pub fn detected_language(&self) -> String {
        let id = unsafe { crispasr_sys::whisper_full_lang_id(self.ctx) };
        let ptr = unsafe { crispasr_sys::whisper_lang_str(id) };
        if ptr.is_null() {
            "unknown".to_string()
        } else {
            unsafe { CStr::from_ptr(ptr) }
                .to_string_lossy()
                .into_owned()
        }
    }
}

impl Drop for CrispASR {
    fn drop(&mut self) {
        unsafe { crispasr_sys::whisper_free(self.ctx) }
    }
}

// =========================================================================
// Unified session — any CrispASR-supported backend through one handle.
//
// Prefer `Session::open` over `CrispASR::new` for new code: it dispatches
// automatically to whichever backend (Whisper, Parakeet, Canary, Cohere,
// Qwen3-ASR, Granite, FastConformer-CTC, Voxtral family, Wav2Vec2) the
// GGUF metadata specifies. `CrispASR` stays around for low-overhead
// Whisper-specific access and ABI stability.
// =========================================================================

/// Word-level timing (populated by backends that produce it).
#[derive(Debug, Clone)]
pub struct SessionWord {
    pub text: String,
    pub start: f64,
    pub end: f64,
    /// Per-word probability in `[0, 1]`. Backends that don't emit a real
    /// per-word probability fall through to `1.0` so consumers can render
    /// uniformly. The C-side `crispasr_session_result_word_p` returns
    /// `-1.0` for "no data" — that case is folded to `1.0` here.
    pub confidence: f32,
}

/// A segment of a unified-session transcription.
#[derive(Debug, Clone)]
pub struct SessionSegment {
    pub text: String,
    pub start: f64,
    pub end: f64,
    pub words: Vec<SessionWord>,
    /// Whisper's per-segment probability that the segment is non-speech (the
    /// `<|nospeech|>` token posterior), in `[0, 1]`. Only the whisper backend
    /// produces it; every other backend leaves the `-1.0` sentinel ("no
    /// data"), so a consumer can tell "unavailable" apart from a genuine low
    /// no-speech probability.
    pub no_speech_prob: f32,
}

/// Per-frame CTC logits captured from a CTC backend.
///
/// `data` is frame-major: `data[t * n_vocab + v]` is the score for vocabulary
/// entry `v` at encoder frame `t`, so its length is `n_vocab * n_frames`.
/// Produced only by [`Session::transcribe_with_logits`] on a backend with a
/// dense CTC grid (Omni CTC, wav2vec2/hubert/data2vec, or canary-ctc); other
/// backends yield no grid. The Omni and wav2vec2 grids are raw logits
/// (pre-softmax); the canary-ctc grid is log-probabilities. Log-softmax before
/// use if you need normalized scores — it is idempotent on the canary grid.
#[derive(Debug, Clone)]
pub struct CtcLogits {
    pub n_vocab: usize,
    pub n_frames: usize,
    pub data: Vec<f32>,
}

/// A loaded session over a CrispASR model of any backend.
pub struct Session {
    handle: *mut crispasr_sys::CrispasrSession,
    n_threads: c_int,
}

// Not `Sync` — do not share between threads without external sync.
unsafe impl Send for Session {}

impl Session {
    /// Open a GGUF model, auto-detecting the backend from metadata.
    pub fn open(model_path: &str) -> Result<Self, String> {
        Self::open_inner(model_path, None, 4)
    }

    /// Open with an explicit backend (skips auto-detect).
    pub fn open_with_backend(
        model_path: &str,
        backend: &str,
        n_threads: i32,
    ) -> Result<Self, String> {
        Self::open_inner(model_path, Some(backend), n_threads)
    }

    fn open_inner(model_path: &str, backend: Option<&str>, n_threads: i32) -> Result<Self, String> {
        let path = CString::new(model_path).map_err(|e| format!("invalid path: {e}"))?;
        let handle = if let Some(be) = backend {
            let be_c = CString::new(be).map_err(|e| format!("invalid backend: {e}"))?;
            unsafe {
                crispasr_sys::crispasr_session_open_explicit(
                    path.as_ptr(),
                    be_c.as_ptr(),
                    n_threads,
                )
            }
        } else {
            unsafe { crispasr_sys::crispasr_session_open(path.as_ptr(), n_threads) }
        };
        if handle.is_null() {
            let avail = Self::available_backends().join(",");
            return Err(format!(
                "Failed to open {model_path:?}. Library was built with: [{avail}]"
            ));
        }
        Ok(Self { handle, n_threads })
    }

    /// List of backend names the loaded CrispASR library was compiled with.
    pub fn available_backends() -> Vec<String> {
        let mut buf = vec![0i8; 256];
        let mut n = unsafe {
            crispasr_sys::crispasr_session_available_backends(buf.as_mut_ptr(), buf.len() as i32)
        };
        if n <= 0 {
            return Vec::new();
        }
        if n as usize >= buf.len() {
            buf.resize(n as usize + 1, 0);
            n = unsafe {
                crispasr_sys::crispasr_session_available_backends(
                    buf.as_mut_ptr(),
                    buf.len() as i32,
                )
            };
            if n <= 0 {
                return Vec::new();
            }
        }
        let cstr = unsafe { CStr::from_ptr(buf.as_ptr()) };
        cstr.to_string_lossy()
            .split(',')
            .filter(|s| !s.is_empty())
            .map(|s| s.trim().to_string())
            .collect()
    }

    /// Detect the backend from a GGUF file without opening it.
    pub fn detect_backend(model_path: &str) -> Result<String, String> {
        let path = CString::new(model_path).map_err(|e| format!("invalid path: {e}"))?;
        let mut buf = [0i8; 64];
        let n = unsafe {
            crispasr_sys::crispasr_detect_backend_from_gguf(
                path.as_ptr(),
                buf.as_mut_ptr(),
                buf.len() as i32,
            )
        };
        if n <= 0 {
            return Err(format!("backend detection failed (code {n})"));
        }
        Ok(unsafe { CStr::from_ptr(buf.as_ptr()) }
            .to_string_lossy()
            .into_owned())
    }

    /// Backend name this session ended up using.
    pub fn backend(&self) -> String {
        let p = unsafe { crispasr_sys::crispasr_session_backend(self.handle) };
        if p.is_null() {
            String::new()
        } else {
            unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned()
        }
    }

    /// The Omni CTC vocabulary as raw SentencePiece pieces, indexed by token
    /// id (`vocab[id]`). Pieces keep the U+2581 (`▁`) word-boundary marker
    /// intact, so a consumer can group a greedy CTC decode over
    /// [`CtcLogits`] into words at `▁` boundaries and map `▁` → space.
    /// Returns `None` for backends that don't expose a CTC vocab.
    pub fn ctc_vocab(&self) -> Option<Vec<String>> {
        let n = unsafe { crispasr_sys::crispasr_session_n_vocab(self.handle) };
        if n <= 0 {
            return None;
        }
        let mut out = Vec::with_capacity(n as usize);
        for id in 0..n {
            let p = unsafe { crispasr_sys::crispasr_session_token_text(self.handle, id) };
            let piece = if p.is_null() {
                String::new()
            } else {
                unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned()
            };
            out.push(piece);
        }
        Some(out)
    }

    /// The acoustic language whisper detected on the last transcribe, as an
    /// ISO-639-1 code (e.g. `"en"`). Whisper-only: other backends return the
    /// session's source-language hint, or `"unknown"` when none was set — as
    /// does whisper before its first transcribe. This is the in-decode
    /// acoustic signal, distinct from a text-LID pass over the transcript.
    pub fn detected_language(&self) -> String {
        let mut buf = [0 as c_char; 32];
        let n = unsafe {
            crispasr_sys::crispasr_session_detected_language(
                self.handle,
                buf.as_mut_ptr(),
                buf.len() as c_int,
            )
        };
        if n <= 0 {
            return "unknown".to_string();
        }
        unsafe { CStr::from_ptr(buf.as_ptr()) }
            .to_string_lossy()
            .into_owned()
    }

    /// Transcribe 16 kHz mono `f32` PCM. The internal dispatcher routes
    /// to whichever backend this session was opened with.
    pub fn transcribe(&self, pcm: &[f32]) -> Result<Vec<SessionSegment>, String> {
        self.transcribe_with_language(pcm, None)
    }

    /// Language-aware transcribe (0.4.9+). `language` is an optional
    /// ISO 639-1 code ("en", "de", "ja", …). Backends that accept a
    /// source-language hint honour it; others ignore silently. `None`
    /// preserves each backend's historical default.
    pub fn transcribe_with_language(
        &self,
        pcm: &[f32],
        language: Option<&str>,
    ) -> Result<Vec<SessionSegment>, String> {
        if pcm.is_empty() {
            return Ok(Vec::new());
        }
        let lang_c = match language {
            Some(l) if !l.is_empty() => {
                Some(CString::new(l).map_err(|e| format!("language NUL: {e}"))?)
            }
            _ => None,
        };
        let res = unsafe {
            match &lang_c {
                Some(c) => crispasr_sys::crispasr_session_transcribe_lang(
                    self.handle,
                    pcm.as_ptr(),
                    pcm.len() as i32,
                    c.as_ptr(),
                ),
                None => crispasr_sys::crispasr_session_transcribe(
                    self.handle,
                    pcm.as_ptr(),
                    pcm.len() as i32,
                ),
            }
        };
        self.parse_session_result(res, "crispasr_session_transcribe")
    }

    /// Opt in to capturing the per-frame CTC logits on subsequent transcribe
    /// calls (backends with a dense CTC grid: Omni CTC, wav2vec2/hubert/data2vec,
    /// canary-ctc). Off by default: capture copies `n_vocab × n_frames` floats
    /// per call, so leave it off unless a consumer (e.g. forced alignment) needs
    /// the grid. Retrieve the logits with [`Self::transcribe_with_logits`].
    pub fn set_return_logits(&self, on: bool) -> Result<(), String> {
        let rc = unsafe {
            crispasr_sys::crispasr_session_set_return_logits(self.handle, if on { 1 } else { 0 })
        };
        if rc != 0 {
            return Err(format!("set_return_logits failed (rc={rc})"));
        }
        Ok(())
    }

    /// Transcribe and also return the CTC logits captured for this call.
    /// Enables logit capture for the duration, so the caller need not call
    /// [`Self::set_return_logits`] first. The logits are `None` for backends
    /// that don't produce a dense CTC grid (only Omni CTC, wav2vec2/hubert/
    /// data2vec, and canary-ctc do) or when the transcript is empty.
    pub fn transcribe_with_logits(
        &self,
        pcm: &[f32],
    ) -> Result<(Vec<SessionSegment>, Option<CtcLogits>), String> {
        if pcm.is_empty() {
            return Ok((Vec::new(), None));
        }
        self.set_return_logits(true)?;
        let res = unsafe {
            crispasr_sys::crispasr_session_transcribe(self.handle, pcm.as_ptr(), pcm.len() as i32)
        };
        let parsed = self.parse_session_result_logits(res, "crispasr_session_transcribe");
        let _ = self.set_return_logits(false);
        parsed
    }

    /// Chunked-encode transcribe (issue #208). Forces the Parakeet backend
    /// through its bounded long-form path (overlapping short-window
    /// transcribe-and-merge for non-JA models, streamed encoder for the
    /// JA-only model) regardless of audio length, so long files transcribe
    /// in bounded time AND recover the sections a single full-length pass
    /// drops (the decoder loses track past ~30 s; a single pass on a 5-min
    /// clip can omit half the words).
    ///
    /// `chunk_seconds <= 0` keeps the per-model defaults; otherwise it sets
    /// the non-JA window length / the JA streamed window. `overlap_seconds
    /// < 0` uses the default. For non-Parakeet backends the chunk parameters
    /// are inert and this is equivalent to [`Self::transcribe`].
    pub fn transcribe_chunked(
        &self,
        pcm: &[f32],
        chunk_seconds: i32,
        overlap_seconds: i32,
    ) -> Result<Vec<SessionSegment>, String> {
        self.transcribe_chunked_with_language(pcm, chunk_seconds, overlap_seconds, None)
    }

    /// Language-aware chunked-encode transcribe (issue #208). See
    /// [`Self::transcribe_chunked`] for the chunking semantics and
    /// [`Self::transcribe_with_language`] for the `language` semantics.
    pub fn transcribe_chunked_with_language(
        &self,
        pcm: &[f32],
        chunk_seconds: i32,
        overlap_seconds: i32,
        language: Option<&str>,
    ) -> Result<Vec<SessionSegment>, String> {
        if pcm.is_empty() {
            return Ok(Vec::new());
        }
        let lang_c = match language {
            Some(l) if !l.is_empty() => {
                Some(CString::new(l).map_err(|e| format!("language NUL: {e}"))?)
            }
            _ => None,
        };
        let res = unsafe {
            crispasr_sys::crispasr_session_transcribe_chunked_lang(
                self.handle,
                pcm.as_ptr(),
                pcm.len() as i32,
                chunk_seconds,
                overlap_seconds,
                lang_c.as_ref().map_or(std::ptr::null(), |c| c.as_ptr()),
            )
        };
        self.parse_session_result(res, "crispasr_session_transcribe_chunked")
    }

    /// Chunked-encode transcribe with a per-window progress callback
    /// (issue #208). `progress(processed_samples, total_samples)` is invoked
    /// once per finished window on the calling thread; `processed` is
    /// monotonically non-decreasing and reaches `total` on the last window.
    /// The callback only fires for the duration of this call, so it need not
    /// be `Send` or `'static`. Short (single-pass) audio and non-Parakeet
    /// backends do not fire it. See [`Self::transcribe_chunked`] for the
    /// chunking semantics.
    pub fn transcribe_chunked_with_progress<F: FnMut(i32, i32)>(
        &self,
        pcm: &[f32],
        chunk_seconds: i32,
        overlap_seconds: i32,
        language: Option<&str>,
        mut progress: F,
    ) -> Result<Vec<SessionSegment>, String> {
        if pcm.is_empty() {
            return Ok(Vec::new());
        }
        let lang_c = match language {
            Some(l) if !l.is_empty() => {
                Some(CString::new(l).map_err(|e| format!("language NUL: {e}"))?)
            }
            _ => None,
        };

        extern "C" fn trampoline<F: FnMut(i32, i32)>(
            processed: c_int,
            total: c_int,
            ud: *mut c_void,
        ) {
            if ud.is_null() {
                return;
            }
            // SAFETY: `ud` is the `&mut F` registered just below. The C side
            // only invokes this synchronously from within the transcribe call
            // (same thread), so the reference is live and unaliased here.
            let f = unsafe { &mut *(ud as *mut F) };
            f(processed, total);
        }

        // Register for the duration of this call only, then clear — a raw
        // pointer to a stack closure must never outlive this frame.
        unsafe {
            crispasr_sys::crispasr_session_set_progress_callback(
                self.handle,
                Some(trampoline::<F>),
                &mut progress as *mut F as *mut c_void,
            );
        }
        let res = unsafe {
            crispasr_sys::crispasr_session_transcribe_chunked_lang(
                self.handle,
                pcm.as_ptr(),
                pcm.len() as i32,
                chunk_seconds,
                overlap_seconds,
                lang_c.as_ref().map_or(std::ptr::null(), |c| c.as_ptr()),
            )
        };
        unsafe {
            crispasr_sys::crispasr_session_set_progress_callback(
                self.handle,
                None,
                std::ptr::null_mut(),
            );
        }
        self.parse_session_result(res, "crispasr_session_transcribe_chunked")
    }

    /// Parse a raw session-result handle into [`SessionSegment`]s and free
    /// it. `ctx` names the call site for the null-result error message.
    fn parse_session_result(
        &self,
        res: *mut crispasr_sys::CrispasrSessionResult,
        ctx: &str,
    ) -> Result<Vec<SessionSegment>, String> {
        self.parse_session_result_logits(res, ctx)
            .map(|(segs, _)| segs)
    }

    /// Like [`Self::parse_session_result`], but also lifts out any raw CTC
    /// logits the backend attached to the result (see [`CtcLogits`]) before
    /// freeing the handle. The logits are `None` unless the session opted in
    /// via [`Self::set_return_logits`] and the backend produced a grid.
    fn parse_session_result_logits(
        &self,
        res: *mut crispasr_sys::CrispasrSessionResult,
        ctx: &str,
    ) -> Result<(Vec<SessionSegment>, Option<CtcLogits>), String> {
        if res.is_null() {
            return Err(format!("{ctx} failed for backend {:?}", self.backend()));
        }

        let mut out = Vec::new();
        unsafe {
            let n = crispasr_sys::crispasr_session_result_n_segments(res);
            for i in 0..n {
                let tp = crispasr_sys::crispasr_session_result_segment_text(res, i);
                let text = if tp.is_null() {
                    String::new()
                } else {
                    CStr::from_ptr(tp).to_string_lossy().into_owned()
                };
                let t0 = crispasr_sys::crispasr_session_result_segment_t0(res, i) as f64 / 100.0;
                let t1 = crispasr_sys::crispasr_session_result_segment_t1(res, i) as f64 / 100.0;

                let wn = crispasr_sys::crispasr_session_result_n_words(res, i);
                let mut words = Vec::with_capacity(wn as usize);
                for j in 0..wn {
                    let wtp = crispasr_sys::crispasr_session_result_word_text(res, i, j);
                    let wt = if wtp.is_null() {
                        String::new()
                    } else {
                        CStr::from_ptr(wtp).to_string_lossy().into_owned()
                    };
                    let raw_p = crispasr_sys::crispasr_session_result_word_p(res, i, j);
                    words.push(SessionWord {
                        text: wt,
                        start: crispasr_sys::crispasr_session_result_word_t0(res, i, j) as f64
                            / 100.0,
                        end: crispasr_sys::crispasr_session_result_word_t1(res, i, j) as f64
                            / 100.0,
                        confidence: if raw_p < 0.0 { 1.0 } else { raw_p },
                    });
                }
                let nsp = crispasr_sys::crispasr_session_result_segment_no_speech_prob(res, i);
                out.push(SessionSegment {
                    text: text.trim().to_string(),
                    start: t0,
                    end: t1,
                    words,
                    no_speech_prob: nsp,
                });
            }
            // Lift out the raw CTC logits (if any) before the handle is freed.
            let n_frames = crispasr_sys::crispasr_session_result_n_logit_frames(res);
            let n_vocab = crispasr_sys::crispasr_session_result_n_logit_vocab(res);
            let lp = crispasr_sys::crispasr_session_result_logits(res);
            let logits = if n_frames > 0 && n_vocab > 0 && !lp.is_null() {
                let n = n_vocab as usize * n_frames as usize;
                Some(CtcLogits {
                    n_vocab: n_vocab as usize,
                    n_frames: n_frames as usize,
                    data: std::slice::from_raw_parts(lp, n).to_vec(),
                })
            } else {
                None
            };
            crispasr_sys::crispasr_session_result_free(res);
            Ok((out, logits))
        }
    }

    /// Transcribe with Silero VAD segmentation + crispasr-style stitching.
    ///
    /// Runs VAD on the PCM buffer, merges short / overlong speech slices
    /// into usable chunks, stitches them into a single buffer with 0.1s
    /// silence gaps, calls the backend once, then remaps segment + word
    /// timestamps back to original-audio positions.
    ///
    /// `vad_model_path` must point to a Silero GGUF on disk. Passing
    /// `None` for `opts` uses the library defaults (mirroring
    /// crispasr's `whisper_vad_default_params`).
    ///
    /// Compared to a fixed-chunk loop, stitching preserves cross-segment
    /// decoder context, which matters for O(T²) backends such as parakeet
    /// / cohere / canary. Falls back to a plain [`Self::transcribe`] call
    /// when no speech is detected or the VAD model fails to load.
    pub fn transcribe_vad(
        &self,
        pcm: &[f32],
        vad_model_path: &str,
        opts: Option<VadOptions>,
    ) -> Result<Vec<SessionSegment>, String> {
        self.transcribe_vad_with_language(pcm, vad_model_path, opts, None)
    }

    /// Language-aware VAD transcribe (0.4.9+). Accepts an ISO 639-1
    /// code that's forwarded into the backend's source-language hint.
    /// See [`Self::transcribe_with_language`] for the full semantics.
    pub fn transcribe_vad_with_language(
        &self,
        pcm: &[f32],
        vad_model_path: &str,
        opts: Option<VadOptions>,
        language: Option<&str>,
    ) -> Result<Vec<SessionSegment>, String> {
        if pcm.is_empty() {
            return Ok(Vec::new());
        }

        let path_c = CString::new(vad_model_path)
            .map_err(|e| format!("vad_model_path contains NUL byte: {e}"))?;
        let abi_opts = opts.unwrap_or_default().to_abi();
        let lang_c = match language {
            Some(l) if !l.is_empty() => {
                Some(CString::new(l).map_err(|e| format!("language NUL: {e}"))?)
            }
            _ => None,
        };

        let res = unsafe {
            match &lang_c {
                Some(c) => crispasr_sys::crispasr_session_transcribe_vad_lang(
                    self.handle,
                    pcm.as_ptr(),
                    pcm.len() as i32,
                    16_000,
                    path_c.as_ptr(),
                    &abi_opts,
                    c.as_ptr(),
                ),
                None => crispasr_sys::crispasr_session_transcribe_vad(
                    self.handle,
                    pcm.as_ptr(),
                    pcm.len() as i32,
                    16_000,
                    path_c.as_ptr(),
                    &abi_opts,
                ),
            }
        };
        if res.is_null() {
            return Err(format!(
                "crispasr_session_transcribe_vad failed for backend {:?}",
                self.backend()
            ));
        }

        let mut out = Vec::new();
        unsafe {
            let n = crispasr_sys::crispasr_session_result_n_segments(res);
            for i in 0..n {
                let tp = crispasr_sys::crispasr_session_result_segment_text(res, i);
                let text = if tp.is_null() {
                    String::new()
                } else {
                    CStr::from_ptr(tp).to_string_lossy().into_owned()
                };
                let t0 = crispasr_sys::crispasr_session_result_segment_t0(res, i) as f64 / 100.0;
                let t1 = crispasr_sys::crispasr_session_result_segment_t1(res, i) as f64 / 100.0;

                let wn = crispasr_sys::crispasr_session_result_n_words(res, i);
                let mut words = Vec::with_capacity(wn as usize);
                for j in 0..wn {
                    let wtp = crispasr_sys::crispasr_session_result_word_text(res, i, j);
                    let wt = if wtp.is_null() {
                        String::new()
                    } else {
                        CStr::from_ptr(wtp).to_string_lossy().into_owned()
                    };
                    let raw_p = crispasr_sys::crispasr_session_result_word_p(res, i, j);
                    words.push(SessionWord {
                        text: wt,
                        start: crispasr_sys::crispasr_session_result_word_t0(res, i, j) as f64
                            / 100.0,
                        end: crispasr_sys::crispasr_session_result_word_t1(res, i, j) as f64
                            / 100.0,
                        confidence: if raw_p < 0.0 { 1.0 } else { raw_p },
                    });
                }
                let nsp = crispasr_sys::crispasr_session_result_segment_no_speech_prob(res, i);
                out.push(SessionSegment {
                    text: text.trim().to_string(),
                    start: t0,
                    end: t1,
                    words,
                    no_speech_prob: nsp,
                });
            }
            crispasr_sys::crispasr_session_result_free(res);
        }
        Ok(out)
    }

    // ---------------------------------------------------------------------
    // TTS synthesis (vibevoice, qwen3-tts)
    // ---------------------------------------------------------------------

    /// Load a separate codec GGUF (qwen3-tts only; no-op for others).
    pub fn set_codec_path(&self, path: &str) -> Result<(), String> {
        let cpath = CString::new(path).map_err(|e| e.to_string())?;
        let rc =
            unsafe { crispasr_sys::crispasr_session_set_codec_path(self.handle, cpath.as_ptr()) };
        if rc != 0 {
            return Err(format!("set_codec_path failed (rc={})", rc));
        }
        Ok(())
    }

    /// Load a voice prompt: a baked GGUF voice pack OR a *.wav reference
    /// (qwen3-tts requires `ref_text` for *.wav inputs).
    ///
    /// For orpheus voice selection is BY NAME — use [`set_speaker_name`]
    /// instead.
    pub fn set_voice(&self, path: &str, ref_text: Option<&str>) -> Result<(), String> {
        let cpath = CString::new(path).map_err(|e| e.to_string())?;
        let crt = match ref_text {
            Some(t) => Some(CString::new(t).map_err(|e| e.to_string())?),
            None => None,
        };
        let rt_ptr = crt.as_ref().map(|c| c.as_ptr()).unwrap_or(std::ptr::null());
        let rc = unsafe {
            crispasr_sys::crispasr_session_set_voice(self.handle, cpath.as_ptr(), rt_ptr)
        };
        if rc != 0 {
            return Err(format!("set_voice failed (rc={})", rc));
        }
        Ok(())
    }

    /// Select a fixed/preset speaker by NAME for backends that bake names
    /// into the GGUF (orpheus). Names are e.g. `"tara"`/`"leo"` for
    /// canopylabs English; `"Anton"`/`"Sophie"` for Kartoffel_Orpheus DE.
    /// Use [`speakers`] to enumerate.
    pub fn set_speaker_name(&self, name: &str) -> Result<(), String> {
        let cname = CString::new(name).map_err(|e| e.to_string())?;
        let rc =
            unsafe { crispasr_sys::crispasr_session_set_speaker_name(self.handle, cname.as_ptr()) };
        match rc {
            0 => Ok(()),
            -2 => Err(format!(
                "unknown speaker {:?}; call .speakers() to enumerate",
                name
            )),
            -3 => Err("backend has no preset speakers; use set_voice() instead".to_string()),
            _ => Err(format!("set_speaker_name failed (rc={})", rc)),
        }
    }

    /// Return the list of preset speaker names for the active backend.
    /// Empty if the backend has no preset-speaker contract.
    pub fn speakers(&self) -> Vec<String> {
        let n = unsafe { crispasr_sys::crispasr_session_n_speakers(self.handle) };
        let mut out = Vec::with_capacity(n.max(0) as usize);
        for i in 0..n {
            let ptr = unsafe { crispasr_sys::crispasr_session_get_speaker_name(self.handle, i) };
            if !ptr.is_null() {
                let s = unsafe { std::ffi::CStr::from_ptr(ptr) }
                    .to_string_lossy()
                    .into_owned();
                out.push(s);
            }
        }
        out
    }

    /// Synthesise `text` to 24 kHz mono PCM. Requires a TTS-capable backend
    /// (`vibevoice`, `qwen3-tts`, `kokoro`, `orpheus`).
    pub fn synthesize(&self, text: &str) -> Result<Vec<f32>, String> {
        let ctext = CString::new(text).map_err(|e| e.to_string())?;
        let mut n: c_int = 0;
        let ptr = unsafe {
            crispasr_sys::crispasr_session_synthesize(
                self.handle,
                ctext.as_ptr(),
                &mut n as *mut c_int,
            )
        };
        if ptr.is_null() || n <= 0 {
            return Err(format!(
                "synthesize returned no audio for backend {:?}",
                self.backend()
            ));
        }
        let out = unsafe { std::slice::from_raw_parts(ptr, n as usize).to_vec() };
        unsafe { crispasr_sys::crispasr_pcm_free(ptr) };
        Ok(out)
    }

    /// Speech-to-speech: input PCM in → output PCM out via a single model
    /// pass. Requires an S2S-capable backend (`lfm2-audio`, `mini-omni2`,
    /// `sidon`, `voxcpm2-vae`). Input PCM must be at the backend's native
    /// input rate (see [`Session::input_sample_rate`]).
    ///
    /// Returns the output PCM plus the optional intermediate transcript the
    /// model produced on the way (`None` if the backend doesn't surface one).
    /// Errors if the backend has no S2S capability or the pass fails.
    pub fn speech_to_speech(&self, pcm: &[f32]) -> Result<(Vec<f32>, Option<String>), String> {
        let mut n: c_int = 0;
        let mut text_ptr: *mut c_char = std::ptr::null_mut();
        let ptr = unsafe {
            crispasr_sys::crispasr_session_speech_to_speech(
                self.handle,
                pcm.as_ptr(),
                pcm.len() as c_int,
                &mut text_ptr as *mut *mut c_char,
                &mut n as *mut c_int,
            )
        };
        if ptr.is_null() || n <= 0 {
            if !text_ptr.is_null() {
                unsafe { crispasr_sys::crispasr_session_translate_text_free(text_ptr) };
            }
            return Err(format!(
                "speech_to_speech returned no audio for backend {:?} (S2S may be unsupported)",
                self.backend()
            ));
        }
        let out = unsafe { std::slice::from_raw_parts(ptr, n as usize).to_vec() };
        unsafe { crispasr_sys::crispasr_pcm_free(ptr) };
        let transcript = if text_ptr.is_null() {
            None
        } else {
            let s = unsafe { CStr::from_ptr(text_ptr) }
                .to_string_lossy()
                .into_owned();
            unsafe { crispasr_sys::crispasr_session_translate_text_free(text_ptr) };
            Some(s)
        };
        Ok((out, transcript))
    }

    /// The sample rate (Hz) the backend expects for input PCM — `16000` for
    /// Whisper-family backends, the model's native rate otherwise, `0` on
    /// error. Feed [`Session::speech_to_speech`] (and TTS voice-clone input)
    /// at this rate rather than resampling twice.
    pub fn input_sample_rate(&self) -> i32 {
        unsafe { crispasr_sys::crispasr_session_input_sample_rate(self.handle) as i32 }
    }

    /// The sample rate (Hz) of the PCM that [`Session::synthesize`] /
    /// [`Session::speech_to_speech`] produce for this backend — the
    /// "backend-native rate" their docs refer to. `0` when the backend
    /// produces no audio output (ASR-only). (#332)
    pub fn output_sample_rate(&self) -> i32 {
        unsafe { crispasr_sys::crispasr_session_output_sample_rate(self.handle) as i32 }
    }

    /// Channel count for audio input (transcribe / s2s / voice references):
    /// `1` (mono) for every current backend. Source separation is the stereo
    /// exception and has its own surface. `0` on error. (#332)
    pub fn input_channels(&self) -> i32 {
        unsafe { crispasr_sys::crispasr_session_input_channels(self.handle) as i32 }
    }

    /// Channel count for synthesized / s2s output audio: `1` (mono) for every
    /// current backend, `0` when the backend produces no audio output. (#332)
    pub fn output_channels(&self) -> i32 {
        unsafe { crispasr_sys::crispasr_session_output_channels(self.handle) as i32 }
    }

    /// Attest that the integrator accepts AI-content marking/disclosure
    /// responsibility (EU AI Act Art. 50). **Required** before
    /// [`Session::synthesize_raw`] will return unmarked audio; the default
    /// [`Session::synthesize`] is watermarked and needs no attestation.
    /// `attestation` is a free-text acknowledgement recorded for audit.
    pub fn accept_marking_responsibility(&self, attestation: &str) -> Result<(), String> {
        let c = CString::new(attestation).map_err(|e| e.to_string())?;
        // The C side records the attestation; the return is informational
        // (mirrors the Python/Dart bindings, which ignore it).
        unsafe {
            crispasr_sys::crispasr_session_accept_marking_responsibility(self.handle, c.as_ptr())
        };
        Ok(())
    }

    /// Declare whose voice a PRESET voice is: `"real_person"`,
    /// `"synthetic"` or `"unknown"`.
    ///
    /// Cloning is not the only way to produce a deep fake: a preset voice
    /// shipped inside a model can be an identifiable individual — a named
    /// donor, or a corpus speaker such as VCTK's `p225` — and EU AI Act
    /// Art. 3(60) attaches to the audio resembling that person, not to which
    /// pipeline produced it. Setting `real_person` makes the Art. 50(4)
    /// reminder fire for a non-cloned voice.
    ///
    /// It does **not** require a consent attestation: whether that donor
    /// agreed to the model being trained is a licensing matter settled
    /// upstream, which you cannot attest to.
    ///
    /// Returns `Err` on an unrecognised value rather than silently
    /// downgrading it to `unknown`.
    pub fn set_speaker_identity(&self, identity: &str) -> Result<(), String> {
        let c = CString::new(identity).map_err(|e| e.to_string())?;
        let rc =
            unsafe { crispasr_sys::crispasr_session_set_speaker_identity(self.handle, c.as_ptr()) };
        match rc {
            0 => Ok(()),
            -2 => Err(format!(
                "unrecognised speaker_identity {identity:?} (expected real_person, synthetic or unknown)"
            )),
            _ => Err(format!("set_speaker_identity failed (rc={rc})")),
        }
    }

    /// Embed the AI-content watermark into f32 mono PCM, in place.
    ///
    /// The other half of [`Session::synthesize_raw`]: opting out of automatic
    /// marking makes marking the result *your* duty (EU AI Act Art. 50(2)), and
    /// this is what discharges it. Do the post-processing you opted out for —
    /// resample, mix, concatenate — then call this on the finished buffer.
    ///
    /// Uses the robust, reliably detectable default strength; AudioSeal instead
    /// if a model was loaded. Associated function, not a method: marking is a
    /// property of the samples, not of the session that produced them.
    pub fn watermark_embed(pcm: &mut [f32]) {
        if pcm.is_empty() {
            return;
        }
        unsafe {
            crispasr_sys::crispasr_watermark_embed(pcm.as_mut_ptr(), pcm.len() as c_int, -1.0)
        };
    }

    /// Confidence in `[0, 1]` that `pcm` carries the watermark.
    ///
    /// A weak diagnostic, not proof: the spread-spectrum detector's null mean is
    /// 0.5, not 0, and a negative result on a short clip is mostly evidence that
    /// the clip was short. See `docs/eu-ai-act.md` §6.7 before reading anything
    /// into a number from here.
    pub fn watermark_detect(pcm: &[f32]) -> f32 {
        if pcm.is_empty() {
            return 0.0;
        }
        unsafe { crispasr_sys::crispasr_watermark_detect(pcm.as_ptr(), pcm.len() as c_int) }
    }

    /// UNMARKED synthesis (no watermark / disclosure), for callers that embed
    /// the mark themselves after post-processing. Hard-refused (returns `Err`)
    /// unless [`Session::accept_marking_responsibility`] was called first.
    /// Prefer [`Session::synthesize`] for the default watermarked output.
    /// Mark the result with [`Session::watermark_embed`].
    pub fn synthesize_raw(&self, text: &str) -> Result<Vec<f32>, String> {
        let ctext = CString::new(text).map_err(|e| e.to_string())?;
        let mut n: c_int = 0;
        let ptr = unsafe {
            crispasr_sys::crispasr_session_synthesize_raw(
                self.handle,
                ctext.as_ptr(),
                &mut n as *mut c_int,
            )
        };
        if ptr.is_null() || n <= 0 {
            return Err(format!(
                "synthesize_raw returned no audio for backend {:?} (call accept_marking_responsibility first?)",
                self.backend()
            ));
        }
        let out = unsafe { std::slice::from_raw_parts(ptr, n as usize).to_vec() };
        unsafe { crispasr_sys::crispasr_pcm_free(ptr) };
        Ok(out)
    }

    /// Drop the kokoro per-session phoneme cache. No-op for non-kokoro
    /// backends. Useful for long-running daemons that resynthesize across
    /// many speakers and want bounded memory. (PLAN #56 #5)
    pub fn clear_phoneme_cache(&self) -> Result<(), String> {
        let rc = unsafe { crispasr_sys::crispasr_session_kokoro_clear_phoneme_cache(self.handle) };
        if rc != 0 {
            return Err(format!("clear_phoneme_cache failed (rc={})", rc));
        }
        Ok(())
    }

    // -----------------------------------------------------------------
    // Sticky session-state setters (PLAN #59 partial unblock).
    // -----------------------------------------------------------------

    /// Sticky source-language hint (canary, cohere, voxtral, whisper).
    /// Empty string clears. Per-call language arg passed to transcribe
    /// methods still wins.
    pub fn set_source_language(&self, lang: &str) -> Result<(), String> {
        let c = CString::new(lang).map_err(|e| e.to_string())?;
        let rc =
            unsafe { crispasr_sys::crispasr_session_set_source_language(self.handle, c.as_ptr()) };
        if rc != 0 {
            return Err(format!("set_source_language failed (rc={})", rc));
        }
        Ok(())
    }

    /// Sticky target-language. When set ≠ source on canary/cohere, the
    /// backend emits a translation. For whisper, pair with
    /// [`set_translate(true)`](Session::set_translate).
    pub fn set_target_language(&self, lang: &str) -> Result<(), String> {
        let c = CString::new(lang).map_err(|e| e.to_string())?;
        let rc =
            unsafe { crispasr_sys::crispasr_session_set_target_language(self.handle, c.as_ptr()) };
        if rc != 0 {
            return Err(format!("set_target_language failed (rc={})", rc));
        }
        Ok(())
    }

    /// Language a voice-cloning reference clip is spoken in (issue #329).
    ///
    /// Cross-lingual TTS backends (cosyvoice3) compare it to the requested
    /// output language — [`set_target_language`](Session::set_target_language),
    /// falling back to [`set_source_language`](Session::set_source_language) —
    /// and drop the reference transcript when they differ, so the clone speaks
    /// the target language instead of carrying the reference's accent.
    ///
    /// Optional: the backend otherwise infers the reference language from the
    /// voice-bank entry or the reference transcript. That inference cannot
    /// answer for a short transcript, and when it cannot, the requested target
    /// language has no effect — set this to make it explicit.
    pub fn set_tts_reference_language(&self, lang: &str) -> Result<(), String> {
        let c = CString::new(lang).map_err(|e| e.to_string())?;
        let rc = unsafe {
            crispasr_sys::crispasr_session_set_tts_reference_language(self.handle, c.as_ptr())
        };
        if rc != 0 {
            return Err(format!("set_tts_reference_language failed (rc={})", rc));
        }
        Ok(())
    }

    /// Toggle punctuation + capitalisation in the output (canary/cohere
    /// natively; LLM backends via post-process strip). Default true.
    pub fn set_punctuation(&self, enable: bool) -> Result<(), String> {
        let rc = unsafe {
            crispasr_sys::crispasr_session_set_punctuation(self.handle, if enable { 1 } else { 0 })
        };
        if rc != 0 {
            return Err(format!("set_punctuation failed (rc={})", rc));
        }
        Ok(())
    }

    /// Whisper sticky `--translate`. For canary/cohere/voxtral the
    /// equivalent is `set_target_language` ≠ source.
    pub fn set_translate(&self, enable: bool) -> Result<(), String> {
        let rc = unsafe {
            crispasr_sys::crispasr_session_set_translate(self.handle, if enable { 1 } else { 0 })
        };
        if rc != 0 {
            return Err(format!("set_translate failed (rc={})", rc));
        }
        Ok(())
    }

    /// Translate `text` from `src_lang` to `tgt_lang` via whichever
    /// MT-capable backend this session loaded (m2m100, m2m100-wmt21,
    /// madlad, gemma4-e2b).  Distinct from [`Self::set_translate`] —
    /// that one is the whisper *audio-side* EN-only translate flag,
    /// applied to PCM input; this one is text→text with arbitrary
    /// language pairs.
    ///
    /// `max_tokens` caps the decoder output length.  Pass `<= 0` to
    /// fall back to the C++ default (200 tokens for m2m100, etc.).
    ///
    /// Backend selection guidance (from the README feature matrix):
    /// - **m2m100** — 100 languages, any-to-any (default for the long
    ///   tail like Bosnian, Swahili, …).
    /// - **m2m100-wmt21** — English-paired only (EN ↔ {zh, de, fr,
    ///   ja, ru, is, ha}), direction-specific checkpoints.  Higher
    ///   quality on those pairs.
    /// - **madlad** — 419 languages via target-language prefix tag
    ///   (handled internally; caller still passes `tgt_lang`).
    /// - **gemma4-e2b** — Dual ASR+MT (140+ langs).
    ///
    /// Errors when:
    /// - `text`, `src_lang`, or `tgt_lang` contain interior NULs;
    /// - the session has no MT-capable backend loaded (returns
    ///   `nullptr` from the C-ABI, surfaced as a clear error);
    /// - the backend's internal translate routine errored out.
    pub fn translate_text(
        &self,
        text: &str,
        src_lang: &str,
        tgt_lang: &str,
        max_tokens: i32,
    ) -> Result<String, String> {
        let ctext = CString::new(text).map_err(|e| format!("text contains NUL: {e}"))?;
        let csrc = CString::new(src_lang).map_err(|e| format!("src_lang contains NUL: {e}"))?;
        let ctgt = CString::new(tgt_lang).map_err(|e| format!("tgt_lang contains NUL: {e}"))?;
        let ptr = unsafe {
            crispasr_sys::crispasr_session_translate_text(
                self.handle,
                ctext.as_ptr(),
                csrc.as_ptr(),
                ctgt.as_ptr(),
                max_tokens,
            )
        };
        if ptr.is_null() {
            return Err(format!(
                "translate_text returned no output (backend {:?} may not be MT-capable, \
                 or the pair {}{} is unsupported)",
                self.backend(),
                src_lang,
                tgt_lang
            ));
        }
        // Same CStr → owned String pattern as `PuncModel::process` — the
        // C side malloc'd this buffer and we own it until we hand it
        // back through `crispasr_session_translate_text_free`.
        let out = unsafe { CStr::from_ptr(ptr) }
            .to_string_lossy()
            .into_owned();
        unsafe { crispasr_sys::crispasr_session_translate_text_free(ptr) };
        Ok(out)
    }

    /// Open a rolling-window streaming decoder for this session
    /// (PLAN #62). Currently whisper-only at the C-ABI level; other
    /// backends return an error. `step_ms` is how often to commit a
    /// partial transcript (default 3000); `length_ms` is the rolling
    /// window size (default 10000); `keep_ms` is the trailing audio
    /// carried over (default 200). `language` empty = auto-detect;
    /// `translate` enables EN-target speech translation (whisper).
    pub fn stream_open(
        &self,
        step_ms: i32,
        length_ms: i32,
        keep_ms: i32,
        language: &str,
        translate: bool,
    ) -> Result<Stream, String> {
        self.stream_open_ex(step_ms, length_ms, keep_ms, language, translate, false)
    }

    /// Like [`stream_open`](Session::stream_open) but with the voxtral4b
    /// live-captions toggle. When `live` is true, decode runs during
    /// `feed()` so `get_text()` returns progressive transcript as audio
    /// arrives (PLAN #7 phase 3). No-op for backends without audio-injection
    /// prompt decode.
    pub fn stream_open_ex(
        &self,
        step_ms: i32,
        length_ms: i32,
        keep_ms: i32,
        language: &str,
        translate: bool,
        live: bool,
    ) -> Result<Stream, String> {
        let lang_c = CString::new(language).map_err(|e| e.to_string())?;
        let h = unsafe {
            crispasr_sys::crispasr_session_stream_open(
                self.handle,
                self.n_threads,
                step_ms,
                length_ms,
                keep_ms,
                lang_c.as_ptr(),
                if translate { 1 } else { 0 },
            )
        };
        if h.is_null() {
            return Err(format!(
                "stream_open failed for backend {:?}",
                self.backend()
            ));
        }
        if live {
            unsafe { crispasr_sys::crispasr_stream_set_live_decode(h, 1) };
        }
        Ok(Stream { handle: h })
    }

    /// Set decoder temperature on backends that support runtime control
    /// (canary, cohere, parakeet, moonshine). Other backends silently
    /// no-op. `seed` is the RNG seed; pass 0 for time-based.
    pub fn set_temperature(&self, temperature: f32, seed: u64) -> Result<(), String> {
        let rc = unsafe {
            crispasr_sys::crispasr_session_set_temperature(self.handle, temperature, seed)
        };
        // rc == -2 means no backend supports it — soft no-op.
        if rc != 0 && rc != -2 {
            return Err(format!("set_temperature failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set the RNG seed for sampling-capable TTS backends that expose a
    /// session-level seed override (chatterbox, vibevoice, qwen3-tts,
    /// orpheus). Other backends silently no-op.
    pub fn set_tts_seed(&self, seed: u64) -> Result<(), String> {
        let rc = unsafe { crispasr_sys::crispasr_session_set_tts_seed(self.handle, seed) };
        if rc != 0 && rc != -2 {
            return Err(format!("set_tts_seed failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set a generated-token cap for autoregressive session backends.
    /// Pass `<= 0` to clear the override and use the backend default.
    pub fn set_max_new_tokens(&self, max_new_tokens: i32) -> Result<(), String> {
        let rc = unsafe {
            crispasr_sys::crispasr_session_set_max_new_tokens(self.handle, max_new_tokens)
        };
        if rc != 0 {
            return Err(format!("set_max_new_tokens failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set an opt-in repeated generated-token penalty for autoregressive
    /// session backends. Pass `<= 0.0` to disable it.
    pub fn set_frequency_penalty(&self, penalty: f32) -> Result<(), String> {
        let rc =
            unsafe { crispasr_sys::crispasr_session_set_frequency_penalty(self.handle, penalty) };
        if rc != 0 {
            return Err(format!("set_frequency_penalty failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set the diffusion / CFM step count for diffusion-based TTS backends
    /// (chatterbox today). Other backends silently no-op.
    pub fn set_tts_steps(&self, steps: i32) -> Result<(), String> {
        let rc = unsafe { crispasr_sys::crispasr_session_set_tts_steps(self.handle, steps) };
        if rc != 0 && rc != -2 {
            return Err(format!("set_tts_steps failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set the number of flow-matching timing candidates ranked per token
    /// (TADA). Higher = more reliable multilingual timing at higher cost.
    /// Other backends silently no-op.
    pub fn set_tts_num_candidates(&self, n: i32) -> Result<(), String> {
        let rc = unsafe { crispasr_sys::crispasr_session_set_tts_num_candidates(self.handle, n) };
        if rc != 0 && rc != -2 {
            return Err(format!("set_tts_num_candidates failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set the top-p nucleus-sampling threshold. Honoured by chatterbox.
    pub fn set_top_p(&self, top_p: f32) -> Result<(), String> {
        let rc = unsafe { crispasr_sys::crispasr_session_set_top_p(self.handle, top_p) };
        if rc != 0 && rc != -2 {
            return Err(format!("set_top_p failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set the top-k sampling cutoff (0 = disabled). Honoured by TADA.
    pub fn set_top_k(&self, top_k: i32) -> Result<(), String> {
        let rc = unsafe { crispasr_sys::crispasr_session_set_top_k(self.handle, top_k) };
        if rc != 0 && rc != -2 {
            return Err(format!("set_top_k failed (rc={})", rc));
        }
        Ok(())
    }

    /// Enable/disable sampling (`false` = greedy). Honoured by TADA.
    pub fn set_do_sample(&self, enable: bool) -> Result<(), String> {
        let rc =
            unsafe { crispasr_sys::crispasr_session_set_do_sample(self.handle, enable as i32) };
        if rc != 0 && rc != -2 {
            return Err(format!("set_do_sample failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set the min-p sampling threshold. Honoured by chatterbox.
    pub fn set_min_p(&self, min_p: f32) -> Result<(), String> {
        let rc = unsafe { crispasr_sys::crispasr_session_set_min_p(self.handle, min_p) };
        if rc != 0 && rc != -2 {
            return Err(format!("set_min_p failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set the repetition penalty (1.0 = no penalty). Honoured by chatterbox.
    pub fn set_repetition_penalty(&self, r: f32) -> Result<(), String> {
        let rc = unsafe { crispasr_sys::crispasr_session_set_repetition_penalty(self.handle, r) };
        if rc != 0 && rc != -2 {
            return Err(format!("set_repetition_penalty failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set the classifier-free-guidance weight (chatterbox). 0 disables CFG;
    /// 0.5 is the upstream default.
    pub fn set_cfg_weight(&self, cfg_weight: f32) -> Result<(), String> {
        let rc = unsafe { crispasr_sys::crispasr_session_set_cfg_weight(self.handle, cfg_weight) };
        if rc != 0 && rc != -2 {
            return Err(format!("set_cfg_weight failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set the TADA flow-matching noise temperature (Python noise_temp,
    /// default 0.9).
    pub fn set_tts_noise_temp(&self, noise_temp: f32) -> Result<(), String> {
        let rc =
            unsafe { crispasr_sys::crispasr_session_set_tts_noise_temp(self.handle, noise_temp) };
        if rc != 0 && rc != -2 {
            return Err(format!("set_tts_noise_temp failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set the emotion-exaggeration scalar (chatterbox). 0.5 is the upstream default.
    pub fn set_exaggeration(&self, exaggeration: f32) -> Result<(), String> {
        let rc =
            unsafe { crispasr_sys::crispasr_session_set_exaggeration(self.handle, exaggeration) };
        if rc != 0 && rc != -2 {
            return Err(format!("set_exaggeration failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set the upper bound on speech tokens per synthesize call (chatterbox).
    /// Default ≈1000 tokens ≈ 20 s.
    pub fn set_max_speech_tokens(&self, n: i32) -> Result<(), String> {
        let rc = unsafe { crispasr_sys::crispasr_session_set_max_speech_tokens(self.handle, n) };
        if rc != 0 && rc != -2 {
            return Err(format!("set_max_speech_tokens failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set the per-phoneme length-scale / speaking-rate scalar. Honoured by
    /// kokoro today; other backends silently no-op. 1.0 = upstream default.
    pub fn set_length_scale(&self, scale: f32) -> Result<(), String> {
        let rc = unsafe { crispasr_sys::crispasr_session_set_length_scale(self.handle, scale) };
        if rc != 0 && rc != -2 {
            return Err(format!("set_length_scale failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set the best-of-N sampling count for ASR backends.
    pub fn set_best_of(&self, n: i32) -> Result<(), String> {
        let rc = unsafe { crispasr_sys::crispasr_session_set_best_of(self.handle, n) };
        if rc != 0 {
            return Err(format!("set_best_of failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set the beam-search width for ASR backends that support it.
    pub fn set_beam_size(&self, n: i32) -> Result<(), String> {
        let rc = unsafe { crispasr_sys::crispasr_session_set_beam_size(self.handle, n) };
        if rc != 0 {
            return Err(format!("set_beam_size failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set a GBNF grammar for constrained whisper decoding. Pass an empty
    /// string for `gbnf_text` to clear the grammar. `penalty` defaults to 100.0.
    pub fn set_grammar_text(
        &self,
        gbnf_text: &str,
        root_rule: &str,
        penalty: f32,
    ) -> Result<(), String> {
        let cgbnf = CString::new(gbnf_text).map_err(|e| e.to_string())?;
        let croot = CString::new(root_rule).map_err(|e| e.to_string())?;
        let rc = unsafe {
            crispasr_sys::crispasr_session_set_grammar_text(
                self.handle,
                cgbnf.as_ptr(),
                croot.as_ptr(),
                penalty,
            )
        };
        if rc == -2 {
            return Err("set_grammar_text: invalid GBNF or root rule not found".into());
        }
        if rc != 0 {
            return Err(format!("set_grammar_text failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set whisper decoder fallback thresholds. `temperature_inc = 0.0`
    /// disables fallback entirely (equivalent to `--no-fallback`).
    pub fn set_fallback_thresholds(
        &self,
        entropy_thold: f32,
        logprob_thold: f32,
        no_speech_thold: f32,
        temperature_inc: f32,
    ) -> Result<(), String> {
        let rc = unsafe {
            crispasr_sys::crispasr_session_set_fallback_thresholds(
                self.handle,
                entropy_thold,
                logprob_thold,
                no_speech_thold,
                temperature_inc,
            )
        };
        if rc != 0 {
            return Err(format!("set_fallback_thresholds failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set per-token top-N alternative-candidate capture for whisper greedy
    /// decode. 0 disables it.
    pub fn set_alt_n(&self, n: i32) -> Result<(), String> {
        let rc = unsafe { crispasr_sys::crispasr_session_set_alt_n(self.handle, n) };
        if rc != 0 {
            return Err(format!("set_alt_n failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set whisper-only text-suppression and prompt-carry extras.
    /// `suppress_regex` may be empty to clear any prior regex.
    pub fn set_whisper_decode_extras(
        &self,
        suppress_nst: bool,
        suppress_regex: &str,
        carry_initial_prompt: bool,
    ) -> Result<(), String> {
        let cregex = CString::new(suppress_regex).map_err(|e| e.to_string())?;
        let rc = unsafe {
            crispasr_sys::crispasr_session_set_whisper_decode_extras(
                self.handle,
                suppress_nst as c_int,
                cregex.as_ptr(),
                carry_initial_prompt as c_int,
            )
        };
        if rc != 0 {
            return Err(format!("set_whisper_decode_extras failed (rc={})", rc));
        }
        Ok(())
    }

    /// Set a free-form prompt / question passed to the backend on the next
    /// transcribe or synthesize call (used by LLM-style backends).
    pub fn set_ask(&self, prompt: &str) -> Result<(), String> {
        let cprompt = CString::new(prompt).map_err(|e| e.to_string())?;
        let rc = unsafe { crispasr_sys::crispasr_session_set_ask(self.handle, cprompt.as_ptr()) };
        if rc != 0 {
            return Err(format!("set_ask failed (rc={})", rc));
        }
        Ok(())
    }

    /// qwen3-tts VoiceDesign: natural-language voice description.
    pub fn set_instruct(&self, instruct: &str) -> Result<(), String> {
        let c = CString::new(instruct).map_err(|e| e.to_string())?;
        let rc = unsafe { crispasr_sys::crispasr_session_set_instruct(self.handle, c.as_ptr()) };
        if rc != 0 {
            return Err(format!("set_instruct failed (rc={})", rc));
        }
        Ok(())
    }

    /// Synthesize `phonemes` verbatim instead of phonemizing the text — the
    /// seam between text processing and the acoustic model. Use it to reproduce
    /// another implementation's pronunciation exactly, or to tell a G2P bug from
    /// a model bug (#316). An empty string clears it.
    ///
    /// Honoured by `kokoro` and `piper`; other backends soft no-op (`rc = -2`).
    pub fn set_tts_phonemes(&self, phonemes: &str) -> Result<(), String> {
        let c = CString::new(phonemes).map_err(|e| e.to_string())?;
        let rc =
            unsafe { crispasr_sys::crispasr_session_set_tts_phonemes(self.handle, c.as_ptr()) };
        if rc == -2 {
            return Err("backend has no phonemes-in entry point (kokoro and piper do)".to_string());
        }
        if rc != 0 {
            return Err(format!("set_tts_phonemes failed (rc={})", rc));
        }
        Ok(())
    }

    /// Select + load a punctuation-restoration model (`auto`/`firered`/`fullstop`/
    /// `punctuate-all`/`pcs`/path; `"none"`/`""` unloads). Auto-downloads on first use.
    pub fn set_punc_model(&self, punc_model: &str) -> Result<(), String> {
        let c = CString::new(punc_model).map_err(|e| e.to_string())?;
        let rc = unsafe { crispasr_sys::crispasr_session_set_punc_model(self.handle, c.as_ptr()) };
        if rc != 0 {
            return Err(format!("set_punc_model failed (rc={})", rc));
        }
        Ok(())
    }

    /// Comma-separated hotwords for contextual biasing, boosted by `boost` per
    /// token match. Empty string clears.
    pub fn set_hotwords(&self, hotwords: &str, boost: f32) -> Result<(), String> {
        let c = CString::new(hotwords).map_err(|e| e.to_string())?;
        let rc =
            unsafe { crispasr_sys::crispasr_session_set_hotwords(self.handle, c.as_ptr(), boost) };
        if rc != 0 {
            return Err(format!("set_hotwords failed (rc={})", rc));
        }
        Ok(())
    }

    /// Apply a named bundle of the four decoder fallback thresholds:
    /// `"conservative"`, `"balanced"` (the shipped defaults, a no-op) or
    /// `"aggressive"`. `"strict"`/`"default"`/`"loose"` are aliases. Mirrors the
    /// CLI's `--sensitivity`.
    ///
    /// The four thresholds interact — a decode is only retried when the logprob
    /// *and* no-speech bars are both crossed — so they move as a set. A later
    /// [`Session::set_fallback_thresholds`] overrides this. An unrecognised
    /// preset is rejected rather than silently treated as `"balanced"`.
    pub fn set_sensitivity(&self, preset: &str) -> Result<(), String> {
        let c = CString::new(preset).map_err(|e| e.to_string())?;
        let rc = unsafe { crispasr_sys::crispasr_session_set_sensitivity(self.handle, c.as_ptr()) };
        if rc == -2 {
            return Err(format!(
                "unknown sensitivity preset {:?} (expected: conservative, balanced, aggressive)",
                preset
            ));
        }
        if rc != 0 {
            return Err(format!("set_sensitivity failed (rc={})", rc));
        }
        Ok(())
    }

    /// Select the G2P pronunciation dictionary for TTS (`olaph`/`open-dict`/path).
    pub fn set_g2p_dict(&self, source: &str) -> Result<(), String> {
        let c = CString::new(source).map_err(|e| e.to_string())?;
        let rc = unsafe { crispasr_sys::crispasr_session_set_g2p_dict(self.handle, c.as_ptr()) };
        if rc != 0 {
            return Err(format!("set_g2p_dict failed (rc={})", rc));
        }
        Ok(())
    }

    /// Select a multi-speaker backend's speaker by index.
    pub fn set_speaker_id(&self, id: i32) -> Result<(), String> {
        let rc = unsafe { crispasr_sys::crispasr_session_set_speaker_id(self.handle, id) };
        if rc != 0 {
            return Err(format!("set_speaker_id failed (rc={})", rc));
        }
        Ok(())
    }

    /// Auto-detect spoken language on raw 16 kHz mono PCM.
    ///
    /// `method`: 0=Whisper, 1=Silero (default), 2=Firered, 3=Ecapa.
    /// Returns `(iso2_code, confidence_in_0_to_1)`.
    pub fn detect_language(
        &self,
        pcm: &[f32],
        lid_model_path: &str,
        method: i32,
    ) -> Result<(String, f32), String> {
        let cpath = CString::new(lid_model_path).map_err(|e| e.to_string())?;
        let mut buf = [0u8; 16];
        let mut prob: c_float = 0.0;
        let rc = unsafe {
            crispasr_sys::crispasr_session_detect_language(
                self.handle,
                pcm.as_ptr(),
                pcm.len() as c_int,
                cpath.as_ptr(),
                method as c_int,
                buf.as_mut_ptr() as *mut c_char,
                buf.len() as c_int,
                &mut prob as *mut c_float,
            )
        };
        if rc != 0 {
            return Err(format!("detect_language failed (rc={})", rc));
        }
        let cstr = unsafe { CStr::from_ptr(buf.as_ptr() as *const c_char) };
        Ok((cstr.to_string_lossy().into_owned(), prob))
    }
}

// ---------------------------------------------------------------------------
// Kokoro per-language routing (PLAN #56 opt 2b).
// ---------------------------------------------------------------------------

/// Result of [`kokoro_resolve_for_lang`]. Mirrors the Python wrapper's
/// `KokoroResolved` dataclass.
#[derive(Clone, Debug)]
pub struct KokoroResolved {
    /// Path to load — may differ from the input when a German backbone
    /// sibling (`kokoro-de-hui-base-*.gguf`) sits next to the official
    /// Kokoro-82M baseline.
    pub model_path: String,
    /// Per-language fallback voice path. `None` if `lang` already has a
    /// native Kokoro-82M voice or no candidate exists in the model dir.
    pub voice_path: Option<String>,
    /// Basename of the picked voice (e.g. "df_victoria"). Same nullity
    /// as `voice_path`.
    pub voice_name: Option<String>,
    /// True iff the model path was rewritten to the German backbone.
    pub backbone_swapped: bool,
}

/// Resolve the kokoro model + fallback voice for `lang`. Mirrors what
/// the CLI does for `--backend kokoro -l <lang>` (PLAN #56 opt 2b).
///
/// Wrappers should call this *before* opening the [`Session`] so the
/// routing kicks in even outside the CLI entry point. Identical to the
/// Python wrapper's `crispasr.kokoro_resolve_for_lang`.
pub fn kokoro_resolve_for_lang(model_path: &str, lang: &str) -> Result<KokoroResolved, String> {
    let cmodel = CString::new(model_path).map_err(|e| e.to_string())?;
    let clang = CString::new(lang).map_err(|e| e.to_string())?;
    let mut out_model = vec![0i8; 1024];
    let mut out_voice = vec![0i8; 1024];
    let mut out_picked = vec![0i8; 64];

    let mut backbone_swapped = false;
    unsafe {
        let rc = crispasr_sys::crispasr_kokoro_resolve_model_for_lang_abi(
            cmodel.as_ptr(),
            clang.as_ptr(),
            out_model.as_mut_ptr() as *mut c_char,
            out_model.len() as c_int,
        );
        if rc < 0 {
            return Err("kokoro_resolve_model_for_lang: buffer too small".into());
        }
        if rc == 0 {
            backbone_swapped = true;
        }
    }
    let model_resolved = unsafe { std::ffi::CStr::from_ptr(out_model.as_ptr() as *const c_char) }
        .to_string_lossy()
        .into_owned();
    let model_resolved = if model_resolved.is_empty() {
        model_path.to_string()
    } else {
        model_resolved
    };

    let (voice_path, voice_name) = unsafe {
        let rc = crispasr_sys::crispasr_kokoro_resolve_fallback_voice_abi(
            cmodel.as_ptr(),
            clang.as_ptr(),
            out_voice.as_mut_ptr() as *mut c_char,
            out_voice.len() as c_int,
            out_picked.as_mut_ptr() as *mut c_char,
            out_picked.len() as c_int,
        );
        if rc < 0 {
            return Err("kokoro_resolve_fallback_voice: buffer too small".into());
        }
        if rc == 0 {
            let p = std::ffi::CStr::from_ptr(out_voice.as_ptr() as *const c_char)
                .to_string_lossy()
                .into_owned();
            let n = std::ffi::CStr::from_ptr(out_picked.as_ptr() as *const c_char)
                .to_string_lossy()
                .into_owned();
            (Some(p), Some(n))
        } else {
            (None, None)
        }
    };

    Ok(KokoroResolved {
        model_path: model_resolved,
        voice_path,
        voice_name,
        backbone_swapped,
    })
}

/// Tunables for [`Session::transcribe_vad`]. Defaults mirror crispasr's
/// `whisper_vad_default_params` plus the max-chunk fallback the shared
/// library uses to bound encoder cost on long audio.
#[derive(Clone, Copy, Debug)]
pub struct VadOptions {
    pub threshold: f32,
    pub min_speech_duration_ms: i32,
    pub min_silence_duration_ms: i32,
    pub speech_pad_ms: i32,
    /// Max merged-segment length (seconds). 0 disables the split.
    pub chunk_seconds: i32,
    /// Threads used for Silero VAD inference only; the ASR backend keeps
    /// the count chosen at session open time.
    pub n_threads: i32,
}

impl Default for VadOptions {
    fn default() -> Self {
        Self {
            threshold: 0.5,
            min_speech_duration_ms: 250,
            min_silence_duration_ms: 100,
            speech_pad_ms: 30,
            chunk_seconds: 30,
            n_threads: 4,
        }
    }
}

impl VadOptions {
    fn to_abi(self) -> crispasr_sys::CrispasrVadAbiOpts {
        crispasr_sys::CrispasrVadAbiOpts {
            threshold: self.threshold,
            min_speech_duration_ms: self.min_speech_duration_ms,
            min_silence_duration_ms: self.min_silence_duration_ms,
            speech_pad_ms: self.speech_pad_ms,
            chunk_seconds: self.chunk_seconds,
            n_threads: self.n_threads,
        }
    }
}

impl Drop for Session {
    fn drop(&mut self) {
        unsafe { crispasr_sys::crispasr_session_close(self.handle) }
    }
}

// =========================================================================
// Streaming (PLAN #62) — rolling-window decoder for whisper today.
// =========================================================================

/// One commit from a streaming session — the latest concatenated text
/// plus its absolute audio-time bounds.
#[derive(Debug, Clone)]
pub struct StreamingUpdate {
    pub text: String,
    pub t0: f64,
    pub t1: f64,
    pub counter: i64,
}

/// Streaming-decoder handle returned by [`Session::stream_open`]. Feed
/// PCM with [`Stream::feed`], pull text with [`Stream::get_text`],
/// finalize with [`Stream::flush`]. Auto-closes on drop.
pub struct Stream {
    handle: *mut crispasr_sys::CrispasrStream,
}

unsafe impl Send for Stream {}

impl Stream {
    /// Toggle voxtral4b live-captions decode-during-feed (PLAN #7
    /// phase 3). When enabled, each new audio_embed produced during
    /// `feed` triggers one greedy decode step; tokens commit
    /// immediately to `out_text` and `get_text` returns progressive
    /// transcript. Set BEFORE the first feed for clean semantics.
    /// No-op on backends without audio-injection prompt decode.
    pub fn set_live_decode(&self, enabled: bool) {
        unsafe {
            crispasr_sys::crispasr_stream_set_live_decode(self.handle, if enabled { 1 } else { 0 })
        };
    }

    /// Push 16 kHz mono float32 PCM. Returns 0 if still buffering, 1
    /// if a new partial transcript is ready (call [`get_text`](Stream::get_text)).
    pub fn feed(&self, pcm: &[f32]) -> Result<i32, String> {
        let rc = unsafe {
            crispasr_sys::crispasr_stream_feed(self.handle, pcm.as_ptr(), pcm.len() as c_int)
        };
        if rc < 0 {
            return Err(format!("stream_feed failed (rc={})", rc));
        }
        Ok(rc)
    }

    /// Return the latest committed transcript + absolute audio-time
    /// bounds. `counter` increments per commit; same value = no new text.
    pub fn get_text(&self) -> Result<StreamingUpdate, String> {
        let mut buf = vec![0u8; 8192];
        let mut t0: f64 = 0.0;
        let mut t1: f64 = 0.0;
        let mut counter: i64 = 0;
        let rc = unsafe {
            crispasr_sys::crispasr_stream_get_text(
                self.handle,
                buf.as_mut_ptr() as *mut c_char,
                buf.len() as c_int,
                &mut t0,
                &mut t1,
                &mut counter,
            )
        };
        if rc < 0 {
            return Err(format!("stream_get_text failed (rc={})", rc));
        }
        let text = unsafe { CStr::from_ptr(buf.as_ptr() as *const c_char) }
            .to_string_lossy()
            .into_owned();
        Ok(StreamingUpdate {
            text,
            t0,
            t1,
            counter,
        })
    }

    /// Finalize any remaining buffered audio.
    pub fn flush(&self) -> Result<(), String> {
        let rc = unsafe { crispasr_sys::crispasr_stream_flush(self.handle) };
        if rc < 0 {
            return Err(format!("stream_flush failed (rc={})", rc));
        }
        Ok(())
    }
}

impl Drop for Stream {
    fn drop(&mut self) {
        unsafe { crispasr_sys::crispasr_stream_close(self.handle) }
    }
}

// =========================================================================
// Microphone capture (PLAN #62d) — cross-platform via miniaudio.
// =========================================================================

use std::os::raw::c_void;
use std::sync::Mutex;

/// Library-level microphone handle. The user-supplied callback is
/// invoked from miniaudio's audio thread with mono float32 PCM in
/// [-1, 1]. Keep the callback short and non-blocking — for ASR, queue
/// the audio and feed [`Stream::feed`] from another thread.
///
/// Auto-stops + closes on drop.
pub struct Mic {
    handle: *mut crispasr_sys::CrispasrMic,
    _trampoline: Box<TrampolineState>,
}

unsafe impl Send for Mic {}

struct TrampolineState {
    cb: Mutex<Box<dyn FnMut(&[f32]) + Send + 'static>>,
}

extern "C" fn mic_trampoline(pcm: *const c_float, n_samples: c_int, userdata: *mut c_void) {
    if userdata.is_null() || pcm.is_null() || n_samples <= 0 {
        return;
    }
    unsafe {
        let state = &*(userdata as *const TrampolineState);
        let slice = std::slice::from_raw_parts(pcm, n_samples as usize);
        if let Ok(mut cb) = state.cb.lock() {
            (cb)(slice);
        }
    }
}

impl Mic {
    /// Open the default capture device. `sample_rate=16000` matches
    /// every ASR backend. Pass `channels=1` for mono (recommended);
    /// channels=2 hands the callback interleaved stereo.
    pub fn open<F>(sample_rate: i32, channels: i32, callback: F) -> Result<Mic, String>
    where
        F: FnMut(&[f32]) + Send + 'static,
    {
        let trampoline = Box::new(TrampolineState {
            cb: Mutex::new(Box::new(callback)),
        });
        let userdata_ptr = trampoline.as_ref() as *const TrampolineState as *mut c_void;
        let handle = unsafe {
            crispasr_sys::crispasr_mic_open(sample_rate, channels, mic_trampoline, userdata_ptr)
        };
        if handle.is_null() {
            return Err("crispasr_mic_open failed".to_string());
        }
        Ok(Mic {
            handle,
            _trampoline: trampoline,
        })
    }

    pub fn start(&self) -> Result<(), String> {
        let rc = unsafe { crispasr_sys::crispasr_mic_start(self.handle) };
        if rc != 0 {
            return Err(format!("mic_start failed (rc={})", rc));
        }
        Ok(())
    }

    pub fn stop(&self) -> Result<(), String> {
        let rc = unsafe { crispasr_sys::crispasr_mic_stop(self.handle) };
        if rc != 0 {
            return Err(format!("mic_stop failed (rc={})", rc));
        }
        Ok(())
    }
}

impl Drop for Mic {
    fn drop(&mut self) {
        unsafe { crispasr_sys::crispasr_mic_close(self.handle) }
    }
}

/// Human-readable name of the default capture device, or empty string
/// if no input device is available.
pub fn mic_default_device_name() -> String {
    let p = unsafe { crispasr_sys::crispasr_mic_default_device_name() };
    if p.is_null() {
        return String::new();
    }
    unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned()
}

// =========================================================================
// HF download + cache + model registry (shared C-ABI, 0.4.8+)
// =========================================================================

/// Known-model registry entry.
#[derive(Clone, Debug)]
pub struct RegistryEntry {
    pub filename: String,
    pub url: String,
    pub approx_size: String,
}

/// Role of one artifact in a canonical model download bundle.
///
/// Mirrors the append-only `crispasr_registry_artifact_kind` C enum, so
/// new kinds may appear in minor releases — match with a `_` arm (#332).
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum RegistryArtifactKind {
    Primary,
    Companion,
    Extra,
}

/// One file in a backend's canonical default download bundle.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RegistryArtifact {
    pub kind: RegistryArtifactKind,
    pub filename: String,
    pub url: String,
    pub approx_size: String,
}

/// The exact artifact bundle downloaded by `-m auto`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RegistryBundle {
    pub backend: String,
    pub license: String,
    pub requires_acceptance: bool,
    pub artifacts: Vec<RegistryArtifact>,
}

/// Look up the canonical GGUF for a backend (whisper, parakeet, canary,
/// voxtral, voxtral4b, granite, granite-4.1, qwen3, cohere, wav2vec2). Returns `None`
/// on miss.
/// List every backend name in the registry, in declaration order.
///
/// Each name can be passed back to [`registry_lookup`] for full details
/// (filename, URL, approximate size).
pub fn list_known_models() -> Vec<String> {
    let mut buf = vec![0u8; 8192];
    let n = unsafe {
        crispasr_sys::crispasr_registry_list_backends_abi(
            buf.as_mut_ptr() as *mut c_char,
            buf.len() as c_int,
        )
    };
    if n < 0 {
        return Vec::new();
    }
    let cstr = unsafe { CStr::from_ptr(buf.as_ptr() as *const c_char) };
    cstr.to_string_lossy()
        .split(',')
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string())
        .collect()
}

pub fn registry_lookup(backend: &str) -> Result<Option<RegistryEntry>, String> {
    registry_call_inner(backend, true)
}

/// Look up by filename (exact match, then fuzzy substring).
pub fn registry_lookup_by_filename(filename: &str) -> Result<Option<RegistryEntry>, String> {
    registry_call_inner(filename, false)
}

/// Return the backend's exact canonical `-m auto` artifact bundle.
///
/// Artifacts are ordered as downloaded: primary model, inline companion,
/// then any extra companions. No preferred quant is applied. Returns `None`
/// when the backend has no registry entry.
pub fn registry_default_bundle(backend: &str) -> Result<Option<RegistryBundle>, String> {
    if backend.is_empty() {
        return Ok(None);
    }
    let backend_c = CString::new(backend).map_err(|e| format!("backend NUL: {e}"))?;
    let mut canonical_buf = [0u8; 256];
    let mut license_buf = [0u8; 1024];
    let mut requires_acceptance = 0;
    let count = unsafe {
        crispasr_sys::crispasr_registry_default_bundle_info_abi(
            backend_c.as_ptr(),
            canonical_buf.as_mut_ptr() as *mut c_char,
            canonical_buf.len() as c_int,
            license_buf.as_mut_ptr() as *mut c_char,
            license_buf.len() as c_int,
            &mut requires_acceptance,
        )
    };
    if count == 0 {
        return Ok(None);
    }
    if count < 0 {
        return Err(format!(
            "default-bundle registry lookup failed (rc={count})"
        ));
    }

    fn slice_to_string(buf: &[u8]) -> String {
        let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
        String::from_utf8_lossy(&buf[..end]).into_owned()
    }

    let mut artifacts = Vec::with_capacity(count as usize);
    for index in 0..count {
        let mut kind = 0;
        let mut filename_buf = [0u8; 256];
        let mut url_buf = [0u8; 2048];
        let mut size_buf = [0u8; 64];
        let rc = unsafe {
            crispasr_sys::crispasr_registry_default_bundle_artifact_abi(
                backend_c.as_ptr(),
                index,
                &mut kind,
                filename_buf.as_mut_ptr() as *mut c_char,
                filename_buf.len() as c_int,
                url_buf.as_mut_ptr() as *mut c_char,
                url_buf.len() as c_int,
                size_buf.as_mut_ptr() as *mut c_char,
                size_buf.len() as c_int,
            )
        };
        if rc != 0 {
            return Err(format!(
                "default-bundle artifact {index} lookup failed (rc={rc})"
            ));
        }
        let kind = match kind {
            0 => RegistryArtifactKind::Primary,
            1 => RegistryArtifactKind::Companion,
            2 => RegistryArtifactKind::Extra,
            value => {
                return Err(format!(
                    "default-bundle artifact {index} has unknown kind {value}"
                ))
            }
        };
        artifacts.push(RegistryArtifact {
            kind,
            filename: slice_to_string(&filename_buf),
            url: slice_to_string(&url_buf),
            approx_size: slice_to_string(&size_buf),
        });
    }

    Ok(Some(RegistryBundle {
        backend: slice_to_string(&canonical_buf),
        license: slice_to_string(&license_buf),
        requires_acceptance: requires_acceptance != 0,
        artifacts,
    }))
}

fn registry_call_inner(key: &str, by_backend: bool) -> Result<Option<RegistryEntry>, String> {
    if key.is_empty() {
        return Ok(None);
    }
    let key_c = CString::new(key).map_err(|e| format!("key NUL: {e}"))?;
    let mut fn_buf = [0u8; 256];
    let mut url_buf = [0u8; 512];
    let mut size_buf = [0u8; 32];
    let rc = unsafe {
        if by_backend {
            crispasr_sys::crispasr_registry_lookup_abi(
                key_c.as_ptr(),
                fn_buf.as_mut_ptr() as *mut c_char,
                fn_buf.len() as i32,
                url_buf.as_mut_ptr() as *mut c_char,
                url_buf.len() as i32,
                size_buf.as_mut_ptr() as *mut c_char,
                size_buf.len() as i32,
            )
        } else {
            crispasr_sys::crispasr_registry_lookup_by_filename_abi(
                key_c.as_ptr(),
                fn_buf.as_mut_ptr() as *mut c_char,
                fn_buf.len() as i32,
                url_buf.as_mut_ptr() as *mut c_char,
                url_buf.len() as i32,
                size_buf.as_mut_ptr() as *mut c_char,
                size_buf.len() as i32,
            )
        }
    };
    if rc != 0 {
        return Ok(None);
    }
    fn slice_to_string(buf: &[u8]) -> String {
        let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
        String::from_utf8_lossy(&buf[..end]).into_owned()
    }
    Ok(Some(RegistryEntry {
        filename: slice_to_string(&fn_buf),
        url: slice_to_string(&url_buf),
        approx_size: slice_to_string(&size_buf),
    }))
}

/// Download `filename` from `url` into the CrispASR cache — or return
/// the cached path if already present. Pass `None` for
/// `cache_dir_override` to use the platform default.
pub fn cache_ensure_file(
    filename: &str,
    url: &str,
    quiet: bool,
    cache_dir_override: Option<&str>,
) -> Result<Option<String>, String> {
    if filename.is_empty() || url.is_empty() {
        return Ok(None);
    }
    let fn_c = CString::new(filename).map_err(|e| format!("filename NUL: {e}"))?;
    let url_c = CString::new(url).map_err(|e| format!("url NUL: {e}"))?;
    let ov_c = CString::new(cache_dir_override.unwrap_or(""))
        .map_err(|e| format!("cache_dir_override NUL: {e}"))?;
    let mut buf = vec![0u8; 2048];
    let rc = unsafe {
        crispasr_sys::crispasr_cache_ensure_file_abi(
            fn_c.as_ptr(),
            url_c.as_ptr(),
            if quiet { 1 } else { 0 },
            ov_c.as_ptr(),
            buf.as_mut_ptr() as *mut c_char,
            buf.len() as i32,
        )
    };
    if rc != 0 {
        return Ok(None);
    }
    let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
    Ok(Some(String::from_utf8_lossy(&buf[..end]).into_owned()))
}

/// Return the CrispASR cache directory (creating it if missing).
pub fn cache_dir(override_path: Option<&str>) -> Result<Option<String>, String> {
    let ov_c =
        CString::new(override_path.unwrap_or("")).map_err(|e| format!("override NUL: {e}"))?;
    let mut buf = vec![0u8; 2048];
    let rc = unsafe {
        crispasr_sys::crispasr_cache_dir_abi(
            ov_c.as_ptr(),
            buf.as_mut_ptr() as *mut c_char,
            buf.len() as i32,
        )
    };
    if rc != 0 {
        return Ok(None);
    }
    let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
    Ok(Some(String::from_utf8_lossy(&buf[..end]).into_owned()))
}

// =========================================================================
// CTC / forced-aligner word timings (shared C-ABI, 0.4.7+)
// =========================================================================

#[derive(Clone, Debug)]
pub struct AlignedWord {
    pub text: String,
    pub start: f64, // seconds
    pub end: f64,
}

/// Run CTC / forced-aligner word timings for a transcript + audio pair.
///
/// `aligner_model` filename picks the backend: paths containing
/// "forced-aligner" / "qwen3-fa" / "qwen3-forced" route to the
/// Qwen3-ForcedAligner path; everything else goes through
/// canary-ctc-aligner. `t_offset` (seconds) is added to every word
/// start/end so the returned timings are absolute against the
/// original audio.
///
/// Returns an empty vector when the aligner failed or produced no
/// output. Errors are printed to stderr by the library, since they
/// typically indicate a missing / wrong model file.
pub fn align_words(
    aligner_model: &str,
    transcript: &str,
    pcm: &[f32],
    t_offset: f64,
    n_threads: i32,
) -> Result<Vec<AlignedWord>, String> {
    if aligner_model.is_empty() || transcript.is_empty() || pcm.is_empty() {
        return Ok(Vec::new());
    }
    let model_c = CString::new(aligner_model).map_err(|e| format!("aligner_model NUL: {e}"))?;
    let trans_c = CString::new(transcript).map_err(|e| format!("transcript NUL: {e}"))?;

    let res = unsafe {
        crispasr_sys::crispasr_align_words_abi(
            model_c.as_ptr(),
            trans_c.as_ptr(),
            pcm.as_ptr(),
            pcm.len() as i32,
            (t_offset * 100.0).round() as i64,
            n_threads,
        )
    };
    if res.is_null() {
        return Ok(Vec::new());
    }

    let mut out = Vec::new();
    unsafe {
        let n = crispasr_sys::crispasr_align_result_n_words(res);
        for i in 0..n {
            let tp = crispasr_sys::crispasr_align_result_word_text(res, i);
            let text = if tp.is_null() {
                String::new()
            } else {
                CStr::from_ptr(tp).to_string_lossy().into_owned()
            };
            let t0 = crispasr_sys::crispasr_align_result_word_t0(res, i) as f64 / 100.0;
            let t1 = crispasr_sys::crispasr_align_result_word_t1(res, i) as f64 / 100.0;
            out.push(AlignedWord {
                text,
                start: t0,
                end: t1,
            });
        }
        crispasr_sys::crispasr_align_result_free(res);
    }
    Ok(out)
}

// =========================================================================
// Language identification (shared C-ABI, 0.4.6+)
// =========================================================================

/// Mirrors the append-only C LID-method enum, so new methods may appear
/// in minor releases — match with a `_` arm (#332).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(i32)]
#[non_exhaustive]
pub enum LidMethod {
    /// Whisper encoder + language head. Needs a multilingual ggml-*.bin model.
    Whisper = 0,
    /// GGUF-packed Silero 95-language classifier.
    Silero = 1,
    /// FireRedTeam/FireRedLID — encoder + 6-layer LID Transformer, 120 langs.
    /// Wired through the same module-level `crispasr_detect_language` C-ABI
    /// as Whisper/Silero — no session required.
    Firered = 2,
    /// SpeechBrain ECAPA-TDNN VoxLingua107 — attentive statistical pooling,
    /// 107 langs.  Same module-level path as the others.
    Ecapa = 3,
}

#[derive(Clone, Debug)]
pub struct LidResult {
    /// ISO 639-1 language code (`"en"`, `"de"`, …). Empty on failure.
    pub lang_code: String,
    /// Posterior probability on the argmax language. `-1.0` on failure.
    pub confidence: f32,
}

/// Run language identification on a 16 kHz mono float PCM buffer.
///
/// `model_path` must point to a concrete model file on disk (the
/// whisper `ggml-*.bin` for [`LidMethod::Whisper`] or a Silero GGUF
/// for [`LidMethod::Silero`]). Auto-download / cache resolution is the
/// caller's responsibility; the CrispASR CLI has a helper for that,
/// wrappers can ship the model as an asset.
pub fn detect_language_pcm(
    pcm: &[f32],
    method: LidMethod,
    model_path: &str,
    n_threads: i32,
    use_gpu: bool,
    gpu_device: i32,
    flash_attn: bool,
) -> Result<LidResult, String> {
    if pcm.is_empty() || model_path.is_empty() {
        return Ok(LidResult {
            lang_code: String::new(),
            confidence: -1.0,
        });
    }
    let path_c = CString::new(model_path).map_err(|e| format!("model_path contains NUL: {e}"))?;

    let mut buf = [0u8; 16];
    let mut conf: c_float = -1.0;
    let rc = unsafe {
        crispasr_sys::crispasr_detect_language_pcm(
            pcm.as_ptr(),
            pcm.len() as i32,
            method as i32,
            path_c.as_ptr(),
            n_threads,
            if use_gpu { 1 } else { 0 },
            gpu_device,
            if flash_attn { 1 } else { 0 },
            buf.as_mut_ptr() as *mut c_char,
            buf.len() as i32,
            &mut conf,
        )
    };
    if rc != 0 {
        return Ok(LidResult {
            lang_code: String::new(),
            confidence: -1.0,
        });
    }
    let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
    let code = std::str::from_utf8(&buf[..end])
        .map_err(|e| format!("LID returned non-UTF8 bytes: {e}"))?
        .to_string();
    Ok(LidResult {
        lang_code: code,
        confidence: conf as f32,
    })
}

// =========================================================================
// Text-LID — P13.5 Phase 7 (C-ABI 0.5.2+)
// =========================================================================

/// Result of [`text_detect_language`].  Label format depends on the
/// loaded GGUF: CLD3 returns ISO 639-1 (`"en"`, `"de"`, `"zh-Latn"`)
/// across 109 labels; GlotLID-V3 / LID-176 fastText return ISO 639-3
/// with a script tag (`"eng_Latn"`, `"sco_Latn"`) across 2102 or 176
/// labels respectively.  Callers needing ISO 639-1 normalisation
/// must do it on their side — the dispatcher preserves the model's
/// native space because the script tag carries real information
/// (e.g. `zh-Latn` ≠ `zh-Hans`).
#[derive(Clone, Debug)]
pub struct TextLidResult {
    /// Predicted language label.  Empty on failure.  See type docs
    /// for the format details.
    pub label: String,
    /// Posterior probability on the argmax label.  `-1.0` on
    /// dispatcher failures, otherwise `[0.0, 1.0]`.
    pub confidence: f32,
}

/// Detect the language of a UTF-8 text string via the internal
/// `text_lid_dispatch` (peek the GGUF's `general.architecture` →
/// route to CLD3 or fastText).
///
/// `model_path` must be a concrete on-disk path; auto-resolution
/// from the registry is the caller's job (use
/// `registry_lookup("lid-cld3" / "lid-glotlid" / "lid-fasttext176")`
/// + `cache_ensure_file` for the same shape the ASR side already
/// uses).
///
/// Errors when:
/// - any input string contains an interior NUL,
/// - the GGUF can't be opened or has an unsupported architecture,
/// - the predict path errors out,
/// - the output buffer (256 bytes here — fits CLD3's longest
///   `zh-Latn` and fastText's longest `<3-letter>_<4-letter>`
///   labels with room to spare) overflows.
pub fn text_detect_language(
    text: &str,
    model_path: &str,
    n_threads: i32,
) -> Result<TextLidResult, String> {
    let ctext = CString::new(text).map_err(|e| format!("text contains NUL: {e}"))?;
    let cmodel = CString::new(model_path).map_err(|e| format!("model_path contains NUL: {e}"))?;

    // 256-byte buffer comfortably fits every label format the
    // dispatcher emits — CLD3's longest is ~10 bytes (`zh-Latn`),
    // fastText's longest is ~12 bytes (`<3letter>_<4letter>`).
    let mut buf = [0u8; 256];
    let mut conf: c_float = -1.0;
    let rc = unsafe {
        crispasr_sys::crispasr_text_detect_language(
            ctext.as_ptr(),
            cmodel.as_ptr(),
            n_threads,
            buf.as_mut_ptr() as *mut c_char,
            buf.len() as i32,
            &mut conf,
        )
    };
    match rc {
        0 => {
            let end = buf.iter().position(|&b| b == 0).unwrap_or(buf.len());
            let label = std::str::from_utf8(&buf[..end])
                .map_err(|e| format!("text-LID returned non-UTF8 bytes: {e}"))?
                .to_string();
            Ok(TextLidResult {
                label,
                confidence: conf as f32,
            })
        }
        -1 => Err("text-LID: invalid args (null pointer or bad buffer size)".to_string()),
        1 => Err(format!(
            "text-LID dispatcher init/predict failed for model {model_path} \
             (check the GGUF's architecture key — must be `lid-cld3` or `lid-fasttext`)"
        )),
        2 => Err(
            "text-LID label exceeded 256-byte output buffer — file an issue, this shouldn't happen \
             with the dispatcher's current label spaces"
                .to_string(),
        ),
        other => Err(format!("text-LID returned unexpected status code {other}")),
    }
}

// =========================================================================
// Diarization (shared C-ABI, 0.4.5+)
// =========================================================================

/// One ASR segment passed to [`diarize_segments`]. Caller fills `t0` / `t1`
/// (seconds) from the upstream transcribe result; the diarizer writes the
/// zero-based speaker index into `speaker` (`-1` means the method had no
/// info to pick).
#[derive(Clone, Copy, Debug)]
pub struct DiarizeSegment {
    pub t0: f64,
    pub t1: f64,
    pub speaker: i32,
}

impl DiarizeSegment {
    pub fn new(t0: f64, t1: f64) -> Self {
        Self {
            t0,
            t1,
            speaker: -1,
        }
    }
}

/// Mirrors the append-only `CrispasrDiarizeMethod` C enum, so new methods
/// may appear in minor releases — match with a `_` arm (#332).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(i32)]
#[non_exhaustive]
pub enum DiarizeMethod {
    /// Stereo only. |L| vs |R| energy per segment, 1.1× margin.
    Energy = 0,
    /// Stereo only. TDOA via cross-correlation, ±5 ms search window.
    Xcorr = 1,
    /// Mono-friendly. Alternates 0/1 every >600 ms gap.
    VadTurns = 2,
    /// Mono-friendly, ML-based. Runs the GGUF pyannote segmentation net;
    /// requires a model path.
    Pyannote = 3,
    /// Mono-friendly, ML-based (#324): WeSpeaker embeddings + spectral
    /// clustering (the FoxNose recipe). Requires
    /// [`DiarizeOptions::foxnose_embedder_path`]. Unlike the other methods
    /// it derives speaker turns from the audio and attributes each caller
    /// segment to the turn it overlaps most.
    FoxNose = 4,
}

/// Construct via [`Default`] and set fields as needed — the struct grows
/// alongside the append-only C ABI (#332).
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct DiarizeOptions {
    pub method: DiarizeMethod,
    /// GGUF path. Required for `Pyannote`, ignored otherwise.
    pub pyannote_model_path: Option<String>,
    /// Threads for pyannote inference; ignored by other methods.
    pub n_threads: i32,
    /// Absolute start (seconds) of the PCM buffer within the original
    /// audio, so the diarizer can map absolute segment timestamps back
    /// to sample indices.
    pub slice_t0: f64,
    /// GGUF path for the speaker-embedding model (WeSpeaker ResNet34-LM).
    /// Required for `FoxNose`, ignored otherwise.
    pub foxnose_embedder_path: Option<String>,
    /// FoxNose speaker-count lower bound for automatic estimation (0 -> 1).
    pub min_speakers: i32,
    /// FoxNose speaker-count upper bound for automatic estimation (0 -> 8).
    pub max_speakers: i32,
    /// FoxNose: > 0 pins the speaker count and skips estimation entirely.
    pub num_speakers: i32,
}

impl Default for DiarizeOptions {
    fn default() -> Self {
        Self {
            method: DiarizeMethod::VadTurns,
            pyannote_model_path: None,
            n_threads: 4,
            slice_t0: 0.0,
            foxnose_embedder_path: None,
            min_speakers: 0,
            max_speakers: 0,
            num_speakers: 0,
        }
    }
}

/// Assign a speaker index to each of `segs`, mutating each
/// [`DiarizeSegment::speaker`] in place.
///
/// Five methods — see [`DiarizeMethod`]. `left` is mono PCM for
/// mono-only methods, otherwise the left channel of a stereo pair.
/// When `is_stereo` is true, `right` must be `Some`. All PCM is 16 kHz
/// float32.
///
/// Returns `Ok(())` on success. Only the model-backed methods
/// ([`DiarizeMethod::Pyannote`], [`DiarizeMethod::FoxNose`]) can fail
/// (model load failure).
pub fn diarize_segments(
    segs: &mut [DiarizeSegment],
    left: &[f32],
    right: Option<&[f32]>,
    is_stereo: bool,
    opts: &DiarizeOptions,
) -> Result<(), String> {
    if segs.is_empty() || left.is_empty() {
        return Ok(());
    }

    let path_c = match (&opts.pyannote_model_path, opts.method) {
        (Some(p), DiarizeMethod::Pyannote) => Some(
            CString::new(p.as_str())
                .map_err(|e| format!("pyannote_model_path contains NUL: {e}"))?,
        ),
        _ => None,
    };
    let foxnose_c = match (&opts.foxnose_embedder_path, opts.method) {
        (Some(p), DiarizeMethod::FoxNose) => Some(
            CString::new(p.as_str())
                .map_err(|e| format!("foxnose_embedder_path contains NUL: {e}"))?,
        ),
        _ => None,
    };

    let abi_opts = crispasr_sys::CrispasrDiarizeOptsAbi {
        method: opts.method as i32,
        n_threads: opts.n_threads,
        slice_t0_cs: (opts.slice_t0 * 100.0).round() as i64,
        pyannote_model_path: path_c
            .as_ref()
            .map(|c| c.as_ptr())
            .unwrap_or(std::ptr::null()),
        foxnose_embedder_path: foxnose_c
            .as_ref()
            .map(|c| c.as_ptr())
            .unwrap_or(std::ptr::null()),
        min_speakers: opts.min_speakers,
        max_speakers: opts.max_speakers,
        num_speakers: opts.num_speakers,
        _pad2: 0,
    };

    let mut abi_segs: Vec<crispasr_sys::CrispasrDiarizeSegAbi> = segs
        .iter()
        .map(|s| crispasr_sys::CrispasrDiarizeSegAbi {
            t0_cs: (s.t0 * 100.0).round() as i64,
            t1_cs: (s.t1 * 100.0).round() as i64,
            speaker: s.speaker,
            _pad: 0,
        })
        .collect();

    let right_ptr = match (is_stereo, right) {
        (true, Some(r)) => r.as_ptr(),
        _ => left.as_ptr(),
    };

    let rc = unsafe {
        crispasr_sys::crispasr_diarize_segments_abi(
            left.as_ptr(),
            right_ptr,
            left.len() as i32,
            if is_stereo { 1 } else { 0 },
            abi_segs.as_mut_ptr(),
            abi_segs.len() as i32,
            &abi_opts,
        )
    };
    match rc {
        0 => {
            for (i, s) in segs.iter_mut().enumerate() {
                s.speaker = abi_segs[i].speaker;
            }
            Ok(())
        }
        1 => Err("diarize model load failed (pyannote / foxnose embedder)".to_string()),
        -1 => Err("invalid arguments to crispasr_diarize_segments_abi".to_string()),
        other => Err(format!("crispasr_diarize_segments_abi returned {other}")),
    }
}

// =========================================================================
// Pluggable speaker embedder + cosine clustering + pyannote cache (#107 P6)
// =========================================================================
//
// These are the same building blocks the CLI's `--diarize-embedder` path
// uses. Together they let a Rust caller compose the full diarization
// pipeline (pyannote segmentation -> per-speech-interval embeddings ->
// agglomerative clustering -> globally stable speaker IDs).

/// Pluggable speaker-embedding model. Wraps the
/// `crispasr_speaker_embedder_*_abi` family in a safe Rust struct.
pub struct SpeakerEmbedder {
    raw: *mut std::ffi::c_void,
}

impl SpeakerEmbedder {
    /// Build a speaker embedder by spec.
    ///
    /// `model_spec` accepts (case-insensitive):
    ///   - `"auto"` / `"titanet"` -> TitaNet-Large (192-d)
    ///   - `"indextts"` / `"indextts-bigvgan"` / `"ecapa"` ->
    ///     IndexTTS-BigVGAN ECAPA-TDNN (512-d)
    ///   - a `.gguf` path -> dispatched by filename
    pub fn new(model_spec: &str, n_threads: i32, cache_dir: Option<&str>) -> Result<Self, String> {
        let spec_c = std::ffi::CString::new(model_spec).map_err(|e| e.to_string())?;
        let cache_c = cache_dir
            .map(|s| std::ffi::CString::new(s))
            .transpose()
            .map_err(|e: std::ffi::NulError| e.to_string())?;
        let cache_ptr = cache_c
            .as_ref()
            .map(|s| s.as_ptr())
            .unwrap_or(std::ptr::null());
        let raw = unsafe {
            crispasr_sys::crispasr_speaker_embedder_make_abi(spec_c.as_ptr(), n_threads, cache_ptr)
        };
        if raw.is_null() {
            return Err(format!("failed to build speaker embedder '{model_spec}'"));
        }
        Ok(Self { raw })
    }

    /// Output embedding dimension (e.g. 192 for TitaNet).
    pub fn dim(&self) -> i32 {
        unsafe { crispasr_sys::crispasr_speaker_embedder_dim_abi(self.raw) }
    }

    /// Backend name for logging (e.g. "titanet-large").
    pub fn name(&self) -> String {
        unsafe {
            let p = crispasr_sys::crispasr_speaker_embedder_name_abi(self.raw);
            if p.is_null() {
                String::new()
            } else {
                std::ffi::CStr::from_ptr(p).to_string_lossy().into_owned()
            }
        }
    }

    /// Extract one embedding from mono 16 kHz f32 PCM. Returns `None`
    /// when the underlying model rejected the input (typically too
    /// short for its mel pipeline).
    pub fn embed(&self, pcm_16k: &[f32]) -> Option<Vec<f32>> {
        let dim = self.dim();
        if dim <= 0 || pcm_16k.is_empty() {
            return None;
        }
        let mut out = vec![0.0f32; dim as usize];
        let ok = unsafe {
            crispasr_sys::crispasr_speaker_embedder_embed_abi(
                self.raw,
                pcm_16k.as_ptr(),
                pcm_16k.len() as i32,
                out.as_mut_ptr(),
            )
        };
        if ok != 0 {
            Some(out)
        } else {
            None
        }
    }
}

impl Drop for SpeakerEmbedder {
    fn drop(&mut self) {
        if !self.raw.is_null() {
            unsafe { crispasr_sys::crispasr_speaker_embedder_free_abi(self.raw) };
            self.raw = std::ptr::null_mut();
        }
    }
}

unsafe impl Send for SpeakerEmbedder {}

/// Agglomerative single-linkage cosine clustering on L2-normalized
/// speaker embeddings.
///
/// `embeddings` is a flat row-major `n * dim` buffer (e.g. four 192-d
/// vectors -> 768 floats). Stops at `merge_threshold` similarity or
/// when the count reaches `max_speakers`. Returns one cluster ID per
/// input in `[0, k)` assigned in first-appearance order.
pub fn agglomerative_cluster(
    embeddings: &[f32],
    n: i32,
    dim: i32,
    merge_threshold: f32,
    max_speakers: i32,
) -> Result<Vec<i32>, String> {
    if n <= 0 || dim <= 0 || embeddings.len() < (n as usize) * (dim as usize) {
        return Err("invalid arguments to agglomerative_cluster".to_string());
    }
    let mut out = vec![0i32; n as usize];
    let k = unsafe {
        crispasr_sys::crispasr_speaker_cluster_abi(
            embeddings.as_ptr(),
            n,
            dim,
            merge_threshold,
            max_speakers,
            out.as_mut_ptr(),
        )
    };
    if k < 0 {
        return Err("crispasr_speaker_cluster_abi returned -1".to_string());
    }
    Ok(out)
}

/// Pre-computed pyannote-seg posteriors over a full audio buffer.
///
/// Build once at the start of a diarize pipeline, then call
/// [`PyannoteCache::apply`] for each set of segment ranges. Gives
/// cross-slice consistency for pyannote-method diarization (#107 P2a)
/// without re-running the segmentation net per slice.
pub struct PyannoteCache {
    raw: *mut std::ffi::c_void,
}

impl PyannoteCache {
    /// Run pyannote-seg once over `pcm_16k` and cache the posteriors.
    pub fn compute(pcm_16k: &[f32], model_path: &str, n_threads: i32) -> Result<Self, String> {
        if pcm_16k.is_empty() {
            return Err("empty audio".to_string());
        }
        let model_c = std::ffi::CString::new(model_path).map_err(|e| e.to_string())?;
        let raw = unsafe {
            crispasr_sys::crispasr_pyannote_cache_compute_abi(
                pcm_16k.as_ptr(),
                pcm_16k.len() as i32,
                model_c.as_ptr(),
                n_threads,
            )
        };
        if raw.is_null() {
            return Err(format!(
                "failed to compute pyannote cache from '{model_path}'"
            ));
        }
        Ok(Self { raw })
    }

    /// Score `segs` against the cached posteriors. Each segment's
    /// `speaker` is set to `0/1/2` (local pyannote-seg track index) or
    /// `-1` for silence.
    pub fn apply(&self, segs: &mut [DiarizeSegment], slice_t0: f64) -> Result<(), String> {
        if segs.is_empty() {
            return Ok(());
        }
        let mut abi_segs: Vec<crispasr_sys::CrispasrDiarizeSegAbi> = segs
            .iter()
            .map(|s| crispasr_sys::CrispasrDiarizeSegAbi {
                t0_cs: (s.t0 * 100.0).round() as i64,
                t1_cs: (s.t1 * 100.0).round() as i64,
                speaker: s.speaker,
                _pad: 0,
            })
            .collect();
        let rc = unsafe {
            crispasr_sys::crispasr_pyannote_cache_apply_abi(
                self.raw,
                (slice_t0 * 100.0).round() as i64,
                abi_segs.as_mut_ptr(),
                abi_segs.len() as i32,
            )
        };
        if rc != 0 {
            return Err(format!("crispasr_pyannote_cache_apply_abi returned {rc}"));
        }
        for (i, s) in segs.iter_mut().enumerate() {
            s.speaker = abi_segs[i].speaker;
        }
        Ok(())
    }
}

impl Drop for PyannoteCache {
    fn drop(&mut self) {
        if !self.raw.is_null() {
            unsafe { crispasr_sys::crispasr_pyannote_cache_free_abi(self.raw) };
            self.raw = std::ptr::null_mut();
        }
    }
}

unsafe impl Send for PyannoteCache {}

// =========================================================================
// FireRedPunc — punctuation restoration post-processor
// =========================================================================

/// BERT-based punctuation restoration model (FireRedPunc).
///
/// Adds punctuation and capitalization to unpunctuated ASR output.
/// Particularly useful for CTC-based backends (wav2vec2, omniasr,
/// fastconformer-ctc, firered-asr) that output lowercase text.
///
/// ```no_run
/// use crispasr::PuncModel;
///
/// let punc = PuncModel::open("fireredpunc-q8_0.gguf").unwrap();
/// let text = punc.process("and so my fellow americans ask not");
/// println!("{text}"); // "And so my fellow americans, ask not..."
/// ```
pub struct PuncModel {
    handle: *mut std::ffi::c_void,
}

unsafe impl Send for PuncModel {}

impl PuncModel {
    /// Load a FireRedPunc GGUF model.
    pub fn open(model_path: &str) -> Result<Self, String> {
        let c_path = CString::new(model_path).map_err(|e| e.to_string())?;
        let handle = unsafe { crispasr_sys::crispasr_punc_init(c_path.as_ptr()) };
        if handle.is_null() {
            return Err(format!("Failed to load punc model: {model_path}"));
        }
        Ok(Self { handle })
    }

    /// Add punctuation to unpunctuated text.
    pub fn process(&self, text: &str) -> String {
        let c_text = CString::new(text).unwrap_or_default();
        let result = unsafe { crispasr_sys::crispasr_punc_process(self.handle, c_text.as_ptr()) };
        if result.is_null() {
            return text.to_string();
        }
        let out = unsafe { CStr::from_ptr(result) }
            .to_string_lossy()
            .into_owned();
        unsafe { crispasr_sys::crispasr_punc_free_text(result) };
        out
    }
}

impl Drop for PuncModel {
    fn drop(&mut self) {
        if !self.handle.is_null() {
            unsafe { crispasr_sys::crispasr_punc_free(self.handle) };
            self.handle = std::ptr::null_mut();
        }
    }
}

// =========================================================================
// Direct Parakeet API (bypasses unified session)
// =========================================================================

/// Direct Parakeet ASR context with word- and token-level timestamps.
///
/// For most use cases prefer [`Session`] which auto-dispatches to Parakeet
/// when the GGUF metadata indicates it.
pub struct Parakeet {
    handle: *mut std::ffi::c_void,
}

unsafe impl Send for Parakeet {}

/// Parakeet transcription result with word and token accessors.
pub struct ParakeetResult {
    handle: *mut std::ffi::c_void,
}

impl ParakeetResult {
    pub fn text(&self) -> String {
        let p = unsafe { crispasr_sys::crispasr_parakeet_result_text(self.handle) };
        if p.is_null() {
            String::new()
        } else {
            unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned()
        }
    }
    pub fn n_words(&self) -> i32 {
        unsafe { crispasr_sys::crispasr_parakeet_result_n_words(self.handle) }
    }
    pub fn word_text(&self, i: i32) -> String {
        let p = unsafe { crispasr_sys::crispasr_parakeet_result_word_text(self.handle, i) };
        if p.is_null() {
            String::new()
        } else {
            unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned()
        }
    }
    pub fn word_t0(&self, i: i32) -> i64 {
        unsafe { crispasr_sys::crispasr_parakeet_result_word_t0(self.handle, i) }
    }
    pub fn word_t1(&self, i: i32) -> i64 {
        unsafe { crispasr_sys::crispasr_parakeet_result_word_t1(self.handle, i) }
    }
    pub fn n_tokens(&self) -> i32 {
        unsafe { crispasr_sys::crispasr_parakeet_result_n_tokens(self.handle) }
    }
    pub fn token_text(&self, i: i32) -> String {
        let p = unsafe { crispasr_sys::crispasr_parakeet_result_token_text(self.handle, i) };
        if p.is_null() {
            String::new()
        } else {
            unsafe { CStr::from_ptr(p) }.to_string_lossy().into_owned()
        }
    }
    pub fn token_t0(&self, i: i32) -> i64 {
        unsafe { crispasr_sys::crispasr_parakeet_result_token_t0(self.handle, i) }
    }
    pub fn token_t1(&self, i: i32) -> i64 {
        unsafe { crispasr_sys::crispasr_parakeet_result_token_t1(self.handle, i) }
    }
    pub fn token_p(&self, i: i32) -> f32 {
        unsafe { crispasr_sys::crispasr_parakeet_result_token_p(self.handle, i) }
    }
}

impl Drop for ParakeetResult {
    fn drop(&mut self) {
        if !self.handle.is_null() {
            unsafe { crispasr_sys::crispasr_parakeet_result_free(self.handle) };
            self.handle = std::ptr::null_mut();
        }
    }
}

impl Parakeet {
    pub fn new(model_path: &str, n_threads: i32, use_flash: bool) -> Result<Self, String> {
        let c_path = CString::new(model_path).map_err(|e| e.to_string())?;
        let handle = unsafe {
            crispasr_sys::crispasr_parakeet_init(
                c_path.as_ptr(),
                n_threads,
                if use_flash { 1 } else { 0 },
            )
        };
        if handle.is_null() {
            return Err(format!("Failed to load Parakeet model: {model_path}"));
        }
        Ok(Self { handle })
    }

    pub fn transcribe(
        &self,
        pcm: &[f32],
        language: Option<&str>,
    ) -> Result<ParakeetResult, String> {
        let lang = language.map(|l| CString::new(l).unwrap_or_default());
        let lang_ptr = lang.as_ref().map_or(std::ptr::null(), |c| c.as_ptr());
        let res = unsafe {
            crispasr_sys::crispasr_parakeet_transcribe(
                self.handle,
                pcm.as_ptr(),
                pcm.len() as c_int,
                lang_ptr,
            )
        };
        if res.is_null() {
            return Err("crispasr_parakeet_transcribe returned null".to_string());
        }
        Ok(ParakeetResult { handle: res })
    }
}

impl Drop for Parakeet {
    fn drop(&mut self) {
        if !self.handle.is_null() {
            unsafe { crispasr_sys::crispasr_parakeet_free(self.handle) };
            self.handle = std::ptr::null_mut();
        }
    }
}

// =========================================================================
// Standalone helpers — full C-ABI parity
// =========================================================================

/// Chunk-boundary LCS dedup: returns the number of leading tokens
/// of `curr_tokens` to drop to remove overlap with `prev_tail_tokens`.
pub fn lcs_dedup_prefix_count(prev_tail: &[i32], curr: &[i32], min_lcs_length: i32) -> i32 {
    unsafe {
        crispasr_sys::crispasr_lcs_dedup_prefix_count(
            prev_tail.as_ptr(),
            prev_tail.len() as c_int,
            curr.as_ptr(),
            curr.len() as c_int,
            min_lcs_length,
        )
    }
}

/// Run standalone VAD returning speech spans in centiseconds.
pub fn vad_segments(
    model_path: &str,
    pcm: &[f32],
    sample_rate: i32,
    threshold: f32,
    min_speech_ms: i32,
    min_silence_ms: i32,
    n_threads: i32,
    use_gpu: bool,
) -> Result<Vec<(f32, f32)>, String> {
    let c_path = CString::new(model_path).map_err(|e| e.to_string())?;
    let mut out_spans: *mut f32 = std::ptr::null_mut();
    let n = unsafe {
        crispasr_sys::crispasr_vad_segments(
            c_path.as_ptr(),
            pcm.as_ptr(),
            pcm.len() as c_int,
            sample_rate,
            threshold,
            min_speech_ms,
            min_silence_ms,
            n_threads,
            if use_gpu { 1 } else { 0 },
            &mut out_spans,
        )
    };
    if n < 0 {
        return Err(format!("crispasr_vad_segments failed (rc={n})"));
    }
    let mut spans = Vec::with_capacity(n as usize);
    for i in 0..n as isize {
        unsafe {
            spans.push((*out_spans.offset(2 * i), *out_spans.offset(2 * i + 1)));
        }
    }
    if n > 0 {
        unsafe { crispasr_sys::crispasr_vad_free(out_spans) };
    }
    Ok(spans)
}

/// Run unified VAD dispatcher returning speech spans in seconds.
pub fn vad_slices(
    model_path: &str,
    pcm: &[f32],
    sample_rate: i32,
    threshold: f32,
    min_speech_ms: i32,
    min_silence_ms: i32,
    speech_pad_ms: i32,
    max_chunk_duration_s: f32,
    n_threads: i32,
) -> Result<Vec<(f32, f32)>, String> {
    let c_path = CString::new(model_path).map_err(|e| e.to_string())?;
    let mut out_spans: *mut f32 = std::ptr::null_mut();
    let n = unsafe {
        crispasr_sys::crispasr_vad_slices(
            c_path.as_ptr(),
            pcm.as_ptr(),
            pcm.len() as c_int,
            sample_rate,
            threshold,
            min_speech_ms,
            min_silence_ms,
            speech_pad_ms,
            max_chunk_duration_s,
            n_threads,
            &mut out_spans,
        )
    };
    if n < 0 {
        return Err(format!("crispasr_vad_slices failed (rc={n})"));
    }
    let mut spans = Vec::with_capacity(n as usize);
    for i in 0..n as isize {
        unsafe {
            spans.push((*out_spans.offset(2 * i), *out_spans.offset(2 * i + 1)));
        }
    }
    if n > 0 {
        unsafe { crispasr_sys::crispasr_vad_free(out_spans) };
    }
    Ok(spans)
}

/// RNNoise audio enhancement on 48 kHz mono PCM.
pub fn enhance_audio_rnnoise(pcm: &[f32]) -> Result<Vec<f32>, String> {
    let mut out = vec![0f32; pcm.len()];
    let rc = unsafe {
        crispasr_sys::crispasr_enhance_audio_rnnoise(
            pcm.as_ptr(),
            pcm.len() as i32,
            out.as_mut_ptr(),
            out.len() as i32,
        )
    };
    if rc != 0 {
        return Err(format!("enhance_audio_rnnoise failed (rc={rc})"));
    }
    Ok(out)
}

/// TitaNet cosine similarity between two embeddings.
pub fn titanet_cosine_sim(a: &[f32], b: &[f32]) -> f32 {
    let dim = a.len().min(b.len()) as i32;
    unsafe { crispasr_sys::crispasr_titanet_cosine_sim(a.as_ptr(), b.as_ptr(), dim) }
}

/// Speaker database wrapper.
pub struct SpeakerDB {
    handle: *mut std::ffi::c_void,
    dir_path: String,
}

unsafe impl Send for SpeakerDB {}

impl SpeakerDB {
    pub fn load(dir_path: &str) -> Result<Self, String> {
        let c_path = CString::new(dir_path).map_err(|e| e.to_string())?;
        let handle = unsafe { crispasr_sys::crispasr_speaker_db_load(c_path.as_ptr()) };
        if handle.is_null() {
            return Err(format!("Failed to load speaker DB: {dir_path}"));
        }
        Ok(Self {
            handle,
            dir_path: dir_path.to_string(),
        })
    }

    pub fn count(&self) -> i32 {
        unsafe { crispasr_sys::crispasr_speaker_db_count(self.handle) }
    }

    pub fn match_embedding(&self, embedding: &[f32], threshold: f32) -> (Option<String>, f32) {
        let mut name_buf = vec![0u8; 256];
        let score = unsafe {
            crispasr_sys::crispasr_speaker_db_match(
                self.handle,
                embedding.as_ptr(),
                embedding.len() as i32,
                threshold,
                name_buf.as_mut_ptr() as *mut c_char,
                256,
            )
        };
        let name = if score >= threshold {
            let c_str = unsafe { CStr::from_ptr(name_buf.as_ptr() as *const c_char) };
            Some(c_str.to_string_lossy().into_owned())
        } else {
            None
        };
        (name, score)
    }

    pub fn enroll(&self, name: &str, embedding: &[f32]) -> Result<(), String> {
        let c_dir = CString::new(&*self.dir_path).map_err(|e| e.to_string())?;
        let c_name = CString::new(name).map_err(|e| e.to_string())?;
        let rc = unsafe {
            crispasr_sys::crispasr_speaker_db_enroll(
                c_dir.as_ptr(),
                c_name.as_ptr(),
                embedding.as_ptr(),
                embedding.len() as i32,
            )
        };
        if rc != 0 {
            return Err(format!("speaker_db_enroll failed (rc={rc})"));
        }
        Ok(())
    }
}

impl Drop for SpeakerDB {
    fn drop(&mut self) {
        if !self.handle.is_null() {
            unsafe { crispasr_sys::crispasr_speaker_db_free(self.handle) };
            self.handle = std::ptr::null_mut();
        }
    }
}

/// Whether `lang` is German (Kokoro phoneme selection).
pub fn kokoro_lang_is_german(lang: &str) -> bool {
    let c = CString::new(lang).unwrap_or_default();
    unsafe { crispasr_sys::crispasr_kokoro_lang_is_german_abi(c.as_ptr()) }
}

/// Whether `lang` has a native Kokoro voice.
pub fn kokoro_lang_has_native_voice(lang: &str) -> bool {
    let c = CString::new(lang).unwrap_or_default();
    unsafe { crispasr_sys::crispasr_kokoro_lang_has_native_voice_abi(c.as_ptr()) }
}