whisper-apr 0.3.3

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

use crate::audio::{RingBuffer, SincResampler, SAMPLE_RATE};
use crate::vad::{VadConfig, VoiceActivityDetector};

#[cfg(not(feature = "std"))]
use alloc::vec::Vec;

/// Default chunk duration in seconds (Whisper processes 30s segments)
pub const DEFAULT_CHUNK_DURATION: f32 = 30.0;

/// Default overlap between chunks (for smooth transcription)
pub const DEFAULT_CHUNK_OVERLAP: f32 = 1.0;

/// Minimum speech duration to trigger chunk (prevents spurious triggers)
pub const MIN_SPEECH_DURATION_MS: u32 = 500;

// =============================================================================
// Low-Latency Mode Constants (WAPR-110)
// =============================================================================

/// Low-latency chunk duration (500ms target)
pub const LOW_LATENCY_CHUNK_DURATION: f32 = 0.5;

/// Low-latency overlap (50ms)
pub const LOW_LATENCY_CHUNK_OVERLAP: f32 = 0.05;

/// Low-latency minimum speech duration (100ms)
pub const LOW_LATENCY_MIN_SPEECH_MS: u32 = 100;

/// Low-latency partial threshold (250ms - half a chunk)
pub const LOW_LATENCY_PARTIAL_THRESHOLD: f32 = 0.25;

/// Low-latency buffer duration (shorter for reduced memory)
pub const LOW_LATENCY_BUFFER_DURATION: f32 = 5.0;

/// Low-latency frame size for VAD (10ms = 160 samples at 16kHz)
pub const LOW_LATENCY_FRAME_SIZE_MS: u32 = 10;

/// Latency mode for streaming configuration
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LatencyMode {
    /// Standard latency (30s chunks, higher accuracy)
    #[default]
    Standard,
    /// Low latency (500ms chunks, faster response)
    LowLatency,
    /// Ultra-low latency (250ms chunks, fastest response)
    UltraLow,
    /// Custom latency settings
    Custom,
}

/// Configuration for the streaming audio processor
#[derive(Debug, Clone)]
pub struct StreamingConfig {
    /// Input sample rate (from AudioContext)
    pub input_sample_rate: u32,
    /// Target sample rate for Whisper (always 16000)
    pub output_sample_rate: u32,
    /// Chunk duration in seconds
    pub chunk_duration: f32,
    /// Overlap between chunks in seconds
    pub chunk_overlap: f32,
    /// Enable VAD filtering
    pub enable_vad: bool,
    /// VAD threshold (0.0-1.0)
    pub vad_threshold: f32,
    /// Minimum speech duration in ms before triggering
    pub min_speech_duration_ms: u32,
    /// Ring buffer duration in seconds
    pub buffer_duration: f32,
    /// Latency mode (WAPR-110)
    pub latency_mode: LatencyMode,
}

impl Default for StreamingConfig {
    fn default() -> Self {
        Self {
            input_sample_rate: 44100,
            output_sample_rate: SAMPLE_RATE,
            chunk_duration: DEFAULT_CHUNK_DURATION,
            chunk_overlap: DEFAULT_CHUNK_OVERLAP,
            enable_vad: true,
            vad_threshold: 0.5,
            min_speech_duration_ms: MIN_SPEECH_DURATION_MS,
            buffer_duration: 120.0, // 2 minutes per spec 11.3
            latency_mode: LatencyMode::Standard,
        }
    }
}

impl StreamingConfig {
    /// Create config for a specific input sample rate
    #[must_use]
    pub fn with_sample_rate(input_sample_rate: u32) -> Self {
        Self {
            input_sample_rate,
            ..Default::default()
        }
    }

    /// Create a low-latency configuration (500ms chunks)
    ///
    /// Optimized for real-time applications requiring fast response:
    /// - 500ms chunk duration
    /// - 50ms overlap
    /// - 100ms minimum speech duration
    /// - 5 second buffer
    ///
    /// # Example
    /// ```rust,ignore
    /// let config = StreamingConfig::low_latency();
    /// let processor = StreamingProcessor::new(config);
    /// ```
    #[must_use]
    pub fn low_latency() -> Self {
        Self {
            input_sample_rate: 44100,
            output_sample_rate: SAMPLE_RATE,
            chunk_duration: LOW_LATENCY_CHUNK_DURATION,
            chunk_overlap: LOW_LATENCY_CHUNK_OVERLAP,
            enable_vad: true,
            vad_threshold: 0.5,
            min_speech_duration_ms: LOW_LATENCY_MIN_SPEECH_MS,
            buffer_duration: LOW_LATENCY_BUFFER_DURATION,
            latency_mode: LatencyMode::LowLatency,
        }
    }

    /// Create an ultra-low-latency configuration (250ms chunks)
    ///
    /// Optimized for the fastest possible response:
    /// - 250ms chunk duration
    /// - 25ms overlap
    /// - 50ms minimum speech duration
    /// - 2 second buffer
    ///
    /// Note: Ultra-low latency may reduce transcription accuracy due to
    /// less context being available to the model.
    ///
    /// # Example
    /// ```rust,ignore
    /// let config = StreamingConfig::ultra_low_latency();
    /// let processor = StreamingProcessor::new(config);
    /// ```
    #[must_use]
    pub fn ultra_low_latency() -> Self {
        Self {
            input_sample_rate: 44100,
            output_sample_rate: SAMPLE_RATE,
            chunk_duration: 0.25, // 250ms
            chunk_overlap: 0.025, // 25ms
            enable_vad: true,
            vad_threshold: 0.5,
            min_speech_duration_ms: 50, // 50ms
            buffer_duration: 2.0,       // 2 seconds
            latency_mode: LatencyMode::UltraLow,
        }
    }

    /// Create a custom latency configuration
    ///
    /// Allows fine-tuning of all latency parameters.
    #[must_use]
    pub fn custom_latency(
        chunk_duration: f32,
        chunk_overlap: f32,
        min_speech_duration_ms: u32,
        buffer_duration: f32,
    ) -> Self {
        Self {
            input_sample_rate: 44100,
            output_sample_rate: SAMPLE_RATE,
            chunk_duration,
            chunk_overlap,
            enable_vad: true,
            vad_threshold: 0.5,
            min_speech_duration_ms,
            buffer_duration,
            latency_mode: LatencyMode::Custom,
        }
    }

    /// Set the latency mode (changes mode marker only)
    #[must_use]
    pub fn with_latency_mode(mut self, mode: LatencyMode) -> Self {
        self.latency_mode = mode;
        self
    }

    /// Get the current latency mode
    #[must_use]
    pub const fn latency_mode(&self) -> LatencyMode {
        self.latency_mode
    }

    /// Get the expected latency in milliseconds
    ///
    /// This is approximately the chunk duration plus processing overhead.
    #[must_use]
    pub fn expected_latency_ms(&self) -> f32 {
        self.chunk_duration * 1000.0
    }

    /// Check if this is a low-latency configuration
    #[must_use]
    pub const fn is_low_latency(&self) -> bool {
        matches!(
            self.latency_mode,
            LatencyMode::LowLatency | LatencyMode::UltraLow
        )
    }

    /// Enable VAD (Voice Activity Detection)
    #[must_use]
    pub fn with_vad(mut self) -> Self {
        self.enable_vad = true;
        self
    }

    /// Disable VAD (process all audio regardless of speech)
    #[must_use]
    pub fn without_vad(mut self) -> Self {
        self.enable_vad = false;
        self
    }

    /// Set VAD threshold
    #[must_use]
    pub fn vad_threshold(mut self, threshold: f32) -> Self {
        self.vad_threshold = threshold;
        self
    }

    /// Set chunk duration
    #[must_use]
    pub fn chunk_duration(mut self, duration: f32) -> Self {
        self.chunk_duration = duration;
        self
    }

    /// Set chunk overlap (WAPR-102)
    ///
    /// The overlap is the amount of audio from the end of the previous chunk
    /// that is prepended to the next chunk. This helps maintain context across
    /// chunk boundaries for better transcription accuracy.
    #[must_use]
    pub fn chunk_overlap(mut self, overlap: f32) -> Self {
        self.chunk_overlap = overlap;
        self
    }

    /// Set minimum speech duration in milliseconds
    #[must_use]
    pub fn min_speech_duration_ms(mut self, duration: u32) -> Self {
        self.min_speech_duration_ms = duration;
        self
    }

    /// Get chunk size in samples at output rate
    #[must_use]
    pub fn chunk_samples(&self) -> usize {
        (self.chunk_duration * self.output_sample_rate as f32) as usize
    }

    /// Get overlap size in samples at output rate
    #[must_use]
    pub fn overlap_samples(&self) -> usize {
        (self.chunk_overlap * self.output_sample_rate as f32) as usize
    }
}

/// State of the streaming processor
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessorState {
    /// Waiting for speech to start
    WaitingForSpeech,
    /// Currently accumulating speech
    AccumulatingSpeech,
    /// Partial result is available (enough audio for interim transcription)
    PartialResultReady,
    /// Chunk ready for processing
    ChunkReady,
    /// Currently processing a chunk (transcription in progress)
    Processing,
    /// Error state (recoverable)
    Error,
}

/// Event emitted by the streaming processor (WAPR-100)
#[derive(Debug, Clone, PartialEq)]
pub enum StreamingEvent {
    /// Speech detection started
    SpeechStart,
    /// Speech detection ended
    SpeechEnd,
    /// Partial result is available
    PartialReady {
        /// Audio accumulated so far (samples)
        accumulated_samples: usize,
        /// Duration in seconds
        duration_secs: f32,
    },
    /// Full chunk is ready for transcription
    ChunkReady {
        /// Chunk duration in seconds
        duration_secs: f32,
    },
    /// Processing started
    ProcessingStarted,
    /// Processing completed
    ProcessingCompleted,
    /// Error occurred
    Error(String),
    /// Reset occurred
    Reset,
}

/// Streaming audio processor for real-time transcription
///
/// This processor handles:
/// 1. Buffering incoming audio via lock-free ring buffer
/// 2. Resampling from native rate to 16kHz
/// 3. Voice activity detection to skip silence
/// 4. Accumulating speech into 30s chunks for inference
/// 5. Emitting events for state transitions (WAPR-100)
#[derive(Debug)]
pub struct StreamingProcessor {
    /// Configuration
    config: StreamingConfig,
    /// Ring buffer for incoming audio
    input_buffer: RingBuffer,
    /// Resampler (if input rate != 16kHz)
    resampler: Option<SincResampler>,
    /// Voice activity detector
    vad: VoiceActivityDetector,
    /// Accumulated chunk for inference
    chunk_buffer: Vec<f32>,
    /// Overlap buffer (last N samples of previous chunk)
    overlap_buffer: Vec<f32>,
    /// Current processor state
    state: ProcessorState,
    /// Previous state (for detecting transitions)
    prev_state: ProcessorState,
    /// Consecutive speech frames count
    speech_frames: u32,
    /// Consecutive silence frames count
    silence_frames: u32,
    /// Total samples processed
    samples_processed: u64,
    /// Pending events queue (WAPR-100)
    events: Vec<StreamingEvent>,
    /// Threshold for partial result (samples) - typically 3-5 seconds
    partial_threshold_samples: usize,
    /// Last partial result position (to avoid duplicate events)
    last_partial_position: usize,
}

/// Default partial result threshold: 3 seconds of audio at 16kHz
const DEFAULT_PARTIAL_THRESHOLD_SECS: f32 = 3.0;

impl StreamingProcessor {
    /// Create a new streaming processor with the given configuration
    #[must_use]
    #[allow(clippy::panic)]
    pub fn new(config: StreamingConfig) -> Self {
        let input_buffer =
            RingBuffer::for_duration(config.buffer_duration, config.input_sample_rate);

        let resampler = if config.input_sample_rate == config.output_sample_rate {
            None
        } else {
            Some(
                SincResampler::new(config.input_sample_rate, config.output_sample_rate)
                    .unwrap_or_else(|e| panic!("failed to create resampler: {e}")),
            )
        };

        let vad_config = VadConfig {
            energy_threshold: config.vad_threshold * 4.0, // Scale 0-1 to typical energy threshold
            ..VadConfig::default()
        };
        let vad = VoiceActivityDetector::new(vad_config);

        let chunk_capacity = config.chunk_samples() + config.overlap_samples();
        let partial_threshold_samples =
            (DEFAULT_PARTIAL_THRESHOLD_SECS * config.output_sample_rate as f32) as usize;

        Self {
            config,
            input_buffer,
            resampler,
            vad,
            chunk_buffer: Vec::with_capacity(chunk_capacity),
            overlap_buffer: Vec::new(),
            state: ProcessorState::WaitingForSpeech,
            prev_state: ProcessorState::WaitingForSpeech,
            speech_frames: 0,
            silence_frames: 0,
            samples_processed: 0,
            events: Vec::new(),
            partial_threshold_samples,
            last_partial_position: 0,
        }
    }

    /// Create a processor with default config for the given sample rate
    #[must_use]
    pub fn with_sample_rate(sample_rate: u32) -> Self {
        Self::new(StreamingConfig::with_sample_rate(sample_rate))
    }

    /// Get current processor state
    #[must_use]
    pub const fn state(&self) -> ProcessorState {
        self.state
    }

    /// Get total samples processed
    #[must_use]
    pub const fn samples_processed(&self) -> u64 {
        self.samples_processed
    }

    /// Get current chunk buffer length
    #[must_use]
    pub fn chunk_len(&self) -> usize {
        self.chunk_buffer.len()
    }

    /// Get chunk progress (0.0 to 1.0)
    #[must_use]
    pub fn chunk_progress(&self) -> f32 {
        self.chunk_buffer.len() as f32 / self.config.chunk_samples() as f32
    }

    /// Check if a complete chunk is ready
    #[must_use]
    pub fn has_chunk(&self) -> bool {
        self.state == ProcessorState::ChunkReady
            || self.chunk_buffer.len() >= self.config.chunk_samples()
    }

    // =========================================================================
    // Chunk Overlap Management (WAPR-102)
    // =========================================================================

    /// Get the current overlap buffer length
    #[must_use]
    pub fn overlap_len(&self) -> usize {
        self.overlap_buffer.len()
    }

    /// Get the overlap duration in seconds
    #[must_use]
    pub fn overlap_duration(&self) -> f32 {
        self.overlap_buffer.len() as f32 / self.config.output_sample_rate as f32
    }

    /// Check if overlap buffer has data
    #[must_use]
    pub fn has_overlap(&self) -> bool {
        !self.overlap_buffer.is_empty()
    }

    /// Get the configured overlap size in samples
    #[must_use]
    pub fn configured_overlap_samples(&self) -> usize {
        self.config.overlap_samples()
    }

    /// Get the configured overlap duration in seconds
    #[must_use]
    pub fn configured_overlap_duration(&self) -> f32 {
        self.config.chunk_overlap
    }

    /// Clear the overlap buffer
    ///
    /// This is useful when you want to start fresh without using
    /// the previous chunk's context.
    pub fn clear_overlap(&mut self) {
        self.overlap_buffer.clear();
    }

    /// Get a copy of the overlap buffer for inspection
    #[must_use]
    pub fn get_overlap_buffer(&self) -> Vec<f32> {
        self.overlap_buffer.clone()
    }

    /// Set a custom overlap buffer
    ///
    /// This allows injecting context from a previous transcription
    /// when resuming a streaming session.
    pub fn set_overlap_buffer(&mut self, overlap: Vec<f32>) {
        self.overlap_buffer = overlap;
    }

    // =========================================================================
    // Event Handling (WAPR-100)
    // =========================================================================

    /// Check if there are pending events
    #[must_use]
    pub fn has_events(&self) -> bool {
        !self.events.is_empty()
    }

    /// Get number of pending events
    #[must_use]
    pub fn event_count(&self) -> usize {
        self.events.len()
    }

    /// Drain all pending events
    pub fn drain_events(&mut self) -> Vec<StreamingEvent> {
        core::mem::take(&mut self.events)
    }

    /// Pop the next event (if any)
    pub fn pop_event(&mut self) -> Option<StreamingEvent> {
        if self.events.is_empty() {
            None
        } else {
            Some(self.events.remove(0))
        }
    }

    /// Peek at the next event without removing it
    #[must_use]
    pub fn peek_event(&self) -> Option<&StreamingEvent> {
        self.events.first()
    }

    /// Clear all pending events
    pub fn clear_events(&mut self) {
        self.events.clear();
    }

    // =========================================================================
    // Partial Results (WAPR-100)
    // =========================================================================

    /// Check if a partial result is available
    ///
    /// Returns true if enough audio has been accumulated for an interim transcription
    #[must_use]
    pub fn has_partial(&self) -> bool {
        self.state == ProcessorState::PartialResultReady
            || (self.state == ProcessorState::AccumulatingSpeech
                && self.chunk_buffer.len() >= self.partial_threshold_samples
                && self.chunk_buffer.len() > self.last_partial_position)
    }

    /// Get partial audio for interim transcription
    ///
    /// Returns the currently accumulated audio without consuming it.
    /// The chunk buffer continues to accumulate more audio.
    pub fn get_partial(&mut self) -> Option<Vec<f32>> {
        if !self.has_partial() {
            return None;
        }

        // Update last partial position to avoid duplicate events
        self.last_partial_position = self.chunk_buffer.len();

        // Return a copy of accumulated audio
        Some(self.chunk_buffer.clone())
    }

    /// Get partial audio duration in seconds
    #[must_use]
    pub fn partial_duration(&self) -> f32 {
        self.chunk_buffer.len() as f32 / self.config.output_sample_rate as f32
    }

    /// Set the partial result threshold in seconds
    ///
    /// Controls how much audio must accumulate before a partial result is triggered.
    pub fn set_partial_threshold(&mut self, seconds: f32) {
        self.partial_threshold_samples = (seconds * self.config.output_sample_rate as f32) as usize;
    }

    /// Get the partial result threshold in seconds
    #[must_use]
    pub fn partial_threshold(&self) -> f32 {
        self.partial_threshold_samples as f32 / self.config.output_sample_rate as f32
    }

    // =========================================================================
    // State Transitions (WAPR-100)
    // =========================================================================

    /// Mark processing as started
    ///
    /// Call this when you begin transcribing a chunk
    pub fn mark_processing_started(&mut self) {
        if self.state == ProcessorState::ChunkReady
            || self.state == ProcessorState::PartialResultReady
        {
            self.prev_state = self.state;
            self.state = ProcessorState::Processing;
            self.events.push(StreamingEvent::ProcessingStarted);
        }
    }

    /// Mark processing as completed
    ///
    /// Call this when transcription of a chunk is done
    pub fn mark_processing_completed(&mut self) {
        if self.state == ProcessorState::Processing {
            self.state = ProcessorState::WaitingForSpeech;
            self.events.push(StreamingEvent::ProcessingCompleted);
        }
    }

    /// Mark an error occurred (recoverable)
    pub fn mark_error(&mut self, message: &str) {
        self.prev_state = self.state;
        self.state = ProcessorState::Error;
        self.events.push(StreamingEvent::Error(message.to_string()));
    }

    /// Recover from error state
    pub fn recover_from_error(&mut self) {
        if self.state == ProcessorState::Error {
            self.state = ProcessorState::WaitingForSpeech;
            self.chunk_buffer.clear();
            self.last_partial_position = 0;
        }
    }

    /// Get the previous state (before last transition)
    #[must_use]
    pub const fn prev_state(&self) -> ProcessorState {
        self.prev_state
    }

    /// Emit an event internally
    fn emit_event(&mut self, event: StreamingEvent) {
        self.events.push(event);
    }

    /// Push audio samples into the processor
    ///
    /// Samples should be at the configured input sample rate
    pub fn push_audio(&mut self, samples: &[f32]) {
        self.input_buffer.write_overwrite(samples);
        self.samples_processed += samples.len() as u64;
    }

    /// Process buffered audio and update state
    ///
    /// Call this regularly (e.g., every 100ms) to process accumulated audio
    pub fn process(&mut self) {
        // Read available samples from ring buffer
        let available = self.input_buffer.available_read();
        if available == 0 {
            return;
        }

        // Process in small frames for VAD (30ms = 480 samples at 16kHz)
        let frame_size = (0.030 * self.config.input_sample_rate as f32) as usize;
        let mut input_frame = vec![0.0; frame_size];

        while self.input_buffer.available_read() >= frame_size {
            let read = self.input_buffer.read(&mut input_frame);
            if read < frame_size {
                break;
            }

            // Resample if needed
            let resampled = if let Some(ref resampler) = self.resampler {
                match resampler.resample(&input_frame) {
                    Ok(samples) => samples,
                    Err(_) => continue,
                }
            } else {
                input_frame.clone()
            };

            // VAD check using process_frame
            let is_speech = if self.config.enable_vad {
                // Process through VAD and check for speech events
                let event = self.vad.process_frame(&resampled);
                matches!(
                    event,
                    crate::vad::VadEvent::SpeechStart | crate::vad::VadEvent::Continue
                ) && self.vad.state() == crate::vad::VadState::Speech
            } else {
                true
            };

            self.update_state(is_speech, &resampled);
        }
    }

    /// Update internal state based on VAD result
    fn update_state(&mut self, is_speech: bool, samples: &[f32]) {
        let prev_speech_frames = self.speech_frames;
        let prev_silence_frames = self.silence_frames;

        if is_speech {
            self.speech_frames += 1;
            self.silence_frames = 0;
        } else {
            self.silence_frames += 1;
            self.speech_frames = 0;
        }

        // Track previous state for events
        self.prev_state = self.state;

        // State machine
        match self.state {
            ProcessorState::WaitingForSpeech => {
                if is_speech && self.speech_frames >= self.min_speech_frames() {
                    self.state = ProcessorState::AccumulatingSpeech;
                    // Start with overlap from previous chunk
                    self.chunk_buffer.clear();
                    self.chunk_buffer.extend(&self.overlap_buffer);
                    self.chunk_buffer.extend_from_slice(samples);
                    self.last_partial_position = 0;

                    // Emit speech start event (WAPR-100)
                    self.emit_event(StreamingEvent::SpeechStart);
                }
            }
            ProcessorState::AccumulatingSpeech => {
                self.chunk_buffer.extend_from_slice(samples);

                // Check for partial result threshold (WAPR-100)
                if self.chunk_buffer.len() >= self.partial_threshold_samples
                    && self.chunk_buffer.len() > self.last_partial_position
                    && self.last_partial_position == 0
                {
                    // First partial result ready
                    self.emit_event(StreamingEvent::PartialReady {
                        accumulated_samples: self.chunk_buffer.len(),
                        duration_secs: self.partial_duration(),
                    });
                }

                // Check if chunk is complete
                if self.chunk_buffer.len() >= self.config.chunk_samples() {
                    self.state = ProcessorState::ChunkReady;
                    let duration =
                        self.chunk_buffer.len() as f32 / self.config.output_sample_rate as f32;
                    self.emit_event(StreamingEvent::ChunkReady {
                        duration_secs: duration,
                    });
                }
                // Or if we hit extended silence (end of utterance)
                else if !is_speech && self.silence_frames >= self.max_silence_frames() {
                    // Emit speech end event
                    self.emit_event(StreamingEvent::SpeechEnd);

                    // Partial chunk is ready
                    if self.chunk_buffer.len() >= self.config.overlap_samples() * 2 {
                        self.state = ProcessorState::ChunkReady;
                        let duration =
                            self.chunk_buffer.len() as f32 / self.config.output_sample_rate as f32;
                        self.emit_event(StreamingEvent::ChunkReady {
                            duration_secs: duration,
                        });
                    } else {
                        // Too short, discard and wait for more speech
                        self.state = ProcessorState::WaitingForSpeech;
                        self.chunk_buffer.clear();
                        self.last_partial_position = 0;
                    }
                }
            }
            ProcessorState::PartialResultReady => {
                // Continue accumulating while partial is being processed
                self.chunk_buffer.extend_from_slice(samples);

                // Check if full chunk is now ready
                if self.chunk_buffer.len() >= self.config.chunk_samples() {
                    self.state = ProcessorState::ChunkReady;
                    let duration =
                        self.chunk_buffer.len() as f32 / self.config.output_sample_rate as f32;
                    self.emit_event(StreamingEvent::ChunkReady {
                        duration_secs: duration,
                    });
                }
            }
            ProcessorState::ChunkReady | ProcessorState::Processing | ProcessorState::Error => {
                // Waiting for chunk to be consumed / processing to complete / error recovery
            }
        }

        // Suppress unused variable warnings
        let _ = prev_speech_frames;
        let _ = prev_silence_frames;
    }

    /// Get minimum speech frames to trigger accumulation
    fn min_speech_frames(&self) -> u32 {
        let frame_duration_ms = 30;
        self.config.min_speech_duration_ms / frame_duration_ms
    }

    /// Get maximum silence frames before ending chunk
    fn max_silence_frames(&self) -> u32 {
        let _ = self; // Used for consistency with min_speech_frames
                      // 1 second of silence
        let frame_duration_ms = 30;
        1000 / frame_duration_ms
    }

    /// Get the accumulated chunk for inference
    ///
    /// Returns None if no chunk is ready. After calling this, the processor
    /// resets to wait for the next utterance.
    pub fn get_chunk(&mut self) -> Option<Vec<f32>> {
        if !self.has_chunk() {
            return None;
        }

        // Save overlap for next chunk
        let overlap_size = self.config.overlap_samples();
        if self.chunk_buffer.len() > overlap_size {
            let start = self.chunk_buffer.len() - overlap_size;
            self.overlap_buffer = self.chunk_buffer[start..].to_vec();
        }

        // Pad to full chunk size if needed
        let target_size = self.config.chunk_samples();
        if self.chunk_buffer.len() < target_size {
            self.chunk_buffer.resize(target_size, 0.0);
        }

        // Take the chunk
        let chunk = core::mem::take(&mut self.chunk_buffer);
        self.prev_state = self.state;
        self.state = ProcessorState::WaitingForSpeech;
        self.speech_frames = 0;
        self.silence_frames = 0;
        self.last_partial_position = 0;

        Some(chunk)
    }

    /// Force flush any accumulated audio as a chunk
    ///
    /// Useful for end-of-stream processing
    pub fn flush(&mut self) -> Option<Vec<f32>> {
        if self.chunk_buffer.is_empty() {
            return None;
        }

        // Process any remaining buffered audio
        self.process();

        // Pad to minimum size (overlap * 2)
        let min_size = self.config.overlap_samples() * 2;
        if self.chunk_buffer.len() < min_size {
            return None;
        }

        // Pad to full chunk size
        let target_size = self.config.chunk_samples();
        self.chunk_buffer.resize(target_size, 0.0);

        let chunk = core::mem::take(&mut self.chunk_buffer);
        self.prev_state = self.state;
        self.state = ProcessorState::WaitingForSpeech;
        self.overlap_buffer.clear();
        self.last_partial_position = 0;

        Some(chunk)
    }

    /// Reset the processor state
    pub fn reset(&mut self) {
        self.input_buffer.clear();
        self.chunk_buffer.clear();
        self.overlap_buffer.clear();
        self.prev_state = self.state;
        self.state = ProcessorState::WaitingForSpeech;
        self.speech_frames = 0;
        self.silence_frames = 0;
        self.last_partial_position = 0;
        self.emit_event(StreamingEvent::Reset);
    }

    /// Get statistics about the processor
    #[must_use]
    pub fn stats(&self) -> ProcessorStats {
        ProcessorStats {
            samples_processed: self.samples_processed,
            buffer_available: self.input_buffer.available_read(),
            buffer_capacity: self.input_buffer.capacity(),
            chunk_progress: self.chunk_progress(),
            state: self.state,
        }
    }
}

/// Statistics about the streaming processor
#[derive(Debug, Clone)]
pub struct ProcessorStats {
    /// Total samples processed
    pub samples_processed: u64,
    /// Samples available in ring buffer
    pub buffer_available: usize,
    /// Ring buffer capacity
    pub buffer_capacity: usize,
    /// Current chunk progress (0.0-1.0)
    pub chunk_progress: f32,
    /// Current state
    pub state: ProcessorState,
}

impl ProcessorStats {
    /// Get buffer fill percentage
    #[must_use]
    pub fn buffer_fill(&self) -> f32 {
        if self.buffer_capacity == 0 {
            0.0
        } else {
            self.buffer_available as f32 / self.buffer_capacity as f32 * 100.0
        }
    }

    /// Get total duration processed in seconds
    #[must_use]
    pub fn duration_processed(&self, sample_rate: u32) -> f32 {
        self.samples_processed as f32 / sample_rate as f32
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    // =========================================================================
    // Configuration Tests
    // =========================================================================

    #[test]
    fn test_config_default() {
        let config = StreamingConfig::default();
        assert_eq!(config.input_sample_rate, 44100);
        assert_eq!(config.output_sample_rate, 16000);
        assert!((config.chunk_duration - 30.0).abs() < f32::EPSILON);
        assert!(config.enable_vad);
    }

    #[test]
    fn test_config_with_sample_rate() {
        let config = StreamingConfig::with_sample_rate(48000);
        assert_eq!(config.input_sample_rate, 48000);
    }

    #[test]
    fn test_config_without_vad() {
        let config = StreamingConfig::default().without_vad();
        assert!(!config.enable_vad);
    }

    #[test]
    fn test_config_chunk_samples() {
        let config = StreamingConfig::default();
        // 30s * 16000 = 480000 samples
        assert_eq!(config.chunk_samples(), 480000);
    }

    #[test]
    fn test_config_overlap_samples() {
        let config = StreamingConfig::default();
        // 1s * 16000 = 16000 samples
        assert_eq!(config.overlap_samples(), 16000);
    }

    // =========================================================================
    // Processor Creation Tests
    // =========================================================================

    #[test]
    fn test_processor_new() {
        let processor = StreamingProcessor::new(StreamingConfig::default());
        assert_eq!(processor.state(), ProcessorState::WaitingForSpeech);
        assert_eq!(processor.samples_processed(), 0);
        assert_eq!(processor.chunk_len(), 0);
    }

    #[test]
    fn test_processor_with_sample_rate() {
        let processor = StreamingProcessor::with_sample_rate(48000);
        assert_eq!(processor.config.input_sample_rate, 48000);
    }

    #[test]
    fn test_processor_same_sample_rate() {
        // When input == output rate, no resampler needed
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            ..Default::default()
        };
        let processor = StreamingProcessor::new(config);
        assert!(processor.resampler.is_none());
    }

    #[test]
    fn test_processor_different_sample_rate() {
        // When input != output rate, resampler is created
        let config = StreamingConfig::default(); // 44100 -> 16000
        let processor = StreamingProcessor::new(config);
        assert!(processor.resampler.is_some());
    }

    // =========================================================================
    // Audio Push Tests
    // =========================================================================

    #[test]
    fn test_push_audio() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        let samples = vec![0.0; 1000];
        processor.push_audio(&samples);
        assert_eq!(processor.samples_processed(), 1000);
    }

    #[test]
    fn test_push_audio_multiple() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        processor.push_audio(&vec![0.0; 500]);
        processor.push_audio(&vec![0.0; 500]);
        assert_eq!(processor.samples_processed(), 1000);
    }

    // =========================================================================
    // State Tests
    // =========================================================================

    #[test]
    fn test_initial_state() {
        let processor = StreamingProcessor::new(StreamingConfig::default());
        assert_eq!(processor.state(), ProcessorState::WaitingForSpeech);
        assert!(!processor.has_chunk());
    }

    #[test]
    fn test_chunk_progress_empty() {
        let processor = StreamingProcessor::new(StreamingConfig::default());
        assert!((processor.chunk_progress() - 0.0).abs() < f32::EPSILON);
    }

    // =========================================================================
    // Reset Tests
    // =========================================================================

    #[test]
    fn test_reset() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        processor.push_audio(&vec![0.1; 10000]);
        processor.reset();
        assert_eq!(processor.state(), ProcessorState::WaitingForSpeech);
        assert_eq!(processor.chunk_len(), 0);
    }

    // =========================================================================
    // Stats Tests
    // =========================================================================

    #[test]
    fn test_stats() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        processor.push_audio(&vec![0.0; 1000]);
        let stats = processor.stats();
        assert_eq!(stats.samples_processed, 1000);
        assert_eq!(stats.state, ProcessorState::WaitingForSpeech);
    }

    #[test]
    fn test_stats_buffer_fill() {
        let stats = ProcessorStats {
            samples_processed: 0,
            buffer_available: 500,
            buffer_capacity: 1000,
            chunk_progress: 0.0,
            state: ProcessorState::WaitingForSpeech,
        };
        assert!((stats.buffer_fill() - 50.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_stats_duration_processed() {
        let stats = ProcessorStats {
            samples_processed: 16000,
            buffer_available: 0,
            buffer_capacity: 1000,
            chunk_progress: 0.0,
            state: ProcessorState::WaitingForSpeech,
        };
        assert!((stats.duration_processed(16000) - 1.0).abs() < f32::EPSILON);
    }

    // =========================================================================
    // VAD Integration Tests
    // =========================================================================

    #[test]
    fn test_vad_disabled() {
        let config = StreamingConfig::default().without_vad();
        let processor = StreamingProcessor::new(config);
        assert!(!processor.config.enable_vad);
    }

    // =========================================================================
    // Flush Tests
    // =========================================================================

    #[test]
    fn test_flush_empty() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        assert!(processor.flush().is_none());
    }

    // =========================================================================
    // Get Chunk Tests
    // =========================================================================

    #[test]
    fn test_get_chunk_not_ready() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        assert!(processor.get_chunk().is_none());
    }

    // =========================================================================
    // Processing Tests
    // =========================================================================

    #[test]
    fn test_process_silence() {
        // Use same sample rate to avoid resampling complexity
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            enable_vad: true,
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);

        // Push silence and process
        let silence = vec![0.0; 4800]; // 300ms at 16kHz
        processor.push_audio(&silence);
        processor.process();

        // Should stay in waiting state for silence
        assert_eq!(processor.state(), ProcessorState::WaitingForSpeech);
    }

    #[test]
    fn test_process_with_vad_disabled() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            enable_vad: false,
            chunk_duration: 0.5, // Short chunk for testing
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);

        // With VAD disabled, all audio is treated as speech
        let audio = vec![0.1; 8000]; // 500ms at 16kHz
        processor.push_audio(&audio);
        processor.process();

        // Should have accumulated some audio
        assert!(processor.chunk_len() > 0 || processor.has_chunk());
    }

    #[test]
    fn test_process_empty_buffer() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());

        // Process without pushing any audio
        processor.process();

        // Should stay in initial state
        assert_eq!(processor.state(), ProcessorState::WaitingForSpeech);
        assert_eq!(processor.chunk_len(), 0);
    }

    #[test]
    fn test_config_vad_threshold() {
        let config = StreamingConfig::default().vad_threshold(0.8);
        assert!((config.vad_threshold - 0.8).abs() < f32::EPSILON);
    }

    #[test]
    fn test_config_chunk_duration() {
        let config = StreamingConfig::default().chunk_duration(10.0);
        assert!((config.chunk_duration - 10.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_stats_buffer_fill_zero_capacity() {
        let stats = ProcessorStats {
            samples_processed: 0,
            buffer_available: 0,
            buffer_capacity: 0,
            chunk_progress: 0.0,
            state: ProcessorState::WaitingForSpeech,
        };
        assert!((stats.buffer_fill() - 0.0).abs() < f32::EPSILON);
    }

    // =========================================================================
    // State Machine Tests
    // =========================================================================

    #[test]
    fn test_update_state_accumulating() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            enable_vad: false,
            chunk_duration: 0.1,       // Very short chunk (1600 samples)
            min_speech_duration_ms: 0, // Immediate speech detection
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);

        // Manually trigger state transition
        let samples = vec![0.1; 320]; // 20ms frame
        processor.state = ProcessorState::AccumulatingSpeech;
        processor.update_state(true, &samples);

        assert_eq!(processor.state(), ProcessorState::AccumulatingSpeech);
        assert_eq!(processor.chunk_buffer.len(), 320);
    }

    #[test]
    fn test_update_state_chunk_ready() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            enable_vad: false,
            chunk_duration: 0.02, // Very short chunk (320 samples)
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);

        // Fill chunk buffer to trigger ready state
        processor.chunk_buffer = vec![0.1; 320];
        processor.state = ProcessorState::AccumulatingSpeech;

        let samples = vec![0.1; 320];
        processor.update_state(true, &samples);

        // Should transition to ChunkReady
        assert_eq!(processor.state(), ProcessorState::ChunkReady);
    }

    #[test]
    fn test_update_state_silence_ends_speech() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            chunk_duration: 30.0,
            chunk_overlap: 0.1, // Small overlap
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);

        // Set up as if we're accumulating speech
        processor.state = ProcessorState::AccumulatingSpeech;
        processor.chunk_buffer = vec![0.1; 5000]; // Some accumulated audio
        processor.silence_frames = 50; // Extended silence

        let samples = vec![0.0; 320];
        processor.update_state(false, &samples);

        // Should transition to ChunkReady due to extended silence
        assert_eq!(processor.state(), ProcessorState::ChunkReady);
    }

    #[test]
    fn test_update_state_short_segment_discarded() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            chunk_duration: 30.0,
            chunk_overlap: 1.0, // 16000 sample overlap
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);

        // Set up as if we're accumulating speech with very little audio
        processor.state = ProcessorState::AccumulatingSpeech;
        processor.chunk_buffer = vec![0.1; 100]; // Very short
        processor.silence_frames = 50; // Extended silence

        let samples = vec![0.0; 320];
        processor.update_state(false, &samples);

        // Should go back to waiting (too short to be a valid chunk)
        assert_eq!(processor.state(), ProcessorState::WaitingForSpeech);
        assert!(processor.chunk_buffer.is_empty());
    }

    #[test]
    fn test_update_state_chunk_ready_stays() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        processor.state = ProcessorState::ChunkReady;

        let samples = vec![0.1; 320];
        processor.update_state(true, &samples);

        // Should stay in ChunkReady until consumed
        assert_eq!(processor.state(), ProcessorState::ChunkReady);
    }

    // =========================================================================
    // Get Chunk Tests
    // =========================================================================

    #[test]
    fn test_get_chunk_ready() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            chunk_duration: 0.02, // 320 samples
            chunk_overlap: 0.01,  // 160 samples
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);

        // Fill chunk buffer to be ready (larger than chunk size)
        processor.chunk_buffer = vec![0.1; 400];
        processor.state = ProcessorState::ChunkReady;

        let chunk = processor.get_chunk();
        assert!(chunk.is_some());

        let chunk = chunk.expect("chunk should exist");
        // get_chunk takes the whole buffer (doesn't trim)
        assert_eq!(chunk.len(), 400);

        // Should reset state
        assert_eq!(processor.state(), ProcessorState::WaitingForSpeech);
    }

    #[test]
    fn test_get_chunk_saves_overlap() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            chunk_duration: 0.02, // 320 samples
            chunk_overlap: 0.01,  // 160 samples
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);

        // Fill chunk buffer
        processor.chunk_buffer = vec![0.1; 400];
        processor.state = ProcessorState::ChunkReady;

        let _ = processor.get_chunk();

        // Should have saved overlap
        assert_eq!(processor.overlap_buffer.len(), 160);
    }

    #[test]
    fn test_get_chunk_pads_short_chunk() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            chunk_duration: 0.02, // 320 samples
            chunk_overlap: 0.0,
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);

        // Fill with less than full chunk
        processor.chunk_buffer = vec![0.1; 200];
        processor.state = ProcessorState::ChunkReady;

        let chunk = processor.get_chunk().expect("should get chunk");

        // Should be padded to full size
        assert_eq!(chunk.len(), 320);
    }

    // =========================================================================
    // Flush Tests
    // =========================================================================

    #[test]
    fn test_flush_with_accumulated_data() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            chunk_duration: 0.1, // 1600 samples
            chunk_overlap: 0.01, // 160 samples
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);

        // Accumulate some data
        processor.chunk_buffer = vec![0.1; 500]; // More than overlap * 2
        processor.state = ProcessorState::AccumulatingSpeech;

        let flushed = processor.flush();
        assert!(flushed.is_some());

        let flushed = flushed.expect("should flush");
        assert_eq!(flushed.len(), 1600); // Padded to full chunk

        // Should reset state
        assert_eq!(processor.state(), ProcessorState::WaitingForSpeech);
        assert!(processor.overlap_buffer.is_empty());
    }

    #[test]
    fn test_flush_too_short() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            chunk_duration: 0.1,
            chunk_overlap: 0.05, // 800 samples, so need > 1600
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);

        // Too little data
        processor.chunk_buffer = vec![0.1; 100];

        let flushed = processor.flush();
        assert!(flushed.is_none());
    }

    // =========================================================================
    // Min/Max Frame Tests
    // =========================================================================

    #[test]
    fn test_min_speech_frames() {
        let config = StreamingConfig {
            min_speech_duration_ms: 300,
            ..Default::default()
        };
        let processor = StreamingProcessor::new(config);
        // 300ms / 30ms per frame = 10 frames
        assert_eq!(processor.min_speech_frames(), 10);
    }

    #[test]
    fn test_max_silence_frames() {
        let processor = StreamingProcessor::new(StreamingConfig::default());
        // 1000ms / 30ms per frame = 33 frames
        assert_eq!(processor.max_silence_frames(), 33);
    }

    // =========================================================================
    // Waiting for Speech State Tests
    // =========================================================================

    #[test]
    fn test_waiting_transitions_to_accumulating() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            min_speech_duration_ms: 0, // Immediate
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);

        // Pre-populate overlap buffer
        processor.overlap_buffer = vec![0.05; 100];
        processor.speech_frames = 1; // Already detected speech

        let samples = vec![0.1; 320];
        processor.update_state(true, &samples);

        // Should transition to AccumulatingSpeech
        assert_eq!(processor.state(), ProcessorState::AccumulatingSpeech);
        // Should include overlap + new samples
        assert!(processor.chunk_buffer.len() >= 320);
    }

    // =========================================================================
    // WAPR-100: Enhanced State Machine Tests
    // =========================================================================

    #[test]
    fn test_streaming_event_variants() {
        // Test all event variants can be created
        let speech_start = StreamingEvent::SpeechStart;
        let speech_end = StreamingEvent::SpeechEnd;
        let partial_ready = StreamingEvent::PartialReady {
            accumulated_samples: 48000,
            duration_secs: 3.0,
        };
        let chunk_ready = StreamingEvent::ChunkReady {
            duration_secs: 30.0,
        };
        let processing_started = StreamingEvent::ProcessingStarted;
        let processing_completed = StreamingEvent::ProcessingCompleted;
        let error = StreamingEvent::Error("test error".to_string());
        let reset = StreamingEvent::Reset;

        // Test Debug and Clone
        assert!(format!("{speech_start:?}").contains("SpeechStart"));
        assert!(format!("{speech_end:?}").contains("SpeechEnd"));
        assert!(format!("{partial_ready:?}").contains("PartialReady"));
        assert!(format!("{chunk_ready:?}").contains("ChunkReady"));
        assert!(format!("{processing_started:?}").contains("ProcessingStarted"));
        assert!(format!("{processing_completed:?}").contains("ProcessingCompleted"));
        assert!(format!("{error:?}").contains("Error"));
        assert!(format!("{reset:?}").contains("Reset"));

        // Test Clone
        let cloned = speech_start.clone();
        assert_eq!(cloned, StreamingEvent::SpeechStart);
    }

    #[test]
    fn test_processor_state_new_variants() {
        // Test new state variants
        let partial_ready = ProcessorState::PartialResultReady;
        let processing = ProcessorState::Processing;
        let error = ProcessorState::Error;

        assert!(format!("{partial_ready:?}").contains("PartialResultReady"));
        assert!(format!("{processing:?}").contains("Processing"));
        assert!(format!("{error:?}").contains("Error"));

        // Test equality
        assert_ne!(
            ProcessorState::PartialResultReady,
            ProcessorState::Processing
        );
        assert_ne!(ProcessorState::Processing, ProcessorState::Error);
    }

    #[test]
    fn test_event_handling_initial() {
        let processor = StreamingProcessor::new(StreamingConfig::default());
        assert!(!processor.has_events());
        assert_eq!(processor.event_count(), 0);
        assert!(processor.peek_event().is_none());
    }

    #[test]
    fn test_event_pop_and_drain() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());

        // Manually add events for testing
        processor.events.push(StreamingEvent::SpeechStart);
        processor.events.push(StreamingEvent::SpeechEnd);

        assert!(processor.has_events());
        assert_eq!(processor.event_count(), 2);

        // Pop first event
        let event = processor.pop_event();
        assert!(event.is_some());
        assert_eq!(event, Some(StreamingEvent::SpeechStart));
        assert_eq!(processor.event_count(), 1);

        // Drain remaining
        let remaining = processor.drain_events();
        assert_eq!(remaining.len(), 1);
        assert_eq!(remaining[0], StreamingEvent::SpeechEnd);
        assert!(!processor.has_events());
    }

    #[test]
    fn test_event_peek() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        processor.events.push(StreamingEvent::Reset);

        let peeked = processor.peek_event();
        assert!(peeked.is_some());
        assert_eq!(peeked, Some(&StreamingEvent::Reset));

        // Peeking doesn't consume
        assert_eq!(processor.event_count(), 1);
    }

    #[test]
    fn test_clear_events() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        processor.events.push(StreamingEvent::SpeechStart);
        processor.events.push(StreamingEvent::SpeechEnd);

        processor.clear_events();
        assert!(!processor.has_events());
        assert_eq!(processor.event_count(), 0);
    }

    #[test]
    fn test_partial_result_threshold() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());

        // Default threshold is 3 seconds = 48000 samples at 16kHz
        assert!((processor.partial_threshold() - 3.0).abs() < 0.01);

        // Change threshold
        processor.set_partial_threshold(5.0);
        assert!((processor.partial_threshold() - 5.0).abs() < 0.01);
    }

    #[test]
    fn test_partial_duration() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);

        // Empty buffer
        assert!((processor.partial_duration() - 0.0).abs() < 0.01);

        // Add some samples
        processor.chunk_buffer = vec![0.1; 16000]; // 1 second
        assert!((processor.partial_duration() - 1.0).abs() < 0.01);
    }

    #[test]
    fn test_has_partial_not_accumulating() {
        let processor = StreamingProcessor::new(StreamingConfig::default());
        assert!(!processor.has_partial()); // Not accumulating
    }

    #[test]
    fn test_has_partial_below_threshold() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        processor.state = ProcessorState::AccumulatingSpeech;
        processor.chunk_buffer = vec![0.1; 16000]; // 1 second, below 3s threshold

        assert!(!processor.has_partial());
    }

    #[test]
    fn test_has_partial_above_threshold() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        processor.state = ProcessorState::AccumulatingSpeech;
        processor.chunk_buffer = vec![0.1; 64000]; // 4 seconds, above 3s threshold

        assert!(processor.has_partial());
    }

    #[test]
    fn test_get_partial() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        processor.state = ProcessorState::AccumulatingSpeech;
        processor.chunk_buffer = vec![0.1; 64000]; // 4 seconds

        let partial = processor.get_partial();
        assert!(partial.is_some());
        assert_eq!(partial.as_ref().map(|p| p.len()), Some(64000));

        // After getting partial, last_partial_position is updated
        assert_eq!(processor.last_partial_position, 64000);

        // Getting again without more audio returns None (already processed this position)
        assert!(!processor.has_partial());
    }

    #[test]
    fn test_processing_state_transitions() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        processor.state = ProcessorState::ChunkReady;

        // Mark processing started
        processor.mark_processing_started();
        assert_eq!(processor.state(), ProcessorState::Processing);
        assert!(processor.has_events());

        // Should have emitted ProcessingStarted event
        let event = processor.pop_event();
        assert_eq!(event, Some(StreamingEvent::ProcessingStarted));

        // Mark processing completed
        processor.mark_processing_completed();
        assert_eq!(processor.state(), ProcessorState::WaitingForSpeech);

        let event = processor.pop_event();
        assert_eq!(event, Some(StreamingEvent::ProcessingCompleted));
    }

    #[test]
    fn test_error_state() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());

        processor.mark_error("Test error message");
        assert_eq!(processor.state(), ProcessorState::Error);

        let event = processor.pop_event();
        assert!(matches!(event, Some(StreamingEvent::Error(msg)) if msg == "Test error message"));
    }

    #[test]
    fn test_error_recovery() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        processor.state = ProcessorState::Error;
        processor.chunk_buffer = vec![0.1; 1000];
        processor.last_partial_position = 500;

        processor.recover_from_error();

        assert_eq!(processor.state(), ProcessorState::WaitingForSpeech);
        assert!(processor.chunk_buffer.is_empty());
        assert_eq!(processor.last_partial_position, 0);
    }

    #[test]
    fn test_prev_state_tracking() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            min_speech_duration_ms: 0,
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);

        assert_eq!(processor.prev_state(), ProcessorState::WaitingForSpeech);

        // Transition to accumulating
        processor.speech_frames = 1;
        processor.update_state(true, &vec![0.1; 320]);

        // Previous state should be WaitingForSpeech
        assert_eq!(processor.prev_state(), ProcessorState::WaitingForSpeech);
        assert_eq!(processor.state(), ProcessorState::AccumulatingSpeech);
    }

    #[test]
    fn test_speech_start_event() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            min_speech_duration_ms: 0, // Immediate
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);
        processor.speech_frames = 1;

        processor.update_state(true, &vec![0.1; 320]);

        // Should have emitted SpeechStart event
        assert!(processor.has_events());
        let event = processor.pop_event();
        assert_eq!(event, Some(StreamingEvent::SpeechStart));
    }

    #[test]
    fn test_speech_end_and_chunk_ready_events() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            chunk_duration: 30.0,
            chunk_overlap: 0.1,
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);

        // Set up as accumulating with enough audio
        processor.state = ProcessorState::AccumulatingSpeech;
        processor.chunk_buffer = vec![0.1; 5000];
        processor.silence_frames = 50; // Extended silence

        processor.update_state(false, &vec![0.0; 320]);

        // Should have SpeechEnd then ChunkReady events
        let events = processor.drain_events();
        assert!(events.iter().any(|e| *e == StreamingEvent::SpeechEnd));
        assert!(events
            .iter()
            .any(|e| matches!(e, StreamingEvent::ChunkReady { .. })));
    }

    #[test]
    fn test_reset_emits_event() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        processor.state = ProcessorState::AccumulatingSpeech;
        processor.chunk_buffer = vec![0.1; 1000];

        processor.reset();

        assert_eq!(processor.state(), ProcessorState::WaitingForSpeech);
        assert!(processor.chunk_buffer.is_empty());

        // Should have emitted Reset event
        let event = processor.pop_event();
        assert_eq!(event, Some(StreamingEvent::Reset));
    }

    #[test]
    fn test_partial_ready_event_on_threshold() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            min_speech_duration_ms: 0,
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);
        processor.set_partial_threshold(0.1); // 1600 samples

        // Transition to accumulating
        processor.speech_frames = 1;
        processor.update_state(true, &vec![0.1; 320]);
        processor.drain_events(); // Clear SpeechStart event

        // Accumulate past threshold
        processor.state = ProcessorState::AccumulatingSpeech;
        processor.chunk_buffer = vec![0.1; 1500]; // Just below threshold

        processor.update_state(true, &vec![0.1; 320]);

        // Should have emitted PartialReady event
        let events = processor.drain_events();
        assert!(events
            .iter()
            .any(|e| matches!(e, StreamingEvent::PartialReady { .. })));
    }

    #[test]
    fn test_processing_state_ignores_transitions() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        processor.state = ProcessorState::Processing;
        processor.chunk_buffer = vec![0.1; 1000];

        // Calling update_state while processing should not change state
        processor.update_state(true, &vec![0.1; 320]);

        assert_eq!(processor.state(), ProcessorState::Processing);
    }

    #[test]
    fn test_error_state_ignores_transitions() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        processor.state = ProcessorState::Error;

        processor.update_state(true, &vec![0.1; 320]);

        assert_eq!(processor.state(), ProcessorState::Error);
    }

    #[test]
    fn test_partial_result_ready_continues_accumulating() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            chunk_duration: 0.1, // 1600 samples for full chunk
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);
        processor.state = ProcessorState::PartialResultReady;
        processor.chunk_buffer = vec![0.1; 1000];

        processor.update_state(true, &vec![0.1; 320]);

        // Should have accumulated more samples
        assert_eq!(processor.chunk_buffer.len(), 1320);
    }

    #[test]
    fn test_partial_to_chunk_ready_transition() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            chunk_duration: 0.1, // 1600 samples
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);
        processor.state = ProcessorState::PartialResultReady;
        processor.chunk_buffer = vec![0.1; 1500]; // Close to full

        processor.update_state(true, &vec![0.1; 320]);

        // Should have transitioned to ChunkReady
        assert_eq!(processor.state(), ProcessorState::ChunkReady);
    }

    #[test]
    fn test_get_chunk_resets_partial_position() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            chunk_duration: 0.02,
            chunk_overlap: 0.01,
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);
        processor.state = ProcessorState::ChunkReady;
        processor.chunk_buffer = vec![0.1; 400];
        processor.last_partial_position = 200;

        let _ = processor.get_chunk();

        // Should have reset partial position
        assert_eq!(processor.last_partial_position, 0);
    }

    #[test]
    fn test_flush_resets_partial_position() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            chunk_duration: 0.1,
            chunk_overlap: 0.01,
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);
        processor.state = ProcessorState::AccumulatingSpeech;
        processor.chunk_buffer = vec![0.1; 500];
        processor.last_partial_position = 100;

        let _ = processor.flush();

        // Should have reset partial position
        assert_eq!(processor.last_partial_position, 0);
    }

    #[test]
    fn test_default_partial_threshold_constant() {
        // Verify the constant is set correctly
        assert!((DEFAULT_PARTIAL_THRESHOLD_SECS - 3.0).abs() < f32::EPSILON);
    }

    // =========================================================================
    // WAPR-102: Chunk Overlap Handling Tests
    // =========================================================================

    #[test]
    fn test_config_chunk_overlap_builder() {
        let config = StreamingConfig::default().chunk_overlap(0.5);
        assert!((config.chunk_overlap - 0.5).abs() < 0.01);
    }

    #[test]
    fn test_config_min_speech_duration_builder() {
        let config = StreamingConfig::default().min_speech_duration_ms(500);
        assert_eq!(config.min_speech_duration_ms, 500);
    }

    #[test]
    fn test_overlap_len_initial() {
        let processor = StreamingProcessor::new(StreamingConfig::default());
        assert_eq!(processor.overlap_len(), 0);
    }

    #[test]
    fn test_overlap_duration_empty() {
        let processor = StreamingProcessor::new(StreamingConfig::default());
        assert!((processor.overlap_duration() - 0.0).abs() < 0.01);
    }

    #[test]
    fn test_has_overlap_initial() {
        let processor = StreamingProcessor::new(StreamingConfig::default());
        assert!(!processor.has_overlap());
    }

    #[test]
    fn test_configured_overlap_samples() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            chunk_overlap: 0.5, // 0.5 seconds
            ..Default::default()
        };
        let processor = StreamingProcessor::new(config);
        assert_eq!(processor.configured_overlap_samples(), 8000); // 0.5 * 16000
    }

    #[test]
    fn test_configured_overlap_duration() {
        let config = StreamingConfig {
            chunk_overlap: 0.75,
            ..Default::default()
        };
        let processor = StreamingProcessor::new(config);
        assert!((processor.configured_overlap_duration() - 0.75).abs() < 0.01);
    }

    #[test]
    fn test_clear_overlap() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        processor.overlap_buffer = vec![0.1; 1000];

        processor.clear_overlap();

        assert!(!processor.has_overlap());
        assert_eq!(processor.overlap_len(), 0);
    }

    #[test]
    fn test_get_overlap_buffer() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        processor.overlap_buffer = vec![0.5; 100];

        let overlap = processor.get_overlap_buffer();
        assert_eq!(overlap.len(), 100);
        assert!((overlap[0] - 0.5).abs() < 0.01);
    }

    #[test]
    fn test_set_overlap_buffer() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        let custom_overlap = vec![0.25; 200];

        processor.set_overlap_buffer(custom_overlap.clone());

        assert!(processor.has_overlap());
        assert_eq!(processor.overlap_len(), 200);
        let buffer = processor.get_overlap_buffer();
        assert!((buffer[0] - 0.25).abs() < 0.01);
    }

    #[test]
    fn test_overlap_preserved_after_get_chunk() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            chunk_duration: 0.02, // 320 samples
            chunk_overlap: 0.01,  // 160 samples overlap
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);

        // Fill chunk buffer with recognizable pattern
        processor.chunk_buffer = (0..400).map(|i| i as f32 * 0.001).collect();
        processor.state = ProcessorState::ChunkReady;

        let _ = processor.get_chunk();

        // Overlap buffer should have last 160 samples
        assert!(processor.has_overlap());
        assert_eq!(processor.overlap_len(), 160);

        // Verify the overlap is from the end of the chunk
        let overlap = processor.get_overlap_buffer();
        // First sample of overlap should be sample 240 from original (400 - 160)
        assert!((overlap[0] - 0.240).abs() < 0.001);
    }

    #[test]
    fn test_overlap_used_when_starting_accumulation() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            min_speech_duration_ms: 0, // Immediate
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);

        // Pre-populate overlap buffer
        processor.overlap_buffer = vec![0.05; 100];
        processor.speech_frames = 1;

        let samples = vec![0.1; 320];
        processor.update_state(true, &samples);

        // Chunk buffer should include overlap + new samples
        assert!(processor.chunk_buffer.len() >= 420);
        // First 100 samples should be from overlap (0.05)
        assert!((processor.chunk_buffer[0] - 0.05).abs() < 0.01);
    }

    #[test]
    fn test_overlap_duration_with_samples() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);
        processor.overlap_buffer = vec![0.1; 8000]; // 0.5 seconds

        assert!((processor.overlap_duration() - 0.5).abs() < 0.01);
    }

    #[test]
    fn test_overlap_reset_clears_buffer() {
        let mut processor = StreamingProcessor::new(StreamingConfig::default());
        processor.overlap_buffer = vec![0.1; 1000];

        processor.reset();

        assert!(!processor.has_overlap());
    }

    #[test]
    fn test_flush_clears_overlap() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            chunk_duration: 0.1,
            chunk_overlap: 0.01,
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);
        processor.state = ProcessorState::AccumulatingSpeech;
        processor.chunk_buffer = vec![0.1; 500];
        processor.overlap_buffer = vec![0.2; 100];

        let _ = processor.flush();

        assert!(!processor.has_overlap());
    }

    #[test]
    fn test_multiple_chunks_preserve_overlap_chain() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            chunk_duration: 0.02,      // 320 samples
            chunk_overlap: 0.005,      // 80 samples overlap
            min_speech_duration_ms: 0, // Immediate transition
            ..Default::default()
        };
        let mut processor = StreamingProcessor::new(config);

        // First chunk
        processor.chunk_buffer = vec![0.1; 400];
        processor.state = ProcessorState::ChunkReady;
        let _ = processor.get_chunk();

        // Verify overlap preserved
        let first_overlap = processor.get_overlap_buffer();
        assert_eq!(first_overlap.len(), 80);

        // Second chunk - simulate accumulation that uses overlap
        // Set speech_frames high enough to trigger transition
        processor.speech_frames = 1;
        processor.state = ProcessorState::WaitingForSpeech;
        processor.update_state(true, &vec![0.2; 320]);

        // After transition, chunk buffer should include overlap + new samples
        assert!(processor.chunk_buffer.len() >= 320);
        // Verify overlap was prepended (first 80 samples should be 0.1)
        assert!((processor.chunk_buffer[0] - 0.1).abs() < 0.01);
    }

    // =========================================================================
    // WAPR-110: Low-Latency Mode Tests
    // =========================================================================

    #[test]
    fn test_latency_mode_enum() {
        // Test all LatencyMode variants
        let standard = LatencyMode::Standard;
        let low = LatencyMode::LowLatency;
        let ultra = LatencyMode::UltraLow;
        let custom = LatencyMode::Custom;

        assert_eq!(standard, LatencyMode::Standard);
        assert_eq!(low, LatencyMode::LowLatency);
        assert_eq!(ultra, LatencyMode::UltraLow);
        assert_eq!(custom, LatencyMode::Custom);

        // Test Debug
        assert!(format!("{standard:?}").contains("Standard"));
        assert!(format!("{low:?}").contains("LowLatency"));
        assert!(format!("{ultra:?}").contains("UltraLow"));
        assert!(format!("{custom:?}").contains("Custom"));

        // Test Copy
        let copied = standard;
        assert_eq!(copied, LatencyMode::Standard);
    }

    #[test]
    fn test_latency_mode_default() {
        let mode = LatencyMode::default();
        assert_eq!(mode, LatencyMode::Standard);
    }

    #[test]
    fn test_low_latency_constants() {
        // Verify constant values match spec
        assert!((LOW_LATENCY_CHUNK_DURATION - 0.5).abs() < f32::EPSILON);
        assert!((LOW_LATENCY_CHUNK_OVERLAP - 0.05).abs() < f32::EPSILON);
        assert_eq!(LOW_LATENCY_MIN_SPEECH_MS, 100);
        assert!((LOW_LATENCY_PARTIAL_THRESHOLD - 0.25).abs() < f32::EPSILON);
        assert!((LOW_LATENCY_BUFFER_DURATION - 5.0).abs() < f32::EPSILON);
        assert_eq!(LOW_LATENCY_FRAME_SIZE_MS, 10);
    }

    #[test]
    fn test_streaming_config_default_latency_mode() {
        let config = StreamingConfig::default();
        assert_eq!(config.latency_mode, LatencyMode::Standard);
    }

    #[test]
    fn test_streaming_config_low_latency() {
        let config = StreamingConfig::low_latency();

        assert_eq!(config.latency_mode, LatencyMode::LowLatency);
        assert!((config.chunk_duration - 0.5).abs() < f32::EPSILON);
        assert!((config.chunk_overlap - 0.05).abs() < f32::EPSILON);
        assert_eq!(config.min_speech_duration_ms, 100);
        assert!((config.buffer_duration - 5.0).abs() < f32::EPSILON);
        assert!(config.enable_vad);
    }

    #[test]
    fn test_streaming_config_ultra_low_latency() {
        let config = StreamingConfig::ultra_low_latency();

        assert_eq!(config.latency_mode, LatencyMode::UltraLow);
        assert!((config.chunk_duration - 0.25).abs() < f32::EPSILON);
        assert!((config.chunk_overlap - 0.025).abs() < f32::EPSILON);
        assert_eq!(config.min_speech_duration_ms, 50);
        assert!((config.buffer_duration - 2.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_streaming_config_custom_latency() {
        let config = StreamingConfig::custom_latency(0.75, 0.1, 200, 10.0);

        assert_eq!(config.latency_mode, LatencyMode::Custom);
        assert!((config.chunk_duration - 0.75).abs() < f32::EPSILON);
        assert!((config.chunk_overlap - 0.1).abs() < f32::EPSILON);
        assert_eq!(config.min_speech_duration_ms, 200);
        assert!((config.buffer_duration - 10.0).abs() < f32::EPSILON);
    }

    #[test]
    fn test_streaming_config_with_latency_mode() {
        let config = StreamingConfig::default().with_latency_mode(LatencyMode::Custom);
        assert_eq!(config.latency_mode, LatencyMode::Custom);
    }

    #[test]
    fn test_streaming_config_latency_mode_getter() {
        let config = StreamingConfig::low_latency();
        assert_eq!(config.latency_mode(), LatencyMode::LowLatency);
    }

    #[test]
    fn test_expected_latency_ms_standard() {
        let config = StreamingConfig::default();
        assert!((config.expected_latency_ms() - 30000.0).abs() < 1.0);
    }

    #[test]
    fn test_expected_latency_ms_low_latency() {
        let config = StreamingConfig::low_latency();
        assert!((config.expected_latency_ms() - 500.0).abs() < 1.0);
    }

    #[test]
    fn test_expected_latency_ms_ultra_low() {
        let config = StreamingConfig::ultra_low_latency();
        assert!((config.expected_latency_ms() - 250.0).abs() < 1.0);
    }

    #[test]
    fn test_is_low_latency_standard() {
        let config = StreamingConfig::default();
        assert!(!config.is_low_latency());
    }

    #[test]
    fn test_is_low_latency_low() {
        let config = StreamingConfig::low_latency();
        assert!(config.is_low_latency());
    }

    #[test]
    fn test_is_low_latency_ultra() {
        let config = StreamingConfig::ultra_low_latency();
        assert!(config.is_low_latency());
    }

    #[test]
    fn test_is_low_latency_custom() {
        let config = StreamingConfig::custom_latency(0.5, 0.05, 100, 5.0);
        assert!(!config.is_low_latency()); // Custom is not considered low-latency
    }

    #[test]
    fn test_low_latency_chunk_samples() {
        let config = StreamingConfig::low_latency();
        // 0.5s * 16000 = 8000 samples
        assert_eq!(config.chunk_samples(), 8000);
    }

    #[test]
    fn test_ultra_low_latency_chunk_samples() {
        let config = StreamingConfig::ultra_low_latency();
        // 0.25s * 16000 = 4000 samples
        assert_eq!(config.chunk_samples(), 4000);
    }

    #[test]
    fn test_low_latency_overlap_samples() {
        let config = StreamingConfig::low_latency();
        // 0.05s * 16000 = 800 samples
        assert_eq!(config.overlap_samples(), 800);
    }

    #[test]
    fn test_processor_with_low_latency_config() {
        let config = StreamingConfig::low_latency();
        let processor = StreamingProcessor::new(config);

        assert_eq!(processor.state(), ProcessorState::WaitingForSpeech);
        // Partial threshold should be adjusted for low latency (250ms)
        // Default is 3s, but for 500ms chunks we'd use shorter threshold
    }

    #[test]
    fn test_processor_low_latency_min_speech_frames() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            min_speech_duration_ms: 100, // Low-latency default
            ..StreamingConfig::low_latency()
        };
        let processor = StreamingProcessor::new(config);

        // 100ms / 30ms per frame = 3 frames
        assert_eq!(processor.min_speech_frames(), 3);
    }

    #[test]
    fn test_low_latency_end_to_end() {
        // Full integration test for low-latency mode
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            chunk_duration: 0.5,
            chunk_overlap: 0.05,
            enable_vad: false, // Disable VAD for deterministic test
            min_speech_duration_ms: 0,
            ..StreamingConfig::low_latency()
        };
        let mut processor = StreamingProcessor::new(config);

        // Push 500ms of audio (8000 samples at 16kHz)
        let audio = vec![0.1; 8000];
        processor.push_audio(&audio);
        processor.process();

        // Should have a chunk ready (or accumulating)
        assert!(processor.has_chunk() || processor.chunk_len() > 0);
    }

    #[test]
    fn test_ultra_low_latency_end_to_end() {
        let config = StreamingConfig {
            input_sample_rate: 16000,
            output_sample_rate: 16000,
            enable_vad: false,
            min_speech_duration_ms: 0,
            ..StreamingConfig::ultra_low_latency()
        };
        let mut processor = StreamingProcessor::new(config);

        // Push 250ms of audio (4000 samples at 16kHz)
        let audio = vec![0.1; 4000];
        processor.push_audio(&audio);
        processor.process();

        // Should have started accumulating or have chunk ready
        assert!(processor.has_chunk() || processor.chunk_len() > 0);
    }

    #[test]
    fn test_low_latency_builder_chain() {
        // Test that builders can be chained with low-latency config
        let config = StreamingConfig::low_latency()
            .without_vad()
            .vad_threshold(0.3);

        assert_eq!(config.latency_mode, LatencyMode::LowLatency);
        assert!(!config.enable_vad);
        assert!((config.vad_threshold - 0.3).abs() < f32::EPSILON);
    }

    #[test]
    fn test_latency_mode_equality() {
        assert_eq!(LatencyMode::Standard, LatencyMode::Standard);
        assert_ne!(LatencyMode::Standard, LatencyMode::LowLatency);
        assert_ne!(LatencyMode::LowLatency, LatencyMode::UltraLow);
        assert_ne!(LatencyMode::UltraLow, LatencyMode::Custom);
    }

    #[test]
    fn test_low_latency_config_sample_rates() {
        let config = StreamingConfig::low_latency();
        assert_eq!(config.input_sample_rate, 44100);
        assert_eq!(config.output_sample_rate, SAMPLE_RATE); // 16000
    }

    #[test]
    fn test_processor_stats_with_low_latency() {
        let config = StreamingConfig::low_latency();
        let mut processor = StreamingProcessor::new(config);

        processor.push_audio(&vec![0.1; 1000]);
        let stats = processor.stats();

        assert_eq!(stats.samples_processed, 1000);
        assert_eq!(stats.state, ProcessorState::WaitingForSpeech);
    }

    #[test]
    fn test_low_latency_reset() {
        let config = StreamingConfig::low_latency();
        let mut processor = StreamingProcessor::new(config);

        processor.push_audio(&vec![0.1; 5000]);
        processor.process();
        processor.reset();

        assert_eq!(processor.state(), ProcessorState::WaitingForSpeech);
        assert_eq!(processor.chunk_len(), 0);
        assert!(!processor.has_overlap());
    }
}