treble-lang 0.8.0

A live coding language for treble
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
//! Offline rendering of a piece (§8.9).
//!
//! A piece has a definite length, so it does not need the loop engine's
//! stay-one-boundary-ahead scheduling: the whole timeline is compiled up front,
//! every note is scheduled at an absolute frame, and the graph is pulled a
//! block at a time until the arrangement and its tail have gone by.
//!
//! ## Occurrence slots and render islands
//!
//! Every pattern of every *occurrence* gets its own instrument slot, rather
//! than one slot per pattern name. Two things fall out of that, and both are
//! why it is worth the extra slots:
//!
//! - **Sweeps do not collide.** A parameter automation is a window of absolute
//!   frames, and [`System::apply_automations`] applies every automation each
//!   block with the last write winning. Two occurrences of one section sharing
//!   a filter node would therefore fight over it — the second occurrence's
//!   ramp, still holding its start value, would overwrite the first's while
//!   the first was mid-sweep. Distinct nodes make each occurrence's window its
//!   own business.
//! - **Filter state does not bleed.** An occurrence gets a fresh delay line and
//!   reverb rather than one carrying the previous playing's buffer, which is
//!   what "the section sounds the same wherever it is played" (§8.5, §8.6)
//!   means once there are stateful filters in the chain.
//!
//! Slots are partitioned into independent render islands. Ungrouped lines from
//! one occurrence run only for that occurrence plus its declared tail; lines
//! sharing a named bus remain in one piece-wide island so the shared filter
//! state is preserved. Offline islands use a fixed Rayon worker pool, then mix
//! in declaration order through one master limiter for deterministic output.

use std::collections::BTreeMap;
use std::sync::{Arc, mpsc};

use crate::ast::{FxArg, FxValue, PatternDef, Ramp, Transform};
use crate::piece::{Piece, Section};
use treble::app::prelude::{AudioGraph, AutomationSpec, AutomationTarget, BusSpec, ParameterRamp};
use treble::audio::{EventScheduler, InstrumentAudioMessage, render_block};
use treble::core::graph::{AudioOutputSink, Entry, Sink, SinkTelemetry, System};
use treble::core::{Block, Note};
use treble::instruments::prelude::InstrumentRegistry;

use super::compile::{
    CompiledPattern, LineTravel, NOTE_GATE, PatternGate, RampWindow, Strike, Travel,
    compile_pattern, core_curve, cycle_seconds, cycle_strikes_at, fx_ramp_window, pattern_fx,
    transform_travels, travel_f64,
};

/// A rendered piece: interleaved stereo samples plus what they came from.
#[derive(Debug, Clone)]
pub struct RenderedPiece {
    pub sample_rate: u32,
    /// Stereo-interleaved samples.
    pub samples: Vec<f32>,
    /// How long the arrangement itself lasts, excluding the tail.
    pub seconds: f64,
    /// How long was rendered in total, arrangement plus tail.
    pub rendered_seconds: f64,
    /// How many section occurrences were played.
    pub occurrences: usize,
    /// How many notes were scheduled — a cheap sanity check that a render that
    /// came out silent was meant to be.
    pub notes: usize,
    /// Sections the arrangement never played (§8.4).
    pub unused: Vec<String>,
    /// Runtime and master-bus measurements from this render.
    pub telemetry: RenderTelemetry,
    /// Whether the master limiter shaped these samples. Without it they are
    /// the plain sum of every line and may stand above full scale.
    pub limited: bool,
}

impl RenderedPiece {
    /// The loudest sample in hand, as a linear level.
    ///
    /// Read off the samples rather than the telemetry, which describes the
    /// render as made: after [`RenderedPiece::trim_start`] the two differ.
    pub fn peak(&self) -> f32 {
        self.samples
            .iter()
            .fold(0.0f32, |loudest, sample| loudest.max(sample.abs()))
    }

    /// Drop the first `frames` frames, so the render starts there.
    ///
    /// For keeping one pass of a section rendered several times over: cut at
    /// [`occurrence_start_frame`], the first frame of the kept pass already
    /// carries whatever the pass before it left ringing, which is what a loop
    /// played back to back sounds like. The arrangement length shrinks by what
    /// was dropped; the counts and telemetry still describe the render as made.
    pub fn trim_start(&mut self, frames: u64) {
        let samples = (frames as usize * 2).min(self.samples.len());
        self.samples.drain(..samples);
        let dropped = (samples / 2) as f64 / f64::from(self.sample_rate);
        self.seconds = (self.seconds - dropped).max(0.0);
        self.rendered_seconds = (self.samples.len() / 2) as f64 / f64::from(self.sample_rate);
    }
}

/// The frame the `index`th occurrence of the timeline starts on.
///
/// Counted with the renderer's own arithmetic — whole frames per cycle, summed
/// occurrence by occurrence — so cutting a render here lands on the sample the
/// occurrence was scheduled from, not one rounded from seconds.
pub fn occurrence_start_frame(piece: &Piece, index: usize, sample_rate: u32) -> u64 {
    piece
        .timeline
        .iter()
        .take(index)
        .map(|occurrence| {
            let section = &piece.sections[occurrence.section];
            section_cycle_frames(section, sample_rate) * u64::from(section.cycles)
        })
        .sum()
}

/// Evidence about the work and headroom of an offline render.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct RenderTelemetry {
    pub islands: usize,
    pub slots: usize,
    pub worker_threads: usize,
    pub pre_limiter_peak: f32,
    pub post_limiter_peak: f32,
    pub max_gain_reduction_db: f32,
    pub limited_samples: usize,
}

/// One line of one occurrence, compiled and placed on the piece's timeline.
struct Placed {
    pattern: CompiledPattern,
    /// The graph slot this line's notes go to.
    slot: usize,
    /// The absolute frame the occurrence starts at.
    start_frame: u64,
    /// The absolute cycle the occurrence starts on. Drops, choices and solos
    /// count from here; the line's travels count from its own first bar.
    origin_cycle: u64,
    /// How long one of this section's cycles is, in frames.
    cycle_frames: u64,
    /// Which cycles of the section the line sounds on, 1-based and inclusive.
    from_cycle: u32,
    to_cycle: u32,
    /// The section's own length, for resolving an open-ended span.
    section_cycles: u32,
}

#[derive(Default)]
struct IslandBuilder {
    graph: AudioGraph,
    placed: Vec<Placed>,
    automations: Vec<AutomationSpec>,
    bus_members: Vec<usize>,
    bus: Option<(String, Vec<treble::instruments::spec::FxSpec>)>,
    start_frame: u64,
    end_frame: u64,
}

struct RenderIsland {
    system: System,
    scheduler: EventScheduler,
    start_frame: u64,
    end_frame: u64,
}

struct IslandAudio {
    start_frame: u64,
    samples: Vec<f32>,
}

enum WorkerMessage {
    Advanced(u64),
    Done {
        index: usize,
        result: Result<IslandAudio, String>,
    },
}

/// Render a piece to interleaved stereo samples.
///
/// Where a render has got to.
///
/// Reported rather than printed, so the caller decides what a progress display
/// looks like — a CLI bar, a GUI meter, or nothing at all.
#[derive(Debug, Clone, PartialEq)]
pub enum Progress {
    /// Compiling one occurrence's lines. `done` of `total` occurrences.
    Compiling { done: usize, total: usize },
    /// Building the audio graph: every slot compiles its instrument here, so
    /// on a large piece this is a visible pause rather than an instant.
    Building { slots: usize },
    /// Rendering audio. `frames` of `total_frames` written.
    Rendering { frames: u64, total_frames: u64 },
    /// Everything is rendered; the samples are in hand.
    Done { frames: u64 },
}

/// How a render is made, beyond the piece and its instruments.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RenderOptions {
    /// Pass the mix through the master limiter. On by default: a piece is
    /// rendered to be listened to, and the ceiling is what keeps it from
    /// clipping.
    ///
    /// Off is for renders that are mixed again downstream — a piece cut into
    /// per-instrument renders that a game sums and limits itself. A limiter
    /// is not linear: each part limited on its own is pulled down by its own
    /// peaks rather than by the mix's, so the parts would no longer add up to
    /// the piece. Unlimited, they do.
    pub master_limiter: bool,
}

impl Default for RenderOptions {
    fn default() -> Self {
        RenderOptions {
            master_limiter: true,
        }
    }
}

/// Render a piece, reporting progress as it goes.
///
/// The plain [`render`] is this with the reports thrown away.
pub fn render_with_progress(
    piece: &Piece,
    registry: &InstrumentRegistry,
    sample_rate: u32,
    progress: &mut dyn FnMut(Progress),
) -> Result<RenderedPiece, String> {
    render_inner(
        piece,
        registry,
        sample_rate,
        RenderOptions::default(),
        progress,
    )
}

/// [`render_with_progress`], made the way `options` says.
pub fn render_with_options(
    piece: &Piece,
    registry: &InstrumentRegistry,
    sample_rate: u32,
    options: RenderOptions,
    progress: &mut dyn FnMut(Progress),
) -> Result<RenderedPiece, String> {
    render_inner(piece, registry, sample_rate, options, progress)
}

/// `registry` supplies the instruments — the built-ins plus whatever the
/// buffer's `def` and `load` lines put there. Nothing else is borrowed: the
/// render builds its own graph, so a performance already sounding is left
/// alone and a headless caller needs no `App` at all.
pub fn render(
    piece: &Piece,
    registry: &InstrumentRegistry,
    sample_rate: u32,
) -> Result<RenderedPiece, String> {
    render_inner(
        piece,
        registry,
        sample_rate,
        RenderOptions::default(),
        &mut |_| {},
    )
}

fn render_inner(
    piece: &Piece,
    registry: &InstrumentRegistry,
    sample_rate: u32,
    options: RenderOptions,
    progress: &mut dyn FnMut(Progress),
) -> Result<RenderedPiece, String> {
    if piece.timeline.is_empty() {
        return Err("the arrangement plays no section, so there is nothing to render".into());
    }

    let tail_frames = (piece.tail * f64::from(sample_rate)).round() as u64;
    let mut occurrence_islands = Vec::new();
    // Lines sharing a named bus stay in one piece-wide island. This preserves
    // the bus's filter state while independent occurrence branches can sleep
    // before their start and disappear after their tail.
    let mut grouped_islands: BTreeMap<String, IslandBuilder> = BTreeMap::new();
    let mut bus_chains: BTreeMap<String, Vec<treble::instruments::spec::FxSpec>> = BTreeMap::new();

    let mut at_frame = 0u64;
    for (index, occurrence) in piece.timeline.iter().enumerate() {
        progress(Progress::Compiling {
            done: index,
            total: piece.timeline.len(),
        });
        let section = &piece.sections[occurrence.section];
        let cycle_frames = section_cycle_frames(section, sample_rate);
        let occurrence_frames = cycle_frames * u64::from(section.cycles);

        for group in &section.groups {
            if group.transforms.iter().any(transform_travels) {
                return Err(format!(
                    "group '{}': a bus serves the whole piece, so its filters cannot travel — \
                     move the range onto the member lines",
                    group.name
                ));
            }
            if !bus_chains.contains_key(&group.name) {
                let (fx, _) = pattern_fx(
                    &group.transforms,
                    section.cycle_seconds(),
                    LineTravel {
                        line: Travel::START,
                        cycle: occurrence.start_cycle as f64,
                        origin: occurrence.start_cycle,
                        divisions: section.sig.0,
                    },
                )
                .map_err(|error| format!("group '{}': {error}", group.name))?;
                bus_chains.insert(group.name.clone(), fx);
            }
        }

        // A section is self-contained (§8.6): its lines' travels are measured
        // from the start of *this* occurrence, so each playing sweeps alike.
        let origin_cycle = occurrence.start_cycle;

        let lines = section
            .patterns
            .iter()
            .chain(&piece.throughout)
            .filter(|line| !line.muted && !section.muted);

        let mut occurrence = IslandBuilder {
            start_frame: at_frame,
            end_frame: at_frame + occurrence_frames + tail_frames,
            ..IslandBuilder::default()
        };
        for line in lines {
            let island = if let Some(group) = &line.group {
                grouped_islands
                    .entry(group.clone())
                    .or_insert_with(|| IslandBuilder {
                        start_frame: 0,
                        ..IslandBuilder::default()
                    })
            } else {
                &mut occurrence
            };
            let placed_line = mount_line(
                &mut island.graph,
                registry,
                section,
                line,
                origin_cycle,
                at_frame,
                cycle_frames,
                &mut island.automations,
                piece.seed,
            )?;
            if line.group.is_some() {
                island.bus_members.push(placed_line.slot);
            }
            island.placed.push(placed_line);
        }

        if !occurrence.placed.is_empty() {
            occurrence_islands.push(occurrence);
        }
        at_frame += occurrence_frames;
    }

    let arrangement_frames = at_frame;
    let total_frames = arrangement_frames + tail_frames;
    for (name, island) in &mut grouped_islands {
        island.end_frame = total_frames;
        island.bus = Some((name.clone(), bus_chains.remove(name).unwrap_or_default()));
    }
    progress(Progress::Compiling {
        done: piece.timeline.len(),
        total: piece.timeline.len(),
    });

    let builders = occurrence_islands
        .into_iter()
        .chain(grouped_islands.into_values())
        .collect::<Vec<_>>();
    let slots = builders.iter().map(|island| island.placed.len()).sum();
    progress(Progress::Building { slots });
    let mut notes = 0;
    let mut islands = Vec::with_capacity(builders.len());
    for builder in builders {
        let (island, island_notes) = build_island(builder, sample_rate)?;
        notes += island_notes;
        islands.push(island);
    }

    let island_count = islands.len();
    let worker_threads = if island_count == 0 {
        0
    } else {
        rayon::current_num_threads().min(island_count)
    };
    let rendered = render_islands(islands, total_frames, progress)?;
    let (samples, master) =
        mix_and_limit(rendered, total_frames, sample_rate, options.master_limiter);
    progress(Progress::Done {
        frames: total_frames,
    });

    Ok(RenderedPiece {
        sample_rate,
        samples,
        seconds: piece.seconds(),
        rendered_seconds: total_frames as f64 / f64::from(sample_rate),
        occurrences: piece.timeline.len(),
        notes,
        unused: piece.unused.clone(),
        telemetry: RenderTelemetry {
            islands: island_count,
            slots,
            worker_threads,
            pre_limiter_peak: master.pre_limiter_peak,
            post_limiter_peak: master.post_limiter_peak,
            max_gain_reduction_db: master.max_gain_reduction_db,
            limited_samples: master.limited_samples,
        },
        limited: options.master_limiter,
    })
}

fn build_island(
    mut builder: IslandBuilder,
    sample_rate: u32,
) -> Result<(RenderIsland, usize), String> {
    if let Some((name, fx)) = builder.bus.take() {
        builder.graph.set_buses(vec![BusSpec {
            name,
            fx,
            members: builder.bus_members,
        }]);
    }
    builder.graph.set_automations(builder.automations);
    let mut system = builder
        .graph
        .compile(sample_rate as f32)
        .map_err(|error| format!("could not build a render island: {error:?}"))?;
    // Island outputs are summed before one final piece-wide limiter. Leaving
    // each island's limiter active would compress branches independently and
    // change both their balance and the historical single-master semantics.
    system
        .set_sink_parameter(0, "limiter_threshold", f32::MAX)
        .map_err(|error| format!("could not configure a render island: {error}"))?;
    let mut scheduler = EventScheduler::new();
    let notes = schedule(&mut scheduler, &builder.placed, &builder.graph);
    Ok((
        RenderIsland {
            system,
            scheduler,
            start_frame: builder.start_frame,
            end_frame: builder.end_frame,
        },
        notes,
    ))
}

fn render_islands(
    islands: Vec<RenderIsland>,
    piece_frames: u64,
    progress: &mut dyn FnMut(Progress),
) -> Result<Vec<IslandAudio>, String> {
    let total_work = islands
        .iter()
        .map(|island| island.end_frame - island.start_frame)
        .sum::<u64>()
        .max(1);
    let island_count = islands.len();
    let mut completed_work = 0u64;
    let mut completed = 0usize;
    let mut results = (0..island_count).map(|_| None).collect::<Vec<_>>();
    let (sender, receiver) = mpsc::channel();
    let report_every = (total_work / 100).max(1);

    std::thread::scope(|thread_scope| {
        let worker_sender = sender.clone();
        thread_scope.spawn(move || {
            rayon::scope(|scope| {
                for (index, island) in islands.into_iter().enumerate() {
                    let sender = worker_sender.clone();
                    scope.spawn(move |_| {
                        let result = render_island(island, report_every, &sender);
                        let _ = sender.send(WorkerMessage::Done { index, result });
                    });
                }
            });
        });
        drop(sender);
        while completed < island_count {
            let Ok(message) = receiver.recv() else {
                break;
            };
            match message {
                WorkerMessage::Advanced(frames) => {
                    completed_work = (completed_work + frames).min(total_work);
                    let piece_progress = ((completed_work as u128 * piece_frames as u128)
                        / total_work as u128) as u64;
                    progress(Progress::Rendering {
                        frames: piece_progress.min(piece_frames),
                        total_frames: piece_frames,
                    });
                }
                WorkerMessage::Done { index, result } => {
                    results[index] = Some(result);
                    completed += 1;
                }
            }
        }
    });

    results
        .into_iter()
        .enumerate()
        .map(|(index, result)| {
            result.ok_or_else(|| format!("render island {index} stopped without a result"))?
        })
        .collect()
}

fn render_island(
    mut island: RenderIsland,
    report_every: u64,
    progress: &mpsc::Sender<WorkerMessage>,
) -> Result<IslandAudio, String> {
    let frames = island.end_frame - island.start_frame;
    let mut samples = Vec::with_capacity(frames as usize * 2);
    let mut frame = island.start_frame;
    let mut reported = frame;
    let mut next_report = frame + report_every;
    while frame < island.end_frame {
        frame = render_block(
            &mut island.system,
            &mut island.scheduler,
            frame,
            &mut samples,
        );
        if frame >= next_report {
            let bounded = frame.min(island.end_frame);
            let _ = progress.send(WorkerMessage::Advanced(bounded - reported));
            reported = bounded;
            next_report = frame + report_every;
        }
    }
    if reported < island.end_frame {
        let _ = progress.send(WorkerMessage::Advanced(island.end_frame - reported));
    }
    samples.truncate(frames as usize * 2);
    Ok(IslandAudio {
        start_frame: island.start_frame,
        samples,
    })
}

fn mix_and_limit(
    islands: Vec<IslandAudio>,
    total_frames: u64,
    sample_rate: u32,
    limit: bool,
) -> (Vec<f32>, SinkTelemetry) {
    let mut mixed = vec![0.0f32; total_frames as usize * 2];
    // `islands` is in declaration order even though workers finish in another
    // order. Fixed-order accumulation keeps floating-point renders bit-exact.
    for island in islands {
        let start = island.start_frame as usize;
        for (offset, frame) in island.samples.chunks_exact(2).enumerate() {
            let target = (start + offset) * 2;
            if target + 1 >= mixed.len() {
                break;
            }
            mixed[target] += frame[0];
            mixed[target + 1] += frame[1];
        }
    }

    let mut sink = AudioOutputSink::new(sample_rate as f32);
    // Unlimited, the master still runs, so the telemetry is measured the same
    // way; its ceiling is just out of reach, as each island's always is. The
    // samples leave at unity gain and pre- and post-limiter peaks agree.
    if !limit {
        sink.set_parameter("limiter_threshold", f32::MAX);
    }
    let mut telemetry = SinkTelemetry::default();
    for chunk in mixed.chunks_mut(512 * 2) {
        let block: Block = chunk
            .chunks_exact(2)
            .map(|frame| [frame[0], frame[1]])
            .collect();
        sink.push(Arc::new(block), 0);
        for (target, frame) in chunk.chunks_exact_mut(2).zip(sink.consume()) {
            target.copy_from_slice(&frame);
        }
        if let Some(block) = sink.telemetry() {
            telemetry.pre_limiter_peak = telemetry.pre_limiter_peak.max(block.pre_limiter_peak);
            telemetry.post_limiter_peak = telemetry.post_limiter_peak.max(block.post_limiter_peak);
            telemetry.max_gain_reduction_db = telemetry
                .max_gain_reduction_db
                .max(block.max_gain_reduction_db);
            telemetry.limited_samples += block.limited_samples;
        }
    }
    (mixed, telemetry)
}

/// How many frames one of a section's cycles lasts.
pub(crate) fn section_cycle_frames(section: &Section, sample_rate: u32) -> u64 {
    (cycle_seconds(section.bpm, section.sig) * f64::from(sample_rate)).round() as u64
}

/// Compile one line of one occurrence, give it a slot, and declare its sweeps.
#[allow(clippy::too_many_arguments)]
fn mount_line(
    graph: &mut AudioGraph,
    registry: &InstrumentRegistry,
    section: &Section,
    line: &PatternDef,
    origin_cycle: u64,
    start_frame: u64,
    cycle_frames: u64,
    automations: &mut Vec<AutomationSpec>,
    seed: u64,
) -> Result<Placed, String> {
    let line_origin = travel_origin(line, origin_cycle);
    let travel = LineTravel {
        line: Travel::START,
        cycle: line_origin as f64,
        origin: line_origin,
        divisions: section.sig.0,
    };
    let (audio_fx, fx_ramps) = pattern_fx(&line.transforms, section.cycle_seconds(), travel)
        .map_err(|error| format!("'{}': {error}", line.name))?;

    let mut spec = registry
        .get(&line.instrument)
        .ok_or_else(|| format!("'{}': unknown instrument '{}'", line.name, line.instrument))?
        .clone();
    // The instrument's own filters keep the front of the chain, so the line's
    // Nth filter lands at `instrument_fx + N` — which is the index a sweep has
    // to name.
    let instrument_fx = spec.fx.len();
    spec.fx.extend(audio_fx.clone());

    let slot = graph
        .add_spec(spec.clone())
        .map_err(|error| format!("'{}': {error}", line.name))?;

    let compiled = compile_pattern(
        line,
        section.scale,
        audio_fx,
        fx_ramps,
        instrument_fx,
        spec,
        PatternGate {
            name: line.name.clone(),
            ..PatternGate::default()
        },
        line_origin,
        section.sig.0,
        seed,
    );

    // Sweeps are declared against this occurrence's own frame window, which is
    // what keeps two playings of one section from fighting over a filter.
    for ramp in &compiled.fx_ramps {
        let Some(window) =
            fx_ramp_window(ramp, compiled.window, compiled.ramp_origin, section.sig.0)
        else {
            continue;
        };
        let (start, end) = window_frames(window, origin_cycle, start_frame, cycle_frames);
        automations.push(AutomationSpec {
            target: AutomationTarget::InstrumentFx {
                slot,
                fx_index: compiled.instrument_fx + ramp.chain_index,
            },
            ramp: ParameterRamp {
                param: ramp.param.clone(),
                from: ramp.from,
                to: ramp.to,
                start_frame: start,
                end_frame: end,
                curve: core_curve(window.curve),
            },
        });
    }

    let span = line.span;
    Ok(Placed {
        pattern: compiled,
        slot,
        start_frame,
        origin_cycle,
        cycle_frames,
        from_cycle: span.map_or(1, |span| span.start()),
        to_cycle: span.map_or(section.cycles, |span| span.end(section.cycles)),
        section_cycles: section.cycles,
    })
}

/// A ramp window's absolute frames, measured from the occurrence's own start.
fn window_frames(
    window: RampWindow,
    origin_cycle: u64,
    start_frame: u64,
    cycle_frames: u64,
) -> (u64, u64) {
    let into = window.origin.saturating_sub(origin_cycle);
    let start = start_frame + into * cycle_frames;
    let span = (window.span * cycle_frames as f64).round().max(1.0) as u64;
    (start, start + span)
}

/// Put every note of every placed line onto the scheduler's timeline.
fn schedule(scheduler: &mut EventScheduler, placed: &[Placed], graph: &AudioGraph) -> usize {
    let mut notes = 0;
    for line in placed {
        let Some(&source_index) = graph.source_map.get(&line.slot) else {
            continue;
        };
        for cycle in line.from_cycle..=line.to_cycle.min(line.section_cycles) {
            // Generative choices count from the occurrence's place in the
            // piece, so a seeded phrase keeps evolving; travels are measured
            // against the line's own window, which starts at its first bar
            // (`travel_origin`). The span is 1-based within the section, so it
            // converts here. Alternations use the cycle within the section
            // instead: `<a b c>` is per-bar harmony, so alternative *k* belongs
            // to bar *k* and must not rotate because the arrangement moved the
            // section (§8.5).
            let absolute = line.origin_cycle + u64::from(cycle - 1);
            let within_section = u64::from(cycle - 1);
            let cycle_start = line.start_frame + u64::from(cycle - 1) * line.cycle_frames;
            for strike in cycle_strikes_at(&line.pattern, absolute, within_section) {
                let start = cycle_start + (strike.start * line.cycle_frames as f64).round() as u64;
                let end = start
                    + ((strike.end - strike.start) * NOTE_GATE * line.cycle_frames as f64).round()
                        as u64;
                for midi in strike.notes {
                    let note = Note::from_midi(midi);
                    scheduler.schedule(
                        start,
                        InstrumentAudioMessage::NoteStart {
                            source_index,
                            note,
                            velocity: strike.velocity,
                        },
                    );
                    scheduler.schedule(
                        end.max(start + 1),
                        InstrumentAudioMessage::NoteStop { source_index, note },
                    );
                    notes += 1;
                }
            }
        }
    }
    notes
}

#[cfg(test)]
mod tests {
    use super::*;
    use treble::instruments::prelude::InstrumentRegistry;

    /// Resolve a source and render it, asserting both steps succeed.
    fn rendered(source: &str) -> RenderedPiece {
        let (program, errors) = crate::parser::parse_program(source);
        assert!(errors.is_empty(), "parse: {errors:?}");
        let (piece, errors) = crate::piece::resolve(&program, (120, (4, 4), None));
        assert!(errors.is_empty(), "resolve: {errors:?}");
        render(&piece, &InstrumentRegistry::built_in(), 44_100).expect("render")
    }

    fn peak(rendered: &RenderedPiece, from: u64, to: u64) -> f32 {
        rendered.samples[(from as usize * 2)..(to as usize * 2).min(rendered.samples.len())]
            .iter()
            .fold(0.0f32, |loudest, sample| loudest.max(sample.abs()))
    }

    #[test]
    fn a_piece_renders_audible_samples() {
        let piece = rendered("bpm 120\ntail 1.0\nsection a 2 {\n  beat kick \"x ~ x ~\"\n}\n");
        assert_eq!(piece.sample_rate, 44_100);
        assert!((piece.seconds - 4.0).abs() < 1e-6, "{}", piece.seconds);
        assert_eq!(piece.samples.len(), 5 * 44_100 * 2);
        assert_eq!(piece.notes, 4);
        assert!(
            peak(&piece, 0, 44_100) > 0.001,
            "the first second is silent"
        );
    }

    #[test]
    fn section_strikes_point_back_at_the_written_steps() {
        let source = "bpm 120\ntail 0\nsection a 2 {\n  bass sine \"<c3 [e3 g3]> ~\" @ 2\n  hat sine \"c5*2\"\n}\n";
        let (program, errors) = crate::parser::parse_program(source);
        assert!(errors.is_empty(), "parse: {errors:?}");
        let (piece, errors) = crate::piece::resolve(&program, (120, (4, 4), None));
        assert!(errors.is_empty(), "resolve: {errors:?}");
        let lines = vec!["bass".to_string()];
        let strikes = section_strikes(&piece, &InstrumentRegistry::built_in(), 0, Some(&lines))
            .expect("strikes");
        assert_eq!(strikes.len(), 1, "only the line asked for");
        let notation = "<c3 [e3 g3]> ~";
        let written: Vec<(u32, &str)> = strikes[0]
            .strikes
            .iter()
            .map(|(cycle, strike)| {
                (
                    *cycle,
                    &notation[strike.source.start as usize..strike.source.end as usize],
                )
            })
            .collect();
        // `@ 2` keeps it to the second bar, where the alternation is on `[e3 g3]`.
        assert_eq!(written, vec![(1, "e3"), (1, "g3")]);
    }

    /// `ramp` counts from where the line comes in (§8.6): a line entering on
    /// bar 3 of a section starts its travel there, not two bars in.
    #[test]
    fn a_late_line_ramps_from_its_own_first_bar() {
        let source =
            "bpm 120\ntail 0\nsection a 4 {\n  late sine \"c4\" @ 3.. | vel 0.2..1.0 | ramp 2\n}\n";
        let (program, errors) = crate::parser::parse_program(source);
        assert!(errors.is_empty(), "parse: {errors:?}");
        let (piece, errors) = crate::piece::resolve(&program, (120, (4, 4), None));
        assert!(errors.is_empty(), "resolve: {errors:?}");
        let lanes =
            section_strikes(&piece, &InstrumentRegistry::built_in(), 0, None).expect("strikes");
        let velocities: Vec<(u32, f32)> = lanes[0]
            .strikes
            .iter()
            .map(|(cycle, strike)| (*cycle, (strike.velocity * 100.0).round() / 100.0))
            .collect();
        assert_eq!(velocities, vec![(2, 0.2), (3, 0.6)]);
        let vel = &lanes[0].automations[0];
        assert_eq!(
            vel.points
                .first()
                .map(|p| (p.0, (p.1 * 100.0).round() / 100.0)),
            Some((2.0, 0.2))
        );
    }

    /// The pitches a source schedules, in order, for one named line.
    fn midi_of(source: &str, line: &str) -> Vec<u8> {
        let (program, errors) = crate::parser::parse_program(source);
        assert!(errors.is_empty(), "parse: {errors:?}");
        let (piece, errors) = crate::piece::resolve(&program, (120, (4, 4), None));
        assert!(errors.is_empty(), "resolve: {errors:?}");
        let mut notes = scheduled_notes(&piece, &InstrumentRegistry::built_in(), 44_100)
            .expect("scheduled notes");
        notes.sort_by_key(|note| note.start);
        notes
            .iter()
            .filter(|note| note.line == line)
            .map(|note| note.midi)
            .collect()
    }

    /// `<a b c>` is per-bar harmony: alternative *k* belongs to bar *k* of the
    /// section, so a section sounds the same wherever the arrangement puts it
    /// (§8.5) and a line's span does not rotate the cycle under it.
    #[test]
    fn alternation_counts_from_the_section_not_the_piece() {
        // Two identical sections at different points in one arrangement.
        let source = "bpm 120\ntail 0\n\
             section pad 4 {\n  rest sine \"~\"\n}\n\
             section one 3 {\n  a sine \"<c3 e4 c5>\"\n}\n\
             section gap 1 {\n  quiet sine \"~\"\n}\n\
             section two 3 {\n  b sine \"<c3 e4 c5>\"\n}\n\
             arrange pad one gap two\n";
        let written = vec![48, 64, 72];
        assert_eq!(midi_of(source, "a"), written, "the first playing");
        assert_eq!(
            midi_of(source, "b"),
            written,
            "an identical section must not rotate because it starts elsewhere"
        );

        // A span that opens later still reads the alternation by bar number, so
        // it stays under whatever the full-span lines are playing.
        let spanned = "bpm 120\ntail 0\n\
             section s 4 {\n  chords sine \"<c3 e4 c5 g4>\"\n  late sine \"<c3 e4 c5 g4>\" @ 3..\n}\n";
        assert_eq!(midi_of(spanned, "chords"), vec![48, 64, 72, 67]);
        assert_eq!(
            midi_of(spanned, "late"),
            vec![72, 67],
            "a line entering at bar 3 takes the third alternative, not the first"
        );
    }

    /// A section rendered on its own sounds the way it does in the song: its
    /// drops and choices count from where the arrangement first plays it, not
    /// from cycle 0, so the notes are the song's, shifted to the start. Its
    /// alternations count from its own first bar either way (§8.6).
    #[test]
    fn an_isolated_section_schedules_the_songs_notes() {
        let source = "bpm 120\ntail 0\n\
             section intro 3 {\n  k kick \"x\"\n}\n\
             section verse 4 {\n  lead sine \"[c4|e4|g4|b4] d5? [a3|f3] g5?\"\n\
             \x20 chords sine \"<c3 e3 g3 a3>\"\n}\n\
             arrange intro verse\n";
        let (program, errors) = crate::parser::parse_program(source);
        assert!(errors.is_empty(), "parse: {errors:?}");
        let (piece, errors) = crate::piece::resolve(&program, (120, (4, 4), None));
        assert!(errors.is_empty(), "resolve: {errors:?}");
        let registry = InstrumentRegistry::built_in();
        let verse = piece.section_index("verse").expect("verse");

        let offset = 3 * section_cycle_frames(&piece.sections[0], 44_100);
        let in_song: Vec<(u64, u8)> = scheduled_notes(&piece, &registry, 44_100)
            .expect("notes")
            .into_iter()
            .filter(|note| note.section == "verse")
            .map(|note| (note.start - offset, note.midi))
            .collect();
        let alone: Vec<(u64, u8)> = scheduled_notes(&piece.isolate(verse, 1), &registry, 44_100)
            .expect("notes")
            .into_iter()
            .map(|note| (note.start, note.midi))
            .collect();
        assert!(!alone.is_empty());
        assert_eq!(alone, in_song);

        // The same section from cycle 0 is a different take — which is the
        // whole reason the occurrence keeps its place.
        let mut from_zero = piece.isolate(verse, 1);
        from_zero.timeline[0].start_cycle = 0;
        let fresh: Vec<(u64, u8)> = scheduled_notes(&from_zero, &registry, 44_100)
            .expect("notes")
            .into_iter()
            .map(|note| (note.start, note.midi))
            .collect();
        assert_ne!(fresh, in_song, "the choices did not depend on the cycle");
    }

    /// Two passes render two sections' worth plus the tail; trimming at the
    /// second pass leaves exactly one pass plus the tail, and those samples
    /// are the render's own, not a re-render.
    #[test]
    fn the_last_pass_is_cut_on_the_frame_it_was_scheduled_from() {
        // 100 bpm makes a cycle 2.4 s, 105_840 frames: a cut computed from
        // seconds would have to round, the renderer's own count does not.
        let source = "bpm 100\ntail 0.5\n\
             section intro 1 {\n  k kick \"x\"\n}\n\
             section verse 2 {\n  pad pad \"[c3,e3,g3]\"\n  hat hihat \"x*4\"\n}\n\
             arrange intro verse\n";
        let (program, errors) = crate::parser::parse_program(source);
        assert!(errors.is_empty(), "parse: {errors:?}");
        let (piece, errors) = crate::piece::resolve(&program, (120, (4, 4), None));
        assert!(errors.is_empty(), "resolve: {errors:?}");
        let verse = piece.section_index("verse").expect("verse");
        let section = &piece.sections[verse];
        let pass_frames = section_cycle_frames(section, 44_100) * u64::from(section.cycles);
        let tail_frames = (0.5f64 * 44_100.0).round() as u64;

        let twice = piece.isolate(verse, 2);
        assert!((twice.seconds() - 2.0 * section.seconds()).abs() < 1e-9);
        let mut rendered = render(&twice, &InstrumentRegistry::built_in(), 44_100).expect("render");
        assert_eq!(
            rendered.samples.len() as u64,
            (2 * pass_frames + tail_frames) * 2
        );
        let whole = rendered.samples.clone();

        let cut = occurrence_start_frame(&twice, 1, 44_100);
        assert_eq!(cut, pass_frames);
        rendered.trim_start(cut);
        assert_eq!(
            rendered.samples.len() as u64,
            (pass_frames + tail_frames) * 2
        );
        assert_eq!(rendered.samples[..], whole[cut as usize * 2..]);
        assert!((rendered.seconds - section.seconds()).abs() < 1e-6);

        // Nothing here is generative, so the kept pass differs from a lone
        // pass only by what the first one left ringing into it.
        let once = render(
            &piece.isolate(verse, 1),
            &InstrumentRegistry::built_in(),
            44_100,
        )
        .expect("render");
        assert_eq!(once.samples.len(), rendered.samples.len());
        let opening = 4_410 * 2;
        let carried = rendered.samples[..opening]
            .iter()
            .zip(&once.samples[..opening])
            .fold(0.0f32, |most, (a, b)| most.max((a - b).abs()));
        assert!(carried > 1e-4, "the first pass left nothing ringing");
    }

    #[test]
    fn the_arrangement_orders_what_is_heard() {
        let piece = rendered(
            "bpm 120\ntail 0\n\
             section a 1 {\n  beat kick \"x\"\n}\n\
             section b 1 {\n  rest kick \"~\"\n}\n\
             arrange b a\n",
        );
        let cycle = 2 * 44_100;
        assert!(
            peak(&piece, 0, cycle) < 1e-6,
            "the silent section must be silent"
        );
        assert!(
            peak(&piece, cycle, 2 * cycle) > 0.001,
            "the sounding one must follow"
        );
    }

    #[test]
    fn ungrouped_occurrences_become_independent_render_islands() {
        let piece = rendered("bpm 120\ntail 0\nsection a 1 {\n  k kick \"x\"\n}\narrange a a a\n");
        assert_eq!(piece.occurrences, 3);
        assert_eq!(piece.telemetry.islands, 3);
        assert_eq!(piece.telemetry.slots, 3);
        assert!(piece.telemetry.worker_threads >= 1);
    }

    #[test]
    fn a_shared_bus_remains_one_piece_wide_island() {
        let piece = rendered(
            "bpm 120\ntail 0\nsection a 1 {\n  group drums {\n    k kick \"x\"\n  } | reverb 0.25\n}\narrange a a a\n",
        );
        assert_eq!(piece.occurrences, 3);
        assert_eq!(piece.telemetry.islands, 1);
        assert_eq!(piece.telemetry.slots, 3);
    }

    #[test]
    fn a_span_places_a_line_inside_its_section() {
        let piece = rendered("bpm 120\ntail 0\nsection a 4 {\n  fill kick \"x\" @ 4\n}\n");
        assert_eq!(piece.notes, 1);
        let cycle = 2 * 44_100;
        assert!(peak(&piece, 0, 3 * cycle) < 1e-6, "cycles 1-3 are silent");
        assert!(peak(&piece, 3 * cycle, 4 * cycle) > 0.001, "cycle 4 sounds");
    }

    #[test]
    fn nothing_leaves_above_the_master_ceiling() {
        // Eight voices at once: the engine's ceiling has to hold, and a render
        // that clipped would be the artifact this whole path was fixed for.
        let piece = rendered(
            "bpm 120\ntail 0\nsection dense 2 {\n\
             \x20 k kick \"x*4\"\n  s snare \"x*4\"\n  h hihat \"x*8\"\n  c clap \"x*4\"\n\
             \x20 t tom \"x*4\"\n  r rim \"x*4\"\n  p pad \"[c3,e3,g3]\"\n  b bass \"c2*4\"\n}\n",
        );
        let worst = piece.samples.iter().fold(0.0f32, |m, s| m.max(s.abs()));
        assert!(worst <= 0.95 + 1e-6, "peaked at {worst}");
        assert!(piece.telemetry.pre_limiter_peak >= piece.telemetry.post_limiter_peak);
        assert!(piece.telemetry.max_gain_reduction_db > 0.0);
        assert!(piece.telemetry.limited_samples > 0);
    }

    /// Rendered without the master limiter, a piece cut into per-instrument
    /// renders adds back up to the whole — which, limited, it does not.
    #[test]
    fn unlimited_parts_sum_to_the_unlimited_mix() {
        let source = "bpm 120\ntail 0.5\nsection dense 2 {\n\
             \x20 k kick \"x*4\"\n  s snare \"x*4\"\n  h hihat \"x*8\"\n\
             \x20 p pad \"[c3,e3,g3]\"\n  b bass \"c2*4\"\n}\n";
        let (program, errors) = crate::parser::parse_program(source);
        assert!(errors.is_empty(), "parse: {errors:?}");
        let (piece, errors) = crate::piece::resolve(&program, (120, (4, 4), None));
        assert!(errors.is_empty(), "resolve: {errors:?}");
        let registry = InstrumentRegistry::built_in();
        let make = |piece: &Piece, master_limiter: bool| {
            render_with_options(
                piece,
                &registry,
                44_100,
                RenderOptions { master_limiter },
                &mut |_| {},
            )
            .expect("render")
        };

        let mix = make(&piece, false);
        assert!(!mix.limited);
        assert!(mix.peak() > 1.0, "too quiet to tell: {}", mix.peak());
        assert_eq!(mix.telemetry.limited_samples, 0);
        assert_eq!(
            mix.telemetry.pre_limiter_peak,
            mix.telemetry.post_limiter_peak
        );
        assert_eq!(mix.telemetry.post_limiter_peak, mix.peak());

        let parts = [vec!["kick", "snare", "hihat"], vec!["pad"], vec!["bass"]];
        let sum_of = |limited: bool| {
            let mut sum = vec![0.0f32; mix.samples.len()];
            for keep in &parts {
                let mut part = piece.clone();
                part.mute_except(keep);
                for (total, sample) in sum.iter_mut().zip(make(&part, limited).samples) {
                    *total += sample;
                }
            }
            sum
        };
        let error = |sum: &[f32]| {
            sum.iter()
                .zip(&mix.samples)
                .fold(0.0f32, |worst, (a, b)| worst.max((a - b).abs()))
        };
        let unlimited = error(&sum_of(false));
        assert!(
            unlimited < 1e-4,
            "the parts drift from the mix by {unlimited}"
        );
        // Limited, the full render is squeezed by the mix's peaks and each
        // part only by its own, so the parts no longer add up to it.
        let limited_mix = make(&piece, true);
        assert!(limited_mix.limited && limited_mix.telemetry.limited_samples > 0);
        let to_limited = sum_of(true)
            .iter()
            .zip(&limited_mix.samples)
            .fold(0.0f32, |worst, (a, b)| worst.max((a - b).abs()));
        assert!(to_limited > 0.05, "the limited parts summed anyway");
    }

    #[test]
    fn progress_is_reported_in_order_and_reaches_the_end() {
        let (program, _) = crate::parser::parse_program(
            "bpm 120\ntail 0\nsection a 2 {\n  beat kick \"x ~ x ~\"\n}\n",
        );
        let (piece, _) = crate::piece::resolve(&program, (120, (4, 4), None));
        let mut seen: Vec<String> = Vec::new();
        let mut last_fraction = 0.0f64;
        let out = render_with_progress(
            &piece,
            &InstrumentRegistry::built_in(),
            44_100,
            &mut |progress| {
                match &progress {
                    Progress::Compiling { .. } => seen.push("compiling".into()),
                    Progress::Building { .. } => seen.push("building".into()),
                    Progress::Rendering {
                        frames,
                        total_frames,
                    } => {
                        let fraction = *frames as f64 / *total_frames as f64;
                        assert!(fraction >= last_fraction, "progress went backwards");
                        assert!(fraction <= 1.0, "progress exceeded 100%");
                        last_fraction = fraction;
                        seen.push("rendering".into());
                    }
                    Progress::Done { .. } => seen.push("done".into()),
                };
            },
        )
        .expect("render");

        assert_eq!(seen.first().map(String::as_str), Some("compiling"));
        assert_eq!(seen.last().map(String::as_str), Some("done"));
        assert!(seen.contains(&"building".to_string()));
        assert!(
            seen.iter().filter(|s| *s == "rendering").count() > 10,
            "too few progress reports to drive a bar"
        );
        assert!(!out.samples.is_empty());
    }

    /// `seed` (§8.8) reaches the generative constructs, and the same seed
    /// reproduces.
    ///
    /// It did not: the walk was hashed on the step index alone, so the
    /// directive documented as salting the generative constructs changed
    /// nothing at all.
    #[test]
    fn the_seed_rerolls_a_generated_walk_and_repeats_exactly() {
        let render_with = |seed: u64| {
            let source = format!(
                "seed {seed}\nbpm 120\ntail 0\nsection a 4 {{\n  walk pluck \"solo(0..7, 6)\"\n}}\n"
            );
            let (program, errors) = crate::parser::parse_program(&source);
            assert!(errors.is_empty(), "{errors:?}");
            let (piece, errors) = crate::piece::resolve(&program, (120, (4, 4), None));
            assert!(errors.is_empty(), "{errors:?}");
            let registry = InstrumentRegistry::built_in();
            let notes = scheduled_notes(&piece, &registry, 44_100).expect("notes");
            notes.into_iter().map(|note| note.midi).collect::<Vec<u8>>()
        };

        let zero = render_with(0);
        let seven = render_with(7);
        assert!(!zero.is_empty(), "the walk generated nothing");
        assert_ne!(zero, seven, "the seed changed nothing");
        assert_eq!(zero, render_with(0), "the same seed did not reproduce");
        assert_eq!(seven, render_with(7), "the same seed did not reproduce");
    }

    /// Rendering twice gives the same samples, which is what makes a render
    /// usable in a build.
    #[test]
    fn two_renders_of_one_piece_are_identical() {
        let source = "bpm 120\ntail 0\nsection a 2 {\n  k kick \"x*4\"\n  h hihat \"x*8\"\n                        p pad \"[c3,e3,g3]\"\n}\n";
        let (program, _) = crate::parser::parse_program(source);
        let (piece, _) = crate::piece::resolve(&program, (120, (4, 4), None));
        let registry = InstrumentRegistry::built_in();
        let first = render(&piece, &registry, 44_100).expect("render");
        let second = render(&piece, &registry, 44_100).expect("render");
        assert_eq!(
            first.samples, second.samples,
            "two renders of one piece differed"
        );
    }

    #[test]
    fn an_empty_arrangement_is_refused_rather_than_rendered_silent() {
        let (program, _) = crate::parser::parse_program("bpm 120\n");
        let (piece, _) = crate::piece::resolve(&program, (120, (4, 4), None));
        let error =
            render(&piece, &InstrumentRegistry::built_in(), 44_100).expect_err("nothing to render");
        assert!(error.contains("nothing to render"), "{error}");
    }
}

/// Every note the piece schedules, as `(absolute frame, midi)`.
///
/// The same walk [`render`] makes, stopping before any audio. Exposed because
/// a piece's note content is worth checking on its own — a harmonic premise
/// ("every note comes from one collection") is a property of the notes, not of
/// the samples, and asserting it against the audio would be guesswork.
pub fn scheduled_notes(
    piece: &Piece,
    registry: &InstrumentRegistry,
    sample_rate: u32,
) -> Result<Vec<ScheduledNote>, String> {
    let mut notes = Vec::new();
    let mut at_frame = 0u64;
    for occurrence in &piece.timeline {
        let section = &piece.sections[occurrence.section];
        let cycle_frames = section_cycle_frames(section, sample_rate);
        let origin_cycle = occurrence.start_cycle;
        for line in section
            .patterns
            .iter()
            .chain(&piece.throughout)
            .filter(|line| !line.muted && !section.muted)
        {
            let compiled = compile_line(piece, section, line, registry, origin_cycle)?;
            for (cycle, strike) in line_strikes(section, line, &compiled, origin_cycle) {
                let cycle_start = at_frame + u64::from(cycle) * cycle_frames;
                let start = cycle_start + (strike.start * cycle_frames as f64).round() as u64;
                let end = start
                    + ((strike.end - strike.start) * NOTE_GATE * cycle_frames as f64).round()
                        as u64;
                for midi in strike.notes {
                    notes.push(ScheduledNote {
                        start,
                        end: end.max(start + 1),
                        midi,
                        line: line.name.clone(),
                        section: section.name.clone(),
                    });
                }
            }
        }
        at_frame += cycle_frames * u64::from(section.cycles);
    }
    notes.sort_by_key(|note| (note.start, note.midi));
    Ok(notes)
}

/// What one line of one section strikes, as an editor draws it.
///
/// The section is taken at its first playing in the arrangement — or at the
/// start of the piece when it is never played — because travels, drops and
/// choices count from there, and a line heard on its own should sound the way
/// it does in the song. Muted lines are included: asking for a line by name
/// is asking to see it.
pub fn section_strikes(
    piece: &Piece,
    registry: &InstrumentRegistry,
    section: usize,
    lines: Option<&[String]>,
) -> Result<Vec<LineStrikes>, String> {
    let placed = &piece.sections[section];
    let origin_cycle = first_playing(piece, section);
    placed
        .patterns
        .iter()
        .filter(|line| lines.is_none_or(|names| names.contains(&line.name)))
        .map(|line| {
            let compiled = compile_line(piece, placed, line, registry, origin_cycle)?;
            let strikes = line_strikes(placed, line, &compiled, origin_cycle).collect();
            Ok(LineStrikes {
                line: line.name.clone(),
                instrument: line.instrument.clone(),
                strikes,
                automations: line_automations(placed, line, &compiled, origin_cycle),
            })
        })
        .collect()
}

/// The absolute cycle a section first starts on, or 0 when it never plays.
///
/// The rule lives on [`Piece::first_playing`], so a caller without the
/// renderer can read it too; this is kept beside [`section_strikes`], which
/// it serves.
pub fn first_playing(piece: &Piece, section: usize) -> u64 {
    piece.first_playing(section)
}

/// One line's strikes over its section, each with the 0-based cycle within
/// the section it falls in.
#[derive(Debug, Clone, PartialEq)]
pub struct LineStrikes {
    pub line: String,
    pub instrument: String,
    pub strikes: Vec<(u32, Strike)>,
    /// The line's values that travel, as the renderer moves them.
    pub automations: Vec<Automation>,
}

/// One travelling value on a line — `lpf 900..2600`, `vel 0.4>0.7>1.0`, an
/// `r(...)` argument — sampled across the cycles the line sounds on.
#[derive(Debug, Clone, PartialEq)]
pub struct Automation {
    /// What moves: `lpf`, `delay time`, `fx Tremolo depth`.
    pub label: String,
    /// `Hz`, `s`, or empty for a plain level.
    pub unit: &'static str,
    /// The lowest and highest value it passes through.
    pub low: f64,
    pub high: f64,
    /// `(cycle within the section, value)`, in order.
    pub points: Vec<(f64, f64)>,
}

/// How many samples a cycle gets: enough for a sweep to read as a curve. A
/// value with its own `r(...)` window may move within a beat, so it gets more.
const SAMPLES_PER_CYCLE: u32 = 16;
const SAMPLES_PER_CYCLE_TIMED: u32 = 64;

/// Every travelling value on a line, sampled with the same travel the
/// renderer uses, over the cycles the line's span allows.
fn line_automations(
    section: &Section,
    line: &PatternDef,
    compiled: &CompiledPattern,
    origin_cycle: u64,
) -> Vec<Automation> {
    let mut found: Vec<(String, &'static str, Ramp<f64>)> = Vec::new();
    for transform in &line.transforms {
        travelling_values(transform, &mut found);
    }
    let from = line.span.map_or(1, |s| s.start());
    let to = line
        .span
        .map_or(section.cycles, |s| s.end(section.cycles))
        .min(section.cycles);
    found
        .into_iter()
        .map(|(label, unit, ramp)| {
            let per_cycle = if ramp.own_window().is_some() {
                SAMPLES_PER_CYCLE_TIMED
            } else {
                SAMPLES_PER_CYCLE
            };
            let value_at = |within: f64| {
                let travel = compiled.line_travel(origin_cycle as f64 + within);
                travel_f64(&ramp, travel).start()
            };
            let mut points = Vec::new();
            for cycle in from..=to {
                for sample in 0..per_cycle {
                    let within = f64::from(cycle - 1) + f64::from(sample) / f64::from(per_cycle);
                    points.push((within, value_at(within)));
                }
            }
            let end = f64::from(to);
            points.push((end, value_at(end - 1e-9)));
            let values = ramp.values();
            let low = values.iter().copied().fold(f64::INFINITY, f64::min);
            let high = values.iter().copied().fold(f64::NEG_INFINITY, f64::max);
            Automation {
                label,
                unit,
                low,
                high,
                points,
            }
        })
        .collect()
}

/// The values on a transform that travel, labelled for an editor.
fn travelling_values(transform: &Transform, found: &mut Vec<(String, &'static str, Ramp<f64>)>) {
    let mut push = |label: &str, unit: &'static str, ramp: &Ramp<f64>| {
        if ramp.travels() {
            found.push((label.to_string(), unit, ramp.clone()));
        }
    };
    match transform {
        Transform::Vel(ramp) => push("vel", "", ramp),
        Transform::Gain(ramp) => push("gain", "", ramp),
        Transform::Pan(ramp) => push("pan", "", ramp),
        Transform::Lpf(ramp) => push("lpf", "Hz", ramp),
        Transform::Hpf(ramp) => push("hpf", "Hz", ramp),
        Transform::Reverb(ramp) => push("reverb", "", ramp),
        Transform::Fast(ramp) => push("fast", "", ramp),
        Transform::Slow(ramp) => push("slow", "", ramp),
        Transform::Oct(ramp) => push("oct", "", &ramp_as_f64(ramp)),
        Transform::Delay(time, feedback, mix) => {
            push("delay time", "s", time);
            push("delay feedback", "", feedback);
            if let Some(mix) = mix {
                push("delay mix", "", mix);
            }
        }
        Transform::Fx(call) => {
            for (index, arg) in call.args.iter().enumerate() {
                let (name, value) = match arg {
                    FxArg::Positional(value) => (format!("#{}", index + 1), value),
                    FxArg::Named(name, value) => (name.clone(), value),
                };
                let unit = match value {
                    FxValue::Hertz(_) => "Hz",
                    FxValue::Plain(_) => "",
                };
                push(&format!("fx {} {name}", call.filter), unit, value.ramp());
            }
        }
        // `every` applies on some cycles only; drawing it as a smooth travel
        // would misdescribe it.
        _ => {}
    }
}

fn ramp_as_f64(ramp: &Ramp<i32>) -> Ramp<f64> {
    match ramp {
        Ramp::Fixed(value) => Ramp::Fixed(f64::from(*value)),
        Ramp::Sweep { from, to } => Ramp::Sweep {
            from: f64::from(*from),
            to: f64::from(*to),
        },
        Ramp::Steps { first, rest } => Ramp::Steps {
            first: f64::from(*first),
            rest: rest.iter().copied().map(f64::from).collect(),
        },
        Ramp::Timed {
            ramp,
            span_divisions,
            curve,
        } => Ramp::Timed {
            ramp: Box::new(ramp_as_f64(ramp)),
            span_divisions: *span_divisions,
            curve: *curve,
        },
    }
}

/// Compile one line the way an occurrence starting on `origin_cycle` plays it.
fn compile_line(
    piece: &Piece,
    section: &Section,
    line: &PatternDef,
    registry: &InstrumentRegistry,
    origin_cycle: u64,
) -> Result<CompiledPattern, String> {
    let line_origin = travel_origin(line, origin_cycle);
    let travel = LineTravel {
        line: Travel::START,
        cycle: line_origin as f64,
        origin: line_origin,
        divisions: section.sig.0,
    };
    let (audio_fx, fx_ramps) = pattern_fx(&line.transforms, section.cycle_seconds(), travel)
        .map_err(|error| format!("'{}': {error}", line.name))?;
    let spec = registry
        .get(&line.instrument)
        .ok_or_else(|| format!("'{}': unknown instrument", line.name))?
        .clone();
    let instrument_fx = spec.fx.len();
    Ok(compile_pattern(
        line,
        section.scale,
        audio_fx,
        fx_ramps,
        instrument_fx,
        spec,
        PatternGate::default(),
        line_origin,
        section.sig.0,
        piece.seed,
    ))
}

/// The absolute cycle a line's travels start from: the first bar of its span
/// in this occurrence (§8.6), so a line entering on bar 13 with `| ramp 4`
/// sweeps across bars 13 to 16 rather than arriving already swept.
fn travel_origin(line: &PatternDef, occurrence_start: u64) -> u64 {
    occurrence_start + u64::from(line.span.map_or(1, |span| span.start()) - 1)
}

/// Every strike of a compiled line across the cycles its span allows, with the
/// 0-based cycle within the section each falls in.
fn line_strikes<'a>(
    section: &Section,
    line: &PatternDef,
    compiled: &'a CompiledPattern,
    origin_cycle: u64,
) -> impl Iterator<Item = (u32, Strike)> + 'a {
    let from = line.span.map_or(1, |s| s.start());
    let to = line
        .span
        .map_or(section.cycles, |s| s.end(section.cycles))
        .min(section.cycles);
    (from..=to).flat_map(move |cycle| {
        let within = cycle - 1;
        cycle_strikes_at(
            compiled,
            origin_cycle + u64::from(within),
            u64::from(within),
        )
        .into_iter()
        .map(move |strike| (within, strike))
    })
}

/// One scheduled note, with enough context to reason about it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ScheduledNote {
    /// Absolute frame the note starts on.
    pub start: u64,
    /// Absolute frame its gate closes.
    pub end: u64,
    pub midi: u8,
    /// The pattern line that played it.
    pub line: String,
    /// The section it was played in.
    pub section: String,
}