bunsen 0.32.0

bunsen is a batteries included common library for burn
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
//! # The stream context: one transcription in progress.
//!
//! [`push`](WhisperStreamContext::write_read) is a fold: append to staging,
//! drain whole hops into the mel context, append the frames to the ring, offer
//! them to the clamp policy, offer the samples to the voice-activity gate, then
//! run whatever the emission policy says is due. The hop-alignment
//! requirement never reaches the caller — staging makes the API honest
//! against a sound card that hands over 480- or 1024-sample buffers.
//!
//! [`feed`](WhisperStreamContext::write) is the first half of that fold and
//! [`advance`](WhisperStreamContext::read) the second, so that a batch of
//! streams can be fed one at a time and advanced together by
//! [`advance_ready`](super::advance_ready).
//!
//! Nothing tensor-shaped crosses a window boundary. Continuity is three
//! host-side values: the seek pointer, the prompt carry, and the clock. The
//! ring holds every frame from `seek` onward and nothing before it.
//!
//! ## Regions
//!
//! With the `endpoint` trigger, a speech region closed by the gate is a
//! decode unit of its own: its frames are cut from the ring, decoded, and
//! committed with times off the parent stream's clock — region-as-
//! stream, without a second stream object. A full window is then decoded
//! only if speech is in progress inside it; a full window of silence is
//! skipped, not decoded, which is the gating half of voice activity.
//!
//! ## What a decode may touch
//!
//! Anything a provisional decode reaches takes `&self`: packaging asks the
//! clamp policy for a reference through `&self`, the model is pure, and the
//! prompt is read. That is what keeps drafts, when they arrive, from becoming
//! a second code path — and it is checkable today, through the
//! test-only probe.

use std::collections::VecDeque;

use burn::{
    Tensor,
    module::Module,
    prelude::{
        Backend,
        TensorData,
    },
};

use crate::{
    errors::{
        BunsenError,
        BunsenResult,
    },
    kits::speech::{
        silero_vad::{
            SileroVadContext,
            SileroVadContextConfig,
            SileroVadMeta,
        },
        whisper::{
            blocks::WhisperMeta,
            decode::{
                DecodeConfig,
                DecodedTokens,
                WhisperFallbackConfig,
                decode_with_fallback,
            },
            driver::{
                CommitRule,
                SpeechRegion,
                StreamClampPolicy,
                StreamClock,
                VoiceActivityFilter,
                WhisperStreamDriver,
                support::segments::split_window,
                transcript::{
                    TranscriptEvent,
                    TranscriptSegment,
                },
            },
        },
    },
    ops::signal::perceptive_audio::{
        PerceptiveAudioConversionContext,
        PerceptiveAudioConverterMeta,
    },
};

/// One context's due unit, packaged and ready to join a batch.
struct Pending<B: Backend> {
    /// Index into the contexts being advanced.
    context: usize,
    unit: Due,
    /// A draft rather than a commit.
    draft: bool,
    /// The prompt it decodes under; what it is batched by.
    prompt: Vec<i64>,
    /// `[1, n_mels, width]`.
    window: Tensor<B, 3>,
}

/// Advances every context that has a decode due, batching the decodes.
///
/// Repeats until no context has anything due, so a context with several
/// windows waiting gets them all; a context with nothing due but a draft
/// due contributes the draft, batched the same way. Returns each context's
/// emissions, in the order of `contexts`.
///
/// # Arguments
/// * `driver` - the driver the contexts were opened from.
/// * `contexts` - the streams, fed through
///   [`feed`](WhisperStreamContext::write) rather than
///   [`push`](WhisperStreamContext::write_read), so that nothing has been
///   decoded yet.
///
/// # Errors
/// As [`WhisperStreamContext::read`].
pub fn advance_ready<B: Backend>(
    driver: &WhisperStreamDriver<B>,
    contexts: &mut [WhisperStreamContext<B>],
) -> BunsenResult<Vec<Vec<TranscriptEvent>>> {
    let mut out: Vec<Vec<TranscriptEvent>> = vec![Vec::new(); contexts.len()];

    loop {
        // One due unit per context, with the prompt it would decode under.
        let mut pending: Vec<Option<Pending<B>>> = Vec::new();
        for (i, ctx) in contexts.iter_mut().enumerate() {
            ctx.skip_silence();
            let (unit, draft) = match ctx.next_due() {
                Some(unit) => (unit, false),
                None => match ctx.draft_unit() {
                    Some(unit) => (unit, true),
                    None => continue,
                },
            };
            let frames = ctx.frames_at(&unit);
            ctx.ensure_language(&frames);
            pending.push(Some(Pending {
                context: i,
                unit,
                draft,
                prompt: ctx.prompt_now(),
                window: ctx.package_padded(frames),
            }));
        }
        if pending.is_empty() {
            return Ok(out);
        }

        // Group by prompt, in order of first appearance.
        let mut groups: Vec<(Vec<i64>, Vec<usize>)> = Vec::new();
        for (k, item) in pending.iter().enumerate() {
            let prompt = &item.as_ref().expect("not yet taken").prompt;
            match groups.iter_mut().find(|(p, _)| p == prompt) {
                Some((_, members)) => members.push(k),
                None => groups.push((prompt.clone(), vec![k])),
            }
        }

        for (prompt, members) in groups {
            let windows: Vec<Tensor<B, 3>> = members
                .iter()
                .map(|&k| pending[k].as_ref().expect("not yet taken").window.clone())
                .collect();
            let batch = Tensor::cat(windows, 0);

            // The first rung of the ladder, batched; any rung above it is
            // the context's own, which is rare.
            let config = driver.decode_config(prompt);
            let first =
                driver
                    .whisper_model()
                    .decode_windows_full(batch, &config, driver.filters());

            for (row, k) in members.into_iter().enumerate() {
                let item = pending[k].take().expect("taken once");
                let ctx = &mut contexts[item.context];
                let decoded = ctx.ladder(&config, item.window, Some(first[row].clone()));
                if item.draft {
                    out[item.context].push(ctx.draft_from(item.unit, decoded)?);
                } else {
                    out[item.context].extend(ctx.commit_due(item.unit, decoded)?);
                }
            }
        }
    }
}

/// One stream: the only stateful type in the driver.
///
/// Opened by [`WhisperStreamDriver::new_context`]. Its tensor state &mdash; the
/// driver's handle, the mel carry, the frame ring, the VAD state &mdash; is
/// `Module` typed; everything else is host-side bookkeeping, small enough to
/// snapshot.
///
/// Not itself a `Module`, deliberately: `burn`'s derive treats every field
/// whose type mentions `B` as a module, `#[module(skip)]` or not, and
/// carries a skipped generic unchanged into the autodiff inner module, so
/// neither a boxed policy nor a policy type parameter survives it. The
/// policy stays behind its trait, boxed, and the context is `Clone + Debug`.
#[derive(Clone, Debug)]
pub struct WhisperStreamContext<B: Backend> {
    driver: WhisperStreamDriver<B>,

    /// The mel front end's streaming state; `None` once flushed.
    mel: Option<PerceptiveAudioConversionContext<B>>,

    /// `[1, frames, n_mels]` log-mels from `origin` onward; `None`
    /// when empty.
    frames: Option<Tensor<B, 3>>,

    /// Samples not yet a whole hop.
    staging: Vec<f32>,

    /// Samples pushed so far, staging included.
    samples_seen: usize,

    /// The stream frame index of the ring's first frame.
    origin: usize,

    /// The stream frame index the next window starts at.
    seek: usize,

    clock: StreamClock,

    /// Every committed id, in order.
    transcript: Vec<i64>,

    /// Where the prompt carry starts in the transcript: upstream's
    /// `prompt_reset_since`, moved past a decode that needed a high
    /// temperature so a failure does not feed the next window.
    prompt_reset: usize,

    /// Media time (samples seen) at the last draft or commit; drafts are
    /// paced from it.
    last_draft: usize,

    /// The language the prompt names: configured, or detected from the
    /// first window decoded; `None` until then on a detecting driver.
    language: Option<String>,

    clamp: Box<dyn StreamClampPolicy<B>>,

    /// Voice activity, when the driver has a VAD and the policy wants
    /// endpoints.
    vad: Option<VoiceActivity<B>>,

    finished: bool,
}

/// The voice-activity half of a stream: Silero's state, the filter, and the
/// regions it has closed but the decode has not yet consumed.
#[derive(Clone, Debug)]
struct VoiceActivity<B: Backend> {
    /// Silero's recurrent state; `None` only while a step is in flight.
    context: Option<SileroVadContext<B>>,

    filter: VoiceActivityFilter,

    /// Samples not yet a whole chunk.
    staging: Vec<f32>,

    /// Padding on each side of a region, in samples.
    pad: usize,

    /// The encoder grid closed regions are snapped onto, in samples.
    grid: usize,

    /// Closed regions, padded and snapped, oldest first.
    regions: VecDeque<SpeechRegion>,

    /// Where the last closed region ended, so the next one's padding cannot
    /// reach back into it.
    last_end: usize,
}

/// One decode unit: `count` frames from stream frame `start`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Due {
    start: usize,
    count: usize,
}

impl<B: Backend> WhisperStreamContext<B> {
    /// Initialize a new context.
    pub fn init(
        driver: WhisperStreamDriver<B>,
        clock: StreamClock,
        clamp: Box<dyn StreamClampPolicy<B>>,
    ) -> Self {
        let mel = driver.mel_converter().new_context(1);

        let vad = match (driver.silero_vad_model(), driver.va_filter_config()) {
            (Some(model), Some(gate)) if driver.config().emission.triggers.endpoint => {
                let device = model.devices()[0].clone();
                Some(VoiceActivity {
                    context: Some(
                        SileroVadContextConfig::new(model.sample_rate()).init(model, &device),
                    ),
                    filter: gate.init(),
                    staging: Vec::new(),
                    pad: gate.speech_pad_samples(),
                    grid: driver.encoder_grid(),
                    regions: VecDeque::new(),
                    last_end: 0,
                })
            }
            _ => None,
        };

        let language = driver.config().language.clone();
        Self {
            driver,
            mel: Some(mel),
            frames: None,
            staging: Vec::new(),
            samples_seen: 0,
            origin: 0,
            seek: 0,
            clock,
            transcript: Vec::new(),
            prompt_reset: 0,
            last_draft: 0,
            language,
            clamp,
            vad,
            finished: false,
        }
    }

    // ---- observation -------------------------------------------------

    /// The stream's clock.
    pub fn clock(&self) -> &StreamClock {
        &self.clock
    }

    /// Every committed id, in order.
    pub fn transcript(&self) -> &[i64] {
        &self.transcript
    }

    /// Samples pushed so far.
    pub fn samples_seen(&self) -> usize {
        self.samples_seen
    }

    /// The stream frame index the next window starts at.
    pub fn seek(&self) -> usize {
        self.seek
    }

    /// Frames produced so far.
    pub fn frames_seen(&self) -> usize {
        self.origin + self.ring_len()
    }

    /// Frames past the seek pointer, waiting for a decode.
    pub fn pending_frames(&self) -> usize {
        self.frames_seen() - self.seek
    }

    /// Whether the gate currently has a region open: speech in progress.
    /// Always `false` without voice activity.
    pub fn is_speaking(&self) -> bool {
        self.vad.as_ref().is_some_and(|v| v.filter.is_open())
    }

    /// Closed regions not yet decoded.
    pub fn regions_pending(&self) -> usize {
        self.vad.as_ref().map_or(0, |v| v.regions.len())
    }

    /// Whether [`flush`](Self::end_read) or [`end_input`](Self::end_input) has
    /// run.
    pub fn is_finished(&self) -> bool {
        self.finished
    }

    fn ring_len(&self) -> usize {
        self.frames.as_ref().map_or(0, |f| f.dims()[1])
    }

    fn hop(&self) -> usize {
        self.driver.mel_converter().hop()
    }

    // ---- input -------------------------------------------------------

    /// Anchor the clock, then [`write_read`](`Self::write_read`).
    ///
    /// # Errors
    /// As [`push`](Self::write_read) and [`StreamClock::anchor`].
    pub fn anchor_write_read(
        &mut self,
        time: f64,
        samples: &[f32],
    ) -> BunsenResult<Vec<TranscriptEvent>> {
        self.clock.anchor(self.samples_seen, time)?;
        self.write_read(samples)
    }

    /// Push samples, emit all finalized [`TranscriptEvent`]s.
    ///
    /// [`feed`](Self::write) then [`advance`](Self::read).
    ///
    /// # Errors
    ///
    /// [`BunsenError::Invalid`] after the stream has ended.
    pub fn write_read(
        &mut self,
        samples: &[f32],
    ) -> BunsenResult<Vec<TranscriptEvent>> {
        self.write(samples)?;
        self.read()
    }

    /// Takes samples in without decoding: the front end and the gate run,
    /// nothing else. Pair with [`advance`](Self::read), or with
    /// [`advance_ready`](super::advance_ready) across many streams.
    ///
    /// # Errors
    /// [`BunsenError::Invalid`] after the stream has ended.
    pub fn write(
        &mut self,
        samples: &[f32],
    ) -> BunsenResult<()> {
        if self.finished {
            return Err(BunsenError::Invalid(
                "the stream has ended; nothing more can be fed".to_string(),
            ));
        }

        self.staging.extend_from_slice(samples);
        self.samples_seen += samples.len();
        if let Some(vad) = &mut self.vad {
            vad.staging.extend_from_slice(samples);
        }

        self.drain_staging(false)?;
        self.run_vad(false);
        Ok(())
    }

    /// Runs every decode that is due, and returns what became final.
    pub fn read(&mut self) -> BunsenResult<Vec<TranscriptEvent>> {
        let mut out = Vec::new();
        loop {
            self.skip_silence();
            let Some(unit) = self.next_due() else {
                break;
            };
            let window = self.frames_at(&unit);
            self.ensure_language(&window);
            let decoded = self.decode_frames(window);
            out.extend(self.commit_due(unit, decoded)?);
        }
        if let Some(unit) = self.draft_unit() {
            let window = self.frames_at(&unit);
            self.ensure_language(&window);
            let decoded = self.decode_frames(window);
            out.push(self.draft_from(unit, decoded)?);
        }
        Ok(out)
    }

    /// Ends the stream and decodes whatever is left past the seek pointer:
    /// [`end_input`](Self::end_input) then [`advance`](Self::read).
    ///
    /// Idempotent; a second flush returns nothing.
    pub fn end_read(&mut self) -> BunsenResult<Vec<TranscriptEvent>> {
        self.end_input()?;
        self.read()
    }

    /// Ends the stream's input: flushes the front end, drops Whisper's
    /// trailing frame, and closes the gate. What that leaves due is decoded
    /// by the next [`advance`](Self::read).
    ///
    /// Idempotent.
    pub fn end_input(&mut self) -> BunsenResult<()> {
        if self.finished {
            return Ok(());
        }
        self.finished = true;

        self.drain_staging(true)?;

        if let Some(mel) = self.mel.take()
            && let Some(tail) = mel.finish()
        {
            self.ingest(tail);
        }

        // Whisper's `stft[..., :-1]`: the stream's last frame is the end
        // padding's, and goes.
        if let Some(frames) = self.frames.take() {
            let n = frames.dims()[1];
            self.frames = (n > 1).then(|| frames.slice_dim(1, 0..n as isize - 1));
        }

        self.run_vad(true);
        Ok(())
    }

    /// Moves whole hops from staging into the front end.
    ///
    /// The first chunk must be long enough to produce a frame under the
    /// start padding, so it waits for a window's worth of samples; after
    /// that a hop at a time is enough. Flushing pads whatever remains with
    /// silence up to that minimum, as upstream pads a clip; a stream that
    /// never received a sample flushes to nothing.
    fn drain_staging(
        &mut self,
        flushing: bool,
    ) -> BunsenResult<()> {
        let mel = self.driver.mel_converter();
        let (hop, n_fft) = (mel.hop(), mel.n_fft());
        let first = self.mel.as_ref().is_some_and(|ctx| ctx.carry().is_none());
        let minimum = if first {
            n_fft.div_ceil(hop) * hop
        } else {
            hop
        };

        let mut whole = self.staging.len() / hop * hop;
        if flushing {
            if self.staging.is_empty() {
                return Ok(());
            }
            whole = self.staging.len().div_ceil(hop).max(minimum / hop) * hop;
            self.staging.resize(whole, 0.0);
        } else if whole < minimum {
            return Ok(());
        }

        let chunk: Vec<f64> = self.staging.drain(..whole).map(f64::from).collect();
        let device = self.driver.devices()[0].clone();
        let waves: Tensor<B, 2> = Tensor::from_data(TensorData::new(chunk, [1, whole]), &device);

        let ctx = self
            .mel
            .take()
            .expect("the front end is open until the input ends");
        let (frames, ctx) = ctx.transform(waves)?;
        self.mel = Some(ctx);
        self.ingest(frames);
        Ok(())
    }

    /// Appends frames to the ring, offering them to the clamp policy first.
    fn ingest(
        &mut self,
        new: Tensor<B, 3>,
    ) {
        self.clamp.observe(new.clone());
        self.frames = Some(match self.frames.take() {
            Some(ring) => Tensor::cat(vec![ring, new], 1),
            None => new,
        });
    }

    /// Runs Silero over every whole chunk in the VAD's staging, steps the
    /// gate, and queues the regions it closes. Flushing pads the last
    /// chunk with silence and closes an open region at the true length.
    fn run_vad(
        &mut self,
        flushing: bool,
    ) {
        let total = self.samples_seen;
        let Some(vad) = &mut self.vad else {
            return;
        };
        let model = self
            .driver
            .silero_vad_model()
            .expect("a VAD is attached when voice activity is on");
        let chunk = model.chunk_size();

        if flushing && !vad.staging.is_empty() {
            let whole = vad.staging.len().div_ceil(chunk) * chunk;
            vad.staging.resize(whole, 0.0);
        }
        let whole = vad.staging.len() / chunk * chunk;
        if whole > 0 {
            let steps = whole / chunk;
            let samples: Vec<f32> = vad.staging.drain(..whole).collect();
            let device = model.devices()[0].clone();
            let chunks: Tensor<B, 3> =
                Tensor::from_data(TensorData::new(samples, [steps, 1, chunk]), &device);

            let context = vad.context.take().expect("present between steps");
            let (probs, context) = model.context_forward_sequence(chunks, context);
            vad.context = Some(context);

            let probs: Vec<f32> = probs.to_data().convert::<f32>().to_vec().unwrap();
            for p in probs {
                if let Some(raw) = vad.filter.step(p) {
                    vad.enqueue(raw, total);
                }
            }
        }

        if flushing && let Some(raw) = vad.filter.clone().finish(total) {
            vad.enqueue(raw, total);
        }
    }

    // ---- scheduling --------------------------------------------------

    /// With endpoints on, drops full windows that hold no speech: nothing
    /// closed inside them, and nothing open in them.
    fn skip_silence(&mut self) {
        let width = self.driver.window_frames();
        let hop = self.hop();
        loop {
            let Some(vad) = &self.vad else {
                return;
            };
            if self.pending_frames() < width {
                return;
            }
            let (from, to) = (self.seek * hop, (self.seek + width) * hop);
            let closed_in = vad.regions.iter().any(|r| r.end > from && r.start < to);
            let open_in = vad.filter.open_since().is_some_and(|s| s < to);
            if closed_in || open_in {
                return;
            }
            self.seek += width;
            self.drop_before_seek();
        }
    }

    /// The next decode unit, if one is due.
    ///
    /// With endpoints on: the oldest closed region reaching past the seek
    /// pointer, a window at a time; else a full window, only while speech
    /// is in progress inside it. Without: a full window, and at the end of
    /// input whatever remains.
    fn next_due(&self) -> Option<Due> {
        let width = self.driver.window_frames();
        let hop = self.hop();
        let available = self.frames_seen();

        if let Some(vad) = &self.vad {
            for region in &vad.regions {
                let (rs, re) = ((region.start / hop), (region.end / hop));
                if re <= self.seek {
                    continue;
                }
                let start = rs.max(self.seek);
                let count = (re - start).min(width);
                if start + count <= available {
                    return Some(Due { start, count });
                }
                // Its frames are still in the front end; at the end of
                // input, take what there is.
                return (self.finished && available > start).then(|| Due {
                    start,
                    count: available - start,
                });
            }

            if self.driver.config().emission.triggers.window_full && self.pending_frames() >= width
            {
                let to = (self.seek + width) * hop;
                if vad.filter.open_since().is_some_and(|s| s < to) {
                    return Some(Due {
                        start: self.seek,
                        count: width,
                    });
                }
            }
            return None;
        }

        if self.pending_frames() >= width {
            return Some(Due {
                start: self.seek,
                count: width,
            });
        }
        (self.finished && self.pending_frames() > 0).then(|| Due {
            start: self.seek,
            count: self.pending_frames(),
        })
    }

    /// The frames of a due unit: `[1, count, n_mels]`.
    fn frames_at(
        &self,
        unit: &Due,
    ) -> Tensor<B, 3> {
        let ring = self.frames.as_ref().expect("due frames exist");
        let start = (unit.start - self.origin) as isize;
        ring.clone()
            .slice_dim(1, start..start + unit.count as isize)
    }

    // ---- decoding ----------------------------------------------------

    /// Packages a window against the clamp policy's reference and pads it
    /// out to the model's width: `[1, n_mels, width]`. Takes `&self`.
    fn package_padded(
        &self,
        window: Tensor<B, 3>,
    ) -> Tensor<B, 3> {
        let reference = self.clamp.reference(window.clone());
        let packaged = self.driver.front_end().package_window(window, reference);

        let width = self.driver.window_frames();
        let [_, n_mels, have] = packaged.dims();
        if have < width {
            let pad = Tensor::zeros([1, n_mels, width - have], &packaged.device());
            Tensor::cat(vec![packaged, pad], 2)
        } else {
            packaged
        }
    }

    /// Packages and decodes a window, up the temperature ladder. Takes
    /// `&self`: with [`frames_at`](Self::frames_at) this is the whole of a
    /// provisional decode.
    fn decode_frames(
        &self,
        window: Tensor<B, 3>,
    ) -> DecodedTokens {
        let base = self.driver.decode_config(self.prompt_now());
        self.ladder(&base, self.package_padded(window), None)
    }

    /// Decodes a packaged window up the ladder, encoding it only if a rung
    /// past `first` is needed.
    ///
    /// # Arguments
    /// * `base` - the decode config at temperature zero.
    /// * `window` - `[1, n_mels, width]`, packaged.
    /// * `first` - the first rung's result when the caller has it.
    fn ladder(
        &self,
        base: &DecodeConfig,
        window: Tensor<B, 3>,
        first: Option<DecodedTokens>,
    ) -> DecodedTokens {
        let model = self.driver.whisper_model();
        let mut xa: Option<Tensor<B, 3>> = None;
        decode_with_fallback(
            &self.driver.config().fallback,
            base,
            first,
            |config| {
                let xa = xa
                    .get_or_insert_with(|| model.forward_encoder(window.clone()))
                    .clone();
                model
                    .decode_features_full(xa, config, self.driver.filters())
                    .pop()
                    .expect("one row in, one row out")
            },
            |ids| self.text_of(ids),
        )
    }

    /// The text of some ids, when the driver can say.
    fn text_of(
        &self,
        ids: &[i64],
    ) -> Option<String> {
        let detokenizer = self.driver.detokenizer()?;
        detokenizer
            .detokenize(&self.driver.token_layout().text_ids(ids))
            .ok()
    }

    /// The prompt for the next window: the sot sequence, preceded by the
    /// transcript's tail after `<|startofprev|>` when carrying is on.
    fn prompt_now(&self) -> Vec<i64> {
        let prompt = self.sot_now();
        let carried = &self.transcript[self.prompt_reset.min(self.transcript.len())..];
        if !self.driver.config().condition_on_previous_text || carried.is_empty() {
            return prompt;
        }

        // Upstream keeps `n_text_ctx / 2 - 1` tokens of context.
        let keep = self.driver.whisper_model().max_text_ctx() / 2 - 1;
        let tail = &carried[carried.len().saturating_sub(keep)..];

        let mut out = Vec::with_capacity(1 + tail.len() + prompt.len());
        out.push(self.driver.token_layout().ids().sot_prev);
        out.extend_from_slice(tail);
        out.extend_from_slice(&prompt);
        out
    }

    /// Detects the stream's language from `frames` when the driver leaves
    /// it to be detected and no window has been decoded yet: upstream's
    /// `detect_language`, on the same features the decode will use.
    fn ensure_language(
        &mut self,
        frames: &Tensor<B, 3>,
    ) {
        if self.language.is_some() || !self.driver.detects_language() {
            return;
        }
        let model = self.driver.whisper_model();
        let xa = model.forward_encoder(self.package_padded(frames.clone()));
        let token = model.detect_language(xa, self.driver.token_layout().ids())[0];
        let code = self
            .driver
            .token_layout()
            .language_code(token)
            .expect("detection picks a language token");
        self.language = Some(code.to_string());
    }

    /// The language the stream's prompt names, once known.
    pub fn language(&self) -> Option<&str> {
        self.language.as_deref()
    }

    /// The sot sequence for this stream: the driver's, with the stream's
    /// language.
    fn sot_now(&self) -> Vec<i64> {
        self.driver
            .sot_sequence(self.language.as_deref())
            .expect("the language is known before a prompt is built")
    }

    /// Commits a decode of a due unit: records the ids, advances the seek
    /// pointer, drops the consumed frames and regions, and places the
    /// segments on the clock.
    ///
    /// A window the fallback policy calls silence (its no-speech
    /// probability over the threshold, its log probability poor) is
    /// skipped whole: nothing is emitted and the seek moves past it.
    ///
    /// Without timestamps the unit is one segment and the seek advances
    /// past it. With them the decode is split on its timestamps
    /// ([`split_window`]); the seek advances to the last closed timestamp,
    /// and the unfinished tail is either dropped, to be decoded again with
    /// more audio behind it (`CommitRule::Complete`, which is what
    /// upstream's seek loop does), or emitted as a draft first
    /// (`CommitRule::LastTimestamp`).
    ///
    /// A decode that needed a temperature above 0.5 resets the prompt
    /// carry, as upstream does, so a failure does not feed the next window.
    fn commit_due(
        &mut self,
        unit: Due,
        decoded: DecodedTokens,
    ) -> BunsenResult<Vec<TranscriptEvent>> {
        let hop = self.hop();
        let mut out = Vec::new();

        let skip = self
            .driver
            .config()
            .fallback
            .should_skip(decoded.no_speech_prob.map(f64::from), decoded.avg_logprob());
        let tokens = decoded.tokens;

        if skip {
            self.seek = unit.start + unit.count;
        } else if self.driver.config().timestamps {
            let split = split_window(
                &tokens,
                self.driver.token_layout().ids(),
                unit.count,
                self.driver.frames_per_timestamp(),
            );
            for segment in split.segments {
                let emission = self.segment_at(
                    unit.start + segment.start,
                    unit.start + segment.end,
                    segment.tokens,
                )?;
                self.transcript.extend_from_slice(&emission.tokens);
                out.push(TranscriptEvent::Committed(emission));
            }
            if !split.tail.is_empty()
                && self.driver.config().emission.commit == CommitRule::LastTimestamp
            {
                let opens = (split.tail[0] - self.driver.token_layout().ids().timestamp_begin)
                    as usize
                    * self.driver.frames_per_timestamp();
                // A tail opening past the unit's audio covers nothing yet;
                // it is decoded again with more audio behind it.
                if opens < unit.count {
                    let draft =
                        self.segment_at(unit.start + opens, unit.start + unit.count, split.tail)?;
                    out.push(TranscriptEvent::Draft(draft));
                }
            }
            // Always forward, never past the unit.
            self.seek = unit.start + split.advance.clamp(1, unit.count);
        } else {
            let segment = self.segment_at(unit.start, unit.start + unit.count, tokens)?;
            self.transcript.extend_from_slice(&segment.tokens);
            out.push(TranscriptEvent::Committed(segment));
            self.seek = unit.start + unit.count;
        }

        if !self.driver.config().condition_on_previous_text
            || WhisperFallbackConfig::resets_prompt(decoded.temperature)
        {
            self.prompt_reset = self.transcript.len();
        }

        self.last_draft = self.samples_seen;
        self.drop_before_seek();

        if let Some(vad) = &mut self.vad {
            let consumed = self.seek * hop;
            while vad.regions.front().is_some_and(|r| r.end <= consumed) {
                vad.regions.pop_front();
            }
        }

        Ok(out)
    }

    /// The draft due, if one is: under the `interval` trigger, while speech
    /// is in progress, once an interval of media time has passed since the
    /// last draft or commit, everything past the seek pointer.
    fn draft_unit(&self) -> Option<Due> {
        let interval = self.driver.interval_samples()?;
        let count = self.pending_frames();
        let due = !self.finished
            && count > 0
            && self.is_speaking()
            && self.samples_seen.saturating_sub(self.last_draft) >= interval;
        due.then_some(Due {
            start: self.seek,
            count,
        })
    }

    /// Emits a decode of a draft unit as a draft: on the clock, detokenized
    /// when the driver can, and touching nothing but the draft pacing. It
    /// covers all audio since the last commit and supersedes the previous
    /// draft whole.
    fn draft_from(
        &mut self,
        unit: Due,
        decoded: DecodedTokens,
    ) -> BunsenResult<TranscriptEvent> {
        self.last_draft = self.samples_seen;
        Ok(TranscriptEvent::Draft(self.segment_at(
            unit.start,
            unit.start + unit.count,
            decoded.tokens,
        )?))
    }

    /// A segment over stream frames `[start, end)`, timed through the clock
    /// and detokenized when the driver can.
    fn segment_at(
        &self,
        start: usize,
        end: usize,
        tokens: Vec<i64>,
    ) -> BunsenResult<TranscriptSegment> {
        let hop = self.hop();
        let text = match self.driver.detokenizer() {
            Some(detokenizer) => {
                Some(detokenizer.detokenize(&self.driver.token_layout().text_ids(&tokens))?)
            }
            None => None,
        };
        Ok(TranscriptSegment {
            start: self.clock.time_at(start * hop),
            end: self.clock.time_at(end * hop),
            tokens,
            text,
        })
    }

    /// Retains the ring from the seek pointer onward, nothing before it.
    fn drop_before_seek(&mut self) {
        let drop = (self.seek - self.origin) as isize;
        self.frames = self.frames.take().and_then(|ring| {
            let n = ring.dims()[1] as isize;
            (drop < n).then(|| ring.slice_dim(1, drop..n))
        });
        self.origin = self.seek;
    }
}

impl<B: Backend> VoiceActivity<B> {
    /// Pads a raw region as far as the stream allows, snaps it outward onto
    /// the encoder grid, and queues it.
    ///
    /// The start pad cannot reach back into the previous region; the end
    /// pad cannot reach past the samples seen, which at close time are at
    /// least `min_silence` past the raw end &mdash; enough for the pad under
    /// both presets.
    fn enqueue(
        &mut self,
        raw: SpeechRegion,
        total: usize,
    ) {
        let start = raw.start.saturating_sub(self.pad).max(self.last_end);
        let end = (raw.end + self.pad).min(total).max(start);
        let mut region = SpeechRegion::new(start, end).snap_outward(self.grid);
        region.start = region.start.max(self.last_end);
        self.last_end = region.end;
        self.regions.push_back(region);
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use serial_test::serial;

    use super::*;
    use crate::{
        burner::module::ModuleInit,
        errors::BunsenResult,
        kits::{
            speech::whisper::{
                Whisper,
                blocks::WhisperApiConfig,
                decode::GreedyDecodeConfig,
                driver::{
                    DecodeTriggers,
                    EmissionPolicy,
                    PerWindow,
                    RunningMaxClamp,
                    WhisperSpecialIds,
                    WhisperTokenLayout,
                    support::drop_last_frame,
                    whisper_stream_context::advance_ready,
                    whisper_stream_driver::WhisperStreamDriverConfig,
                },
                logit_filters::LogitFilter,
            },
            tokens::Detokenizer,
        },
        support::testing::PerformanceBackend,
    };

    type B = PerformanceBackend;
    type Device = burn::prelude::Device<B>;

    /// A layout small enough for a tiny model: 5 base ranks, 1 language.
    fn tiny_layout() -> WhisperSpecialIds {
        WhisperSpecialIds::new(5, 1).unwrap()
    }

    /// A tiny model whose vocabulary fits the tiny layout and whose window
    /// is 16 frames (2560 samples), so a short clip has several windows.
    /// Seeded, so a run is the same run on the same backend.
    fn tiny_model_on<B: Backend>(device: &B::Device) -> Whisper<B> {
        B::seed(device, 7);
        WhisperApiConfig::new(
            /* n_mels */ 8,
            /* vocab_size */ tiny_layout().n_vocab(),
            /* d_model */ 64,
            /* max_audio_ctx */ 16,
            /* n_encoder_layers */ 1,
            /* max_text_ctx */ 16,
            /* n_decoder_layers */ 1,
        )
        .init(device)
    }

    fn config(carry: bool) -> WhisperStreamDriverConfig {
        WhisperStreamDriverConfig::new()
            .with_language(Some("en".to_string()))
            .with_max_tokens(4)
            .with_condition_on_previous_text(carry)
    }

    fn driver<B: Backend>(
        device: &B::Device,
        carry: bool,
    ) -> WhisperStreamDriver<B> {
        config(carry)
            .init_with_layout(
                tiny_model_on::<B>(device),
                WhisperTokenLayout::new(tiny_layout()),
                device,
            )
            .unwrap()
    }

    /// The rate the tiny model, and every clip here, is at.
    const RATE: usize = 16_000;

    fn clock() -> StreamClock {
        StreamClock::uniform(RATE)
    }

    /// A deterministic 1.05 s clip: a tone under a bell-shaped envelope
    /// peaking mid-clip, a rising chirp, and a little noise. The loudest
    /// frames are in the middle on purpose, so the global maximum is never
    /// in the trailing frame that packaging drops.
    fn clip() -> Vec<f32> {
        clip_seeded(0.5, 440.0)
    }

    fn clip_seeded(
        peak_at: f32,
        tone_hz: f32,
    ) -> Vec<f32> {
        let n = 16_800;
        (0..n)
            .map(|i| {
                let t = i as f32 / RATE as f32;
                let envelope = (-(t - peak_at).powi(2) * 20.0).exp();
                let tone = 0.6 * envelope * (2.0 * std::f32::consts::PI * tone_hz * t).sin();
                let chirp =
                    0.2 * (2.0 * std::f32::consts::PI * (3_100.0 * t + 800.0 * t * t)).sin();
                let noise = 0.05 * (((i * 7919) % 1000) as f32 / 500.0 - 1.0);
                tone + chirp + noise
            })
            .collect()
    }

    /// Chunk sizes from a seeded generator: 1 to 1200 samples, so most are
    /// not hop multiples and staging is exercised.
    fn random_sizes(
        seed: usize,
        total: usize,
    ) -> Vec<usize> {
        let mut state = seed;
        let mut sizes = Vec::new();
        let mut left = total;
        while left > 0 {
            state = state
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1);
            let size = ((state >> 33) as usize % 1200 + 1).min(left);
            sizes.push(size);
            left -= size;
        }
        sizes
    }

    fn push_in_pieces(
        ctx: &mut WhisperStreamContext<B>,
        audio: &[f32],
        sizes: &[usize],
    ) -> Vec<TranscriptEvent> {
        let mut out = Vec::new();
        let mut at = 0;
        for &size in sizes {
            out.extend(ctx.write_read(&audio[at..at + size]).unwrap());
            at += size;
        }
        assert_eq!(at, audio.len());
        out.extend(ctx.end_read().unwrap());
        out
    }

    fn tokens_of(emissions: &[TranscriptEvent]) -> Vec<Vec<i64>> {
        emissions
            .iter()
            .map(|e| e.segment().tokens.clone())
            .collect()
    }

    /// The whole clip through the front end in one call, joined with its
    /// tail: what `package_mels` and `decode_chunked` start from.
    fn joined_mels(
        driver: &WhisperStreamDriver<B>,
        audio: &[f32],
        device: &Device,
    ) -> Tensor<B, 3> {
        let n = audio.len();
        let waves: Tensor<B, 2> = Tensor::from_data(
            TensorData::new(
                audio.iter().map(|&v| f64::from(v)).collect::<Vec<_>>(),
                [1, n],
            ),
            device,
        );
        let (mels, ctx) = driver
            .mel_converter()
            .new_context(1)
            .transform(waves)
            .unwrap();
        match ctx.finish() {
            Some(tail) => Tensor::cat(vec![mels, tail], 1),
            None => mels,
        }
    }

    fn greedy_config(driver: &WhisperStreamDriver<B>) -> GreedyDecodeConfig {
        GreedyDecodeConfig::new(driver.prompt().to_vec(), driver.token_layout().ids().eot)
            .with_max_tokens(driver.config().max_tokens)
    }

    /// **I5, against the one-shot path.** One push of the whole clip, with
    /// the running-maximum policy fed everything before the first decode,
    /// is `decode_chunked` over `package_mels` &mdash; window for window,
    /// id for id.
    #[test]
    #[serial]
    fn test_single_push_matches_decode_chunked() {
        let device = Device::default();
        let driver = driver(&device, false);
        let audio = clip();

        let mut ctx = driver.new_context(clock(), RunningMaxClamp::new()).unwrap();
        let mut emissions = ctx.write_read(&audio).unwrap();
        emissions.extend(ctx.end_read().unwrap());

        let expected = driver.whisper_model().decode_chunked(
            driver
                .front_end()
                .package_mels(joined_mels(&driver, &audio, &device)),
            &greedy_config(&driver),
        );

        assert_eq!(expected.len(), 7, "6 full windows and a remainder");
        assert_eq!(tokens_of(&emissions), expected);
        assert!(emissions.iter().all(TranscriptEvent::is_committed));
        assert_eq!(
            ctx.transcript(),
            expected.concat(),
            "the transcript is the committed ids, in order",
        );
    }

    /// The chunking half of I5, stated as the equality caveat says it must
    /// be: the windows two streams decoded agree within tolerance always,
    /// their segments sit at the same times, and their ids agree whenever
    /// the windows are bit-identical.
    ///
    /// The front end's chunk-invariance is approximate on some backends (a
    /// matmul's accumulation order changes with the chunk), and an untrained
    /// model turns a last-digit difference into a flipped argmax. A trained
    /// model on speech does not; that is the validation crate's gate.
    fn assert_same_stream(
        a: &[TranscriptEvent],
        b: &[TranscriptEvent],
        label: &str,
    ) {
        assert_eq!(a.len(), b.len(), "{label}: emission count");

        for (x, y) in a.iter().zip(b) {
            assert_eq!(x, y);
            assert_eq!(x.segment().start, y.segment().start, "{label}: start");
            assert_eq!(x.segment().end, y.segment().end, "{label}: end");
        }
    }

    /// **I5, against chunking.** Random-sized pushes, most of them not hop
    /// multiples, decode the windows one push decodes &mdash; and one push
    /// decodes exactly what packaging each window by hand gives.
    #[test]
    #[serial]
    fn test_random_pushes_match_single_push() {
        let device = Device::default();
        let driver = driver(&device, false);
        let audio = clip();

        let mut whole = driver.new_context(clock(), PerWindow).unwrap();
        let mut expected = whole.write_read(&audio).unwrap();
        expected.extend(whole.end_read().unwrap());

        for seed in [1, 2, 3] {
            let mut ctx = driver.new_context(clock(), PerWindow).unwrap();
            let got = push_in_pieces(&mut ctx, &audio, &random_sizes(seed, audio.len()));
            assert_same_stream(&got, &expected, &format!("seed {seed}"));
        }

        // A dynamic policy is the same policy, and the same chunking is the
        // same arithmetic, so this one is exact.
        let boxed: Box<dyn StreamClampPolicy<B>> = Box::new(PerWindow);
        let mut dynamic = driver.new_context(clock(), boxed).unwrap();
        let mut got = dynamic.write_read(&audio).unwrap();
        got.extend(dynamic.end_read().unwrap());
        assert_eq!(got, expected);

        // The per-window one-shot path, by hand.
        let width = driver.window_frames();
        let trimmed = drop_last_frame(joined_mels(&driver, &audio, &device));
        let frames = trimmed.dims()[1];
        let config = greedy_config(&driver);
        let mut by_hand = Vec::new();
        let mut at = 0;
        while at < frames {
            let count = width.min(frames - at);
            let window = trimmed
                .clone()
                .slice_dim(1, at as isize..(at + count) as isize);
            let mut packaged = driver
                .front_end()
                .package_window(window.clone(), PerWindow.reference(window.clone()));
            if count < width {
                let pad = Tensor::zeros([1, packaged.dims()[1], width - count], &device);
                packaged = Tensor::cat(vec![packaged, pad], 2);
            }
            by_hand.push(driver.whisper_model().decode_window(packaged, &config));
            at += count;
        }
        assert_eq!(tokens_of(&expected), by_hand);
    }

    /// Segments sit on the clock: a window that starts at frame `f` starts
    /// at `f * hop / rate`, and the flushed remainder ends where the audio
    /// does. `push_at` moves all of it by anchoring.
    #[test]
    #[serial]
    fn test_segments_sit_on_the_clock() {
        let device = Device::default();
        let driver: WhisperStreamDriver<B> = driver(&device, false);
        let audio = clip();
        let hop = driver.mel_converter().hop() as f64;
        let width = driver.window_frames();

        let mut ctx = driver.new_context(clock(), PerWindow).unwrap();
        let mut emissions = ctx.anchor_write_read(100.0, &audio).unwrap();
        emissions.extend(ctx.end_read().unwrap());

        let window_seconds = width as f64 * hop / driver.sample_rate() as f64;
        for (w, e) in emissions.iter().enumerate() {
            let segment = e.segment();
            assert!((segment.start - (100.0 + w as f64 * window_seconds)).abs() < 1e-9);
            if w + 1 < emissions.len() {
                assert!((segment.end - segment.start - window_seconds).abs() < 1e-9);
            }
        }

        // 16800 samples -> 104 frames streamed, +2 from finish, -1 trimmed:
        // 105, one per hop, and the remainder ends there.
        let last = emissions.last().unwrap().segment();
        assert_eq!(ctx.seek(), 105);
        assert!((last.end - (100.0 + 105.0 * hop / driver.sample_rate() as f64)).abs() < 1e-9);
        assert_eq!(ctx.pending_frames(), 0);
    }

    /// With carrying on, a window is prompted with the transcript's tail
    /// after `<|startofprev|>`, exactly as decoding it by hand with that
    /// prompt would.
    #[test]
    #[serial]
    fn test_prompt_carry() {
        let device = Default::default();
        let driver: WhisperStreamDriver<B> = driver(&device, true);
        let audio = clip();
        let width = driver.window_frames();

        let mut ctx = driver.new_context(clock(), PerWindow).unwrap();
        let mut emissions = ctx.write_read(&audio).unwrap();
        emissions.extend(ctx.end_read().unwrap());
        let got = tokens_of(&emissions);

        // By hand: the first window with the bare prompt, the second with
        // the carry built from the first's ids.
        let trimmed = drop_last_frame(joined_mels(&driver, &audio, &device));
        let window_at = |w: usize| {
            let window = trimmed
                .clone()
                .slice_dim(1, (w * width) as isize..((w + 1) * width) as isize);
            driver
                .front_end()
                .package_window(window.clone(), PerWindow.reference(window))
        };
        let ids = driver.token_layout().ids();
        let first = driver
            .whisper_model()
            .decode_window(window_at(0), &greedy_config(&driver));
        assert_eq!(got[0], first);

        let keep = driver.whisper_model().max_text_ctx() / 2 - 1;
        let mut prompt = vec![ids.sot_prev];
        prompt.extend_from_slice(&first[first.len().saturating_sub(keep)..]);
        prompt.extend_from_slice(driver.prompt());
        let carried =
            GreedyDecodeConfig::new(prompt, ids.eot).with_max_tokens(driver.config().max_tokens);
        let second = driver.whisper_model().decode_window(window_at(1), &carried);
        assert_eq!(got[1], second);

        // Without carrying, the same audio prompts every window the same
        // way, so this is only a real test if the two differ somewhere.
        let bare = driver
            .whisper_model()
            .decode_window(window_at(1), &greedy_config(&driver));
        assert!(
            !first.is_empty() || second != bare,
            "the tiny model emitted nothing to carry",
        );
    }

    /// A detokenizer on the driver puts text on every segment.
    #[test]
    #[serial]
    fn test_text_through_the_detokenizer() {
        #[derive(Debug)]
        struct Numbers;
        impl Detokenizer for Numbers {
            fn detokenize(
                &self,
                ids: &[i64],
            ) -> BunsenResult<String> {
                Ok(ids.iter().map(i64::to_string).collect::<Vec<_>>().join(" "))
            }
        }

        let device = Default::default();
        let driver: WhisperStreamDriver<B> =
            driver(&device, false).with_detokenizer(Arc::new(Numbers));
        let audio = clip();

        let mut ctx = driver.new_context(clock(), PerWindow).unwrap();
        let mut emissions = ctx.write_read(&audio).unwrap();
        emissions.extend(ctx.end_read().unwrap());

        for e in &emissions {
            let segment = e.segment();
            let text_ids = driver.token_layout().text_ids(&segment.tokens);
            assert_eq!(
                segment.text.as_deref(),
                Some(Numbers.detokenize(&text_ids).unwrap().as_str())
            );
        }
    }

    /// The stream's lifecycle edges: nothing pushed, a stream shorter than a
    /// hop, flush twice, push after flush, feed and advance apart.
    #[test]
    #[serial]
    fn test_lifecycle_edges() {
        let device = Default::default();
        let driver: WhisperStreamDriver<B> = driver(&device, false);

        let mut empty = driver.new_context(clock(), PerWindow).unwrap();
        assert!(empty.end_read().unwrap().is_empty());
        assert!(empty.end_read().unwrap().is_empty(), "flush is idempotent");
        assert!(
            empty.write_read(&[0.0; 16]).is_err(),
            "no pushing after flush"
        );
        assert!(empty.write(&[0.0; 16]).is_err(), "nor feeding");
        assert!(empty.is_finished());
        assert!(!empty.is_speaking());
        assert_eq!(empty.regions_pending(), 0);

        // Shorter than a hop: padded with silence to something decodable.
        let mut short = driver.new_context(clock(), PerWindow).unwrap();
        assert!(short.write_read(&[0.1; 50]).unwrap().is_empty());
        let emissions = short.end_read().unwrap();
        assert_eq!(emissions.len(), 1);
        assert!(short.pending_frames() == 0);

        // Feed then advance is push; end_input then advance is flush.
        let audio = clip();
        let mut split = driver.new_context(clock(), PerWindow).unwrap();
        split.write(&audio).unwrap();
        assert_eq!(split.transcript().len(), 0, "feeding decodes nothing");
        let mut got = split.read().unwrap();
        split.end_input().unwrap();
        got.extend(split.read().unwrap());

        let mut pushed = driver.new_context(clock(), PerWindow).unwrap();
        let mut expected = pushed.write_read(&audio).unwrap();
        expected.extend(pushed.end_read().unwrap());
        assert_eq!(got, expected);
    }

    /// **Batching is scheduling, nothing else.** Two streams advanced
    /// together commit exactly what each commits alone: same windows, same
    /// times, same ids &mdash; and a third stream with no audio is left
    /// alone.
    #[test]
    #[serial]
    fn test_advance_ready_matches_solo() {
        let device = Device::default();
        let driver = driver(&device, false).with_logit_filters(decisive());
        let clips = [clip_seeded(0.5, 440.0), clip_seeded(0.3, 660.0)];

        let mut solo = Vec::new();
        for audio in &clips {
            let mut ctx = driver.new_context(clock(), PerWindow).unwrap();
            let mut emissions = ctx.write_read(audio).unwrap();
            emissions.extend(ctx.end_read().unwrap());
            solo.push(emissions);
        }
        if tokens_of(&solo[0]) == tokens_of(&solo[1]) {
            eprintln!(
                "the seeded tiny model says the same of both clips; scheduling is still pinned"
            );
        }

        let mut contexts: Vec<WhisperStreamContext<B>> = (0..3)
            .map(|_| driver.new_context(clock(), PerWindow).unwrap())
            .collect();
        // The two clips go in whole, so the front end's arithmetic is the
        // solo run's; what differs is only that six windows per stream are
        // decoded twelve at a time. The third stream never gets audio.
        for (ctx, audio) in contexts.iter_mut().zip(&clips) {
            ctx.write(audio).unwrap();
        }
        let mut batched = advance_ready(&driver, &mut contexts).unwrap();
        assert_eq!(batched[0].len(), 6, "six full windows before the end");
        for ctx in contexts.iter_mut().take(2) {
            ctx.end_input().unwrap();
        }
        let tail = advance_ready(&driver, &mut contexts).unwrap();
        for (all, more) in batched.iter_mut().zip(tail) {
            all.extend(more);
        }

        assert_eq!(batched[0], solo[0]);
        assert_eq!(batched[1], solo[1]);
        assert!(batched[2].is_empty());
        assert_eq!(contexts[0].seek(), 105);
    }

    /// Batching is by prompt: a stream that has already committed a window
    /// carries a different prompt from one that has not, so the two form
    /// two groups in one pass, and each decodes as it would alone. The
    /// decode is dictated from the prompt, so a window batched under the
    /// wrong prompt would show.
    #[test]
    #[serial]
    fn test_advance_ready_with_prompt_carry() {
        let device = Device::default();
        let driver = driver(&device, true).with_logit_filters(decisive());
        let audio = clip();
        // 4000 samples: one 16-frame window and change.
        let first = RATE / 4;

        // Solo: A decodes its first window early, then the rest; B all at
        // once.
        let mut a = driver.new_context(clock(), PerWindow).unwrap();
        let mut solo_a = a.write_read(&audio[..first]).unwrap();
        assert_eq!(solo_a.len(), 1, "one window committed early");
        solo_a.extend(a.write_read(&audio[first..]).unwrap());
        solo_a.extend(a.end_read().unwrap());
        let mut b = driver.new_context(clock(), PerWindow).unwrap();
        let mut solo_b = b.write_read(&audio).unwrap();
        solo_b.extend(b.end_read().unwrap());
        assert_ne!(
            solo_a[0].segment().tokens,
            solo_a[1].segment().tokens,
            "the carried prompt changes what is decoded"
        );

        // Batched: A has committed its first window, B nothing; fed the
        // rest, they advance together under two prompts.
        let mut ctx_a = driver.new_context(clock(), PerWindow).unwrap();
        let mut batched_a = ctx_a.write_read(&audio[..first]).unwrap();
        ctx_a.write(&audio[first..]).unwrap();
        ctx_a.end_input().unwrap();
        let mut ctx_b = driver.new_context(clock(), PerWindow).unwrap();
        ctx_b.write(&audio).unwrap();
        ctx_b.end_input().unwrap();
        let mut contexts = vec![ctx_a, ctx_b];
        let out = advance_ready(&driver, &mut contexts).unwrap();
        batched_a.extend(out[0].clone());
        assert_eq!(batched_a, solo_a);
        assert_eq!(out[1], solo_b);
    }

    /// Dictates the decode: whatever the untrained model thinks (its
    /// near-ties flip between runs and backends), the next token is the
    /// scripted one for its position in the window. The script obeys the
    /// timestamp grammar, so the rules, applied after it, pass it through.
    #[derive(Debug)]
    struct Script(Vec<i64>);

    impl<Bk: Backend> LogitFilter<Bk> for Script {
        fn apply(
            &self,
            logits: Tensor<Bk, 2>,
            tokens: &[Vec<i64>],
            prompt_len: usize,
        ) -> Tensor<Bk, 2> {
            let [rows, vocab] = logits.dims();
            let mut data = vec![f32::NEG_INFINITY; rows * vocab];
            for (row, t) in tokens.iter().enumerate() {
                let at = (t.len() - prompt_len).min(self.0.len() - 1);
                data[row * vocab + self.0[at] as usize] = 0.0;
            }
            Tensor::from_data(
                burn::tensor::TensorData::new(data, [rows, vocab]),
                &logits.device(),
            )
        }
    }

    /// Dictates the decode from the prompt: at sampled position `at` the
    /// token is `(prompt_len + at) % 4 + 1`, so streams under different
    /// prompts decode differently, and a window batched under the wrong
    /// prompt would show. Independent of the model, whose forward on this
    /// backend varies from call to call by more than a near-tie.
    #[derive(Debug)]
    struct Echo;

    impl LogitFilter<B> for Echo {
        fn apply(
            &self,
            logits: Tensor<B, 2>,
            tokens: &[Vec<i64>],
            prompt_len: usize,
        ) -> Tensor<B, 2> {
            let [rows, vocab] = logits.dims();
            let mut data = vec![f32::NEG_INFINITY; rows * vocab];
            for (row, t) in tokens.iter().enumerate() {
                let at = t.len() - prompt_len;
                data[row * vocab + (prompt_len + at) % 4 + 1] = 0.0;
            }
            Tensor::from_data(
                burn::tensor::TensorData::new(data, [rows, vocab]),
                &logits.device(),
            )
        }
    }

    /// The filters that make a plumbing test's decode a function of its
    /// prompt alone.
    fn decisive() -> Vec<Arc<dyn LogitFilter<B>>> {
        vec![Arc::new(Echo)]
    }

    /// Each window's script: two closed segments and a reopened tail,
    /// `<|1|> a <|3|><|3|> b <|5|><|5|> c`, at the cap of 8 tokens. The
    /// first timestamp is within the cap of index 2, so the cap is a real
    /// constraint that the script satisfies; the seek advances 10 frames
    /// of 16 per decode, so windows overlap.
    fn script() -> Vec<i64> {
        let tb = tiny_layout().timestamp_begin;
        vec![tb + 1, 1, tb + 3, tb + 3, 2, tb + 5, tb + 5, 3]
    }

    /// A driver that emits timestamps under the script. No prompt carry:
    /// the tiny model's text context is 16, and a carried prompt would
    /// leave the script no room.
    fn timestamped(
        device: &Device,
        commit: CommitRule,
    ) -> WhisperStreamDriver<B> {
        let scripted: Arc<dyn LogitFilter<B>> = Arc::new(Script(script()));
        config(false)
            .with_max_tokens(8)
            .with_timestamps(true)
            .with_max_initial_timestamp(Some(0.04))
            .with_emission(EmissionPolicy::new(DecodeTriggers::new(), commit))
            .init_with_layout(
                tiny_model_on::<B>(device),
                WhisperTokenLayout::new(tiny_layout()),
                device,
            )
            .unwrap()
            .with_logit_filters(vec![scripted])
    }

    /// Pushes a clip through a fresh context and flushes it.
    fn run_clip(
        driver: &WhisperStreamDriver<B>,
        audio: &[f32],
        at: Option<f64>,
    ) -> Vec<TranscriptEvent> {
        let mut ctx = driver.new_context(clock(), PerWindow).unwrap();
        let mut emissions = match at {
            Some(time) => ctx.anchor_write_read(time, audio).unwrap(),
            None => ctx.write_read(audio).unwrap(),
        };
        emissions.extend(ctx.end_read().unwrap());
        assert_eq!(ctx.pending_frames(), 0, "a flush consumes everything");
        assert_eq!(ctx.seek(), 105);
        let committed: Vec<i64> = emissions
            .iter()
            .filter(|e| e.is_committed())
            .flat_map(|e| e.segment().tokens.clone())
            .collect();
        assert_eq!(
            ctx.transcript(),
            &committed[..],
            "the transcript is what was committed"
        );
        emissions
    }

    /// With timestamps on, a window's decode is split on its consecutive
    /// timestamps into segments on the clock, and the seek advances to the
    /// last closed timestamp rather than a whole window: 105 frames at 10
    /// per decode is 11 decodes, 22 segments, each 4 frames long.
    #[test]
    #[serial]
    fn test_timestamps_split_windows_into_segments() {
        let device = Device::default();
        let driver = timestamped(&device, CommitRule::Complete);
        let tb = tiny_layout().timestamp_begin;
        let hop = driver.mel_converter().hop() as f64;
        let frame = |f: f64| f * hop / driver.sample_rate() as f64;
        assert_eq!(driver.frames_per_timestamp(), 2);
        assert_eq!(
            driver.filters().len(),
            2,
            "the test's filter, then the rules appended by the driver"
        );

        let emissions = run_clip(&driver, &clip(), None);
        assert_eq!(emissions.len(), 22);

        for (k, e) in emissions.iter().enumerate() {
            assert!(e.is_committed(), "Complete never drafts");
            let s = e.segment();
            let (window, which) = (k / 2, k % 2);
            let seek = (window * 10) as f64;
            let expected = if which == 0 {
                (vec![tb + 1, 1, tb + 3], seek + 2.0, seek + 6.0)
            } else {
                (vec![tb + 3, 2, tb + 5], seek + 6.0, seek + 10.0)
            };
            assert_eq!(s.tokens, expected.0, "segment {k}");
            assert!(
                (s.start - frame(expected.1)).abs() < 1e-9,
                "segment {k}: {s:?}"
            );
            assert!(
                (s.end - frame(expected.2)).abs() < 1e-9,
                "segment {k}: {s:?}"
            );
        }
    }

    /// **I8.** The same clip on a clock anchored at 100 s yields the same
    /// segments, shifted by 100 s.
    #[test]
    #[serial]
    fn test_segment_times_are_invariant_to_clock_origin() {
        let device = Device::default();
        let driver = timestamped(&device, CommitRule::Complete);
        let audio = clip();

        let base = run_clip(&driver, &audio, None);
        let shifted = run_clip(&driver, &audio, Some(100.0));
        assert_eq!(base.len(), shifted.len());
        for (a, b) in base.iter().zip(&shifted) {
            assert_eq!(a.segment().tokens, b.segment().tokens);
            assert!((b.segment().start - a.segment().start - 100.0).abs() < 1e-9);
            assert!((b.segment().end - a.segment().end - 100.0).abs() < 1e-9);
        }
    }

    /// Under `LastTimestamp` the unfinished tail of a window is emitted as
    /// a draft opening on its timestamp, and what is committed is exactly
    /// what `Complete` commits.
    #[test]
    #[serial]
    fn test_last_timestamp_drafts_the_tail() {
        let device = Device::default();
        let audio = clip();
        let complete = run_clip(&timestamped(&device, CommitRule::Complete), &audio, None);
        let last = run_clip(
            &timestamped(&device, CommitRule::LastTimestamp),
            &audio,
            None,
        );

        let committed: Vec<&TranscriptEvent> = last.iter().filter(|e| e.is_committed()).collect();
        assert_eq!(committed.len(), complete.len());
        for (a, b) in committed.iter().zip(&complete) {
            assert_eq!(a.segment(), b.segment());
        }

        let tb = tiny_layout().timestamp_begin;
        let drafts: Vec<&TranscriptEvent> = last.iter().filter(|e| !e.is_committed()).collect();
        // One per decode, except the last: its 5 frames end before the
        // tail's timestamp at frame 10, so there is nothing to draft yet.
        assert_eq!(drafts.len(), 10);
        for draft in drafts {
            let s = draft.segment();
            assert_eq!(s.tokens, vec![tb + 5, 3], "the reopened tail");
            assert!(s.start <= s.end);
        }
    }

    /// Degenerate at temperature zero, sound once sampling has broken the
    /// loop: while the sampled history is all `1`s (or empty) the logits
    /// are nearly flat with `1` a hair ahead, so the argmax loops on `1` at
    /// a log probability near `-log(vocab)`; once any other token appears,
    /// which only sampling can bring, the logits peak on `2`.
    #[derive(Debug)]
    struct Degenerate;

    impl LogitFilter<B> for Degenerate {
        fn apply(
            &self,
            logits: Tensor<B, 2>,
            tokens: &[Vec<i64>],
            prompt_len: usize,
        ) -> Tensor<B, 2> {
            let [rows, vocab] = logits.dims();
            let mut data = vec![-0.01f32; rows * vocab];
            for (row, t) in tokens.iter().enumerate() {
                let at = row * vocab;
                if t[prompt_len..].iter().all(|&x| x == 1) {
                    data[at + 1] = 0.0;
                } else {
                    data[at..at + vocab].fill(0.0);
                    data[at + 2] = 30.0;
                }
            }
            Tensor::from_data(
                burn::tensor::TensorData::new(data, [rows, vocab]),
                &logits.device(),
            )
        }
    }

    /// A carrying driver under the degenerate filter and a fallback
    /// policy.
    fn degenerate_driver(
        device: &Device,
        fallback: WhisperFallbackConfig,
    ) -> WhisperStreamDriver<B> {
        let filter: Arc<dyn LogitFilter<B>> = Arc::new(Degenerate);
        config(true)
            .with_max_tokens(8)
            .with_fallback(fallback)
            .init_with_layout(
                tiny_model_on::<B>(device),
                WhisperTokenLayout::new(tiny_layout()),
                device,
            )
            .unwrap()
            .with_logit_filters(vec![filter])
    }

    /// The ladder: at temperature zero the decode loops and fails the log
    /// probability threshold; without a ladder that is what is emitted.
    /// With upstream's ladder, sampling at the first rung above zero breaks
    /// the loop and the decode recovers, below the prompt-reset line, so
    /// the carry stands. A ladder whose only rung above zero is past that
    /// line recovers too, and resets the carry.
    #[test]
    #[serial]
    fn test_fallback_ladder_recovers() {
        let device = Device::default();
        let audio = clip();
        let flat = degenerate_driver(&device, WhisperFallbackConfig::new());
        let mut ctx = flat.new_context(clock(), PerWindow).unwrap();
        let mut looped = ctx.write_read(&audio).unwrap();
        looped.extend(ctx.end_read().unwrap());
        assert!(!looped.is_empty());
        // Eight 1s in the first window; fewer after, once the carried
        // prompt has taken its share of the tiny model's 16-token context.
        assert!(
            looped
                .iter()
                .all(|e| !e.segment().tokens.is_empty()
                    && e.segment().tokens.iter().all(|&t| t == 1)),
            "no ladder: the loop is what there is: {looped:?}"
        );
        let carry_len = ctx.prompt_now().len();
        assert!(carry_len > flat.prompt().len(), "the carry stands");

        let climbing = degenerate_driver(&device, WhisperFallbackConfig::upstream());
        let mut ctx = climbing.new_context(clock(), PerWindow).unwrap();
        let mut recovered = ctx.write_read(&audio).unwrap();
        recovered.extend(ctx.end_read().unwrap());
        assert_eq!(recovered.len(), looped.len());
        for e in &recovered {
            let t = &e.segment().tokens;
            assert!(t.contains(&2), "sampling broke the loop: {t:?}");
        }
        assert!(
            ctx.prompt_now().len() > climbing.prompt().len(),
            "recovered below 0.5: the carry stands"
        );

        let hot = degenerate_driver(
            &device,
            WhisperFallbackConfig::new().with_temperatures(vec![0.0, 0.8]),
        );
        let mut ctx = hot.new_context(clock(), PerWindow).unwrap();
        let mut reset = ctx.write_read(&audio).unwrap();
        reset.extend(ctx.end_read().unwrap());
        assert!(reset.iter().all(|e| e.segment().tokens.contains(&2)));
        assert_eq!(
            ctx.prompt_now(),
            hot.prompt(),
            "past 0.5: the carry was reset"
        );
    }

    /// The silence rule: a window whose no-speech probability is over the
    /// threshold and whose log probability is poor is skipped whole, the
    /// seek moving past it with nothing emitted; a good enough log
    /// probability keeps it.
    #[test]
    #[serial]
    fn test_no_speech_skips_a_window() {
        let device = Device::default();
        let audio = clip();

        let skipping = degenerate_driver(
            &device,
            WhisperFallbackConfig::new().with_no_speech_threshold(Some(0.0)),
        );
        let mut ctx = skipping.new_context(clock(), PerWindow).unwrap();
        let mut emissions = ctx.write_read(&audio).unwrap();
        emissions.extend(ctx.end_read().unwrap());
        assert!(
            emissions.is_empty(),
            "every window is silence: {emissions:?}"
        );
        assert_eq!(ctx.seek(), 105, "the seek still moved past them");
        assert!(ctx.transcript().is_empty());

        let kept = degenerate_driver(
            &device,
            WhisperFallbackConfig::new()
                .with_no_speech_threshold(Some(0.0))
                .with_logprob_threshold(Some(-1e9)),
        );
        let mut ctx = kept.new_context(clock(), PerWindow).unwrap();
        let mut emissions = ctx.write_read(&audio).unwrap();
        emissions.extend(ctx.end_read().unwrap());
        assert!(
            !emissions.is_empty(),
            "a good enough log probability keeps a window"
        );
    }

    /// A multilingual driver given no language detects it from the first
    /// window: on a layout with one language, that one, and the stream then
    /// decodes exactly as one configured with it. Solo and batched agree.
    #[test]
    #[serial]
    fn test_language_is_detected_per_stream() {
        let device = Device::default();
        let detecting = WhisperStreamDriverConfig::new()
            .with_max_tokens(4)
            .init_with_layout(
                tiny_model_on::<B>(&device),
                WhisperTokenLayout::new(tiny_layout()),
                &device,
            )
            .unwrap()
            .with_logit_filters(decisive());
        assert!(detecting.detects_language());
        assert!(detecting.prompt().is_empty());
        let only = crate::kits::speech::whisper::blocks::LANGUAGES[0];
        assert_eq!(only, "en");

        let audio = clip();
        let mut solo = detecting.new_context(clock(), PerWindow).unwrap();
        assert_eq!(solo.language(), None);
        let mut expected = solo.write_read(&audio).unwrap();
        expected.extend(solo.end_read().unwrap());
        assert_eq!(solo.language(), Some(only));

        // The same as configuring it.
        let configured = driver(&device, true).with_logit_filters(decisive());
        assert_eq!(run_clip(&configured, &audio, None), expected);

        // Batched: fed, then advanced together.
        let mut batch = vec![
            detecting.new_context(clock(), PerWindow).unwrap(),
            detecting.new_context(clock(), PerWindow).unwrap(),
        ];
        for ctx in &mut batch {
            ctx.write(&audio).unwrap();
            ctx.end_input().unwrap();
        }
        let out = advance_ready(&detecting, &mut batch).unwrap();
        assert_eq!(out[0], expected);
        assert_eq!(out[1], expected);
        assert_eq!(batch[1].language(), Some(only));
    }

    /// The driver reports the model's rate, and the grid derived from it.
    #[test]
    fn test_driver_reports_the_models_rate() {
        let device = Device::default();
        let driver = WhisperStreamDriverConfig::new()
            .init_with_layout(
                tiny_model_on::<B>(&device),
                WhisperTokenLayout::new(tiny_layout()),
                &device,
            )
            .unwrap();
        assert_eq!(driver.sample_rate(), 16_000);
        assert_eq!(driver.mel_converter().hop(), 160);
        assert_eq!(driver.frames_per_timestamp(), 2);
        assert_eq!(driver.encoder_grid(), 320);
        assert_eq!(driver.interval_samples(), None);
    }

    /// The configuration refuses what this slice cannot do, with a reason,
    /// and refuses a mismatched language.
    #[test]
    fn test_init_refuses_the_unsupported() {
        let device = Default::default();
        let policy = WhisperTokenLayout::new(tiny_layout());
        let base = WhisperStreamDriverConfig::new().with_language(Some("en".to_string()));

        assert!(
            base.init_with_layout(tiny_model_on::<B>(&device), policy.clone(), &device)
                .is_ok()
        );
        // Multilingual without a language detects it per stream.
        assert!(
            WhisperStreamDriverConfig::new()
                .init_with_layout(tiny_model_on::<B>(&device), policy.clone(), &device)
                .unwrap()
                .detects_language()
        );
        assert!(
            base.clone()
                .with_timestamps(true)
                .init_with_layout(tiny_model_on::<B>(&device), policy.clone(), &device)
                .is_ok()
        );
        assert!(
            base.clone()
                .with_emission(EmissionPolicy::responsive())
                .init_with_layout(tiny_model_on::<B>(&device), policy.clone(), &device)
                .is_ok(),
            "responsive is the third deployment target",
        );
        assert!(
            base.clone()
                .with_emission(EmissionPolicy::new(
                    DecodeTriggers::new().with_interval(Some(std::time::Duration::ZERO)),
                    CommitRule::Complete,
                ))
                .init_with_layout(tiny_model_on::<B>(&device), policy.clone(), &device)
                .is_err(),
            "an interval of zero",
        );
        assert!(
            base.clone()
                .with_language(Some("xx".to_string()))
                .init_with_layout(tiny_model_on::<B>(&device), policy.clone(), &device)
                .is_err()
        );

        // Conservative is constructible, but a stream under it needs a VAD.
        let conservative = base
            .clone()
            .with_emission(EmissionPolicy::conservative())
            .init_with_layout(tiny_model_on::<B>(&device), policy, &device)
            .unwrap();
        assert!(conservative.new_context(clock(), PerWindow).is_err());

        // A clock at the wrong rate is refused at the stream, not later.
        let driver: WhisperStreamDriver<B> = driver(&device, false);
        assert!(
            driver
                .new_context(StreamClock::uniform(8_000), PerWindow)
                .is_err()
        );
    }

    /// Against the real voice-activity model: regions become segments in
    /// the parent stream's frame of reference, and silence is never
    /// decoded.
    #[cfg(feature = "silero-weights")]
    mod voice_activity {
        use super::*;
        use crate::{
            kits::speech::{
                silero_vad::SileroVad,
                whisper::driver::{
                    CommitRule,
                    DecodeTriggers,
                    VoiceActivityFilterConfig,
                },
            },
            support::{
                audio::load_audio_mono_sr,
                testing::CpuBackend,
            },
        };

        /// Silero and the tiny model on the CPU backend, so the golden
        /// regions from the gate's own test hold here too.
        type C = CpuBackend;
        type CDevice = burn::prelude::Device<C>;

        fn speech() -> Vec<f32> {
            let path = concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/testdata/audio/jfk_moon_4s.mp3"
            );
            load_audio_mono_sr(path, RATE).unwrap()
        }

        fn conservative_driver(device: &CDevice) -> WhisperStreamDriver<C> {
            let vad = SileroVad::<C>::load_16khz_pretrained(device).unwrap();
            config(false)
                .with_emission(EmissionPolicy::conservative())
                .init_with_layout(
                    tiny_model_on::<C>(device),
                    WhisperTokenLayout::new(tiny_layout()),
                    device,
                )
                .unwrap()
                .with_vad(vad, VoiceActivityFilterConfig::fast_whisper_burn())
                .unwrap()
        }

        /// A model or a filter at another rate, or a filter with the wrong
        /// chunk, is refused at attach time; the matching pair is not.
        #[test]
        #[serial]
        fn test_with_vad_refuses_a_mismatch() {
            let device = CDevice::default();
            let driver = || {
                config(false)
                    .with_emission(EmissionPolicy::conservative())
                    .init_with_layout(
                        tiny_model_on::<C>(&device),
                        WhisperTokenLayout::new(tiny_layout()),
                        &device,
                    )
                    .unwrap()
            };
            let filter = VoiceActivityFilterConfig::fast_whisper_burn;

            let eight = SileroVad::<C>::load_8khz_pretrained(&device).unwrap();
            assert!(driver().with_vad(eight, filter()).is_err());

            let vad = SileroVad::<C>::load_16khz_pretrained(&device).unwrap();
            assert!(
                driver()
                    .with_vad(vad.clone(), filter().with_sample_rate(8_000))
                    .is_err()
            );
            assert!(
                driver()
                    .with_vad(vad.clone(), filter().with_samples_per_chunk(256))
                    .is_err()
            );

            let attached = driver().with_vad(vad, filter()).unwrap();
            assert_eq!(
                attached.va_filter_config().map(|f| f.samples_per_chunk),
                Some(512)
            );
        }

        /// The gate's golden regions, padded and snapped outward, are
        /// exactly what gets decoded: the segments tile each region, a
        /// window at a time, nothing lands in the pause between them, and
        /// their times are the parent clock's, anchor and all. Pushed in
        /// random pieces, so the VAD's own staging is exercised.
        #[test]
        #[serial]
        fn test_regions_become_segments_on_the_parent_clock() {
            let device = CDevice::default();
            let vad = SileroVad::<C>::load_16khz_pretrained(&device).unwrap();
            let regions_only = EmissionPolicy::new(
                DecodeTriggers::new()
                    .with_window_full(false)
                    .with_endpoint(true),
                CommitRule::LastTimestamp,
            );
            let driver = config(false)
                .with_emission(regions_only)
                .init_with_layout(
                    tiny_model_on::<C>(&device),
                    WhisperTokenLayout::new(tiny_layout()),
                    &device,
                )
                .unwrap()
                .with_vad(vad, VoiceActivityFilterConfig::fast_whisper_burn())
                .unwrap();
            let audio = speech();
            assert_eq!(audio.len(), 64_000);

            let mut ctx = driver.new_context(clock(), PerWindow).unwrap();
            let sizes = random_sizes(11, audio.len());
            let mut emissions = Vec::new();
            let mut at = 0;
            for (k, &size) in sizes.iter().enumerate() {
                let piece = &audio[at..at + size];
                emissions.extend(if k == 0 {
                    ctx.anchor_write_read(100.0, piece).unwrap()
                } else {
                    ctx.write_read(piece).unwrap()
                });
                at += size;
            }
            emissions.extend(ctx.end_read().unwrap());

            // (0, 16352) and (29728, 56800) from the gate's golden test,
            // snapped outward onto the 320-sample grid.
            let expected = [(0usize, 16_640usize), (29_440, 56_960)];
            let window = driver.window_frames() as f64 * driver.mel_converter().hop() as f64
                / driver.sample_rate() as f64;
            let close = |a: f64, b: f64| (a - b).abs() < 1e-9;

            let mut segments = emissions.iter().map(TranscriptEvent::segment).peekable();
            for (start, end) in expected {
                let (start, end) = (
                    100.0 + start as f64 / RATE as f64,
                    100.0 + end as f64 / RATE as f64,
                );
                let mut at = start;
                while let Some(segment) = segments.next_if(|s| s.start < end) {
                    assert!(close(segment.start, at), "gap before {segment:?}");
                    assert!(segment.end - segment.start <= window + 1e-9);
                    assert!(segment.end <= end + 1e-9, "past the region: {segment:?}");
                    at = segment.end;
                }
                assert!(
                    close(at, end),
                    "region not covered to {end}: stopped at {at}\n{emissions:#?}"
                );
            }
            assert!(segments.next().is_none(), "segments outside every region");
            assert!(emissions.iter().all(TranscriptEvent::is_committed));
            assert_eq!(ctx.regions_pending(), 0);
            assert!(!ctx.is_speaking());
            assert_eq!(
                emissions.len(),
                (104_usize).div_ceil(16) + (172_usize).div_ceil(16),
                "a window at a time over 104 and 172 frames",
            );
        }

        /// Under `conservative()` the full-window trigger runs too: a
        /// window with speech in progress decodes as it fills, so the window
        /// that opens a region may begin a little before it; but nothing is
        /// ever decoded from the pause, and both regions are covered.
        #[test]
        #[serial]
        fn test_conservative_skips_silence() {
            let device = CDevice::default();
            let driver = conservative_driver(&device);
            let audio = speech();

            let mut ctx = driver.new_context(clock(), PerWindow).unwrap();
            let mut emissions = ctx.write_read(&audio).unwrap();
            emissions.extend(ctx.end_read().unwrap());

            let window = driver.window_frames() as f64 * driver.mel_converter().hop() as f64
                / driver.sample_rate() as f64;
            let (gap_start, gap_end) = (16_640.0 / RATE as f64, 29_440.0 / RATE as f64);
            let mut covered_to = 0.0_f64;
            for e in &emissions {
                let s = e.segment();
                assert!(
                    !(s.start >= gap_start && s.end <= gap_end),
                    "a window of silence was decoded: {s:?}",
                );
                assert!(s.start >= covered_to - 1e-9, "out of order: {s:?}");
                if s.start > gap_start + 1e-9 {
                    assert!(
                        s.start >= gap_end - window - 1e-9,
                        "started deep in the pause: {s:?}"
                    );
                }
                covered_to = s.end;
            }
            assert!(
                (covered_to - 56_960.0 / RATE as f64).abs() < 1e-9,
                "covered to {covered_to}\n{emissions:#?}"
            );
            assert_eq!(ctx.regions_pending(), 0);
        }

        /// A responsive driver: conservative plus a draft every 50 ms of
        /// media time while speech is in progress &mdash; shorter than
        /// `responsive()`'s 600 ms because the tiny model's window is 0.16 s
        /// of audio, and a full window commits before a longer interval
        /// could draft. Its decode is scripted so the pin is about
        /// scheduling, not the untrained model.
        fn responsive_driver(device: &CDevice) -> WhisperStreamDriver<C> {
            let vad = SileroVad::<C>::load_16khz_pretrained(device).unwrap();
            let scripted: Arc<dyn LogitFilter<C>> = Arc::new(Script(vec![3, 1, 4, 1]));
            let policy = EmissionPolicy::new(
                DecodeTriggers::new()
                    .with_endpoint(true)
                    .with_interval(Some(std::time::Duration::from_millis(50))),
                CommitRule::LastTimestamp,
            );
            config(false)
                .with_emission(policy)
                .init_with_layout(
                    tiny_model_on::<C>(device),
                    WhisperTokenLayout::new(tiny_layout()),
                    device,
                )
                .unwrap()
                .with_vad(vad, VoiceActivityFilterConfig::fast_whisper_burn())
                .unwrap()
                .with_logit_filters(vec![scripted])
        }

        /// The clip pushed 100 ms at a time, then flushed.
        fn in_pieces(ctx: &mut WhisperStreamContext<C>) -> Vec<TranscriptEvent> {
            let audio = speech();
            let mut out = Vec::new();
            for piece in audio.chunks(RATE / 10) {
                out.extend(ctx.write_read(piece).unwrap());
            }
            out.extend(ctx.end_read().unwrap());
            out
        }

        /// **I9.** Adding the interval trigger cannot change the transcript:
        /// `responsive()` commits exactly what `conservative()` commits, and
        /// drafts besides: each covering the audio since the last commit,
        /// paced at least an interval apart, none after the last commit.
        #[test]
        #[serial]
        fn test_responsive_commits_what_conservative_commits() {
            let device = CDevice::default();
            let scripted: Arc<dyn LogitFilter<C>> = Arc::new(Script(vec![3, 1, 4, 1]));
            let conservative = conservative_driver(&device).with_logit_filters(vec![scripted]);
            let responsive = responsive_driver(&device);

            let mut ctx = conservative.new_context(clock(), PerWindow).unwrap();
            let quiet = in_pieces(&mut ctx);
            assert!(
                quiet.iter().all(|e| e.is_committed()),
                "conservative never drafts"
            );

            let mut ctx = responsive.new_context(clock(), PerWindow).unwrap();
            let chatty = in_pieces(&mut ctx);
            let committed: Vec<&TranscriptEvent> =
                chatty.iter().filter(|e| e.is_committed()).collect();
            assert_eq!(committed.len(), quiet.len());
            for (a, b) in committed.iter().zip(&quiet) {
                assert_eq!(a.segment(), b.segment());
            }

            let drafts: Vec<&TranscriptSegment> = chatty
                .iter()
                .filter(|e| !e.is_committed())
                .map(|e| e.segment())
                .collect();
            assert!(drafts.len() >= 3, "{} drafts", drafts.len());
            let interval = 0.05;
            let mut last_end = f64::NEG_INFINITY;
            let mut last_commit_end = 0.0;
            let mut seen_commits = 0;
            for e in &chatty {
                let s = e.segment();
                if e.is_committed() {
                    last_commit_end = s.end;
                    seen_commits += 1;
                    continue;
                }
                assert!(
                    s.start >= last_commit_end - 1e-9,
                    "a draft starts at the seek: {s:?}"
                );
                assert!(s.end > s.start, "{s:?}");
                assert!(
                    s.end - last_end >= interval - 1e-9,
                    "paced: {s:?} after {last_end}"
                );
                assert_eq!(s.tokens, vec![3, 1, 4, 1]);
                last_end = s.end;
            }
            assert!(seen_commits > 0);
            assert!(
                chatty.last().unwrap().is_committed(),
                "the flush commits everything; nothing is left to draft"
            );
        }

        /// Batched, a responsive stream drafts and commits exactly as it
        /// does alone: fed a piece at a time and advanced after each.
        #[test]
        #[serial]
        fn test_advance_ready_drafts_like_solo() {
            let device = CDevice::default();
            let driver = responsive_driver(&device);
            let audio = speech();

            let mut solo = driver.new_context(clock(), PerWindow).unwrap();
            let mut batch = vec![driver.new_context(clock(), PerWindow).unwrap()];
            let (mut expected, mut got) = (Vec::new(), Vec::new());
            for piece in audio.chunks(RATE / 10) {
                expected.extend(solo.write_read(piece).unwrap());
                batch[0].write(piece).unwrap();
                got.extend(advance_ready(&driver, &mut batch).unwrap().remove(0));
            }
            expected.extend(solo.end_read().unwrap());
            batch[0].end_input().unwrap();
            got.extend(advance_ready(&driver, &mut batch).unwrap().remove(0));
            assert_eq!(got, expected);
            assert!(
                expected.iter().any(|e| !e.is_committed()),
                "there were drafts"
            );
        }

        /// Under the offline policy an attached VAD is simply unused: the
        /// clip decodes as one window at the end, silence and all.
        #[test]
        #[serial]
        fn test_offline_ignores_the_vad() {
            let device = CDevice::default();
            let vad = SileroVad::<C>::load_16khz_pretrained(&device).unwrap();
            let driver = config(false)
                .init_with_layout(
                    tiny_model_on::<C>(&device),
                    WhisperTokenLayout::new(tiny_layout()),
                    &device,
                )
                .unwrap()
                .with_vad(vad, VoiceActivityFilterConfig::fast_whisper_burn())
                .unwrap();
            let audio = speech();

            let mut ctx = driver.new_context(clock(), PerWindow).unwrap();
            let mut emissions = ctx.write_read(&audio).unwrap();
            emissions.extend(ctx.end_read().unwrap());

            // 400 frames of 16 per window: 25 windows, no remainder.
            assert_eq!(emissions.len(), 25);
            assert_eq!(ctx.regions_pending(), 0);
        }
    }
}