bela 0.8.0

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

use core::fmt;
use core::iter;
use core::mem;
use core::ops::Range;
use core::slice;

use bela_sys::BelaContext;

/// Direction of a digital (GPIO) pin. All pins begin as inputs, which
/// is what [`PinMode::default()`](Default::default) is.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub enum PinMode {
    /// The pin reads external logic levels (the default).
    #[default]
    Input,
    /// The pin drives the value set with the `digital_write` family.
    Output,
}

// Within a digital frame word, bits 0-15 hold pin directions
// (1 = input) and bits 16-31 hold pin values.
const DIGITAL_VALUE_SHIFT: usize = 16;

/// The `thread`th of `count` contiguous parts of `len` frames.
///
/// The parts tile `0..len` exactly — each one starts where the last
/// ended, the first starts at 0 and the last ends at `len` — so the
/// threads between them cover the block once, whatever the remainder
/// of the division is. Parts can be empty, which is what more threads
/// than frames means.
///
/// A `count` of 0 is read as 1, the way [`thread_count`] does: it is
/// how a `BelaContext` can spell "one render thread".
///
/// [`thread_count`]: RenderContext::thread_count
#[inline]
pub(crate) const fn partition(len: usize, thread: usize, count: usize) -> Range<usize> {
    let count = if count == 0 { 1 } else { count };
    if thread >= count {
        // Not a share of anything; the caller is out of range.
        return len..len;
    }
    // `len` is a frame count, so neither product can overflow.
    let start = len * thread / count;
    let end = len * (thread + 1) / count;
    start..end
}

/// Generates the accessors every phase has: the audio configuration,
/// and where in the run this block is.
macro_rules! metadata_accessors {
    ($($context:ty),+ $(,)?) => {
        $(
            impl $context {
                /// Read access to the underlying `BelaContext`.
                #[must_use]
                #[inline]
                pub const fn as_sys(&self) -> &BelaContext {
                    &self.0
                }

                /// Number of audio frames per block.
                #[must_use]
                #[inline]
                pub const fn audio_frames(&self) -> usize {
                    self.0.audioFrames as usize
                }

                /// Number of audio input channels.
                #[must_use]
                #[inline]
                pub const fn audio_in_channels(&self) -> usize {
                    self.0.audioInChannels as usize
                }

                /// Number of audio output channels.
                ///
                /// On a Bela Gem Stereo this is 2, and the analog
                /// outputs are not among them — the board has none.
                /// See [`BlockContext`], which carries what was
                /// measured for all four context types.
                #[must_use]
                #[inline]
                pub const fn audio_out_channels(&self) -> usize {
                    self.0.audioOutChannels as usize
                }

                /// Audio sample rate in Hz.
                #[must_use]
                #[inline]
                pub const fn audio_sample_rate(&self) -> f32 {
                    self.0.audioSampleRate
                }

                /// Number of analog frames per block; 0 if analog I/O
                /// is disabled.
                #[must_use]
                #[inline]
                pub const fn analog_frames(&self) -> usize {
                    self.0.analogFrames as usize
                }

                /// Number of analog input channels; 0 if analog I/O is
                /// disabled.
                #[must_use]
                #[inline]
                pub const fn analog_in_channels(&self) -> usize {
                    self.0.analogInChannels as usize
                }

                /// Number of analog output channels; 0 if analog I/O is
                /// disabled.
                #[must_use]
                #[inline]
                pub const fn analog_out_channels(&self) -> usize {
                    self.0.analogOutChannels as usize
                }

                /// Analog sample rate in Hz; 0 if analog I/O is
                /// disabled.
                #[must_use]
                #[inline]
                pub const fn analog_sample_rate(&self) -> f32 {
                    self.0.analogSampleRate
                }

                /// Number of digital frames per block; 0 if digital I/O
                /// is disabled.
                #[must_use]
                #[inline]
                pub const fn digital_frames(&self) -> usize {
                    self.0.digitalFrames as usize
                }

                /// Number of digital (GPIO) channels; 0 if digital I/O
                /// is disabled.
                #[must_use]
                #[inline]
                pub const fn digital_channels(&self) -> usize {
                    self.0.digitalChannels as usize
                }

                /// Digital sample rate in Hz.
                #[must_use]
                #[inline]
                pub const fn digital_sample_rate(&self) -> f32 {
                    self.0.digitalSampleRate
                }

                /// Total audio frames elapsed as of the beginning of
                /// this block.
                #[must_use]
                #[inline]
                pub const fn audio_frames_elapsed(&self) -> u64 {
                    self.0.audioFramesElapsed
                }

                /// Number of detected underruns.
                #[must_use]
                #[inline]
                pub const fn underrun_count(&self) -> u32 {
                    self.0.underrunCount
                }

                /// Which render thread this context belongs to, in
                /// `0..thread_count()`.
                ///
                /// Always 0 outside
                /// [`render`](crate::BelaApplication::render): every
                /// other callback is made once, on the main audio
                /// thread.
                #[must_use]
                #[inline]
                pub const fn this_thread(&self) -> usize {
                    self.0.thisThread as usize
                }

                /// How many threads [`render`] is called on for each
                /// block, which is how many
                /// [`RenderState`](crate::BelaApplication::RenderState)s
                /// there are.
                ///
                /// At least 1. A `BelaContext` can spell one render
                /// thread as either 1 or 0 — libbela copies
                /// [`Settings::thread_count`](crate::Settings::thread_count)
                /// through unchanged and only creates *extra* threads
                /// above 1 — and this reports the number of threads
                /// that actually render, so both come back as 1.
                ///
                /// [`render`]: crate::BelaApplication::render
                #[must_use]
                #[inline]
                pub const fn thread_count(&self) -> usize {
                    let count = self.0.threadCount as usize;
                    if count == 0 { 1 } else { count }
                }
            }
        )+
    };
}

/// Generates the `Debug` every phase has, followed by whatever a
/// phase adds of its own — written after the type in brackets, as
/// accessor names to call.
///
/// The shared part is the metadata accessors and nothing else. The
/// buffers are deliberately absent: a block is thousands of samples,
/// and printing them from a callback would be a real-time hazard
/// dressed as a debug line. `BelaContext` has a `Debug` of its own,
/// which prints the C field names and the buffer pointers rather than
/// this; `as_sys` is the way to it.
macro_rules! metadata_debug {
    ($($context:ident $([$($extra:ident),+ $(,)?])?),+ $(,)?) => {
        $(
            impl fmt::Debug for $context {
                fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                    f.debug_struct(stringify!($context))
                        .field("audio_frames", &self.audio_frames())
                        .field("audio_in_channels", &self.audio_in_channels())
                        .field("audio_out_channels", &self.audio_out_channels())
                        .field("audio_sample_rate", &self.audio_sample_rate())
                        .field("analog_frames", &self.analog_frames())
                        .field("analog_in_channels", &self.analog_in_channels())
                        .field("analog_out_channels", &self.analog_out_channels())
                        .field("analog_sample_rate", &self.analog_sample_rate())
                        .field("digital_frames", &self.digital_frames())
                        .field("digital_channels", &self.digital_channels())
                        .field("digital_sample_rate", &self.digital_sample_rate())
                        .field("audio_frames_elapsed", &self.audio_frames_elapsed())
                        .field("underrun_count", &self.underrun_count())
                        .field("this_thread", &self.this_thread())
                        .field("thread_count", &self.thread_count())
                        $($(.field(stringify!($extra), &self.$extra()))+)?
                        .finish_non_exhaustive()
                }
            }
        )+
    };
}

/// What [`setup`](crate::BelaApplication::setup) and
/// [`create_render_state`](crate::BelaApplication::create_render_state)
/// see: the audio configuration, before any audio has been rendered.
///
/// The buffers are not part of it. `setup` runs inside
/// `Bela_initAudio`, before the audio thread exists, so there is no
/// block to read or write — and reading the sample rate, the block size
/// and the channel counts is what a `setup` is for.
///
/// [`cpu_usage`](SetupContext::cpu_usage) is here too, so that a
/// program can find out in `setup` whether
/// [`Settings::cpu_monitoring`](crate::Settings::cpu_monitoring)
/// reached the hardware.
#[repr(transparent)]
pub struct SetupContext(BelaContext);

/// What [`cleanup`](crate::BelaApplication::cleanup) sees: the same
/// audio configuration [`SetupContext`] described, after the audio
/// thread has been joined.
///
/// No buffers, for the same reason: there is no block in flight. The
/// counters that describe the run as a whole —
/// [`audio_frames_elapsed`](CleanupContext::audio_frames_elapsed),
/// [`underrun_count`](CleanupContext::underrun_count) and
/// [`cpu_usage`](CleanupContext::cpu_usage) — are, which is what makes
/// `cleanup` the place for a closing report.
#[repr(transparent)]
pub struct CleanupContext(BelaContext);

/// What [`render_pre`](crate::BelaApplication::render_pre) and
/// [`render_post`](crate::BelaApplication::render_post) see: the whole
/// block, with nothing else running.
///
/// These two hooks bracket the parallel section — libbela calls
/// `render_pre` before it wakes the render threads and `render_post`
/// after the last of them has finished — so they are the one place a
/// multithreaded application may touch the whole block: preparing the
/// per-thread state and the buffers on the way in, mixing down what
/// the threads produced on the way out.
///
/// The accessors mirror the C helpers from `Bela.h` / `Utilities.h`
/// and assume the default interleaved buffer layout: sample index =
/// `frame * channels + channel`.
///
/// # Bela Gem semantics
///
/// On a Bela Gem Stereo there is nothing to write an analog output
/// with: [`analog_out_channels`](BlockContext::analog_out_channels) is
/// 0 for every channel count the board accepts — 8, 4 and 2 were
/// measured, and a count that differs between the inputs and the
/// outputs is refused before any context exists — and
/// [`audio_out_channels`](BlockContext::audio_out_channels) is 2, so
/// the analog outputs are not folded in there either. So
/// [`analog_write`](BlockContext::analog_write) has no channel it can
/// take on that board, while
/// [`analog_read`](BlockContext::analog_read) has as many as the
/// settings asked for, eight by default. Bela's migration guide
/// describes writing an analog output as
/// [`audio_write`](BlockContext::audio_write) with the channel offset
/// by +2; that is a Gem Multi, which has the outputs, and it has not
/// been measured here.
///
/// [`uniform_sample_rate`](crate::Settings::uniform_sample_rate) is on
/// by default, so analog frames == audio frames unless it is turned
/// off. Output values do not persist across blocks; the within-block
/// persistence of [`analog_write`](BlockContext::analog_write) and
/// [`digital_write`](BlockContext::digital_write) (writing from `frame`
/// to the end of the block) is unchanged.
///
/// On a Bela Gem Stereo, a period of 256 frames or more moves the
/// application callback behind libbela's context FIFO. A digital output
/// configured once and written only when its value changes then stops
/// reaching the pin, whether the period came from
/// [`period_size`](crate::Settings::period_size) or the command line.
/// Re-applying its direction and current value in every application
/// block restores the output loopback, but input sampling has not been
/// tested independently. See [#89](https://github.com/akiomik/bela-rs/issues/89).
///
/// Measured on the board; see `docs/board-facts.md`.
///
/// # Panics
///
/// The indexed accessors panic when `frame` or `channel` is out of
/// range (the C equivalents would read or write out of bounds). On the
/// device a panic aborts the whole process, so treat these as
/// programming errors, not recoverable conditions.
#[repr(transparent)]
pub struct BlockContext(BelaContext);

/// What [`render`](crate::BelaApplication::render) sees: the whole
/// block to read, this thread's share of it to write.
///
/// Bela calls `render` on every render thread at once, for the same
/// block, over the same buffers, and partitions nothing itself. This
/// type is where the partitioning happens: the reading accessors cover
/// the block, because inputs are shared and nobody writes them, while
/// every writing accessor is confined to
/// [`audio_frame_range`](RenderContext::audio_frame_range) and its
/// analog and digital counterparts — contiguous ranges of frames that
/// tile the block exactly across the threads.
///
/// With one render thread the range is the whole block and this
/// behaves like [`BlockContext`] minus the whole-buffer writes.
///
/// # Writing a loop
///
/// The indexed writers work the partition out on every call, since
/// that is what bounds the frame they were given. A loop over frames
/// is cheaper through the slice accessors —
/// [`audio_out`](RenderContext::audio_out) and its siblings — which
/// work it out once:
///
/// ```
/// # use bela::RenderContext;
/// # fn fill(context: &mut RenderContext, value: f32) {
/// let channels = context.audio_out_channels();
/// for samples in context.audio_out().chunks_mut(channels) {
///     samples.fill(value);
/// }
/// # }
/// ```
///
/// # What is not here
///
/// - `as_sys_mut`: the raw context is the way back to the whole output
///   buffer, which is exactly what must not be reachable from several
///   threads at once.
/// - `cpu_usage`: libbela's counters are written by the main audio
///   thread without synchronisation, and a secondary render thread
///   reading them would be a data race. Read it in
///   [`render_pre`](crate::BelaApplication::render_pre) or
///   [`render_post`](crate::BelaApplication::render_post), which run on
///   that thread, and hand the number on.
///
/// # Work that does not divide by frame
///
/// Contiguous frames are the partition this type can hand out safely,
/// and a filter or an oscillator does not survive being cut into
/// pieces that different threads carry across blocks. Keep such state
/// in [`RenderState`](crate::BelaApplication::RenderState), one per
/// thread, and use `render_pre` to line the pieces up before the block
/// and `render_post` to mix them afterwards; `examples/sine.rs` does
/// exactly that with a phase.
///
/// # Bela Gem semantics
///
/// The same as [`BlockContext`]'s, which is where they are written
/// down: what a board reports is a property of the board, not of which
/// callback is asking. On a Gem Stereo that means the analog outputs
/// are absent here too, so
/// [`analog_write`](RenderContext::analog_write) has no channel it can
/// take.
///
/// # Panics
///
/// Reading accessors panic when `frame` or `channel` is out of range,
/// like [`BlockContext`]'s. Writing accessors also panic when `frame`
/// is outside this thread's range, since writing there would race
/// whichever thread owns it.
#[repr(transparent)]
pub struct RenderContext(BelaContext);

metadata_accessors!(SetupContext, CleanupContext, BlockContext, RenderContext);

// Only `RenderContext` has anything to add: the three ranges are what
// separates its view of a block from `BlockContext`'s, so they are the
// first thing worth knowing when a `{:?}` is printed from a `render`
// that is not writing where it expected to.
metadata_debug!(
    SetupContext,
    CleanupContext,
    BlockContext,
    RenderContext[audio_frame_range, analog_frame_range, digital_frame_range],
);

/// Generates the `from_mut_ptr` constructor each context needs, since
/// the safety contract is the same for all of them.
macro_rules! from_mut_ptr {
    ($($context:ident: $phase:literal),+ $(,)?) => {
        $(
            impl $context {
                #[doc = concat!(
                    "Reborrows a raw `BelaContext` pointer as a [`",
                    stringify!($context),
                    "`].\n\n# Safety\n\n`ptr` must be non-null, properly aligned, and point to a \
                     live `BelaContext` that is not accessed through any other reference for the \
                     duration of `'a`. The buffer pointers inside must be either null or valid \
                     for the lengths implied by the frame and channel counts, and for each \
                     domain — audio, analog — the input buffer must not overlap the output \
                     buffer: [`PairedIo`] borrows both from one call and relies on that \
                     separation. Every context libbela hands to a callback satisfies it — \
                     `BelaContextManager` (`/root/Bela/core/BelaContextManager.cpp`) allocates \
                     `audioInV`/`audioOutV` and `analogInV`/`analogOutV` as independent \
                     `std::vector<float>`s and stores each one's own `.data()` pointer in the \
                     context — but it is a constraint on what `ptr` may point to that this crate \
                     cannot check, so it is one a context built by hand or by a test fixture must \
                     keep too.\n\nThe result \
                     stands in for the context of the ", $phase, " callback, and some accessors \
                     take it as proof of being in one — see the type documentation for what they \
                     rely on. A context conjured up elsewhere is not that proof."
                )]
                pub const unsafe fn from_mut_ptr<'a>(ptr: *mut BelaContext) -> &'a mut Self {
                    // repr(transparent) makes the cast sound.
                    unsafe { &mut *ptr.cast::<Self>() }
                }
            }
        )+
    };
}

from_mut_ptr!(
    SetupContext: "setup",
    CleanupContext: "cleanup",
    BlockContext: "render_pre / render_post",
    RenderContext: "render",
);

/// A single borrow over one domain's whole-block input and this view's
/// output range.
///
/// Audio comes from [`audio_io`](BlockContext::audio_io) /
/// [`RenderContext::audio_io`], analog from
/// [`analog_io`](BlockContext::analog_io) /
/// [`RenderContext::analog_io`].
///
/// [`input`](PairedIo::input) always covers the whole block, the same
/// as `audio_in()`. [`output`](PairedIo::output) and
/// [`frames`](PairedIo::frames) are confined to
/// [`output_range`](PairedIo::output_range) instead: the whole block
/// from a [`BlockContext`], this thread's share from a
/// [`RenderContext`] — the same range `audio_frame_range()` and its
/// analog counterpart already describe there. That asymmetry is
/// [`RenderContext`]'s, not this type's; on a [`BlockContext`] input and
/// output cover the same frames.
///
/// There is no `digital_io`. `BelaContext::digital` is one combined
/// input/output word buffer — the pin directions and values share it —
/// so a paired view over it would be two aliasing references to the
/// same memory, which is exactly what this type exists to avoid handing
/// out. [`BlockContext::digital`] / [`BlockContext::digital_mut`] (and
/// their `RenderContext` counterparts) already reach that buffer.
pub struct PairedIo<'a> {
    input: &'a [f32],
    in_channels: usize,
    output: &'a mut [f32],
    out_channels: usize,
    output_range: Range<usize>,
}

// A manual impl, not `#[derive(Debug)]`, for the same reason
// `metadata_debug!` leaves the buffers out: a block is thousands of
// samples, and printing them from a callback would be a real-time
// hazard dressed as a debug line.
impl fmt::Debug for PairedIo<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PairedIo")
            .field("in_channels", &self.in_channels)
            .field("out_channels", &self.out_channels)
            .field("output_range", &self.output_range)
            .finish_non_exhaustive()
    }
}

impl<'a> PairedIo<'a> {
    const fn new(
        input: &'a [f32],
        in_channels: usize,
        output: &'a mut [f32],
        out_channels: usize,
        output_range: Range<usize>,
    ) -> Self {
        Self {
            input,
            in_channels,
            output,
            out_channels,
            output_range,
        }
    }

    /// The whole block's input samples, interleaved. Length is
    /// `frames * in_channels()`, where `frames` is whichever of
    /// `audio_frames()` / `analog_frames()` matches this view's domain.
    #[must_use]
    #[inline]
    pub const fn input(&self) -> &[f32] {
        self.input
    }

    /// Number of input channels; see [`input`](PairedIo::input) for the
    /// layout it multiplies into.
    #[must_use]
    #[inline]
    pub const fn in_channels(&self) -> usize {
        self.in_channels
    }

    /// This view's output samples, interleaved — the frames of
    /// [`output_range`](PairedIo::output_range), so index 0 is channel
    /// 0 of `output_range().start`, not of block frame 0.
    #[inline]
    pub const fn output(&mut self) -> &mut [f32] {
        self.output
    }

    /// Number of output channels; see [`output`](PairedIo::output) for
    /// the layout it multiplies into.
    #[must_use]
    #[inline]
    pub const fn out_channels(&self) -> usize {
        self.out_channels
    }

    /// The block frames [`output`](PairedIo::output) and
    /// [`frames`](PairedIo::frames) cover.
    #[must_use]
    #[inline]
    pub const fn output_range(&self) -> Range<usize> {
        self.output_range.start..self.output_range.end
    }

    /// Reads and writes one frame at a time: for each frame in
    /// [`output_range`](PairedIo::output_range), the input channels at
    /// that same block frame paired with the output channels to fill
    /// in.
    ///
    /// This is the aligned path the module documentation promises:
    /// `input()` indexes from block frame 0 and `output()` from
    /// `output_range().start`, and `frames()` walks both origins
    /// together so a caller never subtracts the offset by hand — the
    /// mistake a [`RenderContext`] view invites, since its input and
    /// output do not start at the same block frame.
    ///
    /// ```
    /// # use bela::RenderContext;
    /// # fn passthrough(context: &mut RenderContext) {
    /// let mut io = context.audio_io();
    /// for (input, output) in io.frames() {
    ///     for (sample, value) in output.iter_mut().zip(input) {
    ///         *sample = *value;
    ///     }
    /// }
    /// # }
    /// ```
    pub fn frames(&mut self) -> impl Iterator<Item = (&[f32], &mut [f32])> + '_ {
        let start = self.output_range.start;
        let len = self.output_range.end - self.output_range.start;
        let in_channels = self.in_channels;
        let out_channels = self.out_channels;
        let input = self.input;
        let mut output: &mut [f32] = self.output;
        let mut index = 0_usize;
        iter::from_fn(move || {
            if index >= len {
                return None;
            }
            let frame = start + index;
            index += 1;

            let in_frame = if in_channels == 0 {
                &[][..]
            } else {
                let offset = frame * in_channels;
                &input[offset..offset + in_channels]
            };

            // Safe equivalent of `chunks_mut`, which panics on a
            // zero-sized chunk — analog output is zero-channel on a
            // Gem Stereo, and this must not panic there.
            let out_frame: &mut [f32] = if out_channels == 0 {
                &mut [][..]
            } else {
                let (frame_slice, rest) = mem::take(&mut output).split_at_mut(out_channels);
                output = rest;
                frame_slice
            };

            Some((in_frame, out_frame))
        })
    }
}

impl BlockContext {
    /// Mutable access to the underlying `BelaContext`.
    ///
    /// # Safety
    ///
    /// The caller must not invalidate data the audio system or the
    /// safe accessors rely on, e.g. by overwriting buffer pointers,
    /// frame counts or channel counts. Writing *through* the output
    /// buffer pointers is fine.
    pub const unsafe fn as_sys_mut(&mut self) -> &mut BelaContext {
        &mut self.0
    }

    // --- Whole-buffer access (interleaved) ---

    /// Audio input samples; empty with audio disabled. Length is
    /// `audio_frames() * audio_in_channels()`.
    #[must_use]
    #[inline]
    pub const fn audio_in(&self) -> &[f32] {
        unsafe {
            shared(
                self.0.audioIn,
                self.audio_frames() * self.audio_in_channels(),
            )
        }
    }

    /// Audio output samples. Length is
    /// `audio_frames() * audio_out_channels()`.
    #[inline]
    pub const fn audio_out(&mut self) -> &mut [f32] {
        unsafe {
            exclusive(
                self.0.audioOut,
                self.audio_frames() * self.audio_out_channels(),
            )
        }
    }

    /// Analog input samples; empty if analog I/O is disabled. Length
    /// is `analog_frames() * analog_in_channels()`.
    #[must_use]
    #[inline]
    pub const fn analog_in(&self) -> &[f32] {
        unsafe {
            shared(
                self.0.analogIn,
                self.analog_frames() * self.analog_in_channels(),
            )
        }
    }

    /// Analog output samples; empty if analog I/O is disabled. Length
    /// is `analog_frames() * analog_out_channels()`.
    #[inline]
    pub const fn analog_out(&mut self) -> &mut [f32] {
        unsafe {
            exclusive(
                self.0.analogOut,
                self.analog_frames() * self.analog_out_channels(),
            )
        }
    }

    /// Digital I/O words, one per digital frame. Prefer the
    /// `digital_*` / `pin_mode*` accessors, which encapsulate the bit
    /// layout.
    #[must_use]
    #[inline]
    pub const fn digital(&self) -> &[u32] {
        unsafe { shared(self.0.digital, self.digital_frames()) }
    }

    /// Mutable access to the digital I/O words. Prefer the
    /// `digital_write*` / `pin_mode*` accessors, which encapsulate the
    /// bit layout.
    #[inline]
    pub const fn digital_mut(&mut self) -> &mut [u32] {
        unsafe { exclusive(self.0.digital, self.digital_frames()) }
    }

    // --- Paired input/output views ---

    /// A single borrow over the whole audio block: [`audio_in`] to read
    /// and [`audio_out`] to write, which cannot be held at the same
    /// time — see the module documentation. The output covers the
    /// whole block here, the same as [`audio_out`].
    ///
    /// [`audio_in`]: BlockContext::audio_in
    /// [`audio_out`]: BlockContext::audio_out
    #[inline]
    pub const fn audio_io(&mut self) -> PairedIo<'_> {
        let in_channels = self.audio_in_channels();
        let out_channels = self.audio_out_channels();
        let frames = self.audio_frames();
        let input = unsafe { shared(self.0.audioIn, frames * in_channels) };
        let output = unsafe { exclusive(self.0.audioOut, frames * out_channels) };
        PairedIo::new(input, in_channels, output, out_channels, 0..frames)
    }

    /// The analog counterpart of [`audio_io`](BlockContext::audio_io).
    #[inline]
    pub const fn analog_io(&mut self) -> PairedIo<'_> {
        let in_channels = self.analog_in_channels();
        let out_channels = self.analog_out_channels();
        let frames = self.analog_frames();
        let input = unsafe { shared(self.0.analogIn, frames * in_channels) };
        let output = unsafe { exclusive(self.0.analogOut, frames * out_channels) };
        PairedIo::new(input, in_channels, output, out_channels, 0..frames)
    }

    // --- Indexed access (mirrors the C helpers) ---

    /// Audio input sample at `frame` for `channel` (`audioRead`).
    ///
    /// # Panics
    /// If `frame` or `channel` is out of range.
    #[must_use]
    #[inline]
    pub fn audio_read(&self, frame: usize, channel: usize) -> f32 {
        let channels = self.audio_in_channels();
        assert!(channel < channels, "audio input channel out of range");
        self.audio_in()[frame * channels + channel]
    }

    /// Sets the audio output at `frame` for `channel` (`audioWrite`).
    /// Audio outputs never persist.
    ///
    /// # Panics
    /// If `frame` or `channel` is out of range.
    #[inline]
    pub fn audio_write(&mut self, frame: usize, channel: usize, value: f32) {
        let channels = self.audio_out_channels();
        assert!(channel < channels, "audio output channel out of range");
        self.audio_out()[frame * channels + channel] = value;
    }

    /// Analog input sample at `frame` for `channel` (`analogRead`).
    ///
    /// The value runs from 0.0 to 1.0 for an input of 0 V to 4.096 V —
    /// the ADC's internal reference, not the 3.3 V rail, so a pin tied
    /// to that rail reads about 0.806 rather than 1.0. Measured on a
    /// Gem Stereo; see "What an analog input reads" in
    /// `docs/board-facts.md`.
    ///
    /// # Panics
    /// If `frame` or `channel` is out of range.
    #[must_use]
    #[inline]
    pub fn analog_read(&self, frame: usize, channel: usize) -> f32 {
        let channels = self.analog_in_channels();
        assert!(channel < channels, "analog input channel out of range");
        self.analog_in()[frame * channels + channel]
    }

    /// Sets the analog output for `channel` from `frame` to the end of
    /// the block (`analogWrite`). A Bela Gem Stereo has no analog
    /// outputs, so every channel is out of range there — see the
    /// type-level documentation.
    ///
    /// # Panics
    /// If `channel` is out of range.
    pub fn analog_write(&mut self, frame: usize, channel: usize, value: f32) {
        let channels = self.analog_out_channels();
        assert!(channel < channels, "analog output channel out of range");
        let frames = self.analog_frames();
        let out = self.analog_out();
        for f in frame..frames {
            out[f * channels + channel] = value;
        }
    }

    /// Sets the analog output at `frame` only (`analogWriteOnce`).
    ///
    /// # Panics
    /// If `frame` or `channel` is out of range.
    #[inline]
    pub fn analog_write_once(&mut self, frame: usize, channel: usize, value: f32) {
        let channels = self.analog_out_channels();
        assert!(channel < channels, "analog output channel out of range");
        self.analog_out()[frame * channels + channel] = value;
    }

    /// Value of the digital `channel` at `frame` (`digitalRead`).
    ///
    /// On a channel set to [`PinMode::Output`] this reports the value
    /// last written to it rather than the state of the pin: the two
    /// share a bit, so a read after a
    /// [`digital_write`](BlockContext::digital_write) echoes the write.
    /// Confirmed on a Gem Stereo; see "What a digital pin does" in
    /// `docs/board-facts.md`.
    ///
    /// # Panics
    /// If `frame` or `channel` is out of range.
    #[must_use]
    #[inline]
    pub fn digital_read(&self, frame: usize, channel: usize) -> bool {
        let mask = digital_value_mask(self.digital_channels(), channel);
        self.digital()[frame] & mask != 0
    }

    /// Sets the digital output `channel` from `frame` to the end of
    /// the block (`digitalWrite`).
    ///
    /// On a Gem Stereo outside its context-FIFO condition, the value
    /// persists into later blocks until something writes the channel
    /// again — and past the end of the program: stopping the audio
    /// system does not return the pin to an input, so a pin left high
    /// stays high until the next audio system starts and opens every
    /// channel as an input again. Ending a program is therefore not a
    /// way of reaching a safe state on whatever the pin drives.
    ///
    /// At periods of 256 frames or more, the FIFO lets a direction and
    /// value set only once fail to reach the physical pin in a later
    /// application block. Re-apply both `pin_mode` and `digital_write`
    /// in every application block for an output that must remain driven.
    /// The output-loopback workaround, not independent input sampling,
    /// is what has been measured; see [#89](https://github.com/akiomik/bela-rs/issues/89).
    ///
    /// # Panics
    /// If `channel` is out of range.
    pub fn digital_write(&mut self, frame: usize, channel: usize, value: bool) {
        let mask = digital_value_mask(self.digital_channels(), channel);
        for word in self.digital_mut().iter_mut().skip(frame) {
            set_bits(word, mask, value);
        }
    }

    /// Sets the digital output `channel` at `frame` only
    /// (`digitalWriteOnce`).
    ///
    /// # Panics
    /// If `frame` or `channel` is out of range.
    #[inline]
    pub fn digital_write_once(&mut self, frame: usize, channel: usize, value: bool) {
        let mask = digital_value_mask(self.digital_channels(), channel);
        set_bits(&mut self.digital_mut()[frame], mask, value);
    }

    /// Sets the direction of digital `channel` from `frame` to the end
    /// of the block (`pinMode`).
    ///
    /// Outside the Gem Stereo context-FIFO condition, the direction
    /// outlives the program the way the value does — see
    /// [`digital_write`](BlockContext::digital_write) — so a channel
    /// left an output goes on driving after the audio system stops.
    /// Every channel is an input again once the next one starts. At
    /// periods of 256 frames or more, set the direction again in every
    /// application block alongside [`digital_write`](BlockContext::digital_write)
    /// for an output that must remain driven; see [#89](https://github.com/akiomik/bela-rs/issues/89).
    ///
    /// # Panics
    /// If `channel` is out of range.
    pub fn pin_mode(&mut self, frame: usize, channel: usize, mode: PinMode) {
        let mask = digital_direction_mask(self.digital_channels(), channel);
        for word in self.digital_mut().iter_mut().skip(frame) {
            set_bits(word, mask, mode == PinMode::Input);
        }
    }

    /// Sets the direction of digital `channel` at `frame` only
    /// (`pinModeOnce`).
    ///
    /// # Panics
    /// If `frame` or `channel` is out of range.
    pub fn pin_mode_once(&mut self, frame: usize, channel: usize, mode: PinMode) {
        let mask = digital_direction_mask(self.digital_channels(), channel);
        set_bits(&mut self.digital_mut()[frame], mask, mode == PinMode::Input);
    }
}

impl RenderContext {
    // --- This thread's share of the block ---

    /// The audio frames this thread is responsible for writing.
    ///
    /// Contiguous, and disjoint from what every other thread gets: the
    /// ranges tile `0..audio_frames()` exactly. Empty when there are
    /// more threads than frames.
    #[must_use]
    #[inline]
    pub const fn audio_frame_range(&self) -> Range<usize> {
        partition(self.audio_frames(), self.this_thread(), self.thread_count())
    }

    /// The analog frames this thread is responsible for writing.
    ///
    /// Split the same way as
    /// [`audio_frame_range`](RenderContext::audio_frame_range), so the
    /// two cover the same stretch of the block even when the analog
    /// frame count differs from the audio one.
    #[must_use]
    #[inline]
    pub const fn analog_frame_range(&self) -> Range<usize> {
        partition(
            self.analog_frames(),
            self.this_thread(),
            self.thread_count(),
        )
    }

    /// The digital frames this thread is responsible for writing.
    ///
    /// Split like [`audio_frame_range`](RenderContext::audio_frame_range).
    #[must_use]
    #[inline]
    pub const fn digital_frame_range(&self) -> Range<usize> {
        partition(
            self.digital_frames(),
            self.this_thread(),
            self.thread_count(),
        )
    }

    // --- Whole-block reads (interleaved) ---

    /// Audio input samples for the whole block; empty with audio
    /// disabled. Length is `audio_frames() * audio_in_channels()`.
    ///
    /// The whole block, not this thread's share: inputs are read-only
    /// and shared, and a filter needs to look back past the start of
    /// its own range.
    #[must_use]
    pub const fn audio_in(&self) -> &[f32] {
        unsafe {
            shared(
                self.0.audioIn,
                self.audio_frames() * self.audio_in_channels(),
            )
        }
    }

    /// Analog input samples for the whole block; empty if analog I/O
    /// is disabled. Length is `analog_frames() * analog_in_channels()`.
    #[must_use]
    pub const fn analog_in(&self) -> &[f32] {
        unsafe {
            shared(
                self.0.analogIn,
                self.analog_frames() * self.analog_in_channels(),
            )
        }
    }

    /// This thread's digital I/O words, one per digital frame in
    /// [`digital_frame_range`](RenderContext::digital_frame_range).
    ///
    /// This thread's share, unlike the audio and analog inputs: the
    /// digital words are the outputs too, so a word outside this range
    /// is one another thread may be writing at this very moment. Read
    /// the whole block's digital state in
    /// [`render_pre`](crate::BelaApplication::render_pre) instead,
    /// where nothing else is running.
    #[must_use]
    #[inline]
    pub const fn digital(&self) -> &[u32] {
        let range = self.digital_frame_range();
        // Safety: the buffer is valid for `digital_frames()` words, and
        // the range is within that; the guard in the runtime is what
        // makes it this thread's alone.
        unsafe { share(self.0.digital, self.digital_frames(), 1, range) }
    }

    // --- This thread's share of the outputs ---

    /// This thread's audio output samples, interleaved.
    ///
    /// The samples of the frames in
    /// [`audio_frame_range`](RenderContext::audio_frame_range), so
    /// index 0 is channel 0 of frame `audio_frame_range().start`, not
    /// of frame 0. [`audio_write`](RenderContext::audio_write) indexes
    /// by block frame instead, if that is easier to keep straight.
    ///
    /// This is the accessor to reach for in a loop over frames: it
    /// works the partition out once, where the indexed writers work it
    /// out on every call.
    #[inline]
    pub const fn audio_out(&mut self) -> &mut [f32] {
        let range = self.audio_frame_range();
        self.audio_share(range)
    }

    /// This thread's analog output samples, interleaved.
    ///
    /// The samples of the frames in
    /// [`analog_frame_range`](RenderContext::analog_frame_range); see
    /// [`audio_out`](RenderContext::audio_out) for what index 0 means
    /// and for why a loop should hold on to the slice.
    #[inline]
    pub const fn analog_out(&mut self) -> &mut [f32] {
        let range = self.analog_frame_range();
        self.analog_share(range)
    }

    /// This thread's digital I/O words, one per digital frame in
    /// [`digital_frame_range`](RenderContext::digital_frame_range).
    #[inline]
    pub const fn digital_mut(&mut self) -> &mut [u32] {
        let range = self.digital_frame_range();
        self.digital_share(range)
    }

    // --- Paired input/output views ---

    /// A single borrow over the audio domain: the whole block's input
    /// to read and this thread's [`audio_frame_range`] to write, which
    /// cannot be held at the same time through `audio_in()` and
    /// [`audio_out`](RenderContext::audio_out) — see the module
    /// documentation.
    ///
    /// [`audio_frame_range`]: RenderContext::audio_frame_range
    #[inline]
    pub const fn audio_io(&mut self) -> PairedIo<'_> {
        let in_channels = self.audio_in_channels();
        let out_channels = self.audio_out_channels();
        let frames = self.audio_frames();
        let range = self.audio_frame_range();
        let input = unsafe { shared(self.0.audioIn, frames * in_channels) };
        let output = self.audio_share(range.start..range.end);
        PairedIo::new(input, in_channels, output, out_channels, range)
    }

    /// The analog counterpart of
    /// [`audio_io`](RenderContext::audio_io), over
    /// [`analog_frame_range`](RenderContext::analog_frame_range).
    #[inline]
    pub const fn analog_io(&mut self) -> PairedIo<'_> {
        let in_channels = self.analog_in_channels();
        let out_channels = self.analog_out_channels();
        let frames = self.analog_frames();
        let range = self.analog_frame_range();
        let input = unsafe { shared(self.0.analogIn, frames * in_channels) };
        let output = self.analog_share(range.start..range.end);
        PairedIo::new(input, in_channels, output, out_channels, range)
    }

    // --- Indexed access (mirrors the C helpers) ---

    /// Audio input sample at `frame` for `channel` (`audioRead`).
    ///
    /// `frame` is a block frame, and may be outside this thread's
    /// range: the audio inputs are a buffer of their own that nobody
    /// writes.
    ///
    /// # Panics
    /// If `frame` or `channel` is out of range.
    #[must_use]
    pub fn audio_read(&self, frame: usize, channel: usize) -> f32 {
        let channels = self.audio_in_channels();
        assert!(channel < channels, "audio input channel out of range");
        self.audio_in()[frame * channels + channel]
    }

    /// Sets the audio output at `frame` for `channel` (`audioWrite`).
    /// Audio outputs never persist.
    ///
    /// # Panics
    /// If `channel` is out of range, or `frame` is outside
    /// [`audio_frame_range`](RenderContext::audio_frame_range).
    #[inline]
    pub fn audio_write(&mut self, frame: usize, channel: usize, value: f32) {
        let channels = self.audio_out_channels();
        assert!(channel < channels, "audio output channel out of range");
        let range = self.audio_frame_range();
        let index = frame_offset(&range, frame, "audio") * channels + channel;
        self.audio_share(range)[index] = value;
    }

    /// Analog input sample at `frame` for `channel` (`analogRead`).
    ///
    /// `frame` is a block frame, and may be outside this thread's
    /// range: the analog inputs are a buffer of their own that nobody
    /// writes.
    ///
    /// The value runs from 0.0 to 1.0 for an input of 0 V to 4.096 V,
    /// as for [`BlockContext::analog_read`].
    ///
    /// # Panics
    /// If `frame` or `channel` is out of range.
    #[must_use]
    pub fn analog_read(&self, frame: usize, channel: usize) -> f32 {
        let channels = self.analog_in_channels();
        assert!(channel < channels, "analog input channel out of range");
        self.analog_in()[frame * channels + channel]
    }

    /// Sets the analog output for `channel` from `frame` to the end of
    /// **this thread's range** (`analogWrite`).
    ///
    /// The C helper writes to the end of the block; the frames past
    /// this thread's range belong to another thread, so this stops
    /// there. With one render thread the two are the same thing. To
    /// hold an analog output across the whole block whatever the
    /// thread count, write it from
    /// [`render_pre`](crate::BelaApplication::render_pre).
    ///
    /// A Bela Gem Stereo has no analog outputs, so every channel is
    /// out of range there — see the type-level documentation.
    ///
    /// # Panics
    /// If `channel` is out of range, or `frame` is outside
    /// [`analog_frame_range`](RenderContext::analog_frame_range).
    pub fn analog_write(&mut self, frame: usize, channel: usize, value: f32) {
        let channels = self.analog_out_channels();
        assert!(channel < channels, "analog output channel out of range");
        let range = self.analog_frame_range();
        let skip = frame_offset(&range, frame, "analog");
        for samples in self.analog_share(range).chunks_mut(channels).skip(skip) {
            samples[channel] = value;
        }
    }

    /// Sets the analog output at `frame` only (`analogWriteOnce`).
    ///
    /// # Panics
    /// If `channel` is out of range, or `frame` is outside
    /// [`analog_frame_range`](RenderContext::analog_frame_range).
    #[inline]
    pub fn analog_write_once(&mut self, frame: usize, channel: usize, value: f32) {
        let channels = self.analog_out_channels();
        assert!(channel < channels, "analog output channel out of range");
        let range = self.analog_frame_range();
        let index = frame_offset(&range, frame, "analog") * channels + channel;
        self.analog_share(range)[index] = value;
    }

    /// Value of the digital `channel` at `frame` (`digitalRead`).
    ///
    /// On a channel set to [`PinMode::Output`] this reports the value
    /// last written to it rather than the state of the pin, as for
    /// [`BlockContext::digital_read`].
    ///
    /// # Panics
    /// If `channel` is out of range, or `frame` is outside
    /// [`digital_frame_range`](RenderContext::digital_frame_range) —
    /// see [`digital`](RenderContext::digital) for why reading is
    /// bounded here and not for the audio and analog inputs.
    #[must_use]
    #[inline]
    pub fn digital_read(&self, frame: usize, channel: usize) -> bool {
        let mask = digital_value_mask(self.digital_channels(), channel);
        let range = self.digital_frame_range();
        let index = frame_offset(&range, frame, "digital");
        // Safety: as for `digital`, whose range this is.
        let words = unsafe { share(self.0.digital, self.digital_frames(), 1, range) };
        words[index] & mask != 0
    }

    /// Sets the digital output `channel` from `frame` to the end of
    /// **this thread's range** (`digitalWrite`).
    ///
    /// Stops at the end of the range for the same reason
    /// [`analog_write`](RenderContext::analog_write) does.
    ///
    /// Outside the Gem Stereo context-FIFO condition, the value
    /// outlives the block and the program alike, as for
    /// [`BlockContext::digital_write`]. At periods of 256 frames or
    /// more, one-time direction and value writes do not establish
    /// persistence at the physical pin; see that method for the
    /// required per-application-block writes and [#89](https://github.com/akiomik/bela-rs/issues/89).
    ///
    /// # Panics
    /// If `channel` is out of range, or `frame` is outside
    /// [`digital_frame_range`](RenderContext::digital_frame_range).
    pub fn digital_write(&mut self, frame: usize, channel: usize, value: bool) {
        let mask = digital_value_mask(self.digital_channels(), channel);
        let range = self.digital_frame_range();
        let skip = frame_offset(&range, frame, "digital");
        for word in self.digital_share(range).iter_mut().skip(skip) {
            set_bits(word, mask, value);
        }
    }

    /// Sets the digital output `channel` at `frame` only
    /// (`digitalWriteOnce`).
    ///
    /// # Panics
    /// If `channel` is out of range, or `frame` is outside
    /// [`digital_frame_range`](RenderContext::digital_frame_range).
    #[inline]
    pub fn digital_write_once(&mut self, frame: usize, channel: usize, value: bool) {
        let mask = digital_value_mask(self.digital_channels(), channel);
        let range = self.digital_frame_range();
        let index = frame_offset(&range, frame, "digital");
        set_bits(&mut self.digital_share(range)[index], mask, value);
    }

    /// Sets the direction of digital `channel` from `frame` to the end
    /// of **this thread's range** (`pinMode`).
    ///
    /// Outside the Gem Stereo context-FIFO condition, the direction
    /// outlives the block and the program alike, as for
    /// [`BlockContext::pin_mode`]. At periods of 256 frames or more,
    /// one-time direction and value writes do not establish persistence
    /// at the physical pin; see that method and
    /// [`BlockContext::digital_write`].
    ///
    /// # Panics
    /// If `channel` is out of range, or `frame` is outside
    /// [`digital_frame_range`](RenderContext::digital_frame_range).
    pub fn pin_mode(&mut self, frame: usize, channel: usize, mode: PinMode) {
        let mask = digital_direction_mask(self.digital_channels(), channel);
        let range = self.digital_frame_range();
        let skip = frame_offset(&range, frame, "digital");
        for word in self.digital_share(range).iter_mut().skip(skip) {
            set_bits(word, mask, mode == PinMode::Input);
        }
    }

    /// Sets the direction of digital `channel` at `frame` only
    /// (`pinModeOnce`).
    ///
    /// # Panics
    /// If `channel` is out of range, or `frame` is outside
    /// [`digital_frame_range`](RenderContext::digital_frame_range).
    pub fn pin_mode_once(&mut self, frame: usize, channel: usize, mode: PinMode) {
        let mask = digital_direction_mask(self.digital_channels(), channel);
        let range = self.digital_frame_range();
        let index = frame_offset(&range, frame, "digital");
        set_bits(
            &mut self.digital_share(range)[index],
            mask,
            mode == PinMode::Input,
        );
    }

    // --- This thread's share, for a range already worked out ---
    //
    // `partition` is two multiplications and two divisions, and the
    // indexed accessors need the range before they can bound-check the
    // frame. Taking it as an argument is what keeps them to one.

    /// Safety: the reference covers this thread's frames and no
    /// others, which is what keeps the concurrent calls apart.
    #[inline]
    const fn audio_share(&mut self, range: Range<usize>) -> &mut [f32] {
        unsafe {
            share_mut(
                self.0.audioOut,
                self.audio_frames(),
                self.audio_out_channels(),
                range,
            )
        }
    }

    /// Safety: as for [`audio_share`](RenderContext::audio_share).
    #[inline]
    const fn analog_share(&mut self, range: Range<usize>) -> &mut [f32] {
        unsafe {
            share_mut(
                self.0.analogOut,
                self.analog_frames(),
                self.analog_out_channels(),
                range,
            )
        }
    }

    /// Safety: as for [`audio_share`](RenderContext::audio_share).
    #[inline]
    const fn digital_share(&mut self, range: Range<usize>) -> &mut [u32] {
        unsafe { share_mut(self.0.digital, self.digital_frames(), 1, range) }
    }
}

/// Proof that the caller is inside one of the Bela callbacks.
///
/// Some operations are only sound there — scheduling an
/// [`AuxiliaryTask`](crate::AuxiliaryTask) is the one this exists for —
/// and taking a `&impl CallbackContext` is how they say so. The four
/// context types implement it and nothing else can: they are handed out
/// by the callbacks and cannot be built without `unsafe`.
pub trait CallbackContext: sealed::Sealed {}

mod sealed {
    pub trait Sealed {}
}

macro_rules! callback_context {
    ($($context:ty),+ $(,)?) => {
        $(
            impl sealed::Sealed for $context {}
            impl CallbackContext for $context {}
        )+
    };
}

callback_context!(SetupContext, CleanupContext, BlockContext, RenderContext);

/// Where in an interleaved buffer of `frames` frames and `channels`
/// channels the samples of `range` are, clamped to the buffer.
///
/// The clamping is for a context whose frame counts and the range
/// derived from them disagree, which cannot happen for a range from
/// [`partition`] but is cheaper to rule out than to reason about.
#[inline]
const fn samples(frames: usize, channels: usize, range: &Range<usize>) -> (usize, usize) {
    let end = if range.end < frames {
        range.end
    } else {
        frames
    };
    let start = if range.start < end { range.start } else { end };
    (start * channels, (end - start) * channels)
}

/// A shared reference to the samples of `range` alone.
///
/// # Safety
/// `ptr` must be null or valid for reads of `frames * channels`
/// elements for the lifetime of the returned slice. Only the samples
/// of `range` are covered by it, so the rest of the buffer may be
/// borrowed elsewhere.
#[inline]
const unsafe fn share<'a, T>(
    ptr: *const T,
    frames: usize,
    channels: usize,
    range: Range<usize>,
) -> &'a [T] {
    if ptr.is_null() {
        return &[];
    }
    let (offset, len) = samples(frames, channels, &range);
    unsafe { slice::from_raw_parts(ptr.add(offset), len) }
}

/// An exclusive reference to the samples of `range` alone.
///
/// This is what makes concurrent `render` calls sound: each one asks
/// for a different `range`, so the references never overlap, and none
/// of them ever covers a sample belonging to another thread — not even
/// for as long as it takes to index into it.
///
/// # Safety
/// `ptr` must be null or valid for reads and writes of
/// `frames * channels` elements for the lifetime of the returned
/// slice, with the samples of `range` unaliased.
#[inline]
const unsafe fn share_mut<'a, T>(
    ptr: *mut T,
    frames: usize,
    channels: usize,
    range: Range<usize>,
) -> &'a mut [T] {
    if ptr.is_null() {
        return &mut [];
    }
    let (offset, len) = samples(frames, channels, &range);
    unsafe { slice::from_raw_parts_mut(ptr.add(offset), len) }
}

/// Where block `frame` sits within this thread's share of the block,
/// which is how the indexed accessors reach it once the reference
/// covers only that share.
///
/// # Panics
/// If `frame` is outside `range`.
#[inline]
fn frame_offset(range: &Range<usize>, frame: usize, domain: &str) -> usize {
    assert!(
        range.contains(&frame),
        "{domain} frame {frame} is outside this thread's range {range:?}"
    );
    frame - range.start
}

/// # Panics
/// If `channel` is out of range.
#[inline]
fn digital_value_mask(channels: usize, channel: usize) -> u32 {
    assert!(channel < channels, "digital channel out of range");
    1 << (channel + DIGITAL_VALUE_SHIFT)
}

/// # Panics
/// If `channel` is out of range.
#[inline]
fn digital_direction_mask(channels: usize, channel: usize) -> u32 {
    assert!(channel < channels, "digital channel out of range");
    1 << channel
}

/// # Safety
/// `ptr` must be null or valid for reads of `len` elements for the
/// lifetime of the returned slice.
#[inline]
const unsafe fn shared<'a, T>(ptr: *const T, len: usize) -> &'a [T] {
    if ptr.is_null() {
        &[]
    } else {
        unsafe { slice::from_raw_parts(ptr, len) }
    }
}

/// # Safety
/// `ptr` must be null or valid for reads and writes of `len` elements,
/// unaliased for the lifetime of the returned slice.
#[inline]
const unsafe fn exclusive<'a, T>(ptr: *mut T, len: usize) -> &'a mut [T] {
    if ptr.is_null() {
        &mut []
    } else {
        unsafe { slice::from_raw_parts_mut(ptr, len) }
    }
}

#[inline]
const fn set_bits(word: &mut u32, mask: u32, on: bool) {
    if on {
        *word |= mask;
    } else {
        *word &= !mask;
    }
}

#[cfg(test)]
#[allow(
    clippy::cast_possible_truncation,
    clippy::cast_precision_loss,
    clippy::float_cmp,
    reason = "tests use small exact values where these casts and comparisons are lossless"
)]
pub(crate) mod tests {
    use core::mem;

    use super::*;

    const AUDIO_FRAMES: usize = 4;
    const AUDIO_IN_CHANNELS: usize = 2;
    // Deliberately none of the boards': more outputs than inputs, and
    // analog outputs that exist, so that the indexing is exercised on
    // a context no hardware would hand over. A Gem Stereo's own shape
    // — 2 out, 0 analog out — would leave most of these tests with
    // nothing to index.
    const AUDIO_OUT_CHANNELS: usize = 4;
    const ANALOG_FRAMES: usize = 4;
    const ANALOG_IN_CHANNELS: usize = 4;
    const ANALOG_OUT_CHANNELS: usize = 2;
    const DIGITAL_FRAMES: usize = 4;
    const DIGITAL_CHANNELS: usize = 16;

    /// Buffers plus a context pointing at them, standing in for what
    /// libbela hands a callback.
    ///
    /// Boxed because the context holds pointers into the fixture's own
    /// fields, which must not move.
    pub(crate) struct Fixture {
        audio_in: Vec<f32>,
        pub(crate) audio_out: Vec<f32>,
        analog_in: Vec<f32>,
        pub(crate) analog_out: Vec<f32>,
        pub(crate) digital: Vec<u32>,
        pub(crate) context: BelaContext,
    }

    impl Fixture {
        pub(crate) fn new() -> Box<Self> {
            Self::with_threads(1)
        }

        /// A fixture whose context reports `threads` render threads.
        pub(crate) fn with_threads(threads: u32) -> Box<Self> {
            // Input samples encode their own position as frame*10+channel.
            let audio_in: Vec<f32> = (0..AUDIO_FRAMES * AUDIO_IN_CHANNELS)
                .map(|i| {
                    let (frame, channel) = (i / AUDIO_IN_CHANNELS, i % AUDIO_IN_CHANNELS);
                    (frame * 10 + channel) as f32
                })
                .collect();
            let analog_in: Vec<f32> = (0..ANALOG_FRAMES * ANALOG_IN_CHANNELS)
                .map(|i| {
                    let (frame, channel) = (i / ANALOG_IN_CHANNELS, i % ANALOG_IN_CHANNELS);
                    (frame * 10 + channel) as f32
                })
                .collect();
            let mut fixture = Box::new(Self {
                audio_in,
                audio_out: vec![0.0; AUDIO_FRAMES * AUDIO_OUT_CHANNELS],
                analog_in,
                analog_out: vec![0.0; ANALOG_FRAMES * ANALOG_OUT_CHANNELS],
                digital: vec![0; DIGITAL_FRAMES],
                context: unsafe { mem::zeroed() },
            });
            fixture.context.audioIn = fixture.audio_in.as_ptr();
            fixture.context.audioOut = fixture.audio_out.as_mut_ptr();
            fixture.context.analogIn = fixture.analog_in.as_ptr();
            fixture.context.analogOut = fixture.analog_out.as_mut_ptr();
            fixture.context.digital = fixture.digital.as_mut_ptr();
            fixture.context.audioFrames = AUDIO_FRAMES as u32;
            fixture.context.audioInChannels = AUDIO_IN_CHANNELS as u32;
            fixture.context.audioOutChannels = AUDIO_OUT_CHANNELS as u32;
            fixture.context.audioSampleRate = 44100.0;
            fixture.context.analogFrames = ANALOG_FRAMES as u32;
            fixture.context.analogInChannels = ANALOG_IN_CHANNELS as u32;
            fixture.context.analogOutChannels = ANALOG_OUT_CHANNELS as u32;
            fixture.context.analogSampleRate = 44100.0;
            fixture.context.digitalFrames = DIGITAL_FRAMES as u32;
            fixture.context.digitalChannels = DIGITAL_CHANNELS as u32;
            fixture.context.audioFramesElapsed = 128;
            fixture.context.thisThread = 0;
            fixture.context.threadCount = threads;
            fixture
        }

        pub(crate) fn block(&mut self) -> &mut BlockContext {
            unsafe { BlockContext::from_mut_ptr(&raw mut self.context) }
        }

        pub(crate) fn setup(&mut self) -> &mut SetupContext {
            unsafe { SetupContext::from_mut_ptr(&raw mut self.context) }
        }

        pub(crate) fn cleanup(&mut self) -> &mut CleanupContext {
            unsafe { CleanupContext::from_mut_ptr(&raw mut self.context) }
        }

        /// The render context thread `thread` would see, with the
        /// thread number written into the context the way libbela's
        /// mirrored copies carry it.
        pub(crate) fn render(&mut self, thread: u32) -> &mut RenderContext {
            self.context.thisThread = thread;
            unsafe { RenderContext::from_mut_ptr(&raw mut self.context) }
        }
    }

    #[test]
    fn metadata_accessors_reflect_the_struct() {
        let mut fixture = Fixture::with_threads(4);
        let context = fixture.block();

        assert_eq!(context.audio_frames(), AUDIO_FRAMES);
        assert_eq!(context.audio_in_channels(), AUDIO_IN_CHANNELS);
        assert_eq!(context.audio_out_channels(), AUDIO_OUT_CHANNELS);
        assert_eq!(context.audio_sample_rate(), 44100.0);
        assert_eq!(context.analog_frames(), ANALOG_FRAMES);
        assert_eq!(context.digital_channels(), DIGITAL_CHANNELS);
        assert_eq!(context.audio_frames_elapsed(), 128);
        assert_eq!(context.underrun_count(), 0);
        assert_eq!(context.this_thread(), 0);
        assert_eq!(context.thread_count(), 4);
    }

    #[test]
    fn the_same_metadata_is_on_every_phase() {
        let mut fixture = Fixture::new();
        assert_eq!(fixture.setup().audio_frames(), AUDIO_FRAMES);
        assert_eq!(fixture.render(0).audio_sample_rate(), 44100.0);
        let cleanup = unsafe { CleanupContext::from_mut_ptr(&raw mut fixture.context) };
        assert_eq!(cleanup.audio_frames_elapsed(), 128);
    }

    #[test]
    fn one_render_thread_is_spelled_either_way() {
        for spelling in [0, 1] {
            let mut fixture = Fixture::with_threads(spelling);
            assert_eq!(
                fixture.render(0).thread_count(),
                1,
                "threadCount {spelling} means one render thread"
            );
            assert_eq!(
                fixture.render(0).audio_frame_range(),
                0..AUDIO_FRAMES,
                "the one thread gets the whole block"
            );
        }
    }

    // --- Partitioning ---

    #[test]
    fn partitions_tile_the_block_exactly() {
        for frames in 0..40_usize {
            for count in 1..8_usize {
                let mut previous_end = 0;
                for thread in 0..count {
                    let range = partition(frames, thread, count);
                    assert_eq!(
                        range.start, previous_end,
                        "{frames} frames, {count} threads"
                    );
                    assert!(range.start <= range.end, "{frames} frames, {count} threads");
                    previous_end = range.end;
                }
                assert_eq!(previous_end, frames, "{frames} frames, {count} threads");
            }
        }
    }

    #[test]
    fn uneven_partitions_differ_by_at_most_one_frame() {
        // 7 frames over 4 threads: 1, 2, 2, 2 rather than 1, 1, 1, 4.
        let lengths: Vec<usize> = (0..4).map(|t| partition(7, t, 4).len()).collect();
        assert_eq!(lengths, vec![1, 2, 2, 2]);
        assert_eq!(lengths.iter().sum::<usize>(), 7);
    }

    #[test]
    fn more_threads_than_frames_gives_empty_ranges() {
        let ranges: Vec<Range<usize>> = (0..4).map(|t| partition(2, t, 4)).collect();
        assert_eq!(ranges, vec![0..0, 0..1, 1..1, 1..2]);
    }

    #[test]
    fn a_thread_outside_the_count_gets_nothing() {
        // Never reached through a context — the runtime refuses such a
        // callback before building one — but the split itself must not
        // hand out somebody else's frames if it is.
        assert_eq!(partition(8, 4, 4), 8..8);
        assert_eq!(partition(8, 9, 4), 8..8);
    }

    #[test]
    fn a_zero_thread_count_is_one_thread() {
        assert_eq!(partition(8, 0, 0), 0..8);
    }

    // --- BlockContext ---

    #[test]
    fn audio_read_uses_the_interleaved_layout() {
        let mut fixture = Fixture::new();
        let context = fixture.block();

        // Sample values encode frame*10+channel.
        assert_eq!(context.audio_read(0, 0), 0.0);
        assert_eq!(context.audio_read(0, 1), 1.0);
        assert_eq!(context.audio_read(3, 1), 31.0);
        assert_eq!(context.audio_in().len(), AUDIO_FRAMES * AUDIO_IN_CHANNELS);
    }

    #[test]
    fn audio_write_targets_exactly_one_sample() {
        let mut fixture = Fixture::new();
        fixture.block().audio_write(2, 3, 0.5);

        let index = 2 * AUDIO_OUT_CHANNELS + 3;
        for (i, &sample) in fixture.audio_out.iter().enumerate() {
            let expected = if i == index { 0.5 } else { 0.0 };
            assert_eq!(sample, expected, "sample {i}");
        }
    }

    #[test]
    fn analog_read_uses_the_interleaved_layout() {
        let mut fixture = Fixture::new();
        assert_eq!(fixture.block().analog_read(2, 3), 23.0);
    }

    #[test]
    fn analog_write_persists_to_the_end_of_the_block() {
        let mut fixture = Fixture::new();
        fixture.block().analog_write(1, 0, 0.7);

        for frame in 0..ANALOG_FRAMES {
            let expected = if frame >= 1 { 0.7 } else { 0.0 };
            assert_eq!(fixture.analog_out[frame * ANALOG_OUT_CHANNELS], expected);
            // The other channel is untouched.
            assert_eq!(fixture.analog_out[frame * ANALOG_OUT_CHANNELS + 1], 0.0);
        }
    }

    #[test]
    fn analog_write_once_targets_exactly_one_sample() {
        let mut fixture = Fixture::new();
        fixture.block().analog_write_once(1, 1, 0.7);

        let index = ANALOG_OUT_CHANNELS + 1;
        for (i, &sample) in fixture.analog_out.iter().enumerate() {
            let expected = if i == index { 0.7 } else { 0.0 };
            assert_eq!(sample, expected, "sample {i}");
        }
    }

    #[test]
    fn digital_value_bits_live_in_the_high_half_word() {
        let mut fixture = Fixture::new();
        let context = fixture.block();

        context.digital_write_once(0, 3, true);
        assert_eq!(fixture.digital[0], 1 << (3 + 16));

        let context = fixture.block();
        assert!(context.digital_read(0, 3));
        assert!(!context.digital_read(0, 2));
        assert!(!context.digital_read(1, 3));
    }

    #[test]
    fn digital_write_persists_and_clears() {
        let mut fixture = Fixture::new();
        fixture.block().digital_write(1, 5, true);
        for frame in 0..DIGITAL_FRAMES {
            assert_eq!(fixture.digital[frame], u32::from(frame >= 1) << (5 + 16));
        }

        fixture.block().digital_write(2, 5, false);
        for frame in 0..DIGITAL_FRAMES {
            assert_eq!(fixture.digital[frame], u32::from(frame == 1) << (5 + 16));
        }
    }

    #[test]
    fn pin_mode_sets_direction_bits_in_the_low_half_word() {
        let mut fixture = Fixture::new();
        fixture.block().pin_mode(0, 7, PinMode::Input);
        for frame in 0..DIGITAL_FRAMES {
            assert_eq!(fixture.digital[frame], 1 << 7);
        }

        fixture.block().pin_mode_once(2, 7, PinMode::Output);
        for frame in 0..DIGITAL_FRAMES {
            assert_eq!(fixture.digital[frame], u32::from(frame != 2) << 7);
        }
    }

    #[test]
    fn disabled_io_yields_empty_slices() {
        let mut context: BelaContext = unsafe { mem::zeroed() };
        let context = unsafe { BlockContext::from_mut_ptr(&raw mut context) };

        assert!(context.audio_in().is_empty());
        assert!(context.audio_out().is_empty());
        assert!(context.analog_in().is_empty());
        assert!(context.analog_out().is_empty());
        assert!(context.digital().is_empty());
    }

    #[test]
    #[should_panic(expected = "audio input channel out of range")]
    fn audio_read_rejects_out_of_range_channels() {
        let mut fixture = Fixture::new();
        let _ = fixture.block().audio_read(0, AUDIO_IN_CHANNELS);
    }

    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn audio_read_rejects_out_of_range_frames() {
        let mut fixture = Fixture::new();
        let _ = fixture.block().audio_read(AUDIO_FRAMES, 0);
    }

    #[test]
    #[should_panic(expected = "digital channel out of range")]
    fn digital_write_rejects_out_of_range_channels() {
        let mut fixture = Fixture::new();
        fixture.block().digital_write(0, DIGITAL_CHANNELS, true);
    }

    // --- PairedIo ---

    #[test]
    fn paired_audio_view_covers_the_whole_block_on_a_block_context() {
        let mut fixture = Fixture::new();
        let mut io = fixture.block().audio_io();

        assert_eq!(io.in_channels(), AUDIO_IN_CHANNELS);
        assert_eq!(io.out_channels(), AUDIO_OUT_CHANNELS);
        assert_eq!(io.output_range(), 0..AUDIO_FRAMES);
        assert_eq!(io.input().len(), AUDIO_FRAMES * AUDIO_IN_CHANNELS);
        assert_eq!(io.output().len(), AUDIO_FRAMES * AUDIO_OUT_CHANNELS);
        // Sample values encode frame*10+channel, same as `audio_read`.
        assert_eq!(
            io.input()[AUDIO_IN_CHANNELS + 1],
            11.0,
            "frame 1, channel 1"
        );
    }

    #[test]
    fn paired_audio_frames_writes_reach_the_underlying_buffer_on_a_block_context() {
        let mut fixture = Fixture::new();
        {
            let mut io = fixture.block().audio_io();
            for (input, output) in io.frames() {
                // AUDIO_OUT_CHANNELS (4) > AUDIO_IN_CHANNELS (2), so
                // `zip` fills only the first two of every frame's
                // four output channels — same as the doctest.
                for (sample, value) in output.iter_mut().zip(input) {
                    *sample = *value;
                }
            }
        }

        for frame in 0..AUDIO_FRAMES {
            for channel in 0..AUDIO_IN_CHANNELS {
                let expected = (frame * 10 + channel) as f32;
                assert_eq!(
                    fixture.audio_out[frame * AUDIO_OUT_CHANNELS + channel],
                    expected,
                    "frame {frame} channel {channel}"
                );
            }
            for channel in AUDIO_IN_CHANNELS..AUDIO_OUT_CHANNELS {
                assert_eq!(
                    fixture.audio_out[frame * AUDIO_OUT_CHANNELS + channel],
                    0.0,
                    "frame {frame} channel {channel} has no input counterpart"
                );
            }
        }
    }

    #[test]
    fn paired_analog_view_is_independent_of_the_audio_buffers() {
        let mut fixture = Fixture::new();
        {
            let mut io = fixture.block().analog_io();
            assert_eq!(io.in_channels(), ANALOG_IN_CHANNELS);
            assert_eq!(io.out_channels(), ANALOG_OUT_CHANNELS);
            assert_eq!(io.input().len(), ANALOG_FRAMES * ANALOG_IN_CHANNELS);
            io.output().fill(9.0);
        }

        assert!(fixture.analog_out.iter().all(|&v| v == 9.0));
        assert!(
            fixture.audio_out.iter().all(|&v| v == 0.0),
            "analog_io must not touch the audio buffers"
        );
    }

    #[test]
    fn paired_view_frames_does_not_panic_when_output_has_no_channels() {
        // A Gem Stereo's analog_out_channels is 0 for every channel
        // count it accepts (docs/board-facts.md); `frames()` must
        // still yield one item per input frame rather than panicking
        // the way `chunks_mut(0)` would.
        let mut context: BelaContext = unsafe { mem::zeroed() };
        context.audioFrames = 3;
        context.audioInChannels = 2;
        context.audioOutChannels = 0;
        let audio_in = [0.0_f32, 1.0, 10.0, 11.0, 20.0, 21.0];
        context.audioIn = audio_in.as_ptr();

        let context = unsafe { BlockContext::from_mut_ptr(&raw mut context) };
        let mut io = context.audio_io();
        assert_eq!(io.out_channels(), 0);

        let mut frame_count = 0;
        for (input, output) in io.frames() {
            assert!(output.is_empty());
            assert_eq!(input.len(), 2);
            frame_count += 1;
        }
        assert_eq!(
            frame_count, 3,
            "three frames, each with zero output channels"
        );
    }

    #[test]
    fn paired_view_frames_does_not_panic_when_input_has_no_channels() {
        let mut context: BelaContext = unsafe { mem::zeroed() };
        context.audioFrames = 3;
        context.audioInChannels = 0;
        context.audioOutChannels = 2;
        let mut audio_out = [0.0_f32; 6];
        context.audioOut = audio_out.as_mut_ptr();

        let context = unsafe { BlockContext::from_mut_ptr(&raw mut context) };
        let mut io = context.audio_io();
        assert_eq!(io.in_channels(), 0);

        let mut frame_count = 0;
        for (input, output) in io.frames() {
            assert!(input.is_empty());
            assert_eq!(output.len(), 2);
            frame_count += 1;
        }
        assert_eq!(
            frame_count, 3,
            "three frames, each with zero input channels"
        );
    }

    // --- RenderContext ---

    #[test]
    fn a_render_context_reads_the_whole_block() {
        let mut fixture = Fixture::with_threads(4);
        let context = fixture.render(3);

        assert_eq!(context.audio_frame_range(), 3..4, "one frame of four");
        // Frame 0 belongs to another thread, and is still readable.
        assert_eq!(context.audio_read(0, 1), 1.0);
        assert_eq!(context.audio_in().len(), AUDIO_FRAMES * AUDIO_IN_CHANNELS);
        assert_eq!(context.analog_read(0, 3), 3.0);
    }

    #[test]
    fn a_render_context_writes_only_its_own_frames() {
        let mut fixture = Fixture::with_threads(2);

        for thread in 0..2 {
            let context = fixture.render(thread);
            let range = context.audio_frame_range();
            for frame in range {
                context.audio_write(frame, 0, frame as f32 + 1.0);
            }
        }

        // Between them the two threads covered the block exactly.
        for frame in 0..AUDIO_FRAMES {
            assert_eq!(
                fixture.audio_out[frame * AUDIO_OUT_CHANNELS],
                frame as f32 + 1.0,
                "frame {frame}"
            );
        }
    }

    #[test]
    fn the_output_slice_is_this_threads_share() {
        let mut fixture = Fixture::with_threads(2);
        let context = fixture.render(1);

        let out = context.audio_out();
        assert_eq!(out.len(), 2 * AUDIO_OUT_CHANNELS, "two of four frames");
        // Index 0 is the first sample of the range, which is frame 2.
        out[0] = 9.0;
        assert_eq!(fixture.audio_out[2 * AUDIO_OUT_CHANNELS], 9.0);
        assert_eq!(fixture.audio_out[0], 0.0, "frame 0 belongs to thread 0");
    }

    #[test]
    fn paired_audio_frames_align_input_and_output_when_the_range_does_not_start_at_zero() {
        let mut fixture = Fixture::with_threads(4);
        {
            // Thread 2 of 4 owns exactly frame 2 (partition(4, 2, 4)).
            let context = fixture.render(2);
            let mut io = context.audio_io();
            assert_eq!(io.output_range(), 2..3);

            let mut frames = io.frames();
            let (input, output) = frames.next().expect("one frame in this thread's range");
            // Input is indexed by the same absolute frame the output
            // range starts at (2), not by 0 — the mismatch `frames()`
            // exists to rule out.
            assert_eq!(input, [20.0, 21.0]);
            output.copy_from_slice(&[1.0, 2.0, 3.0, 4.0]);
            assert!(
                frames.next().is_none(),
                "thread 2 of 4 owns exactly one frame"
            );
        }

        assert_eq!(
            fixture.audio_out[2 * AUDIO_OUT_CHANNELS..3 * AUDIO_OUT_CHANNELS],
            [1.0, 2.0, 3.0, 4.0]
        );
        assert_eq!(
            fixture.audio_out[0..AUDIO_OUT_CHANNELS],
            [0.0; AUDIO_OUT_CHANNELS],
            "frame 0 belongs to another thread"
        );
    }

    #[test]
    fn analog_and_digital_slices_are_partitioned_too() {
        let mut fixture = Fixture::with_threads(4);
        let context = fixture.render(2);

        assert_eq!(context.analog_frame_range(), 2..3);
        assert_eq!(context.digital_frame_range(), 2..3);
        assert_eq!(context.analog_out().len(), ANALOG_OUT_CHANNELS);
        assert_eq!(context.digital_mut().len(), 1);
    }

    #[test]
    fn persisting_writes_stop_at_the_end_of_the_range() {
        let mut fixture = Fixture::with_threads(2);
        // Thread 0 owns frames 0..2, so this must not reach frame 2.
        fixture.render(0).analog_write(0, 0, 0.7);
        fixture.render(0).digital_write(0, 5, true);

        for frame in 0..ANALOG_FRAMES {
            let expected = if frame < 2 { 0.7 } else { 0.0 };
            assert_eq!(
                fixture.analog_out[frame * ANALOG_OUT_CHANNELS],
                expected,
                "analog frame {frame}"
            );
        }
        for frame in 0..DIGITAL_FRAMES {
            assert_eq!(
                fixture.digital[frame],
                u32::from(frame < 2) << (5 + 16),
                "digital frame {frame}"
            );
        }
    }

    #[test]
    fn an_empty_range_hands_out_nothing_to_write() {
        // Four threads, and a block with fewer frames than that would
        // need: the first thread's share is empty.
        let mut fixture = Fixture::with_threads(8);
        let context = fixture.render(0);

        assert_eq!(context.audio_frame_range(), 0..0);
        assert!(context.audio_out().is_empty());
        assert!(context.analog_out().is_empty());
        assert!(context.digital_mut().is_empty());
    }

    #[test]
    #[should_panic(expected = "audio frame 0 is outside this thread's range 2..4")]
    fn writing_another_threads_frame_panics() {
        let mut fixture = Fixture::with_threads(2);
        fixture.render(1).audio_write(0, 0, 1.0);
    }

    #[test]
    #[should_panic(expected = "analog frame 3 is outside this thread's range 0..2")]
    fn a_persisting_analog_write_outside_the_range_panics() {
        let mut fixture = Fixture::with_threads(2);
        fixture.render(0).analog_write(3, 0, 1.0);
    }

    #[test]
    #[should_panic(expected = "digital frame 0 is outside this thread's range 2..4")]
    fn a_digital_write_outside_the_range_panics() {
        let mut fixture = Fixture::with_threads(2);
        fixture.render(1).digital_write(0, 5, true);
    }

    #[test]
    fn digital_reads_are_this_threads_share_too() {
        // Unlike the audio and analog inputs, the digital words are
        // where the outputs go, so a read past this thread's range
        // would be a read of what another thread is writing.
        let mut fixture = Fixture::with_threads(2);
        fixture.render(0).digital_write_once(1, 5, true);

        let context = fixture.render(0);
        assert_eq!(context.digital().len(), 2, "two of four frames");
        assert!(context.digital_read(1, 5));
        assert!(!context.digital_read(0, 5));
    }

    #[test]
    #[should_panic(expected = "digital frame 3 is outside this thread's range 0..2")]
    fn a_digital_read_outside_the_range_panics() {
        let mut fixture = Fixture::with_threads(2);
        let _ = fixture.render(0).digital_read(3, 5);
    }

    #[test]
    fn audio_and_analog_reads_are_not_bounded_that_way() {
        // Their inputs are buffers of their own, which nothing writes.
        let mut fixture = Fixture::with_threads(2);
        let context = fixture.render(1);

        assert_eq!(context.audio_read(0, 0), 0.0);
        assert_eq!(context.analog_read(0, 0), 0.0);
    }

    #[test]
    fn a_pin_begins_as_an_input() {
        // What the hardware does before anything asks otherwise, so it
        // is the only thing the default can be.
        assert_eq!(PinMode::default(), PinMode::Input);
    }

    #[test]
    fn a_context_debugs_as_the_configuration_it_describes() {
        let mut fixture = Fixture::new();
        let printed = format!("{:?}", fixture.block());

        assert!(
            printed.starts_with("BlockContext {"),
            "should name the phase it is: {printed}"
        );
        for field in [
            "audio_frames: 4",
            "audio_out_channels: 4",
            "audio_sample_rate: 44100.0",
            "analog_out_channels: 2",
            "digital_channels: 16",
            "audio_frames_elapsed: 128",
            "thread_count: 1",
        ] {
            assert!(printed.contains(field), "missing {field} in {printed}");
        }
        // The buffers are the one thing that must not be in there: a
        // block is thousands of samples, and this can be reached from
        // a callback.
        assert!(
            !printed.contains("audio_out:") && !printed.contains("audioOut"),
            "should not print the buffers: {printed}"
        );
    }

    #[test]
    fn each_phase_debugs_under_its_own_name() {
        let mut fixture = Fixture::new();

        assert!(format!("{:?}", fixture.setup()).starts_with("SetupContext {"));
        assert!(format!("{:?}", fixture.cleanup()).starts_with("CleanupContext {"));
        assert!(format!("{:?}", fixture.render(0)).starts_with("RenderContext {"));
    }

    #[test]
    fn a_render_context_debugs_the_ranges_that_are_its_own() {
        // What separates this phase from `BlockContext` is which
        // frames it may write, so a `{:?}` printed from a `render`
        // writing in the wrong place has to show them.
        let mut fixture = Fixture::with_threads(2);
        let printed = format!("{:?}", fixture.render(1));

        assert!(
            printed.contains("audio_frame_range: 2..4"),
            "the second of two threads writes the second half: {printed}"
        );
        for field in ["analog_frame_range: 2..4", "digital_frame_range: 2..4"] {
            assert!(printed.contains(field), "missing {field} in {printed}");
        }
        assert!(printed.contains("this_thread: 1"));

        // The phases that have no partition do not grow the fields.
        assert!(!format!("{:?}", fixture.block()).contains("audio_frame_range"));
    }
}