bunsen 0.39.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
//! # The stream context: one stream in progress.

use std::collections::VecDeque;

use burn::Tensor;

use crate::{
    errors::{
        BunsenError,
        BunsenResult,
    },
    kits::speech::asr_driver::{
        AsrEngine,
        AsrStreamDriver,
        CommitRule,
        DecodeRequest,
        LevelPolicy,
        LevelTracker,
        SpeechRegion,
        StreamClock,
        StreamingFeatures,
        TranscriptEvent,
        TranscriptSegment,
        VoiceActivityFilter,
        VoiceActivityStream,
        WindowDecode,
        support::frame_ring::FrameRing,
    },
};

/// Advances every context that has a decode due, batching the decodes.
///
/// Repeats until no context has anything due, so a context with several
/// units due (a burst of closed regions, a long write) advances through all
/// of them. Each round takes one unit from every context that has one and
/// hands them to the engine together; each context's events are what its
/// own [`read`](AsrStreamContext::read) would have returned.
///
/// # Arguments
/// * `driver` - the driver the contexts were opened from.
/// * `contexts` - the streams, fed through [`write`](AsrStreamContext::write)
///   rather than [`write_read`](AsrStreamContext::write_read), so that nothing
///   has been decoded yet.
///
/// # Errors
/// As [`AsrStreamContext::read`].
pub fn advance_ready<E: AsrEngine>(
    driver: &AsrStreamDriver<E>,
    contexts: &mut [AsrStreamContext<E>],
) -> BunsenResult<Vec<Vec<TranscriptEvent>>> {
    let mut out: Vec<Vec<TranscriptEvent>> = vec![Vec::new(); contexts.len()];

    loop {
        // One due unit per context: a commit if one is due, else a draft.
        let mut due: Vec<(usize, Due, bool)> = Vec::new();
        for (i, ctx) in contexts.iter_mut().enumerate() {
            ctx.skip_silence();
            if let Some(unit) = ctx.next_due() {
                due.push((i, unit, false));
            } else if let Some(unit) = ctx.draft_unit() {
                due.push((i, unit, true));
            }
        }
        if due.is_empty() {
            return Ok(out);
        }

        let requests = due
            .iter()
            .map(|&(i, unit, draft)| contexts[i].request(unit, draft))
            .collect();
        let decodes = driver.engine().decode(requests)?;

        for ((i, unit, draft), decode) in due.into_iter().zip(decodes) {
            let ctx = &mut contexts[i];
            if draft {
                out[i].push(ctx.draft_from(unit, decode)?);
            } else {
                out[i].extend(ctx.commit_due(unit, decode)?);
            }
        }
    }
}

/// One stream: the only stateful type of the driver.
///
/// Opened by [`AsrStreamDriver::new_context`], with the stream's
/// [`StreamClock`] and its [`LevelPolicy`]; it holds a clone of the driver,
/// so a driver opens as many as it has streams. Samples go in through
/// [`write_read`](Self::write_read), or [`write`](Self::write) and
/// [`read`](Self::read) apart, and come out as [`TranscriptEvent`]s;
/// [`end_read`](Self::end_read) ends the stream and decodes what is left.
///
/// A decode reads the context through `&self`, and only a commit changes
/// it, so drafting never changes what the stream commits.
#[derive(Clone, Debug)]
pub struct AsrStreamContext<E: AsrEngine> {
    driver: AsrStreamDriver<E>,

    /// The feature front end's streaming state.
    features: E::Features,

    /// The features from `origin` onward.
    frames: FrameRing,

    /// Samples pushed so far.
    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,

    level: LevelTracker<E::Level>,

    /// The engine's carry for this stream.
    state: E::StreamState,

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

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

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

    finished: bool,
}

/// The voice-activity half of a stream: the model's state, the filter, and
/// the regions it has closed but the decode has not yet consumed.
#[derive(Clone, Debug)]
struct VoiceActivity {
    stream: Box<dyn VoiceActivityStream>,

    filter: VoiceActivityFilter,

    /// The samples in one chunk.
    chunk: usize,

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

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

    /// The 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<E: AsrEngine> AsrStreamContext<E> {
    /// Initialize a new context.
    ///
    /// [`AsrStreamDriver::new_context`] is the way in: it checks that the
    /// clock runs at the engine's rate and that a policy wanting endpoints
    /// has a voice-activity model, which this does not.
    ///
    /// # Errors
    /// As the engine's [`new_features`](AsrEngine::new_features).
    pub fn init(
        driver: AsrStreamDriver<E>,
        clock: StreamClock,
        level: LevelPolicy,
    ) -> BunsenResult<Self> {
        let engine = driver.engine();
        let features = engine.new_features()?;
        let state = engine.new_stream_state();

        let vad = match (driver.vad(), driver.va_filter_config()) {
            (Some(model), Some(gate)) if driver.emission().triggers.endpoint => {
                Some(VoiceActivity {
                    stream: model.new_stream(),
                    filter: gate.init(),
                    chunk: model.chunk_size(),
                    staging: Vec::new(),
                    pad: gate.speech_pad_samples(),
                    grid: driver.grid_samples(),
                    regions: VecDeque::new(),
                    last_end: 0,
                })
            }
            _ => None,
        };

        // Two windows: a full window can wait for its decode while the next
        // one fills, before the ring compacts.
        let frames = FrameRing::new(2 * engine.window_frames());
        Ok(Self {
            features,
            frames,
            samples_seen: 0,
            origin: 0,
            seek: 0,
            clock,
            level: LevelTracker::new(level),
            state,
            transcript: Vec::new(),
            last_draft: 0,
            vad,
            finished: false,
            driver,
        })
    }

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

    /// The driver the stream was opened from.
    pub fn driver(&self) -> &AsrStreamDriver<E> {
        &self.driver
    }

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

    /// The stream's level.
    pub fn level(&self) -> &LevelTracker<E::Level> {
        &self.level
    }

    /// The engine's carry for this stream.
    pub fn engine_state(&self) -> &E::StreamState {
        &self.state
    }

    /// 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.frames.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 [`end_read`](Self::end_read) or [`end_input`](Self::end_input)
    /// has run.
    pub fn is_finished(&self) -> bool {
        self.finished
    }

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

    fn window_frames(&self) -> usize {
        self.driver.engine().window_frames()
    }

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

    /// Anchors the clock, then [`write_read`](Self::write_read): the first
    /// of `samples` is placed at media time `time`, and later times follow
    /// from there.
    ///
    /// # Errors
    /// As [`write_read`](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)
    }

    /// Writes samples and returns the [`TranscriptEvent`]s they made due:
    /// [`write`](Self::write) then [`read`](Self::read).
    ///
    /// # Errors
    /// As [`write`](Self::write) and [`read`](Self::read).
    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 [`read`](Self::read), or with
    /// [`advance_ready`] across many streams.
    ///
    /// # Errors
    /// [`Illegal`](crate::errors::BunsenErrorKind::Illegal) after the stream
    /// has ended; as the engine's front end.
    pub fn write(
        &mut self,
        samples: &[f32],
    ) -> BunsenResult<()> {
        if self.finished {
            return Err(BunsenError::illegal(
                "the stream has ended; nothing more can be fed",
            ));
        }

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

        if let Some(frames) = self.features.push(samples)? {
            self.ingest(frames);
        }
        self.run_vad(false);
        Ok(())
    }

    /// Runs every decode that is due, and returns what it emitted: each
    /// decode's events in order, then an `interval` draft if one is due.
    ///
    /// # Errors
    /// As the engine's decode, and its text.
    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 decode = self.decode_one(unit, false)?;
            out.extend(self.commit_due(unit, decode)?);
        }
        if let Some(unit) = self.draft_unit() {
            let decode = self.decode_one(unit, true)?;
            out.push(self.draft_from(unit, decode)?);
        }
        Ok(out)
    }

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

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

        if let Some(tail) = self.features.finish()? {
            self.ingest(tail);
        }
        self.frames
            .drop_back(self.driver.engine().end_frames_dropped());

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

    /// Appends frames to the ring, offering them to the level first.
    fn ingest(
        &mut self,
        new: Tensor<3>,
    ) {
        self.level.observe(new.clone());
        self.frames.push(new);
    }

    /// Runs the voice-activity model 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 chunk = vad.chunk;

        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 samples: Vec<f32> = vad.staging.drain(..whole).collect();
            for p in vad.stream.probabilities(samples) {
                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. An open region counts
    /// from where it will start once closed: its onset less the start pad,
    /// snapped down onto the grid, so the window holding the pad is kept. A
    /// window is judged only once the VAD has ruled a start pad past its
    /// end: an onset there would pad back into it.
    fn skip_silence(&mut self) {
        let width = self.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);
            if vad.filter.sample_count() < to + vad.pad {
                return;
            }
            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| vad.padded_start(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.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.emission().triggers.window_full && self.pending_frames() >= width {
                let to = (self.seek + width) * hop;
                if vad
                    .filter
                    .open_since()
                    .is_some_and(|s| vad.padded_start(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 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().min(self.window_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,
        })
    }

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

    /// The request that decodes a unit: its frames, and the level they are
    /// packaged against. Takes `&self`.
    fn request(
        &self,
        unit: Due,
        draft: bool,
    ) -> DecodeRequest<'_, E> {
        let window = self.frames.window(unit.start - self.origin, unit.count);
        DecodeRequest {
            state: &self.state,
            transcript: &self.transcript,
            level: self.level.reference(window.clone()),
            window,
            draft,
        }
    }

    /// Decodes one unit on its own.
    fn decode_one(
        &self,
        unit: Due,
        draft: bool,
    ) -> BunsenResult<WindowDecode<E::Carry>> {
        Ok(self
            .driver
            .engine()
            .decode(vec![self.request(unit, draft)])?
            .pop()
            .expect("one request in, one decode out"))
    }

    /// Commits a decode of a due unit: records the ids, advances the seek
    /// pointer, drops the consumed frames and regions, places the segments
    /// on the clock, and hands the engine its carry.
    ///
    /// A skipped decode commits nothing, and the seek moves past the unit.
    /// Otherwise each complete segment is committed and the seek advances by
    /// the decode's `advance`, at least one frame and at most the unit; the
    /// unfinished tail is decoded again with more audio behind it, and under
    /// [`CommitRule::LastTimestamp`] emitted first as a draft.
    fn commit_due(
        &mut self,
        unit: Due,
        decode: WindowDecode<E::Carry>,
    ) -> BunsenResult<Vec<TranscriptEvent>> {
        let hop = self.hop();
        let mut out = Vec::new();

        if decode.skip {
            self.seek = unit.start + unit.count;
        } else {
            for segment in decode.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 let Some(tail) = decode.tail
                && self.driver.emission().commit == CommitRule::LastTimestamp
                // A tail opening past the unit's audio covers nothing yet.
                && tail.start < unit.count
            {
                let draft = self.segment_at(
                    unit.start + tail.start,
                    unit.start + unit.count,
                    tail.tokens,
                )?;
                out.push(TranscriptEvent::Draft(draft));
            }
            // Always forward, never past the unit.
            self.seek = unit.start + decode.advance.clamp(1, unit.count);
        }

        self.driver
            .engine()
            .commit(&mut self.state, &self.transcript, decode.carry);

        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)
    }

    /// Emits a decode of a draft unit as a draft: on the clock, with text
    /// when the engine can say, 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,
        decode: WindowDecode<E::Carry>,
    ) -> BunsenResult<TranscriptEvent> {
        self.last_draft = self.samples_seen;
        Ok(TranscriptEvent::Draft(self.segment_at(
            unit.start,
            unit.start + unit.count,
            decode.tokens,
        )?))
    }

    /// A segment over stream frames `[start, end)`, timed through the clock,
    /// with text when the engine can say.
    fn segment_at(
        &self,
        start: usize,
        end: usize,
        tokens: Vec<i64>,
    ) -> BunsenResult<TranscriptSegment> {
        let hop = self.hop();
        Ok(TranscriptSegment {
            start: self.clock.time_at(start * hop),
            end: self.clock.time_at(end * hop),
            text: self.driver.engine().text(&tokens)?,
            tokens,
        })
    }

    /// Retains the ring from the seek pointer onward, nothing before it.
    fn drop_before_seek(&mut self) {
        self.frames.drop_front(self.seek - self.origin);
        self.origin = self.seek;
    }
}

impl VoiceActivity {
    /// Where a region with onset `onset` starts once closed: the start pad
    /// back from the onset, no earlier than the previous region's end,
    /// snapped down onto the grid ([`enqueue`](Self::enqueue)'s start).
    fn padded_start(
        &self,
        onset: usize,
    ) -> usize {
        let start = onset.saturating_sub(self.pad).max(self.last_end);
        (start / self.grid * self.grid).max(self.last_end)
    }

    /// Pads a raw region as far as the stream allows, snaps it outward onto
    /// the 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,
            atomic::{
                AtomicUsize,
                Ordering,
            },
        },
        time::Duration,
    };

    use burn::{
        prelude::TensorData,
        tensor::Device,
    };

    use super::*;
    use crate::{
        errors::{
            BunsenErrorKind,
            testing::ErrorMatcher,
        },
        kits::speech::asr_driver::{
            DecodeTriggers,
            EmissionPolicy,
            MaxLevel,
            StreamingFeatures,
            TimedTokens,
            VoiceActivityFilterConfig,
            VoiceActivityModel,
        },
        support::testing::cpu_device,
    };

    /// Samples per second.
    const RATE: usize = 100;
    /// Samples per frame.
    const HOP: usize = 2;
    /// Frames per window.
    const WIDTH: usize = 8;
    /// The VAD's chunk, in samples.
    const CHUNK: usize = 4;

    /// One frame per hop: the hop's mean, as the frame's one feature.
    #[derive(Clone, Debug)]
    struct ToyFeatures {
        staging: Vec<f32>,
        device: Device,
    }

    impl ToyFeatures {
        fn frames(
            &self,
            samples: Vec<f32>,
        ) -> Option<Tensor<3>> {
            let means: Vec<f32> = samples
                .chunks(HOP)
                .map(|hop| hop.iter().sum::<f32>() / HOP as f32)
                .collect();
            let n = means.len();
            (n > 0).then(|| Tensor::from_data(TensorData::new(means, [1, n, 1]), &self.device))
        }
    }

    impl StreamingFeatures for ToyFeatures {
        fn push(
            &mut self,
            samples: &[f32],
        ) -> BunsenResult<Option<Tensor<3>>> {
            self.staging.extend_from_slice(samples);
            let whole = self.staging.len() / HOP * HOP;
            let samples = self.staging.drain(..whole).collect();
            Ok(self.frames(samples))
        }

        fn finish(&mut self) -> BunsenResult<Option<Tensor<3>>> {
            let mut samples = std::mem::take(&mut self.staging);
            if !samples.is_empty() {
                samples.resize(HOP, 0.0);
            }
            Ok(self.frames(samples))
        }
    }

    /// A stream's carry: the commits seen, and the level of the last.
    #[derive(Clone, Debug, Default, PartialEq)]
    struct ToyState {
        commits: usize,
        last_level: Option<f32>,
    }

    /// Decodes each frame to `round(10 * value)`. With `split`, a segment
    /// every `split` frames and the remainder a tail, as timestamps would;
    /// without, the window is one segment.
    #[derive(Clone, Debug)]
    struct ToyEngine {
        device: Device,
        split: Option<usize>,
        decodes: Arc<AtomicUsize>,
    }

    impl ToyEngine {
        fn new(split: Option<usize>) -> Self {
            Self {
                device: cpu_device(),
                split,
                decodes: Arc::new(AtomicUsize::new(0)),
            }
        }

        fn decodes(&self) -> usize {
            self.decodes.load(Ordering::SeqCst)
        }
    }

    impl AsrEngine for ToyEngine {
        type Carry = f32;
        type Features = ToyFeatures;
        type Level = MaxLevel;
        type StreamState = ToyState;

        fn sample_rate(&self) -> usize {
            RATE
        }

        fn hop(&self) -> usize {
            HOP
        }

        fn window_frames(&self) -> usize {
            WIDTH
        }

        fn grid_frames(&self) -> usize {
            2
        }

        fn new_features(&self) -> BunsenResult<ToyFeatures> {
            Ok(ToyFeatures {
                staging: Vec::new(),
                device: self.device.clone(),
            })
        }

        fn new_stream_state(&self) -> ToyState {
            ToyState::default()
        }

        fn decode(
            &self,
            requests: Vec<DecodeRequest<'_, Self>>,
        ) -> BunsenResult<Vec<WindowDecode<f32>>> {
            Ok(requests
                .into_iter()
                .map(|request| {
                    self.decodes.fetch_add(1, Ordering::SeqCst);
                    let level = request.level.max.into_data().try_to_vec::<f32>().unwrap()[0];
                    let values = request.window.into_data().try_to_vec::<f32>().unwrap();
                    let tokens: Vec<i64> =
                        values.iter().map(|v| (v * 10.0).round() as i64).collect();
                    let count = tokens.len();
                    let Some(k) = self.split else {
                        return WindowDecode::whole(count, tokens, level);
                    };
                    let complete = count / k * k;
                    WindowDecode {
                        segments: (0..complete)
                            .step_by(k)
                            .map(|s| TimedTokens {
                                start: s,
                                end: s + k,
                                tokens: tokens[s..s + k].to_vec(),
                            })
                            .collect(),
                        tail: (complete < count).then(|| TimedTokens {
                            start: complete,
                            end: count,
                            tokens: tokens[complete..].to_vec(),
                        }),
                        advance: complete,
                        skip: false,
                        tokens,
                        carry: level,
                    }
                })
                .collect())
        }

        fn commit(
            &self,
            state: &mut ToyState,
            _transcript: &[i64],
            carry: f32,
        ) {
            state.commits += 1;
            state.last_level = Some(carry);
        }

        fn text(
            &self,
            tokens: &[i64],
        ) -> BunsenResult<Option<String>> {
            Ok(Some(
                tokens
                    .iter()
                    .map(i64::to_string)
                    .collect::<Vec<_>>()
                    .join(" "),
            ))
        }
    }

    /// Speech where a chunk's mean magnitude passes a quarter.
    #[derive(Clone, Debug)]
    struct EnergyVad;

    impl VoiceActivityModel for EnergyVad {
        fn sample_rate(&self) -> usize {
            RATE
        }

        fn chunk_size(&self) -> usize {
            CHUNK
        }

        fn new_stream(&self) -> Box<dyn VoiceActivityStream> {
            Box::new(EnergyVad)
        }
    }

    impl VoiceActivityStream for EnergyVad {
        fn probabilities(
            &mut self,
            samples: Vec<f32>,
        ) -> Vec<f32> {
            samples
                .chunks(CHUNK)
                .map(|c| {
                    let energy = c.iter().map(|v| v.abs()).sum::<f32>() / CHUNK as f32;
                    if energy > 0.25 { 1.0 } else { 0.0 }
                })
                .collect()
        }
    }

    /// 80 ms of silence closes a region; 40 ms of padding on each side.
    fn gate() -> VoiceActivityFilterConfig {
        VoiceActivityFilterConfig::new()
            .with_sample_rate(RATE)
            .with_samples_per_chunk(CHUNK)
            .with_min_silence_ms(80)
            .with_speech_pad_ms(40)
    }

    fn driver(
        engine: ToyEngine,
        emission: EmissionPolicy,
    ) -> AsrStreamDriver<ToyEngine> {
        let driver = AsrStreamDriver::new(engine, emission).unwrap();
        if driver.emission().triggers.endpoint {
            driver.with_vad(Arc::new(EnergyVad), gate()).unwrap()
        } else {
            driver
        }
    }

    fn open(driver: &AsrStreamDriver<ToyEngine>) -> AsrStreamContext<ToyEngine> {
        driver
            .new_context(StreamClock::uniform(RATE), LevelPolicy::PerWindow)
            .unwrap()
    }

    /// A ramp of distinct values, no silence.
    fn ramp(n: usize) -> Vec<f32> {
        (0..n).map(|i| ((i * 7) % 11) as f32 / 10.0).collect()
    }

    /// Silence, speech, a long silence, speech, silence.
    fn speech() -> Vec<f32> {
        let mut out = vec![0.0; 40];
        out.extend((0..32).map(|i| 0.5 + (i % 5) as f32 / 10.0));
        out.extend(vec![0.0; 48]);
        out.extend((0..20).map(|i| 0.6 + (i % 3) as f32 / 10.0));
        out.extend(vec![0.0; 40]);
        out
    }

    /// Writes `samples` in pieces of `sizes` (cycled), then ends the stream.
    fn run(
        ctx: &mut AsrStreamContext<ToyEngine>,
        samples: &[f32],
        sizes: &[usize],
    ) -> Vec<TranscriptEvent> {
        let mut out = Vec::new();
        let mut at = 0;
        for &size in sizes.iter().cycle() {
            if at >= samples.len() {
                break;
            }
            let end = (at + size).min(samples.len());
            out.extend(ctx.write_read(&samples[at..end]).unwrap());
            at = end;
        }
        out.extend(ctx.end_read().unwrap());
        out
    }

    fn committed(events: &[TranscriptEvent]) -> Vec<TranscriptSegment> {
        events
            .iter()
            .filter(|e| e.is_committed())
            .map(|e| e.segment().clone())
            .collect()
    }

    /// Offline, every frame is committed once, a window at a time, whatever
    /// the pieces the audio arrives in.
    #[test]
    fn test_offline_commits_every_frame_however_chunked() {
        let samples = ramp(100);
        let driver = driver(ToyEngine::new(None), EmissionPolicy::offline());

        let whole = run(&mut open(&driver), &samples, &[samples.len()]);
        for sizes in [&[1][..], &[3, 7], &[16], &[5, 1, 11]] {
            assert_eq!(run(&mut open(&driver), &samples, sizes), whole, "{sizes:?}");
        }

        // 50 frames: six full windows and a remainder of two.
        let segments = committed(&whole);
        assert_eq!(segments.len(), 7);
        let expected: Vec<i64> = samples
            .chunks(HOP)
            .map(|hop| ((hop[0] + hop[1]) / 2.0 * 10.0).round() as i64)
            .collect();
        let tokens: Vec<i64> = segments.iter().flat_map(|s| s.tokens.clone()).collect();
        assert_eq!(tokens, expected);
        let text: Vec<String> = expected[..WIDTH].iter().map(i64::to_string).collect();
        assert_eq!(segments[0].text, Some(text.join(" ")));
    }

    /// Segments are placed on the stream's clock, origin and all.
    #[test]
    fn test_segments_sit_on_the_clock() {
        let driver = driver(ToyEngine::new(None), EmissionPolicy::offline());
        let mut ctx = open(&driver);
        let events = ctx.anchor_write_read(10.0, &ramp(32)).unwrap();
        let segments = committed(&events);
        assert_eq!(segments.len(), 2);
        // A window is 8 frames of 2 samples at 100 Hz: 0.16 s.
        assert!((segments[0].start - 10.0).abs() < 1e-9);
        assert!((segments[0].end - 10.16).abs() < 1e-9);
        assert!((segments[1].end - 10.32).abs() < 1e-9);
    }

    /// With timed segments, the seek stops at the last complete one; the
    /// tail is decoded again, and under `LastTimestamp` drafted first.
    /// Drafting it changes nothing committed.
    #[test]
    fn test_split_windows_and_their_tails() {
        // 48 frames: windows advance by 6, the last unit is 6 whole frames.
        let samples = ramp(96);
        let complete = driver(ToyEngine::new(Some(3)), EmissionPolicy::offline());
        let last_timestamp = driver(
            ToyEngine::new(Some(3)),
            EmissionPolicy {
                commit: CommitRule::LastTimestamp,
                ..EmissionPolicy::offline()
            },
        );

        let a = run(&mut open(&complete), &samples, &[samples.len()]);
        let b = run(&mut open(&last_timestamp), &samples, &[samples.len()]);

        assert!(a.iter().all(TranscriptEvent::is_committed));
        assert!(b.iter().any(|e| !e.is_committed()));
        assert_eq!(committed(&a), committed(&b));

        let segments = committed(&a);
        assert_eq!(segments.len(), 16);
        assert!(segments.windows(2).all(|w| w[0].end == w[1].start));
        assert!((segments[15].end - 0.96).abs() < 1e-9);
    }

    /// Under `endpoint`, windows of silence are never decoded, and what is
    /// committed covers the speech.
    #[test]
    fn test_silence_is_skipped() {
        let samples = speech();
        let offline_engine = ToyEngine::new(None);
        let gated_engine = ToyEngine::new(None);
        let offline = driver(offline_engine.clone(), EmissionPolicy::offline());
        let gated = driver(gated_engine.clone(), EmissionPolicy::conservative());

        run(&mut open(&offline), &samples, &[samples.len()]);
        let events = run(&mut open(&gated), &samples, &[samples.len()]);

        assert!(gated_engine.decodes() < offline_engine.decodes());
        let segments = committed(&events);
        assert!(!segments.is_empty());
        // Speech spans 0.40 s to 0.72 s and 1.20 s to 1.40 s; regions are
        // padded by 0.04 s and snapped to 0.04 s.
        assert!(segments.first().unwrap().start >= 0.36 - 1e-9);
        assert!(segments.last().unwrap().end <= 1.44 + 1e-9);
        let covered = |t: f64| segments.iter().any(|s| s.start <= t && t < s.end);
        assert!(covered(0.5) && covered(1.3));
        assert!(!covered(0.9));
    }

    /// Drafts on an interval add events, and never change what is
    /// committed: under any chunking, the same as without them.
    ///
    /// The chunking itself can change what is committed: a window decoded
    /// while speech is still open starts at the seek pointer, not at the
    /// region's padded start.
    #[test]
    fn test_drafts_never_change_commits() {
        let samples = speech();
        let conservative = driver(ToyEngine::new(None), EmissionPolicy::conservative());
        let responsive = driver(
            ToyEngine::new(None),
            EmissionPolicy {
                triggers: DecodeTriggers::new()
                    .with_endpoint(true)
                    .with_interval(Some(Duration::from_millis(60))),
                ..EmissionPolicy::conservative()
            },
        );

        for sizes in [&[4][..], &[6, 2], &[samples.len()]] {
            let mut quiet_ctx = open(&conservative);
            let quiet = run(&mut quiet_ctx, &samples, sizes);
            let mut ctx = open(&responsive);
            let loud = run(&mut ctx, &samples, sizes);
            assert_eq!(committed(&loud), committed(&quiet), "{sizes:?}");
            assert_eq!(ctx.engine_state(), quiet_ctx.engine_state(), "{sizes:?}");
            assert_eq!(ctx.transcript(), quiet_ctx.transcript(), "{sizes:?}");
            if sizes[0] < samples.len() {
                assert!(loud.iter().any(|e| !e.is_committed()), "{sizes:?}");
            }
        }
    }

    /// Batched across streams, each stream gets what its own reads give.
    #[test]
    fn test_advance_ready_matches_solo() {
        let streams = [speech(), ramp(70), speech()[20..].to_vec()];
        let driver = driver(ToyEngine::new(Some(3)), EmissionPolicy::conservative());

        let solo: Vec<Vec<TranscriptEvent>> = streams
            .iter()
            .map(|s| run(&mut open(&driver), s, &[10]))
            .collect();

        let mut contexts: Vec<_> = streams.iter().map(|_| open(&driver)).collect();
        let mut batched: Vec<Vec<TranscriptEvent>> = vec![Vec::new(); streams.len()];
        let longest = streams.iter().map(Vec::len).max().unwrap();
        for at in (0..longest).step_by(10) {
            for (ctx, s) in contexts.iter_mut().zip(&streams) {
                if at < s.len() {
                    ctx.write(&s[at..(at + 10).min(s.len())]).unwrap();
                }
            }
            for (i, events) in advance_ready(&driver, &mut contexts)
                .unwrap()
                .into_iter()
                .enumerate()
            {
                batched[i].extend(events);
            }
        }
        for ctx in contexts.iter_mut() {
            ctx.end_input().unwrap();
        }
        for (i, events) in advance_ready(&driver, &mut contexts)
            .unwrap()
            .into_iter()
            .enumerate()
        {
            batched[i].extend(events);
        }
        assert_eq!(batched, solo);
    }

    /// The level reaches the engine: a window's own, or the loudest seen.
    #[test]
    fn test_level_policy_reaches_the_engine() {
        // A loud first window, then quiet ones.
        let mut samples = vec![0.9; 16];
        samples.extend(vec![0.2; 32]);
        let driver = driver(ToyEngine::new(None), EmissionPolicy::offline());

        let level = |policy| {
            let mut ctx = driver
                .new_context(StreamClock::uniform(RATE), policy)
                .unwrap();
            run(&mut ctx, &samples, &[samples.len()]);
            ctx.engine_state().last_level.unwrap()
        };
        assert!((level(LevelPolicy::PerWindow) - 0.2).abs() < 1e-6);
        assert!((level(LevelPolicy::Running) - 0.9).abs() < 1e-6);
    }

    #[test]
    fn test_refuses_bad_settings() {
        let engine = ToyEngine::new(None);
        let never = EmissionPolicy {
            triggers: DecodeTriggers::new().with_window_full(false),
            ..EmissionPolicy::offline()
        };
        ErrorMatcher::kind(BunsenErrorKind::Illegal)
            .message_contains("nothing would ever decode")
            .assert_err(&AsrStreamDriver::new(engine.clone(), never));

        let zero = EmissionPolicy {
            triggers: DecodeTriggers::new()
                .with_endpoint(true)
                .with_interval(Some(Duration::ZERO)),
            ..EmissionPolicy::conservative()
        };
        ErrorMatcher::kind(BunsenErrorKind::Illegal)
            .assert_err(&AsrStreamDriver::new(engine.clone(), zero));

        let ungated = EmissionPolicy {
            triggers: DecodeTriggers::new().with_interval(Some(Duration::from_millis(60))),
            ..EmissionPolicy::offline()
        };
        ErrorMatcher::kind(BunsenErrorKind::Illegal)
            .message_contains("endpoint")
            .assert_err(&AsrStreamDriver::new(engine.clone(), ungated));

        let agreement = EmissionPolicy {
            commit: CommitRule::Agreement { runs: 2 },
            ..EmissionPolicy::offline()
        };
        ErrorMatcher::kind(BunsenErrorKind::Unsupported)
            .message_contains("not implemented")
            .assert_err(&AsrStreamDriver::new(engine.clone(), agreement));

        // Endpoints without a VAD; a clock at another rate.
        let bare = AsrStreamDriver::new(engine.clone(), EmissionPolicy::conservative()).unwrap();
        ErrorMatcher::kind(BunsenErrorKind::Illegal)
            .message_contains("with_vad")
            .assert_err(&bare.new_context(StreamClock::uniform(RATE), LevelPolicy::PerWindow));
        let offline = AsrStreamDriver::new(engine.clone(), EmissionPolicy::offline()).unwrap();
        ErrorMatcher::kind(BunsenErrorKind::Illegal).assert_err(
            &offline.new_context(StreamClock::uniform(RATE * 2), LevelPolicy::PerWindow),
        );

        // A filter at another rate, or another chunk.
        ErrorMatcher::kind(BunsenErrorKind::Illegal).assert_err(
            &offline
                .clone()
                .with_vad(Arc::new(EnergyVad), gate().with_sample_rate(RATE * 2)),
        );
        ErrorMatcher::kind(BunsenErrorKind::Illegal).assert_err(&offline.clone().with_vad(
            Arc::new(EnergyVad),
            gate().with_samples_per_chunk(CHUNK * 2),
        ));

        // Nothing is fed after the end.
        let mut ctx = open(&offline);
        ctx.end_read().unwrap();
        assert!(ctx.end_read().unwrap().is_empty());
        ErrorMatcher::kind(BunsenErrorKind::Illegal)
            .message_contains("the stream has ended")
            .assert_err(&ctx.write(&[0.0; 4]));
    }
}