coremlit 0.1.0

Safe, synchronous CoreML runtime for macOS (CPU/GPU/Neural Engine) with opt-in on-device multimodal pipelines: speech (Whisper STT, forced alignment, speaker diarization, Silero VAD), AudioSet sound-event tagging, and audio/text/image embeddings (CLAP, granite, SigLIP)
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
//! Configuration types for the WhisperKit pipeline (spec §5.3, §6.2): the
//! 27-knob decode-time surface Swift exposes, plus one Rust-only
//! reproducibility addition ([`DecodingOptions`]), per-stage compute unit
//! selection ([`ComputeOptions`]), and construction config ([`Options`]).
//! Ports `Configurations.swift` `DecodingOptions`/`WhisperKitConfig` and
//! `Models.swift` `DecodingTask`/`ChunkingStrategy`/`ModelComputeOptions`.
//!
//! Reference implementation of rust-options-pattern for this workspace:
//! `DEFAULT_*` consts are the single source of truth; `new()` is `const`
//! and returns the defaults; `Default` delegates to `new()`; every knob has
//! a projected `#[inline(always)]` accessor plus `with_*`/`set_*`, and
//! `Option`/`bool` knobs get the full `set_`/`with_`/`update_`/`maybe_`/
//! `clear_` vocabulary. Every field falls back to its true default on a
//! partial `serde` config — including fields whose default isn't the field
//! type's own `Default` (`NonZeroUsize` has none at all; the four
//! thresholds default `Some(_)`; `ComputeOptions`'s per-stage defaults
//! aren't `ComputeUnits::default()`), which is exactly why those fields use
//! `serde(default = "fn")` rather than the bare form.
//!
//! # The `serde` round trip is lossless, and that is a load-bearing property
//!
//! Every value survives `serialize` -> `deserialize` unchanged, so a
//! serialized [`DecodingOptions`] **reconstructs the exact configuration a
//! run used**. That is what lets [`crate::audio::whisper::provenance::Provenance`] embed one
//! wholesale and still be an honest record of what produced a transcript
//! (coremlit issue #14).
//!
//! Losslessness has a floating-point edge case, and this module closes it
//! (codex round 3, F6): `serde_json` has no JSON form for `NaN` or ±∞ and
//! silently writes each as `null`, so a `Some(-inf)` threshold would read back
//! `None` — a check that fired on every finite value **silently disabled**
//! across a round trip. Every `f32`-bearing knob here is therefore bridged
//! through the `finite_f32`/`finite_f32_option`/`finite_f32_vec` helpers, which
//! refuse a non-finite value on *both* sides of the boundary rather than let it
//! round-trip to a different meaning. This matches Swift, whose
//! `DecodingOptions: Codable` (`Configurations.swift:155`) encodes through the
//! default `JSONEncoder` and so throws on a non-finite field: the value is
//! rejected at the wire, exactly where Swift rejects it, and not at
//! construction — Swift's initializer stores it without complaint, and so do
//! these `const` builders.
//!
//! Losslessness is why the **four `Option<f32>` thresholds**
//! ([`DecodingOptions::compression_ratio_threshold`],
//! [`DecodingOptions::logprob_threshold`],
//! [`DecodingOptions::first_token_logprob_threshold`],
//! [`DecodingOptions::no_speech_threshold`]) are the one place this module
//! *does* emit `null`. They are the only fields whose default is `Some(_)`
//! rather than `None`, so for them — and only for them — "absent" and
//! "`None`" mean different things: absent is "the caller did not configure
//! this knob", which resolves to the default `Some(_)`; `None` is "the
//! caller explicitly DISABLED this check". `skip_serializing_if` would
//! collapse the second into the first, and a disabled threshold would read
//! back **re-enabled at its default** — silently restoring a check the run
//! did not perform. `null` keeps the two apart, and a partial config that
//! simply omits the key still gets its true default.
//!
//! Every other `Option`/collection field defaults to `None`/empty, so for
//! those absent *is* the value and `skip_serializing_if` stays: an unset
//! [`DecodingOptions::seed`] is absent, never a `null`.

use std::{
  num::NonZeroUsize,
  path::{Path, PathBuf},
};

use crate::ComputeUnits;

use crate::audio::whisper::constants::MAX_TOKEN_CONTEXT;

// ---------------------------------------------------------------------
// Task
// ---------------------------------------------------------------------

/// Which Whisper decode task to run (Swift `DecodingTask`).
#[derive(
  Debug, Default, Clone, Copy, PartialEq, Eq, Hash, derive_more::Display, derive_more::IsVariant,
)]
#[display("{}", self.as_str())]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum Task {
  /// Transcribe speech in its spoken language.
  #[default]
  Transcribe,
  /// Translate speech to English.
  Translate,
}

impl Task {
  /// Stable snake_case name of the variant.
  #[inline(always)]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::Transcribe => "transcribe",
      Self::Translate => "translate",
    }
  }
}

/// Error parsing a [`Task`] name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("unknown task name")]
pub struct ParseTaskError(());

impl core::str::FromStr for Task {
  type Err = ParseTaskError;

  fn from_str(s: &str) -> Result<Self, Self::Err> {
    Ok(match s {
      "transcribe" => Self::Transcribe,
      "translate" => Self::Translate,
      _ => return Err(ParseTaskError(())),
    })
  }
}

// ---------------------------------------------------------------------
// ChunkingStrategy
// ---------------------------------------------------------------------

/// How long-form audio is split into chunks before transcription (Swift
/// `ChunkingStrategy`). Swift's `.none` case is renamed `Disabled` here — a
/// variant literally named `None` reads badly next to `Option::None` — but
/// keeps the wire name `"none"` for parity (spec §6.1).
#[derive(
  Debug, Default, Clone, Copy, PartialEq, Eq, Hash, derive_more::Display, derive_more::IsVariant,
)]
#[display("{}", self.as_str())]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum ChunkingStrategy {
  /// No chunking: the whole input is windowed and decoded sequentially.
  #[default]
  #[cfg_attr(feature = "serde", serde(rename = "none"))]
  Disabled,
  /// Split at VAD (voice activity detection) silence boundaries.
  Vad,
}

impl ChunkingStrategy {
  /// Stable wire name of the variant (`"none"`/`"vad"`).
  #[inline(always)]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::Disabled => "none",
      Self::Vad => "vad",
    }
  }
}

/// Error parsing a [`ChunkingStrategy`] name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("unknown chunking strategy name")]
pub struct ParseChunkingStrategyError(());

impl core::str::FromStr for ChunkingStrategy {
  type Err = ParseChunkingStrategyError;

  fn from_str(s: &str) -> Result<Self, Self::Err> {
    Ok(match s {
      "none" => Self::Disabled,
      "vad" => Self::Vad,
      _ => return Err(ParseChunkingStrategyError(())),
    })
  }
}

// ---------------------------------------------------------------------
// WordGrouping
// ---------------------------------------------------------------------

/// How decoded tokens are grouped into "words" for word-level timestamps
/// (coremlit issue #14). Rust-only: Swift has no such switch — it picks the
/// strategy from a language it detects internally, which is precisely the
/// hidden second language decision that caused the original divergence
/// (issue #9), so this port makes the choice explicit instead.
///
/// This only affects **word grouping**. It is orthogonal to the optional
/// `nl-recognizer` feature, which is about *which language code* reaches
/// the splitter, not about how that splitter then groups.
///
/// # What Swift actually does, and why the two variants differ at all
///
/// Swift's `splitToWordTokens` (`Models.swift:1293-1305`) takes the
/// Unicode-splitting arm exactly when
/// `NLLanguageRecognizer.dominantLanguage?.rawValue` is one of
/// `["zh", "ja", "th", "lo", "my", "yue"]`, and the space-splitting arm
/// otherwise. The list looks like "all of CJK" — but the values it is
/// matched against are Apple's `NLLanguage` raw values, and those do not
/// line up with it:
///
/// | language | `NLLanguage` raw value | in Swift's list? | Swift's arm |
/// |---|---|---|---|
/// | Japanese | `ja` | yes | **Unicode** |
/// | Thai | `th` | yes | **Unicode** |
/// | Lao | `lo` | yes | **Unicode** |
/// | Burmese | `my` | yes | **Unicode** |
/// | Chinese | `zh-Hans` / `zh-Hant` | **no** | space |
/// | Cantonese | *(no `NLLanguage` case; recognized as Chinese)* | **no** | space |
///
/// So the coarse "phrase blob" grouping is a **Chinese-only** accident —
/// Chinese is the one language whose `NLLanguage` raw value is *regional*,
/// so it alone falls through a check written for bare codes. Swift
/// fine-grains Japanese, Thai, Lao and Burmese exactly as this port's
/// default does.
///
/// The two variants below therefore differ **only for `zh` and `yue`**. For
/// every other language, including `ja`, they are the same splitter — which
/// is the honest shape, because for every other language Swift and this port
/// already agree.
#[derive(
  Debug, Default, Clone, Copy, PartialEq, Eq, Hash, derive_more::Display, derive_more::IsVariant,
)]
#[display("{}", self.as_str())]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum WordGrouping {
  /// Unicode splitting for every language that is not whitespace-delimited
  /// (`zh`/`ja`/`th`/`lo`/`my`/`yue`), and ordinary space/punctuation
  /// splitting for the rest. **The product-quality opt-in for fine-grained
  /// CJK word timestamps** (coremlit issue #11), and this port's long-standing
  /// behavior — but no longer the default: [`Self::SwiftParity`] became the
  /// default in #41 for stream parity with Swift.
  ///
  /// "Unicode splitting" means the **smallest group of BPE tokens that
  /// completes a Unicode scalar** — not one word per scalar. Whisper's BPE
  /// merges common multi-character sequences into single tokens, so `今天`
  /// arrives as one token and stays one unit, while a character split across
  /// a token boundary is merged back together (that is the only merging
  /// `split_tokens_on_unicode` does). Groups are therefore *token*-shaped and
  /// vary in length; the guarantee is that they are fine-grained and never
  /// contain a broken scalar, not that they are one-per-character.
  ///
  /// This is the product-correct grouping for CJK: those scripts do not
  /// separate words with spaces, so space splitting collapses a whole
  /// utterance into one undifferentiated blob with a single start/end time,
  /// and word timestamps stop meaning anything. Test-pinned in coremlit issue
  /// #11: 85 fine-grained words on the ZH clip, against Swift's 24 blobs.
  FineGrained,
  /// Swift WhisperKit's own grouping, reproduced deliberately: the space
  /// splitter for `zh` and `yue`, and the same Unicode splitting as
  /// [`Self::FineGrained`] everywhere else — `ja`, `th`, `lo` and `my`
  /// included.
  ///
  /// **The default** (coremlit issue #41 — stream parity with Swift as the
  /// default posture; reverses the issue-#11 pin, user-approved). For Chinese
  /// it produces the coarse phrase blob Swift lands on by accident (see the
  /// type's own doc — `NLLanguageRecognizer` answers `zh-Hant`/`zh-Hans`,
  /// which Swift's bare-code CJK check then fails to match), a single
  /// start/end time for an entire utterance; a caller who wants fine-grained
  /// CJK word timestamps instead opts into [`Self::FineGrained`], which is
  /// exactly why that variant still exists.
  ///
  /// **This is not "space-split everything".** An earlier shape of this
  /// variant forced the space splitter for *all* CJK and documented itself as
  /// Swift-parity; it was neither. Swift Unicode-splits Japanese — its own
  /// test pins the twelve groups (`Tests/WhisperKitTests/UnitTests.swift:
  /// 1360-1375`, ported verbatim as `tokenizer::tests`'
  /// `swift_parity_matches_swifts_pinned_japanese_word_tokens`) — so forcing
  /// spaces there diverged from Swift under the very name that promised
  /// parity with it.
  ///
  /// Parity is conditional on the language code, as everywhere else in this
  /// port: Swift reads its code from `NLLanguageRecognizer` over the decoded
  /// text, while this crate passes the decoder's own `<|lang|>` token (spec
  /// §5.3). Where the two identify the same base language, this variant's
  /// grouping is Swift's. A caller who wants Swift's *language signal* too
  /// can enable the `nl-recognizer` feature and pass
  /// `tokenizer::nl_recognizer::redetect_language`'s result — it normalizes
  /// `zh-Hant`/`zh-Hans` to a bare `zh`, which this variant then
  /// space-splits, exactly as Swift does with the regional code.
  #[default]
  SwiftParity,
}

impl WordGrouping {
  /// Stable snake_case name of the variant.
  #[inline(always)]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::FineGrained => "fine_grained",
      Self::SwiftParity => "swift_parity",
    }
  }
}

/// Error parsing a [`WordGrouping`] name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("unknown word grouping name")]
pub struct ParseWordGroupingError(());

impl core::str::FromStr for WordGrouping {
  type Err = ParseWordGroupingError;

  fn from_str(s: &str) -> Result<Self, Self::Err> {
    Ok(match s {
      "fine_grained" => Self::FineGrained,
      "swift_parity" => Self::SwiftParity,
      _ => return Err(ParseWordGroupingError(())),
    })
  }
}

// ---------------------------------------------------------------------
// AlignmentGather
// ---------------------------------------------------------------------

/// How a window's per-token cross-attention rows are gathered into the
/// matrix DTW runs over (coremlit issue #41). Rust-only: Swift has no such
/// switch — it has exactly one gather, and that gather silently drops the
/// tail of its final row.
///
/// **[`Self::Complete`] is the default; [`Self::SwiftParity`] is an opt-in
/// that fails closed.** `Complete` is the numerically correct gather and has
/// no platform dependency at all. `SwiftParity` reproduces a Swift defect
/// whose behavior rests on unspecified CoreVideo layout, so it carries three
/// stated assumptions (A1–A3, enumerated on that variant) and refuses
/// outright on any layout it cannot describe. Correct everywhere by default;
/// bit-parity for callers who explicitly ask and accept the constraint.
///
/// # What Swift actually does, and why the two variants differ at all
///
/// `SegmentSeeker.addWordTimestamps` (`SegmentSeeker.swift:444-461`) copies
/// the gathered rows by hand. It binds both arrays' stride vectors
/// (`weightsStride`/`filteredWeightsStride`) and then ignores them, using
/// `columnCount` — the *logical* column count, 1500 for a 30 s window — as
/// the row pitch on the source and on the destination alike. That is correct
/// only while storage pitch equals column count, and for WhisperKit's
/// Float16 arrays it does not: every one of them is allocated through
/// `MLMultiArray(shape:dataType:initialValue:)`
/// (`ArgmaxCore/MLMultiArrayExtensions.swift:11-53`), which for `.float16`
/// backs the array with an IOSurface `CVPixelBuffer` (`:121-136`,
/// `kCVPixelFormatType_OneComponent16Half`), and CoreVideo pads every row out
/// to a **platform-chosen** boundary. (The plain `MLMultiArray(shape:dataType:)`
/// initializer is contiguous; the padding belongs to the pixel-buffer path,
/// and the pixel-buffer path is the one WhisperKit takes.)
///
/// How much padding is a property of the host, not of this code: Apple's
/// QA1829 states `CVPixelBuffer` row alignment varies by hardware and must be
/// queried, and [`MultiArray::f16_surface`](crate::MultiArray::f16_surface)
/// documents the same. So this port **measures** it at run time, allocating
/// the identical Float16 surfaces Swift's gather allocates and reading back
/// CoreVideo's own strides (`segment::coreml_f16_row_pitch`); nothing below
/// is compiled in. There are TWO such surfaces and they are probed
/// separately — the once-allocated `[max_token_context + 1, cols]` source
/// (`TextDecoder.swift:141`) and the per-call `[N, cols]` destination
/// (`SegmentSeeker.swift:450`) — because "the pitch does not depend on the
/// row count" is something this host was measured to do, not something
/// CoreVideo promises. On the reference host for whisper #41 (M1 Max, macOS
/// 26.5) rows align to 64 bytes — 32 Float16 elements — so `cols = 1500` is
/// stored at a pitch of 1504 at every height, and that is the layout every
/// worked example here uses.
///
/// Two errors follow:
///
/// 1. Swift's `filteredIndices` are `0..<N` by construction, so both sides'
///    offsets are `index * columnCount` and the copies tile contiguously:
///    destination STORAGE offset `o` ends up holding source STORAGE offset
///    `o`, for every `o < N * cols`. (Contiguous *storage* offsets — the
///    logical rows they land on depend on each surface's own pitch.)
/// 2. `dynamicTimeWarping` then reads `matrix[(row - 1) * numberOfColumns +
///    (column - 1)]` (`SegmentSeeker.swift:217`) through `MLMultiArray`'s
///    flat subscript, which *is* stride-aware — so logical row `r` reads
///    destination storage `[r * dst_pitch, r * dst_pitch + cols)`.
///
/// **When the two pitches agree** the errors annihilate wherever that read
/// window still lies inside the copied prefix, and the gather reduces to a
/// truncation: row `r` is cut exactly when `r * pitch + cols > N * cols`,
/// overrunning into destination storage the `initialValue:` fill never
/// covered either — that fill covers only the logical `count`. Per row:
///
/// ```text
/// kept = min(cols, N * cols - r * pitch)   // saturating at 0
/// ```
///
/// Only the LAST row can be affected while `cols >= (N - 2) * (pitch - cols)`.
/// That is a property of the shipping shape and the reference host's pitch,
/// not a general one: it holds for every real Whisper model (`cols =
/// n_audio_ctx = 1500`, measured `pitch = 1504`, `N <= 224`, so reaching the
/// second-to-last row would take `N > 377`), and fails at the small
/// `n_audio_ctx` a test backend can configure, where a run of whole rows goes
/// — hence the general per-row form above rather than a last-row special
/// case. At `N = 120`, `cols = 1500`, `pitch = 1504` the final row keeps 1024
/// columns and reads the remaining 476 out of storage nothing ever wrote.
///
/// **When they disagree** it is not a truncation at all: row `r` reads a
/// SHIFTED window of the source, splicing the tail of one logical row onto
/// the head of the next across the source's own (zero) padding. `segment::
/// gather_swift_rows` reproduces that general mapping rather than the
/// equal-pitch special case, so a host whose CoreVideo pitches the two
/// heights differently gets Swift's actual DTW input instead of a silently
/// wrong "parity".
///
/// Every measured number above is probed — see
/// `probe_alignment_stride.swift`/`.out` under
/// `coremlit/tests/whisper_swift_probes/`. A host whose CoreVideo does
/// not pad `cols` at all measures `pitch == cols` for both surfaces, which
/// makes [`Self::SwiftParity`] identical to [`Self::Complete`] there —
/// correctly, because Swift's gather then has nothing to disturb either.
#[derive(
  Debug, Default, Clone, Copy, PartialEq, Eq, Hash, derive_more::Display, derive_more::IsVariant,
)]
#[display("{}", self.as_str())]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
pub enum AlignmentGather {
  /// Swift's gather reproduced deliberately, truncated final row and all
  /// (`kept` columns per the type's own doc — 1024 of 1500 on a full
  /// 120-token window at the reference host's measured pitch, the rest
  /// zero).
  ///
  /// **Opt-in, and it fails closed.** That one row's tail is an input to the
  /// DTW path, and the path is what the last word's end — and through it the
  /// segment's end, and the **next window's seek** — is read off. Being an
  /// input is not the same as moving the output; where it does move, it
  /// **can** compound across windows, so a gather that keeps the row in full
  /// can be "more correct" and still put the pipeline on windows Swift never
  /// used. That is what the long-form measurement found: against official
  /// Swift on the pinned model, the 1417 s fixture cost 984 words of edit
  /// distance and an entire extra window (52 against Swift's 51) under
  /// [`Self::Complete`], and matched token-for-token under this variant. That
  /// is what this variant is for, and the only thing it is for.
  ///
  /// # The three assumptions this mode carries
  ///
  /// Reproducing a defect whose behavior rests on unspecified CoreVideo
  /// layout means reproducing its unspecified parts too. Three of them are
  /// **assumed, not established**, and none of them is contractual. They are
  /// listed here rather than buried because opting in means accepting them.
  ///
  /// **A1 — layout determinism.** The pitches are measured by allocating the
  /// same Float16 IOSurface Swift's gather allocates and reading CoreVideo's
  /// strides back (`segment::coreml_f16_row_pitch`). That establishes the
  /// pitch of *this port's* allocation. Nothing in CoreVideo promises two
  /// allocations of one shape share a layout, and Swift's allocation lives in
  /// another process this port cannot observe. *Would settle it:* a published
  /// guarantee that row alignment is a pure function of pixel format and
  /// dimensions. Apple's QA1829 requires the value to be queried per buffer,
  /// which is the opposite posture.
  ///
  /// **A2 — fresh-allocation zero fill.** `dynamicTimeWarping` reads
  /// destination storage past the gather's copied prefix; Swift's
  /// `initialValue: FloatType(0)` fill covers only the logical `count` and
  /// the `memcpy` covers only that same prefix, so those cells are whatever
  /// `CVPixelBufferCreate` returned. This mode substitutes **zero**. No part
  /// of CoreVideo promises a fresh IOSurface-backed buffer is zeroed —
  /// `IOSurfaceSetPurgeable(kIOSurfacePurgeableEmpty)` explicitly makes
  /// contents undefined, which is hard to reconcile with an implicit
  /// always-zero guarantee. A previous revision claimed to *verify* this by
  /// sampling a freshly allocated surface's tail; that was wrong twice over —
  /// reading those bytes was undefined behavior, and one clean allocation
  /// says nothing about a different, possibly reused one. Both the reading
  /// and the claim are gone. *Would settle it:* a documented IOSurface/
  /// CoreVideo initialization guarantee, or an in-process handle on the
  /// exact allocation Swift gathered into — neither exists.
  ///
  /// **A3 — layout stability across mutable access.** The reproduction reads
  /// the source array's inter-row padding as zero. Construction does zero it
  /// (the `initialValue:` fill runs over the LOGICAL count, flat, so storage
  /// `[0, src_rows * cols)` starts zero, padding included) and its only
  /// writer, `TextDecoder.updateAlignmentWeights` (`:272-295`), is
  /// stride-aware. But writer and gather both reach the array through
  /// `withUnsafeMutableBytes`, whose contract states the strides handed to
  /// the closure may differ from the value before invocation — so no cited
  /// contract rules out a relayout or a replacement of the backing storage
  /// introducing padding that construction never zeroed. *Would settle it:* a
  /// lifecycle-equivalent native probe at the exact 224-row source height —
  /// repeated stride-aware writes, then a gather-style access, recording the
  /// closure strides and the gather-reachable padding each time — and even
  /// that would be one host's observation, not a contract.
  ///
  /// **Consequence.** This variant claims parity **only where A1–A3 hold**.
  /// It does not detect their violation; where the layout is one this port
  /// cannot describe at all it refuses outright
  /// ([`SegmentError::AlignmentPitchUnavailable`](crate::audio::whisper::error::SegmentError::AlignmentPitchUnavailable),
  /// [`AlignmentPitchUnexpectedLayout`](crate::audio::whisper::error::SegmentError::AlignmentPitchUnexpectedLayout))
  /// rather than guessing. On a host whose CoreVideo does not pad at all,
  /// A2 and A3 are vacuous and this variant equals [`Self::Complete`].
  ///
  /// # Short-form
  ///
  /// The gather runs on **every** word-timestamp window, with no long-form
  /// guard and no subsequent-window guard (Swift has none either, so a guard
  /// would itself be a deviation), and the truncation is real on a single
  /// window: on jfk/tiny, 30 gathered rows over 1500 columns at the measured
  /// pitch of 1504 leave the final row keeping 1384 of them.
  ///
  /// **Established.** On `jfk.wav` / `openai_whisper-tiny`, under the pinned
  /// oracle options, this variant and [`Self::Complete`] produce the same 22
  /// words, and that list matches official Swift exactly — text, start, end,
  /// probability and token ids, no epsilon — as do the segment seeks and
  /// bounds. The integration test
  /// `jfk_tiny_word_timestamps_match_swift_and_this_clip_is_gather_invariant`
  /// (`coremlit/tests/whisper/parity_jfk.rs`) pins both halves.
  ///
  /// **Not established: that short-form output is invariant in general.** It
  /// is not, and a previous revision of this doc said it was. Gather
  /// selection can move a word's end — and with it the segment's end —
  /// **inside a single window**, which this branch's own fixtures measure.
  /// Over ONE `add_word_timestamps` call, with no seek, no second window and
  /// no cascade of any kind, the last word's end and the segment's end come
  /// out **0.88 s under [`Self::Complete`] against 1.58 s under this
  /// variant**
  /// (`segment::tests::swift_parity_gather_truncates_final_alignment_row`).
  /// End to end, a run diverges in its **first** window — same audio, same
  /// decoded script, `seek` 0 under both — at **0.88 s against 1.18 s**,
  /// which is what then places window 2 at a different sample offset
  /// (`transcribe::tests`'
  /// `swift_parity_gather_moves_the_first_windows_end_and_the_next_seek`).
  /// Both fixtures drive constructed alignment matrices rather than a real
  /// decode's, so neither says that some particular clip diverges; what they
  /// establish is that nothing about a short clip exempts it. **A caller who
  /// changes this knob for a short clip can receive different word and
  /// segment timestamps.**
  ///
  /// *Would settle it:* Swift-oracle word goldens over a corpus — several
  /// clips, models and window occupancies — characterizing when a real
  /// decode's DTW path is sensitive to the truncated tail. One clip's
  /// insensitivity is one clip's, and the mechanism predicts no other.
  /// Until that exists, the supportable reading is that the two variants may
  /// differ on any word-timestamp window, and jfk/tiny is the one where they
  /// are measured not to.
  SwiftParity,
  /// Gather every row in full — no truncation.
  ///
  /// **The default.** It is the numerically correct gather: it feeds DTW
  /// everything the model actually produced, which is what the code appears
  /// to promise and what a caller who wants this port's best word timings
  /// should get without asking.
  ///
  /// Just as decisively, it is the gather with **nothing to assume**. It
  /// allocates no IOSurface, measures no row pitch, inspects no storage past
  /// what it wrote, and executes no `unsafe`; none of A1–A3 on
  /// [`Self::SwiftParity`] applies to it, and no property of the host can
  /// move its output. A default whose behavior depends on unspecified
  /// CoreVideo layout is a defect surface for every caller, including every
  /// caller who never heard of this knob — and three review rounds each
  /// uncovered a further unspecified layer under the previous one. So the
  /// correct-everywhere gather is what a caller gets by default, and
  /// bit-parity with a Swift defect is what a caller opts into, having
  /// accepted the constraint.
  ///
  /// It does **not reproduce Swift's gather**: it measures no row pitch and
  /// truncates nothing. That is unconditional, and it is a claim about the
  /// algorithm rather than about the output — so this variant is **not
  /// guaranteed** to track Swift's output, and where it has been measured
  /// against official Swift it has gone both ways. On the 1417 s long-form
  /// fixture it diverged: 984 words of edit distance and an extra window (see
  /// [`Self::SwiftParity`] for those numbers). On `jfk.wav` /
  /// `openai_whisper-tiny`, under the pinned oracle options, it matched
  /// official Swift word for word, exactly as [`Self::SwiftParity`] did. Each
  /// result is that fixture's and that model's, not a rule for long or short
  /// audio generally; short form carries no exemption either, and that
  /// variant's "Short-form" section states what is and is not established
  /// there. On a host whose CoreVideo does not pad, the two variants are one
  /// gather and the question does not arise.
  #[default]
  Complete,
}

impl AlignmentGather {
  /// Stable snake_case name of the variant.
  #[inline(always)]
  pub const fn as_str(&self) -> &'static str {
    match self {
      Self::SwiftParity => "swift_parity",
      Self::Complete => "complete",
    }
  }
}

/// Error parsing an [`AlignmentGather`] name.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("unknown alignment gather name")]
pub struct ParseAlignmentGatherError(());

impl core::str::FromStr for AlignmentGather {
  type Err = ParseAlignmentGatherError;

  fn from_str(s: &str) -> Result<Self, Self::Err> {
    Ok(match s {
      "swift_parity" => Self::SwiftParity,
      "complete" => Self::Complete,
      _ => return Err(ParseAlignmentGatherError(())),
    })
  }
}

// ---------------------------------------------------------------------
// DecodingOptions
// ---------------------------------------------------------------------

/// Default [`DecodingOptions::temperature`] (greedy/argmax decoding).
pub const DEFAULT_TEMPERATURE: f32 = 0.0;
/// Default [`DecodingOptions::temperature_increment_on_fallback`].
pub const DEFAULT_TEMPERATURE_INCREMENT_ON_FALLBACK: f32 = 0.2;
/// Default [`DecodingOptions::temperature_fallback_count`].
pub const DEFAULT_TEMPERATURE_FALLBACK_COUNT: usize = 5;
/// Default [`DecodingOptions::sample_length`] (Whisper's `448 / 2` token context).
pub const DEFAULT_SAMPLE_LENGTH: usize = MAX_TOKEN_CONTEXT;
/// Default [`DecodingOptions::top_k`].
pub const DEFAULT_TOP_K: usize = 5;
/// Default [`DecodingOptions::window_clip_time`], in seconds.
pub const DEFAULT_WINDOW_CLIP_TIME: f32 = 1.0;
/// Default [`DecodingOptions::compression_ratio_threshold`].
pub const DEFAULT_COMPRESSION_RATIO_THRESHOLD: f32 = 2.4;
/// Default [`DecodingOptions::logprob_threshold`].
pub const DEFAULT_LOGPROB_THRESHOLD: f32 = -1.0;
/// Default [`DecodingOptions::first_token_logprob_threshold`].
pub const DEFAULT_FIRST_TOKEN_LOGPROB_THRESHOLD: f32 = -1.5;
/// Default [`DecodingOptions::no_speech_threshold`].
pub const DEFAULT_NO_SPEECH_THRESHOLD: f32 = 0.6;
/// Default [`DecodingOptions::use_prefill_prompt`].
pub const DEFAULT_USE_PREFILL_PROMPT: bool = true;
/// Default [`DecodingOptions::drop_blank_audio`] — blank-audio segments are
/// dropped unless the caller opts back into emitting them.
pub const DEFAULT_DROP_BLANK_AUDIO: bool = true;
/// Default [`DecodingOptions::concurrent_worker_count`] (Swift's macOS default).
pub const DEFAULT_CONCURRENT_WORKER_COUNT: NonZeroUsize = NonZeroUsize::new(16).unwrap();

#[cfg(feature = "serde")]
fn default_temperature_increment_on_fallback() -> f32 {
  DEFAULT_TEMPERATURE_INCREMENT_ON_FALLBACK
}
#[cfg(feature = "serde")]
fn default_temperature_fallback_count() -> usize {
  DEFAULT_TEMPERATURE_FALLBACK_COUNT
}
#[cfg(feature = "serde")]
fn default_sample_length() -> usize {
  DEFAULT_SAMPLE_LENGTH
}
#[cfg(feature = "serde")]
fn default_top_k() -> usize {
  DEFAULT_TOP_K
}
#[cfg(feature = "serde")]
fn default_window_clip_time() -> f32 {
  DEFAULT_WINDOW_CLIP_TIME
}
#[cfg(feature = "serde")]
fn default_concurrent_worker_count() -> NonZeroUsize {
  DEFAULT_CONCURRENT_WORKER_COUNT
}
#[cfg(feature = "serde")]
fn default_compression_ratio_threshold() -> Option<f32> {
  Some(DEFAULT_COMPRESSION_RATIO_THRESHOLD)
}
#[cfg(feature = "serde")]
fn default_logprob_threshold() -> Option<f32> {
  Some(DEFAULT_LOGPROB_THRESHOLD)
}
#[cfg(feature = "serde")]
fn default_first_token_logprob_threshold() -> Option<f32> {
  Some(DEFAULT_FIRST_TOKEN_LOGPROB_THRESHOLD)
}
#[cfg(feature = "serde")]
fn default_no_speech_threshold() -> Option<f32> {
  Some(DEFAULT_NO_SPEECH_THRESHOLD)
}
// `bool::default()` is `false`; `use_prefill_prompt` defaults `true`
// (Swift `usePrefillPrompt = true`), so it needs a fn-default too.
#[cfg(feature = "serde")]
fn default_use_prefill_prompt() -> bool {
  DEFAULT_USE_PREFILL_PROMPT
}
// `drop_blank_audio` likewise defaults `true`, against `bool::default()`'s
// `false` — a config that omits the field must still DROP, not emit.
#[cfg(feature = "serde")]
fn default_drop_blank_audio() -> bool {
  DEFAULT_DROP_BLANK_AUDIO
}

// ---------------------------------------------------------------------
// Non-finite float rejection at the serde boundary (codex round 3, F6)
// ---------------------------------------------------------------------

/// The error a non-finite `f32` raises on either side of the `serde` boundary,
/// shared by the `finite_f32*` helpers below.
#[cfg(feature = "serde")]
pub(crate) const NON_FINITE_FLOAT_MSG: &str = "non-finite float (NaN or infinity) is not \
  representable in JSON and is rejected to keep the serde round trip lossless (matches Swift's \
  JSONEncoder, which throws on non-finite by default)";

/// `serde` bridge for a scalar `f32` that must round-trip losslessly (codex
/// round 3, F6).
///
/// `serde_json` has no JSON form for `NaN`/±∞ and silently writes `null` for
/// each; a `Some(-inf)` `Option<f32>` then reads back `None`, silently
/// disabling a check that fired on every finite value. Swift refuses the same
/// values from the other direction — `DecodingOptions: Codable`
/// (`Configurations.swift:155`) with the default `JSONEncoder`, whose
/// `nonConformingFloatEncodingStrategy` is `.throw`. This helper matches Swift:
/// a non-finite value is refused on serialize (so the lossy `null` is never
/// produced) and on deserialize (so a non-finite literal is never accepted),
/// while a genuine `None` still writes `null` and reads back `None`. In-memory
/// construction is deliberately NOT guarded — Swift's initializer also stores a
/// non-finite value and only its encoder throws (`Configurations.swift:212`).
#[cfg(feature = "serde")]
pub(crate) mod finite_f32 {
  use serde::{Deserialize, Deserializer, Serialize, Serializer};

  pub(crate) fn serialize<S: Serializer>(value: &f32, serializer: S) -> Result<S::Ok, S::Error> {
    if !value.is_finite() {
      return Err(serde::ser::Error::custom(super::NON_FINITE_FLOAT_MSG));
    }
    value.serialize(serializer)
  }

  pub(crate) fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<f32, D::Error> {
    let value = f32::deserialize(deserializer)?;
    if !value.is_finite() {
      return Err(serde::de::Error::custom(super::NON_FINITE_FLOAT_MSG));
    }
    Ok(value)
  }
}

/// `serde` bridge for an `Option<f32>` that must round-trip losslessly: a
/// finite `Some` and a `None` (written `null`) survive, and a non-finite `Some`
/// is refused. Same rationale as `finite_f32`. Composes both with
/// `serde(default = …)` (the four `DecodingOptions` thresholds) and with no
/// default at all (a required, nullable field like
/// `provenance::Provenance::effective_temperature`, which stays required
/// because naming a `with`/`deserialize_with` defeats serde's
/// missing-`Option`-is-`None` special case).
#[cfg(feature = "serde")]
pub(crate) mod finite_f32_option {
  use serde::{Deserialize, Deserializer, Serialize, Serializer};

  pub(crate) fn serialize<S: Serializer>(
    value: &Option<f32>,
    serializer: S,
  ) -> Result<S::Ok, S::Error> {
    if matches!(value, Some(v) if !v.is_finite()) {
      return Err(serde::ser::Error::custom(super::NON_FINITE_FLOAT_MSG));
    }
    value.serialize(serializer)
  }

  pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
    deserializer: D,
  ) -> Result<Option<f32>, D::Error> {
    let value = Option::<f32>::deserialize(deserializer)?;
    if matches!(value, Some(v) if !v.is_finite()) {
      return Err(serde::de::Error::custom(super::NON_FINITE_FLOAT_MSG));
    }
    Ok(value)
  }
}

/// `serde` bridge for a `Vec<f32>` that must round-trip losslessly: every
/// element is finite, or the whole value is refused. Same rationale as
/// `finite_f32`.
#[cfg(feature = "serde")]
pub(crate) mod finite_f32_vec {
  use serde::{Deserialize, Deserializer, Serialize, Serializer};

  pub(crate) fn serialize<S: Serializer>(value: &[f32], serializer: S) -> Result<S::Ok, S::Error> {
    if value.iter().any(|v| !v.is_finite()) {
      return Err(serde::ser::Error::custom(super::NON_FINITE_FLOAT_MSG));
    }
    value.serialize(serializer)
  }

  pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
    deserializer: D,
  ) -> Result<Vec<f32>, D::Error> {
    let value = Vec::<f32>::deserialize(deserializer)?;
    if value.iter().any(|v| !v.is_finite()) {
      return Err(serde::de::Error::custom(super::NON_FINITE_FLOAT_MSG));
    }
    Ok(value)
  }
}

/// Decode-time configuration: Swift's 27-knob `DecodingOptions` surface
/// (spec §6.2), plus four Rust-only additions — [`Self::seed`], for
/// reproducible temperature-fallback sampling (coremlit issue #9; see the
/// crate root's "Reproducibility and provenance" docs), from coremlit
/// issue #14 [`Self::drop_blank_audio`] (the post-decode blank-audio
/// segment filter) and [`Self::word_grouping`] (the explicit CJK
/// word-grouping mode), and from coremlit issue #41
/// [`Self::alignment_gather`] (how the per-token alignment rows are gathered
/// before DTW). `new()`/`Default` apply Swift's defaults verbatim for every
/// ported knob; `seed` defaults unset (`None`), matching today's OS-seeded
/// behavior exactly, and `word_grouping` defaults to Swift's own behavior
/// (coremlit issue #41).
///
/// **Exactly TWO knobs' defaults deliberately diverge from Swift, each with an
/// exact-parity escape hatch** — they are the only such deviations; every other
/// default here is Swift's.
///
/// 1. [`Self::drop_blank_audio`] defaults `true`, dropping the `[BLANK_AUDIO]`
///    segments Swift emits (a product decision, with `false` the exact-parity
///    escape hatch).
/// 2. [`Self::alignment_gather`] defaults to [`AlignmentGather::Complete`],
///    which gathers every alignment row in full where Swift's stride-ignoring
///    gather truncates the last one. `Complete` is the numerically correct
///    gather and depends on no property of the host;
///    [`AlignmentGather::SwiftParity`] replicates the truncation — the
///    mechanism behind the long-form divergence of coremlit issue #41 — and is
///    the exact-parity escape hatch, opt-in because its behavior rests on
///    unspecified CoreVideo layout (see that variant's stated assumptions
///    A1–A3). Long-form is where the divergence was *measured*, not where the
///    mechanism is confined: it runs on every word-timestamp window, and can
///    move timestamps within a single short-form one — see that variant's
///    "Short-form" section.
///
/// [`Self::word_grouping`] is NOT one of them: it defaults to
/// [`WordGrouping::SwiftParity`] — Swift's own Chinese/Cantonese
/// space-fallthrough grouping (coremlit issue #41, reversing the #11 pin,
/// user-approved) — while [`WordGrouping::FineGrained`] is the product-quality
/// opt-in that Unicode-splits CJK into fine-grained words. Default options on a
/// Mandarin clip therefore space-split as Swift does; the behavioral contrast
/// between the two variants is pinned by the named invariant
/// `word_grouping_splits_chinese_and_only_chinese` (`tokenizer/tests.rs`). See
/// each field's own doc.
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DecodingOptions {
  /// Which decode task to run.
  #[cfg_attr(feature = "serde", serde(default))]
  task: Task,
  /// Spoken language, as an ISO code (see [`crate::audio::whisper::constants::languages`]).
  /// Empty means auto-detect (golden empty-means-absent).
  #[cfg_attr(
    feature = "serde",
    serde(default, skip_serializing_if = "String::is_empty")
  )]
  language: String,
  /// Sampling temperature; `0.0` is greedy (argmax) decoding.
  #[cfg_attr(feature = "serde", serde(default, with = "finite_f32"))]
  temperature: f32,
  /// Amount added to `temperature` on each fallback retry.
  #[cfg_attr(
    feature = "serde",
    serde(
      default = "default_temperature_increment_on_fallback",
      with = "finite_f32"
    )
  )]
  temperature_increment_on_fallback: f32,
  /// Maximum number of temperature-fallback retries.
  #[cfg_attr(
    feature = "serde",
    serde(default = "default_temperature_fallback_count")
  )]
  temperature_fallback_count: usize,
  /// Maximum number of tokens to sample per window.
  #[cfg_attr(feature = "serde", serde(default = "default_sample_length"))]
  sample_length: usize,
  /// Candidate count for non-zero-temperature sampling.
  #[cfg_attr(feature = "serde", serde(default = "default_top_k"))]
  top_k: usize,
  /// Base seed for reproducible temperature-fallback sampling. `None`
  /// (the default) leaves sampling OS-seeded. See [`Self::seed`] for the
  /// full contract.
  #[cfg_attr(
    feature = "serde",
    serde(default, skip_serializing_if = "Option::is_none")
  )]
  seed: Option<u64>,
  /// Force the prefill tokens from `task`/`language` rather than let the
  /// model choose them.
  #[cfg_attr(feature = "serde", serde(default = "default_use_prefill_prompt"))]
  use_prefill_prompt: bool,
  /// Detect the spoken language instead of using `language`. Tri-state:
  /// `None` means the caller never chose, and the value resolves against
  /// `use_prefill_prompt` at read time — see [`Self::detect_language`]
  /// (the getter is the single resolution point) for the Swift rule this
  /// ports (`Configurations.swift:222`).
  #[cfg_attr(
    feature = "serde",
    serde(default, skip_serializing_if = "Option::is_none")
  )]
  detect_language: Option<bool>,
  /// Omit special tokens (e.g. `<|endoftext|>`) from decoded text.
  #[cfg_attr(feature = "serde", serde(default))]
  skip_special_tokens: bool,
  /// Omit timestamp tokens from decoding entirely.
  #[cfg_attr(feature = "serde", serde(default))]
  without_timestamps: bool,
  /// Compute word-level timestamps via DTW alignment.
  #[cfg_attr(feature = "serde", serde(default))]
  word_timestamps: bool,
  /// Reject an initial timestamp token above this many seconds into the
  /// window. `None` disables the check (golden `Option<Copy>` exception).
  #[cfg_attr(
    feature = "serde",
    serde(
      default,
      skip_serializing_if = "Option::is_none",
      with = "finite_f32_option"
    )
  )]
  max_initial_timestamp: Option<f32>,
  /// Cap the seek position, in samples, for any single window. `None`
  /// disables the cap.
  #[cfg_attr(
    feature = "serde",
    serde(default, skip_serializing_if = "Option::is_none")
  )]
  max_window_seek: Option<usize>,
  /// Explicit `(start, end)`-pair timestamps, in seconds, to split the
  /// audio into segments before transcription. Empty means the whole input
  /// is one segment.
  #[cfg_attr(
    feature = "serde",
    serde(
      default,
      skip_serializing_if = "Vec::is_empty",
      with = "finite_f32_vec"
    )
  )]
  clip_timestamps: Vec<f32>,
  /// Seconds clipped from the end of each window, to reduce hallucinated
  /// trailing text.
  #[cfg_attr(
    feature = "serde",
    serde(default = "default_window_clip_time", with = "finite_f32")
  )]
  window_clip_time: f32,
  /// Token ids prepended to the prefill tokens as a conditioning prompt.
  #[cfg_attr(
    feature = "serde",
    serde(default, skip_serializing_if = "Vec::is_empty")
  )]
  prompt_tokens: Vec<u32>,
  /// Token ids appended to the prefill tokens as a forced prefix.
  #[cfg_attr(
    feature = "serde",
    serde(default, skip_serializing_if = "Vec::is_empty")
  )]
  prefix_tokens: Vec<u32>,
  /// Suppress the blank (space) token during decoding.
  #[cfg_attr(feature = "serde", serde(default))]
  suppress_blank: bool,
  /// Additional token ids to suppress during decoding.
  #[cfg_attr(
    feature = "serde",
    serde(default, skip_serializing_if = "Vec::is_empty")
  )]
  suppress_tokens: Vec<u32>,
  /// Treat decoding as failed if the output text's compression ratio
  /// exceeds this value (too repetitive). `None` disables the check.
  ///
  /// No `skip_serializing_if`: this knob's default is `Some(_)`, so a
  /// skipped `None` would read back **re-enabled at the default**. See the
  /// module doc's lossless-round-trip section.
  #[cfg_attr(
    feature = "serde",
    serde(
      default = "default_compression_ratio_threshold",
      with = "finite_f32_option"
    )
  )]
  compression_ratio_threshold: Option<f32>,
  /// Treat decoding as failed if the average sampled-token log
  /// probability falls below this value. `None` disables the check.
  ///
  /// Serialized even when `None` — see
  /// [`Self::compression_ratio_threshold`]'s field note.
  #[cfg_attr(
    feature = "serde",
    serde(default = "default_logprob_threshold", with = "finite_f32_option")
  )]
  logprob_threshold: Option<f32>,
  /// Treat decoding as failed if the first sampled token's log
  /// probability falls below this value. `None` disables the check.
  ///
  /// Serialized even when `None` — see
  /// [`Self::compression_ratio_threshold`]'s field note.
  #[cfg_attr(
    feature = "serde",
    serde(
      default = "default_first_token_logprob_threshold",
      with = "finite_f32_option"
    )
  )]
  first_token_logprob_threshold: Option<f32>,
  /// Treat a window as silent when the no-speech probability strictly
  /// exceeds this value. `None` disables the check. (Silence short-circuits
  /// on this comparison ALONE — Swift's own doc comment claiming the
  /// average log probability is also consulted is stale against its code;
  /// see `result::needs_fallback`, `Models.swift:368-370`.)
  ///
  /// Serialized even when `None` — see
  /// [`Self::compression_ratio_threshold`]'s field note.
  #[cfg_attr(
    feature = "serde",
    serde(default = "default_no_speech_threshold", with = "finite_f32_option")
  )]
  no_speech_threshold: Option<f32>,
  /// Worker threads for batch transcription (Swift's macOS default: 16).
  #[cfg_attr(feature = "serde", serde(default = "default_concurrent_worker_count"))]
  concurrent_worker_count: NonZeroUsize,
  /// How long-form audio is split into chunks before transcription.
  #[cfg_attr(feature = "serde", serde(default))]
  chunking_strategy: ChunkingStrategy,
  /// Emit verbose per-step decode logging.
  #[cfg_attr(feature = "serde", serde(default))]
  verbose: bool,
  /// Drop decoded blank-audio segments instead of emitting them. Defaults
  /// `true` — see [`Self::drop_blank_audio`] for the full contract and the
  /// deliberate Swift-parity divergence it carries.
  #[cfg_attr(feature = "serde", serde(default = "default_drop_blank_audio"))]
  drop_blank_audio: bool,
  /// How decoded tokens are grouped into words for word-level timestamps.
  /// Defaults to [`WordGrouping::SwiftParity`] (coremlit issue #41; serde
  /// follows via the enum's `Default`). [`WordGrouping::FineGrained`] is the
  /// product-quality opt-in.
  #[cfg_attr(feature = "serde", serde(default))]
  word_grouping: WordGrouping,
  /// How the per-token alignment rows are gathered before DTW. Defaults to
  /// [`AlignmentGather::Complete`], the un-truncated, platform-independent
  /// gather (coremlit issue #41; serde follows via the enum's `Default`).
  /// [`AlignmentGather::SwiftParity`] is the fail-closed opt-in that
  /// reproduces Swift's truncating gather.
  #[cfg_attr(feature = "serde", serde(default))]
  alignment_gather: AlignmentGather,
}

/// Names every field of [`DecodingOptions`] exactly once, generating (for
/// tests) both a `DECODING_OPTION_FIELD_NAMES` roster and a compile-time
/// exhaustiveness guard that destructures `DecodingOptions` WITHOUT `..`.
///
/// This is what makes the provenance completeness tests non-circular (codex
/// round 3, F7): the field roster they check the mutation table against comes
/// from `DecodingOptions` ITSELF, not from folding the very `mutations()` table
/// under test. Add a field to the struct and the guard below fails to compile
/// until it is named here — and it then lands in
/// `provenance::tests::mutation_table_covers_every_decoding_option` as an
/// uncovered name until it also gets a mutation row. The serde key of every
/// field equals its Rust name (no field carries `serde(rename)`), so
/// `stringify!` yields exactly the serialized key set.
macro_rules! decoding_option_field_names {
  ($($field:ident),+ $(,)?) => {
    /// The full field/serde-key set of [`DecodingOptions`], one entry per
    /// field. Kept exhaustive at compile time by the guard in the same macro
    /// expansion. Consumed by the provenance mutation-table coverage test.
    #[cfg(test)]
    #[allow(dead_code)] // used only by the serde-gated provenance coverage test
    pub(crate) const DECODING_OPTION_FIELD_NAMES: &[&str] = &[$(stringify!($field)),+];

    /// A pure compile-time exhaustiveness check: destructuring without `..`
    /// forces every `DecodingOptions` field to be named in the list above, so
    /// a newly added field breaks the test build until the roster (and the
    /// provenance mutation table) name it. Never called.
    #[cfg(test)]
    #[allow(dead_code)]
    fn _decoding_options_field_exhaustiveness_guard(options: DecodingOptions) {
      let DecodingOptions { $($field: _),+ } = options;
    }
  };
}

decoding_option_field_names!(
  task,
  language,
  temperature,
  temperature_increment_on_fallback,
  temperature_fallback_count,
  sample_length,
  top_k,
  seed,
  use_prefill_prompt,
  detect_language,
  skip_special_tokens,
  without_timestamps,
  word_timestamps,
  max_initial_timestamp,
  max_window_seek,
  clip_timestamps,
  window_clip_time,
  prompt_tokens,
  prefix_tokens,
  suppress_blank,
  suppress_tokens,
  compression_ratio_threshold,
  logprob_threshold,
  first_token_logprob_threshold,
  no_speech_threshold,
  concurrent_worker_count,
  chunking_strategy,
  verbose,
  drop_blank_audio,
  word_grouping,
  alignment_gather,
);

impl Default for DecodingOptions {
  fn default() -> Self {
    Self::new()
  }
}

impl DecodingOptions {
  /// Decode options matching Swift's defaults (spec §6.2).
  pub const fn new() -> Self {
    Self {
      task: Task::Transcribe,
      language: String::new(),
      temperature: DEFAULT_TEMPERATURE,
      temperature_increment_on_fallback: DEFAULT_TEMPERATURE_INCREMENT_ON_FALLBACK,
      temperature_fallback_count: DEFAULT_TEMPERATURE_FALLBACK_COUNT,
      sample_length: DEFAULT_SAMPLE_LENGTH,
      top_k: DEFAULT_TOP_K,
      seed: None,
      use_prefill_prompt: DEFAULT_USE_PREFILL_PROMPT,
      detect_language: None,
      skip_special_tokens: false,
      without_timestamps: false,
      word_timestamps: false,
      max_initial_timestamp: None,
      max_window_seek: None,
      clip_timestamps: Vec::new(),
      window_clip_time: DEFAULT_WINDOW_CLIP_TIME,
      prompt_tokens: Vec::new(),
      prefix_tokens: Vec::new(),
      suppress_blank: false,
      suppress_tokens: Vec::new(),
      compression_ratio_threshold: Some(DEFAULT_COMPRESSION_RATIO_THRESHOLD),
      logprob_threshold: Some(DEFAULT_LOGPROB_THRESHOLD),
      first_token_logprob_threshold: Some(DEFAULT_FIRST_TOKEN_LOGPROB_THRESHOLD),
      no_speech_threshold: Some(DEFAULT_NO_SPEECH_THRESHOLD),
      concurrent_worker_count: DEFAULT_CONCURRENT_WORKER_COUNT,
      chunking_strategy: ChunkingStrategy::Disabled,
      verbose: false,
      drop_blank_audio: DEFAULT_DROP_BLANK_AUDIO,
      word_grouping: WordGrouping::SwiftParity,
      alignment_gather: AlignmentGather::Complete,
    }
  }

  // -- task ---------------------------------------------------------
  /// The configured decode task.
  #[inline(always)]
  pub const fn task(&self) -> Task {
    self.task
  }
  /// Builder form of [`Self::set_task`].
  #[must_use]
  #[inline(always)]
  pub const fn with_task(mut self, task: Task) -> Self {
    self.set_task(task);
    self
  }
  /// Sets [`Self::task`] in place.
  #[inline(always)]
  pub const fn set_task(&mut self, task: Task) -> &mut Self {
    self.task = task;
    self
  }

  // -- language -------------------------------------------------------
  /// Spoken language (ISO code); empty means auto-detect.
  #[inline(always)]
  pub fn language(&self) -> &str {
    self.language.as_str()
  }
  /// Builder form of [`Self::set_language`].
  #[must_use]
  #[inline(always)]
  pub fn with_language(mut self, language: impl Into<String>) -> Self {
    self.set_language(language);
    self
  }
  /// Sets [`Self::language`] in place.
  #[inline(always)]
  pub fn set_language(&mut self, language: impl Into<String>) -> &mut Self {
    self.language = language.into();
    self
  }

  // -- temperature ------------------------------------------------------
  /// Sampling temperature; `0.0` is greedy (argmax) decoding.
  #[inline(always)]
  pub const fn temperature(&self) -> f32 {
    self.temperature
  }
  /// Builder form of [`Self::set_temperature`].
  #[must_use]
  #[inline(always)]
  pub const fn with_temperature(mut self, temperature: f32) -> Self {
    self.set_temperature(temperature);
    self
  }
  /// Sets [`Self::temperature`] in place.
  #[inline(always)]
  pub const fn set_temperature(&mut self, temperature: f32) -> &mut Self {
    self.temperature = temperature;
    self
  }

  // -- temperature_increment_on_fallback ---------------------------------
  /// Amount added to `temperature` on each fallback retry.
  #[inline(always)]
  pub const fn temperature_increment_on_fallback(&self) -> f32 {
    self.temperature_increment_on_fallback
  }
  /// Builder form of [`Self::set_temperature_increment_on_fallback`].
  #[must_use]
  #[inline(always)]
  pub const fn with_temperature_increment_on_fallback(
    mut self,
    temperature_increment_on_fallback: f32,
  ) -> Self {
    self.set_temperature_increment_on_fallback(temperature_increment_on_fallback);
    self
  }
  /// Sets [`Self::temperature_increment_on_fallback`] in place.
  #[inline(always)]
  pub const fn set_temperature_increment_on_fallback(
    &mut self,
    temperature_increment_on_fallback: f32,
  ) -> &mut Self {
    self.temperature_increment_on_fallback = temperature_increment_on_fallback;
    self
  }

  // -- temperature_fallback_count -----------------------------------------
  /// Maximum number of temperature-fallback retries.
  #[inline(always)]
  pub const fn temperature_fallback_count(&self) -> usize {
    self.temperature_fallback_count
  }
  /// Builder form of [`Self::set_temperature_fallback_count`].
  #[must_use]
  #[inline(always)]
  pub const fn with_temperature_fallback_count(
    mut self,
    temperature_fallback_count: usize,
  ) -> Self {
    self.set_temperature_fallback_count(temperature_fallback_count);
    self
  }
  /// Sets [`Self::temperature_fallback_count`] in place.
  #[inline(always)]
  pub const fn set_temperature_fallback_count(
    &mut self,
    temperature_fallback_count: usize,
  ) -> &mut Self {
    self.temperature_fallback_count = temperature_fallback_count;
    self
  }

  // -- sample_length --------------------------------------------------
  /// Maximum number of tokens to sample per window.
  #[inline(always)]
  pub const fn sample_length(&self) -> usize {
    self.sample_length
  }
  /// Builder form of [`Self::set_sample_length`].
  #[must_use]
  #[inline(always)]
  pub const fn with_sample_length(mut self, sample_length: usize) -> Self {
    self.set_sample_length(sample_length);
    self
  }
  /// Sets [`Self::sample_length`] in place.
  #[inline(always)]
  pub const fn set_sample_length(&mut self, sample_length: usize) -> &mut Self {
    self.sample_length = sample_length;
    self
  }

  // -- top_k ------------------------------------------------------------
  /// Candidate count for non-zero-temperature sampling.
  #[inline(always)]
  pub const fn top_k(&self) -> usize {
    self.top_k
  }
  /// Builder form of [`Self::set_top_k`].
  #[must_use]
  #[inline(always)]
  pub const fn with_top_k(mut self, top_k: usize) -> Self {
    self.set_top_k(top_k);
    self
  }
  /// Sets [`Self::top_k`] in place.
  #[inline(always)]
  pub const fn set_top_k(&mut self, top_k: usize) -> &mut Self {
    self.top_k = top_k;
    self
  }

  // -- seed (Option<u64>) ---------------------------------------------------
  /// Base seed for reproducible temperature-fallback sampling.
  ///
  /// `None` (the default) leaves every attempt's
  /// [`GreedyTokenSampler`](crate::audio::whisper::decode::sampler::GreedyTokenSampler)
  /// OS-seeded, matching Swift's own unseeded `Float.random`
  /// (`TokenSampler.swift:169`) — nondeterministic at `temperature > 0`,
  /// by design, on both runtimes; this is the byte-unchanged default
  /// path.
  ///
  /// `Some(seed)` makes the whole transcription reproducible instead:
  /// [`crate::audio::whisper::transcribe::TranscribeTask`]'s fallback ladder derives an
  /// independent per-(worker, window, attempt) sub-seed from it via
  /// [`derive_attempt_seed`](crate::audio::whisper::decode::sampler::derive_attempt_seed)
  /// rather than reusing `seed` verbatim everywhere (see that function's
  /// doc for why, and for the exact mixing function) — so re-running the
  /// same audio through the same options and `seed` always samples the
  /// identical tokens, with the fallback ladder still fully enabled. A
  /// seed makes this port's *own* output reproducible; it cannot make
  /// that output match Swift's, which has no seed knob of its own and
  /// always draws unseeded — record the effective temperature in
  /// provenance either way
  /// ([`TranscriptionSegment::temperature`](crate::audio::whisper::result::TranscriptionSegment::temperature)).
  #[inline(always)]
  pub const fn seed(&self) -> Option<u64> {
    self.seed
  }
  /// Builder form of [`Self::set_seed`].
  #[must_use]
  #[inline(always)]
  pub const fn with_seed(mut self, seed: u64) -> Self {
    self.set_seed(seed);
    self
  }
  /// Sets [`Self::seed`] to `Some(seed)`.
  #[inline(always)]
  pub const fn set_seed(&mut self, seed: u64) -> &mut Self {
    self.seed = Some(seed);
    self
  }
  /// Builder form of [`Self::update_seed`].
  #[must_use]
  #[inline(always)]
  pub const fn maybe_seed(mut self, seed: Option<u64>) -> Self {
    self.update_seed(seed);
    self
  }
  /// Assigns [`Self::seed`] directly.
  #[inline(always)]
  pub const fn update_seed(&mut self, seed: Option<u64>) -> &mut Self {
    self.seed = seed;
    self
  }
  /// Sets [`Self::seed`] to `None`.
  #[inline(always)]
  pub const fn clear_seed(&mut self) -> &mut Self {
    self.seed = None;
    self
  }

  // -- use_prefill_prompt (bool) ------------------------------------------
  /// Force the prefill tokens from `task`/`language` rather than let the
  /// model choose them.
  #[inline(always)]
  pub const fn use_prefill_prompt(&self) -> bool {
    self.use_prefill_prompt
  }
  /// Builder form of [`Self::set_use_prefill_prompt`].
  #[must_use]
  #[inline(always)]
  pub const fn with_use_prefill_prompt(mut self) -> Self {
    self.set_use_prefill_prompt();
    self
  }
  /// Sets [`Self::use_prefill_prompt`] to `true`.
  #[inline(always)]
  pub const fn set_use_prefill_prompt(&mut self) -> &mut Self {
    self.use_prefill_prompt = true;
    self
  }
  /// Builder form of [`Self::update_use_prefill_prompt`].
  #[must_use]
  #[inline(always)]
  pub const fn maybe_use_prefill_prompt(mut self, use_prefill_prompt: bool) -> Self {
    self.update_use_prefill_prompt(use_prefill_prompt);
    self
  }
  /// Assigns [`Self::use_prefill_prompt`] directly.
  #[inline(always)]
  pub const fn update_use_prefill_prompt(&mut self, use_prefill_prompt: bool) -> &mut Self {
    self.use_prefill_prompt = use_prefill_prompt;
    self
  }
  /// Sets [`Self::use_prefill_prompt`] to `false`.
  #[inline(always)]
  pub const fn clear_use_prefill_prompt(&mut self) -> &mut Self {
    self.use_prefill_prompt = false;
    self
  }

  // -- detect_language (tri-state bool) ------------------------------------
  /// Detect the spoken language instead of using `language`, resolved:
  /// when the caller never set it, it defaults to `!use_prefill_prompt` —
  /// detection kicks in by default exactly when prefill is off. Ports
  /// Swift's constructor resolution `detectLanguage ?? !usePrefillPrompt`
  /// (`Configurations.swift:222`, "If prefill is false, detect language
  /// by default"). An explicit [`Self::set_detect_language`]/
  /// [`Self::clear_detect_language`]/[`Self::update_detect_language`]
  /// always wins over the coupling, in either direction, regardless of
  /// mutation order.
  ///
  /// **Construction is Swift-identical.** Build with the chained
  /// `with_*`/`maybe_*` form and this getter returns exactly what
  /// Swift's memberwise initializer would have stored for the same
  /// `(detect_language, use_prefill_prompt)` pair: e.g.
  /// `DecodingOptions::new().maybe_use_prefill_prompt(false)` resolves
  /// `true` here, same as Swift's `DecodingOptions(usePrefillPrompt:
  /// false)`, because both sides apply the identical `?? !usePrefillPrompt`
  /// formula to the same final inputs.
  ///
  /// **Pinned deviation: in-place mutation of `use_prefill_prompt` after
  /// construction, while `detect_language` is still unset.** Swift's
  /// `detectLanguage` is a plain stored `Bool` — resolved once inside
  /// `init`, then frozen; reassigning the `var usePrefillPrompt`
  /// property afterward never touches it again. This getter has no such
  /// freeze point and re-resolves on every call against whatever
  /// `use_prefill_prompt` currently holds. Concretely:
  /// `DecodingOptions::new()` (prefill ON, the default) followed by the
  /// in-place mutator [`Self::clear_use_prefill_prompt`] resolves `true`
  /// here — but Swift's equivalent, `var o = DecodingOptions()`
  /// (`detectLanguage` already frozen `false`) followed by
  /// `o.usePrefillPrompt = false`, leaves `detectLanguage` at the
  /// `false` its initializer committed to. At a nonzero temperature
  /// this changes whether a language-detection probe runs at all, which
  /// consumes the attempt's sampler RNG draw and can shift both the
  /// sampled tokens that follow and the word-level language split.
  ///
  /// This is a deliberate, accepted deviation, not a defect to fix:
  /// eagerly freezing the resolution — inside `new()` or every mutator
  /// that touches `use_prefill_prompt` — would have to materialize
  /// `Some(false)` immediately, destroying the `None` ("caller never
  /// chose") tri-state this field exists to represent, and with it
  /// `serde`'s absent-on-unset round trip
  /// (`skip_serializing_if = "Option::is_none"`) and the explicit-wins
  /// guarantee above — both depend on telling "never set" apart from
  /// "set to whatever the coupling currently says." A caller who wants
  /// Swift's frozen-at-construction behavior after mutating
  /// `use_prefill_prompt` in place sets `detect_language` explicitly
  /// first (one call to [`Self::set_detect_language`]/
  /// [`Self::clear_detect_language`]/[`Self::update_detect_language`]
  /// before the mutation) — an explicit choice always wins over the
  /// coupling.
  ///
  /// This getter is the single resolution point: every pipeline consumer
  /// reads the coupled value through it.
  #[inline(always)]
  pub const fn detect_language(&self) -> bool {
    match self.detect_language {
      Some(explicit) => explicit,
      None => !self.use_prefill_prompt,
    }
  }
  /// Builder form of [`Self::set_detect_language`].
  #[must_use]
  #[inline(always)]
  pub const fn with_detect_language(mut self) -> Self {
    self.set_detect_language();
    self
  }
  /// Sets [`Self::detect_language`] explicitly to `true` (an explicit
  /// value always beats the `!use_prefill_prompt` default coupling).
  #[inline(always)]
  pub const fn set_detect_language(&mut self) -> &mut Self {
    self.detect_language = Some(true);
    self
  }
  /// Builder form of [`Self::update_detect_language`].
  #[must_use]
  #[inline(always)]
  pub const fn maybe_detect_language(mut self, detect_language: bool) -> Self {
    self.update_detect_language(detect_language);
    self
  }
  /// Assigns [`Self::detect_language`] explicitly (an explicit value
  /// always beats the `!use_prefill_prompt` default coupling).
  #[inline(always)]
  pub const fn update_detect_language(&mut self, detect_language: bool) -> &mut Self {
    self.detect_language = Some(detect_language);
    self
  }
  /// Sets [`Self::detect_language`] explicitly to `false` (an explicit
  /// value always beats the `!use_prefill_prompt` default coupling — this
  /// is how a no-prefill caller opts back out of detection).
  #[inline(always)]
  pub const fn clear_detect_language(&mut self) -> &mut Self {
    self.detect_language = Some(false);
    self
  }

  // -- skip_special_tokens (bool) -----------------------------------------
  /// Omit special tokens (e.g. `<|endoftext|>`) from decoded text.
  #[inline(always)]
  pub const fn skip_special_tokens(&self) -> bool {
    self.skip_special_tokens
  }
  /// Builder form of [`Self::set_skip_special_tokens`].
  #[must_use]
  #[inline(always)]
  pub const fn with_skip_special_tokens(mut self) -> Self {
    self.set_skip_special_tokens();
    self
  }
  /// Sets [`Self::skip_special_tokens`] to `true`.
  #[inline(always)]
  pub const fn set_skip_special_tokens(&mut self) -> &mut Self {
    self.skip_special_tokens = true;
    self
  }
  /// Builder form of [`Self::update_skip_special_tokens`].
  #[must_use]
  #[inline(always)]
  pub const fn maybe_skip_special_tokens(mut self, skip_special_tokens: bool) -> Self {
    self.update_skip_special_tokens(skip_special_tokens);
    self
  }
  /// Assigns [`Self::skip_special_tokens`] directly.
  #[inline(always)]
  pub const fn update_skip_special_tokens(&mut self, skip_special_tokens: bool) -> &mut Self {
    self.skip_special_tokens = skip_special_tokens;
    self
  }
  /// Sets [`Self::skip_special_tokens`] to `false`.
  #[inline(always)]
  pub const fn clear_skip_special_tokens(&mut self) -> &mut Self {
    self.skip_special_tokens = false;
    self
  }

  // -- without_timestamps (bool) ------------------------------------------
  /// Omit timestamp tokens from decoding entirely.
  #[inline(always)]
  pub const fn without_timestamps(&self) -> bool {
    self.without_timestamps
  }
  /// Builder form of [`Self::set_without_timestamps`].
  #[must_use]
  #[inline(always)]
  pub const fn with_without_timestamps(mut self) -> Self {
    self.set_without_timestamps();
    self
  }
  /// Sets [`Self::without_timestamps`] to `true`.
  #[inline(always)]
  pub const fn set_without_timestamps(&mut self) -> &mut Self {
    self.without_timestamps = true;
    self
  }
  /// Builder form of [`Self::update_without_timestamps`].
  #[must_use]
  #[inline(always)]
  pub const fn maybe_without_timestamps(mut self, without_timestamps: bool) -> Self {
    self.update_without_timestamps(without_timestamps);
    self
  }
  /// Assigns [`Self::without_timestamps`] directly.
  #[inline(always)]
  pub const fn update_without_timestamps(&mut self, without_timestamps: bool) -> &mut Self {
    self.without_timestamps = without_timestamps;
    self
  }
  /// Sets [`Self::without_timestamps`] to `false`.
  #[inline(always)]
  pub const fn clear_without_timestamps(&mut self) -> &mut Self {
    self.without_timestamps = false;
    self
  }

  // -- word_timestamps (bool) ----------------------------------------------
  /// Compute word-level timestamps via DTW alignment.
  ///
  /// When set, [`crate::audio::whisper::transcribe::TranscribeTask::run`]'s window loop
  /// runs [`crate::audio::whisper::segment::add_word_timestamps`] against each window's
  /// alignment-weight snapshot and writes the result onto that window's
  /// segments (Swift's `addWordTimestamps`, `TranscribeTask.swift:
  /// 196-233). `false` (the default) leaves every segment's `words` empty
  /// and skips that (relatively expensive) DTW alignment pass entirely.
  #[inline(always)]
  pub const fn word_timestamps(&self) -> bool {
    self.word_timestamps
  }
  /// Builder form of [`Self::set_word_timestamps`].
  #[must_use]
  #[inline(always)]
  pub const fn with_word_timestamps(mut self) -> Self {
    self.set_word_timestamps();
    self
  }
  /// Sets [`Self::word_timestamps`] to `true`.
  #[inline(always)]
  pub const fn set_word_timestamps(&mut self) -> &mut Self {
    self.word_timestamps = true;
    self
  }
  /// Builder form of [`Self::update_word_timestamps`].
  #[must_use]
  #[inline(always)]
  pub const fn maybe_word_timestamps(mut self, word_timestamps: bool) -> Self {
    self.update_word_timestamps(word_timestamps);
    self
  }
  /// Assigns [`Self::word_timestamps`] directly.
  #[inline(always)]
  pub const fn update_word_timestamps(&mut self, word_timestamps: bool) -> &mut Self {
    self.word_timestamps = word_timestamps;
    self
  }
  /// Sets [`Self::word_timestamps`] to `false`.
  #[inline(always)]
  pub const fn clear_word_timestamps(&mut self) -> &mut Self {
    self.word_timestamps = false;
    self
  }

  // -- max_initial_timestamp (Option<f32>) --------------------------------
  /// Reject an initial timestamp token above this many seconds into the
  /// window. `None` disables the check.
  #[inline(always)]
  pub const fn max_initial_timestamp(&self) -> Option<f32> {
    self.max_initial_timestamp
  }
  /// Builder form of [`Self::set_max_initial_timestamp`].
  #[must_use]
  #[inline(always)]
  pub const fn with_max_initial_timestamp(mut self, max_initial_timestamp: f32) -> Self {
    self.set_max_initial_timestamp(max_initial_timestamp);
    self
  }
  /// Sets [`Self::max_initial_timestamp`] to `Some(max_initial_timestamp)`.
  #[inline(always)]
  pub const fn set_max_initial_timestamp(&mut self, max_initial_timestamp: f32) -> &mut Self {
    self.max_initial_timestamp = Some(max_initial_timestamp);
    self
  }
  /// Builder form of [`Self::update_max_initial_timestamp`].
  #[must_use]
  #[inline(always)]
  pub const fn maybe_max_initial_timestamp(mut self, max_initial_timestamp: Option<f32>) -> Self {
    self.update_max_initial_timestamp(max_initial_timestamp);
    self
  }
  /// Assigns [`Self::max_initial_timestamp`] directly.
  #[inline(always)]
  pub const fn update_max_initial_timestamp(
    &mut self,
    max_initial_timestamp: Option<f32>,
  ) -> &mut Self {
    self.max_initial_timestamp = max_initial_timestamp;
    self
  }
  /// Sets [`Self::max_initial_timestamp`] to `None`.
  #[inline(always)]
  pub const fn clear_max_initial_timestamp(&mut self) -> &mut Self {
    self.max_initial_timestamp = None;
    self
  }

  // -- max_window_seek (Option<usize>) -------------------------------------
  /// Cap the seek position, in samples, for any single window. `None`
  /// disables the cap. The pipeline floors a configured cap at one
  /// sample of forward progress per window — `Some(0)` would otherwise
  /// pin the seek loop to the same window forever.
  #[inline(always)]
  pub const fn max_window_seek(&self) -> Option<usize> {
    self.max_window_seek
  }
  /// Builder form of [`Self::set_max_window_seek`].
  #[must_use]
  #[inline(always)]
  pub const fn with_max_window_seek(mut self, max_window_seek: usize) -> Self {
    self.set_max_window_seek(max_window_seek);
    self
  }
  /// Sets [`Self::max_window_seek`] to `Some(max_window_seek)`.
  #[inline(always)]
  pub const fn set_max_window_seek(&mut self, max_window_seek: usize) -> &mut Self {
    self.max_window_seek = Some(max_window_seek);
    self
  }
  /// Builder form of [`Self::update_max_window_seek`].
  #[must_use]
  #[inline(always)]
  pub const fn maybe_max_window_seek(mut self, max_window_seek: Option<usize>) -> Self {
    self.update_max_window_seek(max_window_seek);
    self
  }
  /// Assigns [`Self::max_window_seek`] directly.
  #[inline(always)]
  pub const fn update_max_window_seek(&mut self, max_window_seek: Option<usize>) -> &mut Self {
    self.max_window_seek = max_window_seek;
    self
  }
  /// Sets [`Self::max_window_seek`] to `None`.
  #[inline(always)]
  pub const fn clear_max_window_seek(&mut self) -> &mut Self {
    self.max_window_seek = None;
    self
  }

  // -- clip_timestamps (Vec<f32>) -----------------------------------------
  /// Explicit `(start, end)`-pair timestamps, in seconds, to split the
  /// audio into segments before transcription. Empty means one segment.
  #[inline(always)]
  pub const fn clip_timestamps_slice(&self) -> &[f32] {
    self.clip_timestamps.as_slice()
  }
  /// Builder form of [`Self::set_clip_timestamps`].
  #[must_use]
  #[inline(always)]
  pub fn with_clip_timestamps(mut self, clip_timestamps: impl Into<Vec<f32>>) -> Self {
    self.set_clip_timestamps(clip_timestamps);
    self
  }
  /// Sets [`Self::clip_timestamps_slice`] in place.
  #[inline(always)]
  pub fn set_clip_timestamps(&mut self, clip_timestamps: impl Into<Vec<f32>>) -> &mut Self {
    self.clip_timestamps = clip_timestamps.into();
    self
  }

  // -- window_clip_time -----------------------------------------------
  /// Seconds clipped from the end of each window, to reduce hallucinated
  /// trailing text.
  #[inline(always)]
  pub const fn window_clip_time(&self) -> f32 {
    self.window_clip_time
  }
  /// Builder form of [`Self::set_window_clip_time`].
  #[must_use]
  #[inline(always)]
  pub const fn with_window_clip_time(mut self, window_clip_time: f32) -> Self {
    self.set_window_clip_time(window_clip_time);
    self
  }
  /// Sets [`Self::window_clip_time`] in place.
  #[inline(always)]
  pub const fn set_window_clip_time(&mut self, window_clip_time: f32) -> &mut Self {
    self.window_clip_time = window_clip_time;
    self
  }

  // -- prompt_tokens (Vec<u32>) ---------------------------------------
  /// Token ids prepended to the prefill tokens as a conditioning prompt.
  #[inline(always)]
  pub const fn prompt_tokens_slice(&self) -> &[u32] {
    self.prompt_tokens.as_slice()
  }
  /// Builder form of [`Self::set_prompt_tokens`].
  #[must_use]
  #[inline(always)]
  pub fn with_prompt_tokens(mut self, prompt_tokens: impl Into<Vec<u32>>) -> Self {
    self.set_prompt_tokens(prompt_tokens);
    self
  }
  /// Sets [`Self::prompt_tokens_slice`] in place.
  #[inline(always)]
  pub fn set_prompt_tokens(&mut self, prompt_tokens: impl Into<Vec<u32>>) -> &mut Self {
    self.prompt_tokens = prompt_tokens.into();
    self
  }

  // -- prefix_tokens (Vec<u32>) ---------------------------------------
  /// Token ids appended to the prefill tokens as a forced prefix.
  #[inline(always)]
  pub const fn prefix_tokens_slice(&self) -> &[u32] {
    self.prefix_tokens.as_slice()
  }
  /// Builder form of [`Self::set_prefix_tokens`].
  #[must_use]
  #[inline(always)]
  pub fn with_prefix_tokens(mut self, prefix_tokens: impl Into<Vec<u32>>) -> Self {
    self.set_prefix_tokens(prefix_tokens);
    self
  }
  /// Sets [`Self::prefix_tokens_slice`] in place.
  #[inline(always)]
  pub fn set_prefix_tokens(&mut self, prefix_tokens: impl Into<Vec<u32>>) -> &mut Self {
    self.prefix_tokens = prefix_tokens.into();
    self
  }

  // -- suppress_blank (bool) -----------------------------------------------
  /// Suppress the blank (space) token during decoding.
  #[inline(always)]
  pub const fn suppress_blank(&self) -> bool {
    self.suppress_blank
  }
  /// Builder form of [`Self::set_suppress_blank`].
  #[must_use]
  #[inline(always)]
  pub const fn with_suppress_blank(mut self) -> Self {
    self.set_suppress_blank();
    self
  }
  /// Sets [`Self::suppress_blank`] to `true`.
  #[inline(always)]
  pub const fn set_suppress_blank(&mut self) -> &mut Self {
    self.suppress_blank = true;
    self
  }
  /// Builder form of [`Self::update_suppress_blank`].
  #[must_use]
  #[inline(always)]
  pub const fn maybe_suppress_blank(mut self, suppress_blank: bool) -> Self {
    self.update_suppress_blank(suppress_blank);
    self
  }
  /// Assigns [`Self::suppress_blank`] directly.
  #[inline(always)]
  pub const fn update_suppress_blank(&mut self, suppress_blank: bool) -> &mut Self {
    self.suppress_blank = suppress_blank;
    self
  }
  /// Sets [`Self::suppress_blank`] to `false`.
  #[inline(always)]
  pub const fn clear_suppress_blank(&mut self) -> &mut Self {
    self.suppress_blank = false;
    self
  }

  // -- suppress_tokens (Vec<u32>) --------------------------------------
  /// Additional token ids to suppress during decoding.
  #[inline(always)]
  pub const fn suppress_tokens_slice(&self) -> &[u32] {
    self.suppress_tokens.as_slice()
  }
  /// Builder form of [`Self::set_suppress_tokens`].
  #[must_use]
  #[inline(always)]
  pub fn with_suppress_tokens(mut self, suppress_tokens: impl Into<Vec<u32>>) -> Self {
    self.set_suppress_tokens(suppress_tokens);
    self
  }
  /// Sets [`Self::suppress_tokens_slice`] in place.
  #[inline(always)]
  pub fn set_suppress_tokens(&mut self, suppress_tokens: impl Into<Vec<u32>>) -> &mut Self {
    self.suppress_tokens = suppress_tokens.into();
    self
  }

  // -- compression_ratio_threshold (Option<f32>) ---------------------------
  /// Treat decoding as failed if the output text's compression ratio
  /// exceeds this value (too repetitive). `None` disables the check.
  #[inline(always)]
  pub const fn compression_ratio_threshold(&self) -> Option<f32> {
    self.compression_ratio_threshold
  }
  /// Builder form of [`Self::set_compression_ratio_threshold`].
  #[must_use]
  #[inline(always)]
  pub const fn with_compression_ratio_threshold(
    mut self,
    compression_ratio_threshold: f32,
  ) -> Self {
    self.set_compression_ratio_threshold(compression_ratio_threshold);
    self
  }
  /// Sets [`Self::compression_ratio_threshold`] to `Some(compression_ratio_threshold)`.
  #[inline(always)]
  pub const fn set_compression_ratio_threshold(
    &mut self,
    compression_ratio_threshold: f32,
  ) -> &mut Self {
    self.compression_ratio_threshold = Some(compression_ratio_threshold);
    self
  }
  /// Builder form of [`Self::update_compression_ratio_threshold`].
  #[must_use]
  #[inline(always)]
  pub const fn maybe_compression_ratio_threshold(
    mut self,
    compression_ratio_threshold: Option<f32>,
  ) -> Self {
    self.update_compression_ratio_threshold(compression_ratio_threshold);
    self
  }
  /// Assigns [`Self::compression_ratio_threshold`] directly.
  #[inline(always)]
  pub const fn update_compression_ratio_threshold(
    &mut self,
    compression_ratio_threshold: Option<f32>,
  ) -> &mut Self {
    self.compression_ratio_threshold = compression_ratio_threshold;
    self
  }
  /// Sets [`Self::compression_ratio_threshold`] to `None`.
  #[inline(always)]
  pub const fn clear_compression_ratio_threshold(&mut self) -> &mut Self {
    self.compression_ratio_threshold = None;
    self
  }

  // -- logprob_threshold (Option<f32>) -------------------------------------
  /// Treat decoding as failed if the average sampled-token log
  /// probability falls below this value. `None` disables the check.
  #[inline(always)]
  pub const fn logprob_threshold(&self) -> Option<f32> {
    self.logprob_threshold
  }
  /// Builder form of [`Self::set_logprob_threshold`].
  #[must_use]
  #[inline(always)]
  pub const fn with_logprob_threshold(mut self, logprob_threshold: f32) -> Self {
    self.set_logprob_threshold(logprob_threshold);
    self
  }
  /// Sets [`Self::logprob_threshold`] to `Some(logprob_threshold)`.
  #[inline(always)]
  pub const fn set_logprob_threshold(&mut self, logprob_threshold: f32) -> &mut Self {
    self.logprob_threshold = Some(logprob_threshold);
    self
  }
  /// Builder form of [`Self::update_logprob_threshold`].
  #[must_use]
  #[inline(always)]
  pub const fn maybe_logprob_threshold(mut self, logprob_threshold: Option<f32>) -> Self {
    self.update_logprob_threshold(logprob_threshold);
    self
  }
  /// Assigns [`Self::logprob_threshold`] directly.
  #[inline(always)]
  pub const fn update_logprob_threshold(&mut self, logprob_threshold: Option<f32>) -> &mut Self {
    self.logprob_threshold = logprob_threshold;
    self
  }
  /// Sets [`Self::logprob_threshold`] to `None`.
  #[inline(always)]
  pub const fn clear_logprob_threshold(&mut self) -> &mut Self {
    self.logprob_threshold = None;
    self
  }

  // -- first_token_logprob_threshold (Option<f32>) -------------------------
  /// Treat decoding as failed if the first sampled token's log
  /// probability falls below this value. `None` disables the check.
  #[inline(always)]
  pub const fn first_token_logprob_threshold(&self) -> Option<f32> {
    self.first_token_logprob_threshold
  }
  /// Builder form of [`Self::set_first_token_logprob_threshold`].
  #[must_use]
  #[inline(always)]
  pub const fn with_first_token_logprob_threshold(
    mut self,
    first_token_logprob_threshold: f32,
  ) -> Self {
    self.set_first_token_logprob_threshold(first_token_logprob_threshold);
    self
  }
  /// Sets [`Self::first_token_logprob_threshold`] to
  /// `Some(first_token_logprob_threshold)`.
  #[inline(always)]
  pub const fn set_first_token_logprob_threshold(
    &mut self,
    first_token_logprob_threshold: f32,
  ) -> &mut Self {
    self.first_token_logprob_threshold = Some(first_token_logprob_threshold);
    self
  }
  /// Builder form of [`Self::update_first_token_logprob_threshold`].
  #[must_use]
  #[inline(always)]
  pub const fn maybe_first_token_logprob_threshold(
    mut self,
    first_token_logprob_threshold: Option<f32>,
  ) -> Self {
    self.update_first_token_logprob_threshold(first_token_logprob_threshold);
    self
  }
  /// Assigns [`Self::first_token_logprob_threshold`] directly.
  #[inline(always)]
  pub const fn update_first_token_logprob_threshold(
    &mut self,
    first_token_logprob_threshold: Option<f32>,
  ) -> &mut Self {
    self.first_token_logprob_threshold = first_token_logprob_threshold;
    self
  }
  /// Sets [`Self::first_token_logprob_threshold`] to `None`.
  #[inline(always)]
  pub const fn clear_first_token_logprob_threshold(&mut self) -> &mut Self {
    self.first_token_logprob_threshold = None;
    self
  }

  // -- no_speech_threshold (Option<f32>) -----------------------------------
  /// Treat a window as silent when the no-speech probability strictly
  /// exceeds this value. `None` disables the check. (Silence short-circuits
  /// on this comparison ALONE — Swift's own doc comment claiming the
  /// average log probability is also consulted is stale against its code;
  /// see `result::needs_fallback`, `Models.swift:368-370`.)
  #[inline(always)]
  pub const fn no_speech_threshold(&self) -> Option<f32> {
    self.no_speech_threshold
  }
  /// Builder form of [`Self::set_no_speech_threshold`].
  #[must_use]
  #[inline(always)]
  pub const fn with_no_speech_threshold(mut self, no_speech_threshold: f32) -> Self {
    self.set_no_speech_threshold(no_speech_threshold);
    self
  }
  /// Sets [`Self::no_speech_threshold`] to `Some(no_speech_threshold)`.
  #[inline(always)]
  pub const fn set_no_speech_threshold(&mut self, no_speech_threshold: f32) -> &mut Self {
    self.no_speech_threshold = Some(no_speech_threshold);
    self
  }
  /// Builder form of [`Self::update_no_speech_threshold`].
  #[must_use]
  #[inline(always)]
  pub const fn maybe_no_speech_threshold(mut self, no_speech_threshold: Option<f32>) -> Self {
    self.update_no_speech_threshold(no_speech_threshold);
    self
  }
  /// Assigns [`Self::no_speech_threshold`] directly.
  #[inline(always)]
  pub const fn update_no_speech_threshold(
    &mut self,
    no_speech_threshold: Option<f32>,
  ) -> &mut Self {
    self.no_speech_threshold = no_speech_threshold;
    self
  }
  /// Sets [`Self::no_speech_threshold`] to `None`.
  #[inline(always)]
  pub const fn clear_no_speech_threshold(&mut self) -> &mut Self {
    self.no_speech_threshold = None;
    self
  }

  // -- concurrent_worker_count ------------------------------------------
  /// Worker threads for batch transcription (Swift's macOS default: 16).
  #[inline(always)]
  pub const fn concurrent_worker_count(&self) -> NonZeroUsize {
    self.concurrent_worker_count
  }
  /// Builder form of [`Self::set_concurrent_worker_count`].
  #[must_use]
  #[inline(always)]
  pub const fn with_concurrent_worker_count(
    mut self,
    concurrent_worker_count: NonZeroUsize,
  ) -> Self {
    self.set_concurrent_worker_count(concurrent_worker_count);
    self
  }
  /// Sets [`Self::concurrent_worker_count`] in place.
  #[inline(always)]
  pub const fn set_concurrent_worker_count(
    &mut self,
    concurrent_worker_count: NonZeroUsize,
  ) -> &mut Self {
    self.concurrent_worker_count = concurrent_worker_count;
    self
  }

  // -- chunking_strategy ------------------------------------------------
  /// How long-form audio is split into chunks before transcription.
  #[inline(always)]
  pub const fn chunking_strategy(&self) -> ChunkingStrategy {
    self.chunking_strategy
  }
  /// Builder form of [`Self::set_chunking_strategy`].
  #[must_use]
  #[inline(always)]
  pub const fn with_chunking_strategy(mut self, chunking_strategy: ChunkingStrategy) -> Self {
    self.set_chunking_strategy(chunking_strategy);
    self
  }
  /// Sets [`Self::chunking_strategy`] in place.
  #[inline(always)]
  pub const fn set_chunking_strategy(&mut self, chunking_strategy: ChunkingStrategy) -> &mut Self {
    self.chunking_strategy = chunking_strategy;
    self
  }

  // -- verbose (bool) -------------------------------------------------------
  /// Emit verbose per-step decode logging.
  #[inline(always)]
  pub const fn verbose(&self) -> bool {
    self.verbose
  }
  /// Builder form of [`Self::set_verbose`].
  #[must_use]
  #[inline(always)]
  pub const fn with_verbose(mut self) -> Self {
    self.set_verbose();
    self
  }
  /// Sets [`Self::verbose`] to `true`.
  #[inline(always)]
  pub const fn set_verbose(&mut self) -> &mut Self {
    self.verbose = true;
    self
  }
  /// Builder form of [`Self::update_verbose`].
  #[must_use]
  #[inline(always)]
  pub const fn maybe_verbose(mut self, verbose: bool) -> Self {
    self.update_verbose(verbose);
    self
  }
  /// Assigns [`Self::verbose`] directly.
  #[inline(always)]
  pub const fn update_verbose(&mut self, verbose: bool) -> &mut Self {
    self.verbose = verbose;
    self
  }
  /// Sets [`Self::verbose`] to `false`.
  #[inline(always)]
  pub const fn clear_verbose(&mut self) -> &mut Self {
    self.verbose = false;
    self
  }

  // -- drop_blank_audio (bool) ----------------------------------------------
  /// Drop blank-audio segments from the transcription instead of emitting
  /// them. **Defaults `true`** (coremlit issue #14).
  ///
  /// Some Whisper models decode silent or near-silent audio to the literal
  /// text [`BLANK_AUDIO_MARKER`](crate::audio::whisper::constants::BLANK_AUDIO_MARKER)
  /// (`"[BLANK_AUDIO]"`) — a training-data artifact the decoder genuinely
  /// samples, not a special token this crate inserts (see that constant's
  /// doc). When this is `true`,
  /// [`TranscribeTask::run`](crate::audio::whisper::transcribe::TranscribeTask::run)
  /// applies a **post-decode filter** to the assembled segments: any
  /// segment whose *clean* text — its tokens with the special/timestamp
  /// ids stripped, decoded, and whitespace-trimmed, i.e. the same
  /// projection [`TranscriptionResult::text`](crate::audio::whisper::result::TranscriptionResult::text)
  /// is built from, **not** the raw
  /// [`TranscriptionSegment::text`](crate::audio::whisper::result::TranscriptionSegment::text),
  /// which still carries its special tokens — is exactly the marker gets
  /// removed before the result text is assembled. Pure silence therefore
  /// yields an **empty result** (zero segments, empty text) rather than a
  /// one-segment `[BLANK_AUDIO]`; a blank stretch *between* speech is
  /// dropped while the speech around it survives.
  ///
  /// Survivors **keep the ids they were decoded with**: a drop leaves a
  /// gap (`[0, 2]` where segment 1 was blank) rather than relabelling the
  /// segments around it, so ids stay stable whichever way this is set and
  /// the hole itself says what happened. See
  /// [`TranscribeTask::run`](crate::audio::whisper::transcribe::TranscribeTask::run) for
  /// why (an id is an ordinal decode position, not an index, and nothing
  /// in the crate looks a segment up by one).
  ///
  /// Only the **exact** `[BLANK_AUDIO]` literal is dropped. Other
  /// non-speech markers a model emits — `[APPLAUSE]`, `[MUSIC]` — are
  /// deliberately left alone: this is a blank-*audio* filter, not a
  /// general non-speech-annotation stripper.
  ///
  /// **This default is the one deliberate Swift-parity divergence in this
  /// type.** Swift WhisperKit *emits* `[BLANK_AUDIO]` for silence, so
  /// defaulting to `true` diverges from it by design: `[BLANK_AUDIO]` is
  /// noise for the search/index consumers this crate targets, and making
  /// every one of them post-filter it was the worse default. Set this
  /// `false` ([`Self::clear_drop_blank_audio`]) to restore **exact Swift
  /// parity** — the filter is then skipped outright and the marker is
  /// emitted verbatim, one segment, byte-for-byte as before this option
  /// existed.
  ///
  /// Under [`ChunkingStrategy::Vad`], a wholly-silent stretch long enough
  /// to become a chunk of its own — the chunker is *contiguous*, so
  /// silence is never skipped, only cut around — decodes to nothing but
  /// the marker and is therefore emptied outright by this filter.
  ///
  /// **This option is consequently a merge rule as well as a decode
  /// filter.** An emptied chunk has no text, and
  /// [`merge_transcription_results`](crate::audio::whisper::result::merge_transcription_results)
  /// joins *every* result's text with `" "` — so an emptied one would
  /// surface as a bare separator (a doubled space between two speech runs;
  /// a leading or trailing one at the clip's edges).
  /// [`merge_transcription_results_with_options`](crate::audio::whisper::result::merge_transcription_results_with_options)
  /// is the merge that reads this option and **skips empty texts in the
  /// join** when it is set;
  /// [`WhisperKit::transcribe`](crate::audio::whisper::transcribe::WhisperKit::transcribe)
  /// uses it for its own VAD chunks, and it is what a caller folding a
  /// [`WhisperKit::transcribe_all`](crate::audio::whisper::transcribe::WhisperKit::transcribe_all)
  /// batch by hand should use too. Every result is still *merged* — its
  /// timings stay in the summed metrics; only its empty text is skipped.
  /// The plain [`merge_transcription_results`](crate::audio::whisper::result::merge_transcription_results)
  /// keeps Swift's join verbatim, empties included.
  ///
  /// Note the scope that gives the merge: it skips **empty texts**, not
  /// "blank chunks" — it cannot see why a result is empty. With this set,
  /// an empty result from *short audio* (any clip below
  /// [`Self::window_clip_time`] runs no window and returns one) is skipped
  /// from the join too. That is the intended reading — blank-dropping means
  /// empty chunks do not pollute the text — and not a further divergence:
  /// clear this option and Swift's join, bare separators and all, is back
  /// exactly.
  ///
  /// Speech-only audio is unaffected either way: it decodes no such
  /// segment, so the filter finds nothing to drop and the golden parity
  /// transcripts are identical under both settings.
  #[inline(always)]
  pub const fn drop_blank_audio(&self) -> bool {
    self.drop_blank_audio
  }
  /// Builder form of [`Self::set_drop_blank_audio`].
  #[must_use]
  #[inline(always)]
  pub const fn with_drop_blank_audio(mut self) -> Self {
    self.set_drop_blank_audio();
    self
  }
  /// Sets [`Self::drop_blank_audio`] to `true`.
  #[inline(always)]
  pub const fn set_drop_blank_audio(&mut self) -> &mut Self {
    self.drop_blank_audio = true;
    self
  }
  /// Builder form of [`Self::update_drop_blank_audio`].
  #[must_use]
  #[inline(always)]
  pub const fn maybe_drop_blank_audio(mut self, drop_blank_audio: bool) -> Self {
    self.update_drop_blank_audio(drop_blank_audio);
    self
  }
  /// Assigns [`Self::drop_blank_audio`] directly.
  #[inline(always)]
  pub const fn update_drop_blank_audio(&mut self, drop_blank_audio: bool) -> &mut Self {
    self.drop_blank_audio = drop_blank_audio;
    self
  }
  /// Sets [`Self::drop_blank_audio`] to `false` — blank-audio segments are
  /// emitted verbatim, restoring exact Swift parity.
  #[inline(always)]
  pub const fn clear_drop_blank_audio(&mut self) -> &mut Self {
    self.drop_blank_audio = false;
    self
  }

  // -- word_grouping --------------------------------------------------------
  /// How decoded tokens are grouped into words when
  /// [`Self::word_timestamps`] is on (coremlit issue #14). Defaults to
  /// [`WordGrouping::SwiftParity`] (coremlit issue #41 — stream parity with
  /// Swift as the default posture, reversing the #11 pin), which, read against
  /// Apple's actual `NLLanguage` raw values, means the space splitter for
  /// `zh`/`yue` and Unicode splitting for everything else,
  /// `ja`/`th`/`lo`/`my` included.
  ///
  /// [`WordGrouping::FineGrained`] is the product-quality opt-in instead — this
  /// port's long-standing behavior: Unicode splitting for all of the
  /// non-whitespace-delimited languages (`zh`/`ja`/`th`/`lo`/`my`/`yue`),
  /// space/punctuation splitting for everything else, so CJK gets fine-grained
  /// word timestamps (issue #11). See [`WordGrouping`]'s own doc for the table
  /// and for why the coarse phrase-blob grouping is a **Chinese-only** accident
  /// rather than a CJK policy. The two variants consequently differ only for
  /// `zh` and `yue`; this crate defaults to Swift's grouping and lets a caller
  /// ask for the fine-grained split by name.
  ///
  /// Inert unless [`Self::word_timestamps`] is set: word grouping only runs
  /// inside the DTW alignment pass. It never affects the transcript text,
  /// the tokens, or the segments — only how a segment's words are carved
  /// out of them.
  #[inline(always)]
  pub const fn word_grouping(&self) -> WordGrouping {
    self.word_grouping
  }
  /// Builder form of [`Self::set_word_grouping`].
  #[must_use]
  #[inline(always)]
  pub const fn with_word_grouping(mut self, word_grouping: WordGrouping) -> Self {
    self.set_word_grouping(word_grouping);
    self
  }
  /// Sets [`Self::word_grouping`] in place.
  #[inline(always)]
  pub const fn set_word_grouping(&mut self, word_grouping: WordGrouping) -> &mut Self {
    self.word_grouping = word_grouping;
    self
  }

  // -- alignment_gather -----------------------------------------------------
  /// How the per-token cross-attention rows are gathered into the DTW input
  /// when [`Self::word_timestamps`] is on (coremlit issue #41).
  ///
  /// Defaults to [`AlignmentGather::Complete`]: every row in full, no
  /// truncation, no IOSurface allocation, no row-pitch measurement and no
  /// dependence on any property of the host.
  ///
  /// [`AlignmentGather::SwiftParity`] is the opt-in. Swift's gather ignores
  /// its own `MLMultiArray` row strides and indexes both sides by the column
  /// count, which — against the padded rows CoreVideo gives its Float16
  /// pixel-buffer backing — silently truncates the final gathered row to its
  /// first `N * cols - (N - 1) * pitch` columns and leaves the rest reading
  /// storage nothing wrote. That `pitch` is measured on the running host,
  /// never assumed; the mode fails closed rather than guess one (see
  /// [`SegmentError::AlignmentPitchUnavailable`](crate::audio::whisper::error::SegmentError::AlignmentPitchUnavailable)),
  /// and what it substitutes for the unwritten storage is a stated assumption
  /// rather than an observation. See [`AlignmentGather`]'s own doc for the
  /// mechanism, the cited Swift lines, the three assumptions the opt-in
  /// carries, and why it was the truncated row — not the complete one — that
  /// held the 1417 s fixture on Swift's own windows.
  ///
  /// Inert unless [`Self::word_timestamps`] is set: the gather only runs
  /// inside the DTW alignment pass. Unlike [`Self::word_grouping`], though,
  /// its reach is not confined to a segment's words — changing it **can**
  /// move a word's end, and with it the segment's end, the next window's seek
  /// and the rest of the transcript. It applies to **every** word-timestamp
  /// window, including a single-window short-form clip with no seek cascade
  /// to accumulate — matching Swift, which has no such guard either — so
  /// short form is not exempt.
  ///
  /// Whether it *does* move anything on a given clip is that clip's measured
  /// result, not something the mechanism settles in advance. Measured: over
  /// one `add_word_timestamps` call the two variants put the last word's end,
  /// and the segment's, at 0.88 s against 1.58 s (`segment::tests`'
  /// `swift_parity_gather_truncates_final_alignment_row`); end to end they
  /// move a first window's end and the seek taken from it (`transcribe::
  /// tests`' `swift_parity_gather_moves_the_first_windows_end_and_the_next_seek`);
  /// and on `jfk.wav` / `openai_whisper-tiny` they instead agree word for
  /// word and both match official Swift
  /// (`jfk_tiny_word_timestamps_match_swift_and_this_clip_is_gather_invariant`,
  /// `coremlit/tests/whisper/parity_jfk.rs`). Each of those tests pins
  /// the measured output of its own fixture and nothing wider; see also
  /// [`AlignmentGather::SwiftParity`]'s "Short-form" section for the
  /// established / not-established split and what would settle it.
  #[inline(always)]
  pub const fn alignment_gather(&self) -> AlignmentGather {
    self.alignment_gather
  }
  /// Builder form of [`Self::set_alignment_gather`].
  #[must_use]
  #[inline(always)]
  pub const fn with_alignment_gather(mut self, alignment_gather: AlignmentGather) -> Self {
    self.set_alignment_gather(alignment_gather);
    self
  }
  /// Sets [`Self::alignment_gather`] in place.
  #[inline(always)]
  pub const fn set_alignment_gather(&mut self, alignment_gather: AlignmentGather) -> &mut Self {
    self.alignment_gather = alignment_gather;
    self
  }
}

// ---------------------------------------------------------------------
// ComputeOptions
// ---------------------------------------------------------------------

/// Default [`ComputeOptions::mel`] (Swift `ModelComputeOptions.melCompute`).
pub const DEFAULT_MEL_COMPUTE_UNITS: ComputeUnits = ComputeUnits::CpuAndGpu;
/// Default [`ComputeOptions::encoder`] (Swift
/// `ModelComputeOptions.audioEncoderCompute`, macOS 14+/iOS 17+ path).
pub const DEFAULT_ENCODER_COMPUTE_UNITS: ComputeUnits = ComputeUnits::CpuAndNeuralEngine;
/// Default [`ComputeOptions::decoder`] (Swift
/// `ModelComputeOptions.textDecoderCompute`).
pub const DEFAULT_DECODER_COMPUTE_UNITS: ComputeUnits = ComputeUnits::CpuAndNeuralEngine;

// `ComputeUnits::default()` is `All` (coremlit's own general-purpose
// default), which does NOT match WhisperKit's per-stage defaults above —
// so every field here needs a fn-default, never the bare form.
#[cfg(feature = "serde")]
fn default_mel_compute_units() -> ComputeUnits {
  DEFAULT_MEL_COMPUTE_UNITS
}
#[cfg(feature = "serde")]
fn default_encoder_compute_units() -> ComputeUnits {
  DEFAULT_ENCODER_COMPUTE_UNITS
}
#[cfg(feature = "serde")]
fn default_decoder_compute_units() -> ComputeUnits {
  DEFAULT_DECODER_COMPUTE_UNITS
}

/// Per-stage CoreML compute-unit selection (Swift `ModelComputeOptions`).
/// Defaults mirror Swift: mel = CPU+GPU, encoder/decoder = CPU+ANE.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ComputeOptions {
  /// Compute units for the mel-spectrogram feature extractor.
  #[cfg_attr(feature = "serde", serde(default = "default_mel_compute_units"))]
  mel: ComputeUnits,
  /// Compute units for the audio encoder.
  #[cfg_attr(feature = "serde", serde(default = "default_encoder_compute_units"))]
  encoder: ComputeUnits,
  /// Compute units for the text decoder.
  #[cfg_attr(feature = "serde", serde(default = "default_decoder_compute_units"))]
  decoder: ComputeUnits,
}

impl Default for ComputeOptions {
  fn default() -> Self {
    Self::new()
  }
}

impl ComputeOptions {
  /// Compute options matching Swift's `ModelComputeOptions` defaults.
  pub const fn new() -> Self {
    Self {
      mel: DEFAULT_MEL_COMPUTE_UNITS,
      encoder: DEFAULT_ENCODER_COMPUTE_UNITS,
      decoder: DEFAULT_DECODER_COMPUTE_UNITS,
    }
  }

  /// Compute units for the mel-spectrogram feature extractor.
  #[inline(always)]
  pub const fn mel(&self) -> ComputeUnits {
    self.mel
  }
  /// Builder form of [`Self::set_mel`].
  #[must_use]
  #[inline(always)]
  pub const fn with_mel(mut self, mel: ComputeUnits) -> Self {
    self.set_mel(mel);
    self
  }
  /// Sets [`Self::mel`] in place.
  #[inline(always)]
  pub const fn set_mel(&mut self, mel: ComputeUnits) -> &mut Self {
    self.mel = mel;
    self
  }

  /// Compute units for the audio encoder.
  #[inline(always)]
  pub const fn encoder(&self) -> ComputeUnits {
    self.encoder
  }
  /// Builder form of [`Self::set_encoder`].
  #[must_use]
  #[inline(always)]
  pub const fn with_encoder(mut self, encoder: ComputeUnits) -> Self {
    self.set_encoder(encoder);
    self
  }
  /// Sets [`Self::encoder`] in place.
  #[inline(always)]
  pub const fn set_encoder(&mut self, encoder: ComputeUnits) -> &mut Self {
    self.encoder = encoder;
    self
  }

  /// Compute units for the text decoder.
  #[inline(always)]
  pub const fn decoder(&self) -> ComputeUnits {
    self.decoder
  }
  /// Builder form of [`Self::set_decoder`].
  #[must_use]
  #[inline(always)]
  pub const fn with_decoder(mut self, decoder: ComputeUnits) -> Self {
    self.set_decoder(decoder);
    self
  }
  /// Sets [`Self::decoder`] in place.
  #[inline(always)]
  pub const fn set_decoder(&mut self, decoder: ComputeUnits) -> &mut Self {
    self.decoder = decoder;
    self
  }
}

// ---------------------------------------------------------------------
// Options
// ---------------------------------------------------------------------

/// Default [`Options::prewarm`]. Swift's `WhisperKitConfig.prewarm` is
/// `Bool? = nil`, resolved at call sites by `if let prewarm = config.prewarm,
/// prewarm` — nil skips prewarming — so that resolved value is `false`.
pub const DEFAULT_PREWARM: bool = false;
/// Default [`Options::load`]. Swift's `WhisperKitConfig.load` is
/// `Bool? = nil`, resolved by `config.load ?? (config.modelFolder != nil)`.
/// [`Options::new`] always requires a model folder, so that resolves to
/// `true`.
pub const DEFAULT_LOAD: bool = true;

#[cfg(feature = "serde")]
fn default_prewarm() -> bool {
  DEFAULT_PREWARM
}
// `bool::default()` is `false`, which does not match this field's `true`
// default — see `DEFAULT_LOAD`'s doc for the Swift resolution this ports.
#[cfg(feature = "serde")]
fn default_load() -> bool {
  DEFAULT_LOAD
}

/// Construction config for a WhisperKit pipeline: where to load the model
/// and tokenizer from, per-stage compute units, and load-time lifecycle
/// flags (Swift `WhisperKitConfig`, spec §5.3). Model auto-download is
/// deferred (spec §4.7); folders are always local.
///
/// No [`Default`]/zero-arg `new()`: there is no honest default model or
/// tokenizer folder, so construction always requires both (golden §1 — no
/// honest default means no `Default`).
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Options {
  /// Local folder containing the compiled (`.mlmodelc`) Whisper models.
  model_folder: PathBuf,
  /// Local folder containing the BPE tokenizer files.
  tokenizer_folder: PathBuf,
  /// Per-stage CoreML compute-unit selection.
  #[cfg_attr(feature = "serde", serde(default))]
  compute: ComputeOptions,
  /// Sequentially load-then-unload each model once before real use, to
  /// force ANE specialization up front instead of at first inference.
  #[cfg_attr(feature = "serde", serde(default = "default_prewarm"))]
  prewarm: bool,
  /// Load the models at construction time.
  #[cfg_attr(feature = "serde", serde(default = "default_load"))]
  load: bool,
}

impl Options {
  /// Construction config for the given model/tokenizer folders, with every
  /// other knob at its default. Not `const`: owned-path construction takes
  /// `impl Into<PathBuf>`.
  pub fn new(model_folder: impl Into<PathBuf>, tokenizer_folder: impl Into<PathBuf>) -> Self {
    Self {
      model_folder: model_folder.into(),
      tokenizer_folder: tokenizer_folder.into(),
      compute: ComputeOptions::new(),
      prewarm: DEFAULT_PREWARM,
      load: DEFAULT_LOAD,
    }
  }

  // -- model_folder -----------------------------------------------------
  /// Local folder containing the compiled (`.mlmodelc`) Whisper models.
  #[inline(always)]
  pub fn model_folder(&self) -> &Path {
    self.model_folder.as_path()
  }
  /// Builder form of [`Self::set_model_folder`].
  #[must_use]
  #[inline(always)]
  pub fn with_model_folder(mut self, model_folder: impl Into<PathBuf>) -> Self {
    self.set_model_folder(model_folder);
    self
  }
  /// Sets [`Self::model_folder`] in place.
  #[inline(always)]
  pub fn set_model_folder(&mut self, model_folder: impl Into<PathBuf>) -> &mut Self {
    self.model_folder = model_folder.into();
    self
  }

  // -- tokenizer_folder ---------------------------------------------------
  /// Local folder containing the BPE tokenizer files.
  #[inline(always)]
  pub fn tokenizer_folder(&self) -> &Path {
    self.tokenizer_folder.as_path()
  }
  /// Builder form of [`Self::set_tokenizer_folder`].
  #[must_use]
  #[inline(always)]
  pub fn with_tokenizer_folder(mut self, tokenizer_folder: impl Into<PathBuf>) -> Self {
    self.set_tokenizer_folder(tokenizer_folder);
    self
  }
  /// Sets [`Self::tokenizer_folder`] in place.
  #[inline(always)]
  pub fn set_tokenizer_folder(&mut self, tokenizer_folder: impl Into<PathBuf>) -> &mut Self {
    self.tokenizer_folder = tokenizer_folder.into();
    self
  }

  // -- compute ------------------------------------------------------------
  /// Per-stage CoreML compute-unit selection.
  #[inline(always)]
  pub const fn compute(&self) -> ComputeOptions {
    self.compute
  }
  /// Builder form of [`Self::set_compute`].
  #[must_use]
  #[inline(always)]
  pub const fn with_compute(mut self, compute: ComputeOptions) -> Self {
    self.set_compute(compute);
    self
  }
  /// Sets [`Self::compute`] in place.
  #[inline(always)]
  pub const fn set_compute(&mut self, compute: ComputeOptions) -> &mut Self {
    self.compute = compute;
    self
  }

  // -- prewarm (bool) -------------------------------------------------------
  /// Sequentially load-then-unload each model once before real use, to
  /// force ANE specialization up front instead of at first inference.
  #[inline(always)]
  pub const fn prewarm(&self) -> bool {
    self.prewarm
  }
  /// Builder form of [`Self::set_prewarm`].
  #[must_use]
  #[inline(always)]
  pub const fn with_prewarm(mut self) -> Self {
    self.set_prewarm();
    self
  }
  /// Sets [`Self::prewarm`] to `true`.
  #[inline(always)]
  pub const fn set_prewarm(&mut self) -> &mut Self {
    self.prewarm = true;
    self
  }
  /// Builder form of [`Self::update_prewarm`].
  #[must_use]
  #[inline(always)]
  pub const fn maybe_prewarm(mut self, prewarm: bool) -> Self {
    self.update_prewarm(prewarm);
    self
  }
  /// Assigns [`Self::prewarm`] directly.
  #[inline(always)]
  pub const fn update_prewarm(&mut self, prewarm: bool) -> &mut Self {
    self.prewarm = prewarm;
    self
  }
  /// Sets [`Self::prewarm`] to `false`.
  #[inline(always)]
  pub const fn clear_prewarm(&mut self) -> &mut Self {
    self.prewarm = false;
    self
  }

  // -- load (bool) ----------------------------------------------------------
  /// Load the models at construction time.
  #[inline(always)]
  pub const fn load(&self) -> bool {
    self.load
  }
  /// Builder form of [`Self::set_load`].
  #[must_use]
  #[inline(always)]
  pub const fn with_load(mut self) -> Self {
    self.set_load();
    self
  }
  /// Sets [`Self::load`] to `true`.
  #[inline(always)]
  pub const fn set_load(&mut self) -> &mut Self {
    self.load = true;
    self
  }
  /// Builder form of [`Self::update_load`].
  #[must_use]
  #[inline(always)]
  pub const fn maybe_load(mut self, load: bool) -> Self {
    self.update_load(load);
    self
  }
  /// Assigns [`Self::load`] directly.
  #[inline(always)]
  pub const fn update_load(&mut self, load: bool) -> &mut Self {
    self.load = load;
    self
  }
  /// Sets [`Self::load`] to `false`.
  #[inline(always)]
  pub const fn clear_load(&mut self) -> &mut Self {
    self.load = false;
    self
  }
}

#[cfg(test)]
mod tests;