quiver-dsp 0.1.0

A modular audio synthesis library using Arrow-style combinators and graph-based patching
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
//! Extended I/O
//!
//! This module provides extended I/O capabilities:
//! - OSC (Open Sound Control) protocol support
//! - VST/AU plugin wrapper infrastructure
//! - Web Audio backend interface
//!
//! # OSC Support
//!
//! The OSC implementation provides a bridge between network OSC messages
//! and the patch graph, allowing remote control of synthesizer parameters.
//!
//! # Plugin Wrapper
//!
//! The plugin wrapper infrastructure provides the foundation for building
//! VST3/AU/LV2 plugins from Quiver patches.
//!
//! # Web Audio
//!
//! The Web Audio interface provides traits and structures for integrating
//! Quiver with WebAssembly-based audio processing.

use crate::io::AtomicF64;
use crate::port::{GraphModule, PortDef, PortSpec, PortValues, SignalKind};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::sync::Arc;

// ============================================================================
// OSC Protocol Support
// ============================================================================

/// OSC message types
#[derive(Debug, Clone)]
pub enum OscValue {
    /// 32-bit integer
    Int(i32),
    /// 32-bit float
    Float(f32),
    /// String
    String(String),
    /// Blob (binary data)
    Blob(Vec<u8>),
    /// True boolean
    True,
    /// False boolean
    False,
    /// Nil/null
    Nil,
    /// Infinitum/bang
    Infinitum,
    /// 64-bit integer
    Long(i64),
    /// 64-bit float
    Double(f64),
}

impl OscValue {
    /// Convert to f64 for CV use
    pub fn to_f64(&self) -> Option<f64> {
        match self {
            OscValue::Int(v) => Some(*v as f64),
            OscValue::Float(v) => Some(*v as f64),
            OscValue::Long(v) => Some(*v as f64),
            OscValue::Double(v) => Some(*v),
            OscValue::True => Some(1.0),
            OscValue::False => Some(0.0),
            _ => None,
        }
    }

    /// Convert to bool
    pub fn to_bool(&self) -> Option<bool> {
        match self {
            OscValue::Int(v) => Some(*v != 0),
            OscValue::Float(v) => Some(*v != 0.0),
            OscValue::True => Some(true),
            OscValue::False => Some(false),
            _ => None,
        }
    }
}

/// An OSC message with address and arguments
#[derive(Debug, Clone)]
pub struct OscMessage {
    /// OSC address pattern (e.g., "/synth/filter/cutoff")
    pub address: String,
    /// Message arguments
    pub args: Vec<OscValue>,
}

impl OscMessage {
    /// Create a new OSC message
    pub fn new(address: impl Into<String>) -> Self {
        Self {
            address: address.into(),
            args: Vec::new(),
        }
    }

    /// Add an argument
    pub fn with_arg(mut self, arg: OscValue) -> Self {
        self.args.push(arg);
        self
    }

    /// Add a float argument
    pub fn with_float(self, value: f32) -> Self {
        self.with_arg(OscValue::Float(value))
    }

    /// Add an int argument
    pub fn with_int(self, value: i32) -> Self {
        self.with_arg(OscValue::Int(value))
    }

    /// Get the first argument as f64
    pub fn first_f64(&self) -> Option<f64> {
        self.args.first().and_then(|v| v.to_f64())
    }
}

/// OSC address pattern matcher implementing OSC 1.0 wildcard semantics.
///
/// Matching is **component-scoped** (`*` and `?` never cross a `/`), and
/// supports character classes `[a-z]` with ranges, negation `[!...]`, and
/// alternation `{foo,bar}`. Malformed patterns (an unterminated `[` or `{`,
/// or an empty class) fail to match rather than silently swallowing the rest
/// of the pattern.
pub struct OscPattern {
    /// Pattern split into path components (each free of `/`).
    components: Vec<String>,
}

impl OscPattern {
    /// Parse an OSC address pattern.
    pub fn new(pattern: &str) -> Self {
        let components = pattern
            .split('/')
            .filter(|s| !s.is_empty())
            .map(String::from)
            .collect();
        Self { components }
    }

    /// Check if an address matches this pattern.
    ///
    /// Both sides are split into path components; each address component must
    /// match the pattern component at the same position, and the component
    /// counts must be equal (OSC has no cross-component `*`).
    pub fn matches(&self, address: &str) -> bool {
        let parts: Vec<&str> = address.split('/').filter(|s| !s.is_empty()).collect();
        if parts.len() != self.components.len() {
            return false;
        }
        self.components
            .iter()
            .zip(parts.iter())
            .all(|(pat, part)| component_matches(pat, part))
    }
}

/// Match a single path component against an OSC pattern component.
fn component_matches(pattern: &str, text: &str) -> bool {
    let pat: Vec<char> = pattern.chars().collect();
    let txt: Vec<char> = text.chars().collect();
    glob_match(&pat, &txt)
}

/// Recursive OSC glob matcher over the remaining pattern and text.
fn glob_match(pat: &[char], text: &[char]) -> bool {
    let Some((&c, rest)) = pat.split_first() else {
        return text.is_empty();
    };

    match c {
        '*' => {
            // Match zero or more characters (never `/`, already split out).
            (0..=text.len()).any(|i| glob_match(rest, &text[i..]))
        }
        '?' => !text.is_empty() && glob_match(rest, &text[1..]),
        '[' => match parse_class(pat) {
            Some((class, consumed)) => {
                !text.is_empty()
                    && class_matches(&class, text[0])
                    && glob_match(&pat[consumed..], &text[1..])
            }
            // Malformed class => fail to match.
            None => false,
        },
        '{' => match parse_alternation(pat) {
            Some((alts, consumed)) => alts.iter().any(|alt| {
                strip_prefix(alt, text).is_some_and(|rem| glob_match(&pat[consumed..], rem))
            }),
            // Malformed alternation => fail to match.
            None => false,
        },
        _ => !text.is_empty() && text[0] == c && glob_match(rest, &text[1..]),
    }
}

/// One entry of a character class.
enum ClassItem {
    Char(char),
    Range(char, char),
}

/// A parsed `[...]` character class.
struct CharClass {
    negated: bool,
    items: Vec<ClassItem>,
}

/// Parse a `[...]` class beginning at `pat[0] == '['`.
///
/// Returns the class and the number of pattern chars consumed (including the
/// closing `]`), or `None` if the class is unterminated or empty (malformed).
fn parse_class(pat: &[char]) -> Option<(CharClass, usize)> {
    debug_assert_eq!(pat.first(), Some(&'['));
    let mut i = 1;
    let mut negated = false;
    if matches!(pat.get(i), Some('!') | Some('^')) {
        negated = true;
        i += 1;
    }

    let mut items = Vec::new();
    let mut closed = false;
    while i < pat.len() {
        if pat[i] == ']' {
            closed = true;
            i += 1;
            break;
        }
        // A range `a-z`: a '-' between two chars, where the char after '-' is
        // not the closing ']'.
        if i + 2 < pat.len() && pat[i + 1] == '-' && pat[i + 2] != ']' {
            items.push(ClassItem::Range(pat[i], pat[i + 2]));
            i += 3;
        } else {
            items.push(ClassItem::Char(pat[i]));
            i += 1;
        }
    }

    if !closed || items.is_empty() {
        return None;
    }
    Some((CharClass { negated, items }, i))
}

/// Test a character against a parsed class.
fn class_matches(class: &CharClass, ch: char) -> bool {
    let mut hit = false;
    for item in &class.items {
        match item {
            ClassItem::Char(c) => {
                if *c == ch {
                    hit = true;
                    break;
                }
            }
            ClassItem::Range(a, b) => {
                let (lo, hi) = if a <= b { (*a, *b) } else { (*b, *a) };
                if ch >= lo && ch <= hi {
                    hit = true;
                    break;
                }
            }
        }
    }
    hit ^ class.negated
}

/// Parse a `{a,b,c}` alternation beginning at `pat[0] == '{'`.
///
/// Returns the (literal) alternatives and the number of pattern chars consumed
/// (including the closing `}`), or `None` if unterminated (malformed).
fn parse_alternation(pat: &[char]) -> Option<(Vec<Vec<char>>, usize)> {
    debug_assert_eq!(pat.first(), Some(&'{'));
    let mut i = 1;
    let mut alts = Vec::new();
    let mut current = Vec::new();
    let mut closed = false;
    while i < pat.len() {
        match pat[i] {
            '}' => {
                alts.push(current);
                closed = true;
                i += 1;
                break;
            }
            ',' => {
                alts.push(core::mem::take(&mut current));
                i += 1;
            }
            c => {
                current.push(c);
                i += 1;
            }
        }
    }
    if !closed {
        return None;
    }
    Some((alts, i))
}

/// If `text` starts with the literal `prefix`, return the remaining text.
fn strip_prefix<'a>(prefix: &[char], text: &'a [char]) -> Option<&'a [char]> {
    if text.len() >= prefix.len() && text[..prefix.len()] == *prefix {
        Some(&text[prefix.len()..])
    } else {
        None
    }
}

/// Binding between an OSC address and a parameter
pub struct OscBinding {
    /// OSC address pattern
    pub pattern: OscPattern,
    /// Target value
    pub value: Arc<AtomicF64>,
    /// Optional scale factor
    pub scale: f64,
    /// Optional offset
    pub offset: f64,
}

impl OscBinding {
    /// Create a new binding
    pub fn new(pattern: &str, value: Arc<AtomicF64>) -> Self {
        Self {
            pattern: OscPattern::new(pattern),
            value,
            scale: 1.0,
            offset: 0.0,
        }
    }

    /// Set scale factor
    pub fn with_scale(mut self, scale: f64) -> Self {
        self.scale = scale;
        self
    }

    /// Set offset
    pub fn with_offset(mut self, offset: f64) -> Self {
        self.offset = offset;
        self
    }

    /// Apply a message to this binding
    pub fn apply(&self, msg: &OscMessage) -> bool {
        if !self.pattern.matches(&msg.address) {
            return false;
        }

        if let Some(v) = msg.first_f64() {
            self.value.set(v * self.scale + self.offset);
            return true;
        }

        false
    }
}

/// OSC receiver that routes messages to bindings
pub struct OscReceiver {
    /// Registered bindings
    bindings: Vec<OscBinding>,
    /// Counter for total messages received
    message_count: AtomicU32,
    /// Counter for messages that matched at least one binding
    matched_count: AtomicU32,
}

impl OscReceiver {
    /// Create a new OSC receiver
    pub fn new() -> Self {
        Self {
            bindings: Vec::new(),
            message_count: AtomicU32::new(0),
            matched_count: AtomicU32::new(0),
        }
    }

    /// Add a binding
    pub fn add_binding(&mut self, binding: OscBinding) {
        self.bindings.push(binding);
    }

    /// Create a binding for a parameter
    pub fn bind(&mut self, pattern: &str, value: Arc<AtomicF64>) {
        self.add_binding(OscBinding::new(pattern, value));
    }

    /// Create a scaled binding (e.g., 0-1 to 20-20000 Hz)
    pub fn bind_scaled(&mut self, pattern: &str, value: Arc<AtomicF64>, scale: f64, offset: f64) {
        self.add_binding(
            OscBinding::new(pattern, value)
                .with_scale(scale)
                .with_offset(offset),
        );
    }

    /// Process an OSC message
    /// Returns true if at least one binding matched
    pub fn handle_message(&self, msg: &OscMessage) -> bool {
        self.message_count.fetch_add(1, Ordering::Relaxed);
        let mut handled = false;
        for binding in &self.bindings {
            if binding.apply(msg) {
                handled = true;
            }
        }
        if handled {
            self.matched_count.fetch_add(1, Ordering::Relaxed);
        }
        handled
    }

    /// Get the number of bindings
    pub fn binding_count(&self) -> usize {
        self.bindings.len()
    }

    /// Get the total number of messages received
    pub fn message_count(&self) -> u32 {
        self.message_count.load(Ordering::Relaxed)
    }

    /// Get the number of messages that matched at least one binding
    pub fn matched_count(&self) -> u32 {
        self.matched_count.load(Ordering::Relaxed)
    }

    /// Reset the message counters
    pub fn reset_counters(&self) {
        self.message_count.store(0, Ordering::Relaxed);
        self.matched_count.store(0, Ordering::Relaxed);
    }
}

impl Default for OscReceiver {
    fn default() -> Self {
        Self::new()
    }
}

/// OSC input module for patch graphs
pub struct OscInput {
    /// Target value
    value: Arc<AtomicF64>,
    /// Port specification
    spec: PortSpec,
    /// OSC address (for documentation)
    address: String,
}

impl OscInput {
    /// Create a new OSC input
    pub fn new(address: impl Into<String>, value: Arc<AtomicF64>, kind: SignalKind) -> Self {
        Self {
            value,
            spec: PortSpec {
                inputs: vec![],
                outputs: vec![PortDef::new(0, "out", kind)],
            },
            address: address.into(),
        }
    }

    /// Get the OSC address
    pub fn address(&self) -> &str {
        &self.address
    }

    /// Get reference to the value
    pub fn value_ref(&self) -> &Arc<AtomicF64> {
        &self.value
    }
}

impl GraphModule for OscInput {
    fn port_spec(&self) -> &PortSpec {
        &self.spec
    }

    fn tick(&mut self, _inputs: &PortValues, outputs: &mut PortValues) {
        outputs.set(0, self.value.get());
    }

    fn reset(&mut self) {}

    fn set_sample_rate(&mut self, _: f64) {}

    fn type_id(&self) -> &'static str {
        "osc_input"
    }
}

// ============================================================================
// Plugin Wrapper Infrastructure
// ============================================================================

/// Plugin parameter definition
#[derive(Debug, Clone)]
pub struct PluginParameter {
    /// Parameter ID
    pub id: u32,
    /// Display name
    pub name: String,
    /// Short name (for limited displays)
    pub short_name: String,
    /// Minimum value
    pub min: f64,
    /// Maximum value
    pub max: f64,
    /// Default value
    pub default: f64,
    /// Unit label (e.g., "Hz", "dB", "%")
    pub unit: String,
    /// Number of steps (0 = continuous)
    pub steps: u32,
}

impl PluginParameter {
    /// Create a new continuous parameter
    pub fn new(id: u32, name: &str, min: f64, max: f64, default: f64) -> Self {
        Self {
            id,
            name: name.to_string(),
            short_name: name.chars().take(8).collect(),
            min,
            max,
            default,
            unit: String::new(),
            steps: 0,
        }
    }

    /// Set the unit label
    pub fn with_unit(mut self, unit: &str) -> Self {
        self.unit = unit.to_string();
        self
    }

    /// Set the number of steps (for discrete parameters)
    pub fn with_steps(mut self, steps: u32) -> Self {
        self.steps = steps;
        self
    }

    /// Set the short name
    pub fn with_short_name(mut self, short_name: &str) -> Self {
        self.short_name = short_name.to_string();
        self
    }

    /// Normalize a value to 0.0-1.0 range
    pub fn normalize(&self, value: f64) -> f64 {
        (value - self.min) / (self.max - self.min)
    }

    /// Denormalize from 0.0-1.0 to parameter range
    pub fn denormalize(&self, normalized: f64) -> f64 {
        self.min + normalized * (self.max - self.min)
    }

    /// Quantize to steps (if discrete)
    pub fn quantize(&self, value: f64) -> f64 {
        if self.steps == 0 {
            return value;
        }
        let step_size = (self.max - self.min) / self.steps as f64;
        let steps = ((value - self.min) / step_size).round();
        self.min + steps * step_size
    }
}

/// Plugin audio bus configuration
#[derive(Debug, Clone)]
pub struct AudioBusConfig {
    /// Number of input channels
    pub inputs: u32,
    /// Number of output channels
    pub outputs: u32,
    /// Bus name
    pub name: String,
}

impl AudioBusConfig {
    /// Create a stereo output configuration
    pub fn stereo_out() -> Self {
        Self {
            inputs: 0,
            outputs: 2,
            name: "Main".to_string(),
        }
    }

    /// Create a stereo I/O configuration
    pub fn stereo_io() -> Self {
        Self {
            inputs: 2,
            outputs: 2,
            name: "Main".to_string(),
        }
    }

    /// Create a mono output configuration
    pub fn mono_out() -> Self {
        Self {
            inputs: 0,
            outputs: 1,
            name: "Main".to_string(),
        }
    }
}

/// Plugin metadata
#[derive(Debug, Clone)]
pub struct PluginInfo {
    /// Plugin unique identifier
    pub id: String,
    /// Display name
    pub name: String,
    /// Vendor name
    pub vendor: String,
    /// Version string
    pub version: String,
    /// Plugin category
    pub category: PluginCategory,
    /// Whether the plugin is a synth (has no audio inputs)
    pub is_synth: bool,
    /// Supported sample rates (empty = any)
    pub sample_rates: Vec<f64>,
    /// Maximum block size (0 = any)
    pub max_block_size: usize,
    /// Latency in samples
    pub latency: u32,
}

/// Plugin category
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PluginCategory {
    Effect,
    Instrument,
    Analyzer,
    Spatial,
    Generator,
    Other,
}

impl PluginInfo {
    /// Create a new synth plugin info
    pub fn synth(id: &str, name: &str, vendor: &str) -> Self {
        Self {
            id: id.to_string(),
            name: name.to_string(),
            vendor: vendor.to_string(),
            version: "1.0.0".to_string(),
            category: PluginCategory::Instrument,
            is_synth: true,
            sample_rates: vec![],
            max_block_size: 0,
            latency: 0,
        }
    }

    /// Create a new effect plugin info
    pub fn effect(id: &str, name: &str, vendor: &str) -> Self {
        Self {
            id: id.to_string(),
            name: name.to_string(),
            vendor: vendor.to_string(),
            version: "1.0.0".to_string(),
            category: PluginCategory::Effect,
            is_synth: false,
            sample_rates: vec![],
            max_block_size: 0,
            latency: 0,
        }
    }
}

/// Plugin wrapper for adapting Quiver patches to plugin formats
pub struct PluginWrapper {
    /// Plugin metadata
    pub info: PluginInfo,
    /// Audio bus configuration
    pub bus_config: AudioBusConfig,
    /// Parameter definitions
    pub parameters: Vec<PluginParameter>,
    /// Parameter values (atomic for thread-safe access)
    pub param_values: Vec<Arc<AtomicF64>>,
    /// Sample rate
    pub sample_rate: f64,
    /// Processing state
    pub is_processing: AtomicBool,
}

impl PluginWrapper {
    /// Create a new plugin wrapper
    pub fn new(info: PluginInfo, bus_config: AudioBusConfig) -> Self {
        Self {
            info,
            bus_config,
            parameters: Vec::new(),
            param_values: Vec::new(),
            sample_rate: 44100.0,
            is_processing: AtomicBool::new(false),
        }
    }

    /// Add a parameter
    pub fn add_parameter(&mut self, param: PluginParameter) -> Arc<AtomicF64> {
        let value = Arc::new(AtomicF64::new(param.default));
        self.param_values.push(value.clone());
        self.parameters.push(param);
        value
    }

    /// Get parameter count
    pub fn parameter_count(&self) -> usize {
        self.parameters.len()
    }

    /// Get parameter value by index
    pub fn get_parameter(&self, index: usize) -> Option<f64> {
        self.param_values.get(index).map(|v| v.get())
    }

    /// Set parameter value by index (normalized 0-1)
    pub fn set_parameter_normalized(&self, index: usize, normalized: f64) {
        if let (Some(param), Some(value)) =
            (self.parameters.get(index), self.param_values.get(index))
        {
            let denormalized = param.denormalize(normalized.clamp(0.0, 1.0));
            let quantized = param.quantize(denormalized);
            value.set(quantized);
        }
    }

    /// Set sample rate
    pub fn set_sample_rate(&mut self, sample_rate: f64) {
        self.sample_rate = sample_rate;
    }

    /// Start processing
    pub fn start_processing(&self) {
        self.is_processing.store(true, Ordering::SeqCst);
    }

    /// Stop processing
    pub fn stop_processing(&self) {
        self.is_processing.store(false, Ordering::SeqCst);
    }

    /// Check if processing is active
    pub fn is_processing(&self) -> bool {
        self.is_processing.load(Ordering::SeqCst)
    }

    /// Get the latency in samples
    pub fn latency(&self) -> u32 {
        self.info.latency
    }

    /// Set the latency in samples
    pub fn set_latency(&mut self, samples: u32) {
        self.info.latency = samples;
    }
}

// ============================================================================
// MIDI Support for Plugin Integration
// ============================================================================

/// MIDI message status bytes
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MidiStatus {
    /// Note Off (channel 0-15)
    NoteOff(u8),
    /// Note On (channel 0-15)
    NoteOn(u8),
    /// Polyphonic Aftertouch (channel 0-15)
    PolyPressure(u8),
    /// Control Change (channel 0-15)
    ControlChange(u8),
    /// Program Change (channel 0-15)
    ProgramChange(u8),
    /// Channel Aftertouch (channel 0-15)
    ChannelPressure(u8),
    /// Pitch Bend (channel 0-15)
    PitchBend(u8),
    /// System message
    System(u8),
}

impl MidiStatus {
    /// Parse status byte
    pub fn from_byte(byte: u8) -> Option<Self> {
        let status = byte & 0xF0;
        let channel = byte & 0x0F;
        match status {
            0x80 => Some(MidiStatus::NoteOff(channel)),
            0x90 => Some(MidiStatus::NoteOn(channel)),
            0xA0 => Some(MidiStatus::PolyPressure(channel)),
            0xB0 => Some(MidiStatus::ControlChange(channel)),
            0xC0 => Some(MidiStatus::ProgramChange(channel)),
            0xD0 => Some(MidiStatus::ChannelPressure(channel)),
            0xE0 => Some(MidiStatus::PitchBend(channel)),
            0xF0..=0xFF => Some(MidiStatus::System(byte)),
            _ => None,
        }
    }

    /// Get the channel (0-15) or None for system messages
    pub fn channel(&self) -> Option<u8> {
        match self {
            MidiStatus::NoteOff(ch)
            | MidiStatus::NoteOn(ch)
            | MidiStatus::PolyPressure(ch)
            | MidiStatus::ControlChange(ch)
            | MidiStatus::ProgramChange(ch)
            | MidiStatus::ChannelPressure(ch)
            | MidiStatus::PitchBend(ch) => Some(*ch),
            MidiStatus::System(_) => None,
        }
    }
}

/// A MIDI message with timing information
#[derive(Debug, Clone)]
pub struct MidiMessage {
    /// Sample offset within the current buffer
    pub sample_offset: u32,
    /// Status byte
    pub status: MidiStatus,
    /// Data byte 1 (note number, CC number, etc.)
    pub data1: u8,
    /// Data byte 2 (velocity, CC value, etc.)
    pub data2: u8,
}

impl MidiMessage {
    /// Create a Note On message
    pub fn note_on(channel: u8, note: u8, velocity: u8) -> Self {
        Self {
            sample_offset: 0,
            status: MidiStatus::NoteOn(channel & 0x0F),
            data1: note & 0x7F,
            data2: velocity & 0x7F,
        }
    }

    /// Create a Note Off message
    pub fn note_off(channel: u8, note: u8, velocity: u8) -> Self {
        Self {
            sample_offset: 0,
            status: MidiStatus::NoteOff(channel & 0x0F),
            data1: note & 0x7F,
            data2: velocity & 0x7F,
        }
    }

    /// Create a Control Change message
    pub fn control_change(channel: u8, cc: u8, value: u8) -> Self {
        Self {
            sample_offset: 0,
            status: MidiStatus::ControlChange(channel & 0x0F),
            data1: cc & 0x7F,
            data2: value & 0x7F,
        }
    }

    /// Create a Pitch Bend message (value: -8192 to 8191)
    pub fn pitch_bend(channel: u8, value: i16) -> Self {
        let unsigned = (value + 8192).clamp(0, 16383) as u16;
        Self {
            sample_offset: 0,
            status: MidiStatus::PitchBend(channel & 0x0F),
            data1: (unsigned & 0x7F) as u8,
            data2: ((unsigned >> 7) & 0x7F) as u8,
        }
    }

    /// Set sample offset for sample-accurate timing
    pub fn at_sample(mut self, offset: u32) -> Self {
        self.sample_offset = offset;
        self
    }

    /// Check if this is a Note On with non-zero velocity
    pub fn is_note_on(&self) -> bool {
        matches!(self.status, MidiStatus::NoteOn(_)) && self.data2 > 0
    }

    /// Check if this is a Note Off (or Note On with velocity 0)
    pub fn is_note_off(&self) -> bool {
        matches!(self.status, MidiStatus::NoteOff(_))
            || (matches!(self.status, MidiStatus::NoteOn(_)) && self.data2 == 0)
    }

    /// Get the note number (0-127)
    pub fn note(&self) -> u8 {
        self.data1
    }

    /// Get the velocity (0-127)
    pub fn velocity(&self) -> u8 {
        self.data2
    }

    /// Convert note to frequency (A4 = 440Hz)
    pub fn note_to_frequency(&self) -> f64 {
        440.0 * 2.0_f64.powf((self.data1 as f64 - 69.0) / 12.0)
    }

    /// Convert note to V/Oct (0V = C4, 1V = C5, etc.)
    pub fn note_to_volt_per_octave(&self) -> f64 {
        (self.data1 as f64 - 60.0) / 12.0
    }

    /// Get pitch bend as -1.0 to 1.0 (for +/- 2 semitones typically)
    pub fn pitch_bend_normalized(&self) -> f64 {
        if !matches!(self.status, MidiStatus::PitchBend(_)) {
            return 0.0;
        }
        let value = (self.data1 as i32) | ((self.data2 as i32) << 7);
        (value - 8192) as f64 / 8192.0
    }
}

/// MIDI event buffer for a processing block
pub struct MidiBuffer {
    /// Events sorted by sample offset
    events: Vec<MidiMessage>,
}

impl MidiBuffer {
    /// Create an empty MIDI buffer
    pub fn new() -> Self {
        Self { events: Vec::new() }
    }

    /// Create a buffer with capacity
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            events: Vec::with_capacity(capacity),
        }
    }

    /// Add an event
    pub fn push(&mut self, event: MidiMessage) {
        self.events.push(event);
    }

    /// Clear the buffer
    pub fn clear(&mut self) {
        self.events.clear();
    }

    /// Sort events by sample offset
    pub fn sort(&mut self) {
        self.events.sort_by_key(|e| e.sample_offset);
    }

    /// Get iterator over events
    pub fn iter(&self) -> impl Iterator<Item = &MidiMessage> {
        self.events.iter()
    }

    /// Get events at a specific sample offset
    pub fn events_at(&self, sample: u32) -> impl Iterator<Item = &MidiMessage> {
        self.events
            .iter()
            .filter(move |e| e.sample_offset == sample)
    }

    /// Get number of events
    pub fn len(&self) -> usize {
        self.events.len()
    }

    /// Check if empty
    pub fn is_empty(&self) -> bool {
        self.events.is_empty()
    }
}

impl Default for MidiBuffer {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Plugin Processor Trait
// ============================================================================

/// Processing context passed to plugin processor
pub struct ProcessContext<'a> {
    /// Sample rate
    pub sample_rate: f64,
    /// Number of samples in this block
    pub num_samples: usize,
    /// Current transport position in samples (if available)
    pub transport_position: Option<u64>,
    /// Current tempo in BPM (if available)
    pub tempo: Option<f64>,
    /// Whether transport is playing
    pub is_playing: bool,
    /// MIDI input events
    pub midi_in: &'a MidiBuffer,
    /// MIDI output events
    pub midi_out: &'a mut MidiBuffer,
}

/// Trait for plugin audio processors
///
/// This trait provides the complete interface for implementing audio plugins.
/// Implementations can be used with VST3, AU, or LV2 wrappers.
///
/// # Example
///
/// ```no_run
/// use quiver::prelude::*;
/// use quiver::extended_io::{PluginProcessor, ProcessContext};
///
/// struct MySynth {
///     patch: Patch,
///     sample_rate: f64,
/// }
///
/// impl PluginProcessor for MySynth {
///     fn initialize(&mut self, sample_rate: f64, _max_block_size: usize) {
///         self.sample_rate = sample_rate;
///     }
///
///     fn process(
///         &mut self,
///         _inputs: &[&[f32]],
///         outputs: &mut [&mut [f32]],
///         context: &mut ProcessContext,
///     ) {
///         // Handle MIDI
///         for event in context.midi_in.iter() {
///             if event.is_note_on() {
///                 // Trigger a note...
///             }
///         }
///
///         // Process audio
///         for i in 0..context.num_samples {
///             let (left, right) = self.patch.tick();
///             outputs[0][i] = left as f32;
///             outputs[1][i] = right as f32;
///         }
///     }
///
///     fn reset(&mut self) {
///         self.patch.reset();
///     }
///
///     fn set_parameter(&mut self, _id: u32, _value: f64) {}
///     fn get_parameter(&self, _id: u32) -> f64 { 0.0 }
/// }
/// ```
pub trait PluginProcessor: Send {
    /// Initialize the processor
    ///
    /// Called once when the plugin is instantiated or when sample rate changes.
    fn initialize(&mut self, sample_rate: f64, max_block_size: usize);

    /// Process a block of audio
    ///
    /// `inputs`: Slice of input channel buffers (may be empty for synths)
    /// `outputs`: Slice of output channel buffers
    /// `context`: Processing context with timing and MIDI
    fn process(
        &mut self,
        inputs: &[&[f32]],
        outputs: &mut [&mut [f32]],
        context: &mut ProcessContext,
    );

    /// Reset processor state
    ///
    /// Called when playback stops or when bypassed for a while.
    fn reset(&mut self);

    /// Set a parameter value
    fn set_parameter(&mut self, id: u32, value: f64);

    /// Get a parameter value
    fn get_parameter(&self, id: u32) -> f64;

    /// Get the number of parameters
    fn parameter_count(&self) -> usize {
        0
    }

    /// Get parameter info
    fn parameter_info(&self, _id: u32) -> Option<PluginParameter> {
        None
    }

    /// Get tail length in samples (for reverbs, delays, etc.)
    fn tail_samples(&self) -> u32 {
        0
    }

    /// Get latency in samples
    fn latency_samples(&self) -> u32 {
        0
    }

    /// Handle state save (return serialized state)
    fn save_state(&self) -> Vec<u8> {
        Vec::new()
    }

    /// Handle state load
    fn load_state(&mut self, _data: &[u8]) -> bool {
        false
    }
}

// ============================================================================
// Web Audio Backend Interface
// ============================================================================

/// Web Audio processor configuration
#[derive(Debug, Clone)]
pub struct WebAudioConfig {
    /// Number of input channels
    pub input_channels: u32,
    /// Number of output channels
    pub output_channels: u32,
    /// Sample rate (typically 44100 or 48000 for web)
    pub sample_rate: f64,
    /// Block size (typically 128 for Web Audio)
    pub block_size: usize,
}

impl Default for WebAudioConfig {
    fn default() -> Self {
        Self {
            input_channels: 0,
            output_channels: 2,
            sample_rate: 44100.0,
            block_size: 128,
        }
    }
}

/// Trait for Web Audio compatible processors
///
/// This trait provides the interface for WebAssembly-based audio processing.
/// Implementations can be compiled to WASM and used with AudioWorkletProcessor.
pub trait WebAudioProcessor: Send {
    /// Initialize the processor with the given configuration
    fn initialize(&mut self, config: &WebAudioConfig);

    /// Process a block of audio
    ///
    /// `inputs`: Interleaved input samples (channels * block_size)
    /// `outputs`: Buffer for interleaved output samples
    /// Returns true to keep processing, false to end
    fn process(&mut self, inputs: &[f32], outputs: &mut [f32]) -> bool;

    /// Handle a parameter change
    fn set_parameter(&mut self, name: &str, value: f64);

    /// Get current parameter value
    fn get_parameter(&self, name: &str) -> Option<f64>;

    /// Get all parameter names
    fn parameter_names(&self) -> Vec<String>;

    /// Handle a message from the main thread
    fn handle_message(&mut self, _data: &[u8]) {}
}

/// Web Audio worklet adapter
///
/// Adapts a Quiver patch for use as a Web Audio worklet.
pub struct WebAudioWorklet {
    /// Configuration
    config: WebAudioConfig,
    /// Parameter map
    parameters: HashMap<String, Arc<AtomicF64>>,
    /// Active state
    active: bool,
}

impl WebAudioWorklet {
    /// Create a new worklet adapter
    pub fn new() -> Self {
        Self {
            config: WebAudioConfig::default(),
            parameters: HashMap::new(),
            active: false,
        }
    }

    /// Add a parameter
    pub fn add_parameter(&mut self, name: &str, initial: f64) -> Arc<AtomicF64> {
        let value = Arc::new(AtomicF64::new(initial));
        self.parameters.insert(name.to_string(), value.clone());
        value
    }

    /// Initialize with configuration
    pub fn initialize(&mut self, config: WebAudioConfig) {
        self.config = config;
        self.active = true;
    }

    /// Get configuration
    pub fn config(&self) -> &WebAudioConfig {
        &self.config
    }

    /// Check if active
    pub fn is_active(&self) -> bool {
        self.active
    }

    /// Get a parameter value
    pub fn get_parameter(&self, name: &str) -> Option<f64> {
        self.parameters.get(name).map(|v| v.get())
    }

    /// Set a parameter value
    pub fn set_parameter(&mut self, name: &str, value: f64) {
        if let Some(param) = self.parameters.get(name) {
            param.set(value);
        }
    }
}

impl Default for WebAudioWorklet {
    fn default() -> Self {
        Self::new()
    }
}

/// Web Audio block processor for AudioWorklet integration
///
/// This struct provides the sample-accurate processing required for
/// Web Audio's AudioWorkletProcessor. It handles the 128-sample render
/// quantum and provides efficient block processing.
///
/// # JavaScript Integration Example
///
/// ```javascript
/// // In your AudioWorkletProcessor
/// class QuiverProcessor extends AudioWorkletProcessor {
///   constructor() {
///     super();
///     this.engine = new QuiverEngine(sampleRate);
///     this.engine.load_patch(patchJson);
///     this.engine.compile();
///   }
///
///   process(inputs, outputs, parameters) {
///     const output = outputs[0];
///     const samples = this.engine.process_block(128);
///
///     // Deinterleave stereo output
///     for (let i = 0; i < 128; i++) {
///       output[0][i] = samples[i * 2];
///       output[1][i] = samples[i * 2 + 1];
///     }
///     return true;
///   }
/// }
/// ```
pub struct WebAudioBlockProcessor {
    /// Configuration
    config: WebAudioConfig,
    /// Left channel buffer
    left_buffer: Vec<f64>,
    /// Right channel buffer
    right_buffer: Vec<f64>,
    /// Interleaved output buffer (for f32)
    interleaved_buffer: Vec<f32>,
    /// Parameter map
    parameters: HashMap<String, Arc<AtomicF64>>,
    /// Active state
    active: bool,
}

impl WebAudioBlockProcessor {
    /// Create a new block processor with default Web Audio config (128 samples)
    pub fn new() -> Self {
        Self::with_config(WebAudioConfig::default())
    }

    /// Create a new block processor with custom configuration
    pub fn with_config(config: WebAudioConfig) -> Self {
        let block_size = config.block_size;
        Self {
            config,
            left_buffer: vec![0.0; block_size],
            right_buffer: vec![0.0; block_size],
            interleaved_buffer: vec![0.0; block_size * 2],
            parameters: HashMap::new(),
            active: false,
        }
    }

    /// Add a parameter
    pub fn add_parameter(&mut self, name: &str, initial: f64) -> Arc<AtomicF64> {
        let value = Arc::new(AtomicF64::new(initial));
        self.parameters.insert(name.to_string(), value.clone());
        value
    }

    /// Initialize/activate the processor
    pub fn activate(&mut self) {
        self.active = true;
    }

    /// Deactivate the processor
    pub fn deactivate(&mut self) {
        self.active = false;
    }

    /// Check if active
    pub fn is_active(&self) -> bool {
        self.active
    }

    /// Get configuration
    pub fn config(&self) -> &WebAudioConfig {
        &self.config
    }

    /// Get the block size
    pub fn block_size(&self) -> usize {
        self.config.block_size
    }

    /// Get the sample rate
    pub fn sample_rate(&self) -> f64 {
        self.config.sample_rate
    }

    /// Get a parameter value
    pub fn get_parameter(&self, name: &str) -> Option<f64> {
        self.parameters.get(name).map(|v| v.get())
    }

    /// Set a parameter value
    pub fn set_parameter(&mut self, name: &str, value: f64) {
        if let Some(param) = self.parameters.get(name) {
            param.set(value);
        }
    }

    /// Get all parameter names
    pub fn parameter_names(&self) -> Vec<String> {
        self.parameters.keys().cloned().collect()
    }

    /// Process a block using a closure that generates samples
    ///
    /// The closure receives the sample index and should return (left, right).
    /// Returns a reference to the interleaved output buffer.
    pub fn process_with<F>(&mut self, mut generator: F) -> &[f32]
    where
        F: FnMut(usize) -> (f64, f64),
    {
        for i in 0..self.config.block_size {
            let (left, right) = generator(i);
            self.left_buffer[i] = left;
            self.right_buffer[i] = right;
        }

        interleave_stereo(
            &self.left_buffer,
            &self.right_buffer,
            &mut self.interleaved_buffer,
        );

        &self.interleaved_buffer
    }

    /// Get the left channel buffer (for direct writing)
    pub fn left_buffer_mut(&mut self) -> &mut [f64] {
        &mut self.left_buffer
    }

    /// Get the right channel buffer (for direct writing)
    pub fn right_buffer_mut(&mut self) -> &mut [f64] {
        &mut self.right_buffer
    }

    /// Finalize and get interleaved output after writing to channel buffers
    pub fn finalize(&mut self) -> &[f32] {
        interleave_stereo(
            &self.left_buffer,
            &self.right_buffer,
            &mut self.interleaved_buffer,
        );
        &self.interleaved_buffer
    }

    /// Clear all buffers
    pub fn clear(&mut self) {
        self.left_buffer.fill(0.0);
        self.right_buffer.fill(0.0);
        self.interleaved_buffer.fill(0.0);
    }
}

impl Default for WebAudioBlockProcessor {
    fn default() -> Self {
        Self::new()
    }
}

/// Convert f64 audio block to f32 for Web Audio
#[inline]
pub fn f64_to_f32_block(src: &[f64], dst: &mut [f32]) {
    let len = src.len().min(dst.len());
    for i in 0..len {
        dst[i] = src[i] as f32;
    }
}

/// Convert f32 audio block to f64 from Web Audio
#[inline]
pub fn f32_to_f64_block(src: &[f32], dst: &mut [f64]) {
    let len = src.len().min(dst.len());
    for i in 0..len {
        dst[i] = src[i] as f64;
    }
}

/// Interleave stereo channels for Web Audio
#[inline]
pub fn interleave_stereo(left: &[f64], right: &[f64], output: &mut [f32]) {
    let frames = left.len().min(right.len()).min(output.len() / 2);
    for i in 0..frames {
        output[i * 2] = left[i] as f32;
        output[i * 2 + 1] = right[i] as f32;
    }
}

/// Deinterleave stereo channels from Web Audio
#[inline]
pub fn deinterleave_stereo(input: &[f32], left: &mut [f64], right: &mut [f64]) {
    let frames = (input.len() / 2).min(left.len()).min(right.len());
    for i in 0..frames {
        left[i] = input[i * 2] as f64;
        right[i] = input[i * 2 + 1] as f64;
    }
}

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

    // OSC Tests
    #[test]
    fn test_osc_message() {
        let msg = OscMessage::new("/synth/filter/cutoff").with_float(0.75);
        assert_eq!(msg.address, "/synth/filter/cutoff");
        assert!((msg.first_f64().unwrap() - 0.75).abs() < 0.001);
    }

    #[test]
    fn test_osc_pattern_literal() {
        let pattern = OscPattern::new("/synth/osc/pitch");
        assert!(pattern.matches("/synth/osc/pitch"));
        assert!(!pattern.matches("/synth/osc/volume"));
        assert!(!pattern.matches("/synth/osc"));
    }

    #[test]
    fn test_osc_pattern_wildcard() {
        let pattern = OscPattern::new("/synth/*");
        // `*` matches within a single component...
        assert!(pattern.matches("/synth/osc"));
        assert!(pattern.matches("/synth/filter"));
        // ...but never crosses a component boundary (OSC has no cross-component `*`).
        assert!(!pattern.matches("/synth/filter/cutoff"));
        assert!(!pattern.matches("/synth"));
    }

    #[test]
    fn test_osc_pattern_wildcard_partial_component() {
        let pattern = OscPattern::new("/synth/osc*");
        assert!(pattern.matches("/synth/osc"));
        assert!(pattern.matches("/synth/osc1"));
        assert!(pattern.matches("/synth/oscillator"));
        assert!(!pattern.matches("/synth/lfo"));

        let mid = OscPattern::new("/a/f*r");
        assert!(mid.matches("/a/filter"));
        assert!(mid.matches("/a/fr"));
        assert!(!mid.matches("/a/filik"));
    }

    #[test]
    fn test_osc_pattern_char_class_range() {
        let pattern = OscPattern::new("/ch[0-9]");
        assert!(pattern.matches("/ch0"));
        assert!(pattern.matches("/ch7"));
        assert!(!pattern.matches("/chx"));
        // A range char is not a literal set of {0, -, 9}.
        assert!(!pattern.matches("/ch-"));

        let alpha = OscPattern::new("/[a-c]");
        assert!(alpha.matches("/a"));
        assert!(alpha.matches("/c"));
        assert!(!alpha.matches("/d"));
    }

    #[test]
    fn test_osc_pattern_char_class_negation() {
        let pattern = OscPattern::new("/ch[!0-9]");
        assert!(pattern.matches("/chx"));
        assert!(!pattern.matches("/ch5"));

        let neg = OscPattern::new("/[!abc]");
        assert!(neg.matches("/d"));
        assert!(!neg.matches("/a"));
    }

    #[test]
    fn test_osc_pattern_alternation() {
        let pattern = OscPattern::new("/synth/{osc,lfo}");
        assert!(pattern.matches("/synth/osc"));
        assert!(pattern.matches("/synth/lfo"));
        assert!(!pattern.matches("/synth/vcf"));

        // Alternation combined with surrounding literals.
        let mixed = OscPattern::new("/v{1,2}/gain");
        assert!(mixed.matches("/v1/gain"));
        assert!(mixed.matches("/v2/gain"));
        assert!(!mixed.matches("/v3/gain"));
    }

    #[test]
    fn test_osc_pattern_malformed_fails() {
        // Unterminated class must fail to match, not swallow the rest.
        let unterminated_class = OscPattern::new("/ch[0-9");
        assert!(!unterminated_class.matches("/ch5"));
        assert!(!unterminated_class.matches("/ch"));

        // Unterminated alternation must fail to match.
        let unterminated_alt = OscPattern::new("/synth/{osc,lfo");
        assert!(!unterminated_alt.matches("/synth/osc"));

        // Empty class is malformed.
        let empty_class = OscPattern::new("/ch[]");
        assert!(!empty_class.matches("/ch"));
    }

    #[test]
    fn test_osc_binding() {
        let value = Arc::new(AtomicF64::new(0.0));
        let binding = OscBinding::new("/test/param", value.clone()).with_scale(10.0);

        let msg = OscMessage::new("/test/param").with_float(0.5);
        assert!(binding.apply(&msg));
        assert!((value.get() - 5.0).abs() < 0.001);
    }

    #[test]
    fn test_osc_receiver() {
        let mut receiver = OscReceiver::new();
        let value = Arc::new(AtomicF64::new(0.0));
        receiver.bind("/synth/volume", value.clone());

        let msg = OscMessage::new("/synth/volume").with_float(0.8);
        assert!(receiver.handle_message(&msg));
        assert!((value.get() - 0.8).abs() < 0.001);

        let msg2 = OscMessage::new("/synth/pitch").with_float(0.5);
        assert!(!receiver.handle_message(&msg2));
    }

    // Plugin Wrapper Tests
    #[test]
    fn test_plugin_parameter() {
        let param = PluginParameter::new(0, "Cutoff", 20.0, 20000.0, 1000.0).with_unit("Hz");

        assert!((param.normalize(20.0) - 0.0).abs() < 0.001);
        assert!((param.normalize(20000.0) - 1.0).abs() < 0.001);
        assert!((param.denormalize(0.5) - 10010.0).abs() < 1.0);
    }

    #[test]
    fn test_plugin_parameter_quantize() {
        let param = PluginParameter::new(0, "Steps", 0.0, 10.0, 5.0).with_steps(10);

        // With 10 steps over 0-10 range, step size is 1.0
        // 0.5 rounds to 0.0 or 1.0
        assert!((param.quantize(0.4) - 0.0).abs() < 0.1);
        assert!((param.quantize(0.6) - 1.0).abs() < 0.1);
        assert!((param.quantize(4.7) - 5.0).abs() < 0.1);
        assert!((param.quantize(9.9) - 10.0).abs() < 0.1);
    }

    #[test]
    fn test_plugin_wrapper() {
        let info = PluginInfo::synth("com.quiver.test", "Test Synth", "Quiver");
        let bus = AudioBusConfig::stereo_out();

        let mut wrapper = PluginWrapper::new(info, bus);
        let cutoff =
            wrapper.add_parameter(PluginParameter::new(0, "Cutoff", 20.0, 20000.0, 1000.0));

        assert_eq!(wrapper.parameter_count(), 1);
        assert!((wrapper.get_parameter(0).unwrap() - 1000.0).abs() < 0.001);

        wrapper.set_parameter_normalized(0, 0.5);
        assert!((cutoff.get() - 10010.0).abs() < 1.0);
    }

    // Web Audio Tests
    #[test]
    fn test_web_audio_config() {
        let config = WebAudioConfig::default();
        assert_eq!(config.output_channels, 2);
        assert_eq!(config.block_size, 128);
    }

    #[test]
    fn test_web_audio_worklet() {
        let mut worklet = WebAudioWorklet::new();
        let freq = worklet.add_parameter("frequency", 440.0);

        assert!((worklet.get_parameter("frequency").unwrap() - 440.0).abs() < 0.001);

        worklet.set_parameter("frequency", 880.0);
        assert!((freq.get() - 880.0).abs() < 0.001);
    }

    #[test]
    fn test_interleave_stereo() {
        let left = vec![1.0, 2.0, 3.0];
        let right = vec![4.0, 5.0, 6.0];
        let mut output = vec![0.0f32; 6];

        interleave_stereo(&left, &right, &mut output);

        assert!((output[0] - 1.0).abs() < 0.001);
        assert!((output[1] - 4.0).abs() < 0.001);
        assert!((output[2] - 2.0).abs() < 0.001);
        assert!((output[3] - 5.0).abs() < 0.001);
    }

    #[test]
    fn test_deinterleave_stereo() {
        let input = vec![1.0f32, 4.0, 2.0, 5.0, 3.0, 6.0];
        let mut left = vec![0.0; 3];
        let mut right = vec![0.0; 3];

        deinterleave_stereo(&input, &mut left, &mut right);

        assert!((left[0] - 1.0).abs() < 0.001);
        assert!((left[1] - 2.0).abs() < 0.001);
        assert!((left[2] - 3.0).abs() < 0.001);
        assert!((right[0] - 4.0).abs() < 0.001);
        assert!((right[1] - 5.0).abs() < 0.001);
        assert!((right[2] - 6.0).abs() < 0.001);
    }

    #[test]
    fn test_osc_value_to_f64() {
        assert!((OscValue::Int(42).to_f64().unwrap() - 42.0).abs() < 0.001);
        assert!((OscValue::Float(2.5).to_f64().unwrap() - 2.5).abs() < 0.01);
        assert!((OscValue::Long(100).to_f64().unwrap() - 100.0).abs() < 0.001);
        assert!((OscValue::Double(2.71).to_f64().unwrap() - 2.71).abs() < 0.001);
        assert!((OscValue::True.to_f64().unwrap() - 1.0).abs() < 0.001);
        assert!((OscValue::False.to_f64().unwrap() - 0.0).abs() < 0.001);
        assert!(OscValue::Nil.to_f64().is_none());
    }

    #[test]
    fn test_osc_value_to_bool() {
        assert_eq!(OscValue::Int(1).to_bool(), Some(true));
        assert_eq!(OscValue::Int(0).to_bool(), Some(false));
        assert_eq!(OscValue::Float(1.0).to_bool(), Some(true));
        assert_eq!(OscValue::Float(0.0).to_bool(), Some(false));
        assert_eq!(OscValue::True.to_bool(), Some(true));
        assert_eq!(OscValue::False.to_bool(), Some(false));
        assert_eq!(OscValue::Nil.to_bool(), None);
    }

    #[test]
    fn test_osc_message_with_int() {
        let msg = OscMessage::new("/test").with_int(42);
        assert_eq!(msg.args.len(), 1);
    }

    #[test]
    fn test_osc_pattern_single_char() {
        let pattern = OscPattern::new("/a/?");
        assert!(pattern.matches("/a/b"));
        assert!(!pattern.matches("/a/bb"));
    }

    #[test]
    fn test_osc_pattern_char_class() {
        let pattern = OscPattern::new("/[abc]");
        assert!(pattern.matches("/a"));
        assert!(pattern.matches("/b"));
        assert!(!pattern.matches("/d"));
    }

    #[test]
    fn test_osc_binding_with_offset() {
        let value = Arc::new(AtomicF64::new(0.0));
        let binding = OscBinding::new("/test", value.clone())
            .with_scale(2.0)
            .with_offset(10.0);

        let msg = OscMessage::new("/test").with_float(5.0);
        binding.apply(&msg);
        assert!((value.get() - 20.0).abs() < 0.001);
    }

    #[test]
    fn test_osc_binding_non_matching() {
        let value = Arc::new(AtomicF64::new(0.0));
        let binding = OscBinding::new("/test", value.clone());

        let msg = OscMessage::new("/other").with_float(5.0);
        assert!(!binding.apply(&msg));
    }

    #[test]
    fn test_osc_receiver_bind_scaled() {
        let mut receiver = OscReceiver::new();
        let value = Arc::new(AtomicF64::new(0.0));
        receiver.bind_scaled("/test", value.clone(), 10.0, 5.0);

        let msg = OscMessage::new("/test").with_float(1.0);
        receiver.handle_message(&msg);
        assert!((value.get() - 15.0).abs() < 0.001);
    }

    #[test]
    fn test_osc_receiver_counters() {
        let mut receiver = OscReceiver::new();
        let value = Arc::new(AtomicF64::new(0.0));
        receiver.bind("/test", value.clone());

        let msg = OscMessage::new("/test").with_float(1.0);
        receiver.handle_message(&msg);

        assert_eq!(receiver.message_count(), 1);
        assert_eq!(receiver.matched_count(), 1);
        assert_eq!(receiver.binding_count(), 1);

        receiver.reset_counters();
        assert_eq!(receiver.message_count(), 0);
    }

    #[test]
    fn test_osc_receiver_default() {
        let receiver = OscReceiver::default();
        assert_eq!(receiver.binding_count(), 0);
    }

    #[test]
    fn test_osc_input_module() {
        let value = Arc::new(AtomicF64::new(5.0));
        let mut input = OscInput::new("/test/param", value.clone(), SignalKind::CvUnipolar);

        assert_eq!(input.address(), "/test/param");
        assert!((input.value_ref().get() - 5.0).abs() < 0.001);

        let inputs = PortValues::new();
        let mut outputs = PortValues::new();
        input.tick(&inputs, &mut outputs);

        assert!((outputs.get(0).unwrap() - 5.0).abs() < 0.001);

        input.reset();
        input.set_sample_rate(48000.0);
        assert_eq!(input.type_id(), "osc_input");
    }

    // MIDI Tests
    #[test]
    fn test_midi_status_parsing() {
        assert_eq!(MidiStatus::from_byte(0x90), Some(MidiStatus::NoteOn(0)));
        assert_eq!(MidiStatus::from_byte(0x95), Some(MidiStatus::NoteOn(5)));
        assert_eq!(MidiStatus::from_byte(0x80), Some(MidiStatus::NoteOff(0)));
        assert_eq!(
            MidiStatus::from_byte(0xB0),
            Some(MidiStatus::ControlChange(0))
        );
        assert_eq!(MidiStatus::from_byte(0xE0), Some(MidiStatus::PitchBend(0)));
        assert_eq!(MidiStatus::from_byte(0xF0), Some(MidiStatus::System(0xF0)));
    }

    #[test]
    fn test_midi_status_channel() {
        let note_on = MidiStatus::NoteOn(5);
        assert_eq!(note_on.channel(), Some(5));

        let system = MidiStatus::System(0xF0);
        assert_eq!(system.channel(), None);
    }

    #[test]
    fn test_midi_note_on() {
        let msg = MidiMessage::note_on(0, 60, 100);
        assert!(msg.is_note_on());
        assert!(!msg.is_note_off());
        assert_eq!(msg.note(), 60);
        assert_eq!(msg.velocity(), 100);
    }

    #[test]
    fn test_midi_note_off() {
        let msg = MidiMessage::note_off(0, 60, 0);
        assert!(!msg.is_note_on());
        assert!(msg.is_note_off());
    }

    #[test]
    fn test_midi_note_on_zero_velocity() {
        // Note On with velocity 0 is treated as Note Off
        let msg = MidiMessage::note_on(0, 60, 0);
        assert!(!msg.is_note_on());
        assert!(msg.is_note_off());
    }

    #[test]
    fn test_midi_control_change() {
        let msg = MidiMessage::control_change(0, 1, 64);
        assert_eq!(msg.data1, 1); // CC number
        assert_eq!(msg.data2, 64); // Value
    }

    #[test]
    fn test_midi_pitch_bend() {
        // Center position (0)
        let msg = MidiMessage::pitch_bend(0, 0);
        let normalized = msg.pitch_bend_normalized();
        assert!(normalized.abs() < 0.001);

        // Max positive
        let msg = MidiMessage::pitch_bend(0, 8191);
        let normalized = msg.pitch_bend_normalized();
        assert!((normalized - 1.0).abs() < 0.01);

        // Max negative
        let msg = MidiMessage::pitch_bend(0, -8192);
        let normalized = msg.pitch_bend_normalized();
        assert!((normalized + 1.0).abs() < 0.01);
    }

    #[test]
    fn test_midi_note_to_frequency() {
        let msg = MidiMessage::note_on(0, 69, 100); // A4
        assert!((msg.note_to_frequency() - 440.0).abs() < 0.01);

        let msg = MidiMessage::note_on(0, 60, 100); // C4
        assert!((msg.note_to_frequency() - 261.63).abs() < 0.1);
    }

    #[test]
    fn test_midi_note_to_volt_per_octave() {
        let msg = MidiMessage::note_on(0, 60, 100); // C4 = 0V
        assert!(msg.note_to_volt_per_octave().abs() < 0.001);

        let msg = MidiMessage::note_on(0, 72, 100); // C5 = 1V
        assert!((msg.note_to_volt_per_octave() - 1.0).abs() < 0.001);
    }

    #[test]
    fn test_midi_at_sample() {
        let msg = MidiMessage::note_on(0, 60, 100).at_sample(64);
        assert_eq!(msg.sample_offset, 64);
    }

    #[test]
    fn test_midi_buffer() {
        let mut buffer = MidiBuffer::new();
        assert!(buffer.is_empty());
        assert_eq!(buffer.len(), 0);

        buffer.push(MidiMessage::note_on(0, 60, 100).at_sample(0));
        buffer.push(MidiMessage::note_on(0, 64, 100).at_sample(32));
        buffer.push(MidiMessage::note_on(0, 67, 100).at_sample(64));

        assert_eq!(buffer.len(), 3);
        assert!(!buffer.is_empty());

        // Test events_at
        let at_0: Vec<_> = buffer.events_at(0).collect();
        assert_eq!(at_0.len(), 1);
        assert_eq!(at_0[0].note(), 60);

        // Test clear
        buffer.clear();
        assert!(buffer.is_empty());
    }

    #[test]
    fn test_midi_buffer_sort() {
        let mut buffer = MidiBuffer::with_capacity(10);
        buffer.push(MidiMessage::note_on(0, 60, 100).at_sample(64));
        buffer.push(MidiMessage::note_on(0, 64, 100).at_sample(0));
        buffer.push(MidiMessage::note_on(0, 67, 100).at_sample(32));

        buffer.sort();

        let events: Vec<_> = buffer.iter().collect();
        assert_eq!(events[0].sample_offset, 0);
        assert_eq!(events[1].sample_offset, 32);
        assert_eq!(events[2].sample_offset, 64);
    }

    #[test]
    fn test_midi_buffer_default() {
        let buffer = MidiBuffer::default();
        assert!(buffer.is_empty());
    }

    // Plugin Wrapper Extended Tests
    #[test]
    fn test_plugin_wrapper_latency() {
        let info = PluginInfo::effect("com.quiver.test", "Test Effect", "Quiver");
        let bus = AudioBusConfig::stereo_io();

        let mut wrapper = PluginWrapper::new(info, bus);
        assert_eq!(wrapper.latency(), 0);

        wrapper.set_latency(256);
        assert_eq!(wrapper.latency(), 256);
    }

    #[test]
    fn test_plugin_wrapper_processing_state() {
        let info = PluginInfo::synth("com.quiver.test", "Test Synth", "Quiver");
        let bus = AudioBusConfig::stereo_out();
        let wrapper = PluginWrapper::new(info, bus);

        assert!(!wrapper.is_processing());
        wrapper.start_processing();
        assert!(wrapper.is_processing());
        wrapper.stop_processing();
        assert!(!wrapper.is_processing());
    }

    #[test]
    fn test_audio_bus_config() {
        let stereo_out = AudioBusConfig::stereo_out();
        assert_eq!(stereo_out.inputs, 0);
        assert_eq!(stereo_out.outputs, 2);

        let stereo_io = AudioBusConfig::stereo_io();
        assert_eq!(stereo_io.inputs, 2);
        assert_eq!(stereo_io.outputs, 2);

        let mono_out = AudioBusConfig::mono_out();
        assert_eq!(mono_out.inputs, 0);
        assert_eq!(mono_out.outputs, 1);
    }

    // Web Audio Block Processor Tests
    #[test]
    fn test_web_audio_block_processor_new() {
        let processor = WebAudioBlockProcessor::new();
        assert_eq!(processor.block_size(), 128);
        assert!((processor.sample_rate() - 44100.0).abs() < 0.001);
        assert!(!processor.is_active());
    }

    #[test]
    fn test_web_audio_block_processor_with_config() {
        let config = WebAudioConfig {
            input_channels: 0,
            output_channels: 2,
            sample_rate: 48000.0,
            block_size: 256,
        };
        let processor = WebAudioBlockProcessor::with_config(config);
        assert_eq!(processor.block_size(), 256);
        assert!((processor.sample_rate() - 48000.0).abs() < 0.001);
    }

    #[test]
    fn test_web_audio_block_processor_activate() {
        let mut processor = WebAudioBlockProcessor::new();
        assert!(!processor.is_active());

        processor.activate();
        assert!(processor.is_active());

        processor.deactivate();
        assert!(!processor.is_active());
    }

    #[test]
    fn test_web_audio_block_processor_parameters() {
        let mut processor = WebAudioBlockProcessor::new();
        let freq = processor.add_parameter("frequency", 440.0);

        assert!((processor.get_parameter("frequency").unwrap() - 440.0).abs() < 0.001);

        processor.set_parameter("frequency", 880.0);
        assert!((freq.get() - 880.0).abs() < 0.001);

        let names = processor.parameter_names();
        assert!(names.contains(&"frequency".to_string()));
    }

    #[test]
    fn test_web_audio_block_processor_process_with() {
        let mut processor = WebAudioBlockProcessor::new();
        let mut phase = 0.0;

        let output = processor.process_with(|_i| {
            let sample = (phase * std::f64::consts::TAU).sin();
            phase += 440.0 / 44100.0;
            (sample, sample)
        });

        // Output is interleaved stereo, 128 * 2 = 256 samples
        assert_eq!(output.len(), 256);

        // First sample should be close to 0 (sin(0))
        assert!(output[0].abs() < 0.1);
    }

    #[test]
    fn test_web_audio_block_processor_direct_buffer() {
        let mut processor = WebAudioBlockProcessor::new();

        // Write directly to left buffer
        {
            let left = processor.left_buffer_mut();
            for (i, slot) in left.iter_mut().enumerate().take(128) {
                *slot = (i as f64) / 128.0;
            }
        }

        // Write directly to right buffer
        {
            let right = processor.right_buffer_mut();
            for (i, slot) in right.iter_mut().enumerate().take(128) {
                *slot = 1.0 - (i as f64) / 128.0;
            }
        }

        let output = processor.finalize();

        // Check first sample pair
        assert!(output[0].abs() < 0.01); // left[0] = 0
        assert!((output[1] - 1.0).abs() < 0.01); // right[0] = 1

        // Check last sample pair
        assert!((output[254] - 127.0 / 128.0).abs() < 0.01);
        assert!((output[255] - 1.0 / 128.0).abs() < 0.01);
    }

    #[test]
    fn test_web_audio_block_processor_clear() {
        let mut processor = WebAudioBlockProcessor::new();

        // Fill with non-zero values
        processor.process_with(|_| (1.0, 1.0));

        // Clear
        processor.clear();

        let output = processor.finalize();
        for sample in output {
            assert!(*sample < 0.001);
        }
    }

    #[test]
    fn test_web_audio_block_processor_default() {
        let processor = WebAudioBlockProcessor::default();
        assert_eq!(processor.block_size(), 128);
    }

    #[test]
    fn test_f64_to_f32_block() {
        let src = vec![0.5_f64, -0.5, 1.0, -1.0];
        let mut dst = vec![0.0_f32; 4];

        f64_to_f32_block(&src, &mut dst);

        assert!((dst[0] - 0.5).abs() < 0.001);
        assert!((dst[1] + 0.5).abs() < 0.001);
        assert!((dst[2] - 1.0).abs() < 0.001);
        assert!((dst[3] + 1.0).abs() < 0.001);
    }

    #[test]
    fn test_f32_to_f64_block() {
        let src = vec![0.5_f32, -0.5, 1.0, -1.0];
        let mut dst = vec![0.0_f64; 4];

        f32_to_f64_block(&src, &mut dst);

        assert!((dst[0] - 0.5).abs() < 0.001);
        assert!((dst[1] + 0.5).abs() < 0.001);
        assert!((dst[2] - 1.0).abs() < 0.001);
        assert!((dst[3] + 1.0).abs() < 0.001);
    }
}