nooise 2.5.5

Ambient music generator for the terminal
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
//! Song codes: the binary snapshot format behind `Ctrl+S` and
//! `nooise <code>`.
//!
//! This module owns the container version and every value encoding. Control
//! values are generic over `all_specs()`; anything that is not a flat control
//! value (automation routes, runtime session records) gets its own record
//! type. Unknown record types skip; an unknown container version is fatal.

use std::collections::BTreeSet;
use std::error::Error;
use std::fmt;

use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;

use super::range_epoch::{CURRENT_RANGE_EPOCH, stale_modulation};
use super::song_ids::{song_id_at, song_id_index};
use super::voice::{TONAL_MAX_LOOP_STEPS, TONAL_PHRASES, TonalSequenceState};
use super::{
    AutomationState, ControlAddress, ControlKind, ControlSpec, DEFAULT_LFO_DEPTH_RATIO, EnvTrigger,
    EnvelopeRoute, FluidControls, GESTURE_COUNT, GestureEnvelope, GestureKind, GestureState,
    LfoRoute, LfoShape, MAX_AUTOMATION_LANES_PER_KIND, MAX_ENV_ATTACK_BEATS, MAX_ENV_DECAY_BEATS,
    MAX_LFO_CYCLE_BEATS, MAX_LFO_OFFSET_BEATS, MAX_LFO_STEPS, MIN_LFO_CYCLE_BEATS, MUTE_BYTES,
    ModKind, ModuleSlotField, MuteState, PAD_RHYTHM_ROWS, Step, TAB_COUNT, Tab, all_specs,
    parse_module_slot_id, spec_by_id,
};

const MAGIC: &[u8; 4] = b"NOOI";
/// Control ids are interned as `SONG_ID_TABLE` indexes and continuous values
/// are quantized to a u16 taper position. The container version is the
/// format's version axis. Capture alone versions its playback-period payload;
/// other record payloads carry no version byte of their own.
/// The one other axis is the dial-range epoch (`range_epoch.rs`), which dates
/// what a stored modulation depth means rather than how bytes are laid out. Version 1 (length-
/// prefixed ids, f32 values, its own nested automation payload versions) is
/// gone; a v1 code is rejected with a message telling the user why.
pub(crate) const CONTAINER_VERSION: u8 = 2;
/// Unchanged across container versions: the CLI, `just add-morph`, and both
/// Python helpers all match song codes on this prefix.
pub(crate) const CODE_PREFIX: &str = "n1_";
pub(crate) const SNAPSHOT_RECORD: u8 = 0;
pub(crate) const AUTOMATION_RECORD: u8 = 1;
const TONAL_SEQUENCE_RECORD: u8 = 2;
const MUTE_RECORD: u8 = 3;
const GESTURE_RECORD: u8 = 4;
/// `u16` dial-range epoch the code was written under. Absent means epoch 0.
const RANGE_EPOCH_RECORD: u8 = 5;
/// Optional MIDI-row visibility; one bit per Pad, Arp, and Lead In/Out row.
const MIDI_ROWS_RECORD: u8 = 6;
/// Pad rhythm rows hidden during MIDI startup and restored with a song.
const PAD_RHYTHM_ROWS_RECORD: u8 = 7;
/// Visibility bit of the retired `pad.swing` row. Visibility is not audible
/// state; the swing value itself is refused as `RetiredControl`.
const RETIRED_PAD_SWING_ROW: u8 = 1 << 1;
const CAPTURE_RECORD: u8 = 8;
const LANE_BYPASS_RECORD: u8 = 9;
/// The playback period is semantic song state: refuse the sixteen-bar format
/// rather than silently speeding up saved loops.
const CAPTURE_WIRE_VERSION: u8 = 3;
const GESTURE_HELD_FLAG: u8 = 1 << 0;
/// Wire tag for each LFO shape. Append-only: a tag is part of every saved
/// code that carries the shape. `shape_tag`/`shape_from_tag` are the two
/// directions of this one table.
const LFO_SHAPE_TAGS: [(LfoShape, u8); 8] = [
    (LfoShape::Sine, 0),
    (LfoShape::Triangle, 1),
    (LfoShape::RampUp, 2),
    (LfoShape::RampDown, 3),
    (LfoShape::Square, 4),
    (LfoShape::RandomDrift, 5),
    (LfoShape::SampleHold, 6),
    (LfoShape::Steps, 7),
];
const ENV_TRIGGER_EVERY_BEATS: u8 = 0;
const ENV_TRIGGER_ON_KICK: u8 = 1;
const ENV_TRIGGER_ONCE: u8 = 2;
/// Fallback `EveryBeats` interval for an envelope whose stored trigger param
/// is non-finite; matches `EnvTrigger`'s own "every 4 beats" default.
const DEFAULT_ENV_TRIGGER_BEATS: f32 = 4.0;

#[derive(Clone, Default)]
pub(crate) struct SongState {
    pub(crate) controls: FluidControls,
    pub(crate) automation: AutomationState,
    pub(crate) tonal_sequence: Option<TonalSequenceState>,
    pub(crate) muted: MuteState,
    pub(crate) gestures: GestureState,
}

impl SongState {
    pub(crate) fn from_controls(controls: FluidControls) -> Self {
        Self {
            controls,
            automation: AutomationState::default(),
            tonal_sequence: None,
            muted: [false; TAB_COUNT],
            gestures: GestureState::default(),
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum SongCodeError {
    MissingPrefix,
    InvalidBase64,
    InvalidMagic,
    UnsupportedVersion(u8),
    Truncated,
    TooLarge,
    /// A stored value carried a tag this build has no encoding for.
    InvalidValueTag(u8),
    InvalidGestureTarget(u8),
    InvalidGestureKind(u8),
    InvalidGestureFlags(u8),
    InvalidGestureCount(u8),
    InvalidGestureAmount,
    InvalidGestureTimeAnchor {
        target: u8,
        kind: u8,
    },
    DuplicateGesture {
        target: u8,
        kind: u8,
    },
    DuplicateGestureRecord,
    InvalidMidiRows(u8),
    DuplicateMidiRowsRecord,
    InvalidPadRhythmRows(u8),
    DuplicatePadRhythmRowsRecord,
    InvalidCapture,
    InvalidLaneBypass,
    /// The code sets a control this build retired. Its value has nowhere to
    /// go, so the code is refused rather than loaded with that value missing.
    RetiredControl(&'static str),
    /// An LFO Steps lane on this control carries a negative step. Steps are
    /// unipolar now; the value has no equivalent, so the code is refused.
    NegativeLfoStep(&'static str),
    /// The code is from an older dial-range epoch and modulates a dial whose
    /// range has changed since, so its depths would sweep the wrong span.
    /// Like a retired control, it is refused rather than reinterpreted.
    StaleRange(&'static str),
    /// The code gives a table-indexed control (`ControlSpec::song_values`) a
    /// value this build has no entry for, most likely one a newer build
    /// added. Loading it would put some other entry in its place.
    UnknownValue {
        id: &'static str,
        value: i16,
    },
    /// The code gives a table-indexed control a value that is not a whole
    /// number, which no writer produces.
    NotATableValue(&'static str),
    /// A live control has no `SONG_ID_TABLE` slot, so it cannot be saved.
    /// `song_ids_cover_every_registry_control` exists to stop this reaching a
    /// user; append the id to the table.
    UnregisteredControl(&'static str),
}

impl fmt::Display for SongCodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidCapture => write!(f, "song code has an invalid captured loop"),
            Self::InvalidLaneBypass => write!(f, "song code has invalid lane bypass data"),
            Self::MissingPrefix => write!(f, "song code must start with {CODE_PREFIX}"),
            Self::InvalidBase64 => write!(f, "song code is not valid base64url"),
            Self::InvalidMagic => write!(f, "song code is not a nooise snapshot"),
            Self::UnsupportedVersion(version) => write!(
                f,
                "song code version {version} is from an older nooise and can no longer be read \
                 (this build writes and reads version {CONTAINER_VERSION})"
            ),
            Self::Truncated => write!(f, "song code is truncated"),
            Self::TooLarge => write!(f, "song code payload is too large"),
            Self::InvalidValueTag(tag) => write!(f, "song code has unknown value tag {tag}"),
            Self::InvalidGestureTarget(target) => {
                write!(f, "song code has unknown gesture target {target}")
            }
            Self::InvalidGestureKind(kind) => {
                write!(f, "song code has unknown gesture kind {kind}")
            }
            Self::InvalidGestureFlags(flags) => {
                write!(f, "song code has unknown gesture flags {flags:#04x}")
            }
            Self::InvalidGestureCount(count) => {
                write!(f, "song code has too many gesture entries ({count})")
            }
            Self::InvalidGestureAmount => {
                write!(f, "song code has a gesture amount outside 0..=1")
            }
            Self::InvalidGestureTimeAnchor { target, kind } => write!(
                f,
                "gesture kind {kind} on target {target} was not rebased to song time zero"
            ),
            Self::DuplicateGesture { target, kind } => write!(
                f,
                "song code repeats gesture kind {kind} on target {target}"
            ),
            Self::DuplicateGestureRecord => write!(f, "song code repeats the gesture record"),
            Self::InvalidMidiRows(rows) => {
                write!(f, "song code has unknown MIDI row bits {rows:#04x}")
            }
            Self::DuplicateMidiRowsRecord => write!(f, "song code repeats the MIDI rows record"),
            Self::InvalidPadRhythmRows(rows) => {
                write!(f, "song code has unknown Pad rhythm row bits {rows:#04x}")
            }
            Self::DuplicatePadRhythmRowsRecord => {
                write!(f, "song code repeats the Pad rhythm rows record")
            }
            Self::RetiredControl(id) => write!(
                f,
                "song code sets {id}, a control this build no longer has; the code predates the \
                 change that retired it and can no longer be loaded"
            ),
            Self::NegativeLfoStep(id) => write!(
                f,
                "song code gives the LFO on {id} a negative step; steps now run 0 to 100% and \
                 the code can no longer be loaded"
            ),
            Self::StaleRange(id) => write!(
                f,
                "song code modulates {id}, whose dial range changed after the code was saved; \
                 the code predates that change and can no longer be loaded"
            ),
            Self::UnknownValue { id, value } => write!(
                f,
                "song code sets {id} to {value}, which this build does not have; the code is \
                 probably from a newer nooise"
            ),
            Self::NotATableValue(id) => {
                write!(f, "song code gives {id} a value that is not a whole number")
            }
            Self::UnregisteredControl(id) => {
                write!(f, "control {id} is missing from the song id table")
            }
        }
    }
}

impl Error for SongCodeError {}

pub(crate) fn encode_song_code(song: &SongState) -> Result<String, SongCodeError> {
    encode_song_code_at_epoch(song, CURRENT_RANGE_EPOCH)
}

/// `encode_song_code` stamped with any dial-range epoch, so a test can write
/// a code the way an older build would have.
pub(crate) fn encode_song_code_at_epoch(
    song: &SongState,
    epoch: u16,
) -> Result<String, SongCodeError> {
    let mut bytes = Vec::new();
    bytes.extend_from_slice(MAGIC);
    bytes.push(CONTAINER_VERSION);
    write_record(RANGE_EPOCH_RECORD, &epoch.to_le_bytes(), &mut bytes)?;

    let mut snapshot = Vec::new();
    write_snapshot(&song.controls, &mut snapshot)?;
    write_record(SNAPSHOT_RECORD, &snapshot, &mut bytes)?;

    if automation_has_content(&song.automation) {
        let mut automation = Vec::new();
        write_automation(&song.automation, &mut automation)?;
        write_record(AUTOMATION_RECORD, &automation, &mut bytes)?;
    }
    let mut bypass = Vec::new();
    for (address, lfos, envelopes) in song.automation.bypass_masks() {
        write_control_index(address.id(), &mut bypass)?;
        bypass.extend_from_slice(&[lfos, envelopes]);
    }
    if !bypass.is_empty() {
        write_record(LANE_BYPASS_RECORD, &bypass, &mut bytes)?;
    }
    if !song.automation.captures.is_empty() {
        let mut captures = Vec::new();
        if song.automation.captures.len() > super::MAX_CAPTURES {
            return Err(SongCodeError::InvalidCapture);
        }
        captures.push(CAPTURE_WIRE_VERSION);
        captures.push(song.automation.captures.len() as u8);
        for (address, clip) in &song.automation.captures {
            validate_capture(clip)?;
            if !super::capture_eligible(&address.spec().contextual(&song.controls)) {
                return Err(SongCodeError::InvalidCapture);
            }
            let id = song_id_index(address.id())
                .ok_or(SongCodeError::UnregisteredControl(address.id()))?;
            captures.extend_from_slice(&id.to_le_bytes());
            captures.push(u8::from(clip.enabled));
            captures.extend_from_slice(&clip.origin.to_le_bytes());
            captures.extend_from_slice(&clip.launch.to_le_bytes());
            captures.extend_from_slice(&clip.samples);
        }
        write_record(CAPTURE_RECORD, &captures, &mut bytes)?;
    }

    if let Some(sequence) = &song.tonal_sequence {
        let mut tonal_sequence = Vec::new();
        write_tonal_sequence(sequence, &mut tonal_sequence)?;
        write_record(TONAL_SEQUENCE_RECORD, &tonal_sequence, &mut bytes)?;
    }
    if song.muted.iter().any(|muted| *muted) {
        write_record(MUTE_RECORD, &mute_bytes(&song.muted), &mut bytes)?;
    }
    if song.controls.midi_rows != 0 {
        write_record(MIDI_ROWS_RECORD, &[song.controls.midi_rows], &mut bytes)?;
    }
    if song.controls.hidden_pad_rhythm_rows != PAD_RHYTHM_ROWS {
        write_record(
            PAD_RHYTHM_ROWS_RECORD,
            &[song.controls.hidden_pad_rhythm_rows],
            &mut bytes,
        )?;
    }
    let mut gestures = Vec::new();
    if write_gestures(&song.gestures, &mut gestures)? {
        write_record(GESTURE_RECORD, &gestures, &mut bytes)?;
    }
    Ok(format!("{CODE_PREFIX}{}", URL_SAFE_NO_PAD.encode(bytes)))
}

/// Decode a code this build can play. A code from an older dial-range epoch
/// that modulates a dial moved since is refused (`StaleRange`).
pub(crate) fn decode_song_code(code: &str) -> Result<SongState, SongCodeError> {
    let (song, epoch) = decode_song_code_at_any_epoch(code)?;
    match stale_modulation(&song, epoch) {
        Some(id) => Err(SongCodeError::StaleRange(id)),
        None => Ok(song),
    }
}

/// Decode a code and report its dial-range epoch without judging it.
fn decode_song_code_at_any_epoch(code: &str) -> Result<(SongState, u16), SongCodeError> {
    let encoded = code
        .strip_prefix(CODE_PREFIX)
        .ok_or(SongCodeError::MissingPrefix)?;
    let bytes = URL_SAFE_NO_PAD
        .decode(encoded)
        .map_err(|_| SongCodeError::InvalidBase64)?;
    let mut reader = Reader::new(&bytes);

    if reader.bytes(MAGIC.len())? != MAGIC {
        return Err(SongCodeError::InvalidMagic);
    }
    match reader.u8()? {
        CONTAINER_VERSION => decode_container(&mut reader),
        version => Err(SongCodeError::UnsupportedVersion(version)),
    }
}

fn decode_container(reader: &mut Reader) -> Result<(SongState, u16), SongCodeError> {
    let mut song = SongState::default();
    let mut gesture_record_seen = false;
    let mut midi_rows_record_seen = false;
    let mut pad_rhythm_rows_record_seen = false;
    let mut capture_record_seen = false;
    let mut lane_bypass = None;
    let mut epoch = 0;

    while !reader.is_empty() {
        let record_type = reader.u8()?;
        let len = reader.u32()? as usize;
        let payload = reader.bytes(len)?;
        match record_type {
            LANE_BYPASS_RECORD => {
                if lane_bypass.replace(payload).is_some() {
                    return Err(SongCodeError::InvalidLaneBypass);
                }
            }
            CAPTURE_RECORD => {
                if capture_record_seen {
                    return Err(SongCodeError::InvalidCapture);
                }
                capture_record_seen = true;
                read_captures(payload, &mut song.automation)?;
            }
            SNAPSHOT_RECORD => read_snapshot(payload, &mut song.controls)?,
            AUTOMATION_RECORD => read_automation(payload, &mut song.automation)?,
            TONAL_SEQUENCE_RECORD => song.tonal_sequence = Some(read_tonal_sequence(payload)?),
            MUTE_RECORD => read_mute(payload, &mut song.muted)?,
            RANGE_EPOCH_RECORD => epoch = Reader::new(payload).u16()?,
            MIDI_ROWS_RECORD => {
                if midi_rows_record_seen {
                    return Err(SongCodeError::DuplicateMidiRowsRecord);
                }
                midi_rows_record_seen = true;
                let mut rows = Reader::new(payload);
                let bits = rows.u8()?;
                if !rows.is_empty() || bits & !0b00_111111 != 0 {
                    return Err(SongCodeError::InvalidMidiRows(bits));
                }
                song.controls.midi_rows = bits;
            }
            PAD_RHYTHM_ROWS_RECORD => {
                if pad_rhythm_rows_record_seen {
                    return Err(SongCodeError::DuplicatePadRhythmRowsRecord);
                }
                pad_rhythm_rows_record_seen = true;
                let mut rows = Reader::new(payload);
                let bits = rows.u8()?;
                if !rows.is_empty() || bits & !(PAD_RHYTHM_ROWS | RETIRED_PAD_SWING_ROW) != 0 {
                    return Err(SongCodeError::InvalidPadRhythmRows(bits));
                }
                song.controls.hidden_pad_rhythm_rows = bits & PAD_RHYTHM_ROWS;
            }
            GESTURE_RECORD => {
                if gesture_record_seen {
                    return Err(SongCodeError::DuplicateGestureRecord);
                }
                gesture_record_seen = true;
                read_gestures(payload, &mut song.gestures)?;
            }
            // Records are length-prefixed, so an unknown one is skipped
            // without losing alignment. This stays permissive on purpose: it
            // is how a code from a newer nooise carrying a record this build
            // has never heard of still loads everything else. Version
            // mismatches are caught at the container version, which is a hard
            // error — this is forward compatibility, not a silent fallback.
            _ => {}
        }
    }

    if let Some(payload) = lane_bypass {
        read_lane_bypass(payload, &mut song)?;
    }
    for address in song.automation.captures.keys() {
        if !super::capture_eligible(&address.spec().contextual(&song.controls))
            || (parse_module_slot_id(address.id()).is_some()
                && super::module_slot_row(address.id(), &song.controls)
                    .is_none_or(|(slot, _)| slot.kind().is_none()))
        {
            return Err(SongCodeError::InvalidCapture);
        }
    }
    Ok((song, epoch))
}

fn read_lane_bypass(payload: &[u8], song: &mut SongState) -> Result<(), SongCodeError> {
    if payload.is_empty() || !payload.len().is_multiple_of(4) {
        return Err(SongCodeError::InvalidLaneBypass);
    }
    let mut seen = BTreeSet::new();
    for entry in payload.chunks_exact(4) {
        let index = u16::from_le_bytes([entry[0], entry[1]]);
        reject_retired_control(index)?;
        let spec = control_at(index).ok_or(SongCodeError::InvalidLaneBypass)?;
        let address = ControlAddress::new(spec.id);
        let [lfos, envelopes] = [entry[2], entry[3]];
        if !seen.insert(address)
            || lfos | envelopes == 0
            || (lfos | envelopes) & !0x0f != 0
            || (parse_module_slot_id(spec.id).is_some()
                && super::module_slot_row(spec.id, &song.controls)
                    .is_none_or(|(slot, _)| slot.kind().is_none()))
        {
            return Err(SongCodeError::InvalidLaneBypass);
        }
        for (kind, mask) in [(ModKind::Lfo, lfos), (ModKind::Envelope, envelopes)] {
            for lane in 0..MAX_AUTOMATION_LANES_PER_KIND {
                if mask & (1 << lane) != 0
                    && !song.automation.set_lane_enabled(address, kind, lane, false)
                {
                    return Err(SongCodeError::InvalidLaneBypass);
                }
            }
        }
    }
    Ok(())
}

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

    fn source() -> SongState {
        let mut song = SongState::default();
        let address = ControlAddress::new("master.level");
        for index in 0..4 {
            song.automation.add_route(
                address,
                LfoRoute {
                    enabled: index % 2 == 0,
                    depth_ratio: 0.25,
                    ..LfoRoute::default()
                },
            );
            song.automation.add_envelope(
                address,
                EnvelopeRoute {
                    enabled: index % 2 != 0,
                    amount: -0.5,
                    ..EnvelopeRoute::default()
                },
            );
        }
        song
    }

    #[test]
    fn bypass_masks_round_trip_and_can_precede_lane_records() {
        let song = source();
        let code = encode_song_code(&song).unwrap();
        assert!(code.len() < 2000);
        let loaded = decode_song_code(&code).unwrap();
        assert_eq!(
            song.automation.bypass_masks().collect::<Vec<_>>(),
            loaded.automation.bypass_masks().collect::<Vec<_>>()
        );
        let id = song_id_index("master.level").unwrap().to_le_bytes();
        let payload = [id[0], id[1], 0b1010, 0b0101];
        let mut lanes = Vec::new();
        write_automation(&song.automation, &mut lanes).unwrap();
        let reversed = code_from_records(
            CONTAINER_VERSION,
            &[(LANE_BYPASS_RECORD, &payload), (AUTOMATION_RECORD, &lanes)],
        );
        assert_eq!(
            decode_song_code(&reversed)
                .unwrap()
                .automation
                .bypass_masks()
                .collect::<Vec<_>>(),
            loaded.automation.bypass_masks().collect::<Vec<_>>()
        );
        let old = code_from_records(CONTAINER_VERSION, &[(AUTOMATION_RECORD, &lanes)]);
        let old = decode_song_code(&old).unwrap();
        assert!(old.automation.routes().all(|(_, lane)| lane.enabled));
        assert!(old.automation.envelopes().all(|(_, lane)| lane.enabled));
        assert!(old.automation.bypass_masks().next().is_none());
    }

    #[test]
    fn malformed_bypass_masks_are_refused_instead_of_ignored() {
        let id = song_id_index("master.level").unwrap().to_le_bytes();
        let valid = [id[0], id[1], 1, 0];
        let mut lanes = Vec::new();
        write_automation(&source().automation, &mut lanes).unwrap();
        for invalid in [
            vec![],
            vec![id[0]],
            vec![id[0], id[1], 1, 0, 0],
            vec![id[0], id[1], 0, 0],
            vec![id[0], id[1], 16, 0],
            vec![id[0], id[1], 0, 16],
            vec![255, 255, 1, 0],
            valid.repeat(2),
        ] {
            let code = code_from_records(
                CONTAINER_VERSION,
                &[(AUTOMATION_RECORD, &lanes), (LANE_BYPASS_RECORD, &invalid)],
            );
            assert_eq!(
                decode_song_code(&code).err(),
                Some(SongCodeError::InvalidLaneBypass),
                "{invalid:?}"
            );
        }
        let duplicate = code_from_records(
            CONTAINER_VERSION,
            &[
                (AUTOMATION_RECORD, &lanes),
                (LANE_BYPASS_RECORD, &valid),
                (LANE_BYPASS_RECORD, &valid),
            ],
        );
        assert_eq!(
            decode_song_code(&duplicate).err(),
            Some(SongCodeError::InvalidLaneBypass)
        );
        let missing = code_from_records(CONTAINER_VERSION, &[(LANE_BYPASS_RECORD, &valid)]);
        assert_eq!(
            decode_song_code(&missing).err(),
            Some(SongCodeError::InvalidLaneBypass)
        );
        let retired = song_id_index("pad.reverb_mix").unwrap().to_le_bytes();
        let mut one_lane = AutomationState::default();
        one_lane.add_route(ControlAddress::new("master.level"), LfoRoute::default());
        let mut one_lane_bytes = Vec::new();
        write_automation(&one_lane, &mut one_lane_bytes).unwrap();
        let sparse = code_from_records(
            CONTAINER_VERSION,
            &[
                (AUTOMATION_RECORD, &one_lane_bytes),
                (LANE_BYPASS_RECORD, &[id[0], id[1], 8, 0]),
            ],
        );
        assert_eq!(
            decode_song_code(&sparse).err(),
            Some(SongCodeError::InvalidLaneBypass)
        );
        let code = code_from_records(
            CONTAINER_VERSION,
            &[(LANE_BYPASS_RECORD, &[retired[0], retired[1], 1, 0])],
        );
        assert_eq!(
            decode_song_code(&code).err(),
            Some(SongCodeError::RetiredControl("pad.reverb_mix"))
        );
    }
}

fn validate_capture(clip: &super::CaptureClip) -> Result<(), SongCodeError> {
    if !clip.origin.is_finite()
        || !(-super::CAPTURE_BEATS..=0.0).contains(&clip.origin)
        || !clip.launch.is_finite()
        || !(0.0..=4.0).contains(&clip.launch)
    {
        return Err(SongCodeError::InvalidCapture);
    }
    Ok(())
}

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

    fn payload(id: &str) -> Vec<u8> {
        let mut payload = vec![CAPTURE_WIRE_VERSION, 1];
        payload.extend_from_slice(&song_id_index(id).unwrap().to_le_bytes());
        payload.push(1);
        payload.extend_from_slice(&0.0f64.to_le_bytes());
        payload.extend_from_slice(&0.0f64.to_le_bytes());
        payload.extend_from_slice(&[128; super::super::CAPTURE_SAMPLES]);
        payload
    }

    fn decode(payload: &[u8]) -> Result<SongState, SongCodeError> {
        decode_song_code(&code_from_records(
            CONTAINER_VERSION,
            &[
                (RANGE_EPOCH_RECORD, &CURRENT_RANGE_EPOCH.to_le_bytes()),
                (CAPTURE_RECORD, payload),
            ],
        ))
    }

    #[test]
    fn capture_record_refuses_invalid_anchors_flags_duplicates_and_targets() {
        let original = payload("pad.level");
        assert!(decode(&original).is_ok());
        let mut invalid = original.clone();
        invalid[4] = 2;
        assert_eq!(decode(&invalid).err(), Some(SongCodeError::InvalidCapture));
        invalid = original.clone();
        invalid[5..13].copy_from_slice(&f64::NAN.to_le_bytes());
        assert_eq!(decode(&invalid).err(), Some(SongCodeError::InvalidCapture));
        invalid = original.clone();
        invalid[13..21].copy_from_slice(&5.0f64.to_le_bytes());
        assert_eq!(decode(&invalid).err(), Some(SongCodeError::InvalidCapture));
        invalid = original.clone();
        invalid[1] = 2;
        invalid.extend_from_slice(&original[2..]);
        assert_eq!(decode(&invalid).err(), Some(SongCodeError::InvalidCapture));
        assert_eq!(
            decode(&payload("pad.type")).err(),
            Some(SongCodeError::InvalidCapture)
        );
        assert_eq!(
            decode(&payload("kick.filter")).err(),
            Some(SongCodeError::RetiredControl("kick.filter"))
        );
        assert_eq!(
            decode(&original[..original.len() - 1]).err(),
            Some(SongCodeError::Truncated)
        );
    }

    #[test]
    fn captured_filter_positions_obey_the_dial_range_epoch() {
        let bytes = payload("bass.slot1.time");
        let code = code_from_records(CONTAINER_VERSION, &[(CAPTURE_RECORD, &bytes)]);
        assert_eq!(
            decode_song_code(&code).err(),
            Some(SongCodeError::StaleRange("bass.slot1.time"))
        );
    }

    #[test]
    fn sixteen_bar_capture_records_refuse_instead_of_changing_duration() {
        let mut old = payload("pad.level");
        old[0] = 2;
        assert_eq!(decode(&old).err(), Some(SongCodeError::InvalidCapture));
    }
}

fn read_captures(payload: &[u8], automation: &mut AutomationState) -> Result<(), SongCodeError> {
    let mut reader = Reader::new(payload);
    if reader.u8()? != CAPTURE_WIRE_VERSION {
        return Err(SongCodeError::InvalidCapture);
    }
    let count = reader.u8()? as usize;
    if count > super::MAX_CAPTURES {
        return Err(SongCodeError::InvalidCapture);
    }
    let mut seen = BTreeSet::new();
    for _ in 0..count {
        let index = reader.u16()?;
        if !seen.insert(index) {
            return Err(SongCodeError::InvalidCapture);
        }
        let enabled = match reader.u8()? {
            0 => false,
            1 => true,
            _ => return Err(SongCodeError::InvalidCapture),
        };
        let mut anchor = [0; 8];
        anchor.copy_from_slice(reader.bytes(8)?);
        let origin = f64::from_le_bytes(anchor);
        anchor.copy_from_slice(reader.bytes(8)?);
        let launch = f64::from_le_bytes(anchor);
        let mut samples = [0; super::CAPTURE_SAMPLES];
        samples.copy_from_slice(reader.bytes(super::CAPTURE_SAMPLES)?);
        let clip = super::CaptureClip {
            samples,
            origin,
            launch,
            enabled,
        };
        validate_capture(&clip)?;
        if let Some(id) = song_id_at(index) {
            if spec_by_id(id).is_none() {
                return Err(SongCodeError::RetiredControl(id));
            }
            automation.captures.insert(ControlAddress::new(id), clip);
        }
    }
    if !reader.is_empty() {
        return Err(SongCodeError::InvalidCapture);
    }
    Ok(())
}

/// Gesture record: `u8 entry_count`, then fixed-width entries of stable
/// `u8 target_mute_bit`, `u8 kind`, `u8 flags`, and a `u16` amount in 0..=1.
/// One quantization step is 1/65,535 of the gesture throw, well below an
/// audible envelope difference. Gestures play over Master only, so the target
/// is always Master's mute bit; an entry aimed at a voice is a retired
/// per-layer gesture and the code is refused.
fn write_gestures(gestures: &GestureState, out: &mut Vec<u8>) -> Result<bool, SongCodeError> {
    let target = u8::try_from(Tab::Master.mute_bit()).map_err(|_| SongCodeError::TooLarge)?;
    let mut entries = Vec::new();
    for kind in GestureKind::ALL {
        let envelope = gestures.envelope(kind);
        if !envelope.amount.is_finite() || !(0.0..=1.0).contains(&envelope.amount) {
            return Err(SongCodeError::InvalidGestureAmount);
        }
        if !envelope.held && envelope.amount == 0.0 {
            continue;
        }
        if envelope.at_seconds != 0.0 {
            return Err(SongCodeError::InvalidGestureTimeAnchor {
                target,
                kind: kind.wire_tag(),
            });
        }
        entries.push((
            kind.wire_tag(),
            u8::from(envelope.held) * GESTURE_HELD_FLAG,
            unit_to_u16(envelope.amount),
        ));
    }
    if entries.is_empty() {
        return Ok(false);
    }
    let count = u8::try_from(entries.len()).map_err(|_| SongCodeError::TooLarge)?;
    out.push(count);
    for (kind, flags, amount) in entries {
        out.extend_from_slice(&[target, kind, flags]);
        out.extend_from_slice(&amount.to_le_bytes());
    }
    Ok(true)
}

fn read_gestures(bytes: &[u8], gestures: &mut GestureState) -> Result<(), SongCodeError> {
    let mut reader = Reader::new(bytes);
    let count = reader.u8()?;
    if count as usize > GESTURE_COUNT {
        return Err(SongCodeError::InvalidGestureCount(count));
    }
    let expected_len = 1 + count as usize * 5;
    if bytes.len() != expected_len {
        return Err(SongCodeError::Truncated);
    }
    let mut seen: BTreeSet<u8> = GestureKind::ALL
        .into_iter()
        .filter(|kind| {
            let envelope = gestures.envelope(*kind);
            envelope.held || envelope.amount > 0.0
        })
        .map(GestureKind::wire_tag)
        .collect();
    for _ in 0..count {
        let target = reader.u8()?;
        match Tab::all()
            .into_iter()
            .find(|tab| tab.mute_bit() == target as usize)
        {
            Some(Tab::Master) => {}
            Some(_) => return Err(SongCodeError::RetiredControl("per-layer gesture")),
            None => return Err(SongCodeError::InvalidGestureTarget(target)),
        }
        let kind_tag = reader.u8()?;
        if kind_tag == GestureKind::RETIRED_THIN_WIRE_TAG {
            return Err(SongCodeError::RetiredControl("thin gesture"));
        }
        let kind = GestureKind::from_wire_tag(kind_tag)
            .ok_or(SongCodeError::InvalidGestureKind(kind_tag))?;
        let flags = reader.u8()?;
        if flags & !GESTURE_HELD_FLAG != 0 {
            return Err(SongCodeError::InvalidGestureFlags(flags));
        }
        if !seen.insert(kind_tag) {
            return Err(SongCodeError::DuplicateGesture {
                target,
                kind: kind_tag,
            });
        }
        let held = flags & GESTURE_HELD_FLAG != 0;
        let amount = u16_to_unit(reader.u16()?);
        gestures.lanes[kind as usize] = GestureEnvelope {
            amount,
            at_seconds: 0.0,
            held,
            restored: held,
        };
    }
    if !reader.is_empty() {
        return Err(SongCodeError::Truncated);
    }
    Ok(())
}

/// The mute record is a little-endian bit set indexed by `Tab::mute_bit`,
/// not by tab discriminant: a tab's bit is assigned once and never moves, so
/// a new tab in the middle of the strip cannot silently steal a saved mute
/// from the tab after it. One byte per eight bits; a code written before a
/// tab existed simply carries no bit for it, which reads as unmuted.
fn mute_bytes(muted: &MuteState) -> Vec<u8> {
    let mut bytes = vec![0u8; MUTE_BYTES];
    for tab in Tab::all() {
        if muted[tab as usize] {
            let bit = tab.mute_bit();
            bytes[bit / 8] |= 1 << (bit % 8);
        }
    }
    bytes
}

fn read_mute(bytes: &[u8], muted: &mut MuteState) -> Result<(), SongCodeError> {
    if bytes.is_empty() || bytes.len() > MUTE_BYTES {
        return Err(SongCodeError::Truncated);
    }
    for tab in Tab::all() {
        let bit = tab.mute_bit();
        muted[tab as usize] = bytes
            .get(bit / 8)
            .is_some_and(|byte| byte & (1 << (bit % 8)) != 0);
    }
    Ok(())
}

fn write_tonal_sequence(
    sequence: &TonalSequenceState,
    out: &mut Vec<u8>,
) -> Result<(), SongCodeError> {
    let note_count = u8::try_from(sequence.notes.len()).map_err(|_| SongCodeError::TooLarge)?;
    out.push(sequence.phrase as u8);
    out.push(note_count);
    for note in &sequence.notes {
        out.extend_from_slice(&note.to_le_bytes());
    }
    out.extend_from_slice(&sequence.evolution_seed.to_le_bytes());
    out.extend_from_slice(&sequence.evolution_count.to_le_bytes());
    Ok(())
}

fn read_tonal_sequence(bytes: &[u8]) -> Result<TonalSequenceState, SongCodeError> {
    let mut reader = Reader::new(bytes);
    let phrase = reader.u8()? as usize;
    let note_count = reader.u8()? as usize;
    if phrase >= TONAL_PHRASES.len() || note_count == 0 || note_count > TONAL_MAX_LOOP_STEPS {
        return Err(SongCodeError::Truncated);
    }
    let mut notes = Vec::with_capacity(note_count);
    for _ in 0..note_count {
        notes.push(reader.i32()?);
    }
    let evolution_seed = reader.u64()?;
    let evolution_count = reader.u64()?;
    if !reader.is_empty() {
        return Err(SongCodeError::Truncated);
    }
    Ok(TonalSequenceState {
        phrase,
        notes,
        evolution_seed,
        evolution_count,
    })
}

// ============================================================
// Codec
// ============================================================

/// How a snapshot entry spells its value. The tag travels with the value
/// so a reader never re-derives the choice from the live `ControlSpec` — a
/// control's kind or step ladder may change in a later build without
/// invalidating codes written today — and so an entry naming an unknown
/// control can still be skipped without losing byte alignment.
pub(crate) const VALUE_TAG_POSITION: u8 = 0;
pub(crate) const VALUE_TAG_INT: u8 = 1;
pub(crate) const VALUE_TAG_FLOAT: u8 = 2;
pub(crate) const VALUE_TAG_SMALL_INT: u8 = 3;

/// Even span for bipolar `-1..=1` amounts, so exactly 0 — the neutral value
/// every automation amount rests at — round-trips to exactly 0.
const BIPOLAR_SPAN: f32 = 65_534.0;

#[derive(Clone, Copy, PartialEq)]
enum EncodedValue {
    /// Position along the spec's taper: 0 is `min`, `u16::MAX` is `max`.
    Position(u16),
    SmallInt(i8),
    Int(i16),
    Float(f32),
}

impl EncodedValue {
    /// Continuous rows ride the taper in position space. Discrete rows and
    /// musical step ladders (`Step::PowerOfTwo`, `Step::BeatGrid`) do not:
    /// `DialScale::from_step` overrides the taper for both ladders and neither
    /// `beat_grid_ratio` nor the `Log2` override has an inverse in the crate,
    /// so they store their value exactly instead. Discrete rows are already
    /// whole numbers and would gain nothing but error from a round trip
    /// through 0..1.
    fn encode(spec: &ControlSpec, value: f32, c: &FluidControls) -> Self {
        if let Some(values) = spec.song_values {
            // `value` is quantized onto the dial, so it is a whole position
            // within the table (`song_values_cover_every_dial_position`).
            return Self::SmallInt(values[value as usize]);
        }
        if !spec.exact_in_song
            && spec.kind != ControlKind::Discrete
            && matches!(spec.step, Step::Linear(_))
        {
            Self::Position(unit_to_u16(spec.ratio(value, c)))
        } else {
            Self::exact(value)
        }
    }

    /// Smallest exactly-lossless spelling of a whole number: one byte through
    /// `i8` (which covers every discrete row — the widest is `master.tune` at
    /// -12..12 — and the low power-of-two/beat-grid rungs), two through `i16`,
    /// four as a raw `f32` for anything fractional. The value is absolute, not
    /// relative to `spec.min`, so a later build that retunes a control's range
    /// cannot silently reinterpret a code written today.
    fn exact(value: f32) -> Self {
        let rounded = value.round();
        if value != rounded {
            return Self::Float(value);
        }
        if (i8::MIN as f32..=i8::MAX as f32).contains(&rounded) {
            Self::SmallInt(rounded as i8)
        } else if (i16::MIN as f32..=i16::MAX as f32).contains(&rounded) {
            Self::Int(rounded as i16)
        } else {
            Self::Float(value)
        }
    }

    fn write(self, out: &mut Vec<u8>) {
        match self {
            Self::Position(position) => {
                out.push(VALUE_TAG_POSITION);
                out.extend_from_slice(&position.to_le_bytes());
            }
            Self::SmallInt(value) => {
                out.push(VALUE_TAG_SMALL_INT);
                out.extend_from_slice(&value.to_le_bytes());
            }
            Self::Int(value) => {
                out.push(VALUE_TAG_INT);
                out.extend_from_slice(&value.to_le_bytes());
            }
            Self::Float(value) => {
                out.push(VALUE_TAG_FLOAT);
                out.extend_from_slice(&value.to_le_bytes());
            }
        }
    }

    fn read(reader: &mut Reader) -> Result<Self, SongCodeError> {
        match reader.u8()? {
            VALUE_TAG_POSITION => Ok(Self::Position(reader.u16()?)),
            VALUE_TAG_SMALL_INT => Ok(Self::SmallInt(reader.i8()?)),
            VALUE_TAG_INT => Ok(Self::Int(reader.i16()?)),
            VALUE_TAG_FLOAT => Ok(Self::Float(reader.f32()?)),
            tag => Err(SongCodeError::InvalidValueTag(tag)),
        }
    }

    /// `Taper::value_at` clamps its ratio but not its output, so the inverse
    /// can land a float hair outside the range; clamp here rather than relying
    /// on every caller to route through `apply_quantized_value`.
    fn resolve(self, spec: &ControlSpec) -> Result<f32, SongCodeError> {
        if let Some(values) = spec.song_values {
            // Only an exact whole number names a table entry; the writer
            // never spells one as a taper position.
            let stored = match self {
                Self::SmallInt(value) => value as i16,
                Self::Int(value) => value,
                Self::Float(_) | Self::Position(_) => {
                    return Err(SongCodeError::NotATableValue(spec.id));
                }
            };
            return values
                .iter()
                .position(|&value| value as i16 == stored)
                .map(|position| position as f32)
                .ok_or(SongCodeError::UnknownValue {
                    id: spec.id,
                    value: stored,
                });
        }
        let value = match self {
            Self::Position(position) => {
                spec.taper
                    .value_at(u16_to_unit(position), spec.min, spec.max)
            }
            Self::SmallInt(value) => value as f32,
            Self::Int(value) => value as f32,
            Self::Float(value) => value,
        };
        Ok(value.clamp(spec.min, spec.max))
    }
}

/// A `0..=1` ratio as a u16; both endpoints land exactly.
fn unit_to_u16(value: f32) -> u16 {
    (value.clamp(0.0, 1.0) * u16::MAX as f32).round() as u16
}

fn u16_to_unit(value: u16) -> f32 {
    value as f32 / u16::MAX as f32
}

fn bipolar_to_u16(value: f32) -> u16 {
    ((value.clamp(-1.0, 1.0) + 1.0) * 0.5 * BIPOLAR_SPAN).round() as u16
}

fn u16_to_bipolar(value: u16) -> f32 {
    (value as f32 / BIPOLAR_SPAN).min(1.0) * 2.0 - 1.0
}

/// The `SONG_ID_TABLE` slot for a live control id. A registry control with no
/// slot is a table that was not appended to, not a user error.
fn write_control_index(id: &'static str, out: &mut Vec<u8>) -> Result<(), SongCodeError> {
    let index = song_id_index(id).ok_or(SongCodeError::UnregisteredControl(id))?;
    out.extend_from_slice(&index.to_le_bytes());
    Ok(())
}

/// The live spec an interned index names, or `None` when this build has no
/// such slot or no longer registers that control.
fn control_at(index: u16) -> Option<&'static ControlSpec> {
    song_id_at(index).and_then(spec_by_id)
}

/// Snapshot record:
/// `u16 entry_count`, then per entry `u16 id_index` + one tagged value.
/// Entries are still deduped first-wins over `all_specs()` and still pruned
/// against `FluidControls::default`.
///
/// The prune compares the *encoded* value against the encoded default rather
/// than the two raw floats. A plain absolute `f32::EPSILON` comparison is
/// only safe while `quantize` is a no-op for tapered dials: a position round
/// trip carries relative error, so on a large-magnitude control (a Filter
/// cutoff at 8 kHz, `perc.decay_ms` at 2 s) a value that decoded to its own default
/// would re-encode as a spurious entry, growing the code on every save/load
/// cycle. Equal encodings are provably redundant — the reader would
/// reconstruct the default from either — so this both fixes that and prunes
/// slightly harder.
fn write_snapshot(controls: &FluidControls, out: &mut Vec<u8>) -> Result<(), SongCodeError> {
    let defaults = FluidControls::default();
    let mut entries = Vec::new();
    let mut seen = BTreeSet::new();

    for spec in all_specs() {
        if !seen.insert(spec.id) {
            continue;
        }
        // Slot fields borrow their units from the loaded module. Encode the
        // value and prune baseline through that same semantic view.
        let spec = spec.contextual(controls);
        // Both encodes map through the live session's contextual view (spec is
        // already contextual to `controls`, and `contextual` is idempotent) so
        // the baseline prune compares positions on one mapping.
        let value = EncodedValue::encode(&spec, spec.quantized_value(controls), controls);
        let default = EncodedValue::encode(&spec, spec.quantized_value(&defaults), controls);
        if value == default {
            continue;
        }
        let index = song_id_index(spec.id).ok_or(SongCodeError::UnregisteredControl(spec.id))?;
        entries.push((index, value));
    }

    write_u16(entries.len(), out)?;
    for (index, value) in entries {
        out.extend_from_slice(&index.to_le_bytes());
        value.write(out);
    }
    Ok(())
}

fn read_snapshot(bytes: &[u8], controls: &mut FluidControls) -> Result<(), SongCodeError> {
    let mut reader = Reader::new(bytes);
    let count = reader.u16()?;
    let mut entries = Vec::with_capacity(count as usize);
    for _ in 0..count {
        let index = reader.u16()?;
        let value = EncodedValue::read(&mut reader)?;
        entries.push((index, value));
    }

    // A slot's kind and Delay clock modes define the units of its remaining
    // fields. Resolve those structural values first regardless of registry or
    // song-id order, then decode the parameters through the established unit.
    for structural in [true, false] {
        for &(index, value) in &entries {
            let id = song_id_at(index).unwrap_or_default();
            let is_structural = parse_module_slot_id(id).is_some_and(|(_, _, field)| {
                matches!(
                    field,
                    ModuleSlotField::Kind | ModuleSlotField::Clock | ModuleSlotField::RightClock
                )
            });
            if is_structural != structural {
                continue;
            }
            if let Some(spec) = control_at(index) {
                let spec = spec.contextual(controls);
                spec.apply_quantized_value(value.resolve(&spec)?, controls);
            } else if !structural {
                reject_retired_control(index)?;
            }
        }
    }
    Ok(())
}

/// An index inside `SONG_ID_TABLE` whose id no registry control claims names
/// a control this build retired. There is nowhere to put its value, so the
/// code is rejected instead of decoded with that value silently missing.
/// An index past the table's end is a control from a *newer* build and stays
/// skipped — that is forward compatibility, not a retirement.
fn reject_retired_control(index: u16) -> Result<(), SongCodeError> {
    match song_id_at(index) {
        Some(id) if spec_by_id(id).is_none() => Err(SongCodeError::RetiredControl(id)),
        _ => Ok(()),
    }
}

/// Automation record. Control ids are interned `u16` indexes and the bounded
/// ratios (`depth_ratio`, `step_glide`, step values, and envelope amount) are
/// u16-quantized. Repeated control indexes represent stacked lanes.
/// Beat-valued fields and
/// `LfoRoute::seed` stay bit-exact — a quantized rate or seed would move
/// where a modulator sits on the transport grid.
fn write_automation(automation: &AutomationState, out: &mut Vec<u8>) -> Result<(), SongCodeError> {
    write_u16(automation.routes().count(), out)?;
    for (address, route) in automation.routes() {
        write_control_index(address.id(), out)?;
        out.extend_from_slice(&route.cycle_beats.to_le_bytes());
        out.extend_from_slice(&unit_to_u16(route.depth_ratio).to_le_bytes());
        out.push(shape_tag(route.shape));
        out.extend_from_slice(&route.phase_offset_beats.to_le_bytes());
        out.extend_from_slice(&route.seed.to_le_bytes());
        if route.shape == LfoShape::Steps {
            out.push(route.step_count);
            out.extend_from_slice(&unit_to_u16(route.step_glide).to_le_bytes());
            for value in &route.steps[..route.active_step_count()] {
                out.extend_from_slice(&bipolar_to_u16(*value).to_le_bytes());
            }
        }
    }

    // Reserved legacy macro-route section. Always empty in current codes.
    write_u16(0, out)?;

    write_u16(automation.envelopes().count(), out)?;
    for (address, route) in automation.envelopes() {
        write_control_index(address.id(), out)?;
        out.extend_from_slice(&bipolar_to_u16(route.amount).to_le_bytes());
        out.extend_from_slice(&route.attack_beats.to_le_bytes());
        out.extend_from_slice(&route.decay_beats.to_le_bytes());
        let (tag, param) = env_trigger_tag(route.trigger);
        out.push(tag);
        out.extend_from_slice(&param.to_le_bytes());
    }

    // Reserved legacy field-macro section. Always empty in current codes.
    write_u16(0, out)?;

    Ok(())
}

fn read_automation(bytes: &[u8], automation: &mut AutomationState) -> Result<(), SongCodeError> {
    let mut reader = Reader::new(bytes);

    let lfo_count = reader.u16()?;
    for _ in 0..lfo_count {
        let index = reader.u16()?;
        let cycle_beats = reader.f32()?;
        let depth_ratio = u16_to_unit(reader.u16()?);
        let shape_byte = reader.u8()?;
        let phase_offset_beats = reader.f32()?;
        let seed = reader.u32()?;

        // Read the staircase before resolving the id and shape, so a route
        // this build cannot place is still skipped in byte-aligned whole.
        let steps = if shape_from_tag(shape_byte) == Some(LfoShape::Steps) {
            let step_count = reader.u8()?;
            let step_glide = u16_to_unit(reader.u16()?);
            let live = (step_count as usize).clamp(1, MAX_LFO_STEPS);
            let mut values = [0.0f32; MAX_LFO_STEPS];
            for value in values.iter_mut().take(live) {
                *value = u16_to_bipolar(reader.u16()?);
            }
            Some((step_count, step_glide, values))
        } else {
            None
        };

        reject_retired_control(index)?;
        let (Some(spec), Some(shape)) = (control_at(index), shape_from_tag(shape_byte)) else {
            continue;
        };
        let mut route = build_lfo_route(cycle_beats, depth_ratio, shape, phase_offset_beats, seed);
        if let Some((_, _, values)) = steps
            && values.iter().any(|value| *value < 0.0)
        {
            return Err(SongCodeError::NegativeLfoStep(spec.id));
        }
        if let Some((step_count, step_glide, values)) = steps {
            route.step_count = step_count.clamp(1, MAX_LFO_STEPS as u8);
            route.step_glide = step_glide;
            route.steps = values;
        }
        automation.add_route(ControlAddress::new(spec.id), route);
    }

    let macro_count = reader.u16()?;
    if macro_count > 0 {
        return Err(SongCodeError::RetiredControl("macro route"));
    }

    let envelope_count = reader.u16()?;
    for _ in 0..envelope_count {
        let index = reader.u16()?;
        let amount = u16_to_bipolar(reader.u16()?);
        let attack_beats = reader.f32()?;
        let decay_beats = reader.f32()?;
        let trigger_tag = reader.u8()?;
        let trigger_param = reader.f32()?;

        reject_retired_control(index)?;
        let (Some(spec), Some(trigger)) = (
            control_at(index),
            env_trigger_from_tag(
                trigger_tag,
                finite_or(trigger_param, DEFAULT_ENV_TRIGGER_BEATS),
            ),
        ) else {
            continue;
        };
        automation.add_envelope(
            ControlAddress::new(spec.id),
            EnvelopeRoute {
                enabled: true,
                amount,
                attack_beats: finite_or(attack_beats, 0.0).clamp(0.0, MAX_ENV_ATTACK_BEATS),
                decay_beats: finite_or(decay_beats, 0.0).clamp(0.0, MAX_ENV_DECAY_BEATS),
                trigger,
            },
        );
    }

    let field_macro_count = reader.u16()?;
    if field_macro_count > 0 {
        return Err(SongCodeError::RetiredControl("macro route"));
    }

    Ok(())
}

/// Authored lanes persist even while their amount is zero.
fn automation_has_content(automation: &AutomationState) -> bool {
    automation.routes().next().is_some() || automation.envelopes().next().is_some()
}

/// Shared `LfoRoute` construction for the reader: clamps every field to its
/// valid range and substitutes a default for anything non-finite, so a
/// corrupt or hand-edited code cannot install an out-of-range modulator.
fn build_lfo_route(
    cycle_beats: f32,
    depth_ratio: f32,
    shape: LfoShape,
    phase_offset_beats: f32,
    seed: u32,
) -> LfoRoute {
    LfoRoute {
        cycle_beats: finite_or(cycle_beats, 2.0).clamp(MIN_LFO_CYCLE_BEATS, MAX_LFO_CYCLE_BEATS),
        depth_ratio: finite_or(depth_ratio, DEFAULT_LFO_DEPTH_RATIO).clamp(0.0, 1.0),
        shape,
        phase_offset_beats: finite_or(phase_offset_beats, 0.0).clamp(0.0, MAX_LFO_OFFSET_BEATS),
        seed,
        // A non-Steps route ignores these; a Steps route overwrites them
        // from its inline staircase.
        ..LfoRoute::default()
    }
}

fn env_trigger_tag(trigger: EnvTrigger) -> (u8, f32) {
    match trigger {
        EnvTrigger::EveryBeats(beats) => (ENV_TRIGGER_EVERY_BEATS, beats),
        EnvTrigger::OnKick => (ENV_TRIGGER_ON_KICK, 0.0),
        EnvTrigger::Once => (ENV_TRIGGER_ONCE, 0.0),
    }
}

fn env_trigger_from_tag(tag: u8, param: f32) -> Option<EnvTrigger> {
    match tag {
        ENV_TRIGGER_EVERY_BEATS => Some(EnvTrigger::EveryBeats(param)),
        ENV_TRIGGER_ON_KICK => Some(EnvTrigger::OnKick),
        ENV_TRIGGER_ONCE => Some(EnvTrigger::Once),
        _ => None,
    }
}

/// Every shape has a row (`lfo_shape_tags_cover_every_shape`), so the
/// `expect` can only fire on a table edit.
fn shape_tag(shape: LfoShape) -> u8 {
    LFO_SHAPE_TAGS
        .iter()
        .find(|(candidate, _)| *candidate == shape)
        .map(|(_, tag)| *tag)
        .expect("LFO_SHAPE_TAGS has a row for every shape")
}

fn shape_from_tag(tag: u8) -> Option<LfoShape> {
    LFO_SHAPE_TAGS
        .iter()
        .find(|(_, candidate)| *candidate == tag)
        .map(|(shape, _)| *shape)
}

fn finite_or(value: f32, fallback: f32) -> f32 {
    if value.is_finite() { value } else { fallback }
}

fn write_record(record_type: u8, payload: &[u8], out: &mut Vec<u8>) -> Result<(), SongCodeError> {
    let len = u32::try_from(payload.len()).map_err(|_| SongCodeError::TooLarge)?;
    out.push(record_type);
    out.extend_from_slice(&len.to_le_bytes());
    out.extend_from_slice(payload);
    Ok(())
}

/// A song code whose container carries `version` and exactly `records`, so a
/// test can hand the decoder any byte sequence without re-spelling the
/// magic, prefix, or base64 layer.
#[cfg(test)]
pub(crate) fn code_from_records(version: u8, records: &[(u8, &[u8])]) -> String {
    let mut bytes = Vec::new();
    bytes.extend_from_slice(MAGIC);
    bytes.push(version);
    for (record_type, payload) in records {
        write_record(*record_type, payload, &mut bytes).unwrap();
    }
    format!("{CODE_PREFIX}{}", URL_SAFE_NO_PAD.encode(bytes))
}

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

    #[test]
    fn rejects_unknown_row_bits() {
        let code = code_from_records(CONTAINER_VERSION, &[(MIDI_ROWS_RECORD, &[0b0100_0000])]);
        assert_eq!(
            decode_song_code(&code).err(),
            Some(SongCodeError::InvalidMidiRows(0b0100_0000))
        );
    }

    #[test]
    fn rejects_duplicate_row_records() {
        let code = code_from_records(
            CONTAINER_VERSION,
            &[(MIDI_ROWS_RECORD, &[1]), (MIDI_ROWS_RECORD, &[2])],
        );
        assert_eq!(
            decode_song_code(&code).err(),
            Some(SongCodeError::DuplicateMidiRowsRecord)
        );
    }
}

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

    #[test]
    fn rejects_unknown_hidden_row_bits() {
        let code = code_from_records(
            CONTAINER_VERSION,
            &[(PAD_RHYTHM_ROWS_RECORD, &[0b0000_1000])],
        );
        assert_eq!(
            decode_song_code(&code).err(),
            Some(SongCodeError::InvalidPadRhythmRows(0b0000_1000))
        );
    }

    #[test]
    fn drops_the_retired_swing_row_bit() {
        let code = code_from_records(
            CONTAINER_VERSION,
            &[(PAD_RHYTHM_ROWS_RECORD, &[0b0000_0110])],
        );
        assert_eq!(
            decode_song_code(&code)
                .unwrap()
                .controls
                .hidden_pad_rhythm_rows,
            0b0000_0100
        );
    }
}

/// The snapshot record payload `encode_song_code` writes for `controls`.
#[cfg(test)]
pub(crate) fn snapshot_payload(controls: &FluidControls) -> Vec<u8> {
    let mut snapshot = Vec::new();
    write_snapshot(controls, &mut snapshot).unwrap();
    snapshot
}

fn write_u16(value: usize, out: &mut Vec<u8>) -> Result<(), SongCodeError> {
    let value = u16::try_from(value).map_err(|_| SongCodeError::TooLarge)?;
    out.extend_from_slice(&value.to_le_bytes());
    Ok(())
}

struct Reader<'a> {
    bytes: &'a [u8],
    pos: usize,
}

impl<'a> Reader<'a> {
    fn new(bytes: &'a [u8]) -> Self {
        Self { bytes, pos: 0 }
    }

    fn is_empty(&self) -> bool {
        self.pos == self.bytes.len()
    }

    fn bytes(&mut self, len: usize) -> Result<&'a [u8], SongCodeError> {
        let end = self.pos.checked_add(len).ok_or(SongCodeError::TooLarge)?;
        let Some(bytes) = self.bytes.get(self.pos..end) else {
            return Err(SongCodeError::Truncated);
        };
        self.pos = end;
        Ok(bytes)
    }

    fn u8(&mut self) -> Result<u8, SongCodeError> {
        Ok(self.bytes(1)?[0])
    }

    fn read_array<const N: usize>(&mut self) -> Result<[u8; N], SongCodeError> {
        let mut bytes = [0u8; N];
        bytes.copy_from_slice(self.bytes(N)?);
        Ok(bytes)
    }

    fn u16(&mut self) -> Result<u16, SongCodeError> {
        Ok(u16::from_le_bytes(self.read_array()?))
    }

    fn u32(&mut self) -> Result<u32, SongCodeError> {
        Ok(u32::from_le_bytes(self.read_array()?))
    }

    fn u64(&mut self) -> Result<u64, SongCodeError> {
        Ok(u64::from_le_bytes(self.read_array()?))
    }

    fn i8(&mut self) -> Result<i8, SongCodeError> {
        Ok(self.u8()? as i8)
    }

    fn i16(&mut self) -> Result<i16, SongCodeError> {
        Ok(i16::from_le_bytes(self.read_array()?))
    }

    fn i32(&mut self) -> Result<i32, SongCodeError> {
        Ok(i32::from_le_bytes(self.read_array()?))
    }

    fn f32(&mut self) -> Result<f32, SongCodeError> {
        Ok(f32::from_le_bytes(self.read_array()?))
    }
}

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

    const AMOUNT_STEP: f32 = 1.0 / u16::MAX as f32;

    fn code_with_gesture_payload(payload: &[u8]) -> String {
        code_from_records(CONTAINER_VERSION, &[(GESTURE_RECORD, payload)])
    }

    fn entry(target: u8, kind: u8, flags: u8, amount: u16) -> [u8; 5] {
        let amount = amount.to_le_bytes();
        [target, kind, flags, amount[0], amount[1]]
    }

    fn payload(entries: &[[u8; 5]]) -> Vec<u8> {
        let mut payload = vec![entries.len() as u8];
        payload.extend(entries.iter().flatten());
        payload
    }

    #[test]
    fn inactive_gestures_add_no_song_code_payload() {
        let song = SongState::default();
        let snapshot = snapshot_payload(&song.controls);
        let epoch = CURRENT_RANGE_EPOCH.to_le_bytes();
        let expected = code_from_records(
            CONTAINER_VERSION,
            &[(RANGE_EPOCH_RECORD, &epoch), (SNAPSHOT_RECORD, &snapshot)],
        );

        assert_eq!(encode_song_code(&song).unwrap(), expected);
    }

    #[test]
    fn gesture_kind_wire_tags_are_stable() {
        assert_eq!(GestureKind::ALL.map(GestureKind::wire_tag), [0, 1, 2, 4]);
    }

    #[test]
    fn held_gesture_round_trip_resumes_rising_from_time_zero() {
        let mut song = SongState::default();
        song.gestures.lanes[GestureKind::Bloom as usize] = GestureEnvelope {
            amount: 0.375,
            at_seconds: 0.0,
            held: true,
            restored: false,
        };

        let decoded = decode_song_code(&encode_song_code(&song).unwrap()).unwrap();
        let envelope = decoded.gestures.envelope(GestureKind::Bloom);

        assert!((envelope.amount - 0.375).abs() <= AMOUNT_STEP);
        assert_eq!(envelope.at_seconds, 0.0);
        assert!(envelope.held);
        assert!(envelope.restored);
        assert!(envelope.amount_at(GestureKind::Bloom, 0.1) > envelope.amount);
    }

    #[test]
    fn zero_amount_held_gesture_is_not_omitted_as_inactive() {
        let mut song = SongState::default();
        song.gestures.lanes[GestureKind::Lift as usize].held = true;

        let decoded = decode_song_code(&encode_song_code(&song).unwrap()).unwrap();
        let envelope = decoded.gestures.envelope(GestureKind::Lift);

        assert!(envelope.held);
        assert!(envelope.restored);
    }

    #[test]
    fn returning_gesture_round_trip_resumes_returning_from_time_zero() {
        let mut song = SongState::default();
        song.gestures.lanes[GestureKind::Submerge as usize] = GestureEnvelope {
            amount: 0.625,
            at_seconds: 0.0,
            held: false,
            restored: false,
        };

        let decoded = decode_song_code(&encode_song_code(&song).unwrap()).unwrap();
        let envelope = decoded.gestures.envelope(GestureKind::Submerge);

        assert!((envelope.amount - 0.625).abs() <= AMOUNT_STEP);
        assert_eq!(envelope.at_seconds, 0.0);
        assert!(!envelope.held);
        assert!(!envelope.restored);
        assert!(envelope.amount_at(GestureKind::Submerge, 0.1) < envelope.amount);
    }

    #[test]
    fn gesture_record_refuses_a_retired_per_layer_target() {
        let payload = payload(&[entry(
            Tab::Chords.mute_bit() as u8,
            GestureKind::Echo.wire_tag(),
            GESTURE_HELD_FLAG,
            unit_to_u16(0.5),
        )]);
        assert_eq!(
            decode_song_code(&code_with_gesture_payload(&payload)).err(),
            Some(SongCodeError::RetiredControl("per-layer gesture"))
        );
    }

    #[test]
    fn gesture_target_wire_id_uses_the_stable_mute_bit() {
        let payload = payload(&[entry(
            Tab::Master.mute_bit() as u8,
            GestureKind::Lift.wire_tag(),
            0,
            unit_to_u16(0.5),
        )]);

        let decoded = decode_song_code(&code_with_gesture_payload(&payload)).unwrap();

        assert!(decoded.gestures.envelope(GestureKind::Lift).amount > 0.0);
    }

    #[test]
    fn gesture_record_refuses_the_retired_thin_gesture() {
        let payload = payload(&[entry(
            Tab::Master.mute_bit() as u8,
            GestureKind::RETIRED_THIN_WIRE_TAG,
            0,
            unit_to_u16(0.5),
        )]);
        assert_eq!(
            decode_song_code(&code_with_gesture_payload(&payload)).err(),
            Some(SongCodeError::RetiredControl("thin gesture"))
        );
    }

    #[test]
    fn gesture_record_rejects_unknown_target() {
        let payload = payload(&[entry(255, GestureKind::Bloom.wire_tag(), 0, 1)]);
        assert_eq!(
            decode_song_code(&code_with_gesture_payload(&payload)).err(),
            Some(SongCodeError::InvalidGestureTarget(255))
        );
    }

    #[test]
    fn gesture_record_rejects_unknown_kind() {
        let payload = payload(&[entry(Tab::Master.mute_bit() as u8, 255, 0, 1)]);
        assert_eq!(
            decode_song_code(&code_with_gesture_payload(&payload)).err(),
            Some(SongCodeError::InvalidGestureKind(255))
        );
    }

    #[test]
    fn gesture_record_rejects_unknown_flags() {
        let payload = payload(&[entry(
            Tab::Master.mute_bit() as u8,
            GestureKind::Bloom.wire_tag(),
            0b10,
            1,
        )]);
        assert_eq!(
            decode_song_code(&code_with_gesture_payload(&payload)).err(),
            Some(SongCodeError::InvalidGestureFlags(0b10))
        );
    }

    #[test]
    fn gesture_record_rejects_more_entries_than_fixed_storage() {
        let payload = [(GESTURE_COUNT + 1) as u8];
        assert_eq!(
            decode_song_code(&code_with_gesture_payload(&payload)).err(),
            Some(SongCodeError::InvalidGestureCount(
                (GESTURE_COUNT + 1) as u8
            ))
        );
    }

    #[test]
    fn gesture_record_rejects_duplicate_target_and_kind() {
        let duplicate = entry(
            Tab::Master.mute_bit() as u8,
            GestureKind::Bloom.wire_tag(),
            0,
            1,
        );
        let payload = payload(&[duplicate, duplicate]);
        assert_eq!(
            decode_song_code(&code_with_gesture_payload(&payload)).err(),
            Some(SongCodeError::DuplicateGesture {
                target: Tab::Master.mute_bit() as u8,
                kind: GestureKind::Bloom.wire_tag(),
            })
        );
    }

    #[test]
    fn song_code_rejects_duplicate_gesture_records() {
        let payload = payload(&[]);
        let code = code_from_records(
            CONTAINER_VERSION,
            &[(GESTURE_RECORD, &payload), (GESTURE_RECORD, &payload)],
        );

        assert_eq!(
            decode_song_code(&code).err(),
            Some(SongCodeError::DuplicateGestureRecord)
        );
    }

    #[test]
    fn gesture_record_rejects_a_truncated_entry() {
        let truncated = [
            1,
            Tab::Master.mute_bit() as u8,
            GestureKind::Bloom.wire_tag(),
        ];
        assert_eq!(
            decode_song_code(&code_with_gesture_payload(&truncated)).err(),
            Some(SongCodeError::Truncated)
        );
    }

    #[test]
    fn gesture_record_rejects_trailing_bytes() {
        let trailing = [0, 0];
        assert_eq!(
            decode_song_code(&code_with_gesture_payload(&trailing)).err(),
            Some(SongCodeError::Truncated)
        );
    }

    #[test]
    fn gesture_writer_rejects_non_finite_or_out_of_range_amounts() {
        for amount in [f32::NAN, f32::INFINITY, -0.1, 1.1] {
            let mut song = SongState::default();
            song.gestures.lanes[GestureKind::Lift as usize].amount = amount;
            assert_eq!(
                encode_song_code(&song).err(),
                Some(SongCodeError::InvalidGestureAmount)
            );
        }
    }

    #[test]
    fn gesture_writer_rejects_an_active_envelope_not_rebased_to_time_zero() {
        let mut song = SongState::default();
        song.gestures.lanes[GestureKind::Echo as usize] = GestureEnvelope {
            amount: 0.5,
            at_seconds: 42.0,
            held: false,
            restored: false,
        };

        assert_eq!(
            encode_song_code(&song).err(),
            Some(SongCodeError::InvalidGestureTimeAnchor {
                target: Tab::Master.mute_bit() as u8,
                kind: GestureKind::Echo.wire_tag(),
            })
        );
    }

    #[test]
    fn maximum_gesture_record_stays_below_120_characters() {
        let mut song = SongState::default();
        for kind in GestureKind::ALL {
            song.gestures.lanes[kind as usize].amount = 1.0;
        }

        let code = encode_song_code(&song).unwrap();

        assert!(code.len() < 120, "max gesture code is {} chars", code.len());
    }
}

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

    /// A one-entry snapshot payload setting id-table slot `index`.
    fn snapshot_entry(index: u16) -> Vec<u8> {
        let mut snapshot = Vec::new();
        write_u16(1usize, &mut snapshot).unwrap();
        snapshot.extend_from_slice(&index.to_le_bytes());
        EncodedValue::Position(unit_to_u16(0.35)).write(&mut snapshot);
        snapshot
    }

    /// One snapshot entry naming `id`, wrapped in a valid container.
    fn code_setting(id: &str) -> String {
        let index = song_id_index(id).expect("id is in the table");
        code_from_records(
            CONTAINER_VERSION,
            &[(SNAPSHOT_RECORD, &snapshot_entry(index))],
        )
    }

    /// A code from before the per-voice effect sliders folded into module
    /// slots names controls that no longer exist. Loading it and quietly
    /// leaving those values at their defaults would hand back a song that
    /// sounds wrong with no explanation, so the code is refused instead.
    #[test]
    fn a_code_setting_a_retired_control_is_refused() {
        assert_eq!(
            decode_song_code(&code_setting("pad.reverb_mix")).err(),
            Some(SongCodeError::RetiredControl("pad.reverb_mix"))
        );
    }

    #[test]
    fn a_code_setting_the_retired_pad_swing_is_refused() {
        assert_eq!(
            decode_song_code(&code_setting("pad.swing")).err(),
            Some(SongCodeError::RetiredControl("pad.swing"))
        );
    }

    #[test]
    fn a_code_setting_a_retired_filter_control_is_refused() {
        assert_eq!(
            decode_song_code(&code_setting("bass.cutoff")).err(),
            Some(SongCodeError::RetiredControl("bass.cutoff"))
        );
        assert_eq!(
            decode_song_code(&code_setting("kick.filter")).err(),
            Some(SongCodeError::RetiredControl("kick.filter"))
        );
        assert_eq!(
            decode_song_code(&code_setting("clap.filter")).err(),
            Some(SongCodeError::RetiredControl("clap.filter"))
        );
    }

    /// The same skip that makes a retired id fatal must not catch an id from
    /// a newer build: that index is past the table's end, not inside it.
    #[test]
    fn a_code_setting_an_id_this_build_has_never_heard_of_still_loads() {
        let code = code_from_records(
            CONTAINER_VERSION,
            &[(SNAPSHOT_RECORD, &snapshot_entry(u16::MAX))],
        );

        assert!(decode_song_code(&code).is_ok());
    }
}

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

    #[test]
    fn lfo_shape_tags_cover_every_shape() {
        let mut tags = BTreeSet::new();
        for shape in LfoShape::ALL {
            let tag = shape_tag(shape);
            assert_eq!(shape_from_tag(tag), Some(shape));
            assert!(tags.insert(tag), "{shape:?}: tag {tag} reused");
        }
        assert_eq!(tags.len(), LFO_SHAPE_TAGS.len());
    }
}

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

    /// A code written when the strip ended at Master carried one mute byte
    /// with Master on bit 7. Lead's bit is 8, in the second byte, so that
    /// old payload still lands on Master and Lead reads as unmuted.
    #[test]
    fn a_one_byte_mute_payload_from_before_lead_still_names_master() {
        let mut muted = [false; TAB_COUNT];
        read_mute(&[1 << 7 | 1 << 4], &mut muted).unwrap();
        assert!(muted[Tab::Master as usize]);
        assert!(muted[Tab::Tonal as usize]);
        assert!(!muted[Tab::Lead as usize]);
        assert_eq!(read_mute(&[], &mut muted), Err(SongCodeError::Truncated));
        assert_eq!(
            read_mute(&[0, 0, 0], &mut muted),
            Err(SongCodeError::Truncated)
        );
    }
}

#[cfg(test)]
mod song_value_tests {
    use super::super::voice::{CUSTOM_PROGRESSION_INDEX, PROGRESSIONS, progression_index};
    use super::*;

    /// A code whose only entry sets `pad.progression` to `value`.
    fn code_with_progression(value: EncodedValue) -> String {
        let mut snapshot = Vec::new();
        write_u16(1usize, &mut snapshot).unwrap();
        let index = song_id_index("pad.progression").expect("id is in the table");
        snapshot.extend_from_slice(&index.to_le_bytes());
        value.write(&mut snapshot);
        code_from_records(CONTAINER_VERSION, &[(SNAPSHOT_RECORD, &snapshot)])
    }

    fn decoded_progression(value: EncodedValue) -> Result<usize, SongCodeError> {
        decode_song_code(&code_with_progression(value))
            .map(|song| progression_index(song.controls.pad.progression))
    }

    /// Every built-in song but four was saved on Custom as the value 8, from
    /// when Custom was the ninth dial position. Progressions added after it
    /// must leave that value naming Custom.
    #[test]
    fn saved_progression_values_keep_their_meaning() {
        assert_eq!(
            decoded_progression(EncodedValue::SmallInt(8)),
            Ok(CUSTOM_PROGRESSION_INDEX)
        );
        for (letter, value) in ('A'..='H').zip(0..8) {
            let progression = decoded_progression(EncodedValue::SmallInt(value)).unwrap();
            assert_eq!(
                PROGRESSIONS[progression].song_value, value,
                "progression {letter}"
            );
        }
    }

    #[test]
    fn every_progression_round_trips_through_its_song_value() {
        for position in 0..=CUSTOM_PROGRESSION_INDEX {
            let mut song = SongState::default();
            song.controls.pad.progression = position as f32;
            let decoded = decode_song_code(&encode_song_code(&song).unwrap()).unwrap();
            assert_eq!(
                progression_index(decoded.controls.pad.progression),
                position
            );
        }
    }

    /// A progression from a newer build must not load as whatever this
    /// build happens to hold at that number.
    #[test]
    fn an_unknown_progression_value_is_refused() {
        assert_eq!(
            decoded_progression(EncodedValue::SmallInt(99)),
            Err(SongCodeError::UnknownValue {
                id: "pad.progression",
                value: 99
            })
        );
        assert_eq!(
            decoded_progression(EncodedValue::Float(2.5)),
            Err(SongCodeError::NotATableValue("pad.progression"))
        );
    }

    #[test]
    fn chord_offset_round_trips() {
        let mut song = SongState::default();
        song.controls.pad.chord_offset = 4.0;
        let decoded = decode_song_code(&encode_song_code(&song).unwrap()).unwrap();
        assert_eq!(decoded.controls.pad.chord_offset, 4.0);
    }

    #[test]
    fn pad_stab_pattern_round_trips() {
        let mut song = SongState::default();
        song.controls.pad.trigger = 1.0;
        song.controls.modules.pad[1] = super::super::module::preset_slot("swing", 0.4);
        song.controls.pad.gate_beats = 1.0;
        song.controls.pad.steps[1] = 1.0;
        song.controls.pad.steps[4] = 0.0;
        let decoded = decode_song_code(&encode_song_code(&song).unwrap()).unwrap();
        assert_eq!(decoded.controls.pad.trigger, 1.0);
        assert!((decoded.controls.modules.pad[1].amount - 0.4).abs() < 0.001);
        assert_eq!(decoded.controls.pad.gate_beats, 1.0);
        assert_eq!(decoded.controls.pad.steps, song.controls.pad.steps);
    }

    #[test]
    fn arp_midi_mode_and_gate_round_trip() {
        let mut song = SongState::default();
        song.controls.arp.midi_out = 1.0;
        song.controls.arp.midi_gate_beats = 1.0;
        let decoded = decode_song_code(&encode_song_code(&song).unwrap()).unwrap();
        assert_eq!(decoded.controls.arp.midi_out, 1.0);
        assert_eq!(decoded.controls.arp.midi_gate_beats, 1.0);
    }

    #[test]
    fn pad_and_lead_midi_controls_round_trip() {
        let mut song = SongState::default();
        song.controls.pad.midi_out = 0.0;
        song.controls.lead.midi_out = 1.0;
        song.controls.lead.midi_gate_beats = 1.5;
        let decoded = decode_song_code(&encode_song_code(&song).unwrap()).unwrap();
        assert_eq!(decoded.controls.pad.midi_out, 0.0);
        assert_eq!(decoded.controls.lead.midi_out, 1.0);
        assert_eq!(decoded.controls.lead.midi_gate_beats, 1.5);
    }

    #[test]
    fn pad_chord_note_count_round_trips() {
        let mut song = SongState::default();
        song.controls.pad.chord_notes = 2.0;
        let decoded = decode_song_code(&encode_song_code(&song).unwrap()).unwrap();
        assert_eq!(decoded.controls.pad.chord_notes, 2.0);
    }
}