nord-format 0.6.0

Read and write Nord keyboard files from Rust, byte for byte
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
//! Building a sample instrument from PCM.
//!
//! The inverse of [`codec`](super::codec). What this emits is what Nord Sample Editor
//! writes for the same input, byte for byte, apart from one residue: the resampling
//! [`kernel`](super::kernel) is the instrument's to within a few `1e-8` per tap, and a
//! handful of taps the editor evaluates a ulp off the closed form leave the occasional
//! field one count from the editor's. No structural field moves with it, and neither
//! does the pitch, the length, or anything else about what the instrument plays.
//!
//! The record coding the editor picks, [`Predictor::Minimising`], is the default here.
//! [`Predictor::Plain`] opts out and states every content field outright: the same
//! audio in a file several times larger on smooth material, and not the editor's bytes.
//!
//! Under either predictor a file from here **round-trips through this crate's own
//! decoder exactly** and obeys every structural law the format is known to have.
//!
//! For [`Layout::V2`], the Electro 5 loads and plays one under either predictor, at
//! the pitch the decoder renders. Confirmed on hardware. The wide generations
//! reproduce the editor's own renders, but the Electro 5 plays only v2, so their
//! playback: Inferred from specimens; not confirmed on hardware.
//!
//! ```no_run
//! # use nord_format::formats::nsmp::encode;
//! let samples: Vec<i16> = vec![0; 44_100];
//! let options = encode::Options::new("Test").root_key(60);
//! let instrument = encode::instrument(&samples, &options).unwrap();
//! std::fs::write("test.nsmp", instrument.to_bytes().unwrap()).unwrap();
//! ```
//!
//! **All three generations write from the one plan.** [`Options::layout`] picks the
//! generation; what moves with it is the container — the narrow `NWS` chain against
//! the wide `NSMP` one, and the section schemas inside — and the stream's units, which
//! [`Units`] holds. The lattice, the kernel, the quantiser, the count laws and the
//! record grammar's bit layout are the same object in all three.
//!
//! [`multi_zone`] is the same builder across a keyboard: one `stk` per zone, highest
//! zone first, each zone's record naming its stroke by the global id the caller gives
//! it. Zone counts move where a stroke's audio may start, so the allocation each stroke
//! is packed into comes from [`stroke::header_len`](super::stroke::header_len) rather
//! than from a constant.
//!
//! **Stereo is the mono plan run once per channel and interleaved.** A stereo stroke
//! carries both channels under one header at the doubled cell, and every count-law
//! landmark — the field total, the resync position, both 1:1 runs — is exactly its mono
//! value doubled. So the whole of stereo, on the plan side, is a channel count: cells
//! and 1:1 records double, the terminator states the doubled cell, and the predictor
//! keeps a history per channel. Where the two channels' *bits* go does move with the
//! generation: v2 and v3 alternate fields in one bitstream, v4 packs each channel's
//! half into its own words and alternates those.
//!
//! For [`Layout::V2`], a stereo encode plays with its channels in order and
//! independent. Confirmed on hardware. The wide generations: Inferred from specimens;
//! not confirmed on hardware.
//!
//! A [`Loop`] truncates the stroke at its end and opens a marked record at its start,
//! which is the whole of what the container stores about looping: the crossfade is
//! baked into the audio here, while loop detune, the decay switch and the short loop's
//! pitch-tracking flag reach nowhere. Wide headers carry the decay amount. The fade's
//! frame count is the caller's to work out — a project states the long loop's in frames
//! and the short loop's as a percentage of its length — and it arrives here already in
//! frames, fraction and all.
//!
//! For [`Layout::V2`], the Electro 5 sustains a looped encode to note-off, and the
//! seam is clean. Confirmed on hardware. The wide generations: Inferred from
//! specimens; not confirmed on hardware.

use super::codec::{self, Layout, PITCH_DEN, PITCH_NUM, WRAP};
use super::kernel;
use super::section::{self, Section, Section4};
use super::stroke::packet_len;
use super::{Sample, SampleV3};
use crate::cbin::{Cbin, Generation, Header};
use crate::error::{Error, ParseError};
use crate::formats::nsmpproj;

/// Content version this writes per generation: `format × 100 + revision`, at the
/// revision the editor emits.
const fn version(layout: Layout) -> u32 {
    match layout {
        Layout::V2 => 200,
        Layout::V3 => 300,
        Layout::V4 => 400,
    }
}

/// The sample-instrument `aux` value, the same in every generation.
/// Unexplained: real programs hold this, and the panel cannot produce it.
const AUX: u32 = 0x000f_0000;

/// Largest field count a record header can state, from its 14-bit count field.
/// ⚠️ A record covers whole cells, so how many *cells* that is halves on a stereo
/// stroke — the count is a field count, and a stereo cell holds two channels' worth.
const MAX_COUNT: usize = (1 << 14) - 1;

/// Widest field a stroke's peak may take: quantisation shifts until it fits. On a
/// stereo stroke this is the whole of the shift rule.
const PEAK_WIDTH: u8 = 14;

/// The stream units one stroke is written in: the generation's word and cell sizes,
/// scaled by how many channels share the stroke.
///
/// Everything else about the encoder is generation-independent — the lattice, the
/// kernel, the quantiser and the record grammar's bit layout do not move — so this is
/// the whole of what a generation changes about a stream.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Units {
    layout: Layout,
    /// 1 or 2.
    channels: usize,
}

impl Units {
    const fn word(self) -> usize {
        self.layout.word()
    }

    const fn word_bits(self) -> usize {
        self.layout.word() * 8
    }

    /// Fields one content cell covers: the generation's cell per channel.
    const fn cell(self) -> usize {
        self.layout.cell() * self.channels
    }

    /// Fields one 1:1 record covers at most: the generation's RMAX per channel.
    const fn chunk(self) -> usize {
        self.layout.rmax() * self.channels
    }

    /// Whether a record's two channels occupy alternating, independently padded
    /// words rather than alternating fields in one bitstream.
    const fn splits(self) -> bool {
        self.channels == 2 && self.layout.splits_wide_openings()
    }

    /// Words one channel's half of a split record occupies.
    const fn half(self, count: usize, width: u8) -> usize {
        (count / 2 * width as usize).div_ceil(self.word_bits())
    }

    /// Words one record occupies, header included.
    ///
    /// A split record pays for each channel's own padding; a content record tiles
    /// whole words either way, so only the 1:1 regime is ever wider for it.
    const fn span(self, count: usize, width: u8) -> usize {
        if self.splits() {
            1 + 2 * self.half(count, width)
        } else {
            (self.word_bits() + count * width as usize).div_ceil(self.word_bits())
        }
    }

    /// Words in one packet of allocation.
    const fn packet_words(self) -> usize {
        packet_len(self.layout) / self.word()
    }

    /// Words of slack the allocation keeps ahead of the chain's first record.
    ///
    /// The chain is right-aligned in whole packets either way; the wide chain buys a
    /// further packet rather than let the lead fall below this, so its strokes carry
    /// 7 to 38 words of slack where a narrow one carries 0 to 126.
    ///
    /// Inferred from specimens; not confirmed on hardware.
    const fn min_lead(self) -> usize {
        match self.layout {
            Layout::V2 => 0,
            Layout::V3 | Layout::V4 => 7,
        }
    }

    /// Absolute field ceiling imposed by the stream directory and minimum width.
    const fn max_fields(self) -> usize {
        MAX_STREAM_WORDS * self.word_bits() / MIN_WIDTH as usize
    }
}

/// Last-record field counts, per channel, that do not carry the extra quantiser bit —
/// `None` for a generation whose mono strokes never spend it.
///
/// A run's records are RMAX-sized until a remainder, so the range a last record can
/// take is the generation's: 24..=32 fields at v2 and 32..=48 at v3. Every width in
/// both ranges has been read off a render, and these are the ones that never buy the
/// bit. There is no arithmetic behind either set and no correspondence between them.
///
/// Inferred from specimens; not confirmed on hardware.
const fn dead_last_record(layout: Layout) -> Option<&'static [usize]> {
    match layout {
        Layout::V2 => Some(&[24, 29, 32]),
        Layout::V3 => Some(&[32, 41, 43, 45, 47, 48]),
        Layout::V4 => None,
    }
}

/// Whether a stroke spends one more quantiser bit than its peak needs, narrowing its
/// widest field a bit under [`PEAK_WIDTH`] and shrinking the stream.
///
/// `values` are the stroke's fields before any shift. Read them at the smallest shift
/// that fits the peak in [`PEAK_WIDTH`] bits: the bit is spent when a field still
/// outside the signed 13-bit range there falls inside the **last record of one of the
/// stroke's 1:1 runs** and that record's field count is not one [`dead_last_record`]
/// names. A field in an earlier record of a run, or out in the content cells, never
/// buys it, and no run's length is otherwise consulted.
///
/// ⚠️ Every 1:1 run counts, the loop's included — a marked record opens a run of its
/// own past the resync, and a field landing in its last record buys the bit exactly
/// as one in the opening or resync run does.
///
/// A stereo stroke never spends the bit, in any generation, and neither does a v4 mono
/// one: both quantise at the peak term alone.
///
/// Inferred from specimens; not confirmed on hardware. The Electro 5 plays v2 only.
fn spends_extra_bit(values: &[i64], plan: &Plan) -> bool {
    if plan.channels != 1 {
        return false;
    }
    let Some(dead) = dead_last_record(plan.layout) else {
        return false;
    };
    let over = 1i64 << (PEAK_WIDTH - 2);
    let shift = peak_shift(values, PEAK_WIDTH);
    [
        Some((0, plan.warmup)),
        Some((plan.resync_at, plan.resync)),
        plan.looped.map(|points| (points.at, points.warmup)),
    ]
    .into_iter()
    .flatten()
    .any(|(base, run)| {
        let Some(&last) = chunks(run, plan.chunk()).last() else {
            return false;
        };
        !dead.contains(&(last / plan.channels))
            && values[base + run - last..base + run].iter().any(|&v| {
                let v = v >> shift;
                v < -over || v >= over
            })
    })
}

/// The smallest nonnegative shift fitting every value in `width` bits.
fn peak_shift(values: &[i64], width: u8) -> i32 {
    let low = values.iter().copied().min().unwrap_or(0);
    let high = values.iter().copied().max().unwrap_or(0);
    let mut shift = 0i32;
    while width_of(low >> shift, high >> shift) > width {
        shift += 1;
    }
    shift
}

/// Widest field a record header can declare, from its four-bit width. Padding stores
/// values wider than they need, which sign-extend back to themselves.
const MAX_STORED_WIDTH: u8 = 16;

/// Narrowest field. Width 2 is the draft the encoder codes everything at before it
/// promotes anything, and a width-1 flag-1 record is the terminator.
const MIN_WIDTH: u8 = 2;

/// Channels one stroke may carry. The terminator states the cell size, and one bit of
/// doubling is all it can say.
const MAX_CHANNELS: usize = 2;

/// Zones one instrument may hold, from the `map` section's single count byte.
const MAX_ZONES: usize = u8::MAX as usize;

/// The widest stroke id a zone record can name: the field is one byte, and zero is
/// not an id the editor issues.
const MAX_STROKE_ID: u32 = u8::MAX as u32;

/// Fields an unlooped stroke carries past the end of its source, every one of which
/// stores zero: the kernel's ring past the last sample is cut, not coded.
const RING_OUT: usize = 127;

/// Fields the stream's opening ramp lasts, per channel: field `f` of each channel is
/// scaled by `(f / RAMP_IN)³`, truncated, until the ramp reaches 1.
/// Inferred from specimens; not confirmed on hardware.
const RAMP_IN: usize = 35;

/// Shortest input the editor encodes: below it, it clamps a project's own extent
/// rather than laying a shorter stream out. The opening, the count laws and the
/// resync are the same object all the way down to it.
pub const MIN_FRAMES: usize = 92;

/// Fields per channel a looped stroke carries past its loop end, repeating the loop's
/// own opening so that playback is unchanged. The mark clears the loop start by the
/// same amount, which is why the loop's length survives it.
const LOOP_LEAD: usize = 5;

/// Fields per channel a loop's marked record clears the **resync point** by, at least.
/// A loop whose ordinary [`LOOP_LEAD`] would land the mark nearer than this is pushed
/// back by repeating more of itself, which moves the whole stream's length with it.
///
/// The floor is on the gap from the resync point, not on the mark's own position and
/// not on the room left between the mark and the run in front of it: a resync run may
/// reach the mark record with nothing between them.
///
/// Inferred from specimens; not confirmed on hardware.
const fn min_resync_gap(layout: Layout) -> usize {
    match layout {
        Layout::V2 => 72,
        Layout::V3 | Layout::V4 => 64,
    }
}

/// Longest input the stroke header's 16-bit word directory can address unambiguously.
const MAX_STREAM_WORDS: usize = WRAP;

/// Backward-difference coefficients for predictor orders 0 to 4.
const DIFFERENCE: [&[i32]; 5] = [
    &[1],
    &[1, -1],
    &[1, -2, 1],
    &[1, -3, 3, -1],
    &[1, -4, 6, -4, 1],
];

/// How content records code their fields.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Predictor {
    /// Store every content field outright at order zero.
    Plain,
    /// Choose the narrowest predictor per cell, the lowest order among equals — the
    /// editor's own choice. Smaller than plain records and exact through this crate's
    /// decoder.
    #[default]
    Minimising,
}

/// A sustain loop, in source frames.
///
/// The container stores a loop as two things and nothing else: the stroke stops at
/// [`end`](Loop::end), and the record the loop starts at carries the mark bit. Loop
/// detune, loop decay, and whether the editor called this a short loop or a long one
/// are not stored anywhere, so a caller that needs them cannot have them.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Loop {
    /// First frame of the loop.
    pub start: usize,
    /// One past its last frame. Audio after it is not encoded.
    pub end: usize,
    /// Frames of the loop's tail that fade into the frames before [`start`](Loop::start).
    /// The fade is applied to the samples here, because that is where the instrument
    /// reads it from. Fractional, because a project can state it as a percentage of the
    /// loop rather than a frame count, and dropping the fraction moves the fade a field.
    /// Inferred from specimens; not confirmed on hardware.
    pub crossfade: f64,
}

impl Loop {
    /// A loop over `start..end` with no crossfade.
    pub fn new(start: usize, end: usize) -> Loop {
        Loop {
            start,
            end,
            crossfade: 0.0,
        }
    }

    pub fn crossfade(mut self, frames: f64) -> Loop {
        self.crossfade = frames;
        self
    }
}

/// What to build around the audio.
#[derive(Debug, Clone)]
pub struct Options {
    name: String,
    root_key: u8,
    top_note: Option<u8>,
    predictor: Predictor,
    loops: Option<Loop>,
    channels: u16,
    secondary_start: Option<f64>,
    shift: Option<u8>,
    layout: Layout,
}

impl Options {
    /// Defaults: the name given, root key C4, the editor's own top note, the editor's
    /// record coding, no loop, the v2 generation.
    pub fn new(name: impl Into<String>) -> Options {
        Options {
            name: name.into(),
            root_key: 60,
            top_note: None,
            predictor: Predictor::default(),
            loops: None,
            channels: 1,
            secondary_start: None,
            shift: None,
            layout: Layout::V2,
        }
    }

    /// Which generation to write: `.nsmp`, `.nsmp3` or `.nsmp4`. The audio is the same
    /// object in all three — what moves is the container and the stream's units.
    pub fn layout(mut self, layout: Layout) -> Options {
        self.layout = layout;
        self
    }

    /// Resynchronise the stream at `frames` source frames from the first one — a
    /// project's `m_startSecondary`, measured from its `m_start`. Unset, the stream
    /// resynchronises where a fresh project would put it: [`default_secondary_start`].
    pub fn secondary_start(mut self, frames: f64) -> Options {
        self.secondary_start = Some(frames);
        self
    }

    /// How many channels the PCM interleaves — 1 or 2. Anything else is refused when
    /// the instrument is built.
    pub fn channels(mut self, channels: u16) -> Options {
        self.channels = channels;
        self
    }

    /// Quantise at `bits` of shift instead of what the shift rule picks. Experimental: a
    /// lever for laying the same stroke out at neighbouring shifts, not a setting the
    /// editor exposes.
    pub fn shift(mut self, bits: u8) -> Options {
        self.shift = Some(bits);
        self
    }

    /// Loop the stroke, which also truncates it at [`Loop::end`].
    pub fn loops(mut self, points: Loop) -> Options {
        self.loops = Some(points);
        self
    }

    /// The MIDI note the sample plays untransposed at.
    pub fn root_key(mut self, note: u8) -> Options {
        self.root_key = note;
        self
    }

    /// The highest note the zone covers. Defaults to two octaves above the root, which
    /// is the layout the editor lays down for a single zone.
    pub fn top_note(mut self, note: u8) -> Options {
        self.top_note = Some(note);
        self
    }

    pub fn predictor(mut self, predictor: Predictor) -> Options {
        self.predictor = predictor;
        self
    }

    fn resolved_top_note(&self) -> u8 {
        self.top_note
            .unwrap_or_else(|| self.root_key.saturating_add(24).min(127))
    }
}

/// Where a loop lands on the field lattice. Every count is in stream fields, so on a
/// stereo stroke each is twice what one channel sees.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Looped {
    /// Field the marked record opens at.
    pub at: usize,
    /// Fields repeated past the loop end, which is also how far `at` clears the loop
    /// start: [`LOOP_LEAD`] per channel, or more when the mark is pushed off the
    /// resync point by [`min_resync_gap`].
    pub lead: usize,
    /// Fields of the loop's tail the crossfade rewrites.
    pub crossfade: usize,
    /// Fields in the 1:1 run the loop opens with.
    pub warmup: usize,
    /// Content cells between that run and the terminator.
    pub cells: usize,
}

/// Stroke landmarks derived from the source frame count.
///
/// Every field count here is a **stream** count: on a stereo stroke the two channels
/// interleave, so each is twice the per-channel number the mono laws state. [`cell`] and
/// [`chunk`] scale with it, which is the whole of what stereo changes about the plan.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Plan {
    /// Which generation's units the stream is written in.
    pub layout: Layout,
    /// Channels interleaved into the stream: 1 or 2.
    pub channels: usize,
    /// Fields in the stream — the source plus a ring-out past its end, or, when the
    /// stroke loops, the source up to the loop end plus the repeated lead.
    pub fields: usize,
    /// Field the resync record starts at.
    pub resync_at: usize,
    /// Fields in the opening 1:1 run.
    pub warmup: usize,
    /// Fields in the resync 1:1 run.
    pub resync: usize,
    /// Content cells between the warmup and the resync.
    pub cells_before: usize,
    /// Content cells between the resync and the loop start, or the terminator.
    pub cells_after: usize,
    /// The loop, once it is on the lattice.
    pub looped: Option<Looped>,
}

impl Plan {
    const fn units(&self) -> Units {
        Units {
            layout: self.layout,
            channels: self.channels,
        }
    }

    /// Fields one content cell covers — the generation's cell per channel.
    pub const fn cell(&self) -> usize {
        self.units().cell()
    }

    /// Fields one 1:1 record covers at most — the generation's RMAX per channel.
    const fn chunk(&self) -> usize {
        self.units().chunk()
    }
}

/// Source frames onto the field lattice.
fn fields_of(frames: usize) -> Option<usize> {
    let frames = u64::try_from(frames).ok()?;
    frames
        .checked_mul(u64::from(PITCH_DEN))
        .and_then(|n| round_ratio(n, u64::from(PITCH_NUM)))
}

/// The same lattice, for a landmark that falls between two frames — a fade a project
/// states as a percentage of its loop rather than as a frame count. Rounding such a
/// value to a whole frame before it reaches the lattice opens the ramp a field early.
fn fields_at(frames: f64) -> Option<usize> {
    let fields = frames * f64::from(PITCH_DEN) / f64::from(PITCH_NUM);
    (fields.is_finite() && (0.0..=f64::from(u32::MAX)).contains(&fields))
        .then_some(fields.round() as usize)
}

impl Plan {
    /// The layout for `frames` source frames of `channels`-channel audio, no loop,
    /// resynchronising at `secondary_start` source frames from the first — the
    /// project's `m_startSecondary` measured from its `m_start`, or
    /// [`default_secondary_start`] for audio no project describes.
    ///
    /// Refuses a secondary start the stream cannot resynchronise at: off the lattice,
    /// or too close to either end for the 1:1 runs around it.
    pub fn new(
        layout: Layout,
        frames: usize,
        channels: usize,
        secondary_start: f64,
    ) -> Result<Plan, Error> {
        Plan::modelled(frames, channels)?;
        let fields = fields_of(frames)
            .and_then(|f| f.checked_add(RING_OUT))
            .and_then(|f| f.checked_mul(channels))
            .ok_or_else(|| size_error(frames))?;
        let resync_at = Plan::resync_at(secondary_start, channels)?;
        Plan::lay_out(layout, frames, channels, fields, None, resync_at)
    }

    /// The layout for a stroke that loops: `frames` source samples truncated at
    /// [`Loop::end`], with the loop's own opening repeated past it, resynchronising at
    /// `secondary_start` as [`new`](Plan::new) does.
    ///
    /// The marked record sits [`LOOP_LEAD`] fields per channel past the loop start, or
    /// [`min_resync_gap`] past the resync point when that is further: a loop starting
    /// near the resync is pushed back, and the stream grows by what it is pushed.
    ///
    /// Refuses a loop the format cannot state — one outside the audio, one shorter than
    /// the run it has to open with, or a crossfade with no material in front of the loop
    /// to fade from — and a secondary start past the loop start, which a project's own
    /// is repaired to never be.
    pub fn looped(
        layout: Layout,
        frames: usize,
        channels: usize,
        points: Loop,
        secondary_start: f64,
    ) -> Result<Plan, Error> {
        Plan::modelled(points.end, channels)?;
        if points.start >= points.end || points.end > frames {
            return Err(ParseError::OutOfBounds {
                value: format!("a loop over frames {}..{}", points.start, points.end),
                bound: format!("a non-empty region of the {frames} frames given"),
            }
            .into());
        }
        // Everything below is laid out per channel and scaled at the end, because that
        // is what the encoder does: one plan, interleaved.
        let lattice = |n: usize| fields_of(n).and_then(|f| f.checked_mul(channels));
        let lattice_at = |n: f64| fields_at(n).and_then(|f| f.checked_mul(channels));
        let start = lattice(points.start).ok_or_else(|| size_error(points.start))?;
        // The loop's length is what has to survive, so it is put on the lattice as a
        // length. Rounding its two ends separately can cost it a field.
        let span = points.end - points.start;
        let length = lattice(span).ok_or_else(|| size_error(points.end))?;
        let end = start
            .checked_add(length)
            .ok_or_else(|| size_error(points.end))?;
        let units = Units { layout, channels };
        let (cell, chunk) = (units.cell(), units.chunk());
        let resync_at = Plan::resync_at(secondary_start, channels)?;
        if resync_at > start {
            return Err(ParseError::OutOfBounds {
                value: format!("a secondary start at field {resync_at}"),
                bound: format!(
                    "field {start}, where the loop starts, or earlier — the marked \
                     record clears the resync point, so the loop cannot open ahead of it"
                ),
            }
            .into());
        }
        // The mark clears the resync point by the generation's floor, so a loop that
        // starts too near it is pushed back by repeating more of itself.
        let at = start
            .checked_add(LOOP_LEAD * channels)
            .zip(resync_at.checked_add(min_resync_gap(layout) * channels))
            .map(|(ideal, floor)| ideal.max(floor))
            .ok_or_else(|| size_error(points.start))?;
        let lead = at - start;
        let fields = end
            .checked_add(lead)
            .ok_or_else(|| size_error(points.end))?;
        let warmup = band(length, cell, chunk);
        if length < warmup.saturating_add(cell) {
            return Err(ParseError::OutOfBounds {
                value: format!("a {length}-field loop"),
                bound: format!(
                    "a loop long enough for the {warmup}-field 1:1 run it opens with and \
                     one {cell}-field cell after it"
                ),
            }
            .into());
        }
        if !(0.0..=points.start as f64).contains(&points.crossfade) {
            return Err(ParseError::OutOfBounds {
                value: format!("a {} frame crossfade", points.crossfade),
                bound: format!(
                    "the {} frames before the loop starts — the fade compares \
                     each frame with the material one loop length behind it",
                    points.start,
                ),
            }
            .into());
        }
        // Put the fade's opening on the loop-relative lattice. Above 100% it begins
        // before the loop start, so its distance is added to the loop length.
        let crossfade = if points.crossfade <= span as f64 {
            let opens =
                lattice_at(span as f64 - points.crossfade).ok_or_else(|| size_error(span))?;
            length.checked_sub(opens).ok_or_else(|| size_error(span))?
        } else {
            let before = lattice_at(points.crossfade - span as f64)
                .ok_or_else(|| size_error(points.start))?;
            length
                .checked_add(before)
                .ok_or_else(|| size_error(points.end))?
        };
        if crossfade > start {
            return Err(ParseError::OutOfBounds {
                value: format!("a {} frame crossfade", points.crossfade),
                bound: format!(
                    "the {} frames before the loop starts — the field lattice \
                     leaves no earlier material to compare",
                    points.start,
                ),
            }
            .into());
        }
        Plan::lay_out(
            layout,
            frames,
            channels,
            fields,
            Some(Looped {
                at,
                lead,
                crossfade,
                warmup,
                cells: (length - warmup) / cell,
            }),
            resync_at,
        )
    }

    /// The secondary start on the lattice — a per-channel position, doubled like every
    /// other landmark when the two channels interleave.
    fn resync_at(secondary_start: f64, channels: usize) -> Result<usize, Error> {
        fields_at(secondary_start)
            .and_then(|f| f.checked_mul(channels))
            .ok_or_else(|| {
                ParseError::OutOfBounds {
                    value: format!("a secondary start at frame {secondary_start}"),
                    bound: "a position on the field lattice".into(),
                }
                .into()
            })
    }

    fn modelled(frames: usize, channels: usize) -> Result<(), Error> {
        if !(1..=MAX_CHANNELS).contains(&channels) {
            return Err(ParseError::OutOfBounds {
                value: format!("{channels} channels"),
                bound: format!(
                    "1 or {MAX_CHANNELS} — the terminator states one cell size, and all \
                     it can say is whether the cell is doubled"
                ),
            }
            .into());
        }
        if frames >= MIN_FRAMES {
            return Ok(());
        }
        Err(ParseError::OutOfBounds {
            value: format!("{frames} frames"),
            bound: format!(
                "the modelled range: at least {MIN_FRAMES} frames, below which the \
                 stream opens a way this crate has not modelled"
            ),
        }
        .into())
    }

    /// Place the warmup, the resync and the cells between them across everything ahead
    /// of the loop — or across the whole stream when there is none.
    fn lay_out(
        layout: Layout,
        frames: usize,
        channels: usize,
        fields: usize,
        looped: Option<Looped>,
        resync_at: usize,
    ) -> Result<Plan, Error> {
        let units = Units { layout, channels };
        if fields > units.max_fields() {
            return Err(size_error(frames).into());
        }
        let (cell, chunk) = (units.cell(), units.chunk());
        let band = |r: usize| band(r, cell, chunk);
        let head = looped.map_or(fields, |l| l.at);
        let warmup = band(resync_at);
        let fits = resync_at >= warmup
            && head
                .checked_sub(warmup)
                .and_then(|rest| resync_at.checked_add(band(rest)))
                .is_some_and(|end| head >= end);
        if !fits {
            return Err(ParseError::OutOfBounds {
                value: format!("a secondary start at field {resync_at}"),
                bound: format!(
                    "the {head} fields ahead of the {}, less the 1:1 run at each end",
                    if looped.is_some() {
                        "loop"
                    } else {
                        "terminator"
                    }
                ),
            }
            .into());
        }
        let resync = band(head - warmup);
        Ok(Plan {
            layout,
            channels,
            fields,
            resync_at,
            warmup,
            resync,
            cells_before: (resync_at - warmup) / cell,
            cells_after: (head - resync_at - resync) / cell,
            looped,
        })
    }
}

/// Where a fresh project would put the resync in `frames` untrimmed source frames: the
/// `m_startSecondary` [`nsmpproj::default_secondary_start`] states, repaired around
/// `loops` the way the editor repairs a project it loads.
pub fn default_secondary_start(frames: usize, loops: Option<Loop>) -> f64 {
    let stop = frames as f64;
    nsmpproj::repaired_secondary_start(
        nsmpproj::default_secondary_start(stop),
        stop,
        loops.map(|l| nsmpproj::repaired_loop_start(l.start as f64)),
    )
}

/// `round(num/den)`, half away from zero, on non-negative integers.
fn round_ratio(num: u64, den: u64) -> Option<usize> {
    num.checked_add(den / 2)
        .and_then(|n| usize::try_from(n / den).ok())
}

/// Frames in interleaved PCM, refusing a buffer that is not whole frames.
fn frames_of(source: &[i16], channels: usize) -> Result<usize, Error> {
    if channels == 0 || !source.len().is_multiple_of(channels) {
        return Err(ParseError::AssertFail(format!(
            "{} sample(s) is not a whole number of {channels}-channel frames",
            source.len()
        ))
        .into());
    }
    Ok(source.len() / channels)
}

fn size_error(frames: usize) -> ParseError {
    ParseError::OutOfBounds {
        value: format!("{frames} frames"),
        bound: format!("audio whose encoded stream fits {MAX_STREAM_WORDS} words"),
    }
}

/// The 1:1 run that preserves a landmark's cell phase — constructive, and the same
/// statement at either channel count.
///
/// A run of `j` records covers between `j*cell` and `j*rmax` fields, so the reachable
/// lengths come in windows with gaps between them: 24..=32, 48..=64, 72..=96 at the mono
/// pair, and everything doubled at the stereo one. `band(r)` is the smallest reachable
/// length at or above `cell` that is congruent to `r`, which at `r ≡ 0` is `cell` itself.
fn band(r: usize, cell: usize, rmax: usize) -> usize {
    let residue = if r.is_multiple_of(cell) {
        cell
    } else {
        r % cell
    };
    let mut length = if residue == cell {
        cell
    } else {
        residue + cell
    };
    // The windows overlap from `j = 3` at 24/32 and from `j = 2` at 32/48, so this
    // settles within a few steps; the bound is a guard, not a limit anything reaches.
    while length <= 64 * cell {
        if (1..=8).any(|j| j * cell <= length && length <= j * rmax) {
            return length;
        }
        length += cell;
    }
    length
}

/// Split a 1:1 run into records of at most `chunk` fields. [`band`] is what guarantees
/// the remainder is a legal record rather than a stub.
fn chunks(mut n: usize, chunk: usize) -> Vec<usize> {
    let mut out = Vec::new();
    while n > chunk {
        out.push(chunk);
        n -= chunk;
    }
    out.push(n);
    out
}

/// The source on the lattice, quantised — the stream's field values and the two
/// header statistics that describe them.
#[derive(Debug, Clone)]
struct Quantised {
    /// One stored value per field, sign-extended and within the stream's maximum width.
    values: Vec<i32>,
    /// Bits the values were shifted right by. Dequantising shifts back.
    shift: i32,
    /// Statistic B: the content field of largest magnitude, taken at a fixed shift of 2.
    /// Carries the extreme's sign where the generation stores one; a magnitude at v2.
    peak: i32,
}

/// Largest magnitude statistic B's 24 bits hold once a sign is allowed for. A field
/// is the source's own 16-bit unit taken at a shift of two, so nothing reaches it.
const MAX_PEAK: i64 = (1 << 23) - 1;

/// The opening ramp: the first [`RAMP_IN`] fields of a channel rise as the cube of
/// their position, toward zero like everything else the encoder quantises.
fn ramp_in(fields: &mut [i64]) {
    let cube = |n: usize| (n * n * n) as i64;
    for (f, value) in fields.iter_mut().enumerate().take(RAMP_IN) {
        *value = *value * cube(f) / cube(RAMP_IN);
    }
}

/// Ramp the loop's tail into the material one loop length behind it, then repeat the
/// loop's opening past its end.
///
/// One channel at a time, so every count here is a per-channel one.
///
/// The ramp is linear across the crossfade, which is what the editor's own crossfade
/// ladder measures out.
///
/// Inferred from specimens; not confirmed on hardware.
fn bake_loop(raw: &mut [i64], at: usize, lead: usize, crossfade: usize) {
    let fields = raw.len();
    let end = fields - lead;
    let length = fields - at;
    let span = crossfade as i64;
    for k in 0..crossfade {
        let f = end - crossfade + k;
        let (near, far) = (raw[f], raw[f - length]);
        let step = (far - near) * k as i64;
        raw[f] = near + (2 * step + span * step.signum()) / (2 * span);
    }
    // The repeated fields are the loop's own opening, so the loop plays the same region
    // however far the mark clears its start.
    for k in 0..lead {
        raw[end + k] = raw[at - lead + k];
    }
}

/// Resample and choose the smallest nonnegative shift that fits the stroke's peak into
/// [`PEAK_WIDTH`] bits, plus the further bit a mono stroke spends when
/// [`spends_extra_bit`] says so. `forced` lays the stroke out at that shift instead.
///
/// Each channel is resampled on its own lattice and the results interleaved, because
/// that is what the stream carries; the shift and statistic B are one pair for the
/// stroke, taken across both.
fn quantise(source: &[i16], plan: &Plan, forced: Option<u8>) -> Quantised {
    let channels = plan.channels;
    let per = plan.fields / channels;
    let mut raw = vec![0i64; plan.fields];
    // The sums each field truncates from. Statistic B ranks fields on these, so two
    // fields that truncate alike still order.
    let mut sums = vec![0f64; plan.fields];
    let mut lane: Vec<i16> = Vec::with_capacity(source.len().div_ceil(channels));
    for channel in 0..channels {
        lane.clear();
        lane.extend(source.iter().skip(channel).step_by(channels).copied());
        let accumulated: Vec<f64> = (0..per).map(|f| kernel::accumulate(&lane, f)).collect();
        let mut fields: Vec<i64> = accumulated.iter().map(|sum| sum.trunc() as i64).collect();
        ramp_in(&mut fields);
        match &plan.looped {
            Some(points) => bake_loop(
                &mut fields,
                points.at / channels,
                points.lead / channels,
                points.crossfade / channels,
            ),
            None => fields[per - RING_OUT..].fill(0),
        }
        for (f, (value, sum)) in fields.into_iter().zip(accumulated).enumerate() {
            let at = f * channels + channel;
            raw[at] = value;
            // A field the ramp, the loop or the ring-out rewrote ranks by what it holds.
            sums[at] = if value == sum.trunc() as i64 {
                sum
            } else {
                value as f64
            };
        }
    }
    let mut shift = peak_shift(&raw, PEAK_WIDTH);
    if spends_extra_bit(&raw, plan) {
        shift += 1;
    }
    if let Some(bits) = forced {
        shift = i32::from(bits);
    }

    // Statistic B is the content field of largest magnitude at a fixed shift of two —
    // a negative extreme therefore rounds away from zero — and a later field takes the
    // extreme only by exceeding it. Content only, which is why a value the 1:1 regime
    // carries never sets it.
    let opening = plan.looped.map(|l| l.at..l.at + l.warmup);
    let content = |f: usize| {
        ((f >= plan.warmup && f < plan.resync_at) || f >= plan.resync_at + plan.resync)
            && !opening.as_ref().is_some_and(|run| run.contains(&f))
    };
    let extreme = (0..plan.fields)
        .filter(|&f| content(f))
        .fold(None, |best: Option<usize>, f| match best {
            Some(b) if sums[f].abs() <= sums[b].abs() => Some(b),
            _ => Some(f),
        });
    let signed = extreme
        .map_or(0, |f| raw[f] >> 2)
        .clamp(-MAX_PEAK - 1, MAX_PEAK) as i32;
    let peak = match plan.layout.signed_peak() {
        true => signed,
        false => signed.abs(),
    };

    Quantised {
        values: raw.iter().map(|&v| (v >> shift) as i32).collect(),
        shift,
        peak,
    }
}

/// Bits a two's-complement field needs to hold everything in `low..=high`, floored at
/// [`MIN_WIDTH`].
fn width_of(low: i64, high: i64) -> u8 {
    let mut w = MIN_WIDTH;
    while i128::from(low) < -(1i128 << (w - 1)) || i128::from(high) > (1i128 << (w - 1)) - 1 {
        w += 1;
    }
    w
}

/// One record, before it becomes words.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Spec {
    one_to_one: bool,
    width: u8,
    order: u8,
    /// Set on the record a loop starts at, and on no other.
    mark: bool,
    first: usize,
    count: usize,
}

impl Spec {
    /// Words this record occupies, header included.
    fn span(&self, units: Units) -> usize {
        units.span(self.count, self.width)
    }
}

/// The Nth backward difference at `at`, across record boundaries.
///
/// ⚠️ **`stride` is the channel count**: the predictor runs per channel, so a stereo
/// field differences against the field two slots back, not the other channel's.
fn residual(values: &[i32], at: usize, order: u8, stride: usize) -> i64 {
    DIFFERENCE[usize::from(order)]
        .iter()
        .enumerate()
        .map(|(j, &c)| match at.checked_sub(j * stride) {
            Some(k) => i64::from(c) * i64::from(values[k]),
            None => 0,
        })
        .sum()
}

/// The width one cell needs at `order`, and the sum of the residuals it would store.
/// One cell is `stride` channels' worth, and a record declares one width for both.
fn width_at(values: &[i32], first: usize, order: u8, cell: usize, stride: usize) -> u8 {
    let mut low = 0i64;
    let mut high = 0i64;
    for at in first..first + cell {
        let e = residual(values, at, order, stride);
        low = low.min(e);
        high = high.max(e);
    }
    width_of(low, high)
}

/// The width each predictor order codes one cell at, indexed by order — order 0 alone
/// under [`Predictor::Plain`].
fn widths_at(
    values: &[i32],
    first: usize,
    predictor: Predictor,
    cell: usize,
    stride: usize,
) -> Vec<u8> {
    let orders = match predictor {
        Predictor::Plain => 1,
        Predictor::Minimising => DIFFERENCE.len(),
    };
    (0..orders as u8)
        .map(|order| width_at(values, first, order, cell, stride))
        .collect()
}

/// The order and width a cell is coded at, given the widths each order needs: the
/// record being extended, `(order, width)`, keeps its order while the cell's narrowest
/// width is still the record's and that order still reaches it; otherwise the lowest
/// order that reaches the narrowest width.
fn choose_order(widths: &[u8], extending: Option<(u8, u8)>) -> (u8, u8) {
    let narrowest = *widths.iter().min().unwrap_or(&MIN_WIDTH);
    let reaches = |order: u8| widths.get(usize::from(order)) == Some(&narrowest);
    let order = extending
        .filter(|&(order, width)| width == narrowest && reaches(order))
        .map_or_else(
            || (0..widths.len() as u8).find(|&o| reaches(o)).unwrap_or(0),
            |(order, _)| order,
        );
    (order, narrowest)
}

/// Partition 1:1 values and like-coded content cells into records, with the index of
/// the record the resync run opens at — what the header's second pointer names.
///
/// A loop appends a third regime — its own 1:1 run, marked, and the content after it —
/// grown to a whole number of packets by [`pad_to_packet`].
fn records(values: &[i32], plan: &Plan, predictor: Predictor) -> Result<(Vec<Spec>, usize), Error> {
    let mut out = Vec::new();
    let mut at = 0usize;
    let (cell, chunk, stride) = (plan.cell(), plan.chunk(), plan.channels);

    let one_to_one = |out: &mut Vec<Spec>, at: &mut usize, fields: usize| {
        for count in chunks(fields, chunk) {
            let mut low = 0i64;
            let mut high = 0i64;
            for &v in &values[*at..*at + count] {
                low = low.min(i64::from(v));
                high = high.max(i64::from(v));
            }
            out.push(Spec {
                one_to_one: true,
                width: width_of(low, high),
                order: 0,
                mark: false,
                first: *at,
                count,
            });
            *at += count;
        }
    };

    // A record runs on while each cell's narrowest width is still the record's and the
    // record's own order still reaches it; the first cell that breaks either opens a new
    // record at the lowest order that reaches its width.
    let content = |out: &mut Vec<Spec>, at: &mut usize, cells: usize| {
        let mut run: Option<Spec> = None;
        for index in 0..cells {
            let first = *at + index * cell;
            let widths = widths_at(values, first, predictor, cell, stride);
            let (order, width) = choose_order(&widths, run.map(|r| (r.order, r.width)));
            match run {
                Some(ref mut record)
                    if (record.order, record.width) == (order, width)
                        && record.count + cell <= MAX_COUNT =>
                {
                    record.count += cell;
                }
                _ => {
                    out.extend(run.take());
                    run = Some(Spec {
                        one_to_one: false,
                        width,
                        order,
                        mark: false,
                        first,
                        count: cell,
                    });
                }
            }
        }
        out.extend(run);
        *at += cells * cell;
    };

    one_to_one(&mut out, &mut at, plan.warmup);
    content(&mut out, &mut at, plan.cells_before);
    let resync_record = out.len();
    one_to_one(&mut out, &mut at, plan.resync);
    content(&mut out, &mut at, plan.cells_after);
    if let Some(points) = &plan.looped {
        let opening = out.len();
        one_to_one(&mut out, &mut at, points.warmup);
        out[opening].mark = true;
        content(&mut out, &mut at, points.cells);
        pad_to_packet(&mut out, opening, plan.units())?;
    }
    if at != plan.fields {
        return Err(ParseError::AssertFail(format!(
            "the record plan covered {at} of {} fields",
            plan.fields
        ))
        .into());
    }
    Ok((out, resync_record))
}

/// Pad the loop region out to whole packets: sweep its content records front to back,
/// halving each one that covers more than one cell — the smaller half first — and
/// carrying on into the second half, pass after pass, until the words fit.
///
/// A region with nothing left to split is widened instead, front to back, spending
/// each content record up to [`widen_cap`] before moving on, so the last one widened
/// takes only the words still owed. A 1:1 record is walked past by either sweep,
/// whatever room it has, the marked one the region opens at included.
///
/// Inferred from specimens; not confirmed on hardware.
fn pad_to_packet(specs: &mut Vec<Spec>, opening: usize, units: Units) -> Result<(), Error> {
    let cell = units.cell();
    let packet = units.packet_words();
    let words = |specs: &[Spec]| specs.iter().map(|s| s.span(units)).sum::<usize>();
    let mut pad = (packet - words(&specs[opening..]) % packet) % packet;

    let splittable = |spec: &Spec| !spec.one_to_one && spec.count > cell;
    while pad > 0 && specs[opening..].iter().any(splittable) {
        let mut at = opening;
        while pad > 0 && at < specs.len() {
            let spec = specs[at];
            if splittable(&spec) {
                let head = spec.count / cell / 2 * cell;
                specs[at].count = head;
                specs.insert(
                    at + 1,
                    Spec {
                        first: spec.first + head,
                        count: spec.count - head,
                        ..spec
                    },
                );
                pad -= 1;
            }
            at += 1;
        }
    }

    let cap = widen_cap(units.layout);
    for spec in specs[opening..].iter_mut() {
        if pad == 0 {
            break;
        }
        if spec.one_to_one {
            continue;
        }
        let count = spec.count;
        let step = |width: u8| units.span(count, width + 1) - units.span(count, width);
        while spec.width < cap && step(spec.width) <= pad {
            pad -= step(spec.width);
            spec.width += 1;
        }
    }
    if pad > 0 {
        return Err(ParseError::OutOfBounds {
            value: format!("a loop of {} record(s)", specs.len() - opening),
            bound: format!(
                "a loop with {pad} more word(s) of room in it — the encoded loop has to \
                 be whole packets long, and no record of this one may be widened past \
                 {cap}"
            ),
        }
        .into());
    }
    Ok(())
}

/// Widest the padding sweep writes a content record at, per generation. It is the
/// generation's own constant and not a property of the region: a record already one
/// width under the cap is still widened past itself, up to the cap, and a record
/// holding room under the cap is never left unspent.
///
/// v4 stops one width above the narrow chain and v3, so this is a table rather than a
/// constant. Nothing derives one entry from another.
///
/// Inferred from specimens; not confirmed on hardware.
const fn widen_cap(layout: Layout) -> u8 {
    match layout {
        Layout::V2 | Layout::V3 => 13,
        Layout::V4 => 14,
    }
}

/// A packed stroke stream: the words, and where the header's directory points.
struct Stream {
    words: Vec<u8>,
    first_record: usize,
    resync: usize,
    /// The marked record a loop starts at, when the stroke loops.
    mark: Option<usize>,
    terminator: usize,
}

/// Right-align records in the allocation the preamble law gives this stroke:
/// `preamble` bytes of payload, then whole packets until the chain fits.
///
/// `preamble` is [`stroke::header_len`](super::stroke::header_len), which a zone table
/// can drive below the stroke header — the first packet then starts inside what would
/// otherwise be header, and the loop repays the difference.
fn pack(
    specs: &[Spec],
    values: &[i32],
    resync_record: usize,
    preamble: usize,
    plan: &Plan,
) -> Result<Stream, Error> {
    let units = plan.units();
    let (word, header) = (units.word(), plan.layout.header_len());
    let chain: usize = specs.iter().map(|s| s.span(units)).sum::<usize>() + 1;
    let need = (chain + units.min_lead())
        .checked_mul(word)
        .and_then(|bytes| bytes.checked_add(header))
        .ok_or_else(|| ParseError::OutOfBounds {
            value: format!("a chain of {chain} words"),
            bound: "a stroke payload of addressable length".into(),
        })?;
    let mut payload = preamble;
    while payload < need {
        payload += packet_len(plan.layout);
    }
    if !(payload - header).is_multiple_of(word) {
        return Err(ParseError::AssertFail(format!(
            "a {preamble}-byte preamble puts the word stream off a word boundary; the \
             sections in front of the stroke are not whole words"
        ))
        .into());
    }
    let total = (payload - header) / word;
    if total > MAX_STREAM_WORDS {
        return Err(ParseError::OutOfBounds {
            value: format!("a stream of {total} words"),
            bound: format!(
                "{MAX_STREAM_WORDS} words, the reach of the stroke header's 16-bit word \
                 directory"
            ),
        }
        .into());
    }

    let mut words = vec![0u8; total * word];
    let lead = total - chain;
    let mut at = lead;
    let mut resync = lead;
    let mut mark = None;
    for (index, spec) in specs.iter().enumerate() {
        if index == resync_record {
            resync = at;
        }
        if spec.mark {
            mark = Some(at);
        }
        write_record(&mut words, at, spec, values, units);
        at += spec.span(units);
    }
    // The terminator states the cell size, which is what says how many channels the
    // stroke carries: twice the layout's cell and a reader de-interleaves.
    if at.checked_add(1) != Some(total) {
        return Err(ParseError::AssertFail(format!(
            "the record chain ended at word {at} of {total}"
        ))
        .into());
    }
    let terminator = (1u32 << 23) | plan.cell() as u32;
    words[at * word..(at + 1) * word].copy_from_slice(&terminator.to_be_bytes()[4 - word..]);

    Ok(Stream {
        words,
        first_record: lead,
        resync,
        mark,
        terminator: at,
    })
}

/// Writes one record: its header word, then its fields, which start at the first bit
/// after it. Any alignment tail is left zero at the end of the segment.
///
/// v2 and v3 store a stereo stroke's channels as **alternating fields**, which is the
/// order `values` is already in, so the fields go down in stream order; v4 gives each
/// channel its own word stream and alternates the words, so its halves are packed
/// apart and then interleaved. Only the residual's reach moves with the channel count.
fn write_record(words: &mut [u8], at: usize, spec: &Spec, values: &[i32], units: Units) {
    let (word, bits) = (units.word(), units.word_bits());
    let head = (u32::from(spec.one_to_one) << 23)
        | (u32::from(spec.width - 1) << 19)
        | (u32::from(spec.mark) << 18)
        | (u32::from(spec.order) << 14)
        | spec.count as u32;
    words[at * word..(at + 1) * word].copy_from_slice(&head.to_be_bytes()[4 - word..]);

    let stored = |k: usize| -> u64 {
        let value = residual(values, spec.first + k, spec.order, units.channels);
        (value as u64) & ((1u64 << spec.width) - 1)
    };
    let put = |words: &mut [u8], mut bit: usize, raw: u64| {
        for b in (0..spec.width).rev() {
            if raw >> b & 1 != 0 {
                words[bit / 8] |= 1 << (7 - bit % 8);
            }
            bit += 1;
        }
    };

    if !units.splits() {
        for k in 0..spec.count {
            put(
                words,
                (at + 1) * bits + k * usize::from(spec.width),
                stored(k),
            );
        }
        return;
    }
    // Each channel is packed into its own contiguous words first, because the two
    // halves are padded apart; the words then alternate from the header on.
    let per = spec.count / 2;
    let half = units.half(spec.count, spec.width);
    let mut packed = vec![0u8; half * word];
    for channel in 0..2 {
        packed.fill(0);
        for k in 0..per {
            put(
                &mut packed,
                k * usize::from(spec.width),
                stored(2 * k + channel),
            );
        }
        for w in 0..half {
            let to = (at + 1 + 2 * w + channel) * word;
            words[to..to + word].copy_from_slice(&packed[w * word..(w + 1) * word]);
        }
    }
}

/// Encode `A = gain · 2^(41+s)/peak` as `(mantissa, exponent)`: the exponent carries the
/// quantiser shift, the mantissa is `1/peak` to 20 bits scaled by the zone's gain
/// ([`zone::GAIN_UNITY`](super::zone::GAIN_UNITY) is 1.0). The reciprocal is held as a
/// 24-bit fraction in `[½, 1)` — three bits finer than the mantissa — before the gain
/// multiplies it, and one floor follows; the mantissa leaves its normalised range
/// freely in either direction, and the exponent never moves with it.
///
/// ⚠️ **`gain` is the decibel field's round trip, not the project's own float.** The
/// two agree below `2^24` and part above it, where the mantissa wraps into its field
/// and the file states a level far quieter than the project asked for. That is what
/// the instrument plays; a caller that means to warn about it owns the warning.
///
/// ⚠️ **`peak` is the file's, not the stroke's.** Every stroke of a multi-zone
/// instrument reciprocates the largest statistic B in the file; only the shift and the
/// zone's own gain are the stroke's. Reciprocating each stroke's own peak instead
/// leaves every zone but the loudest playing at the wrong level.
fn statistic_a(peak: u32, shift: i32, gain: u64) -> (u32, u8) {
    let peak = u64::from(peak.max(1));
    let bits = 64 - peak.leading_zeros() as i32;
    let exact_power = i32::from(peak.is_power_of_two());
    let reciprocal = (1u64 << (21 + bits + (1 - exact_power))) / peak;
    let mantissa = (reciprocal * gain) >> (super::zone::GAIN_BITS + 3);
    (
        (mantissa % (1 << 24)) as u32,
        (22 + shift - bits + exact_power) as u8,
    )
}

/// Build the fixed header and its body-relative, wrapping word directory.
fn stroke_header(
    layout: Layout,
    zone: &NewZone<'_>,
    encoded: &Encoded,
    body_at: usize,
    file_peak: u32,
) -> Vec<u8> {
    let (q, stream) = (&encoded.q, &encoded.stream);
    let mut head = vec![0u8; layout.header_len()];
    head[0..4].copy_from_slice(&zone.global_id.to_be_bytes());
    head[super::stroke::ROOT_KEY] = zone.root_key;
    // Unexplained: real programs hold this, and the panel cannot produce it.
    head[6..8].copy_from_slice(&[0x88, 0xba]);
    // The channel count, stated a second time — the terminator's cell size says it too,
    // and a reader takes the terminator because that is what the record sizes follow.
    head[8] = zone.channels as u8;

    let (mantissa, exponent) =
        statistic_a(file_peak, q.shift, gain_units(gain_decibels(zone.gain)));
    head[codec::MANTISSA_AT..codec::MANTISSA_AT + 3].copy_from_slice(&mantissa.to_be_bytes()[1..]);
    head[codec::STAT_A_EXP_AT] = exponent;
    head[codec::PEAK_AT..codec::PEAK_AT + 3].copy_from_slice(&(q.peak as u32).to_be_bytes()[1..]);

    let base = (body_at + layout.header_len()) / layout.word() % WRAP;
    let pointer = |word: usize| ((base + word) % WRAP) as u16;
    // The third pointer names the loop's marked record; aimed at the terminator it says
    // the stroke does not loop.
    let directory = [
        pointer(stream.first_record),
        pointer(stream.resync),
        pointer(stream.mark.unwrap_or(stream.terminator)),
        pointer(stream.terminator),
    ];
    for (i, p) in directory.iter().enumerate() {
        let at = codec::SEEK_AT + codec::SEEK_STRIDE * i;
        head[at..at + 2].copy_from_slice(&p.to_be_bytes());
        // Unexplained: real programs hold this, and the panel cannot produce it.
        if i < 3 {
            head[at + 2] = 0x80;
        }
    }
    // The wide header's two float32 tails; the narrow header is too short to hold them.
    let tails = [gain_decibels(zone.gain), zone.loop_decay];
    for (at, value) in codec::TAIL_FLOATS_AT.iter().zip(tails) {
        if let Some(slot) = head.get_mut(*at..at + 4) {
            slot.copy_from_slice(&value.to_be_bytes());
        }
    }
    head
}

/// The loop decay amount a project carries until something sets one.
pub const DEFAULT_LOOP_DECAY: f32 = 20.0;

/// One zone's stream, and the quantiser statistics describing it.
///
/// A stroke header cannot be written until every zone is here: statistic A
/// reciprocates the file's peak, so the last zone's audio decides the first zone's
/// header.
struct Encoded {
    q: Quantised,
    stream: Stream,
}

/// Lay out and pack one zone's stream, into `preamble` bytes plus whole packets.
fn encode_stroke(
    layout: Layout,
    zone: &NewZone<'_>,
    preamble: usize,
    predictor: Predictor,
) -> Result<Encoded, Error> {
    let channels = usize::from(zone.channels);
    let frames = frames_of(zone.source, channels)?;
    let plan = match zone.loops {
        Some(points) => Plan::looped(layout, frames, channels, points, zone.secondary_start)?,
        None => Plan::new(layout, frames, channels, zone.secondary_start)?,
    };
    if let Some(bits) = zone.shift {
        if i32::from(bits) > codec::SHIFT_LIMIT {
            return Err(ParseError::OutOfBounds {
                value: format!("a quantiser shift of {bits} bits"),
                bound: format!("0 through {} bits", codec::SHIFT_LIMIT),
            }
            .into());
        }
    }
    let q = quantise(zone.source, &plan, zone.shift);
    let low = q.values.iter().copied().min().unwrap_or(0);
    let high = q.values.iter().copied().max().unwrap_or(0);
    if width_of(i64::from(low), i64::from(high)) > MAX_STORED_WIDTH {
        return Err(ParseError::OutOfBounds {
            value: format!(
                "a quantiser shift of {} bits for fields spanning {low}..={high}",
                q.shift
            ),
            bound: format!("values that fit the stream's {MAX_STORED_WIDTH}-bit fields"),
        }
        .into());
    }
    let (specs, resync_record) = records(&q.values, &plan, predictor)?;
    let stream = pack(&specs, &q.values, resync_record, preamble, &plan)?;
    Ok(Encoded { q, stream })
}

/// Every zone's stream in order, and the peak each of their headers reciprocates.
fn encode_strokes(
    layout: Layout,
    zones: &[NewZone<'_>],
    predictor: Predictor,
    cat_len: usize,
    map_len: usize,
) -> Result<(Vec<Encoded>, u32), Error> {
    let encoded = zones
        .iter()
        .enumerate()
        .map(|(index, zone)| {
            let chain = super::Chain::written_for(layout);
            let preamble = super::stroke::header_len(layout, chain, index, cat_len, map_len);
            encode_stroke(layout, zone, preamble, predictor)
        })
        .collect::<Result<Vec<_>, Error>>()?;
    let peak = encoded
        .iter()
        .map(|e| e.q.peak.unsigned_abs())
        .max()
        .unwrap_or(1);
    Ok((encoded, peak))
}

/// One zone's `stk` payload at body offset `body_at`.
///
/// `body_at` comes from the sections already sized in front of this stroke, so only
/// the chain builders can supply it: it is the base the word directory is written
/// against, and a wrong one produces a file whose directory names records that are
/// not there.
fn stroke_payload(
    layout: Layout,
    zone: &NewZone<'_>,
    encoded: &Encoded,
    body_at: usize,
    file_peak: u32,
) -> Result<Vec<u8>, Error> {
    midi_note("root key", zone.root_key)?;
    body_at
        .checked_add(layout.header_len())
        .ok_or_else(|| ParseError::OutOfBounds {
            value: format!("body offset {body_at}"),
            bound: "an addressable stroke header".into(),
        })?;
    let mut payload = stroke_header(layout, zone, encoded, body_at, file_peak);
    payload.extend_from_slice(&encoded.stream.words);
    Ok(payload)
}

/// Section schema versions the narrow chain writes. They track the section's own
/// schema rather than the content version.
const HDR_VERSION: u8 = 9;
const CAT_VERSION: u8 = 5;
const STK_VERSION: u8 = 9;
const STY_VERSION: u8 = 5;
const CONTAINER_VERSION: u8 = 11;

/// The category every chain's `cat` section opens with.
/// Unexplained: real programs hold this, and the panel cannot produce it.
const CATEGORY: u8 = 0x0f;

/// The `hdr` section: a fixed prefix, then the instrument name NUL-padded.
fn hdr(name: &str) -> Result<Section, Error> {
    let mut payload = vec![0u8; 111];
    // Unexplained: real programs hold this, and the panel cannot produce it.
    payload[0..6].copy_from_slice(&[0x00, 0x01, 0xb4, 0x00, 0x06, 0x50]);
    super::StringField::NAME.write(&mut payload, name)?;
    Ok(Section {
        tag: *section::HDR,
        version: HDR_VERSION,
        payload,
    })
}

/// The `cat` section: a short prefix and two length-prefixed labels.
fn cat() -> Section {
    let mut payload = vec![CATEGORY, 0x00, 0x00, 0x00, 0x01];
    for label in [&b"Production"[..], &b"Origin"[..]] {
        payload.push(label.len() as u8);
        payload.extend_from_slice(label);
    }
    // Every section payload is a whole number of 24-bit words; the labels are
    // padded out to one.
    while !payload.len().is_multiple_of(3) {
        payload.push(0);
    }
    Section {
        tag: *section::CAT,
        version: CAT_VERSION,
        payload,
    }
}

/// Build a neutral keyboard map — unity gain and no detune at every key —
/// and the zone table behind it.
///
/// `zones` is one record per zone, already high to low.
fn map(map_gain: u32, zones: &[ZoneRecord]) -> Result<Section, Error> {
    let mut payload = vec![0u8; super::zone::RECORDS_AT + super::zone::RECORD_LEN * zones.len()];
    let mut keys = super::keymap::KeyTable::NEUTRAL;
    keys.instrument = super::keymap::Level::new(map_gain, 0)?;
    payload[..super::zone::COUNT_AT].copy_from_slice(&keys.prefix());
    payload[super::zone::COUNT_AT] = zones.len() as u8;
    // Zones are stored high to low by top note.
    for (index, record) in zones.iter().enumerate() {
        let at = super::zone::RECORDS_AT + super::zone::RECORD_LEN * index;
        payload[at + 2] = record.id;
        // Nothing here says whether the zone loops: a zone record is byte-identical
        // either way, and the loop lives in the stroke's own word directory.
        payload[at + 3..at + 6].copy_from_slice(&record.gain.to_be_bytes()[1..]);
        payload[at + 9] = record.top_note;
        // One sample in the zone, so the playing stroke sits at the bottom of the
        // strength axis. A stack positions its enabled stroke higher; nothing the
        // builder produces has one.
        payload[at + 10..at + 12].copy_from_slice(&super::zone::REL_STRENGTH_DEFAULT.to_be_bytes());
    }
    Ok(Section {
        tag: *section::MAP,
        version: super::keymap::VERSION,
        payload,
    })
}

/// The narrow `sty` preset, including every project value its schema stores.
fn sty(preset: Preset) -> Result<Section, Error> {
    if preset.velocity_to_amplitude >= super::sty::VELOCITY_LEVELS
        || preset.velocity_to_timbre >= super::sty::VELOCITY_LEVELS
    {
        return Err(ParseError::OutOfBounds {
            value: format!(
                "velocity levels {} and {}",
                preset.velocity_to_amplitude, preset.velocity_to_timbre
            ),
            bound: format!("levels below {}", super::sty::VELOCITY_LEVELS),
        }
        .into());
    }
    let mut payload = vec![0x00, 0x01, 0x00, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00];
    payload[3] = u8::from(preset.dynamics_enabled);
    payload[4] = preset.velocity_to_amplitude;
    payload[5] = preset.velocity_to_timbre;
    Ok(Section {
        tag: *section::STY,
        version: STY_VERSION,
        payload,
    })
}

/// Everything a `.nsmp3` chain and a `.nsmp4` chain do not share.
///
/// The section versions track their own schemas, so they move independently of the
/// content version and of each other. The payloads named here are constant across
/// every render of a project that does not reach them.
///
/// Inferred from specimens; not confirmed on hardware.
struct WideSchema {
    container: u32,
    /// The `NSMP` payload. Constant per generation and unrelated to the stroke count.
    /// Unexplained: real programs hold this, and the panel cannot produce it.
    container_payload: [u8; 4],
    hdr: u32,
    map: u32,
    /// Bytes one per-key record takes: the level alone, or the level and the partner
    /// quad the wider schema puts behind it.
    key_stride: usize,
    /// The unexplained run between the per-key table and the zone count.
    map_gap: &'static [u8],
    /// The unexplained run behind the last zone record.
    map_tail: &'static [u8],
    sty: u32,
    /// The preset a project that touches none renders as.
    /// Unexplained: real programs hold this, and the panel cannot produce it.
    sty_payload: &'static [u8],
    /// Where the category's dynamics curve writes into that payload, and what.
    sty_dynamics: &'static [(usize, u8)],
}

/// One gain-and-detune unit at `gain`, with no detune. It opens the `map` section as
/// the instrument's own level and then repeats once per key.
fn level(gain: u32) -> [u8; super::keymap::RECORD_LEN] {
    let mut out = [0u8; super::keymap::RECORD_LEN];
    out[..3].copy_from_slice(&gain.to_be_bytes()[1..]);
    out
}

const STY_V3_PAYLOAD: [u8; super::sty::V3_LEN] = [
    0x00, 0x00, 0x7f, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x7f, 0x00, 0x02, 0x00,
    0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00,
];

const STY_V4_PAYLOAD: [u8; super::sty::V4_LEN_LONG] = [
    0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e,
    0x1e, 0x1e, 0x00, 0x00, 0x00, 0x7f, 0x7f, 0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00,
    0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
];

const STY_V3_DYNAMICS: [(usize, u8); 4] = [(4, 43), (12, 74), (14, 1), (16, 74)];
const STY_V4_DYNAMICS: [(usize, u8); 5] = [(3, 1), (4, 1), (85, 74), (86, 82), (87, 90)];

/// The schema for a wide generation, `None` for the narrow chain.
fn wide_schema(layout: Layout) -> Option<WideSchema> {
    match layout {
        Layout::V2 => None,
        Layout::V3 => Some(WideSchema {
            container: 30,
            container_payload: [0x00, 0x02, 0x00, 0x0c],
            hdr: 10,
            map: 14,
            key_stride: super::keymap::RECORD_LEN,
            map_gap: &[],
            map_tail: &[0x00],
            sty: super::sty::VERSION_V3,
            sty_payload: &STY_V3_PAYLOAD,
            sty_dynamics: &STY_V3_DYNAMICS,
        }),
        Layout::V4 => Some(WideSchema {
            container: 40,
            container_payload: [0x00, 0x02, 0x00, 0x05],
            hdr: 11,
            map: 21,
            key_stride: super::keymap::RECORD_LEN + 4,
            map_gap: &[
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
                0x02, 0x02, 0x02, 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x10, 0x00, 0x00, 0x10, 0x00,
                0x00, 0x00, 0x00,
            ],
            map_tail: &[0x00, 0x00, 0x00, 0x01, 0x00, 0x00],
            sty: super::sty::VERSION_V4,
            sty_payload: &STY_V4_PAYLOAD,
            sty_dynamics: &STY_V4_DYNAMICS,
        }),
    }
}

/// The wide `hdr` section: the same prefix at a wider name field, with the sub-name
/// the vendor's filenames append left empty.
fn hdr4(schema: &WideSchema, name: &str) -> Result<Section4, Error> {
    let mut payload = vec![0u8; 112];
    // Unexplained: real programs hold this, and the panel cannot produce it.
    payload[4..6].copy_from_slice(&[0x06, 0x50]);
    super::StringField::NAME_V3.write(&mut payload, name)?;
    Ok(Section4 {
        tag: *section::HDR4,
        version: schema.hdr,
        payload,
    })
}

/// The wide `cat` section: the category alone, where the narrow chain also spells
/// out its labels.
fn cat4() -> Section4 {
    let mut payload = vec![0u8; 8];
    payload[0] = CATEGORY;
    Section4 {
        tag: *section::CAT4,
        version: 7,
        payload,
    }
}

/// The wide `map` section: a per-key table at unity gain and no detune, then the
/// zone records behind their count.
///
/// The wider schema's per-key record carries a partner quad as well as the level.
/// The editor writes the identity there whatever the zone layout — only the vendor's
/// own builder fills it in — so every quad names its own key.
fn map4(schema: &WideSchema, map_gain: u32, zones: &[WideZoneRecord]) -> Section4 {
    let mut payload = Vec::with_capacity(
        super::keymap::RECORD_LEN
            + super::keymap::KEYS * schema.key_stride
            + schema.map_gap.len()
            + 1
            + super::zone::WIDE_RECORD_LEN * zones.len()
            + schema.map_tail.len(),
    );
    payload.extend_from_slice(&level(map_gain));
    for key in 0..super::keymap::KEYS as u8 {
        payload.extend_from_slice(&level(super::zone::GAIN_UNITY));
        payload.extend(std::iter::repeat_n(
            key,
            schema.key_stride - super::keymap::RECORD_LEN,
        ));
    }
    payload.extend_from_slice(schema.map_gap);
    payload.push(zones.len() as u8);
    for record in zones {
        payload.extend_from_slice(&record.bytes());
    }
    payload.extend_from_slice(schema.map_tail);
    Section4 {
        tag: *section::MAP4,
        version: schema.map,
        payload,
    }
}

/// The wide `sty` preset, including the dynamics group a project controls.
fn sty4(schema: &WideSchema, preset: Preset) -> Section4 {
    let mut payload = schema.sty_payload.to_vec();
    if preset.dynamics_enabled {
        for &(at, value) in schema.sty_dynamics {
            payload[at] = value;
        }
    }
    Section4 {
        tag: *section::STY4,
        version: schema.sty,
        payload,
    }
}

/// The `meta` section: the length of everything ahead of it, which is the only place
/// a wide file states its own size.
fn meta4(chain_len: usize) -> Section4 {
    let mut payload = vec![0u8; super::meta::LEN];
    payload[0..2].copy_from_slice(&2u16.to_be_bytes());
    payload[2..6].copy_from_slice(&(chain_len as u32).to_be_bytes());
    Section4 {
        tag: *section::META4,
        version: super::meta::VERSION,
        payload,
    }
}

/// One zone to build: its audio, where it sits on the keyboard, and the id its
/// record names its stroke by.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct NewZone<'a> {
    /// PCM at [`codec::SOURCE_RATE`], already trimmed to what the zone plays and
    /// **interleaved** when it has more than one channel.
    pub source: &'a [i16],
    /// Channels [`source`](NewZone::source) interleaves: 1 or 2.
    pub channels: u16,
    /// The note this sample plays untransposed at.
    pub root_key: u8,
    /// Highest note this zone answers to. Stored as given — the file keeps top notes,
    /// it does not derive them from the root keys.
    pub top_note: u8,
    /// The stroke's global id, 1 through [`MAX_STROKE_ID`]. Zones name their strokes
    /// by it rather than by position, so it need not run parallel to the sections.
    pub global_id: u32,
    /// The zone's sustain loop, which truncates its audio at [`Loop::end`].
    pub loops: Option<Loop>,
    /// Where the stream resynchronises: the project's `m_startSecondary` in source
    /// frames from the first frame of [`source`](NewZone::source), after the repair
    /// the editor applies on load ([`nsmpproj::Stroke::encoded_secondary_start`]).
    pub secondary_start: f64,
    /// Quantiser shift to lay the stroke out at instead of the rule's choice, or `None`
    /// for the rule. Experimental — see [`Options::shift`].
    pub shift: Option<u8>,
    /// The stroke's loop decay amount — a project's `m_loopDecay` — in the project's
    /// own units, [`DEFAULT_LOOP_DECAY`] until something sets one.
    ///
    /// ⚠️ A wide stroke header carries it whether or not the stroke loops and whether
    /// or not the decay is switched on; nothing in the file says which. The narrow
    /// chain drops the field altogether.
    pub loop_decay: f32,
    /// Playback gain as a linear ratio, 1.0 for unity, below [`MAX_ZONE_GAIN`]. Not
    /// applied to the audio: the instrument applies it when it plays.
    ///
    /// Where it is stored moves with the generation, and the stroke's statistic A
    /// carries it in every one. The narrow zone record holds it linearly to 20
    /// fractional bits; a wide stroke header holds `20·log10(gain)` as a float32 and
    /// no byte of a wide zone record moves with it.
    pub gain: f64,
}

/// Build a one-zone instrument from PCM at [`codec::SOURCE_RATE`], mono or stereo
/// interleaved per [`Options::channels`], in the generation [`Options::layout`] names.
/// Refuses unmodelled lengths, invalid metadata, and streams past the directory limit.
pub fn instrument(source: &[i16], options: &Options) -> Result<crate::Sample, Error> {
    midi_note("root key", options.root_key)?;
    let frames = frames_of(source, usize::from(options.channels))?;
    let secondary_start = options
        .secondary_start
        .unwrap_or_else(|| default_secondary_start(frames, options.loops));
    multi_zone(
        Instrument {
            name: &options.name,
            map_gain: 1.0,
            predictor: options.predictor,
            layout: options.layout,
            preset: Preset::default(),
        },
        &[NewZone {
            source,
            channels: options.channels,
            root_key: options.root_key,
            top_note: options.resolved_top_note(),
            global_id: 1,
            loops: options.loops,
            secondary_start,
            shift: options.shift,
            gain: 1.0,
            loop_decay: DEFAULT_LOOP_DECAY,
        }],
    )
}

/// Everything an instrument states apart from its zones.
#[derive(Debug, Clone, Copy)]
pub struct Instrument<'a> {
    /// The name the `hdr` section carries.
    pub name: &'a str,
    /// The instrument's own playing gain, a linear ratio on top of every zone's. It
    /// opens the `map` section in all three generations, and it is the one gain field
    /// that clamps: [`MAX_MAP_GAIN_DB`] and no higher, whatever the caller asks for.
    pub map_gain: f64,
    /// How content records code their fields.
    pub predictor: Predictor,
    /// Which generation to write: `.nsmp`, `.nsmp3` or `.nsmp4`.
    pub layout: Layout,
    /// The sound preset values a project can carry into the instrument.
    pub preset: Preset,
}

/// Project preset values with a decoded destination in at least one generation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Preset {
    /// Whether the instrument loads with its category's dynamics curve.
    pub dynamics_enabled: bool,
    /// The narrow preset's velocity-to-amplitude level.
    pub velocity_to_amplitude: u8,
    /// The narrow preset's velocity-to-timbre level.
    pub velocity_to_timbre: u8,
}

impl Default for Preset {
    fn default() -> Preset {
        Preset {
            dynamics_enabled: false,
            velocity_to_amplitude: 1,
            velocity_to_timbre: 1,
        }
    }
}

/// Build an instrument that spans the keyboard: one `stk` per zone, in the order
/// given, which must be highest zone first.
///
/// Refuses an empty or overlapping zone list, a duplicate or unnameable stroke id,
/// and everything [`instrument`] refuses about one zone's audio.
pub fn multi_zone(
    instrument: Instrument<'_>,
    zones: &[NewZone<'_>],
) -> Result<crate::Sample, Error> {
    match wide_schema(instrument.layout) {
        Some(schema) => wide_chain(instrument, zones, &schema).map(crate::Sample::V3),
        None => narrow_chain(instrument, zones).map(crate::Sample::V2),
    }
}

/// The CBIN header every generation writes, at its own content version.
fn container(layout: Layout) -> Header {
    Header {
        generation: Generation::V1,
        tag: *b"nsmp",
        location: 0xFFFF_FFFF,
        aux: AUX,
        version: version(layout),
    }
}

fn narrow_chain(instrument: Instrument<'_>, zones: &[NewZone<'_>]) -> Result<Cbin<Sample>, Error> {
    let table = zone_table(zones)?;
    let hdr = hdr(instrument.name)?;
    let cat = cat();
    let map = map(map_gain_units(instrument.map_gain), &table)?;
    // The directory a stroke carries counts words from the start of the body, and these
    // two decide where the first packet may start, so both are sized before any stream
    // is written.
    let cat_len = cat.payload.len();
    let map_len = map.payload.len();

    let mut sections = vec![
        Section {
            tag: *section::CONTAINER,
            version: CONTAINER_VERSION,
            payload: Vec::new(),
        },
        hdr,
        cat,
        map,
    ];
    let (encoded, file_peak) =
        encode_strokes(Layout::V2, zones, instrument.predictor, cat_len, map_len)?;
    let mut body_at: usize = sections.iter().map(Section::encoded_len).sum();
    for (zone, stroke) in zones.iter().zip(&encoded) {
        let payload = stroke_payload(
            Layout::V2,
            zone,
            stroke,
            body_at + section::HEADER_LEN,
            file_peak,
        )?;
        body_at += section::HEADER_LEN + payload.len();
        sections.push(Section {
            tag: *section::STK,
            version: STK_VERSION,
            payload,
        });
    }
    sections.push(sty(instrument.preset)?);

    Ok(Cbin {
        header: container(Layout::V2),
        body: Sample { sections },
    })
}

/// The `stk` schema version both wide generations carry.
const STK4_VERSION: u32 = 11;

fn wide_chain(
    instrument: Instrument<'_>,
    zones: &[NewZone<'_>],
    schema: &WideSchema,
) -> Result<Cbin<SampleV3>, Error> {
    let layout = instrument.layout;
    let table = wide_zone_table(zones)?;
    let hdr = hdr4(schema, instrument.name)?;
    let cat = cat4();
    let map = map4(schema, map_gain_units(instrument.map_gain), &table);
    let cat_len = cat.payload.len();
    let map_len = map.payload.len();

    let mut sections = vec![
        Section4 {
            tag: *section::CONTAINER4,
            version: schema.container,
            payload: schema.container_payload.to_vec(),
        },
        hdr,
        cat,
        map,
    ];
    let (encoded, file_peak) =
        encode_strokes(layout, zones, instrument.predictor, cat_len, map_len)?;
    let mut body_at: usize = sections.iter().map(Section4::encoded_len).sum();
    for (zone, stroke) in zones.iter().zip(&encoded) {
        let payload = stroke_payload(
            layout,
            zone,
            stroke,
            body_at + section::HEADER4_LEN,
            file_peak,
        )?;
        body_at += section::HEADER4_LEN + payload.len();
        sections.push(Section4 {
            tag: *section::STK4,
            version: STK4_VERSION,
            payload,
        });
    }
    sections.push(sty4(schema, instrument.preset));
    let chain_len: usize = sections.iter().map(Section4::encoded_len).sum();
    sections.push(meta4(chain_len));

    Ok(Cbin {
        header: container(layout),
        body: SampleV3 { sections },
    })
}

/// What a wide `map` section stores per zone.
struct WideZoneRecord {
    root_key: u8,
    top_note: u8,
    low_note: u8,
    global_id: u32,
}

impl WideZoneRecord {
    fn bytes(&self) -> [u8; super::zone::WIDE_RECORD_LEN] {
        let mut r = [0u8; super::zone::WIDE_RECORD_LEN];
        r[0] = self.root_key;
        r[1] = self.top_note;
        r[2] = self.low_note;
        // Unexplained: real programs hold this, and the panel cannot produce it.
        r[7] = 1;
        r[8..12].copy_from_slice(&self.global_id.to_be_bytes());
        // One sample in the zone, so the playing stroke sits at the bottom of the
        // strength axis.
        r[12..14].copy_from_slice(&super::zone::REL_STRENGTH_DEFAULT.to_be_bytes());
        let full = super::zone::VelocityWindow::FULL;
        r[14] = full.low;
        r[15] = full.high;
        r
    }
}

/// Validate the zone list and reduce it to the records a wide `map` stores.
///
/// A wide zone states its own bottom as well as its top, and zones tile: each reaches
/// down to one above the zone below it, and the lowest reaches the keyboard's floor.
fn wide_zone_table(zones: &[NewZone<'_>]) -> Result<Vec<WideZoneRecord>, Error> {
    let table = zone_table(zones)?;
    Ok(table
        .iter()
        .enumerate()
        .map(|(index, record)| WideZoneRecord {
            root_key: zones[index].root_key,
            top_note: record.top_note,
            low_note: match table.get(index + 1) {
                Some(below) => below.top_note.saturating_add(1),
                None => super::zone::KEY_FLOOR,
            },
            global_id: zones[index].global_id,
        })
        .collect())
}

/// What the `map` section stores per zone.
struct ZoneRecord {
    id: u8,
    top_note: u8,
    gain: u32,
}

/// Validate the zone list and reduce it to the records the `map` section stores.
fn zone_table(zones: &[NewZone<'_>]) -> Result<Vec<ZoneRecord>, Error> {
    if zones.is_empty() || zones.len() > MAX_ZONES {
        return Err(ParseError::OutOfBounds {
            value: format!("{} zones", zones.len()),
            bound: format!("1 through {MAX_ZONES}, the map section's own count byte"),
        }
        .into());
    }
    let mut table = Vec::with_capacity(zones.len());
    for (index, zone) in zones.iter().enumerate() {
        midi_note("root key", zone.root_key)?;
        midi_note("top note", zone.top_note)?;
        if !(1..=MAX_STROKE_ID).contains(&zone.global_id) {
            return Err(ParseError::OutOfBounds {
                value: format!("stroke id {}", zone.global_id),
                bound: format!("1 through {MAX_STROKE_ID}, what a zone record can name"),
            }
            .into());
        }
        if !zone.gain.is_finite() || zone.gain > MAX_ZONE_GAIN {
            return Err(ParseError::OutOfBounds {
                value: format!("zone {index} gain {}", zone.gain),
                bound: format!("a finite gain up to {MAX_ZONE_GAIN}"),
            }
            .into());
        }
        let id = zone.global_id as u8;
        if table.iter().any(|seen: &ZoneRecord| seen.id == id) {
            return Err(ParseError::AssertFail(format!(
                "two zones claim stroke id {id}, and a zone record names its stroke by id"
            ))
            .into());
        }
        if index > 0 && zone.top_note >= zones[index - 1].top_note {
            return Err(ParseError::AssertFail(format!(
                "zone {index} reaches up to note {} but the zone before it stops at {}; \
                 zones are stored highest first and may not overlap",
                zone.top_note,
                zones[index - 1].top_note
            ))
            .into());
        }
        table.push(ZoneRecord {
            id,
            top_note: zone.top_note,
            gain: zone_record_gain(zone.gain),
        });
    }
    Ok(table)
}

/// The ceiling the `map`'s own gain clamps at, in decibels. A project asking for more
/// renders at this and is not repaired.
pub const MAX_MAP_GAIN_DB: f64 = 9.0;

/// Largest zone gain whose stores this reproduces. Past it the u24s' wrap count is
/// unmeasured; below it the wrap is the format's, not a mistake.
pub const MAX_ZONE_GAIN: f64 = 1000.0;

/// The zone's playing gain in decibels — the number a wide stroke header stores, and
/// the number every other gain field is derived through.
///
/// The logarithm is evaluated wider than the field and rounded once; computing it in
/// float32 throughout moves the last byte on the powers of two. Neither clamped nor
/// gridded: silence is `-inf` and a negative gain is the default quiet NaN, which is
/// what the map gain's ceiling comparison then fails against.
fn gain_decibels(gain: f64) -> f32 {
    let decibels = 20.0 * gain.log10();
    match decibels.is_nan() {
        true => f32::from_bits(0x7fc0_0000),
        false => decibels as f32,
    }
}

/// The gain back from its decibel, linear with
/// [`zone::GAIN_BITS`](super::zone::GAIN_BITS) fractional bits, exponentiated wider
/// than the decibel and rounded once.
///
/// ⚠️ **Not the identity on the linear gain it came from.** Below `2^24` the decibel's
/// own precision is worth less than half a step and the two agree; above it they part
/// by tens of steps, and it is this value — not the project's — that statistic A is
/// built from.
fn gain_units(decibels: f32) -> u64 {
    let units = 10f64.powf(f64::from(decibels) / 20.0) * f64::from(super::zone::GAIN_UNITY);
    units.round() as u64
}

/// The `map`'s own gain as the section's opening u24. The one gain field that clamps.
fn map_gain_units(gain: f64) -> u32 {
    let ceiling = MAX_MAP_GAIN_DB as f32;
    let decibels = gain_decibels(gain);
    // The comparison, not the value, is what the ceiling is: a NaN decibel — which is
    // what a negative gain gives — fails it and takes the ceiling rather than the floor.
    let clamped = if decibels < ceiling {
        decibels
    } else {
        ceiling
    };
    gain_units(clamped) as u32
}

/// A zone gain as the narrow zone record stores it: the project's own float, wrapping
/// mod `2^24`, with a negative converting to zero rather than masking.
///
/// ⚠️ The record and statistic A part company here. The record takes the project's
/// float and the mantissa takes the decibel round trip, so past a gain of 16 the two
/// u24s in one file disagree and the record's reads back as a plausible quieter gain.
fn zone_record_gain(gain: f64) -> u32 {
    let units = (gain * f64::from(super::zone::GAIN_UNITY)).round() as u64;
    (units % (1 << 24)) as u32
}

fn midi_note(name: &str, note: u8) -> Result<(), Error> {
    if note <= 127 {
        return Ok(());
    }
    Err(ParseError::OutOfBounds {
        value: format!("{name} {note}"),
        bound: "a MIDI note from 0 through 127".into(),
    }
    .into())
}

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

    /// The narrow chain's own units, which most of these tests are written against.
    const CELL: usize = Layout::V2.cell();
    const CHUNK: usize = Layout::V2.rmax();
    const HEADER_LEN: usize = Layout::V2.header_len();
    const PACKET_LEN: usize = packet_len(Layout::V2);
    const VERSION: u32 = version(Layout::V2);
    const MONO: Units = Units {
        layout: Layout::V2,
        channels: 1,
    };
    const PACKET_WORDS: usize = MONO.packet_words();

    /// The narrow body an encode produced. These tests build no wide one.
    fn narrow(sample: crate::Sample) -> Cbin<Sample> {
        match sample {
            crate::Sample::V2(file) => file,
            crate::Sample::V3(_) => panic!("the narrow chain was asked for"),
        }
    }

    fn built(
        zones: &[NewZone<'_>],
        name: &str,
        predictor: Predictor,
    ) -> Result<Cbin<Sample>, Error> {
        multi_zone(made(name, predictor, Layout::V2), zones).map(narrow)
    }

    /// An instrument at unity map gain, which is what all but one test wants.
    fn made(name: &str, predictor: Predictor, layout: Layout) -> Instrument<'_> {
        Instrument {
            name,
            map_gain: 1.0,
            predictor,
            layout,
            preset: Preset::default(),
        }
    }

    fn plan(frames: usize, channels: usize) -> Result<Plan, Error> {
        Plan::new(
            Layout::V2,
            frames,
            channels,
            default_secondary_start(frames, None),
        )
    }

    fn looped(frames: usize, channels: usize, points: Loop) -> Result<Plan, Error> {
        Plan::looped(
            Layout::V2,
            frames,
            channels,
            points,
            default_secondary_start(frames, Some(points)),
        )
    }

    fn sine(hz: f64, amplitude: f64, frames: usize) -> Vec<i16> {
        (0..frames)
            .map(|k| {
                let t = k as f64 / f64::from(codec::SOURCE_RATE);
                (amplitude * (2.0 * std::f64::consts::PI * hz * t).sin()).round() as i16
            })
            .collect()
    }

    fn encoded(source: &[i16], predictor: Predictor) -> Cbin<Sample> {
        narrow(instrument(source, &Options::new("Test").predictor(predictor)).unwrap())
    }

    #[test]
    fn the_band_is_the_shortest_run_a_whole_number_of_records_can_cover() {
        for channels in [1usize, 2] {
            let (cell, rmax) = (CELL * channels, CHUNK * channels);
            for r in 0..2000usize {
                let b = band(r, cell, rmax);
                assert_eq!(b % cell, r % cell, "{channels}ch r {r}");
                assert!(b >= cell, "band({r}) = {b}");
                let records = (1..=8).find(|j| j * cell <= b && b <= j * rmax);
                assert!(records.is_some(), "{channels}ch band({r}) = {b}");
                for shorter in (cell..b).filter(|s| s % cell == b % cell) {
                    assert!(
                        !(1..=8).any(|j| j * cell <= shorter && shorter <= j * rmax),
                        "{channels}ch band({r}) = {b}, but {shorter} is reachable"
                    );
                }
            }
            assert_eq!(band(0, cell, rmax), cell);
            assert_eq!(band(cell, cell, rmax), cell);
        }
    }

    #[test]
    fn every_one_to_one_chunk_is_a_legal_count() {
        for channels in [1usize, 2] {
            let (cell, rmax) = (CELL * channels, CHUNK * channels);
            for r in 0..2000usize {
                let run = band(r, cell, rmax);
                let split = chunks(run, rmax);
                assert_eq!(split.iter().sum::<usize>(), run, "band({r})");
                for c in split {
                    assert!((cell..=rmax).contains(&c), "band({r}) chunk {c}");
                }
            }
        }
    }

    #[test]
    fn the_plan_covers_every_field_exactly_once() {
        for frames in [4096, 8192, 10_000, 44_100, 100_000, 441_000] {
            let p = plan(frames, 1).unwrap();
            assert_eq!(
                p.warmup + CELL * p.cells_before + p.resync + CELL * p.cells_after,
                p.fields,
                "{frames} frames"
            );
            assert_eq!(p.warmup + CELL * p.cells_before, p.resync_at);
        }
    }

    // Landmarks read off Nord Sample Editor renders of self-generated audio whose
    // projects state the fresh default, `m_startSecondary = m_stop / 8`, from
    // `m_start = 1`: a 44 100-frame mono sine and a 30 870-frame stereo pair.
    #[test]
    fn the_resync_lands_where_the_projects_secondary_start_says() {
        let mono = Plan::new(Layout::V2, 44_099, 1, 5_512.5 - 1.0).unwrap();
        assert_eq!(
            (mono.fields, mono.warmup, mono.resync_at, mono.resync),
            (35_128, 30, 4_374, 58)
        );
        let both = Plan::new(Layout::V2, 30_869, 2, 3_858.75 - 1.0).unwrap();
        assert_eq!(
            (both.fields, both.warmup, both.resync_at, both.resync),
            (49_256, 124, 6_124, 124)
        );
        // Half-up on the lattice: 11 025 frames land on exactly 8 750.5 fields.
        assert_eq!(
            Plan::new(Layout::V2, 88_200, 1, 11_025.0)
                .unwrap()
                .resync_at,
            8_751
        );
    }

    #[test]
    fn a_secondary_start_the_stream_cannot_resync_at_is_refused() {
        for at in [0.0, 20.0, 50_000.0, -1.0, f64::NAN, f64::INFINITY] {
            assert!(
                Plan::new(Layout::V2, 44_100, 1, at).is_err(),
                "secondary start {at}"
            );
        }
        let looped = |at| Plan::looped(Layout::V2, 44_100, 1, Loop::new(8_192, 40_000), at);
        assert!(looped(8_193.0).is_err(), "past the loop start");
        assert!(looped(8_192.0).is_ok(), "at the loop start, mark pushed");
        assert!(looped(4_096.0).is_ok());
    }

    /// The mark's two anchors, on a loop that clears the resync point and on ones that
    /// do not, at both channel counts.
    #[test]
    fn a_loop_mark_clears_the_resync_point_by_the_generations_floor() {
        // Loop start and secondary start in frames, then the field the mark lands on
        // at V2, V3 and V4.
        for (start, secondary, channels, marks) in [
            (92, 92.0, 1, [145, 137, 137]),
            (200, 150.0, 1, [191, 183, 183]),
            (600, 500.0, 1, [481, 481, 481]),
            (92, 92.0, 2, [290, 274, 274]),
        ] {
            let points = Loop::new(start, start + 16_384);
            for (layout, mark) in [Layout::V2, Layout::V3, Layout::V4].into_iter().zip(marks) {
                let plan = Plan::looped(layout, 88_200, channels, points, secondary).unwrap();
                let looped = plan.looped.unwrap();
                assert_eq!(
                    looped.at, mark,
                    "{layout:?} {channels}ch: a loop at frame {start} resyncing at {secondary}"
                );
                assert_eq!(looped.lead, mark - fields_of(start).unwrap() * channels);
                assert_eq!(plan.fields, mark + fields_of(16_384).unwrap() * channels);
            }
        }
    }

    #[test]
    fn audio_without_a_project_resyncs_where_a_fresh_project_would() {
        assert_eq!(default_secondary_start(44_100, None), 5_512.5);
        assert_eq!(
            default_secondary_start(44_100, Some(Loop::new(1_000, 40_000))),
            500.0
        );
        assert_eq!(
            default_secondary_start(44_100, Some(Loop::new(0, 40_000))),
            nsmpproj::MIN_SECONDARY_START
        );
        let stated = instrument(
            &vec![0i16; 44_100],
            &Options::new("Stated").secondary_start(5_521.281862),
        )
        .unwrap();
        let fresh = instrument(&vec![0i16; 44_100], &Options::new("Stated")).unwrap();
        assert_ne!(stated.stroke_streams()[0].1, fresh.stroke_streams()[0].1);
    }

    #[test]
    fn the_stream_opens_on_a_cubic_ramp() {
        let mut fields = vec![-4_000i64; 40];
        ramp_in(&mut fields);
        assert_eq!(fields[0], 0);
        assert_eq!(fields[7], -4_000 * 343 / 42_875);
        assert_eq!(fields[34], -4_000 * 39_304 / 42_875);
        assert!(fields[..RAMP_IN].windows(2).all(|w| w[0] >= w[1]));
        assert!(fields[RAMP_IN..].iter().all(|&v| v == -4_000));
    }

    #[test]
    fn a_width_tie_goes_to_the_lowest_order_unless_a_record_already_holds_it() {
        let widths = [13, 10, 7, 4, 4];
        assert_eq!(choose_order(&widths, None), (3, 4));
        assert_eq!(choose_order(&widths, Some((4, 4))), (4, 4));
        assert_eq!(choose_order(&widths, Some((4, 3))), (3, 4), "width changed");
        assert_eq!(choose_order(&widths, Some((2, 4))), (3, 4));
        assert_eq!(choose_order(&[9], Some((3, 9))), (0, 9));
        // C(k, 3): the third difference is 1 everywhere and the fourth is 0, so orders
        // 3 and 4 both fit width 2.
        let values: Vec<i32> = (0..48).map(|k| k * (k - 1) * (k - 2) / 6).collect();
        assert_eq!(
            widths_at(&values, 8, Predictor::Minimising, CELL, 1)[3..],
            [MIN_WIDTH, MIN_WIDTH]
        );
        assert_eq!(widths_at(&values, 8, Predictor::Plain, CELL, 1).len(), 1);
    }

    #[test]
    fn short_input_is_refused_rather_than_guessed_at() {
        assert!(plan(MIN_FRAMES - 1, 1).is_err());
        assert!(plan(MIN_FRAMES, 1).is_ok());
        assert!(plan(usize::MAX, 1).is_err());
        assert!(instrument(&[0i16; MIN_FRAMES - 1], &Options::new("Test")).is_err());
        assert!(instrument(&[0i16; MIN_FRAMES], &Options::new("Test")).is_ok());
    }

    #[test]
    fn forced_shifts_that_cannot_be_encoded_are_refused() {
        let mut step = vec![i16::MIN; MIN_FRAMES];
        step[MIN_FRAMES / 2..].fill(i16::MAX);
        assert!(instrument(&step, &Options::new("Test").shift(0)).is_err());
        assert!(instrument(
            &[0i16; MIN_FRAMES],
            &Options::new("Test").shift(codec::SHIFT_LIMIT as u8 + 1)
        )
        .is_err());
    }

    #[test]
    fn midi_notes_outside_the_wire_range_are_refused() {
        let source = vec![0i16; MIN_FRAMES];
        assert!(instrument(&source, &Options::new("Test").root_key(128)).is_err());
        assert!(instrument(&source, &Options::new("Test").top_note(255)).is_err());
        let bad_root = NewZone {
            root_key: 128,
            ..zone(&source, 60, 127, 1)
        };
        let encoded = encode_stroke(Layout::V2, &bad_root, 165, Predictor::Plain).unwrap();
        assert!(stroke_payload(Layout::V2, &bad_root, &encoded, 0, 1).is_err());
    }

    #[test]
    fn the_allocation_is_whole_packets_with_the_chain_at_the_end() {
        let file = encoded(&sine(440.0, 8000.0, 44_100), Predictor::Plain);
        let map_len = section::find(&file.body.sections, section::MAP)
            .unwrap()
            .payload
            .len();
        let cat_len = section::find(&file.body.sections, section::CAT)
            .unwrap()
            .payload
            .len();
        let stroke = section::find(&file.body.sections, section::STK).unwrap();
        let head = super::super::stroke::header_len(
            Layout::V2,
            super::super::Chain::Library2,
            0,
            cat_len,
            map_len,
        );
        assert_eq!((stroke.payload.len() - head) % PACKET_LEN, 0);
        assert_eq!(&stroke.payload[stroke.payload.len() - 3..], &[0x80, 0, 24]);
    }

    #[test]
    fn every_predictor_round_trips_through_the_decoder_exactly() {
        let mut differenced = 0usize;
        for predictor in [Predictor::Plain, Predictor::Minimising] {
            for source in [
                sine(440.0, 12_000.0, 44_100),
                sine(30.0, 32_000.0, 20_000),
                vec![0i16; 8192],
                vec![9000i16; 8192],
            ] {
                let file = encoded(&source, predictor);
                let (at, stroke) = file.stroke_streams()[0];
                let plan = plan(source.len(), 1).unwrap();
                let q = quantise(&source, &plan, None);

                let audio = codec::decode(stroke, at, codec::Layout::V2).unwrap();
                assert_eq!(audio.samples.len(), plan.fields);
                if predictor == Predictor::Plain {
                    assert_eq!(audio.differenced, 0);
                } else {
                    differenced += audio.differenced;
                }
                let gain = 1i32 << q.shift;
                for (f, (&want, &got)) in q.values.iter().zip(&audio.samples).enumerate() {
                    assert_eq!(i32::from(got), want * gain, "{predictor:?} field {f}");
                }
            }
        }
        assert!(differenced > 0, "minimising never chose a predictor");
    }

    #[test]
    fn a_sine_comes_back_a_sine() {
        let source = sine(440.0, 20_000.0, 44_100);
        let file = encoded(&source, Predictor::Plain);
        let (at, stroke) = file.stroke_streams()[0];
        let audio = codec::decode(stroke, at, codec::Layout::V2).unwrap();
        // Well inside the source, away from the ends the kernel rings at.
        let window = &audio.samples[10_000..20_000];
        let peak = window.iter().map(|&v| i32::from(v).abs()).max().unwrap();
        assert!((19_000..=21_000).contains(&peak), "peak {peak}");
        let zero_crossings = window.windows(2).filter(|w| w[0] < 0 && w[1] >= 0).count();
        // 10000 fields at 35002 Hz is 0.2857 s, which holds 125.7 cycles of 440 Hz.
        assert!((124..=127).contains(&zero_crossings), "{zero_crossings}");
    }

    #[test]
    fn a_records_fields_start_right_after_its_header() {
        // 30 fields of 13 bits is 390, leaving 18 spare bits in 18 words.
        let spec = Spec {
            one_to_one: true,
            width: 13,
            order: 0,
            mark: false,
            first: 0,
            count: 30,
        };
        let tail = spec.span(MONO) * 24 - 24 - spec.count * usize::from(spec.width);
        assert_eq!(tail, 18, "this spec is chosen to leave a tail");

        let values: Vec<i32> = (0..30).map(|k| k * 7 - 40).collect();
        let mut words = vec![0u8; spec.span(MONO) * 3];
        write_record(&mut words, 0, &spec, &values, MONO);

        // The tail is the last `tail` bits of the segment, and nothing is in it.
        let total = spec.span(MONO) * 24;
        for bit in total - tail..total {
            assert_eq!(
                words[bit / 8] >> (7 - bit % 8) & 1,
                0,
                "bit {bit} is in the alignment tail and should be clear"
            );
        }
        // And the reader agrees about where the values are.
        let mut stroke = vec![0u8; HEADER_LEN];
        stroke.extend_from_slice(&words);
        stroke.extend_from_slice(&[0x80, 0x00, 0x18]);
        let end = (HEADER_LEN / 3 + spec.span(MONO)) as u16;
        for (i, p) in [HEADER_LEN as u16 / 3, 0, end, end].iter().enumerate() {
            let at = codec::SEEK_AT + codec::SEEK_STRIDE * i;
            stroke[at..at + 2].copy_from_slice(&p.to_be_bytes());
        }
        let walked = codec::walk(&stroke, 0, codec::Layout::V2).unwrap();
        assert_eq!(walked.records[0].values, values);
    }

    #[test]
    fn the_instrument_reads_back_as_one() {
        let file = instrument(
            &sine(220.0, 15_000.0, 30_000),
            &Options::new("Encoded").root_key(48).top_note(72),
        )
        .unwrap();
        let bytes = file.to_bytes().unwrap();
        let read = super::super::from_bytes(&bytes).unwrap();
        assert_eq!(read.name().unwrap(), "Encoded");
        assert_eq!(read.header.version, VERSION);
        let zones = read.zones().unwrap();
        assert_eq!(zones.len(), 1);
        assert_eq!(zones[0].top_note, 72);
        assert_eq!(read.strokes().unwrap()[0].root_key, 48);
        assert_eq!(read.to_bytes().unwrap(), bytes);
    }

    #[test]
    fn the_directory_names_the_records_the_walk_finds() {
        let file = encoded(&sine(300.0, 9000.0, 50_000), Predictor::Plain);
        let (at, stroke) = file.stroke_streams()[0];
        let stream = codec::walk(stroke, at, codec::Layout::V2).unwrap();
        let directory = codec::Directory::read(stroke).unwrap();
        assert_eq!(
            codec::Directory::resolve(directory.first_record, at, codec::Layout::V2),
            stream.first_record
        );
        assert_eq!(
            codec::Directory::resolve(directory.terminator, at, codec::Layout::V2),
            stream.terminator
        );
        let resync = codec::Directory::resolve(directory.resync, at, codec::Layout::V2);
        let record = stream.records.iter().find(|r| r.at == resync).unwrap();
        assert!(record.one_to_one);
        assert_eq!(record.first_field, plan(50_000, 1).unwrap().resync_at);
    }

    #[test]
    fn the_header_states_the_shift_it_quantised_at() {
        for amplitude in [40.0, 900.0, 8000.0, 32_000.0] {
            let source = sine(440.0, amplitude, 20_000);
            let plan = plan(source.len(), 1).unwrap();
            let file = encoded(&source, Predictor::Plain);
            let (_, stroke) = file.stroke_streams()[0];
            let q = quantise(&source, &plan, None);
            assert_eq!(
                codec::shift(stroke, codec::Layout::V2),
                Some(q.shift),
                "amplitude {amplitude}"
            );
            assert_eq!(codec::peak(stroke, codec::Layout::V2), Some(q.peak));
            assert!(q.shift >= 0);
        }
    }

    #[test]
    fn the_shift_tracks_how_loud_the_content_is() {
        let quiet = plan(20_000, 1)
            .map(|p| quantise(&sine(440.0, 500.0, 20_000), &p, None).shift)
            .unwrap();
        let loud = plan(20_000, 1)
            .map(|p| quantise(&sine(440.0, 32_000.0, 20_000), &p, None).shift)
            .unwrap();
        assert_eq!(quiet, 0);
        assert!(loud > quiet, "loud {loud} vs quiet {quiet}");
    }

    #[test]
    fn a_stereo_stroke_stops_shifting_where_its_peak_fits() {
        let frames = 30_000;
        let left = sine(220.0, 12_000.0, frames);
        let right = sine(330.0, 12_000.0, frames);
        let both: Vec<i16> = left
            .iter()
            .zip(&right)
            .flat_map(|(&l, &r)| [l, r])
            .collect();
        let mono = quantise(&left, &plan(frames, 1).unwrap(), None);
        let stereo = quantise(&both, &plan(frames, 2).unwrap(), None);
        assert_eq!(stereo.shift, 1);
        let widest = stereo
            .values
            .iter()
            .map(|v| width_of(i64::from(*v), i64::from(*v)))
            .max()
            .unwrap();
        assert_eq!(widest, PEAK_WIDTH);
        // The mono stroke sees the same peak and may spend one further bit on top.
        assert!((stereo.shift..=stereo.shift + 1).contains(&mono.shift));
    }

    /// A stroke whose only loud field sits at `field`, resynchronising at `resync`.
    fn probe(layout: Layout, resync: usize, field: usize) -> (Plan, Vec<i64>) {
        let frames = 100_000;
        let secondary = resync as f64 * f64::from(PITCH_NUM) / f64::from(PITCH_DEN);
        let plan = Plan::new(layout, frames, 1, secondary).unwrap();
        assert_eq!(plan.resync_at, resync);
        let mut values = vec![0i64; plan.fields];
        values[field] = 1 << (PEAK_WIDTH - 2);
        (plan, values)
    }

    #[test]
    fn only_a_run_s_last_record_buys_the_extra_bit() {
        // The resync run at 5464 is 89 fields: [0, 32), [32, 64), [64, 89).
        let (plan, values) = probe(Layout::V2, 5464, 5464 + 76);
        assert!(spends_extra_bit(&values, &plan));
        for offset in [12, 61, 89, 95] {
            let (plan, values) = probe(Layout::V2, 5464, 5464 + offset);
            assert!(!spends_extra_bit(&values, &plan), "run offset {offset}");
        }
    }

    /// A mono stroke that is one 1:1 run ending in a `last`-field record, with `value`
    /// in that record's final field and nothing anywhere else.
    fn opening_run(layout: Layout, last: usize, value: i64) -> (Plan, Vec<i64>) {
        let chunk = layout.rmax();
        let warmup = if last == chunk { chunk } else { chunk + last };
        let plan = Plan {
            layout,
            channels: 1,
            fields: warmup,
            resync_at: warmup,
            warmup,
            resync: 0,
            cells_before: 0,
            cells_after: 0,
            looped: None,
        };
        let mut values = vec![0; warmup];
        values[warmup - 1] = value;
        (plan, values)
    }

    #[test]
    fn each_last_record_width_obeys_the_measured_rule() {
        for (last, buys) in [
            (24, false),
            (25, true),
            (26, true),
            (27, true),
            (28, true),
            (29, false),
            (30, true),
            (31, true),
            (32, false),
        ] {
            let (plan, values) = opening_run(Layout::V2, last, 1 << (PEAK_WIDTH - 2));
            assert_eq!(spends_extra_bit(&values, &plan), buys, "width {last}");
        }
    }

    #[test]
    fn the_extra_bit_uses_signed_thirteen_bit_bounds() {
        for (value, buys) in [(-4097, true), (-4096, false), (4095, false), (4096, true)] {
            let (plan, values) = opening_run(Layout::V2, 25, value);
            assert_eq!(spends_extra_bit(&values, &plan), buys, "value {value}");
        }
    }

    /// The last record of a v3 run is 32..=48 fields, and these eleven of the
    /// seventeen buy the bit.
    const V3_LIVE: [usize; 11] = [33, 34, 35, 36, 37, 38, 39, 40, 42, 44, 46];

    #[test]
    fn six_of_the_seventeen_v3_last_record_widths_never_buy_it() {
        for last in 32..=48 {
            let (plan, values) = opening_run(Layout::V3, last, 1 << (PEAK_WIDTH - 2));
            assert_eq!(
                spends_extra_bit(&values, &plan),
                V3_LIVE.contains(&last),
                "width {last}"
            );
        }
    }

    #[test]
    fn a_v4_mono_stroke_never_buys_the_extra_bit() {
        for last in 32..=48 {
            let (plan, values) = opening_run(Layout::V4, last, 1 << (PEAK_WIDTH - 2));
            assert!(!spends_extra_bit(&values, &plan), "width {last}");
        }
    }

    /// A looped mono stroke whose only loud field sits in the last record of the run
    /// the mark opens. The opening run is a full RMAX record, a width both generations
    /// call dead, so nothing but the loop's run can buy the bit.
    fn loop_run(layout: Layout, last: usize) -> (Plan, Vec<i64>) {
        let at = layout.rmax();
        let fields = at + last;
        let plan = Plan {
            layout,
            channels: 1,
            fields,
            resync_at: at,
            warmup: at,
            resync: 0,
            cells_before: 0,
            cells_after: 0,
            looped: Some(Looped {
                at,
                lead: 0,
                crossfade: 0,
                warmup: last,
                cells: 0,
            }),
        };
        let mut values = vec![0; fields];
        values[fields - 1] = 1 << (PEAK_WIDTH - 2);
        (plan, values)
    }

    #[test]
    fn the_run_a_loop_mark_opens_buys_the_extra_bit() {
        for (layout, live, dead) in [(Layout::V2, 25, 29), (Layout::V3, 33, 41)] {
            let (plan, values) = loop_run(layout, live);
            assert!(spends_extra_bit(&values, &plan), "{layout:?} live");

            let unmarked = Plan {
                looped: None,
                ..plan
            };
            assert!(!spends_extra_bit(&values, &unmarked), "{layout:?} unlooped");

            let (plan, values) = loop_run(layout, dead);
            assert!(!spends_extra_bit(&values, &plan), "{layout:?} dead");
        }
    }

    #[test]
    fn the_extra_bit_narrows_the_stroke_the_header_declares() {
        let loud = header_shift(&sine(440.0, 12_000.0, 44_100), 1);
        let quiet = header_shift(&sine(440.0, 3_000.0, 44_100), 1);
        assert_eq!(loud - quiet, 2);
    }

    fn header_shift(source: &[i16], channels: u16) -> i32 {
        let options = Options::new("Shift")
            .channels(channels)
            .predictor(Predictor::Minimising);
        let file = instrument(source, &options).unwrap();
        let (_, stroke) = file.stroke_streams()[0];
        codec::shift(stroke, codec::Layout::V2).unwrap()
    }

    #[test]
    fn statistic_b_takes_the_sign_of_the_extreme_field() {
        let frames = 20_000;
        let mut up = vec![0i16; frames];
        up[10_000] = 13;
        let down: Vec<i16> = up.iter().map(|v| -v).collect();
        let positive = quantise(&up, &plan(frames, 1).unwrap(), None).peak;
        let negative = quantise(&down, &plan(frames, 1).unwrap(), None).peak;
        assert_eq!(positive, 2);
        assert_eq!(negative, 3);
        let opposed: Vec<i16> = up.iter().zip(&down).flat_map(|(&l, &r)| [l, r]).collect();
        let stereo = quantise(&opposed, &plan(frames, 2).unwrap(), None).peak;
        assert_eq!(stereo, positive);
    }

    #[test]
    fn no_field_overflows_the_width_its_record_declares() {
        for predictor in [Predictor::Plain, Predictor::Minimising] {
            let source = sine(440.0, 32_000.0, 30_000);
            let plan = plan(source.len(), 1).unwrap();
            let q = quantise(&source, &plan, None);
            let (specs, _) = records(&q.values, &plan, predictor).unwrap();
            for spec in specs {
                let limit = 1i64 << (spec.width - 1);
                for k in 0..spec.count {
                    let v = residual(&q.values, spec.first + k, spec.order, 1);
                    assert!((-limit..limit).contains(&v), "{spec:?} field {k} = {v}");
                }
                assert!(spec.width <= PEAK_WIDTH || spec.order > 0);
            }
        }
    }

    #[test]
    fn records_tile_the_lattice_the_way_the_laws_say() {
        let source = sine(440.0, 20_000.0, 60_000);
        let plan = plan(source.len(), 1).unwrap();
        let q = quantise(&source, &plan, None);
        let (specs, _) = records(&q.values, &plan, Predictor::Plain).unwrap();

        let mut at = 0;
        for spec in &specs {
            assert_eq!(spec.first, at);
            if !spec.one_to_one {
                assert_eq!(spec.count % CELL, 0);
                assert!(spec.count <= MAX_COUNT);
            }
            at += spec.count;
        }
        assert_eq!(at, plan.fields);
        let one_to_one: usize = specs.iter().filter(|s| s.one_to_one).map(|s| s.count).sum();
        assert_eq!(one_to_one, plan.warmup + plan.resync);
    }

    #[test]
    fn the_minimising_predictor_narrows_smooth_material() {
        let source = sine(60.0, 30_000.0, 60_000);
        let plan = plan(source.len(), 1).unwrap();
        let q = quantise(&source, &plan, None);
        let (plain, _) = records(&q.values, &plan, Predictor::Plain).unwrap();
        let (minimised, _) = records(&q.values, &plan, Predictor::Minimising).unwrap();

        let bits = |specs: &[Spec]| -> usize { specs.iter().map(|s| s.span(MONO)).sum() };
        assert!(
            bits(&minimised) < bits(&plain),
            "{} words vs {}",
            bits(&minimised),
            bits(&plain)
        );
        assert!(minimised.iter().any(|s| s.order > 0));
        // The 1:1 regime never predicts.
        assert!(minimised.iter().all(|s| !s.one_to_one || s.order == 0));
    }

    #[test]
    fn a_residual_integrates_back_to_the_field_it_came_from() {
        let values: Vec<i32> = (0..200).map(|k| (k * k / 7) % 501 - 250).collect();
        for order in 1..DIFFERENCE.len() as u8 {
            for at in usize::from(order)..values.len() {
                let mut v = residual(&values, at, order, 1);
                for (j, &c) in DIFFERENCE[usize::from(order)].iter().enumerate().skip(1) {
                    v -= i64::from(c) * i64::from(values[at - j]);
                }
                assert_eq!(v, i64::from(values[at]), "order {order} at {at}");
            }
        }
    }

    #[test]
    fn statistic_a_round_trips_the_shift() {
        for peak in [0u32, 1, 2, 255, 4095, 4096, 8191, 8192] {
            for shift in 0..6 {
                let (mantissa, exponent) = statistic_a(peak, shift, u64::from(GAIN_UNITY));
                let mut stroke = vec![0u8; HEADER_LEN];
                stroke[codec::STAT_A_EXP_AT] = exponent;
                stroke[codec::PEAK_AT..codec::PEAK_AT + 3]
                    .copy_from_slice(&peak.to_be_bytes()[1..]);
                assert_eq!(
                    codec::shift(&stroke, codec::Layout::V2),
                    Some(shift),
                    "peak {peak}"
                );
                assert!((1 << 19..1 << 20).contains(&mantissa) || peak == 0);
            }
        }
    }

    #[test]
    fn the_stroke_header_holds_the_fixed_bytes_where_the_format_puts_them() {
        let file = instrument(
            &sine(440.0, 9000.0, 20_000),
            &Options::new("Test").root_key(64),
        )
        .unwrap();
        let (_, head) = file.stroke_streams()[0];
        assert_eq!(head[0..5], [0, 0, 0, 1, 0]);
        assert_eq!(head[5], 64);
        assert_eq!(head[6..9], [0x88, 0xba, 0x01]);
        let stereo = instrument(
            &vec![0i16; 2 * MIN_FRAMES],
            &Options::new("Test").channels(2),
        )
        .unwrap();
        assert_eq!(stereo.stroke_streams()[0].1[6..9], [0x88, 0xba, 0x02]);
        assert_eq!(head[16..20], [0, 0, 0, 0]);
        assert_eq!([head[22], head[31], head[40]], [0x80, 0x80, 0x80]);
        assert_eq!(head[49..51], [0, 0]);
        for gap in [23..29, 32..38, 41..47] {
            assert!(head[gap.clone()].iter().all(|&b| b == 0), "{gap:?}");
        }
    }

    fn zone(source: &[i16], root_key: u8, top_note: u8, global_id: u32) -> NewZone<'_> {
        NewZone {
            source,
            channels: 1,
            root_key,
            top_note,
            global_id,
            loops: None,
            secondary_start: default_secondary_start(source.len(), None),
            shift: None,
            gain: 1.0,
            loop_decay: DEFAULT_LOOP_DECAY,
        }
    }

    #[test]
    fn statistic_a_scales_a_24_bit_reciprocal_by_the_gain() {
        assert_eq!(statistic_a(4096, 2, u64::from(GAIN_UNITY)), (524_288, 12));
        assert_eq!(
            statistic_a(4096, 2, u64::from(GAIN_UNITY / 2)),
            (262_144, 12)
        );
        assert_eq!(
            statistic_a(4096, 2, 2 * u64::from(GAIN_UNITY)),
            (1_048_576, 12)
        );
        assert_eq!(statistic_a(1225, 0, 1_436_549), (1_200_837, 11));
        assert_eq!(statistic_a(4195, 2, 8_378_122), (8_180_401, 11));
        assert_eq!(statistic_a(1225, 0, 5_557_453), (4_645_576, 11));
    }

    /// Every zone of an instrument reciprocates the same peak — the file's — so a
    /// quiet zone plays quietly rather than being normalised up to the loud one.
    #[test]
    fn statistic_a_reciprocates_the_loudest_zone_in_the_file() {
        let loud = sine(440.0, 12_000.0, 20_000);
        let quiet = sine(440.0, 3_000.0, 20_000);
        let file = built(
            &[zone(&loud, 72, 127, 1), zone(&quiet, 48, 71, 2)],
            "Two",
            Predictor::Plain,
        )
        .unwrap();
        let field = |s: &[u8], at: usize| u32::from_be_bytes([0, s[at], s[at + 1], s[at + 2]]);
        let streams = file.stroke_streams();
        let (mantissa, peak) = (|s| field(s, 9), |s| field(s, 13));
        let (first, second) = (streams[0].1, streams[1].1);
        assert!(peak(first) > peak(second));
        assert_eq!(mantissa(first), mantissa(second));
        assert_eq!(
            mantissa(second),
            statistic_a(peak(first), 0, u64::from(GAIN_UNITY)).0,
            "the quiet zone reciprocates the loud zone's peak"
        );
        assert_ne!(
            mantissa(second),
            statistic_a(peak(second), 0, u64::from(GAIN_UNITY)).0
        );
    }

    #[test]
    fn a_zone_gain_scales_statistic_a_and_touches_nothing_else() {
        let source = sine(440.0, 12_000.0, 20_000);
        let unity = built(&[zone(&source, 60, 127, 1)], "Gain", Predictor::Plain).unwrap();
        let half = NewZone {
            gain: 0.5,
            ..zone(&source, 60, 127, 1)
        };
        let halved = built(&[half], "Gain", Predictor::Plain).unwrap();
        let (_, a) = unity.stroke_streams()[0];
        let (_, b) = halved.stroke_streams()[0];
        assert_eq!(a[..9], b[..9]);
        assert_eq!(a[12..], b[12..]);
        let mantissa = |s: &[u8]| u32::from_be_bytes([0, s[9], s[10], s[11]]);
        assert_eq!(mantissa(b), mantissa(a) / 2);
        assert_eq!(unity.zones().unwrap()[0].gain, GAIN_UNITY);
        assert_eq!(halved.zones().unwrap()[0].gain, GAIN_UNITY / 2);

        let over = NewZone {
            gain: MAX_ZONE_GAIN * 2.0,
            ..zone(&source, 60, 127, 1)
        };
        assert!(built(&[over], "Gain", Predictor::Plain).is_err());
    }

    #[test]
    fn every_zone_reads_back_paired_to_its_own_stroke() {
        let high = sine(880.0, 12_000.0, 12_000);
        let mid = sine(440.0, 12_000.0, 9_000);
        let low = sine(220.0, 12_000.0, 15_000);
        let file = built(
            &[
                zone(&high, 72, 96, 7),
                zone(&mid, 60, 65, 3),
                zone(&low, 48, 53, 9),
            ],
            "Three",
            Predictor::Plain,
        )
        .unwrap();

        let read = super::super::from_bytes(&file.to_bytes().unwrap()).unwrap();
        assert_eq!(read.name().unwrap(), "Three");
        let zones = read.zones().unwrap();
        assert_eq!(
            zones.iter().map(|z| z.top_note).collect::<Vec<_>>(),
            [96, 65, 53]
        );
        assert_eq!(
            zones.iter().map(|z| z.stroke_id).collect::<Vec<_>>(),
            [7, 3, 9]
        );
        assert_eq!(
            read.strokes()
                .unwrap()
                .iter()
                .map(|s| s.root_key)
                .collect::<Vec<_>>(),
            [72, 60, 48]
        );

        for (index, source) in [&high, &mid, &low].iter().enumerate() {
            let (at, stream) = read.zone_stream(index).unwrap();
            let audio = codec::decode(stream, at, codec::Layout::V2).unwrap();
            let plan = plan(source.len(), 1).unwrap();
            let q = quantise(source, &plan, None);
            let gain = 1i32 << q.shift;
            assert_eq!(audio.samples.len(), plan.fields, "zone {index}");
            for (f, (&want, &got)) in q.values.iter().zip(&audio.samples).enumerate() {
                assert_eq!(i32::from(got), want * gain, "zone {index} field {f}");
            }
        }
    }

    #[test]
    fn a_zone_decodes_the_same_alone_as_in_a_crowd() {
        let source = sine(330.0, 18_000.0, 20_000);
        let alone = narrow(instrument(&source, &Options::new("One").root_key(60)).unwrap());
        let crowd = built(
            &[
                zone(&sine(880.0, 9000.0, 8000), 72, 96, 3),
                zone(&source, 60, 65, 2),
                zone(&sine(110.0, 9000.0, 8000), 48, 53, 1),
            ],
            "Three",
            Predictor::default(),
        )
        .unwrap();

        let one = alone.zone_stream(0).unwrap();
        let many = crowd.zone_stream(1).unwrap();
        assert_ne!(one.1, many.1, "the streams differ; only the audio must not");
        assert_eq!(
            codec::decode(one.1, one.0, codec::Layout::V2).unwrap(),
            codec::decode(many.1, many.0, codec::Layout::V2).unwrap()
        );
    }

    #[test]
    fn every_stroke_is_its_own_header_length_plus_whole_packets() {
        let source = sine(440.0, 12_000.0, 12_000);
        for count in 1..=6usize {
            let zones: Vec<NewZone> = (0..count)
                .map(|i| zone(&source, 60, 120 - 10 * i as u8, i as u32 + 1))
                .collect();
            let file = built(&zones, "Ladder", Predictor::Plain).unwrap();
            let cat_len = section::find(&file.body.sections, section::CAT)
                .unwrap()
                .payload
                .len();
            let map_len = section::find(&file.body.sections, section::MAP)
                .unwrap()
                .payload
                .len();
            for (index, section) in file
                .body
                .sections
                .iter()
                .filter(|s| s.is(section::STK))
                .enumerate()
            {
                let head = super::super::stroke::header_len(
                    Layout::V2,
                    super::super::Chain::Library2,
                    index,
                    cat_len,
                    map_len,
                );
                assert_eq!(
                    (section.payload.len() - head) % PACKET_LEN,
                    0,
                    "{count} zones, stroke {index}: {} bytes over a {head}-byte header",
                    section.payload.len()
                );
            }
        }
    }

    #[test]
    fn a_zone_list_the_format_cannot_store_is_refused() {
        let source = vec![0i16; MIN_FRAMES];
        let one = |root, top, id| built(&[zone(&source, root, top, id)], "x", Predictor::Plain);
        assert!(built(&[], "x", Predictor::Plain).is_err());
        assert!(one(60, 84, 0).is_err(), "id zero names no stroke");
        assert!(one(60, 84, 256).is_err(), "id past the record's one byte");
        assert!(one(60, 128, 1).is_err());
        assert!(one(128, 84, 1).is_err());
        assert!(one(60, 84, 1).is_ok());

        let pair = |tops: [u8; 2], ids: [u32; 2]| {
            built(
                &[
                    zone(&source, 60, tops[0], ids[0]),
                    zone(&source, 48, tops[1], ids[1]),
                ],
                "x",
                Predictor::Plain,
            )
        };
        assert!(pair([84, 53], [1, 1]).is_err(), "duplicate stroke id");
        assert!(pair([53, 84], [2, 1]).is_err(), "zones out of order");
        assert!(pair([84, 84], [2, 1]).is_err(), "zones overlap");
        assert!(pair([84, 53], [2, 1]).is_ok());
    }

    #[test]
    fn a_looped_plan_covers_every_field_exactly_once() {
        for (frames, start, end) in [
            (88_200, 16_384, 32_768),
            (88_200, 4_096, 20_480),
            (88_200, 92, 16_476),
            (88_200, 43_981, 60_365),
            (44_100, 20_000, 44_100),
        ] {
            let plan = looped(frames, 1, Loop::new(start, end)).unwrap();
            let points = plan.looped.unwrap();
            assert_eq!(
                plan.warmup + CELL * plan.cells_before + plan.resync + CELL * plan.cells_after,
                points.at,
                "{start}..{end}: the pre-roll does not reach the loop"
            );
            assert_eq!(
                points.at + points.warmup + CELL * points.cells,
                plan.fields,
                "{start}..{end}: the loop does not reach the terminator"
            );
            assert_eq!(points.at - fields_of(start).unwrap(), points.lead);
        }
    }

    #[test]
    fn a_loop_comes_back_the_length_it_asked_for() {
        let source = sine(220.0, 18_000.0, 88_200);
        for (start, end) in [
            (16_384, 32_768),
            (43_981, 60_365),
            (4_096, 20_480),
            (65_536, 81_920),
        ] {
            let file = instrument(
                &source,
                &Options::new("Looped").loops(Loop::new(start, end)),
            )
            .unwrap_or_else(|e| panic!("loop {start}..{end}: {e}"));
            let (at, stroke) = file.stroke_streams()[0];
            let walk = codec::walk(stroke, at, codec::Layout::V2).unwrap();
            let mark = walk.records.iter().find(|r| r.mark).unwrap();
            let frames = (walk.fields - mark.first_field) as f64 * f64::from(codec::SOURCE_RATE)
                / f64::from(codec::FIELD_RATE);
            assert!(
                (frames - (end - start) as f64).abs() < 1.0,
                "loop {start}..{end} came back {frames} frames long"
            );
        }
    }

    #[test]
    fn the_loop_starts_a_packet_and_the_directory_says_so() {
        let source = sine(330.0, 14_000.0, 60_000);
        for (start, end) in [(8_192, 24_576), (20_000, 40_000), (4_096, 59_000)] {
            for predictor in [Predictor::Plain, Predictor::Minimising] {
                let file = instrument(
                    &source,
                    &Options::new("Looped")
                        .predictor(predictor)
                        .loops(Loop::new(start, end)),
                )
                .unwrap();
                let (at, stroke) = file.stroke_streams()[0];
                let walk = codec::walk(stroke, at, codec::Layout::V2).unwrap();
                let directory = codec::Directory::read(stroke).unwrap();
                let marked: Vec<_> = walk.records.iter().filter(|r| r.mark).collect();
                assert_eq!(marked.len(), 1, "{start}..{end} {predictor:?}");
                assert_eq!(
                    codec::Directory::resolve(directory.mark, at, codec::Layout::V2),
                    marked[0].at
                );
                assert_ne!(directory.mark, directory.terminator);
                assert_eq!(
                    (walk.terminator - marked[0].at) % PACKET_WORDS,
                    0,
                    "{start}..{end} {predictor:?}: {} words",
                    walk.terminator - marked[0].at
                );
            }
        }
    }

    #[test]
    fn an_unlooped_stroke_marks_nothing() {
        let file = encoded(&sine(440.0, 9_000.0, 44_100), Predictor::Plain);
        let (at, stroke) = file.stroke_streams()[0];
        let directory = codec::Directory::read(stroke).unwrap();
        assert_eq!(directory.mark, directory.terminator);
        assert!(codec::walk(stroke, at, codec::Layout::V2)
            .unwrap()
            .records
            .iter()
            .all(|r| !r.mark));
    }

    #[test]
    fn the_tail_repeats_the_loops_opening() {
        let source = sine(200.0, 20_000.0, 88_200);
        let plan = looped(source.len(), 1, Loop::new(16_384, 32_768)).unwrap();
        let points = plan.looped.unwrap();
        let values = quantise(&source, &plan, None).values;
        assert_eq!(
            values[plan.fields - points.lead..],
            values[points.at - points.lead..points.at]
        );
    }

    // (loop length, crossfade frames, fields the ramp covers).
    // Inferred from specimens; not confirmed on hardware.
    const MEASURED_FADES: &[(usize, f64, usize)] = &[
        (8_192, 81.92, 65),
        (8_192, 163.84, 130),
        (8_192, 409.6, 325),
        (8_192, 819.2, 650),
        (8_192, 1_638.4, 1_300),
        (8_192, 2_048.0, 1_626),
        (8_192, 3_276.8, 2_601),
        (8_192, 4_096.0, 3_251),
        (8_192, 6_144.0, 4_877),
        (8_192, 8_192.0, 6_502),
        (2_048, 512.0, 406),
        (4_096, 1_024.0, 813),
        (16_384, 4_096.0, 3_251),
        (32_768, 8_192.0, 6_502),
        (7_000, 700.0, 556),
        (10_000, 1_000.0, 794),
        (4_096, 409.6, 325),
        (1_024, 409.6, 325),
        (16_384, 256.0, 203),
        (16_384, 1_024.0, 813),
        (16_384, 8_192.0, 6_502),
    ];

    #[test]
    fn the_fade_opens_where_the_editors_own_renders_open_it() {
        for &(length, crossfade, want) in MEASURED_FADES {
            let points = Loop::new(16_384, 16_384 + length).crossfade(crossfade);
            let plan = looped(88_200, 1, points).unwrap();
            assert_eq!(
                plan.looped.unwrap().crossfade,
                want,
                "a {crossfade} frame fade in a {length} frame loop"
            );
        }
    }

    #[test]
    fn the_crossfade_ramps_linearly_into_the_material_before_the_loop() {
        let source = sine(150.0, 22_000.0, 88_200);
        let points = Loop::new(16_384, 32_768);
        let plan = looped(source.len(), 1, points).unwrap();
        let faded = looped(source.len(), 1, points.crossfade(4_096.0)).unwrap();
        let (plain, mixed) = (
            quantise(&source, &plan, None).values,
            quantise(&source, &faded, None).values,
        );
        assert_eq!(plain.len(), mixed.len());

        let loop_at = faded.looped.unwrap();
        let end = faded.fields - loop_at.lead;
        let length = faded.fields - loop_at.at;
        let span = loop_at.crossfade;
        assert!(span > 3_000, "the fade is {span} fields");
        // Untouched in front of the fade, and the fade itself is the ramp.
        assert_eq!(plain[..end - span], mixed[..end - span]);
        for k in 0..span {
            let f = end - span + k;
            let (near, far) = (f64::from(plain[f]), f64::from(plain[f - length]));
            let u = k as f64 / span as f64;
            let want = near + (far - near) * u;
            assert!(
                (f64::from(mixed[f]) - want).abs() <= 1.0,
                "field {f}: {} against {want}",
                mixed[f]
            );
        }
    }

    #[test]
    fn a_crossfade_may_begin_before_the_loop_start() {
        let source = sine(150.0, 22_000.0, 60_000);
        let points = Loop::new(16_384, 24_576).crossfade(16_384.0);
        let plan = looped(source.len(), 1, points).unwrap();
        let looped = plan.looped.unwrap();

        assert!(looped.crossfade > fields_of(points.end - points.start).unwrap());
        assert!(looped.crossfade <= fields_of(points.start).unwrap());
        let file = instrument(&source, &Options::new("Long fade").loops(points)).unwrap();
        let (at, stroke) = file.stroke_streams()[0];
        assert!(codec::decode(stroke, at, codec::Layout::V2).is_ok());
    }

    #[test]
    fn a_loop_the_format_cannot_state_is_refused() {
        let frames = 44_100;
        let stated = |points| looped(frames, 1, points);
        assert!(stated(Loop::new(8_192, 40_000)).is_ok());
        assert!(stated(Loop::new(8_192, 8_192)).is_err(), "empty loop");
        assert!(stated(Loop::new(40_000, 8_192)).is_err(), "loop runs back");
        assert!(stated(Loop::new(8_192, 44_101)).is_err(), "past the audio");
        assert!(
            stated(Loop::new(8_192, 8_250)).is_err(),
            "shorter than a run"
        );
        assert!(
            stated(Loop::new(1_024, 40_000).crossfade(4_096.0)).is_err(),
            "nothing in front of the loop to fade from"
        );
        assert!(
            stated(Loop::new(8_192, 40_000).crossfade(40_000.0)).is_err(),
            "not enough material before the fade"
        );
        // Below the shortest stroke the editor encodes, whatever the loop says.
        assert!(looped(MIN_FRAMES - 1, 1, Loop::new(10, 60)).is_err());
    }

    #[test]
    fn a_looped_stroke_round_trips_through_the_decoder_exactly() {
        let source = sine(180.0, 16_000.0, 60_000);
        for predictor in [Predictor::Plain, Predictor::Minimising] {
            for points in [
                Loop::new(8_192, 40_960),
                Loop::new(8_192, 40_960).crossfade(4_096.0),
            ] {
                let file = instrument(
                    &source,
                    &Options::new("Looped").predictor(predictor).loops(points),
                )
                .unwrap();
                let (at, stroke) = file.stroke_streams()[0];
                let plan = looped(source.len(), 1, points).unwrap();
                let q = quantise(&source, &plan, None);
                let audio = codec::decode(stroke, at, codec::Layout::V2).unwrap();
                assert_eq!(audio.samples.len(), plan.fields);
                let gain = 1i32 << q.shift;
                for (f, (&want, &got)) in q.values.iter().zip(&audio.samples).enumerate() {
                    assert_eq!(i32::from(got), want * gain, "{predictor:?} field {f}");
                }
            }
        }
    }

    // Full-scale broadband material can exhaust the three spare bits per field before
    // a short loop reaches the next packet boundary.
    /// A loop region with nothing left to split is widened forward, each content record
    /// spent up to the cap before the next is touched, so the last one widened takes
    /// only the words still owed. Widening from the back instead finishes in fewer,
    /// wider records, which is not what the editor writes.
    ///
    /// The alignment run the region opens with is walked past however much room it has,
    /// and however many records it takes — the marked one here is followed by a second.
    ///
    /// The two wide generations lay the same mono region out in the same words, so the
    /// widths they finish on differ only by the cap: v3 stops one width below v4 and
    /// the deficit runs on into the next record.
    #[test]
    fn the_widen_fallback_walks_past_the_regions_alignment_records() {
        for (layout, widths) in [
            (Layout::V3, [1, 1, 13, 9, 1, 1]),
            (Layout::V4, [1, 1, 14, 8, 1, 1]),
        ] {
            let units = Units {
                layout,
                channels: 1,
            };
            let record = Spec {
                one_to_one: false,
                width: 1,
                order: 0,
                mark: false,
                first: 0,
                count: units.cell(),
            };
            let opening = Spec {
                one_to_one: true,
                ..record
            };
            let mut specs = vec![
                Spec {
                    mark: true,
                    ..opening
                },
                opening,
                record,
                record,
                record,
                record,
            ];
            pad_to_packet(&mut specs, 0, units).unwrap();
            assert_eq!(
                specs.iter().map(|s| s.width).collect::<Vec<_>>(),
                widths,
                "{layout:?}"
            );
            let words: usize = specs.iter().map(|s| s.span(units)).sum();
            assert_eq!(words % units.packet_words(), 0, "{layout:?}");
        }
    }

    /// The cap is the generation's own constant, so a content record sitting one width
    /// under it is widened past itself before the next record is reached — and only as
    /// far as the cap, whatever room the record still has. Each region here opens with
    /// its alignment run and is two words short of a whole packet: the narrow chain and
    /// v3 spend those two words one to a record, v4 spends both on the first.
    #[test]
    fn the_widen_cap_is_the_generations_constant() {
        for (layout, alignment, content, spent) in [
            (Layout::V2, 2usize, 9usize, [13u8, 13]),
            (Layout::V3, 1, 2, [13, 13]),
            (Layout::V4, 1, 2, [14, 12]),
        ] {
            let units = Units {
                layout,
                channels: 1,
            };
            // Cell-sized, so the region has nothing left to split and must be widened.
            let record = Spec {
                one_to_one: false,
                width: 12,
                order: 0,
                mark: false,
                first: 0,
                count: units.cell(),
            };
            let mut specs: Vec<Spec> = (0..alignment)
                .map(|i| Spec {
                    one_to_one: true,
                    width: 3,
                    mark: i == 0,
                    ..record
                })
                .chain(std::iter::repeat_n(record, content))
                .collect();
            pad_to_packet(&mut specs, 0, units).unwrap();

            let mut want = vec![3u8; alignment];
            want.extend(spent);
            want.resize(alignment + content, record.width);
            assert_eq!(
                specs.iter().map(|s| s.width).collect::<Vec<_>>(),
                want,
                "{layout:?}"
            );
            let words: usize = specs.iter().map(|s| s.span(units)).sum();
            assert_eq!(words % units.packet_words(), 0, "{layout:?}");
        }
    }

    #[test]
    fn a_loop_that_needs_width_past_the_measured_cap_is_refused() {
        let units = Units {
            layout: Layout::V3,
            channels: 1,
        };
        let record = Spec {
            one_to_one: false,
            width: widen_cap(Layout::V3),
            order: 0,
            mark: false,
            first: 0,
            count: units.cell(),
        };
        let mut specs = vec![
            Spec {
                one_to_one: true,
                width: 1,
                mark: true,
                ..record
            },
            record,
            record,
        ];
        let before = specs.clone();
        assert!(pad_to_packet(&mut specs, 0, units).is_err());
        assert_eq!(specs, before);
    }

    #[test]
    fn a_loop_lands_on_a_packet_boundary_or_is_refused() {
        let mut source = Vec::with_capacity(60_000);
        let mut state = 12_345u64;
        for k in 0..60_000u64 {
            state = state
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1);
            let noise = ((state >> 40) as i32 - 8_192) / 4;
            let tone = (20_000.0 * (k as f64 * 0.031).sin()) as i32;
            source.push((tone + noise).clamp(-32_768, 32_767) as i16);
        }

        let mut placed = 0usize;
        let mut refused = 0usize;
        for start in (4_096..48_000).step_by(7_919) {
            for length in [900, 1_500, 4_096, 11_000] {
                for predictor in [Predictor::Plain, Predictor::Minimising] {
                    let points =
                        Loop::new(start, start + length).crossfade((length / 4).min(start) as f64);
                    let options = Options::new("Sweep").predictor(predictor).loops(points);
                    let Ok(file) = instrument(&source, &options) else {
                        refused += 1;
                        continue;
                    };
                    let (at, stroke) = file.stroke_streams()[0];
                    let walk = codec::walk(stroke, at, codec::Layout::V2).unwrap();
                    let mark = walk.records.iter().find(|r| r.mark).unwrap();
                    assert_eq!(
                        (walk.terminator - mark.at) % PACKET_WORDS,
                        0,
                        "loop {start}..{} under {predictor:?} covers {} words",
                        start + length,
                        walk.terminator - mark.at
                    );
                    placed += 1;
                }
            }
        }
        assert!(placed > 0, "no loop was placed");
        assert!(refused > 0, "no loop was refused");
    }

    fn stereo(hz: f64, ratio: f64, amplitude: f64, frames: usize) -> Vec<i16> {
        let left = sine(hz, amplitude, frames);
        let right = sine(hz * ratio, amplitude * 0.6, frames);
        left.iter()
            .zip(&right)
            .flat_map(|(&l, &r)| [l, r])
            .collect()
    }

    #[test]
    fn a_stereo_plan_is_the_mono_plan_doubled() {
        for frames in [4096, 4409, 8192, 10_000, 44_100, 100_000, 441_000] {
            let mono = plan(frames, 1).unwrap();
            let both = plan(frames, 2).unwrap();
            assert_eq!(both.fields, 2 * mono.fields, "{frames} frames: T");
            assert_eq!(both.resync_at, 2 * mono.resync_at, "{frames} frames: R1");
            assert_eq!(both.warmup, 2 * mono.warmup, "{frames} frames: W");
            assert_eq!(both.resync, 2 * mono.resync, "{frames} frames: R");
            assert_eq!(both.cells_before, mono.cells_before, "{frames} frames");
            assert_eq!(both.cells_after, mono.cells_after, "{frames} frames");
            assert_eq!(
                both.warmup
                    + both.cell() * both.cells_before
                    + both.resync
                    + both.cell() * both.cells_after,
                both.fields,
                "{frames} frames: the plan does not tile the lattice"
            );
        }
    }

    #[test]
    fn a_stereo_stroke_round_trips_through_the_decoder_exactly() {
        for predictor in [Predictor::Plain, Predictor::Minimising] {
            let source = stereo(220.0, 1.5, 14_000.0, 30_000);
            let file = instrument(
                &source,
                &Options::new("Stereo").channels(2).predictor(predictor),
            )
            .unwrap();
            let (at, stroke) = file.stroke_streams()[0];

            let stream = codec::walk(stroke, at, codec::Layout::V2).unwrap();
            assert_eq!(stream.channels, 2, "{predictor:?}");
            assert_eq!(stream.cell, Some(2 * CELL), "{predictor:?}");
            assert_eq!(&stroke[stroke.len() - 3..], &[0x80, 0, 48]);

            let plan = plan(30_000, 2).unwrap();
            let q = quantise(&source, &plan, None);
            let audio = codec::decode(stroke, at, codec::Layout::V2).unwrap();
            assert_eq!(audio.channels, 2);
            assert_eq!(audio.samples.len(), plan.fields);
            let gain = 1i32 << q.shift;
            for (f, (&want, &got)) in q.values.iter().zip(&audio.samples).enumerate() {
                assert_eq!(i32::from(got), want * gain, "{predictor:?} field {f}");
            }
        }
    }

    #[test]
    fn each_channel_predicts_against_its_own_history() {
        let frames = 20_000;
        let source: Vec<i16> = (0..frames)
            .flat_map(|k| {
                let up = (k as i32 % 2048) - 1024;
                [up as i16, -(up as i16)]
            })
            .collect();
        let file = instrument(
            &source,
            &Options::new("Ramps")
                .channels(2)
                .predictor(Predictor::Minimising),
        )
        .unwrap();
        let (at, stroke) = file.stroke_streams()[0];
        let audio = codec::decode(stroke, at, codec::Layout::V2).unwrap();
        assert!(audio.differenced > 0, "nothing chose a predictor");

        let plan = plan(frames, 2).unwrap();
        let q = quantise(&source, &plan, None);
        let gain = 1i32 << q.shift;
        for (f, (&want, &got)) in q.values.iter().zip(&audio.samples).enumerate() {
            assert_eq!(i32::from(got), want * gain, "field {f}");
        }
    }

    #[test]
    fn the_channels_are_resampled_apart() {
        let frames = 12_000;
        let source: Vec<i16> = sine(300.0, 20_000.0, frames)
            .into_iter()
            .flat_map(|l| [l, 0])
            .collect();
        let file = instrument(&source, &Options::new("Panned").channels(2)).unwrap();
        let (at, stroke) = file.stroke_streams()[0];
        let audio = codec::decode(stroke, at, codec::Layout::V2).unwrap();
        assert!(audio.samples.iter().step_by(2).any(|&v| v.abs() > 10_000));
        assert!(audio.samples[1..].iter().step_by(2).all(|&v| v == 0));
    }

    #[test]
    fn a_stereo_stroke_loops_the_way_a_mono_one_does() {
        let source = stereo(180.0, 1.25, 16_000.0, 60_000);
        let points = Loop::new(8_192, 40_960).crossfade(2_048.0);
        let file = instrument(&source, &Options::new("Looped").channels(2).loops(points)).unwrap();
        let (at, stroke) = file.stroke_streams()[0];
        let walk = codec::walk(stroke, at, codec::Layout::V2).unwrap();
        assert_eq!(walk.channels, 2);
        let mark = walk.records.iter().find(|r| r.mark).unwrap();
        assert_eq!((walk.terminator - mark.at) % PACKET_WORDS, 0);
        let frames = (walk.fields - mark.first_field) as f64 / 2.0 * f64::from(codec::SOURCE_RATE)
            / f64::from(codec::FIELD_RATE);
        assert!(
            (frames - 32_768.0).abs() < 1.0,
            "loop came back {frames} frames"
        );

        let plan = looped(60_000, 2, points).unwrap();
        let q = quantise(&source, &plan, None);
        let audio = codec::decode(stroke, at, codec::Layout::V2).unwrap();
        let gain = 1i32 << q.shift;
        for (f, (&want, &got)) in q.values.iter().zip(&audio.samples).enumerate() {
            assert_eq!(i32::from(got), want * gain, "field {f}");
        }
    }

    #[test]
    fn a_channel_count_the_terminator_cannot_state_is_refused() {
        let source = vec![0i16; 3 * MIN_FRAMES];
        assert!(plan(MIN_FRAMES, 0).is_err());
        assert!(plan(MIN_FRAMES, 3).is_err());
        assert!(instrument(&source, &Options::new("x").channels(3)).is_err());
        assert!(instrument(
            &vec![0i16; 2 * MIN_FRAMES + 1],
            &Options::new("x").channels(2)
        )
        .is_err());
        assert!(instrument(&vec![0i16; 2 * MIN_FRAMES], &Options::new("x").channels(2)).is_ok());
        let short = vec![0i16; MIN_FRAMES];
        assert!(instrument(&short, &Options::new("x")).is_ok());
        assert!(instrument(&short, &Options::new("x").channels(2)).is_err());
    }

    /// Every generation, mono and stereo, through this crate's own decoder. v4 stereo
    /// is the one that packs each channel's half into its own words, so it is the one
    /// this would catch.
    #[test]
    fn every_generation_round_trips_through_the_decoder_exactly() {
        for layout in [Layout::V2, Layout::V3, Layout::V4] {
            for channels in [1u16, 2] {
                let frames = 30_000;
                let source: Vec<i16> = match channels {
                    1 => sine(220.0, 14_000.0, frames),
                    _ => stereo(220.0, 1.5, 14_000.0, frames),
                };
                let file = instrument(
                    &source,
                    &Options::new("Round trip")
                        .layout(layout)
                        .channels(channels)
                        .predictor(Predictor::Minimising),
                )
                .unwrap();
                let (at, stroke) = file.stroke_streams()[0];
                let plan = Plan::new(
                    layout,
                    frames,
                    usize::from(channels),
                    default_secondary_start(frames, None),
                )
                .unwrap();
                let q = quantise(&source, &plan, None);
                let audio = codec::decode(stroke, at, layout)
                    .unwrap_or_else(|e| panic!("{layout:?} {channels}ch: {e}"));
                assert_eq!(audio.channels, channels, "{layout:?} {channels}ch");
                assert_eq!(audio.samples.len(), plan.fields, "{layout:?} {channels}ch");
                let gain = 1i32 << q.shift;
                for (f, (&want, &got)) in q.values.iter().zip(&audio.samples).enumerate() {
                    assert_eq!(
                        i32::from(got),
                        want * gain,
                        "{layout:?} {channels}ch field {f}"
                    );
                }
            }
        }
    }

    #[test]
    fn a_wide_instrument_reads_back_as_one() {
        for (layout, version) in [(Layout::V3, 300u32), (Layout::V4, 400)] {
            let file = instrument(
                &sine(220.0, 15_000.0, 30_000),
                &Options::new("Encoded")
                    .layout(layout)
                    .root_key(48)
                    .top_note(72),
            )
            .unwrap();
            let bytes = file.to_bytes().unwrap();
            let read = crate::from_stream(&mut std::io::Cursor::new(&bytes)).unwrap();
            let crate::Entity::Sample(read) = read else {
                panic!("{layout:?} did not read back as a sample");
            };
            assert_eq!(read.name().unwrap(), "Encoded", "{layout:?}");
            assert_eq!(read.layout().unwrap(), layout, "{layout:?}");
            assert_eq!(read.to_bytes().unwrap(), bytes, "{layout:?}");
            let crate::Sample::V3(read) = &read else {
                panic!("{layout:?} did not read back on the wide chain");
            };
            assert_eq!(read.header.version, version);
            let zones = read.zones().unwrap();
            assert_eq!(zones.len(), 1);
            assert_eq!(zones[0].root_key, 48);
            assert_eq!(zones[0].top_note, 72);
            assert_eq!(zones[0].low_note, Some(super::super::zone::KEY_FLOOR));
            assert_eq!(
                read.meta().unwrap().chain_len as usize,
                read.chain_len_before_meta()
            );
        }
    }

    /// Zones tile: each reaches down to one above the one below it, and the lowest to
    /// the keyboard's floor. Records are stored high to low in every generation.
    #[test]
    fn a_wide_zone_states_its_own_bottom() {
        let high = sine(880.0, 12_000.0, 12_000);
        let low = sine(220.0, 12_000.0, 15_000);
        let floor = super::super::zone::KEY_FLOOR;
        let stored = [(96, 66), (65, floor)];
        for layout in [Layout::V3, Layout::V4] {
            let file = multi_zone(
                made("Two", Predictor::Plain, layout),
                &[zone(&high, 72, 96, 2), zone(&low, 48, 65, 1)],
            )
            .unwrap();
            let zones = file.zones().unwrap();
            assert_eq!(
                zones
                    .iter()
                    .map(|z| (z.top_note, z.low_note.unwrap()))
                    .collect::<Vec<_>>(),
                stored,
                "{layout:?}"
            );
        }
    }

    /// Decibel words read off editor renders of one project at sixteen stroke gains,
    /// four of them predicted before the render and landing on it. The logarithm is
    /// evaluated wider than the field and rounded once: computing it in float32
    /// throughout moves the last byte on the powers of two.
    #[test]
    fn a_zone_gain_in_decibels_is_the_word_the_editor_writes() {
        for (gain, word) in [
            (-1.0, 0x7fc0_0000u32),
            (0.0, 0xff80_0000),
            (0.01, 0xc220_0000),
            (0.1, 0xc1a0_0000),
            (0.5, 0xc0c0_a8c1),
            (1.0, 0x0000_0000),
            (1.1, 0x3f53_ee38),
            (1.5, 0x4061_6595),
            (2.0, 0x40c0_a8c1),
            (4.0, 0x4140_a8c1),
            (8.0, 0x4190_7e91),
            (16.0, 0x41c0_a8c1),
            (20.5, 0x41d1_e170),
            (63.75, 0x4210_5bc1),
            (333.33, 0x4249_d478),
            (1000.0, 0x4270_0000),
        ] {
            assert_eq!(gain_decibels(gain).to_bits(), word, "a gain of {gain}");
        }
    }

    /// Statistic A's mantissa is built from the decibel and not from the project's
    /// float. The two part company only past `2^24`, and these deltas are what the
    /// editor writes there.
    #[test]
    fn the_gain_statistic_a_uses_is_the_decibels_round_trip() {
        for (gain, delta) in [
            (0.01, 0i64),
            (1.1, 0),
            (15.99, 0),
            (16.0, -1),
            (20.5, -1),
            (24.0, 1),
            (33.0, 2),
            (48.0, -1),
            (63.75, -3),
            (100.0, 0),
            (333.33, 39),
            (1000.0, 0),
        ] {
            let plain = (gain * f64::from(GAIN_UNITY)).round() as i64;
            let round_trip = gain_units(gain_decibels(gain)) as i64;
            assert_eq!(round_trip - plain, delta, "a gain of {gain}");
        }
    }

    /// Fixed-point words read off editor renders of one project at eleven map gains.
    /// The ceiling is a clamp on the decibel: the knee sits on a round +9.000 dB
    /// rather than on a round linear number, and a negative gain — whose decibel is a
    /// NaN — fails the comparison and takes the ceiling rather than the floor.
    #[test]
    fn a_map_gain_is_the_word_the_editor_writes_and_clamps_at_the_ceiling() {
        for (gain, units) in [
            (-1.0, 0x2d_18_19_u32),
            (0.0, 0x00_00_00),
            (0.0001, 0x00_00_69),
            (0.01, 0x00_28_f6),
            (0.5, 0x08_00_00),
            (1.0, 0x10_00_00),
            (1.1, 0x11_99_9a),
            (2.0, 0x20_00_00),
            (2.8125, 0x2d_00_00),
            (2.828125, 0x2d_18_19),
            (4.0, 0x2d_18_19),
            (16.0, 0x2d_18_19),
        ] {
            assert_eq!(map_gain_units(gain), units, "a map gain of {gain}");
        }
    }

    /// A zone gain past 16 overflows both u24 stores, by different rules: the record
    /// takes the project's float and wraps, and the mantissa takes the decibel's round
    /// trip and truncates into its field. Words read off editor renders.
    #[test]
    fn a_zone_gain_past_sixteen_wraps_in_both_stores() {
        for (gain, record) in [
            (-1.0, 0x00_00_00_u32),
            (0.0, 0x00_00_00),
            (15.99, 0xff_d7_0a),
            (16.0, 0x00_00_00),
            (33.0, 0x10_00_00),
            (333.33, 0xd5_47_ae),
            (1000.0, 0x80_00_00),
        ] {
            assert_eq!(zone_record_gain(gain), record, "a gain of {gain}");
        }
        // `WG-base`'s peak is 4096, so the reciprocal is 2^22 and every step below is
        // exact in integers.
        for (gain, mantissa) in [
            (-1.0, 0x00_00_00_u32),
            (0.0, 0x00_00_00),
            (15.99, 0x7f_eb_85),
            (16.0, 0x7f_ff_ff),
            (33.0, 0x08_00_01),
            (333.33, 0x6a_a3_ea),
            (1000.0, 0x40_00_00),
        ] {
            let (got, _) = statistic_a(4096, 0, gain_units(gain_decibels(gain)));
            assert_eq!(got, mantissa, "a gain of {gain}");
        }
    }

    /// The map gain opens the `map` section and reaches nothing else — not the zone
    /// records, not statistic A, not a stream byte.
    #[test]
    fn a_map_gain_moves_the_map_section_alone() {
        let source = sine(440.0, 12_000.0, 20_000);
        for layout in [Layout::V2, Layout::V3, Layout::V4] {
            let unity = made("Map", Predictor::Plain, layout);
            let quiet = Instrument {
                map_gain: 0.5,
                ..unity
            };
            let one = [zone(&source, 60, 127, 1)];
            let before = multi_zone(unity, &one).unwrap().to_bytes().unwrap();
            let after = multi_zone(quiet, &one).unwrap().to_bytes().unwrap();
            assert_eq!(before.len(), after.len(), "{layout:?}");
            let moved: Vec<_> = (0..before.len())
                .filter(|&i| before[i] != after[i])
                .collect();
            // The gain's own top byte — 0x10 against 0x08 — and the container checksum.
            assert!(moved.len() <= 1 + 4, "{layout:?}: {moved:?}");
        }
    }

    #[test]
    fn a_project_preset_reaches_each_generation_in_its_own_schema() {
        let source = sine(440.0, 12_000.0, 20_000);
        let preset = Preset {
            dynamics_enabled: true,
            velocity_to_amplitude: 2,
            velocity_to_timbre: 0,
        };
        for layout in [Layout::V2, Layout::V3, Layout::V4] {
            let instrument = Instrument {
                preset,
                ..made("Preset", Predictor::Plain, layout)
            };
            let sample = multi_zone(instrument, &[zone(&source, 60, 127, 1)]).unwrap();
            match sample {
                crate::Sample::V2(file) => {
                    let sty = section::find(&file.body.sections, section::STY).unwrap();
                    assert_eq!(sty.payload, [0, 1, 0, 1, 2, 0, 0, 0, 0]);
                }
                crate::Sample::V3(file) => {
                    let sty = section::find4(&file.body.sections, section::STY4).unwrap();
                    match layout {
                        Layout::V3 => {
                            assert_eq!((sty.payload[4], sty.payload[12]), (43, 74));
                            assert_eq!((sty.payload[14], sty.payload[16]), (1, 74));
                        }
                        Layout::V4 => {
                            assert_eq!((sty.payload[3], sty.payload[4]), (1, 1));
                            assert_eq!(sty.payload[85..88], [74, 82, 90]);
                        }
                        Layout::V2 => unreachable!(),
                    }
                }
            }
        }
    }

    /// A wide zone gain reaches the stroke header's decibel field and statistic A, and
    /// nothing else: no byte of the 16-byte zone record moves with it.
    #[test]
    fn a_wide_zone_gain_lands_in_the_stroke_header() {
        let source = sine(440.0, 12_000.0, 20_000);
        for layout in [Layout::V3, Layout::V4] {
            let one = zone(&source, 60, 127, 1);
            let made = made("Gain", Predictor::Plain, layout);
            let unity = multi_zone(made, &[one]).unwrap();
            let halved = multi_zone(made, &[NewZone { gain: 0.5, ..one }]).unwrap();
            let (_, a) = unity.stroke_streams()[0];
            let (_, b) = halved.stroke_streams()[0];
            let mantissa = |s: &[u8]| u32::from_be_bytes([0, s[9], s[10], s[11]]);
            assert_eq!(mantissa(b), mantissa(a) / 2, "{layout:?}");
            let gain_at = codec::TAIL_FLOATS_AT[0];
            assert_eq!(a[..9], b[..9], "{layout:?}");
            assert_eq!(a[12..gain_at], b[12..gain_at], "{layout:?}");
            assert_eq!(a[gain_at + 4..], b[gain_at + 4..], "{layout:?}");
            assert_eq!(
                codec::zone_gain_db(b, layout),
                Some(gain_decibels(0.5)),
                "{layout:?}"
            );
            // Statistic A's mantissa, the decibel word and the container checksum are
            // the whole of what a zone gain moves; the zone record does not.
            let (before, after) = (unity.to_bytes().unwrap(), halved.to_bytes().unwrap());
            let differing = before.iter().zip(&after).filter(|(x, y)| x != y).count();
            assert_eq!(before.len(), after.len(), "{layout:?}");
            assert!(differing <= 3 + 4 + 4, "{layout:?}: {differing} bytes");
        }
    }

    /// The loop decay amount is the wide header's second float32, verbatim in the
    /// project's own units, and the narrow header is too short to hold it at all.
    #[test]
    fn a_loop_decay_lands_in_the_wide_header_and_nowhere_narrow() {
        let source = sine(440.0, 12_000.0, 20_000);
        let at = codec::TAIL_FLOATS_AT[1];
        for layout in [Layout::V2, Layout::V3, Layout::V4] {
            let one = zone(&source, 60, 127, 1);
            let made = made("Decay", Predictor::Plain, layout);
            let base = multi_zone(made, &[one]).unwrap();
            let slower = multi_zone(
                made,
                &[NewZone {
                    loop_decay: 60.0,
                    ..one
                }],
            )
            .unwrap();
            let (_, a) = base.stroke_streams()[0];
            let (_, b) = slower.stroke_streams()[0];
            let wide = layout != Layout::V2;
            assert_eq!(
                codec::loop_decay(a, layout),
                wide.then_some(DEFAULT_LOOP_DECAY),
                "{layout:?}"
            );
            assert_eq!(
                codec::loop_decay(b, layout),
                wide.then_some(60.0),
                "{layout:?}"
            );
            match wide {
                false => assert_eq!(a, b),
                true => {
                    assert_eq!(a[..at], b[..at], "{layout:?}");
                    assert_eq!(a[at + 4..], b[at + 4..], "{layout:?}");
                }
            }
        }
    }

    #[test]
    fn a_zone_gain_past_the_measured_range_is_refused() {
        let source = sine(440.0, 12_000.0, 20_000);
        for layout in [Layout::V2, Layout::V3, Layout::V4] {
            for gain in [MAX_ZONE_GAIN * 2.0, f64::NAN, f64::INFINITY] {
                let loud = NewZone {
                    gain,
                    ..zone(&source, 60, 127, 1)
                };
                assert!(
                    multi_zone(made("Gain", Predictor::Plain, layout), &[loud]).is_err(),
                    "{layout:?} at {gain}"
                );
            }
            let wrapping = NewZone {
                gain: MAX_ZONE_GAIN,
                ..zone(&source, 60, 127, 1)
            };
            assert!(multi_zone(made("Gain", Predictor::Plain, layout), &[wrapping]).is_ok());
        }
    }

    /// The wide terminator states 32 fields per channel where the narrow one states 24,
    /// and a 1:1 run reaches 48 fields per channel rather than 32.
    #[test]
    fn the_wide_plan_tiles_the_lattice_in_its_own_units() {
        for frames in [4096, 10_000, 44_100, 100_000] {
            for layout in [Layout::V3, Layout::V4] {
                let p =
                    Plan::new(layout, frames, 1, default_secondary_start(frames, None)).unwrap();
                assert_eq!(p.cell(), 32, "{layout:?} {frames} frames");
                assert_eq!(
                    p.warmup + p.cell() * p.cells_before + p.resync + p.cell() * p.cells_after,
                    p.fields,
                    "{layout:?} {frames} frames"
                );
                for run in chunks(p.warmup, p.chunk())
                    .into_iter()
                    .chain(chunks(p.resync, p.chunk()))
                {
                    assert!(
                        (32..=48).contains(&run),
                        "{layout:?} {frames} frames: {run}"
                    );
                }
            }
        }
    }

    /// A silent wide stroke stores statistic B as a signed extreme, so it reads back
    /// through the codec's own sign rule rather than as a 24-bit magnitude.
    #[test]
    fn a_wide_statistic_b_carries_the_extremes_sign() {
        let frames = 20_000;
        let mut down = vec![0i16; frames];
        down[10_000] = -13;
        for layout in [Layout::V2, Layout::V3, Layout::V4] {
            let file = instrument(&down, &Options::new("Peak").layout(layout)).unwrap();
            let (_, stroke) = file.stroke_streams()[0];
            let want = if layout.signed_peak() { -3 } else { 3 };
            assert_eq!(codec::peak(stroke, layout), Some(want), "{layout:?}");
        }
    }

    #[test]
    fn silence_codes_at_the_draft_width_throughout() {
        let file = encoded(&vec![0i16; 44_100], Predictor::Plain);
        let (at, stroke) = file.stroke_streams()[0];
        let stream = codec::walk(stroke, at, codec::Layout::V2).unwrap();
        assert!(stream.records.iter().all(|r| r.width == MIN_WIDTH));
        assert!(stream
            .records
            .iter()
            .all(|r| r.values.iter().all(|&v| v == 0)));
        assert_eq!(codec::peak(stroke, codec::Layout::V2), Some(0));
        assert!(codec::decode(stroke, at, codec::Layout::V2)
            .unwrap()
            .samples
            .iter()
            .all(|&s| s == 0));
    }
}