rustvani 0.2.0

Voice AI framework for Rust — real-time speech pipelines with STT, LLM, TTS, and Dhara conversation flows
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
//! 60db Speech-to-Text WebSocket service.
//!
//! Connects to 60db's real-time STT WebSocket API and pushes
//! TranscriptionFrames downstream when transcripts arrive.
//!
//! Pipeline position:
//!   transport.input() → SixtyDbSttHandler → llm → tts → transport.output()
//!
//! Wiring:
//!   let stt = SixtyDbSttHandler::new(SixtyDbSttConfig {
//!       api_key: std::env::var("SIXTYDB_API_KEY").unwrap(),
//!       ..Default::default()
//!   })
//!   .into_processor();
//!
//! Frames consumed:
//!   - StartFrame             → connects WebSocket
//!   - InputAudioRaw          → denoise → resample → encode → send to 60db
//!   - EndFrame / CancelFrame → disconnects WebSocket
//!
//! Frames produced:
//!   - TranscriptionFrame (downstream) on transcript
//!   - UserStartedSpeaking (downstream) on speech_started (barge-in)
//!   - UserStoppedSpeaking (downstream) on canonical final
//!   - ErrorFrame (upstream) on connection / parse errors
//!
//! Auth: apiKey query parameter.
//! URL:  wss://api.60db.ai/ws/stt?apiKey=...

use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};

use async_trait::async_trait;
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64;
use futures::{SinkExt, StreamExt};
use log;
use serde::Serialize;
use tokio::sync::{mpsc, Mutex};
use tokio::task::JoinHandle;
use tokio_tungstenite::tungstenite::http::Request;
use tokio_tungstenite::tungstenite::Message;

use crate::audio_process::noisefilter::RNNoiseFilter;
use crate::audio_process::resamplers::{ResamplerQuality, StreamResampler};
use crate::error::Result;
use crate::frames::{
    ControlFrame, Frame, FrameDirection, FrameHandler, FrameInner, FrameProcessor,
    SystemFrame, TranscriptionData,
};

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

const SIXTYDB_BASE_WSS: &str = "wss://api.60db.ai/ws/stt";
const SIXTYDB_BASE_WS: &str = "ws://api.60db.ai/ws/stt";

// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------

/// Audio encoding for the 60db STT session.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SixtyDbEncoding {
    /// 16-bit little-endian PCM (browser mode). Sent as JSON base64.
    Linear,
    /// G.711 μ-law (telephony mode). Sent as binary WS frames.
    Mulaw,
}

impl Default for SixtyDbEncoding {
    fn default() -> Self {
        Self::Linear
    }
}

impl SixtyDbEncoding {
    fn as_str(&self) -> &'static str {
        match self {
            Self::Linear => "linear",
            Self::Mulaw => "mulaw",
        }
    }
}

/// Real-time audio enhancement level.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SixtyDbAudioEnhancement {
    Off,
    Light,
    Adaptive,
}

impl Default for SixtyDbAudioEnhancement {
    fn default() -> Self {
        Self::Off
    }
}

impl SixtyDbAudioEnhancement {
    fn as_str(&self) -> &'static str {
        match self {
            Self::Off => "off",
            Self::Light => "light",
            Self::Adaptive => "adaptive",
        }
    }
}

/// Context hint for LLM refinement.
#[derive(Debug, Clone, Default, Serialize)]
pub struct SixtyDbContext {
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub general: Vec<SixtyDbContextItem>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub terms: Vec<String>,
}

/// A single key/value context hint.
#[derive(Debug, Clone, Serialize)]
pub struct SixtyDbContextItem {
    pub key: String,
    pub value: String,
}

/// Configuration for SixtyDbSttHandler.
#[derive(Debug, Clone)]
pub struct SixtyDbSttConfig {
    /// 60db API key.
    pub api_key: String,

    /// Language codes e.g. `["en"]`, `["en", "hi"]`.
    /// Empty vec or omitted = auto-detect.
    pub languages: Vec<String>,

    /// Optional context for LLM refinement.
    pub context: Option<SixtyDbContext>,

    /// Audio encoding.
    pub encoding: SixtyDbEncoding,

    /// Audio sample rate sent to the server.
    /// If the pipeline input rate differs, the handler resamples automatically.
    pub sample_rate: u32,

    /// Silence duration (ms) after last speech chunk before finalizing.
    /// Values below 300 ms are silently clamped to 300 ms by the server.
    pub utterance_end_ms: u32,

    /// Keep session alive between utterances.
    pub continuous_mode: bool,

    /// How often (ms) to emit interim partial results.
    /// Values below 300 ms are clamped to 300 ms.
    /// `None` = disabled.
    pub interim_results_frequency: Option<u32>,

    /// Audio enhancement level.
    pub audio_enhancement: SixtyDbAudioEnhancement,

    /// Enable speaker diarization.
    pub diarize: bool,

    /// Lower bound on speaker count (only when diarize=true).
    pub min_speakers: Option<i32>,

    /// Upper bound on speaker count (only when diarize=true).
    pub max_speakers: Option<i32>,

    /// Use `ws://` instead of `wss://`.
    pub insecure: bool,

    /// Enable RNNoise noise suppression before sending audio to 60db.
    pub noise_reduction: bool,

    /// Quality preset for the internal sample-rate converter.
    /// Only used when the incoming `InputAudioRaw` rate differs from `sample_rate`.
    pub resampler_quality: ResamplerQuality,
}

impl Default for SixtyDbSttConfig {
    fn default() -> Self {
        Self {
            api_key: String::new(),
            languages: vec!["en".to_string()],
            context: None,
            encoding: SixtyDbEncoding::Linear,
            sample_rate: 16_000,
            utterance_end_ms: 500,
            continuous_mode: true,
            interim_results_frequency: Some(300),
            audio_enhancement: SixtyDbAudioEnhancement::Off,
            diarize: false,
            min_speakers: None,
            max_speakers: None,
            insecure: false,
            noise_reduction: true,
            resampler_quality: ResamplerQuality::Quick,
        }
    }
}

impl SixtyDbSttConfig {
    fn ws_url(&self) -> String {
        let base = if self.insecure {
            SIXTYDB_BASE_WS
        } else {
            SIXTYDB_BASE_WSS
        };
        format!("{}?apiKey={}", base, urlencoding(&self.api_key))
    }

    fn start_message(&self) -> String {
        #[derive(Serialize)]
        struct StartMsg {
            #[serde(rename = "type")]
            msg_type: &'static str,
            #[serde(skip_serializing_if = "Option::is_none")]
            languages: Option<Vec<String>>,
            #[serde(skip_serializing_if = "Option::is_none")]
            context: Option<SixtyDbContext>,
            config: Config,
        }

        #[derive(Serialize)]
        struct Config {
            encoding: &'static str,
            sample_rate: u32,
            utterance_end_ms: u32,
            continuous_mode: bool,
            #[serde(skip_serializing_if = "Option::is_none")]
            interim_results_frequency: Option<u32>,
            audio_enhancement: &'static str,
            diarize: bool,
            #[serde(skip_serializing_if = "Option::is_none")]
            min_speakers: Option<i32>,
            #[serde(skip_serializing_if = "Option::is_none")]
            max_speakers: Option<i32>,
        }

        let languages = if self.languages.is_empty() {
            None
        } else {
            Some(self.languages.clone())
        };

        let msg = StartMsg {
            msg_type: "start",
            languages,
            context: self.context.clone(),
            config: Config {
                encoding: self.encoding.as_str(),
                sample_rate: self.sample_rate,
                utterance_end_ms: self.utterance_end_ms,
                continuous_mode: self.continuous_mode,
                interim_results_frequency: self.interim_results_frequency,
                audio_enhancement: self.audio_enhancement.as_str(),
                diarize: self.diarize,
                min_speakers: self.min_speakers,
                max_speakers: self.max_speakers,
            },
        };

        serde_json::to_string(&msg).unwrap_or_default()
    }
}

// ---------------------------------------------------------------------------
// Connection state
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WsState {
    Disconnected,
    WsConnected,
    ConnectionEstablished,
    SessionStarted,
    Stopping,
    Stopped,
}

// ---------------------------------------------------------------------------
// Internal state
// ---------------------------------------------------------------------------

struct SixtyDbSttState {
    ws_tx: Option<mpsc::Sender<Message>>,
    send_task: Option<JoinHandle<()>>,
    receive_task: Option<JoinHandle<()>>,
    ws_state: WsState,
    /// Audio buffered before `session_started` arrives.
    audio_buffer: Vec<Vec<u8>>,
    /// Sample rate observed from the first `InputAudioRaw` frame.
    input_sample_rate: Option<u32>,
}

impl SixtyDbSttState {
    fn new() -> Self {
        Self {
            ws_tx: None,
            send_task: None,
            receive_task: None,
            ws_state: WsState::Disconnected,
            audio_buffer: Vec::new(),
            input_sample_rate: None,
        }
    }
}

// ---------------------------------------------------------------------------
// SixtyDbSttHandler
// ---------------------------------------------------------------------------

pub struct SixtyDbSttHandler {
    config: SixtyDbSttConfig,
    state: Arc<Mutex<SixtyDbSttState>>,
    /// Lazily initialised on first `InputAudioRaw` with the actual input rate.
    noise_filter: Arc<Mutex<Option<RNNoiseFilter>>>,
    /// Lazily initialised when incoming rate differs from `config.sample_rate`.
    resampler: Arc<Mutex<Option<StreamResampler>>>,
}

impl SixtyDbSttHandler {
    pub fn new(config: SixtyDbSttConfig) -> Self {
        Self {
            config,
            state: Arc::new(Mutex::new(SixtyDbSttState::new())),
            noise_filter: Arc::new(Mutex::new(None)),
            resampler: Arc::new(Mutex::new(None)),
        }
    }

    pub fn into_processor(self) -> FrameProcessor {
        FrameProcessor::new("SixtyDbStt", Box::new(self), false)
    }
}

// ---------------------------------------------------------------------------
// Connection / disconnection
// ---------------------------------------------------------------------------

impl SixtyDbSttHandler {
    async fn connect(&self, processor: FrameProcessor) {
        let url = self.config.ws_url();
        log::info!("SixtyDbStt: connecting to {}", url);

        let request = match Request::builder()
            .uri(&url)
            .header("Host", "api.60db.ai")
            .header("Connection", "Upgrade")
            .header("Upgrade", "websocket")
            .header("Sec-WebSocket-Version", "13")
            .header(
                "Sec-WebSocket-Key",
                tokio_tungstenite::tungstenite::handshake::client::generate_key(),
            )
            .body(())
        {
            Ok(r) => r,
            Err(e) => {
                let _ = processor
                    .push_error(format!("SixtyDbStt: request build failed: {}", e), false)
                    .await;
                return;
            }
        };

        let ws_stream = match tokio_tungstenite::connect_async(request).await {
            Ok((stream, _)) => stream,
            Err(e) => {
                let _ = processor
                    .push_error(format!("SixtyDbStt: connect failed: {}", e), false)
                    .await;
                return;
            }
        };

        let (sink, stream) = ws_stream.split();
        let (ws_tx, ws_rx) = mpsc::channel::<Message>(64);

        let send_task = tokio::spawn(run_send_task(sink, ws_rx));
        let config_clone = self.config.clone();
        let state_clone = self.state.clone();
        let receive_task = tokio::spawn(run_receive_task(
            stream,
            processor,
            config_clone,
            state_clone,
        ));

        let mut state = self.state.lock().await;
        state.ws_tx = Some(ws_tx);
        state.send_task = Some(send_task);
        state.receive_task = Some(receive_task);
        state.ws_state = WsState::WsConnected;
        state.audio_buffer.clear();
        state.input_sample_rate = None;

        log::info!("SixtyDbStt: WebSocket connected, awaiting handshake");
    }

    async fn disconnect(&self) {
        let mut state = self.state.lock().await;
        state.ws_state = WsState::Stopping;
        if let Some(h) = state.receive_task.take() {
            h.abort();
        }
        if let Some(h) = state.send_task.take() {
            h.abort();
        }
        state.ws_tx = None;
        state.audio_buffer.clear();
        state.input_sample_rate = None;
        drop(state);

        *self.noise_filter.lock().await = None;
        *self.resampler.lock().await = None;

        log::info!("SixtyDbStt: disconnected");
    }

    async fn send_ws_message(&self, msg: Message) {
        let tx = { self.state.lock().await.ws_tx.clone() };
        if let Some(tx) = tx {
            let _ = tx.send(msg).await;
        }
    }

    async fn send_json(&self, json: String) {
        self.send_ws_message(Message::Text(json.into())).await;
    }

    /// Send audio to 60db.
    /// Binary mode → raw μ-law bytes as WS binary frame.
    /// JSON mode → base64-encoded Int16 PCM wrapped in JSON.
    async fn send_audio(&self, audio: &[u8]) {
        let mut state = self.state.lock().await;

        match state.ws_state {
            WsState::SessionStarted => {
                // Flush any buffered audio first
                let buffered: Vec<Vec<u8>> = state.audio_buffer.drain(..).collect();
                drop(state);

                for chunk in buffered {
                    self.deliver_audio(&chunk).await;
                }
                self.deliver_audio(audio).await;
            }
            WsState::WsConnected | WsState::ConnectionEstablished => {
                state.audio_buffer.push(audio.to_vec());
            }
            _ => {}
        }
    }

    async fn deliver_audio(&self, audio: &[u8]) {
        match self.config.encoding {
            SixtyDbEncoding::Mulaw => {
                self.send_ws_message(Message::Binary(audio.to_vec().into())).await;
            }
            SixtyDbEncoding::Linear => {
                let msg = serde_json::json!({
                    "type": "audio",
                    "audio": BASE64.encode(audio),
                    "encoding": "linear",
                    "sample_rate": self.config.sample_rate,
                    "timestamp": unix_ms(),
                });
                self.send_json(msg.to_string()).await;
            }
        }
    }

    async fn send_stop(&self) {
        self.send_json(r#"{"type":"stop"}"#.to_string()).await;
    }
}

// ---------------------------------------------------------------------------
// Audio byte ↔ i16 helpers
// ---------------------------------------------------------------------------

fn bytes_to_i16(audio: &[u8]) -> Vec<i16> {
    audio
        .chunks_exact(2)
        .map(|c| i16::from_le_bytes([c[0], c[1]]))
        .collect()
}

fn i16_to_bytes(samples: &[i16]) -> Vec<u8> {
    samples.iter().flat_map(|s| s.to_le_bytes()).collect()
}

fn i16_to_f32(samples: &[i16]) -> Vec<f32> {
    samples.iter().map(|&s| s as f32).collect()
}

fn f32_to_i16(samples: &[f32]) -> Vec<i16> {
    samples
        .iter()
        .map(|&s| s.clamp(i16::MIN as f32, i16::MAX as f32) as i16)
        .collect()
}

// ---------------------------------------------------------------------------
// Audio pipeline helpers
// ---------------------------------------------------------------------------

impl SixtyDbSttHandler {
    /// Denoise (if enabled) → resample (if needed) → send to WebSocket.
    async fn prepare_and_send(&self, pcm: &[i16], sample_rate: u32, denoise: bool) {
        // 1. Optional denoising — lazily initialised with the actual input rate.
        let denoised = if denoise && self.config.noise_reduction {
            let mut nf_guard = self.noise_filter.lock().await;
            if nf_guard.is_none() {
                log::info!(
                    "SixtyDbStt: noise reduction enabled (input_rate={})",
                    sample_rate
                );
                *nf_guard = Some(RNNoiseFilter::new(sample_rate));
            }
            nf_guard.as_mut().unwrap().filter(pcm)
        } else {
            pcm.to_vec()
        };

        if denoised.is_empty() {
            return;
        }

        // Track input rate for downstream tail-flush logic.
        {
            let mut state = self.state.lock().await;
            state.input_sample_rate = Some(sample_rate);
        }

        // 2. Optional resampling — lazily initialised when rates diverge.
        let resampled = if sample_rate != self.config.sample_rate {
            let mut r_guard = self.resampler.lock().await;
            if r_guard.is_none() {
                log::info!(
                    "SixtyDbStt: resampling {} → {} Hz",
                    sample_rate,
                    self.config.sample_rate
                );
                *r_guard = Some(StreamResampler::new(
                    sample_rate,
                    self.config.sample_rate,
                    self.config.resampler_quality,
                ));
            }
            let f32_samples = i16_to_f32(&denoised);
            let resampled_f32 = r_guard.as_mut().unwrap().process(&f32_samples);
            f32_to_i16(&resampled_f32)
        } else {
            denoised
        };

        if !resampled.is_empty() {
            self.send_audio(&i16_to_bytes(&resampled)).await;
        }
    }
}

// ---------------------------------------------------------------------------
// FrameHandler impl
// ---------------------------------------------------------------------------

#[async_trait]
impl FrameHandler for SixtyDbSttHandler {
    async fn on_process_frame(
        &self,
        processor: &FrameProcessor,
        frame: Frame,
        direction: FrameDirection,
    ) -> Result<()> {
        match &frame.inner {
            FrameInner::System(SystemFrame::Start(_)) => {
                processor.push_frame(frame, direction).await?;
                self.connect(processor.clone()).await;
            }

            FrameInner::System(SystemFrame::InputAudioRaw(ref audio)) => {
                processor.push_frame(frame.clone(), direction).await?;

                let pcm = bytes_to_i16(&audio.audio);
                self.prepare_and_send(&pcm, audio.sample_rate, true).await;
            }

            FrameInner::System(SystemFrame::VADUserStoppedSpeaking { .. }) => {
                processor.push_frame(frame, direction).await?;

                // Flush noise filter tail
                if self.config.noise_reduction {
                    let tail = {
                        let mut nf_guard = self.noise_filter.lock().await;
                        nf_guard.as_mut().map(|nf| nf.flush()).unwrap_or_default()
                    };
                    if !tail.is_empty() {
                        let sample_rate = {
                            let state = self.state.lock().await;
                            state.input_sample_rate.unwrap_or(self.config.sample_rate)
                        };
                        self.prepare_and_send(&tail, sample_rate, false).await;
                    }
                }
            }

            FrameInner::Control(ControlFrame::End { .. })
            | FrameInner::System(SystemFrame::Cancel { .. }) => {
                let sample_rate = {
                    let state = self.state.lock().await;
                    state.input_sample_rate.unwrap_or(self.config.sample_rate)
                };

                // Flush noise filter tail
                if self.config.noise_reduction {
                    let tail = {
                        let mut nf_guard = self.noise_filter.lock().await;
                        nf_guard.as_mut().map(|nf| nf.flush()).unwrap_or_default()
                    };
                    if !tail.is_empty() {
                        self.prepare_and_send(&tail, sample_rate, false).await;
                    }
                }

                // Flush resampler tail
                let resampler_tail = {
                    let mut r_guard = self.resampler.lock().await;
                    r_guard.as_mut().map(|r| r.flush()).unwrap_or_default()
                };
                if !resampler_tail.is_empty() {
                    let i16_tail = f32_to_i16(&resampler_tail);
                    self.send_audio(&i16_to_bytes(&i16_tail)).await;
                }

                self.send_stop().await;
                // Give the server a moment to process remaining buffer,
                // then disconnect.
                tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;
                self.disconnect().await;
                processor.push_frame(frame, direction).await?;
            }

            _ => {
                processor.push_frame(frame, direction).await?;
            }
        }
        Ok(())
    }

    fn can_generate_metrics(&self) -> bool {
        true
    }
}

// ---------------------------------------------------------------------------
// Background task type aliases
// ---------------------------------------------------------------------------

type WsSink = futures::stream::SplitSink<
    tokio_tungstenite::WebSocketStream<
        tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>,
    >,
    Message,
>;

type WsStream = futures::stream::SplitStream<
    tokio_tungstenite::WebSocketStream<
        tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>,
    >,
>;

// ---------------------------------------------------------------------------
// Background tasks
// ---------------------------------------------------------------------------

async fn run_send_task(mut sink: WsSink, mut rx: mpsc::Receiver<Message>) {
    while let Some(msg) = rx.recv().await {
        if sink.send(msg).await.is_err() {
            log::warn!("SixtyDbStt: send failed — closing send task");
            break;
        }
    }
    let _ = sink.close().await;
    log::debug!("SixtyDbStt: send task exited");
}

async fn run_receive_task(
    mut stream: WsStream,
    processor: FrameProcessor,
    config: SixtyDbSttConfig,
    shared_state: Arc<Mutex<SixtyDbSttState>>,
) {
    log::debug!("SixtyDbStt: receive task started");

    while let Some(result) = stream.next().await {
        match result {
            Ok(Message::Text(text)) => {
                handle_text_message(text.as_str(), &processor, &config, &shared_state).await;
            }
            Ok(Message::Close(_)) => {
                log::info!("SixtyDbStt: server closed WebSocket");
                break;
            }
            Err(e) => {
                let _ = processor
                    .push_error(format!("SixtyDbStt: receive error: {}", e), false)
                    .await;
                break;
            }
            _ => {}
        }
    }

    log::debug!("SixtyDbStt: receive task exited");
}

// ---------------------------------------------------------------------------
// Message handling
// ---------------------------------------------------------------------------

async fn handle_text_message(
    text: &str,
    processor: &FrameProcessor,
    config: &SixtyDbSttConfig,
    shared_state: &Arc<Mutex<SixtyDbSttState>>,
) {
    log::trace!("SixtyDbStt: raw message: {}", text);

    let val: serde_json::Value = match serde_json::from_str(text) {
        Ok(v) => v,
        Err(e) => {
            log::warn!("SixtyDbStt: JSON parse error: {} — raw: {}", e, text);
            return;
        }
    };

    let obj = match val.as_object() {
        Some(o) => o,
        None => return,
    };

    // `connecting` and `connection_established` have no `type` field.
    if obj.contains_key("connecting") {
        let msg = obj.get("message").and_then(|v| v.as_str()).unwrap_or("");
        log::info!("SixtyDbStt: connecting — {}", msg);
        return;
    }

    if obj.contains_key("connection_established") {
        log::info!("SixtyDbStt: connection_established — sending start");
        let start_json = config.start_message();
        {
            let mut state = shared_state.lock().await;
            if let Some(ref tx) = state.ws_tx {
                let _ = tx.send(Message::Text(start_json.into())).await;
            }
            state.ws_state = WsState::ConnectionEstablished;
        }
        return;
    }

    let msg_type = match obj.get("type").and_then(|v| v.as_str()) {
        Some(t) => t,
        None => {
            log::debug!("SixtyDbStt: unknown message shape: {}", text);
            return;
        }
    };

    match msg_type {
        "connected" => {
            log::info!("SixtyDbStt: proxy connected to upstream STT");
        }

        "session_started" => {
            log::info!("SixtyDbStt: session_started — audio streaming enabled");
            let mut state = shared_state.lock().await;
            state.ws_state = WsState::SessionStarted;
            let buffered: Vec<Vec<u8>> = state.audio_buffer.drain(..).collect();
            let tx = state.ws_tx.clone();
            drop(state);

            // Flush buffered audio through ws_tx
            if let Some(tx) = tx {
                for chunk in buffered {
                    let msg = match config.encoding {
                        SixtyDbEncoding::Mulaw => Message::Binary(chunk.into()),
                        SixtyDbEncoding::Linear => {
                            let json = serde_json::json!({
                                "type": "audio",
                                "audio": BASE64.encode(&chunk),
                                "encoding": "linear",
                                "sample_rate": config.sample_rate,
                                "timestamp": unix_ms(),
                            });
                            Message::Text(json.to_string().into())
                        }
                    };
                    let _ = tx.send(msg).await;
                }
            }
        }

        "speech_started" => {
            log::debug!("SixtyDbStt: speech_started — barge-in");
            let _ = processor
                .push_frame(Frame::user_started_speaking(), FrameDirection::Downstream)
                .await;
        }

        "transcription" => {
            handle_transcription(obj, processor).await;
        }

        "language_changed" => {
            let lang = obj.get("language").and_then(|v| v.as_str()).unwrap_or("unknown");
            log::info!("SixtyDbStt: language_changed — {}", lang);
        }

        "mode_changed" => {
            let mode = obj.get("mode_name").and_then(|v| v.as_str()).unwrap_or("unknown");
            log::info!("SixtyDbStt: mode_changed — {}", mode);
        }

        "session_stopped" => {
            log::info!("SixtyDbStt: session_stopped");
            if let Some(summary) = obj.get("billing_summary") {
                log::info!("SixtyDbStt: billing_summary: {}", summary);
            }
            let mut state = shared_state.lock().await;
            state.ws_state = WsState::Stopped;
        }

        "error" => {
            let error = obj.get("error").and_then(|v| v.as_str()).unwrap_or("unknown error");
            let error_code = obj.get("error_code").and_then(|v| v.as_str());
            log::warn!(
                "SixtyDbStt: server error: {} (code: {:?})",
                error,
                error_code
            );
            let _ = processor
                .push_error(format!("SixtyDbStt: {} (code: {:?})", error, error_code), false)
                .await;
        }

        "test_response" => {
            log::trace!("SixtyDbStt: test_response");
        }

        other => {
            log::debug!("SixtyDbStt: unhandled message type: {}", other);
        }
    }
}

async fn handle_transcription(
    obj: &serde_json::Map<String, serde_json::Value>,
    processor: &FrameProcessor,
) {
    let text = match obj.get("text").and_then(|v| v.as_str()) {
        Some(t) => t.to_string(),
        None => return,
    };

    let is_final = obj.get("is_final").and_then(|v| v.as_bool()).unwrap_or(false);
    let speech_final = obj.get("speech_final").and_then(|v| v.as_bool()).unwrap_or(false);
    let is_partial = obj.get("is_partial").and_then(|v| v.as_bool()).unwrap_or(false);

    // Skip interim partials — they are only for barge-in word-count checks.
    // Never send interim text to the LLM.
    if is_partial && !is_final {
        log::trace!("SixtyDbStt: interim — '{}'", text);
        return;
    }

    // When LLM refinement is active, we get a first emit (is_final=true, speech_final=false).
    // We emit it as a non-finalized transcription for fast UI paint / barge-in.
    // The canonical (speech_final=true) follows shortly and is emitted as finalized.
    let finalized = is_final && speech_final;

    // Empty speech_final signal — reset state, do not treat as error.
    if text.is_empty() && finalized {
        let processing_mode = obj
            .get("processing_mode")
            .and_then(|v| v.as_str())
            .unwrap_or("speech_end_no_result");
        log::debug!(
            "SixtyDbStt: empty final (mode={}) — resetting state",
            processing_mode
        );
        return;
    }

    let language = obj
        .get("language")
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let confidence = obj.get("confidence").and_then(|v| v.as_f64()).unwrap_or(0.0);

    let mut frame_data = TranscriptionData::new(text.clone(), "", time_now());
    frame_data.language = language;
    frame_data.finalized = finalized;

    log::info!(
        "SixtyDbStt: transcript='{}' is_final={} speech_final={} finalized={} confidence={:.2} lang={:?}",
        frame_data.text,
        is_final,
        speech_final,
        finalized,
        confidence,
        frame_data.language
    );

    let _ = processor
        .push_frame(Frame::transcription(frame_data), FrameDirection::Downstream)
        .await;

    // Emit UserStoppedSpeaking on canonical final to signal end of utterance.
    if finalized {
        let _ = processor
            .push_frame(Frame::user_stopped_speaking(), FrameDirection::Downstream)
            .await;
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn time_now() -> String {
    let d = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();
    format!("{}.{:03}", d.as_secs(), d.subsec_millis())
}

fn unix_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis() as u64
}

fn urlencoding(s: &str) -> String {
    s.chars()
        .flat_map(|c| match c {
            'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_' | '.' | '~' => vec![c],
            _ => format!("%{:02X}", c as u32).chars().collect(),
        })
        .collect()
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::frames::{AudioRawData, DataFrame, ErrorFrameData, FrameInner, StartFrameData};
    use crate::FrameProcessor;
    use crate::PassthroughHandler;

    // ========================================================================
    // Helpers
    // ========================================================================

    fn default_config() -> SixtyDbSttConfig {
        SixtyDbSttConfig {
            api_key: "test_key".to_string(),
            ..Default::default()
        }
    }

    async fn started_processor() -> FrameProcessor {
        let proc = FrameProcessor::new("test", Box::new(PassthroughHandler), false);
        proc.process_frame(Frame::start(StartFrameData::default()), FrameDirection::Downstream)
            .await
            .unwrap();
        proc
    }

    fn capture_pushes(proc: &FrameProcessor) -> Arc<std::sync::Mutex<Vec<Frame>>> {
        let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
        let cap = captured.clone();
        proc.on_after_push_frame(move |f| {
            cap.lock().unwrap().push(f.clone());
        });
        captured
    }

    fn capture_errors(proc: &FrameProcessor) -> Arc<std::sync::Mutex<Vec<ErrorFrameData>>> {
        let captured = Arc::new(std::sync::Mutex::new(Vec::new()));
        let cap = captured.clone();
        proc.on_error(move |e| {
            cap.lock().unwrap().push(e.clone());
        });
        captured
    }

    async fn handler_with_state(
        config: SixtyDbSttConfig,
        ws_state: WsState,
    ) -> (SixtyDbSttHandler, mpsc::Receiver<Message>) {
        let handler = SixtyDbSttHandler::new(config);
        let (tx, rx) = mpsc::channel::<Message>(64);
        {
            let mut state = handler.state.lock().await;
            state.ws_tx = Some(tx);
            state.ws_state = ws_state;
        }
        (handler, rx)
    }

    // ========================================================================
    // Config & serialization
    // ========================================================================

    #[test]
    fn test_default_config() {
        let cfg = SixtyDbSttConfig::default();
        assert_eq!(cfg.api_key, "");
        assert_eq!(cfg.languages, vec!["en"]);
        assert_eq!(cfg.encoding, SixtyDbEncoding::Linear);
        assert_eq!(cfg.sample_rate, 16_000);
        assert_eq!(cfg.utterance_end_ms, 500);
        assert!(cfg.continuous_mode);
        assert_eq!(cfg.interim_results_frequency, Some(300));
        assert_eq!(cfg.audio_enhancement, SixtyDbAudioEnhancement::Off);
        assert!(!cfg.diarize);
        assert!(!cfg.insecure);
        assert!(cfg.noise_reduction);
        assert!(matches!(cfg.resampler_quality, ResamplerQuality::Quick));
    }

    #[test]
    fn test_ws_url_secure() {
        let cfg = SixtyDbSttConfig {
            api_key: "sk_test_123".to_string(),
            ..Default::default()
        };
        assert_eq!(cfg.ws_url(), "wss://api.60db.ai/ws/stt?apiKey=sk_test_123");
    }

    #[test]
    fn test_ws_url_insecure() {
        let cfg = SixtyDbSttConfig {
            api_key: "sk_test_123".to_string(),
            insecure: true,
            ..Default::default()
        };
        assert_eq!(cfg.ws_url(), "ws://api.60db.ai/ws/stt?apiKey=sk_test_123");
    }

    #[test]
    fn test_start_message_json() {
        let cfg = SixtyDbSttConfig {
            api_key: "key".to_string(),
            languages: vec!["en".to_string(), "hi".to_string()],
            encoding: SixtyDbEncoding::Linear,
            sample_rate: 48_000,
            utterance_end_ms: 500,
            continuous_mode: true,
            interim_results_frequency: Some(300),
            audio_enhancement: SixtyDbAudioEnhancement::Adaptive,
            diarize: true,
            min_speakers: Some(2),
            max_speakers: Some(4),
            ..Default::default()
        };

        let json = cfg.start_message();
        let val: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(val["type"], "start");
        assert_eq!(val["languages"], serde_json::json!(["en", "hi"]));
        assert_eq!(val["config"]["encoding"], "linear");
        assert_eq!(val["config"]["sample_rate"], 48_000);
        assert_eq!(val["config"]["utterance_end_ms"], 500);
        assert_eq!(val["config"]["continuous_mode"], true);
        assert_eq!(val["config"]["interim_results_frequency"], 300);
        assert_eq!(val["config"]["audio_enhancement"], "adaptive");
        assert_eq!(val["config"]["diarize"], true);
        assert_eq!(val["config"]["min_speakers"], 2);
        assert_eq!(val["config"]["max_speakers"], 4);
    }

    #[test]
    fn test_start_message_auto_languages() {
        let cfg = SixtyDbSttConfig {
            api_key: "key".to_string(),
            languages: vec![],
            ..Default::default()
        };
        let json = cfg.start_message();
        let val: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert!(val["languages"].is_null());
    }

    #[test]
    fn test_start_message_with_context() {
        let cfg = SixtyDbSttConfig {
            api_key: "key".to_string(),
            context: Some(SixtyDbContext {
                general: vec![
                    SixtyDbContextItem {
                        key: "domain".to_string(),
                        value: "Healthcare".to_string(),
                    },
                ],
                text: Some("Routine check-up.".to_string()),
                terms: vec!["Metformin".to_string()],
            }),
            ..Default::default()
        };
        let json = cfg.start_message();
        let val: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert_eq!(val["context"]["general"][0]["key"], "domain");
        assert_eq!(val["context"]["general"][0]["value"], "Healthcare");
        assert_eq!(val["context"]["text"], "Routine check-up.");
        assert_eq!(val["context"]["terms"][0], "Metformin");
    }

    #[test]
    fn test_urlencoding() {
        assert_eq!(urlencoding("hello world"), "hello%20world");
        assert_eq!(urlencoding("a+b"), "a%2Bb");
    }

    // ========================================================================
    // Message parsing — connection handshake
    // ========================================================================

    #[tokio::test]
    async fn test_handle_connecting_logs_only() {
        let config = default_config();
        let proc = started_processor().await;
        let state = Arc::new(Mutex::new(SixtyDbSttState::new()));
        let text = r#"{"connecting":true,"message":"Authenticating...","timestamp":1234}"#;
        handle_text_message(text, &proc, &config, &state).await;
        assert!(matches!(state.lock().await.ws_state, WsState::Disconnected));
    }

    #[tokio::test]
    async fn test_handle_connection_established_sends_start() {
        let config = default_config();
        let proc = started_processor().await;
        let (tx, mut rx) = mpsc::channel::<Message>(64);
        let mut s = SixtyDbSttState::new();
        s.ws_tx = Some(tx);
        let state = Arc::new(Mutex::new(s));

        let text = r#"{"connection_established":{"service":"stt","user_id":1,"credit_balance":10.0,"workspace":"default"}}"#;
        handle_text_message(text, &proc, &config, &state).await;

        let msg = rx.recv().await.expect("start message should be sent");
        if let Message::Text(t) = msg {
            let val: serde_json::Value = serde_json::from_str(&t).unwrap();
            assert_eq!(val["type"], "start");
            assert_eq!(val["config"]["sample_rate"], 16_000);
        } else {
            panic!("expected text message, got {:?}", msg);
        }
        assert!(matches!(state.lock().await.ws_state, WsState::ConnectionEstablished));
    }

    #[tokio::test]
    async fn test_handle_connected_logs_only() {
        let config = default_config();
        let proc = started_processor().await;
        let state = Arc::new(Mutex::new(SixtyDbSttState::new()));
        let text = r#"{"type":"connected","server_info":{"server_type":"60db STT","ready":true}}"#;
        handle_text_message(text, &proc, &config, &state).await;
        assert!(state.lock().await.ws_tx.is_none());
    }

    #[tokio::test]
    async fn test_handle_session_started_flushes_buffered_audio() {
        let config = default_config();
        let proc = started_processor().await;
        let (tx, mut rx) = mpsc::channel::<Message>(64);
        let mut s = SixtyDbSttState::new();
        s.ws_tx = Some(tx);
        s.ws_state = WsState::ConnectionEstablished;
        s.audio_buffer.push(vec![0xAB, 0xCD, 0xEF, 0x01]);
        let state = Arc::new(Mutex::new(s));

        let text = r#"{"type":"session_started","session_id":"sess_123","language":"EN"}"#;
        handle_text_message(text, &proc, &config, &state).await;

        assert!(matches!(state.lock().await.ws_state, WsState::SessionStarted));
        assert!(state.lock().await.audio_buffer.is_empty());

        let msg = rx.recv().await.expect("buffered audio should be flushed");
        match msg {
            Message::Text(t) => {
                let val: serde_json::Value = serde_json::from_str(&t).unwrap();
                assert_eq!(val["type"], "audio");
            }
            other => panic!("expected text message, got {:?}", other),
        }
    }

    // ========================================================================
    // Message parsing — transcription & speech events
    // ========================================================================

    #[tokio::test]
    async fn test_handle_speech_started_pushes_user_started_speaking() {
        let config = default_config();
        let proc = started_processor().await;
        let captured = capture_pushes(&proc);
        let state = Arc::new(Mutex::new(SixtyDbSttState::new()));

        let text = r#"{"type":"speech_started","timestamp":1700000000.123}"#;
        handle_text_message(text, &proc, &config, &state).await;

        let frames = captured.lock().unwrap();
        assert_eq!(frames.len(), 1);
        assert_eq!(frames[0].name(), "UserStartedSpeakingFrame");
    }

    #[tokio::test]
    async fn test_handle_transcription_interim_ignored() {
        let config = default_config();
        let proc = started_processor().await;
        let captured = capture_pushes(&proc);
        let state = Arc::new(Mutex::new(SixtyDbSttState::new()));

        let text = r#"{"type":"transcription","text":"hello how","confidence":0.72,"language":"en","is_final":false,"speech_final":false,"is_partial":true}"#;
        handle_text_message(text, &proc, &config, &state).await;

        assert!(captured.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn test_handle_transcription_first_emit_non_finalized() {
        let config = default_config();
        let proc = started_processor().await;
        let captured = capture_pushes(&proc);
        let state = Arc::new(Mutex::new(SixtyDbSttState::new()));

        let text = r#"{"type":"transcription","text":"Hello how are you","confidence":0.85,"language":"en","is_final":true,"speech_final":false,"is_partial":false,"sentence_id":1}"#;
        handle_text_message(text, &proc, &config, &state).await;

        let frames = captured.lock().unwrap();
        assert_eq!(frames.len(), 1);
        assert_eq!(frames[0].name(), "TranscriptionFrame");
        if let FrameInner::Data(DataFrame::Transcription(ref data)) = frames[0].inner {
            assert_eq!(data.text, "Hello how are you");
            assert!(!data.finalized);
            assert_eq!(data.language, Some("en".to_string()));
        } else {
            panic!("expected TranscriptionFrame");
        }
    }

    #[tokio::test]
    async fn test_handle_transcription_canonical_finalized() {
        let config = default_config();
        let proc = started_processor().await;
        let captured = capture_pushes(&proc);
        let state = Arc::new(Mutex::new(SixtyDbSttState::new()));

        let text = r#"{"type":"transcription","text":"Hello, how are you?","confidence":0.87,"language":"en","is_final":true,"speech_final":true,"is_partial":false,"sentence_id":1,"duration":1.82}"#;
        handle_text_message(text, &proc, &config, &state).await;

        let frames = captured.lock().unwrap();
        assert_eq!(frames.len(), 2);
        assert_eq!(frames[0].name(), "TranscriptionFrame");
        assert_eq!(frames[1].name(), "UserStoppedSpeakingFrame");

        if let FrameInner::Data(DataFrame::Transcription(ref data)) = frames[0].inner {
            assert_eq!(data.text, "Hello, how are you?");
            assert!(data.finalized);
        } else {
            panic!("expected TranscriptionFrame");
        }
    }

    #[tokio::test]
    async fn test_handle_transcription_empty_final_ignored() {
        let config = default_config();
        let proc = started_processor().await;
        let captured = capture_pushes(&proc);
        let state = Arc::new(Mutex::new(SixtyDbSttState::new()));

        let text = r#"{"type":"transcription","text":"","confidence":0.0,"is_final":true,"speech_final":true,"processing_mode":"speech_end_no_result","timestamp":1700000000.789}"#;
        handle_text_message(text, &proc, &config, &state).await;

        assert!(captured.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn test_handle_language_changed() {
        let config = default_config();
        let proc = started_processor().await;
        let state = Arc::new(Mutex::new(SixtyDbSttState::new()));
        let text = r#"{"type":"language_changed","language":"Multi-language: HI","language_code":["hi"]}"#;
        handle_text_message(text, &proc, &config, &state).await;
        assert!(state.lock().await.ws_tx.is_none());
    }

    #[tokio::test]
    async fn test_handle_mode_changed() {
        let config = default_config();
        let proc = started_processor().await;
        let state = Arc::new(Mutex::new(SixtyDbSttState::new()));
        let text = r#"{"type":"mode_changed","continuous_mode":true,"mode_name":"continuous","silence_threshold":0.5}"#;
        handle_text_message(text, &proc, &config, &state).await;
        assert!(state.lock().await.ws_tx.is_none());
    }

    // ========================================================================
    // Message parsing — errors & lifecycle
    // ========================================================================

    #[tokio::test]
    async fn test_handle_error_pushes_upstream() {
        let config = default_config();
        let proc = started_processor().await;
        let errors = capture_errors(&proc);
        let state = Arc::new(Mutex::new(SixtyDbSttState::new()));

        let text = r#"{"type":"error","error":"Audio processing error","timestamp":1700000000.0}"#;
        handle_text_message(text, &proc, &config, &state).await;

        let errs = errors.lock().unwrap();
        assert_eq!(errs.len(), 1);
        assert!(errs[0].error.contains("Audio processing error"));
    }

    #[tokio::test]
    async fn test_handle_concurrency_error() {
        let config = default_config();
        let proc = started_processor().await;
        let errors = capture_errors(&proc);
        let state = Arc::new(Mutex::new(SixtyDbSttState::new()));

        let text = r#"{"type":"error","error":"Too many concurrent STT sessions","error_code":"STT_CONCURRENCY_LIMIT","details":{"limit":8}}"#;
        handle_text_message(text, &proc, &config, &state).await;

        let errs = errors.lock().unwrap();
        assert_eq!(errs.len(), 1);
        assert!(errs[0].error.contains("STT_CONCURRENCY_LIMIT"));
    }

    #[tokio::test]
    async fn test_handle_session_stopped_sets_state() {
        let config = default_config();
        let proc = started_processor().await;
        let state = Arc::new(Mutex::new(SixtyDbSttState::new()));

        let text = r#"{"type":"session_stopped","billing_summary":{"total_duration_seconds":12.40,"total_cost":0.000620}}"#;
        handle_text_message(text, &proc, &config, &state).await;

        assert!(matches!(state.lock().await.ws_state, WsState::Stopped));
    }

    #[tokio::test]
    async fn test_handle_unknown_type_ignored() {
        let config = default_config();
        let proc = started_processor().await;
        let captured = capture_pushes(&proc);
        let state = Arc::new(Mutex::new(SixtyDbSttState::new()));

        let text = r#"{"type":"flibble","data":123}"#;
        handle_text_message(text, &proc, &config, &state).await;

        assert!(captured.lock().unwrap().is_empty());
    }

    #[tokio::test]
    async fn test_handle_malformed_json_ignored() {
        let config = default_config();
        let proc = started_processor().await;
        let captured = capture_pushes(&proc);
        let state = Arc::new(Mutex::new(SixtyDbSttState::new()));

        handle_text_message("not json at all", &proc, &config, &state).await;
        assert!(captured.lock().unwrap().is_empty());
    }

    // ========================================================================
    // Audio pipeline — prepare_and_send
    // ========================================================================

    #[tokio::test]
    async fn test_prepare_and_send_no_resample_passes_through() {
        let config = SixtyDbSttConfig {
            api_key: "test".to_string(),
            sample_rate: 16_000,
            encoding: SixtyDbEncoding::Linear,
            noise_reduction: false,
            ..Default::default()
        };
        let (handler, mut rx) = handler_with_state(config, WsState::SessionStarted).await;

        let pcm = vec![1000i16; 960];
        handler.prepare_and_send(&pcm, 16_000, false).await;

        let msg = rx.recv().await.expect("audio message should be sent");
        if let Message::Text(t) = msg {
            let val: serde_json::Value = serde_json::from_str(&t).unwrap();
            assert_eq!(val["type"], "audio");
            assert_eq!(val["encoding"], "linear");
            assert_eq!(val["sample_rate"], 16_000);
            let audio_bytes = BASE64.decode(val["audio"].as_str().unwrap()).unwrap();
            let samples = bytes_to_i16(&audio_bytes);
            assert_eq!(samples.len(), 960);
        } else {
            panic!("expected text message");
        }
    }

    #[tokio::test]
    async fn test_prepare_and_send_resamples_16k_to_48k() {
        let config = SixtyDbSttConfig {
            api_key: "test".to_string(),
            sample_rate: 48_000,
            encoding: SixtyDbEncoding::Linear,
            noise_reduction: false,
            resampler_quality: ResamplerQuality::Quick,
            ..Default::default()
        };
        let (handler, mut rx) = handler_with_state(config, WsState::SessionStarted).await;

        let pcm = vec![1000i16; 960];
        handler.prepare_and_send(&pcm, 16_000, false).await;

        let msg = rx.recv().await.expect("audio message should be sent");
        if let Message::Text(t) = msg {
            let val: serde_json::Value = serde_json::from_str(&t).unwrap();
            assert_eq!(val["type"], "audio");
            assert_eq!(val["sample_rate"], 48_000);
            let audio_bytes = BASE64.decode(val["audio"].as_str().unwrap()).unwrap();
            let samples = bytes_to_i16(&audio_bytes);
            assert!(
                samples.len() >= 2800 && samples.len() <= 3000,
                "expected ~2880 samples after upsampling, got {}",
                samples.len()
            );
        } else {
            panic!("expected text message");
        }

        assert!(handler.resampler.lock().await.is_some());
    }

    #[tokio::test]
    async fn test_prepare_and_send_with_denoise() {
        let config = SixtyDbSttConfig {
            api_key: "test".to_string(),
            sample_rate: 16_000,
            encoding: SixtyDbEncoding::Linear,
            noise_reduction: true,
            ..Default::default()
        };
        let (handler, mut rx) = handler_with_state(config, WsState::SessionStarted).await;

        let pcm = vec![1000i16; 960];
        handler.prepare_and_send(&pcm, 16_000, true).await;

        assert!(handler.noise_filter.lock().await.is_some());

        while let Ok(Some(_)) = tokio::time::timeout(tokio::time::Duration::from_millis(50), rx.recv()).await {}
    }

    #[tokio::test]
    async fn test_prepare_and_send_with_denoise_and_resample() {
        let config = SixtyDbSttConfig {
            api_key: "test".to_string(),
            sample_rate: 48_000,
            encoding: SixtyDbEncoding::Linear,
            noise_reduction: true,
            resampler_quality: ResamplerQuality::Quick,
            ..Default::default()
        };
        let (handler, mut rx) = handler_with_state(config, WsState::SessionStarted).await;

        let pcm = vec![1000i16; 960];
        handler.prepare_and_send(&pcm, 16_000, true).await;

        assert!(handler.noise_filter.lock().await.is_some());
        assert!(handler.resampler.lock().await.is_some());

        while let Ok(Some(_)) = tokio::time::timeout(tokio::time::Duration::from_millis(50), rx.recv()).await {}
    }

    #[tokio::test]
    async fn test_prepare_and_send_buffers_when_not_session_started() {
        let config = SixtyDbSttConfig {
            api_key: "test".to_string(),
            sample_rate: 16_000,
            encoding: SixtyDbEncoding::Linear,
            noise_reduction: false,
            ..Default::default()
        };
        let (handler, mut rx) = handler_with_state(config, WsState::ConnectionEstablished).await;

        let pcm = vec![1000i16; 100];
        handler.prepare_and_send(&pcm, 16_000, false).await;

        assert!(rx.try_recv().is_err());
        let state = handler.state.lock().await;
        assert_eq!(state.audio_buffer.len(), 1);
        assert_eq!(bytes_to_i16(&state.audio_buffer[0]), pcm);
    }

    // ========================================================================
    // Audio pipeline — send_audio / deliver_audio encoding modes
    // ========================================================================

    #[tokio::test]
    async fn test_deliver_audio_linear_sends_json() {
        let config = SixtyDbSttConfig {
            api_key: "test".to_string(),
            sample_rate: 16_000,
            encoding: SixtyDbEncoding::Linear,
            ..Default::default()
        };
        let (handler, mut rx) = handler_with_state(config, WsState::SessionStarted).await;

        let bytes = i16_to_bytes(&vec![1000i16, 2000i16, 3000i16]);
        handler.deliver_audio(&bytes).await;

        let msg = rx.recv().await.unwrap();
        if let Message::Text(t) = msg {
            let val: serde_json::Value = serde_json::from_str(&t).unwrap();
            assert_eq!(val["type"], "audio");
            assert_eq!(val["encoding"], "linear");
            let decoded = BASE64.decode(val["audio"].as_str().unwrap()).unwrap();
            assert_eq!(decoded, bytes);
        } else {
            panic!("expected text message");
        }
    }

    #[tokio::test]
    async fn test_deliver_audio_mulaw_sends_binary() {
        let config = SixtyDbSttConfig {
            api_key: "test".to_string(),
            sample_rate: 8000,
            encoding: SixtyDbEncoding::Mulaw,
            ..Default::default()
        };
        let (handler, mut rx) = handler_with_state(config, WsState::SessionStarted).await;

        let bytes = vec![0xFFu8, 0xAA, 0x55];
        handler.deliver_audio(&bytes).await;

        let msg = rx.recv().await.unwrap();
        if let Message::Binary(b) = msg {
            assert_eq!(b.to_vec(), bytes);
        } else {
            panic!("expected binary message");
        }
    }

    // ========================================================================
    // Frame routing — on_process_frame
    // ========================================================================

    #[tokio::test]
    async fn test_on_process_input_audio_passes_frame_downstream() {
        let config = SixtyDbSttConfig {
            api_key: "test".to_string(),
            sample_rate: 16_000,
            encoding: SixtyDbEncoding::Linear,
            noise_reduction: false,
            ..Default::default()
        };
        let handler = SixtyDbSttHandler::new(config);
        let proc = started_processor().await;
        let captured = capture_pushes(&proc);

        let (tx, mut rx) = mpsc::channel::<Message>(64);
        {
            let mut state = handler.state.lock().await;
            state.ws_tx = Some(tx);
            state.ws_state = WsState::SessionStarted;
        }

        let audio_data = AudioRawData::new(i16_to_bytes(&vec![1000i16; 100]), 16_000, 1);
        let frame = Frame::input_audio_raw(audio_data);
        handler.on_process_frame(&proc, frame, FrameDirection::Downstream).await.unwrap();

        let frames = captured.lock().unwrap();
        assert_eq!(frames.len(), 1);
        assert_eq!(frames[0].name(), "InputAudioRawFrame");

        let msg = rx.recv().await.expect("audio should be sent");
        assert!(matches!(msg, Message::Text(_)));
    }

    #[tokio::test]
    async fn test_on_process_vad_stop_flushes_noise_filter() {
        let config = SixtyDbSttConfig {
            api_key: "test".to_string(),
            sample_rate: 16_000,
            encoding: SixtyDbEncoding::Linear,
            noise_reduction: true,
            ..Default::default()
        };
        let handler = SixtyDbSttHandler::new(config);
        let proc = started_processor().await;

        let (tx, mut rx) = mpsc::channel::<Message>(64);
        {
            let mut state = handler.state.lock().await;
            state.ws_tx = Some(tx);
            state.ws_state = WsState::SessionStarted;
        }

        let audio_data = AudioRawData::new(i16_to_bytes(&vec![1000i16; 960]), 16_000, 1);
        let frame = Frame::input_audio_raw(audio_data);
        handler.on_process_frame(&proc, frame.clone(), FrameDirection::Downstream).await.unwrap();

        let vad_frame = Frame::vad_user_stopped_speaking(0.0, 0.0);
        handler.on_process_frame(&proc, vad_frame, FrameDirection::Downstream).await.unwrap();

        assert!(handler.noise_filter.lock().await.is_some());
    }

    #[tokio::test]
    async fn test_on_process_end_frame_sends_stop() {
        let config = SixtyDbSttConfig {
            api_key: "test".to_string(),
            sample_rate: 16_000,
            encoding: SixtyDbEncoding::Linear,
            noise_reduction: false,
            ..Default::default()
        };
        let handler = SixtyDbSttHandler::new(config);
        let proc = started_processor().await;

        let (tx, mut rx) = mpsc::channel::<Message>(64);
        {
            let mut state = handler.state.lock().await;
            state.ws_tx = Some(tx);
            state.ws_state = WsState::SessionStarted;
        }

        let frame = Frame::end();
        handler.on_process_frame(&proc, frame, FrameDirection::Downstream).await.unwrap();

        let msg = tokio::time::timeout(tokio::time::Duration::from_millis(500), rx.recv())
            .await
            .expect("timeout waiting for stop")
            .expect("stop message should be sent");
        if let Message::Text(t) = msg {
            assert!(t.contains("stop"));
        } else {
            panic!("expected text message");
        }

        assert!(matches!(
            handler.state.lock().await.ws_state,
            WsState::Stopping | WsState::Disconnected
        ));
    }

    #[tokio::test]
    async fn test_on_process_cancel_frame_sends_stop() {
        let config = SixtyDbSttConfig {
            api_key: "test".to_string(),
            sample_rate: 16_000,
            encoding: SixtyDbEncoding::Linear,
            noise_reduction: false,
            ..Default::default()
        };
        let handler = SixtyDbSttHandler::new(config);
        let proc = started_processor().await;

        let (tx, mut rx) = mpsc::channel::<Message>(64);
        {
            let mut state = handler.state.lock().await;
            state.ws_tx = Some(tx);
            state.ws_state = WsState::SessionStarted;
        }

        let frame = Frame::cancel();
        handler.on_process_frame(&proc, frame, FrameDirection::Downstream).await.unwrap();

        let msg = tokio::time::timeout(tokio::time::Duration::from_millis(500), rx.recv())
            .await
            .expect("timeout waiting for stop")
            .expect("stop message should be sent");
        if let Message::Text(t) = msg {
            assert!(t.contains("stop"));
        } else {
            panic!("expected text message");
        }
    }

    // ========================================================================
    // State machine & lifecycle
    // ========================================================================

    #[tokio::test]
    async fn test_disconnect_cleans_up_state() {
        let config = default_config();
        let handler = SixtyDbSttHandler::new(config);

        {
            let mut nf = handler.noise_filter.lock().await;
            *nf = Some(RNNoiseFilter::new(16_000));
        }
        {
            let mut r = handler.resampler.lock().await;
            *r = Some(StreamResampler::new(16_000, 48_000, ResamplerQuality::Quick));
        }
        {
            let mut state = handler.state.lock().await;
            state.input_sample_rate = Some(16_000);
            state.audio_buffer.push(vec![1, 2, 3]);
        }

        handler.disconnect().await;

        let state = handler.state.lock().await;
        assert!(matches!(state.ws_state, WsState::Stopping));
        assert!(state.ws_tx.is_none());
        assert!(state.audio_buffer.is_empty());
        assert!(state.input_sample_rate.is_none());
        assert!(handler.noise_filter.lock().await.is_none());
        assert!(handler.resampler.lock().await.is_none());
    }

    #[tokio::test]
    async fn test_send_stop_produces_valid_json() {
        let config = default_config();
        let (handler, mut rx) = handler_with_state(config, WsState::SessionStarted).await;

        handler.send_stop().await;

        let msg = rx.recv().await.expect("stop message");
        if let Message::Text(t) = msg {
            let val: serde_json::Value = serde_json::from_str(&t).unwrap();
            assert_eq!(val["type"], "stop");
        } else {
            panic!("expected text message");
        }
    }

    #[tokio::test]
    async fn test_audio_buffering_and_flush() {
        let config = SixtyDbSttConfig {
            api_key: "test".to_string(),
            sample_rate: 16_000,
            encoding: SixtyDbEncoding::Linear,
            ..Default::default()
        };
        let (handler, mut rx) = handler_with_state(config, WsState::ConnectionEstablished).await;

        let chunk1 = vec![1u8, 2, 3, 4];
        let chunk2 = vec![5u8, 6, 7, 8];
        handler.send_audio(&chunk1).await;
        handler.send_audio(&chunk2).await;

        {
            let state = handler.state.lock().await;
            assert_eq!(state.audio_buffer.len(), 2);
            assert_eq!(state.audio_buffer[0], chunk1);
            assert_eq!(state.audio_buffer[1], chunk2);
        }

        {
            let mut state = handler.state.lock().await;
            state.ws_state = WsState::SessionStarted;
        }

        let chunk3 = vec![9u8, 10, 11, 12];
        handler.send_audio(&chunk3).await;

        let msg1 = rx.recv().await.expect("chunk1");
        let msg2 = rx.recv().await.expect("chunk2");
        let msg3 = rx.recv().await.expect("chunk3");

        for msg in [msg1, msg2, msg3] {
            assert!(matches!(msg, Message::Text(_)));
        }

        assert!(handler.state.lock().await.audio_buffer.is_empty());
    }

    // ========================================================================
    // Edge cases
    // ========================================================================

    #[tokio::test]
    async fn test_prepare_and_send_empty_pcm_does_nothing() {
        let config = SixtyDbSttConfig {
            api_key: "test".to_string(),
            sample_rate: 16_000,
            encoding: SixtyDbEncoding::Linear,
            noise_reduction: false,
            ..Default::default()
        };
        let (handler, mut rx) = handler_with_state(config, WsState::SessionStarted).await;

        handler.prepare_and_send(&[], 16_000, false).await;

        assert!(rx.try_recv().is_err());
    }

    #[tokio::test]
    async fn test_transcription_with_words_field() {
        let config = default_config();
        let proc = started_processor().await;
        let captured = capture_pushes(&proc);
        let state = Arc::new(Mutex::new(SixtyDbSttState::new()));

        let text = r#"{"type":"transcription","text":"Hello","confidence":0.94,"language":"en","is_final":true,"speech_final":true,"words":[{"word":"Hello","start":0.0,"end":0.32,"confidence":0.94}],"sentence_id":5}"#;
        handle_text_message(text, &proc, &config, &state).await;

        let frames = captured.lock().unwrap();
        assert_eq!(frames.len(), 2);
        if let FrameInner::Data(DataFrame::Transcription(ref data)) = frames[0].inner {
            assert_eq!(data.text, "Hello");
            assert!(data.finalized);
        } else {
            panic!("expected TranscriptionFrame");
        }
    }

    #[tokio::test]
    async fn test_transcription_boosted_word() {
        let config = default_config();
        let proc = started_processor().await;
        let captured = capture_pushes(&proc);
        let state = Arc::new(Mutex::new(SixtyDbSttState::new()));

        let text = r#"{"type":"transcription","text":"Acme","confidence":0.85,"language":"en","is_final":true,"speech_final":true,"words":[{"word":"Acme","start":1.5,"end":2.0,"confidence":0.85,"boosted":true,"original":"akmie"}]}"#;
        handle_text_message(text, &proc, &config, &state).await;

        let frames = captured.lock().unwrap();
        assert_eq!(frames[0].name(), "TranscriptionFrame");
        if let FrameInner::Data(DataFrame::Transcription(ref data)) = frames[0].inner {
            assert_eq!(data.text, "Acme");
        } else {
            panic!("expected TranscriptionFrame");
        }
    }
}