whisper-nvidia-cli 0.1.0

One-shot agent-native local NVIDIA GPU speech-to-text CLI powered by whisper.cpp
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
//! Decode, resample to 16 kHz mono, inspect, and cut silence.

use std::io::{Read, Seek, SeekFrom};
use std::path::Path;

use regex::Regex;
use std::sync::OnceLock;

use crate::error::Error;
use crate::media_helper::probe_video;

/// Decoded PCM before resampling.
#[derive(Debug, Clone)]
pub struct PcmData {
    /// Interleaved samples, one `i16` per channel per frame.
    pub samples: Vec<i16>,
    /// Sample rate in hertz.
    pub sample_rate: u32,
    /// Number of interleaved channels.
    pub channels: usize,
}

impl PcmData {
    /// Duration in seconds.
    pub fn duration_seconds(&self) -> f64 {
        if self.sample_rate == 0 || self.channels == 0 {
            return 0.0;
        }
        self.samples.len() as f64 / (self.sample_rate as f64 * self.channels as f64)
    }
}

/// Media probe used by `inspect`.
#[derive(Debug, Clone)]
pub struct Probe {
    /// Container or codec name reported by the decoder.
    pub format: String,
    /// Sample rate in hertz.
    pub sample_rate: u32,
    /// Number of channels found in the stream.
    pub channels: usize,
    /// Media length in seconds.
    pub duration_seconds: f64,
    /// True when the source is a video container carrying audio.
    pub is_video: bool,
}

/// Video containers routed to the helper, seeding `config video-extensions`.
pub const VIDEO_EXT: &[&str] = &["mp4", "mov", "m4v", "mkv", "webm", "avi"];

/// Audio containers the native decoder accepts (FR-045).
pub const AUDIO_EXT: &[&str] = &["ogg", "mp3", "wav", "flac"];

/// The accepted container lists for this invocation.
///
/// Published once rather than threaded through every decode entry point, for
/// the same reason the deadline and the memory cap are: the lists belong to the
/// invocation, and the check that consults them sits several call frames below
/// the flag that set them. `decode_file`, `decode_file_with_format` and
/// `inspect_file` are all reached from different depths.
static CONTAINERS: OnceLock<(Vec<String>, Vec<String>)> = OnceLock::new();

/// Publish the operator's container lists. Called once, before any decode.
///
/// Calling it twice is a programming error rather than a race: the second call
/// is ignored, which is why the resolution happens in one place at startup.
pub fn publish_containers(audio: Vec<String>, video: Vec<String>) {
    let _ = CONTAINERS.set((audio, video));
}

/// Audio containers in force, falling back to the compiled seed.
fn audio_ext() -> Vec<String> {
    CONTAINERS.get().map_or_else(
        || AUDIO_EXT.iter().map(|s| (*s).to_string()).collect(),
        |(a, _)| a.clone(),
    )
}

/// Video containers in force, falling back to the compiled seed.
fn video_ext() -> Vec<String> {
    CONTAINERS.get().map_or_else(
        || VIDEO_EXT.iter().map(|s| (*s).to_string()).collect(),
        |(_, v)| v.clone(),
    )
}

/// True when the path looks like a video container.
pub fn is_video_path(path: &Path) -> bool {
    ext(path)
        .map(|e| video_ext().iter().any(|v| v == &e))
        .unwrap_or(false)
}

/// Decode a file or return a format error.
pub fn decode_file(path: &Path) -> Result<PcmData, Error> {
    if !path.exists() {
        return Err(Error::InputNotFound {
            path: path.display().to_string(),
        });
    }
    if is_video_path(path) {
        return Err(Error::HelperMissing);
    }
    // An extension outside the allowlist is a format decision, not a decode failure:
    // report it as such instead of letting symphonia fail with a generic decode error.
    if let Some(e) = ext(path) {
        if !audio_ext().iter().any(|a| a == &e) {
            return Err(Error::UnsupportedFormat { format: e });
        }
    }
    decode_native(path)
}

/// Decode a file whose container the caller declared.
///
/// Every check a forced format needs — is this a video, does the declared
/// container contradict the magic bytes — is answered by the first twelve
/// bytes. Reading the whole file to answer them turned a streaming decode into
/// a resident copy plus a second copy inside the cursor: measured at 89 MiB of
/// peak against 19 MiB for the same 38 MB recording without the flag, and
/// insensitive to `--max-memory`, because no allocation was consulting it.
///
/// Declaring the format is routine. It must not silently disable the only
/// memory guard the product has.
pub fn decode_file_with_format(path: &Path, forced: &str) -> Result<PcmData, Error> {
    let mut file = std::fs::File::open(path).map_err(|e| {
        if e.kind() == std::io::ErrorKind::NotFound {
            Error::InputNotFound {
                path: path.display().to_string(),
            }
        } else {
            Error::Io(e)
        }
    })?;
    let mut header = [0u8; HEADER_PEEK];
    let read = read_up_to(&mut file, &mut header)?;
    let forced = validate_forced(&header[..read], Some(forced))?;
    file.seek(std::io::SeekFrom::Start(0))?;
    decode_cursor(file, forced.as_deref())
}

/// Fill `buf` as far as the source allows, tolerating a short file.
///
/// `read_exact` would turn a recording smaller than the peek window into an
/// unexpected-EOF error, which is not what a short file means.
fn read_up_to<R: Read>(reader: &mut R, buf: &mut [u8]) -> Result<usize, Error> {
    let mut filled = 0;
    while filled < buf.len() {
        match reader.read(&mut buf[filled..])? {
            0 => break,
            n => filled += n,
        }
    }
    Ok(filled)
}

/// Bytes of prefix the container checks need. `detect_container` reads twelve.
const HEADER_PEEK: usize = 12;

/// Reject a declared format that is unusable or contradicted by the bytes.
///
/// Shared by the file path and the stdin path so a forced format is judged the
/// same way regardless of where the bytes came from. Only the prefix is needed,
/// which is what lets the file path stay a stream.
fn validate_forced(header: &[u8], forced: Option<&str>) -> Result<Option<String>, Error> {
    if looks_video(header) {
        return Err(Error::HelperMissing);
    }
    let forced = forced.map(normalize_format);
    if let Some(fmt) = forced.as_deref() {
        if video_ext().iter().any(|v| v == fmt) {
            return Err(Error::HelperMissing);
        }
        if !audio_ext().iter().any(|a| a == fmt) {
            return Err(Error::UnsupportedFormat {
                format: fmt.to_string(),
            });
        }
        // A forced format that contradicts the real container is a lie: fail
        // loudly instead of silently decoding whatever the magic bytes say.
        //
        // The fault is the contradiction, not the format. Answering
        // "unsupported audio format: mp3" for mp3 bytes that are really wav
        // told the caller that a listed format was unlisted, and sent them off
        // to install a helper they did not need.
        if let Some(actual) = detect_container(header) {
            if actual != fmt {
                return Err(Error::FormatMismatch {
                    format: fmt.to_string(),
                });
            }
        }
    }
    Ok(forced)
}

/// Decode bytes already in memory (stdin).
pub fn decode_bytes(bytes: &[u8], forced: Option<&str>) -> Result<PcmData, Error> {
    if bytes.is_empty() {
        return Err(Error::NoInput);
    }
    let head = &bytes[..bytes.len().min(HEADER_PEEK)];
    let forced = validate_forced(head, forced)?;
    decode_cursor(std::io::Cursor::new(bytes.to_vec()), forced.as_deref())
}

/// Lowercase a user-supplied format token and fold known spellings.
fn normalize_format(fmt: &str) -> String {
    let f = fmt.trim().to_ascii_lowercase();
    match f.as_str() {
        "wave" => "wav".to_string(),
        "oga" | "opus" | "vorbis" => "ogg".to_string(),
        "mpeg3" | "mpga" => "mp3".to_string(),
        _ => f,
    }
}

/// Container identified by magic bytes, or `None` when the header is unknown.
fn detect_container(bytes: &[u8]) -> Option<&'static str> {
    if bytes.len() >= 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WAVE" {
        return Some("wav");
    }
    if bytes.starts_with(b"fLaC") {
        return Some("flac");
    }
    if bytes.starts_with(b"OggS") {
        return Some("ogg");
    }
    if bytes.starts_with(b"ID3") {
        return Some("mp3");
    }
    if bytes.len() >= 2 && bytes[0] == 0xFF && (bytes[1] & 0xE0) == 0xE0 {
        return Some("mp3");
    }
    None
}

/// Probe without running the engine.
///
/// `helper` is the media helper resolved by
/// [`resolve_helper`](crate::media_helper::resolve_helper). Video used to
/// short-circuit here with `duration_seconds: 0.0`, `sample_rate: 0` and
/// `channels: 0` — three measurements that were never taken, reported in the
/// same shape as measurements that were. FR-014 exists so an agent can "decidir
/// o modelo antes de pagar", and a duration of zero silently tells it that
/// every video is free.
pub fn inspect_file(path: &Path, helper: Option<&str>) -> Result<Probe, Error> {
    if !path.exists() {
        return Err(Error::InputNotFound {
            path: path.display().to_string(),
        });
    }
    if is_video_path(path) {
        let format = ext(path).unwrap_or_else(|| "video".into());
        // No helper anywhere means this container cannot be measured OR
        // transcribed, which is the same 69 FR-013 already answers for the
        // transcription route. Reporting zeros instead would be a fabricated
        // measurement, and this verb exists to be trusted.
        let (duration_seconds, sample_rate, channels) =
            probe_video(helper.unwrap_or_default(), path, None)?;
        return Ok(Probe {
            format,
            sample_rate,
            channels,
            duration_seconds,
            is_video: true,
        });
    }
    match decode_native(path) {
        Ok(pcm) => Ok(Probe {
            format: detected_format(path),
            sample_rate: pcm.sample_rate,
            channels: pcm.channels,
            duration_seconds: pcm.duration_seconds(),
            is_video: false,
        }),
        // A listed container can carry a codec the native decoder has none for:
        // Opus inside Ogg is the measured case, and symphonia publishes no Opus
        // decoder. Without this branch `inspect` answered 65 for a recording
        // `transcribe` accepts through the same helper, so an agent that
        // consults `inspect` first would skip a file the product can read.
        //
        // Only a decode fault gets here. A blown cap or a spent deadline is a
        // verdict on the run, and spawning a second reader to hear it again
        // costs the host the very memory the refusal was defending.
        Err(err) if err.is_decode_fault() => {
            let (duration_seconds, sample_rate, channels) =
                probe_video(helper.unwrap_or_default(), path, None).map_err(|_| err)?;
            Ok(Probe {
                format: detected_format(path),
                sample_rate,
                channels,
                duration_seconds,
                is_video: false,
            })
        }
        Err(err) => Err(err),
    }
}

/// The container the bytes actually are, falling back to the extension.
///
/// FR-014 says `inspect` reports the media's format, and this used to report
/// the filename's extension instead. Copying a WAV to `recording.opus` made
/// the verb answer `"opus"` for bytes that are RIFF/WAVE, and an agent picking
/// a decoder or a model from that field acts on a claim about the name rather
/// than about the media. `detect_container` already existed and was used only
/// on the stdin path; the capability was there, just not where the verb that
/// promises it could reach.
///
/// The extension remains the fallback: it is the best available answer for a
/// container this product cannot sniff, and it is what the caller passed.
fn detected_format(path: &Path) -> String {
    let sniffed = std::fs::File::open(path).ok().and_then(|mut f| {
        let mut head = [0u8; 16];
        let read = std::io::Read::read(&mut f, &mut head).ok()?;
        detect_container(&head[..read]).map(str::to_string)
    });
    sniffed
        .or_else(|| ext(path))
        .unwrap_or_else(|| "audio".into())
}

fn decode_native(path: &Path) -> Result<PcmData, Error> {
    let file = std::fs::File::open(path).map_err(|e| {
        if e.kind() == std::io::ErrorKind::NotFound {
            Error::InputNotFound {
                path: path.display().to_string(),
            }
        } else {
            Error::Io(e)
        }
    })?;
    decode_cursor(file, ext(path).as_deref())
}

fn decode_cursor<R: Read + Seek + Send + Sync + 'static>(
    mut reader: R,
    hint_ext: Option<&str>,
) -> Result<PcmData, Error> {
    let mut header = [0u8; 12];
    let _ = reader.read(&mut header);
    let _ = reader.seek(SeekFrom::Start(0));
    if header.len() >= 12 && &header[0..4] == b"RIFF" && &header[8..12] == b"WAVE" {
        return decode_wav_reader(reader);
    }
    decode_symphonia(reader, hint_ext)
}

/// Drain a sample iterator, stopping if the invocation is out of time.
///
/// Checked every 64K samples, which is four seconds of 16 kHz mono: frequent
/// enough that a deadline lands inside the decode, rare enough that the clock
/// read costs nothing against the per-sample work.
fn collect_checked<I>(iter: I) -> Result<Vec<i16>, Error>
where
    I: Iterator<Item = Result<i16, hound::Error>>,
{
    // `hound` knows the sample count, so the lower bound of the hint is the
    // real length. Without it this vector grows by doubling and copies itself
    // repeatedly — and it is the very allocation the comment below calls "the
    // one the cap exists to bound", so the transient peak of the growth could
    // trip the cap on a file that fits.
    let mut out = Vec::with_capacity(iter.size_hint().0);
    for (i, sample) in iter.enumerate() {
        if i % 65_536 == 0 {
            if crate::signal::is_shutdown_requested() {
                return Err(crate::signal::shutdown_error().unwrap_or(Error::Interrupted));
            }
            if crate::signal::deadline_exceeded() {
                return Err(Error::Timeout);
            }
            // The buffer being filled here is the allocation the cap exists to
            // bound. Consulting it only after the loop lets the host absorb the
            // whole file first, which is the outcome the flag was added to
            // prevent.
            if crate::gpu::memory_cap_exceeded() {
                return Err(Error::MemoryCap);
            }
        }
        out.push(sample.map_err(|e| Error::AudioDecode(anyhow::anyhow!(e)))?);
    }
    Ok(out)
}

fn decode_wav_reader<R: Read>(reader: R) -> Result<PcmData, Error> {
    let mut wav =
        hound::WavReader::new(reader).map_err(|e| Error::AudioDecode(anyhow::anyhow!(e)))?;
    let spec = wav.spec();
    // Reading straight into `i16` only works for a 16-bit integer file. A 24,
    // 32-bit or floating point wav made hound refuse with "the sample has more
    // bits than the destination type", which surfaced as a decode failure on
    // a format the product claims to accept.
    // WAV takes this path rather than symphonia, so the clock check added to
    // the packet loop never covered the product's most common input. Measured:
    // a twenty minute WAV decoded for sixteen seconds here with `--timeout 1`
    // set, and the batch lost its per-target lines to the watchdog. Collecting
    // straight into a `Vec` gave nowhere to look at the clock, so the loop is
    // explicit now.
    let samples: Vec<i16> = match spec.sample_format {
        hound::SampleFormat::Float => {
            collect_checked(wav.samples::<f32>().map(|s| s.map(float_to_i16)))?
        }
        hound::SampleFormat::Int => {
            let bits = spec.bits_per_sample;
            collect_checked(
                wav.samples::<i32>()
                    .map(|s| s.map(|v| scale_int_to_i16(v, bits))),
            )?
        }
    };
    Ok(PcmData {
        samples,
        sample_rate: spec.sample_rate,
        channels: spec.channels as usize,
    })
}

/// Duration in seconds from container metadata, without decoding any audio.
///
/// `inspect_file` answers the same question by decoding the whole file, which
/// is the right shape for `inspect` — it also reports the real sample rate and
/// channel count. It is the wrong shape for a duration cap checked before
/// transcription: measured on a five minute WAV, the cap check cost 4.55 s and
/// the file was then decoded a second time, so the guard meant to save work
/// doubled it.
///
/// Returns `None` when the container does not declare a frame count. The caller
/// must then fall back rather than assume the recording is short.
pub fn probe_duration(path: &Path) -> Option<f64> {
    use symphonia::core::io::MediaSourceStream;
    use symphonia::core::probe::Hint;

    let file = std::fs::File::open(path).ok()?;
    let mss = MediaSourceStream::new(Box::new(file), Default::default());
    let mut hint = Hint::new();
    if let Some(e) = ext(path) {
        hint.with_extension(&e);
    }
    duration_from_probe(mss, &hint)
}

/// Bytes of prefix handed to the container probe.
///
/// A declared frame count lives in the header, so the probe never needs the
/// recording. Copying this much is negligible next to a file that can be tens
/// of megabytes, and a container that needs more simply declares nothing and
/// falls back to the post-decode check, exactly as an unseekable one does.
const PROBE_PREFIX: usize = 64 * 1024;

/// How many bytes a caller must have buffered before the probe can answer.
///
/// Exposed so a streaming reader can ask at the right moment instead of
/// guessing, and so the number stays defined in one place.
pub fn probe_prefix() -> usize {
    PROBE_PREFIX
}

/// Seconds the container declares for bytes already in memory.
///
/// The file path had a cheap refusal — the header decides in 139 us — and stdin
/// did not, so the identical recording under the identical cap was refused in
/// 0.00 s and 13.5 MiB through `--file` and in 7.99 s and 124.7 MiB through
/// `--stdin`. The guard existed; stdin was simply not one of the places it had
/// been applied.
///
/// Returns `None` when the container declares no frame count. The caller must
/// then fall back rather than assume the recording is short.
pub fn probe_duration_bytes(bytes: &[u8], forced: Option<&str>) -> Option<f64> {
    use symphonia::core::io::MediaSourceStream;
    use symphonia::core::probe::Hint;

    let head = bytes[..bytes.len().min(PROBE_PREFIX)].to_vec();
    let mss = MediaSourceStream::new(Box::new(std::io::Cursor::new(head)), Default::default());
    let mut hint = Hint::new();
    if let Some(f) = forced {
        hint.with_extension(f);
    }
    duration_from_probe(mss, &hint)
}

/// Read the declared frame count off a probed container.
///
/// Shared so the file path and the stdin path answer the same question the same
/// way. Two copies of this arithmetic would be two places for the cap to drift.
fn duration_from_probe(
    mss: symphonia::core::io::MediaSourceStream,
    hint: &symphonia::core::probe::Hint,
) -> Option<f64> {
    use symphonia::core::formats::FormatOptions;
    use symphonia::core::meta::MetadataOptions;

    let probed = symphonia::default::get_probe()
        .format(
            hint,
            mss,
            &FormatOptions::default(),
            &MetadataOptions::default(),
        )
        .ok()?;
    let track = probed
        .format
        .tracks()
        .iter()
        .find(|t| t.codec_params.codec != symphonia::core::codecs::CODEC_TYPE_NULL)?;
    let frames = track.codec_params.n_frames?;
    let rate = track.codec_params.sample_rate? as f64;
    if rate <= 0.0 {
        return None;
    }
    Some(frames as f64 / rate)
}

fn decode_symphonia<R: Read + Seek + Send + Sync + 'static>(
    reader: R,
    hint_ext: Option<&str>,
) -> Result<PcmData, Error> {
    use symphonia::core::audio::AudioBufferRef;
    use symphonia::core::codecs::DecoderOptions;
    use symphonia::core::formats::FormatOptions;
    use symphonia::core::io::MediaSourceStream;
    use symphonia::core::meta::MetadataOptions;
    use symphonia::core::probe::Hint;

    let mss = MediaSourceStream::new(Box::new(ReadSeek(reader)), Default::default());
    let mut hint = Hint::new();
    if let Some(ext) = hint_ext {
        hint.with_extension(ext);
    }
    let probed = symphonia::default::get_probe()
        .format(
            &hint,
            mss,
            &FormatOptions::default(),
            &MetadataOptions::default(),
        )
        .map_err(|e| Error::AudioDecode(anyhow::anyhow!(e)))?;
    let mut format = probed.format;
    let track = format
        .tracks()
        .iter()
        .find(|t| t.codec_params.codec != symphonia::core::codecs::CODEC_TYPE_NULL)
        .ok_or_else(|| Error::AudioDecode(anyhow::anyhow!("no audio track")))?
        .clone();
    let mut decoder = symphonia::default::get_codecs()
        .make(&track.codec_params, &DecoderOptions::default())
        .map_err(|e| Error::AudioDecode(anyhow::anyhow!(e)))?;
    let sample_rate = track.codec_params.sample_rate.unwrap_or(16_000);
    let mut channels = track.codec_params.channels.map(|c| c.count()).unwrap_or(1);
    let mut samples = Vec::new();
    // Decoding is the one long stage that used to be deaf to the clock.
    // Inference checks per slice and the video helper checks per poll, but a
    // native decode ran to completion no matter what. Measured on a five
    // minute WAV: about nine seconds spent here, so a batch under `--timeout`
    // was killed by the watchdog mid-file and FR-003 lost its per-target lines
    // and its summary. Checking every 64 packets is far below the cost of
    // decoding one of them.
    let mut packets = 0u32;
    loop {
        packets = packets.wrapping_add(1);
        if packets.is_multiple_of(64) {
            if crate::signal::is_shutdown_requested() {
                return Err(
                    crate::signal::shutdown_error().unwrap_or(crate::error::Error::Interrupted)
                );
            }
            if crate::signal::deadline_exceeded() {
                return Err(crate::error::Error::Timeout);
            }
            if crate::gpu::memory_cap_exceeded() {
                return Err(crate::error::Error::MemoryCap);
            }
        }
        let packet = match format.next_packet() {
            Ok(p) => p,
            Err(symphonia::core::errors::Error::IoError(e))
                if e.kind() == std::io::ErrorKind::UnexpectedEof =>
            {
                break;
            }
            Err(_) => break,
        };
        if packet.track_id() != track.id {
            continue;
        }
        let Ok(decoded) = decoder.decode(&packet) else {
            continue;
        };
        // Every variant is named. A catch-all here is what made a listed
        // format decode without error and produce nothing: FLAC arrives as
        // S32, fell into `_ => {}`, and the run ended with an empty buffer
        // reported as "unsupported format" — a message about the wrong cause.
        // Naming them all means a future symphonia variant breaks the build
        // instead of vanishing at runtime.
        channels = match decoded {
            AudioBufferRef::U8(buf) => interleave(buf.as_ref(), &mut samples),
            AudioBufferRef::U16(buf) => interleave(buf.as_ref(), &mut samples),
            AudioBufferRef::U24(buf) => interleave(buf.as_ref(), &mut samples),
            AudioBufferRef::U32(buf) => interleave(buf.as_ref(), &mut samples),
            AudioBufferRef::S8(buf) => interleave(buf.as_ref(), &mut samples),
            AudioBufferRef::S16(buf) => interleave(buf.as_ref(), &mut samples),
            AudioBufferRef::S24(buf) => interleave(buf.as_ref(), &mut samples),
            AudioBufferRef::S32(buf) => interleave(buf.as_ref(), &mut samples),
            AudioBufferRef::F32(buf) => interleave(buf.as_ref(), &mut samples),
            AudioBufferRef::F64(buf) => interleave(buf.as_ref(), &mut samples),
        };
    }
    if samples.is_empty() {
        return Err(Error::AudioDecode(anyhow::anyhow!("empty decode")));
    }
    Ok(PcmData {
        samples,
        sample_rate,
        channels: channels.max(1),
    })
}

/// Convert a normalized float sample to 16-bit, clamping out-of-range values.
///
/// A float wav is allowed to exceed 1.0; wrapping it would turn a loud peak
/// into a loud click of the opposite sign.
fn float_to_i16(value: f32) -> i16 {
    (value.clamp(-1.0, 1.0) * i16::MAX as f32) as i16
}

/// Rescale an integer sample of `bits` width into 16-bit.
///
/// hound hands every integer width back as `i32` holding a value already sign
/// extended to `bits`, so the only work left is moving the significant bits
/// into the top 16.
fn scale_int_to_i16(value: i32, bits: u16) -> i16 {
    match bits {
        0..=15 => (value << (16 - bits.max(1))) as i16,
        16 => value as i16,
        _ => (value >> (bits - 16)) as i16,
    }
}

/// Append one decoded buffer as interleaved 16-bit samples.
///
/// Returns the channel count so the caller does not have to re-read the spec.
/// The conversion is symphonia's own, which is what keeps 8, 24, 32-bit and
/// floating point sources from each needing hand-written arithmetic.
fn interleave<S>(buf: &symphonia::core::audio::AudioBuffer<S>, out: &mut Vec<i16>) -> usize
where
    S: symphonia::core::sample::Sample + symphonia::core::conv::IntoSample<i16> + Copy,
{
    // `frames` and `chan` live on `Signal`. `into_sample` needs no import: the
    // bound on `S` already brings the trait into scope.
    use symphonia::core::audio::Signal;

    let channels = buf.spec().channels.count();
    let frames = buf.frames();
    out.reserve(frames * channels);
    for i in 0..frames {
        for ch in 0..channels {
            out.push(buf.chan(ch)[i].into_sample());
        }
    }
    channels
}

struct ReadSeek<R>(R);
impl<R: Read + Seek + Send + Sync> Read for ReadSeek<R> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.0.read(buf)
    }
}
impl<R: Read + Seek + Send + Sync> Seek for ReadSeek<R> {
    fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
        self.0.seek(pos)
    }
}
impl<R: Read + Seek + Send + Sync> symphonia::core::io::MediaSource for ReadSeek<R> {
    fn is_seekable(&self) -> bool {
        true
    }
    fn byte_len(&self) -> Option<u64> {
        None
    }
}

/// Convert any PCM to 16 kHz mono f32.
/// Divisor that maps every `i16` into `[-1.0, 1.0]`.
///
/// 32768, not `i16::MAX`. The signed range is asymmetric — it runs from -32768
/// to 32767 — so dividing by 32767 sends the most negative sample to
/// -1.0000305, outside the range the engine is promised. The excess is 0.003%,
/// which no aggregate notices: RMS, duration and sample count are all unchanged.
/// It shows up only on samples that sit exactly at the floor, which is what
/// clipped audio is made of.
///
/// The cost of the correct divisor is that full scale positive becomes 0.99997
/// instead of 1.0, which is the trade every audio toolchain makes and the only
/// one that keeps both ends inside the interval.
const I16_SCALE: f32 = 32_768.0;

/// The one sample rate the engine accepts, in hertz.
///
/// Named because timestamps are converted against it in a second place, and two
/// literals that must agree are one edit away from disagreeing.
pub const ENGINE_RATE: u32 = 16_000;

/// Fold to one channel and resample to `ENGINE_RATE`, as normalized `f32`.
pub fn to_16k_mono(pcm: &PcmData) -> Result<Vec<f32>, Error> {
    // One `f32` per input sample is the upper bound: the mono fold can only
    // shrink the count, and the resample that may follow is bounded by the
    // ratio. The buffer is taken in a single `collect`, so asking beforehand
    // is the only place a cap can still refuse it.
    crate::gpu::ensure_headroom(pcm.samples.len() as u64 * 4)?;
    let mono: Vec<f32> = if pcm.channels <= 1 {
        pcm.samples.iter().map(|s| *s as f32 / I16_SCALE).collect()
    } else {
        pcm.samples
            .chunks(pcm.channels)
            .map(|c| c.iter().map(|s| *s as f32).sum::<f32>() / (c.len() as f32 * I16_SCALE))
            .collect()
    };
    if pcm.sample_rate == ENGINE_RATE {
        return Ok(mono);
    }
    if pcm.sample_rate == 0 {
        return Err(Error::AudioDecode(anyhow::anyhow!("invalid sample rate")));
    }
    resample_linear(&mono, pcm.sample_rate, ENGINE_RATE)
}

/// Taps in the anti-aliasing filter. Odd, so the delay is a whole sample.
///
/// Thirty-one is enough to put the stopband well down without making the
/// filter cost comparable to the decode it protects.
const LOWPASS_TAPS: usize = 31;

/// Remove everything above the destination's Nyquist before decimating.
///
/// Linear interpolation alone does not resample, it merely picks points. Energy
/// above half the destination rate has nowhere to go and folds back into the
/// audible band as a tone that was never spoken. Measured on the previous code,
/// a one second sine at 48 kHz resampled to 16 kHz:
///
///   12000 Hz in  ->  4000 Hz out, at full amplitude
///   20000 Hz in  ->  4000 Hz out, at full amplitude
///   15000 Hz in  ->  1000 Hz out, at full amplitude
///
/// Those are not attenuated remnants: the RMS was identical to the input, so
/// the whole tone survived at the wrong frequency, in the middle of the range
/// speech occupies. A transcription model is then asked to interpret a sound
/// the microphone never heard.
///
/// The window is Hann and the cutoff sits slightly under Nyquist, which trades
/// a little of the top of the band for a stopband that actually stops.
fn lowpass(input: &[f32], from: u32, to: u32) -> Vec<f32> {
    // Cutoff as a fraction of the source rate. 0.45 rather than 0.5 leaves the
    // transition band somewhere to live.
    let cutoff = 0.45 * to as f64 / from as f64;
    let half = (LOWPASS_TAPS / 2) as isize;
    let mut taps = Vec::with_capacity(LOWPASS_TAPS);
    for i in 0..LOWPASS_TAPS {
        let n = i as isize - half;
        // Windowed sinc: the ideal brick wall, made finite by a Hann window.
        let sinc = if n == 0 {
            2.0 * cutoff
        } else {
            let x = std::f64::consts::PI * n as f64;
            (2.0 * cutoff * x).sin() / x
        };
        let window =
            0.5 - 0.5 * (2.0 * std::f64::consts::PI * i as f64 / (LOWPASS_TAPS - 1) as f64).cos();
        taps.push((sinc * window) as f32);
    }
    let sum: f32 = taps.iter().sum();
    if sum != 0.0 {
        for t in &mut taps {
            *t /= sum;
        }
    }

    let mut out = Vec::with_capacity(input.len());
    for i in 0..input.len() {
        let mut acc = 0.0f32;
        for (k, tap) in taps.iter().enumerate() {
            // Clamp at the edges rather than zero-padding: a hard zero outside
            // the signal is itself a step, and a step is broadband.
            let idx = (i as isize + k as isize - half).clamp(0, input.len() as isize - 1);
            acc += input[idx as usize] * tap;
        }
        out.push(acc);
    }
    out
}

fn resample_linear(input: &[f32], from: u32, to: u32) -> Result<Vec<f32>, Error> {
    if input.is_empty() {
        return Ok(Vec::new());
    }
    // Only downsampling folds. Going up invents no energy above the source's
    // own Nyquist, so filtering there would just blur the signal.
    let filtered;
    let input = if to < from {
        filtered = lowpass(input, from, to);
        &filtered[..]
    } else {
        input
    };
    let ratio = to as f64 / from as f64;
    let out_len = ((input.len() as f64) * ratio).round() as usize;
    let mut out = Vec::with_capacity(out_len);
    for i in 0..out_len {
        let src = i as f64 / ratio;
        let idx = src.floor() as usize;
        let frac = (src - idx as f64) as f32;
        let a = input[idx.min(input.len() - 1)];
        let b = input[(idx + 1).min(input.len() - 1)];
        out.push(a + (b - a) * frac);
    }
    Ok(out)
}

/// Lowest RMS floor, reached at sensitivity 0.0.
const VAD_RMS_MIN: f32 = 0.002;
/// Highest RMS floor, reached at sensitivity 1.0.
const VAD_RMS_MAX: f32 = 0.10;
/// Energy window of the cut, in samples: 30 ms at [`ENGINE_RATE`].
///
/// It was a bare `480` inside the loop, which is the kind of number nobody can
/// change without first proving what it meant.
const VAD_FRAME_SAMPLES: usize = 480;

/// Move a timestamp from the concatenated speech buffer back to the source file.
///
/// Cutting silence hands the engine a buffer whose clock runs faster than the
/// recording's: the removed pauses are simply not there. Every timestamp the
/// engine reports is on that compressed clock, so a segment sitting at 10 s in
/// the file is announced at 2 s once eight seconds of silence have been dropped.
///
/// Nothing else in the envelope disagrees. The text is identical, the segment
/// count is identical, `vad_chunks` is identical, and `duration_seconds` is
/// measured on the original and stays right — which is what makes the envelope
/// self-contradictory rather than merely wrong: it claims twelve seconds of
/// audio whose last segment ends at four.
///
/// FR-006 exists so the caller can cut the recording at the reported offsets.
/// Un-mapped offsets cut silence.
///
/// `chunks` are sample ranges into the original buffer, in order. An empty
/// `chunks` means no cut happened and the clocks already agree.
pub fn source_time(chunks: &[(usize, usize)], total_samples: usize, seconds: f64) -> f64 {
    if chunks.is_empty() || !seconds.is_finite() || seconds <= 0.0 {
        return seconds.max(0.0);
    }
    let target = (seconds * f64::from(ENGINE_RATE)).round() as usize;
    let mut consumed = 0usize;
    let mut last_end = 0usize;
    for (start, end) in chunks {
        let end = (*end).min(total_samples);
        last_end = end;
        let len = end.saturating_sub(*start);
        if target < consumed + len {
            let offset = target - consumed;
            return (*start + offset) as f64 / f64::from(ENGINE_RATE);
        }
        consumed += len;
    }
    // A timestamp past the end of the speech the engine was given. The engine
    // can report one, so it maps to where the speech ended rather than to a
    // point that does not exist.
    last_end as f64 / f64::from(ENGINE_RATE)
}

/// The three numbers that shape the cut, seeded from the compiled defaults.
///
/// They were bare literals inside `vad_chunks` and next to it, which left the
/// operator with a single sensitivity knob and no way to move the window or
/// the floor it maps onto. A recording with loud room noise has no position of
/// that one knob that works, because the whole usable range sits below the
/// noise.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct VadSettings {
    /// Energy window, in samples.
    pub frame_samples: usize,
    /// RMS floor at sensitivity just above zero.
    pub rms_min: f32,
    /// RMS floor at sensitivity 1.0.
    pub rms_max: f32,
}

impl Default for VadSettings {
    fn default() -> Self {
        Self {
            frame_samples: VAD_FRAME_SAMPLES,
            rms_min: VAD_RMS_MIN,
            rms_max: VAD_RMS_MAX,
        }
    }
}

impl VadSettings {
    /// Build from a millisecond window and the two floors.
    ///
    /// The window is given in milliseconds because that is the unit the
    /// operator thinks in; samples are what the loop needs, and the conversion
    /// belongs here rather than at every call site.
    pub fn from_ms(frame_ms: u32, rms_min: f32, rms_max: f32) -> Self {
        let frame_samples = (u64::from(frame_ms) * u64::from(ENGINE_RATE) / 1000).max(1) as usize;
        Self {
            frame_samples,
            rms_min,
            rms_max,
        }
    }

    /// Map the 0..1 sensitivity onto an RMS floor for this configuration.
    ///
    /// The knob is a sensitivity, not an amplitude: normalized speech sits
    /// around RMS 0.05..0.15, so comparing the knob directly against RMS made
    /// an earlier default of 0.5 reject every frame. The linear map keeps 0.5
    /// near 0.05, which is just under quiet speech and above room noise.
    ///
    /// The map never reaches zero, because a floor of zero would call every
    /// frame speech and produce one range covering the whole buffer — the same
    /// result as not cutting, at the cost of a full pass. `vad_chunks` turns
    /// sensitivity zero into a real "off" before this map is ever consulted.
    fn floor(&self, threshold: f32) -> f32 {
        let t = threshold.clamp(0.0, 1.0);
        self.rms_min + t * (self.rms_max - self.rms_min)
    }
}

/// Fade a chunk in and out so splicing it does not click.
///
/// Concatenating cut pieces joins two waveforms at an arbitrary sample, and the
/// amplitude step at that seam is a broadband click. With `--vad 0.5` a 95 s
/// take produced 237 pieces, so the engine received hundreds of impulses that
/// are not speech and tries to decode them as if they were.
///
/// The published measurement behind this is Koenecke and colleagues, "Careless
/// Whisper: Speech-to-Text Hallucination Harms": by logistic regression, the
/// attribute most strongly associated with a Whisper hallucination is a longer
/// non-vocal share of the audio. A seam is not silence, but it is equally not
/// speech, and it lands at exactly the boundary the decoder leans on.
///
/// Five milliseconds is short enough that no phoneme is lost — speech runs at
/// tens of milliseconds per phone — and long enough to remove the step. The
/// shipped default of `--vad 0` cuts nothing, so this runs only for an operator
/// who asked for the cut.
pub fn ramp_edges(chunk: &mut [f32]) {
    const RAMP_MS: usize = 5;
    let ramp = (ENGINE_RATE as usize * RAMP_MS / 1000).min(chunk.len() / 2);
    if ramp == 0 {
        return;
    }
    let last = chunk.len() - 1;
    for i in 0..ramp {
        let gain = i as f32 / ramp as f32;
        chunk[i] *= gain;
        chunk[last - i] *= gain;
    }
}

/// Energy VAD. Empty result means "use the whole file".
pub fn vad_chunks(samples: &[f32], threshold: f32, settings: &VadSettings) -> Vec<(usize, usize)> {
    // Sensitivity zero means OFF, not "the lowest floor". `vad_rms_floor` maps
    // the knob onto `VAD_RMS_MIN..VAD_RMS_MAX`, so its weakest setting is still
    // an energy floor of 0.002 — above the room noise of a real recording.
    // Measured on 95 s of speech: that weakest setting still cut the take into
    // 122 chunks. Every cut costs the decoder the context it uses to choose
    // words, so a knob whose minimum still cuts has no position that means
    // "leave the recording alone". Returning no ranges is exactly that
    // instruction, and it is the contract the caller already honours.
    if samples.is_empty() || threshold <= 0.0 {
        return Vec::new();
    }
    let floor = settings.floor(threshold);
    let frame = settings.frame_samples;
    // One entry per frame, and the frame count is known before the loop starts.
    let mut speech = Vec::with_capacity(samples.len().div_ceil(frame));
    let mut i = 0;
    while i < samples.len() {
        let end = (i + frame).min(samples.len());
        let energy: f32 = samples[i..end].iter().map(|s| s * s).sum::<f32>() / (end - i) as f32;
        speech.push(energy.sqrt() >= floor);
        i = end;
    }
    let mut ranges = Vec::new();
    let mut start: Option<usize> = None;
    for (idx, is_speech) in speech.iter().enumerate() {
        if *is_speech && start.is_none() {
            start = Some(idx * frame);
        } else if !*is_speech {
            if let Some(s) = start.take() {
                ranges.push((s, idx * frame));
            }
        }
    }
    if let Some(s) = start {
        ranges.push((s, samples.len()));
    }
    ranges
}

/// How many lines the caption filter dropped, and what is left.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FilteredText {
    /// The transcript with the matched lines removed.
    pub text: String,
    /// How many lines were dropped.
    pub removed: usize,
}

/// Drop known caption hallucinations.
///
/// `re` is `None` when the operator turned the filter off. That switch has to
/// exist because the seeded patterns are a guess about what is noise, and a
/// guess that deletes the operator's own words with no way to stop it is not a
/// feature. `www\.` in particular removes any line that starts that way,
/// including one a speaker actually said.
///
/// The count comes back with the text for the same reason: the removal used to
/// be silent, so a transcript could come out shorter than the audio with
/// nothing in the envelope admitting that anything had been taken out.
pub fn filter_hallucinations(text: &str, re: Option<&Regex>) -> FilteredText {
    let Some(re) = re else {
        return FilteredText {
            text: text.to_string(),
            removed: 0,
        };
    };
    let removed = text.lines().filter(|l| re.is_match(l)).count();
    let filtered = re.replace_all(text, "");
    let mut result = String::new();
    let mut prev_empty = false;
    for line in filtered.lines() {
        let empty = line.trim().is_empty();
        if empty {
            if !prev_empty {
                result.push('\n');
            }
            prev_empty = true;
        } else {
            result.push_str(line);
            result.push('\n');
            prev_empty = false;
        }
    }
    FilteredText {
        text: result.trim_end().to_string(),
        removed,
    }
}

/// Collapse consecutive identical lines.
pub fn collapse_consecutive_repeats(text: &str) -> String {
    let mut result = String::new();
    let mut last: Option<String> = None;
    for line in text.lines() {
        let content = line.trim();
        if content.is_empty() {
            result.push('\n');
            last = None;
        } else if last.as_deref() == Some(content) {
        } else {
            result.push_str(line);
            result.push('\n');
            last = Some(content.to_string());
        }
    }
    result.trim_end().to_string()
}

/// The seeded caption patterns, one alternative per entry.
///
/// This was a single compiled regex whose alternatives were all Portuguese plus
/// two English words. The product speaks many languages, so a filter that only
/// recognises noise in one of them cleans the Portuguese transcript and leaves
/// the Spanish one exactly as the model hallucinated it. The list below is a
/// seed and not a policy: `config set hallucination-patterns` replaces it.
pub const HALLUCINATION_PATTERNS: &[&str] = &[
    r"legenda(?:s)? por\b",
    r"legendas? pela comunidade",
    r"transcri(?:ção|cao) por\b",
    r"transcri(?:ção|cao) e legendas?\b",
    r"amara\.org",
    r"inscreva-se",
    r"subscribe",
    r"www\.",
    // Spanish, French, German and Italian caption boilerplate, which the
    // Portuguese-only list let through untouched.
    r"subtítulos? (?:por|realizados)",
    r"subtitulado por\b",
    r"sous-titr(?:es|age) (?:par|de)\b",
    r"untertitel (?:von|im auftrag)",
    r"sottotitoli (?:e revisione )?a cura",
];

/// Compile the caption filter from the operator's patterns.
///
/// An invalid pattern is a configuration fault and is reported as one, rather
/// than silently falling back to the seed: an operator who wrote a broken
/// pattern must learn that, not get filtering they did not ask for.
pub fn hallucination_regex_from(patterns: &[String]) -> Result<Regex, Error> {
    let body = patterns.join("|");
    Regex::new(&format!(r"(?im)^[ \t]*({body}).*$"))
        .map_err(|e| Error::Config(format!("invalid hallucination pattern: {e}")))
}

/// The compiled seed, built once.
pub fn default_hallucination_regex() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| {
        let body = HALLUCINATION_PATTERNS.join("|");
        Regex::new(&format!(r"(?im)^[ \t]*({body}).*$")).expect("seeded patterns must compile")
    })
}

fn ext(path: &Path) -> Option<String> {
    path.extension()
        .and_then(|e| e.to_str())
        .map(|s| s.to_ascii_lowercase())
}

fn looks_video(bytes: &[u8]) -> bool {
    bytes.len() > 8 && &bytes[4..8] == b"ftyp"
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The seam is the point of the ramp: both ends reach zero.
    #[test]
    fn ramp_edges_lands_on_zero_at_both_ends() {
        let mut chunk = vec![1.0f32; 16_000];
        ramp_edges(&mut chunk);
        assert_eq!(chunk[0], 0.0, "the leading edge must start at silence");
        assert_eq!(
            chunk[chunk.len() - 1],
            0.0,
            "the trailing edge must end at silence"
        );
        // The middle is untouched: a 5 ms ramp at 16 kHz is 80 samples a side.
        assert_eq!(chunk[8_000], 1.0, "the body of the chunk must not be faded");
    }

    /// A chunk shorter than two ramps must not be faded into nothing, and must
    /// never index out of bounds.
    #[test]
    fn ramp_edges_survives_a_tiny_chunk() {
        for len in [0usize, 1, 2, 3, 79, 160] {
            let mut chunk = vec![1.0f32; len];
            ramp_edges(&mut chunk);
            assert_eq!(chunk.len(), len, "length changed for {len}");
        }
    }

    #[test]
    fn hallucination_strips_legendas() {
        let input = "Hello world\nlegendas por comunidade\nGoodbye";
        let out = filter_hallucinations(input, Some(default_hallucination_regex()));
        assert!(out.text.contains("Hello world"));
        assert!(!out.text.contains("legendas por"));
        assert_eq!(out.removed, 1, "the drop must be counted, not silent");
    }

    /// The filter is a guess about what is noise, so the operator must be able
    /// to stop it removing their own words.
    #[test]
    fn hallucination_filter_off_keeps_everything() {
        let input = "Hello world\nlegendas por comunidade\nGoodbye";
        let out = filter_hallucinations(input, None);
        assert_eq!(out.text, input);
        assert_eq!(out.removed, 0);
    }

    /// A Portuguese-only list cleaned one language and left every other
    /// transcript exactly as the model hallucinated it.
    #[test]
    fn hallucination_reaches_other_languages() {
        for line in [
            "Subtítulos por la comunidad",
            "Sous-titrage par Amara",
            "Untertitel von der Community",
            "Sottotitoli a cura di qualcuno",
        ] {
            let input = format!("Hola\n{line}\nAdios");
            let out = filter_hallucinations(&input, Some(default_hallucination_regex()));
            assert_eq!(out.removed, 1, "not filtered: {line}");
            assert!(out.text.contains("Hola"), "content lost for: {line}");
        }
    }

    /// An operator's own patterns replace the seed rather than adding to it.
    #[test]
    fn operator_patterns_replace_the_seed() {
        let re = hallucination_regex_from(&["ruído meu".to_string()]).expect("compile");
        let out = filter_hallucinations("keep\nruído meu\nkeep2", Some(&re));
        assert_eq!(out.removed, 1);
        // The seeded pattern is no longer in force.
        let out2 = filter_hallucinations("legendas por alguem", Some(&re));
        assert_eq!(out2.removed, 0);
    }

    /// A broken pattern is a configuration fault, never a silent fallback to
    /// filtering the operator did not ask for.
    #[test]
    fn invalid_pattern_is_a_config_error() {
        let err = hallucination_regex_from(&["(unclosed".to_string()]).expect_err("must fail");
        assert_eq!(err.exit_code(), 78);
    }

    #[test]
    fn collapse_repeats() {
        let result = collapse_consecutive_repeats("a\na\nb");
        assert_eq!(result, "a\nb");
    }

    #[test]
    fn vad_empty_on_silence() {
        let samples = vec![0.0f32; 16000];
        assert!(vad_chunks(&samples, 0.5, &VadSettings::default()).is_empty());
    }

    #[test]
    fn vad_empty_on_absolute_silence() {
        let samples = vec![0.0f32; 48_000];
        assert!(vad_chunks(&samples, 0.5, &VadSettings::default()).is_empty());
    }

    #[test]
    fn vad_splits_speech_around_silence() {
        let half = 8_000; // 0.5 s at 16 kHz
        let tone = |n: usize| -> Vec<f32> {
            (0..n)
                .map(|i| (i as f32 * 2.0 * std::f32::consts::PI * 200.0 / 16_000.0).sin() * 0.3)
                .collect()
        };
        let mut samples = tone(half);
        samples.extend(std::iter::repeat_n(0.0f32, half));
        samples.extend(tone(half));
        let chunks = vad_chunks(&samples, 0.5, &VadSettings::default());
        assert!(chunks.len() >= 2, "expected split, got {chunks:?}");
    }

    /// Sensitivity zero must mean OFF, on the very signal that splits.
    ///
    /// The same buffer that produces two or more ranges at 0.5 must produce
    /// none at 0.0, which is the difference between "the quietest floor" and
    /// "no floor at all". Measured on a real 95 s recording, the old weakest
    /// floor still cut it into 122 chunks and the transcript degraded with it;
    /// this test is what keeps that from coming back through the seed.
    #[test]
    fn sensitivity_zero_never_cuts_even_around_silence() {
        let half = 8_000;
        let tone = |n: usize| -> Vec<f32> {
            (0..n)
                .map(|i| (i as f32 * 2.0 * std::f32::consts::PI * 200.0 / 16_000.0).sin() * 0.3)
                .collect()
        };
        let mut samples = tone(half);
        samples.extend(std::iter::repeat_n(0.0f32, half));
        samples.extend(tone(half));
        assert!(
            vad_chunks(&samples, 0.5, &VadSettings::default()).len() >= 2,
            "the fixture must be one that a live cut would split"
        );
        assert!(
            vad_chunks(&samples, 0.0, &VadSettings::default()).is_empty(),
            "sensitivity 0 must hand the whole recording to the engine"
        );
    }

    /// A negative sensitivity is off too, never a floor below the minimum.
    #[test]
    fn sensitivity_below_zero_is_also_off() {
        let samples = vec![0.3f32; 16_000];
        assert!(vad_chunks(&samples, -1.0, &VadSettings::default()).is_empty());
    }

    fn sine_i16(freq: f32, rate: u32, n: usize) -> Vec<i16> {
        (0..n)
            .map(|i| {
                let v = (i as f32 * 2.0 * std::f32::consts::PI * freq / rate as f32).sin() * 0.3;
                (v * i16::MAX as f32) as i16
            })
            .collect()
    }

    #[test]
    fn stereo_48k_matches_mono_16k() {
        let mono = PcmData {
            samples: sine_i16(100.0, 16_000, 16_000),
            sample_rate: 16_000,
            channels: 1,
        };
        let frames = sine_i16(100.0, 48_000, 48_000);
        let mut interleaved = Vec::with_capacity(frames.len() * 2);
        for s in &frames {
            interleaved.push(*s);
            interleaved.push(*s);
        }
        let stereo = PcmData {
            samples: interleaved,
            sample_rate: 48_000,
            channels: 2,
        };

        let a = to_16k_mono(&mono).expect("mono");
        let b = to_16k_mono(&stereo).expect("stereo");
        assert!(
            (a.len() as i64 - b.len() as i64).abs() <= 1,
            "lengths {} vs {}",
            a.len(),
            b.len()
        );
        let n = a.len().min(b.len());
        for i in 0..n {
            assert!(
                (a[i] - b[i]).abs() < 0.01,
                "sample {i}: {} vs {}",
                a[i],
                b[i]
            );
        }
    }

    #[test]
    fn zero_sample_rate_is_decode_error() {
        let pcm = PcmData {
            samples: vec![0i16; 32],
            sample_rate: 0,
            channels: 1,
        };
        assert!(to_16k_mono(&pcm).is_err());
    }

    /// Minimal in-memory WAV so the format tests need no fixture on disk.
    fn wav_bytes() -> Vec<u8> {
        let spec = hound::WavSpec {
            channels: 1,
            sample_rate: 16_000,
            bits_per_sample: 16,
            sample_format: hound::SampleFormat::Int,
        };
        let mut cursor = std::io::Cursor::new(Vec::new());
        {
            let mut w = hound::WavWriter::new(&mut cursor, spec).expect("writer");
            for s in sine_i16(200.0, 16_000, 1_600) {
                w.write_sample(s).expect("sample");
            }
            w.finalize().expect("finalize");
        }
        cursor.into_inner()
    }

    #[test]
    fn unknown_extension_is_unsupported_format() {
        let path = std::env::temp_dir().join(format!(
            "whisper-nvidia-audio-{}-{}.xyz",
            std::process::id(),
            line!()
        ));
        std::fs::write(&path, wav_bytes()).expect("write");
        let err = decode_file(&path).expect_err("must reject");
        let _ = std::fs::remove_file(&path);
        assert!(matches!(err, Error::UnsupportedFormat { .. }), "{err:?}");
        assert_eq!(err.exit_code(), 65);
    }

    /// Declaring a supported format the bytes are not is a contradiction, and
    /// it must not be reported as the format being unsupported: mp3 is listed,
    /// so that answer sends the caller to fix the wrong thing.
    #[test]
    fn lying_forced_format_is_a_mismatch_not_an_unsupported_format() {
        let err = decode_bytes(&wav_bytes(), Some("mp3")).expect_err("must reject");
        assert!(matches!(err, Error::FormatMismatch { .. }), "{err:?}");
        assert_eq!(err.exit_code(), 65);
        assert!(
            err.to_string().contains("does not match"),
            "the message must name the contradiction: {err}"
        );
    }

    /// A format that genuinely is not listed keeps the other answer.
    #[test]
    fn a_format_outside_the_list_is_unsupported() {
        let err = decode_bytes(&wav_bytes(), Some("banana")).expect_err("must reject");
        assert!(matches!(err, Error::UnsupportedFormat { .. }), "{err:?}");
        assert_eq!(err.exit_code(), 65);
    }

    #[test]
    fn honest_forced_format_decodes() {
        let pcm = decode_bytes(&wav_bytes(), Some("wav")).expect("wav decodes");
        assert_eq!(pcm.sample_rate, 16_000);
        assert_eq!(pcm.channels, 1);
    }
}

#[cfg(test)]
mod antialias_tests {
    use super::*;

    fn sine(freq: f64, rate: u32, n: usize) -> Vec<f32> {
        (0..n)
            .map(|i| {
                (2.0 * std::f64::consts::PI * freq * i as f64 / rate as f64).sin() as f32 * 0.3
            })
            .collect()
    }

    fn rms(x: &[f32]) -> f32 {
        if x.is_empty() {
            return 0.0;
        }
        (x.iter().map(|v| v * v).sum::<f32>() / x.len() as f32).sqrt()
    }

    /// Energy above the destination's Nyquist must not survive the resample.
    ///
    /// Without a filter it survives at full amplitude and at the wrong
    /// frequency: 12 kHz became a 4 kHz tone, right where speech lives.
    #[test]
    fn tones_above_nyquist_are_removed_rather_than_folded() {
        let src = 48_000u32;
        for freq in [12_000.0, 15_000.0, 20_000.0] {
            let input = sine(freq, src, src as usize);
            let before = rms(&input);
            let out = resample_linear(&input, src, 16_000).expect("resample");
            let after = rms(&out);
            assert!(
                after < before * 0.2,
                "a {freq} Hz tone is above the 8 kHz Nyquist of the destination \
                 and must not come through: rms went {before:.4} -> {after:.4}"
            );
        }
    }

    /// Speech-band content must survive, or the filter is just a mute button.
    ///
    /// This is the control. A filter that removed everything would satisfy the
    /// assertion above and destroy the product.
    #[test]
    fn tones_below_nyquist_come_through() {
        let src = 48_000u32;
        for freq in [200.0, 1_000.0, 3_000.0] {
            let input = sine(freq, src, src as usize);
            let before = rms(&input);
            let out = resample_linear(&input, src, 16_000).expect("resample");
            let after = rms(&out);
            assert!(
                after > before * 0.7,
                "a {freq} Hz tone is well inside the band and must survive: \
                 rms went {before:.4} -> {after:.4}"
            );
        }
    }

    /// Upsampling is left alone: there is nothing above the source's Nyquist.
    ///
    /// The tone is 500 Hz against a 4 kHz Nyquist. Linear interpolation is
    /// itself a gentle low-pass, so a tone close to Nyquist loses amplitude to
    /// the interpolation regardless of the filter — measured 24% at 3 kHz from
    /// an 8 kHz source. That is a property of the interpolator this change did
    /// not touch, and asserting against it here would have this test fail for a
    /// reason it is not about.
    #[test]
    fn upsampling_does_not_filter() {
        let input = sine(500.0, 8_000, 8_000);
        let before = rms(&input);
        let out = resample_linear(&input, 8_000, 16_000).expect("resample");
        assert!(
            rms(&out) > before * 0.9,
            "upsampling must not attenuate a tone well inside the band: \
             {before:.4} -> {:.4}",
            rms(&out)
        );
        assert_eq!(out.len(), 16_000, "and must produce the right sample count");
    }
}

#[cfg(test)]
mod normalization_tests {
    use super::*;

    /// Every sample must land inside the range the engine is promised.
    ///
    /// The signed 16-bit range is asymmetric, so dividing by `i16::MAX` sends
    /// the floor to -1.0000305. No aggregate sees it — RMS, duration and sample
    /// count are identical either way — and it appears only on samples sitting
    /// exactly at the floor, which is what clipped audio is made of.
    #[test]
    fn the_most_negative_sample_stays_inside_minus_one() {
        let pcm = PcmData {
            samples: vec![i16::MIN, i16::MAX, 0, i16::MIN],
            sample_rate: 16_000,
            channels: 1,
        };
        let out = to_16k_mono(&pcm).expect("convert");
        for (i, v) in out.iter().enumerate() {
            assert!(
                (-1.0..=1.0).contains(v),
                "sample {i} normalised to {v}, outside the range the engine accepts"
            );
        }
        assert_eq!(out[0], -1.0, "the floor maps exactly to -1.0");
    }

    /// The same holds after a stereo fold, which divides by its own count.
    #[test]
    fn a_stereo_fold_also_stays_in_range() {
        let pcm = PcmData {
            samples: vec![i16::MIN, i16::MIN, i16::MAX, i16::MAX],
            sample_rate: 16_000,
            channels: 2,
        };
        let out = to_16k_mono(&pcm).expect("convert");
        assert_eq!(out.len(), 2, "two frames from four interleaved samples");
        for v in &out {
            assert!(
                (-1.0..=1.0).contains(v),
                "a folded frame normalised to {v}, outside the accepted range"
            );
        }
    }

    /// Full scale must still reach nearly one, or the fix is just attenuation.
    #[test]
    fn full_scale_is_not_quietly_scaled_down() {
        let pcm = PcmData {
            samples: vec![i16::MAX],
            sample_rate: 16_000,
            channels: 1,
        };
        let out = to_16k_mono(&pcm).expect("convert");
        assert!(
            out[0] > 0.999,
            "positive full scale must stay at the top of the range, got {}",
            out[0]
        );
    }
}

#[cfg(test)]
mod source_time_tests {
    use super::*;

    /// Two seconds of speech, an eight second pause, two more seconds.
    fn gapped() -> (Vec<(usize, usize)>, usize) {
        let r = ENGINE_RATE as usize;
        (vec![(0, 2 * r), (10 * r, 12 * r)], 12 * r)
    }

    #[test]
    fn a_timestamp_inside_the_first_chunk_is_unchanged() {
        let (chunks, total) = gapped();
        assert_eq!(source_time(&chunks, total, 1.5), 1.5);
    }

    /// The point that proves the mapping exists.
    ///
    /// On the compressed clock the second phrase starts at 2 s, because the
    /// pause was never handed to the engine. In the recording it starts at 10 s.
    #[test]
    fn the_second_chunk_is_moved_past_the_pause() {
        let (chunks, total) = gapped();
        assert_eq!(source_time(&chunks, total, 2.0), 10.0);
        assert_eq!(source_time(&chunks, total, 3.5), 11.5);
    }

    /// The end of the speech is the end of the last chunk, not of the file.
    #[test]
    fn a_timestamp_past_the_speech_lands_where_the_speech_ended() {
        let (chunks, total) = gapped();
        assert_eq!(source_time(&chunks, total, 99.0), 12.0);
    }

    /// No cut means the two clocks are the same clock.
    #[test]
    fn an_empty_cut_is_the_identity() {
        assert_eq!(source_time(&[], 16_000, 7.25), 7.25);
    }

    /// A mapping is only useful if it never moves a timestamp backwards.
    ///
    /// Cutting only removes time, so every mapped offset must be at or after
    /// where it sat on the compressed clock, and the order must survive.
    #[test]
    fn the_mapping_never_runs_backwards() {
        let (chunks, total) = gapped();
        // One sample of slack: the mapping rounds to a sample boundary, so an
        // input that falls between two samples comes back rounded. Accumulating
        // `t += 0.1` instead of deriving it also drifts — the first run of this
        // test reported 0.30000000000000004 mapping "backwards" to 0.3, which
        // was the loop's arithmetic, not the product's.
        let slack = 1.0 / f64::from(ENGINE_RATE);
        let mut previous = 0.0f64;
        for step in 0..=40 {
            let t = f64::from(step) / 10.0;
            let mapped = source_time(&chunks, total, t);
            assert!(
                mapped + slack >= t,
                "cutting removes time, so {t} cannot map to an earlier {mapped}"
            );
            assert!(
                mapped + slack >= previous,
                "order broke: {t} mapped to {mapped}, behind the previous {previous}"
            );
            previous = mapped;
        }
    }
}