alpha2-model 0.10.0

Versioned project and timeline model for alpha2.
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
use crate::{Animated, BusId, Domain, Extrapolation, Interpolation, TimeMap, TrackId};
use alpha2_time::{MediaTime, TICKS_PER_SECOND, TimeRange};
use serde::{Deserialize, Serialize};

pub(crate) const TICKS_PER_MS: u32 = 120;
const _: () = assert!(TICKS_PER_SECOND == 1_000 * TICKS_PER_MS as i64);

/// Largest linear amplitude accepted by any authored gain.
pub const MAX_GAIN: f32 = 16.0;

/// Most audio effects a project holds state for at once: the master's, the buses', the
/// tracks', and those of clips holding state then (see [`AUDIO_EFFECT_STATE_MARGIN_MS`]). An
/// equalizer is one effect regardless of bands.
pub const MAX_AUDIO_EFFECTS: usize = 8_192;

/// Most audio held in delay lines at once, in milliseconds, summed over the effects
/// [`MAX_AUDIO_EFFECTS`] counts (a compressor's `lookahead_ms`, a reverb's
/// [`REVERB_DELAY_MS`]) and the routing edges that wait for a longer path (see
/// [`crate::Project::audio_effect_load`]). At the highest project rate this is under 100 MB of
/// state.
pub const MAX_AUDIO_DELAY_MS: u32 = 120_000;

/// How long before its start, beyond its track's and its own compressor lookahead, a clip's
/// effects count as holding state, in milliseconds. This covers one block of the largest size
/// at the lowest project rate plus per-lookahead sample rounding. Effects count until the
/// clip's end.
pub const AUDIO_EFFECT_STATE_MARGIN_MS: u32 = 1_100;

/// What one reverb counts toward [`MAX_AUDIO_DELAY_MS`]; its comb and allpass lines hold
/// about 157 ms at any rate.
pub const REVERB_DELAY_MS: u32 = 160;

/// Largest peaking gain, in decibels either way, an EQ band renders.
pub const MAX_EQ_GAIN_DB: f32 = 36.0;

/// The resonances an EQ band renders.
pub const EQ_Q_RANGE: std::ops::RangeInclusive<f32> = 0.05..=50.0;

/// The frequencies an EQ band may name, in hertz: 10 Hz to just under the Nyquist frequency
/// of the highest project rate. A band renders at most at 0.49 times the project's rate, so
/// a higher band sounds at that limit.
pub const EQ_FREQUENCY_RANGE_HZ: std::ops::RangeInclusive<f32> = 10.0..=47_040.0;

/// Largest compressor ratio.
pub const MAX_COMPRESSOR_RATIO: f32 = 100.0;

/// Largest pitch shift of a clip either way, in cents: two octaves.
pub const MAX_PITCH_CENTS: f32 = 2_400.0;

const CENTS_PER_OCTAVE: f32 = 1_200.0;

/// Most effects one chain holds: a clip's, a track's, a bus's, or the master's.
pub const MAX_CHAIN_EFFECTS: usize = 16;

/// Most buses a project holds.
pub const MAX_AUDIO_BUSES: usize = 64;

/// Most sends one track or bus holds.
pub const MAX_AUDIO_SENDS: usize = 8;

/// Most bands one equalizer holds.
pub const MAX_EQ_BANDS: usize = 16;

/// The quietest compressor or expander threshold or ducker depth, in decibels; each is at most
/// 0 dB.
pub const MIN_LEVEL_DB: f32 = -96.0;

/// Longest compressor or expander lookahead, in milliseconds.
pub const MAX_LOOKAHEAD_MS: f32 = 100.0;

/// Widest compressor knee, in decibels.
pub const MAX_KNEE_DB: f32 = 24.0;

/// Largest compressor makeup gain, in decibels either way.
pub const MAX_MAKEUP_DB: f32 = 24.0;

/// Deepest expander attenuation, in decibels.
pub const MAX_EXPANDER_RANGE_DB: f32 = 96.0;

/// Longest expander hold, in milliseconds.
pub const MAX_HOLD_MS: f32 = 10_000.0;

/// Longest delay effect time, in milliseconds; the shortest is one.
pub const MAX_DELAY_MS: f32 = 2_000.0;

/// Most feedback a delay effect takes.
pub const MAX_DELAY_FEEDBACK: f32 = 0.95;

/// Largest magnitude of a matrix effect's gain.
pub const MAX_MATRIX_GAIN: f32 = 4.0;

/// Longest attack or release time, in milliseconds.
pub const MAX_ENVELOPE_MS: f32 = 10_000.0;

/// The filter shape of one equalizer band, by the Audio EQ Cookbook's second-order forms.
#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum EqBandKind {
    /// Bell-shaped parametric band.
    Peaking,
    /// Second-order low-pass.
    LowPass,
    /// Second-order high-pass.
    HighPass,
    /// Raises or lowers everything below the corner by `gain_db`, half of it at the corner.
    LowShelf,
    /// Raises or lowers everything above the corner by `gain_db`, half of it at the corner.
    HighShelf,
    /// Removes the centre frequency and passes the rest.
    Notch,
    /// Passes the centre frequency at unity and falls away on both sides.
    BandPass,
    /// Passes every frequency at unity and turns the phase through 180 degrees at the centre.
    AllPass,
}

/// How a compressor measures the level it compresses by.
#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum Detector {
    /// The largest sample magnitude, smoothed by the attack and release.
    #[default]
    Peak,
    /// The square root of the mean square, smoothed by the attack and release: a sine reads
    /// 3 dB under its peak.
    Rms,
}

/// One static filter before a compressor's or expander's level detector, so that only a band
/// of the detected signal drives the gain. A compressor with a high-pass here is a de-esser.
#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DetectorFilter {
    /// Filter shape. A peaking or shelving shape has a gain of 0 dB.
    pub kind: EqBandKind,
    /// Centre or corner frequency in hertz, within [`EQ_FREQUENCY_RANGE_HZ`].
    pub frequency_hz: f32,
    /// Resonance, within [`EQ_Q_RANGE`].
    pub q: f32,
}

impl DetectorFilter {
    fn is_valid(self) -> bool {
        Domain::EQ_FREQUENCY_HZ.contains(self.frequency_hz) && Domain::EQ_Q.contains(self.q)
    }
}

/// A single equalizer section stored independently from its DSP implementation.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct EqBand {
    /// Filter shape.
    pub kind: EqBandKind,
    /// Animated center or corner frequency in hertz, within [`EQ_FREQUENCY_RANGE_HZ`].
    pub frequency_hz: Animated<f32>,
    /// Animated resonance, within [`EQ_Q_RANGE`]. Larger values produce narrower bands.
    pub q: Animated<f32>,
    /// Animated gain of a peaking or shelving band in decibels, at most [`MAX_EQ_GAIN_DB`]
    /// either way. Ignored by the other shapes.
    #[serde(default = "zero")]
    pub gain_db: Animated<f32>,
}

/// One parameter of an audio effect that animates.
#[derive(Clone, Copy, Debug)]
pub struct AudioEffectParam<V> {
    /// The equalizer band that holds it, for a band's parameter.
    pub band: Option<usize>,
    /// Its field name.
    pub name: &'static str,
    /// Its place in the JSON schema, as `Type.field` or `Type[tag].field`.
    pub place: &'static str,
    /// The values it takes. A constant or a keyframe outside is refused; an interpolated or
    /// bound value is clamped.
    pub domain: Domain,
    /// The value.
    pub value: V,
}

impl<V> AudioEffectParam<V> {
    /// Its path below the effect: `threshold_db`, `bands[1].gain_db`.
    #[must_use]
    pub fn path(&self) -> String {
        match self.band {
            Some(band) => format!("bands[{band}].{}", self.name),
            None => self.name.to_owned(),
        }
    }
}

macro_rules! effect_params {
    ($effect:expr, $visit:expr, $bands:ident) => {{
        let mut visit = |band, name, place, domain, value| {
            $visit(AudioEffectParam {
                band,
                name,
                place,
                domain,
                value,
            });
        };
        match $effect {
            AudioEffect::Eq { bands } => {
                for (index, band) in bands.$bands().enumerate() {
                    let at = Some(index);
                    let EqBand {
                        kind: _,
                        frequency_hz,
                        q,
                        gain_db,
                    } = band;
                    visit(
                        at,
                        "frequency_hz",
                        "EqBand.frequency_hz",
                        Domain::EQ_FREQUENCY_HZ,
                        frequency_hz,
                    );
                    visit(at, "q", "EqBand.q", Domain::EQ_Q, q);
                    visit(at, "gain_db", "EqBand.gain_db", Domain::EQ_GAIN_DB, gain_db);
                }
            }
            AudioEffect::Compressor {
                threshold_db,
                ratio,
                knee_db,
                makeup_db,
                attack_ms: _,
                release_ms: _,
                lookahead_ms: _,
                detector: _,
                detector_filter: _,
                sidechain: _,
            } => {
                visit(
                    None,
                    "threshold_db",
                    "AudioEffect[compressor].threshold_db",
                    Domain::LEVEL_DB,
                    threshold_db,
                );
                visit(
                    None,
                    "ratio",
                    "AudioEffect[compressor].ratio",
                    Domain::COMPRESSOR_RATIO,
                    ratio,
                );
                visit(
                    None,
                    "knee_db",
                    "AudioEffect[compressor].knee_db",
                    Domain::KNEE_DB,
                    knee_db,
                );
                visit(
                    None,
                    "makeup_db",
                    "AudioEffect[compressor].makeup_db",
                    Domain::MAKEUP_DB,
                    makeup_db,
                );
            }
            AudioEffect::Expander {
                threshold_db,
                ratio,
                range_db,
                attack_ms: _,
                hold_ms: _,
                release_ms: _,
                lookahead_ms: _,
                detector_filter: _,
                sidechain: _,
            } => {
                visit(
                    None,
                    "threshold_db",
                    "AudioEffect[expander].threshold_db",
                    Domain::LEVEL_DB,
                    threshold_db,
                );
                visit(
                    None,
                    "ratio",
                    "AudioEffect[expander].ratio",
                    Domain::COMPRESSOR_RATIO,
                    ratio,
                );
                visit(
                    None,
                    "range_db",
                    "AudioEffect[expander].range_db",
                    Domain::EXPANDER_RANGE_DB,
                    range_db,
                );
            }
            AudioEffect::Delay {
                time_ms: _,
                feedback,
                mix,
            } => {
                visit(
                    None,
                    "feedback",
                    "AudioEffect[delay].feedback",
                    Domain::DELAY_FEEDBACK,
                    feedback,
                );
                visit(None, "mix", "AudioEffect[delay].mix", Domain::UNIT, mix);
            }
            AudioEffect::Matrix { left, right } => {
                let [from_left, from_right] = left;
                visit(
                    None,
                    "left[0]",
                    "AudioEffect[matrix].left",
                    Domain::MATRIX_GAIN,
                    from_left,
                );
                visit(
                    None,
                    "left[1]",
                    "AudioEffect[matrix].left",
                    Domain::MATRIX_GAIN,
                    from_right,
                );
                let [from_left, from_right] = right;
                visit(
                    None,
                    "right[0]",
                    "AudioEffect[matrix].right",
                    Domain::MATRIX_GAIN,
                    from_left,
                );
                visit(
                    None,
                    "right[1]",
                    "AudioEffect[matrix].right",
                    Domain::MATRIX_GAIN,
                    from_right,
                );
            }
            AudioEffect::Ducker {
                sidechain: _,
                threshold,
                depth_db,
                attack_ms: _,
                release_ms: _,
            } => {
                visit(
                    None,
                    "threshold",
                    "AudioEffect[ducker].threshold",
                    Domain::POSITIVE,
                    threshold,
                );
                visit(
                    None,
                    "depth_db",
                    "AudioEffect[ducker].depth_db",
                    Domain::LEVEL_DB,
                    depth_db,
                );
            }
            AudioEffect::Reverb {
                room_size: _,
                damping: _,
                mix,
            } => visit(None, "mix", "AudioEffect[reverb].mix", Domain::UNIT, mix),
        }
    }};
}

/// A serializable audio effect applied to a clip, a track, a bus or the master.
///
/// An effect with a `sidechain` follows the level of that track or bus instead of its own
/// input: its signal after its effects and before its fader and pan. A clip's effects take
/// none.
///
/// A parameter documented as animated is keyed in timeline time and evaluated at every 32nd
/// sample of the effect's own input, counted from timeline zero; the effect moves in a straight
/// line between two such points. A constant parameter keeps its exact value.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AudioEffect {
    /// Cascaded biquad sections.
    Eq {
        /// Ordered filter sections, 1 to [`MAX_EQ_BANDS`] of them.
        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_EQ_BANDS }>")]
        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_EQ_BANDS)))]
        bands: Vec<EqBand>,
    },
    /// Lookahead dynamic range compression with linked channels.
    ///
    /// With the level `x`, the threshold `T`, the ratio `R` and the knee `W` in decibels, the
    /// gain is 0 dB while `2 (x - T) < -W`, `(1/R - 1) (x - T + W/2)^2 / (2 W)` while
    /// `2 |x - T| <= W`, and `T + (x - T) / R - x` above; the makeup gain is added to it.
    Compressor {
        /// Animated level above which gain reduction begins, in decibels from [`MIN_LEVEL_DB`]
        /// to 0.
        threshold_db: Animated<f32>,
        /// Animated downward ratio, from one (unity) to [`MAX_COMPRESSOR_RATIO`].
        ratio: Animated<f32>,
        /// Animated width of the knee centred on the threshold, in decibels from 0 (a hard
        /// knee) to [`MAX_KNEE_DB`].
        #[serde(default = "zero")]
        knee_db: Animated<f32>,
        /// Animated gain applied after the reduction, in decibels, at most [`MAX_MAKEUP_DB`]
        /// either way.
        #[serde(default = "zero")]
        makeup_db: Animated<f32>,
        /// Attack time in milliseconds, positive and at most [`MAX_ENVELOPE_MS`].
        attack_ms: f32,
        /// Release time in milliseconds, positive and at most [`MAX_ENVELOPE_MS`].
        release_ms: f32,
        /// Lookahead in milliseconds, at most [`MAX_LOOKAHEAD_MS`]. Reported as graph latency.
        #[serde(default)]
        lookahead_ms: f32,
        /// How the level is measured.
        #[serde(default)]
        detector: Detector,
        /// A filter before the detector.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        detector_filter: Option<DetectorFilter>,
        /// The track or bus whose level drives the reduction; absent, the effect's own input.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        sidechain: Option<AudioNodeRef>,
    },
    /// Downward expansion with linked channels; with a high ratio, a gate.
    ///
    /// The level is a peak follower with the attack and release times. Under the threshold
    /// `T` a level `x` in decibels asks for `min((T - x) (R - 1), range_db)` decibels of
    /// attenuation. The gain opens with the attack time; before it closes it holds for
    /// `hold_ms`, then closes with the release time.
    Expander {
        /// Animated level below which attenuation begins, in decibels from [`MIN_LEVEL_DB`]
        /// to 0.
        threshold_db: Animated<f32>,
        /// Animated ratio, from one (unity) to [`MAX_COMPRESSOR_RATIO`]: under the threshold
        /// the output falls this many decibels for each decibel the level falls.
        ratio: Animated<f32>,
        /// Animated limit of the attenuation, in decibels from 0 to
        /// [`MAX_EXPANDER_RANGE_DB`], which is the default.
        #[serde(default = "full_range")]
        range_db: Animated<f32>,
        /// Attack time in milliseconds, positive and at most [`MAX_ENVELOPE_MS`].
        attack_ms: f32,
        /// Hold time in milliseconds, at most [`MAX_HOLD_MS`].
        #[serde(default)]
        hold_ms: f32,
        /// Release time in milliseconds, positive and at most [`MAX_ENVELOPE_MS`].
        release_ms: f32,
        /// Lookahead in milliseconds, at most [`MAX_LOOKAHEAD_MS`]. Reported as graph latency.
        #[serde(default)]
        lookahead_ms: f32,
        /// A filter before the detector.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        detector_filter: Option<DetectorFilter>,
        /// The track or bus whose level drives the gain; absent, the effect's own input.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        sidechain: Option<AudioNodeRef>,
    },
    /// A feedback delay line: each channel repeats after `time_ms`. With the sample `x` and
    /// the line's oldest sample `d`, the line takes `x + feedback * d` and the output is
    /// `x * (1 - mix) + d * mix`. It adds no latency.
    Delay {
        /// Delay time in milliseconds, from 1 to [`MAX_DELAY_MS`].
        time_ms: f32,
        /// Animated share of the delayed signal fed back into the line, from 0 to
        /// [`MAX_DELAY_FEEDBACK`].
        feedback: Animated<f32>,
        /// Animated wet mix, in `0..=1`.
        mix: Animated<f32>,
    },
    /// A two-by-two gain matrix over the stereo pair: the left output is
    /// `left[0] * L + left[1] * R` and the right `right[0] * L + right[1] * R`. Width, swap,
    /// mono, polarity and balance are settings of it. A mono mix takes
    /// `((left[0] + left[1]) + (right[0] + right[1])) / 2` times the sample.
    Matrix {
        /// The animated gains the left output takes from left and right, each at most
        /// [`MAX_MATRIX_GAIN`] either way.
        left: [Animated<f32>; 2],
        /// The animated gains the right output takes from left and right, each at most
        /// [`MAX_MATRIX_GAIN`] either way.
        right: [Animated<f32>; 2],
    },
    /// Lowers the signal while its key sounds.
    Ducker {
        /// The track or bus whose level drives the attenuation.
        sidechain: AudioNodeRef,
        /// Animated linear key level above which attenuation begins. Positive.
        threshold: Animated<f32>,
        /// Animated maximum attenuation in decibels, from [`MIN_LEVEL_DB`] to 0.
        depth_db: Animated<f32>,
        /// Attack time in milliseconds, positive and at most [`MAX_ENVELOPE_MS`].
        attack_ms: f32,
        /// Release time in milliseconds, positive and at most [`MAX_ENVELOPE_MS`].
        release_ms: f32,
    },
    /// Schroeder reverberation.
    Reverb {
        /// Room size, in `0..=1`.
        room_size: f32,
        /// High-frequency damping, in `0..=1`.
        damping: f32,
        /// Animated wet mix, in `0..=1`.
        mix: Animated<f32>,
    },
}

impl AudioEffect {
    /// What this effect counts toward [`MAX_AUDIO_DELAY_MS`], in ticks (120 per millisecond),
    /// rounded up. Tick counts are exact, so a project's effects sum the same in any order.
    #[must_use]
    pub fn delay_ticks(&self) -> u64 {
        match self {
            Self::Eq { .. } | Self::Ducker { .. } | Self::Matrix { .. } => 0,
            Self::Compressor { .. } | Self::Expander { .. } => self.lookahead_ticks(),
            Self::Delay { time_ms, .. } => ms_ticks(*time_ms),
            Self::Reverb { .. } => u64::from(REVERB_DELAY_MS) * u64::from(TICKS_PER_MS),
        }
    }

    /// How early a mixer reads this effect's input, in ticks, rounded up: a compressor's or
    /// expander's `lookahead_ms`.
    #[must_use]
    pub fn lookahead_ticks(&self) -> u64 {
        match self {
            Self::Compressor { lookahead_ms, .. } | Self::Expander { lookahead_ms, .. } => {
                ms_ticks(*lookahead_ms)
            }
            _ => 0,
        }
    }

    /// The track or bus this effect is keyed by, if any.
    #[must_use]
    pub const fn sidechain(&self) -> Option<&AudioNodeRef> {
        match self {
            Self::Compressor { sidechain, .. } | Self::Expander { sidechain, .. } => {
                sidechain.as_ref()
            }
            Self::Ducker { sidechain, .. } => Some(sidechain),
            Self::Eq { .. } | Self::Reverb { .. } | Self::Delay { .. } | Self::Matrix { .. } => {
                None
            }
        }
    }

    /// Calls `visit` with each parameter that animates, in the effect's field order, band by
    /// band for an equalizer.
    pub fn for_each_param<'a>(
        &'a self,
        visit: &mut dyn FnMut(AudioEffectParam<&'a Animated<f32>>),
    ) {
        effect_params!(self, visit, iter);
    }

    /// [`Self::for_each_param`], to change the values.
    pub fn for_each_param_mut<'a>(
        &'a mut self,
        visit: &mut dyn FnMut(AudioEffectParam<&'a mut Animated<f32>>),
    ) {
        effect_params!(self, visit, iter_mut);
    }

    pub(crate) fn is_valid(&self) -> bool {
        let mut params_valid = true;
        self.for_each_param(&mut |param| {
            params_valid &= valid_range(param.value, param.domain);
        });
        params_valid
            && match self {
                Self::Eq { bands } => !bands.is_empty() && bands.len() <= MAX_EQ_BANDS,
                Self::Compressor {
                    threshold_db: _,
                    ratio: _,
                    knee_db: _,
                    makeup_db: _,
                    attack_ms,
                    release_ms,
                    lookahead_ms,
                    detector: _,
                    detector_filter,
                    sidechain: _,
                } => {
                    positive_ms(*attack_ms)
                        && positive_ms(*release_ms)
                        && (0.0..=MAX_LOOKAHEAD_MS).contains(lookahead_ms)
                        && detector_filter.is_none_or(DetectorFilter::is_valid)
                }
                Self::Expander {
                    threshold_db: _,
                    ratio: _,
                    range_db: _,
                    attack_ms,
                    hold_ms,
                    release_ms,
                    lookahead_ms,
                    detector_filter,
                    sidechain: _,
                } => {
                    positive_ms(*attack_ms)
                        && (0.0..=MAX_HOLD_MS).contains(hold_ms)
                        && positive_ms(*release_ms)
                        && (0.0..=MAX_LOOKAHEAD_MS).contains(lookahead_ms)
                        && detector_filter.is_none_or(DetectorFilter::is_valid)
                }
                Self::Delay {
                    time_ms,
                    feedback: _,
                    mix: _,
                } => (1.0..=MAX_DELAY_MS).contains(time_ms),
                Self::Matrix { left: _, right: _ } => true,
                Self::Reverb {
                    room_size,
                    damping,
                    mix: _,
                } => unit(*room_size) && unit(*damping),
                Self::Ducker {
                    sidechain: _,
                    threshold: _,
                    depth_db: _,
                    attack_ms,
                    release_ms,
                } => positive_ms(*attack_ms) && positive_ms(*release_ms),
            }
    }
}

impl From<f32> for Animated<f32> {
    fn from(value: f32) -> Self {
        Self::Constant { value }
    }
}

/// Curve applied by a clip's fade in and fade out.
#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum FadeShape {
    /// Amplitude moves linearly. Two linear fades over one overlap dip by 6 dB.
    #[default]
    Linear,
    /// Amplitude follows a quarter sine. Two of these crossfade at constant power.
    EqualPower,
}

impl FadeShape {
    /// Maps linear fade progress in `0..=1` to an amplitude multiplier.
    #[must_use]
    pub fn amplitude(self, progress: f32) -> f32 {
        let progress = progress.clamp(0.0, 1.0);
        match self {
            Self::Linear => progress,
            Self::EqualPower => libm::sinf(progress * core::f32::consts::FRAC_PI_2),
        }
    }
}

/// Per-clip audio presentation controls.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct AudioProperties {
    /// Animated linear amplitude constrained to `0..=MAX_GAIN`.
    #[serde(default = "unit_gain")]
    pub gain: Animated<f32>,
    /// Animated stereo position from `-1` (left) to `1` (right).
    #[serde(default = "center_pan")]
    pub pan: Animated<f32>,
    /// Fade-in duration measured from the clip's timeline start. Non-negative.
    #[serde(default)]
    pub fade_in: MediaTime,
    /// Fade-out duration measured back from the clip's timeline end. Non-negative.
    #[serde(default)]
    pub fade_out: MediaTime,
    /// Curve of the fade in.
    #[serde(default)]
    pub fade_in_shape: FadeShape,
    /// Curve of the fade out.
    #[serde(default)]
    pub fade_out_shape: FadeShape,
    /// Silences this clip without removing it.
    #[serde(default)]
    pub muted: bool,
    /// Ordered effects applied before the track bus, at most [`MAX_CHAIN_EFFECTS`]. None takes
    /// a `sidechain`.
    #[serde(default)]
    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_CHAIN_EFFECTS }>")]
    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_CHAIN_EFFECTS)))]
    pub effects: Vec<AudioEffect>,
    /// Keeps the clip's pitch when its speed is not 1 by time-stretching instead of resampling.
    /// No effect at speed 1, on loops or on freezes.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub preserve_pitch: bool,
    /// Shifts the clip's pitch by this many cents (100 to a semitone, 1,200 to an octave) without
    /// changing its length, within [`MAX_PITCH_CENTS`] either way. With `preserve_pitch` the
    /// result sits this far from the source's pitch; without it, this far from the pitch the
    /// clip's speed gives. The shift time-stretches and then resamples, so formants move with
    /// the pitch: it suits speech and intervals of a few semitones, and sounds rougher on music
    /// and over wide intervals. No effect on loops or on freezes.
    #[serde(default, skip_serializing_if = "is_zero")]
    pub pitch_cents: f32,
    /// The source's audio stream the clip plays, counted from 0 over the file's audio streams in
    /// container order. Absent plays the stream the host picks by default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stream: Option<u32>,
    /// What each project channel plays of the stream's channels. Absent plays every channel,
    /// folded by speaker position.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub channel_map: Option<ChannelMap>,
}

/// Largest magnitude of a [`ChannelTerm`] gain.
pub const MAX_CHANNEL_GAIN: f32 = 16.0;

/// One channel of a stream and its weight in a row of a [`ChannelMap`].
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ChannelTerm {
    /// A channel of the stream, by index from 0, below [`alpha2_media::MAX_AUDIO_CHANNELS`].
    pub channel: u32,
    /// Its weight, at most [`MAX_CHANNEL_GAIN`] either way; negative inverts polarity.
    #[serde(default = "one")]
    pub gain: f32,
}

impl ChannelTerm {
    /// `channel` at unity.
    #[must_use]
    pub const fn new(channel: u32) -> Self {
        Self { channel, gain: 1.0 }
    }

    fn is_valid(self) -> bool {
        (self.channel as usize) < alpha2_media::MAX_AUDIO_CHANNELS
            && self.gain.is_finite()
            && self.gain.abs() <= MAX_CHANNEL_GAIN
    }
}

/// What the left and right channels play of a stream's channels: each a sum of weighted
/// channels, where terms naming one channel add. A mono project plays the average of the two
/// rows. At least one row has a term.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ChannelMap {
    /// What the left channel plays, at most [`alpha2_media::MAX_AUDIO_CHANNELS`] terms; empty is
    /// silence.
    #[serde(
        deserialize_with = "crate::bounded::seq::<_, _, { alpha2_media::MAX_AUDIO_CHANNELS }>"
    )]
    #[cfg_attr(
        feature = "schema",
        schemars(length(max = alpha2_media::MAX_AUDIO_CHANNELS))
    )]
    pub left: Vec<ChannelTerm>,
    /// What the right channel plays, at most [`alpha2_media::MAX_AUDIO_CHANNELS`] terms; empty
    /// is silence.
    #[serde(
        deserialize_with = "crate::bounded::seq::<_, _, { alpha2_media::MAX_AUDIO_CHANNELS }>"
    )]
    #[cfg_attr(
        feature = "schema",
        schemars(length(max = alpha2_media::MAX_AUDIO_CHANNELS))
    )]
    pub right: Vec<ChannelTerm>,
}

impl ChannelMap {
    /// One channel on both sides, as a mono source plays.
    #[must_use]
    pub fn mono(channel: u32) -> Self {
        Self::pair(channel, channel)
    }

    /// `left` on the left and `right` on the right, as a stereo pair plays.
    #[must_use]
    pub fn pair(left: u32, right: u32) -> Self {
        Self {
            left: vec![ChannelTerm::new(left)],
            right: vec![ChannelTerm::new(right)],
        }
    }

    fn is_valid(&self) -> bool {
        let rows = [&self.left, &self.right];
        rows.iter().any(|row| !row.is_empty())
            && rows.iter().all(|row| {
                row.len() <= alpha2_media::MAX_AUDIO_CHANNELS
                    && row.iter().all(|term| term.is_valid())
            })
    }
}

const fn one() -> f32 {
    1.0
}

#[expect(
    clippy::trivially_copy_pass_by_ref,
    reason = "serde passes the field by reference"
)]
fn is_zero(value: &f32) -> bool {
    *value == 0.0
}

impl Default for AudioProperties {
    fn default() -> Self {
        Self {
            gain: unit_gain(),
            pan: center_pan(),
            fade_in: MediaTime::ZERO,
            fade_out: MediaTime::ZERO,
            fade_in_shape: FadeShape::Linear,
            fade_out_shape: FadeShape::Linear,
            muted: false,
            effects: Vec::new(),
            preserve_pitch: false,
            pitch_cents: 0.0,
            stream: None,
            channel_map: None,
        }
    }
}

impl AudioProperties {
    /// Returns whether this clip can contribute signal at any timestamp.
    #[must_use]
    pub fn is_audible(&self) -> bool {
        !self.muted
            && match &self.gain {
                Animated::Constant { value } => *value > 0.0,
                Animated::Keyframes {
                    keyframes,
                    before,
                    after,
                } => {
                    [*before, *after].contains(&Extrapolation::Linear)
                        || keyframes.iter().any(|keyframe| keyframe.value > 0.0)
                        || keyframes
                            .windows(2)
                            .any(|pair| match pair[0].interpolation {
                                Interpolation::ValueBezier(curve) => {
                                    curve.range(pair[0].value, pair[1].value)[1] > 0.0
                                }
                                _ => false,
                            })
                }
                Animated::Split { .. } => false,
                Animated::Data(_) => true,
            }
    }

    pub(crate) fn validate(&self) -> bool {
        valid_gain(&self.gain)
            && valid_pan(&self.pan)
            && self.fade_in.ticks() >= 0
            && self.fade_out.ticks() >= 0
            && self.effects.len() <= MAX_CHAIN_EFFECTS
            && self
                .effects
                .iter()
                .all(|effect| effect.is_valid() && effect.sidechain().is_none())
            && self.channel_map.as_ref().is_none_or(ChannelMap::is_valid)
            && self.pitch_cents.abs() <= MAX_PITCH_CENTS
    }

    /// How a clip with these controls reads `source_range` over `timeline_range` under
    /// `time_map`.
    ///
    /// With `s` the clip's speed and `r` the ratio `pitch_cents` names, the pitch moves by `r`
    /// with `preserve_pitch` and by `s r` without it, and the read stretches by the speed over
    /// that. A stage whose factor is exactly 1 is left out: `r` is rational only at whole
    /// octaves, so only there can it cancel against a speed.
    ///
    /// A time curve has no one speed, so nothing cancels on it: it reads `Stretched` with
    /// `preserve_pitch`, `Resampled` without, and `PitchedAlong` for any `pitch_cents`.
    #[must_use]
    pub fn read(
        &self,
        time_map: &TimeMap,
        timeline_range: TimeRange,
        source_range: TimeRange,
    ) -> AudioRead {
        let ratio = || libm::exp2(f64::from(self.pitch_cents) / f64::from(CENTS_PER_OCTAVE));
        match time_map {
            TimeMap::Forward | TimeMap::Reverse => {}
            TimeMap::Curve { .. } if self.pitch_cents != 0.0 => {
                return AudioRead::PitchedAlong {
                    ratio: ratio(),
                    preserve: self.preserve_pitch,
                };
            }
            TimeMap::Curve { .. } if self.preserve_pitch => return AudioRead::Stretched,
            TimeMap::Curve { .. } | TimeMap::Loop { .. } | TimeMap::Freeze { .. } => {
                return AudioRead::Resampled;
            }
        }
        let ticks = |range: TimeRange| range.duration().map_or(0, MediaTime::ticks);
        let (timeline, source) = (ticks(timeline_range), ticks(source_range));
        if self.pitch_cents == 0.0 {
            return if self.preserve_pitch && timeline != source {
                AudioRead::Stretched
            } else {
                AudioRead::Resampled
            };
        }
        let speed_is_octaves = |octaves: i8| {
            let (timeline, source) = (i128::from(timeline), i128::from(source));
            source << octaves.min(0).unsigned_abs() == timeline << octaves.max(0).unsigned_abs()
        };
        #[expect(
            clippy::float_cmp,
            reason = "a whole number of octaves is an exact value"
        )]
        let octaves =
            (-2_i8..=2).find(|&octaves| self.pitch_cents == CENTS_PER_OCTAVE * f32::from(octaves));
        match octaves {
            Some(octaves) if self.preserve_pitch && speed_is_octaves(octaves) => {
                return AudioRead::Resampled;
            }
            Some(octaves) if !self.preserve_pitch && speed_is_octaves(-octaves) => {
                return AudioRead::Stretched;
            }
            _ => {}
        }
        #[expect(
            clippy::cast_precision_loss,
            reason = "a speed is a ratio of durations, not an exact count"
        )]
        let speed = if timeline > 0 && source > 0 {
            source as f64 / timeline as f64
        } else {
            1.0
        };
        let pitch = if self.preserve_pitch {
            ratio()
        } else {
            speed * ratio()
        };
        AudioRead::Pitched {
            stretch: speed / pitch,
            pitch,
        }
    }
}

/// How a clip's sound is read from its source.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AudioRead {
    /// Resampled at the clip's speed, so its pitch moves with the speed. Loops and freezes read
    /// this way.
    Resampled,
    /// Time-stretched to the clip's speed, at the source's pitch.
    Stretched,
    /// Time-stretched, then resampled.
    Pitched {
        /// Source time per unit of the stretched signal's time: the clip's speed over `pitch`.
        stretch: f64,
        /// The frequency ratio the resampling moves the stretched signal by.
        pitch: f64,
    },
    /// On a time curve: time-stretched along the curve, then resampled.
    PitchedAlong {
        /// The frequency ratio `pitch_cents` names.
        ratio: f64,
        /// Whether the pitch stays at the source's times `ratio` whatever the curve's speed;
        /// otherwise it also moves with the speed.
        preserve: bool,
    },
}

impl AudioRead {
    /// Whether the read holds a time stretch's state.
    #[must_use]
    pub const fn stretches(self) -> bool {
        !matches!(self, Self::Resampled)
    }
}

/// Per-track audio bus controls.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TrackAudio {
    /// Animated linear bus amplitude constrained to `0..=MAX_GAIN`.
    #[serde(default = "unit_gain")]
    pub gain: Animated<f32>,
    /// Animated stereo position applied after the clip mix, from `-1` (left) to `1` (right).
    #[serde(default = "center_pan")]
    pub pan: Animated<f32>,
    /// Silences this bus on its output, its sends and as a key.
    #[serde(default)]
    pub muted: bool,
    /// Restricts the mix to what flows through soloed tracks and buses when any sets this.
    #[serde(default)]
    pub solo: bool,
    /// Ordered effects applied to the summed clip signal, at most [`MAX_CHAIN_EFFECTS`].
    #[serde(default)]
    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_CHAIN_EFFECTS }>")]
    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_CHAIN_EFFECTS)))]
    pub effects: Vec<AudioEffect>,

    /// The bus this track outputs to; absent is the master.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output: Option<BusId>,
    /// Copies of this track's signal sent into buses, at most [`MAX_AUDIO_SENDS`].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_AUDIO_SENDS }>")]
    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_AUDIO_SENDS)))]
    pub sends: Vec<AudioSend>,
}

impl Default for TrackAudio {
    fn default() -> Self {
        Self {
            gain: unit_gain(),
            pan: center_pan(),
            muted: false,
            solo: false,
            effects: Vec::new(),
            output: None,
            sends: Vec::new(),
        }
    }
}

impl TrackAudio {
    pub(crate) fn validate(&self) -> bool {
        valid_gain(&self.gain)
            && valid_pan(&self.pan)
            && self.effects.len() <= MAX_CHAIN_EFFECTS
            && self.effects.iter().all(AudioEffect::is_valid)
            && self.sends.len() <= MAX_AUDIO_SENDS
    }
}

/// Where a send takes its copy of the signal.
#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum SendTap {
    /// After the fader and pan.
    #[default]
    PostFader,
    /// After the effects, before the fader and pan.
    PreFader,
}

/// A copy of a track's or bus's signal added into a bus.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct AudioSend {
    /// The bus that receives the copy.
    pub to: BusId,
    /// Animated linear amplitude of the copy, constrained to `0..=MAX_GAIN`.
    #[serde(default = "unit_gain")]
    pub gain: Animated<f32>,
    /// Where the copy is taken.
    #[serde(default)]
    pub tap: SendTap,
}

impl AudioSend {
    pub(crate) fn is_valid(&self) -> bool {
        valid_gain(&self.gain)
    }
}

/// A named bus: it sums what tracks and other buses route into it, runs its effects, and
/// outputs through its fader to another bus or the master.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct AudioBus {
    /// Stable identity, unique among the project's buses.
    pub id: BusId,
    /// Display name.
    #[serde(default)]
    pub name: String,
    /// Animated linear bus amplitude constrained to `0..=MAX_GAIN`.
    #[serde(default = "unit_gain")]
    pub gain: Animated<f32>,
    /// Animated stereo position applied after the effects, from `-1` (left) to `1` (right).
    #[serde(default = "center_pan")]
    pub pan: Animated<f32>,
    /// Silences this bus on its output, its sends and as a key.
    #[serde(default)]
    pub muted: bool,
    /// Restricts the mix to what flows through soloed tracks and buses when any sets this.
    #[serde(default)]
    pub solo: bool,
    /// Ordered effects applied to the summed input, at most [`MAX_CHAIN_EFFECTS`].
    #[serde(default)]
    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_CHAIN_EFFECTS }>")]
    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_CHAIN_EFFECTS)))]
    pub effects: Vec<AudioEffect>,
    /// The bus this one outputs to; absent is the master.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output: Option<BusId>,
    /// Copies of this bus's signal sent into other buses, at most [`MAX_AUDIO_SENDS`].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_AUDIO_SENDS }>")]
    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_AUDIO_SENDS)))]
    pub sends: Vec<AudioSend>,
}

impl AudioBus {
    /// A bus with unity gain, centre pan, no effects and its output on the master.
    #[must_use]
    pub fn new(id: BusId) -> Self {
        Self {
            id,
            name: String::new(),
            gain: unit_gain(),
            pan: center_pan(),
            muted: false,
            solo: false,
            effects: Vec::new(),
            output: None,
            sends: Vec::new(),
        }
    }

    pub(crate) fn validate(&self) -> bool {
        valid_gain(&self.gain)
            && valid_pan(&self.pan)
            && self.effects.len() <= MAX_CHAIN_EFFECTS
            && self.effects.iter().all(AudioEffect::is_valid)
            && self.sends.len() <= MAX_AUDIO_SENDS
    }
}

/// A track or a bus, named by its id.
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case", deny_unknown_fields)]
pub enum AudioNodeRef {
    /// A track.
    Track(TrackId),
    /// A bus.
    Bus(BusId),
}

impl core::fmt::Display for AudioNodeRef {
    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Track(track) => write!(formatter, "track {track}"),
            Self::Bus(bus) => write!(formatter, "bus {bus}"),
        }
    }
}

/// Project-wide master bus settings.
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct MasterAudio {
    /// Animated linear master amplitude constrained to `0..=MAX_GAIN`.
    #[serde(default = "unit_gain")]
    pub gain: Animated<f32>,
    /// Ordered effects applied to what is routed to the master, at most [`MAX_CHAIN_EFFECTS`].
    #[serde(default)]
    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_CHAIN_EFFECTS }>")]
    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_CHAIN_EFFECTS)))]
    pub effects: Vec<AudioEffect>,
    /// Final peak limiter. Omitted means [`Limiter::default`]; an explicit `null` leaves the mix
    /// unlimited.
    #[serde(default = "default_limiter")]
    pub limiter: Option<Limiter>,
    /// Buses that tracks and other buses route into before the master, at most
    /// [`MAX_AUDIO_BUSES`].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_AUDIO_BUSES }>")]
    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_AUDIO_BUSES)))]
    pub buses: Vec<AudioBus>,
}

impl Default for MasterAudio {
    fn default() -> Self {
        Self {
            gain: unit_gain(),
            effects: Vec::new(),
            limiter: default_limiter(),
            buses: Vec::new(),
        }
    }
}

impl MasterAudio {
    pub(crate) fn validate(&self) -> bool {
        valid_gain(&self.gain)
            && self.effects.len() <= MAX_CHAIN_EFFECTS
            && self.effects.iter().all(AudioEffect::is_valid)
            && self.limiter.is_none_or(Limiter::is_valid)
    }
}

/// Final peak limiter placed at the end of the master bus.
#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Limiter {
    /// Linear ceiling, positive and at most [`MAX_GAIN`]. One is full scale.
    pub threshold: f32,
    /// Release time in milliseconds, positive and at most [`MAX_ENVELOPE_MS`].
    pub release_ms: f32,
}

impl Default for Limiter {
    fn default() -> Self {
        Self {
            threshold: 1.0,
            release_ms: 50.0,
        }
    }
}

impl Limiter {
    fn is_valid(self) -> bool {
        self.threshold.is_finite()
            && self.threshold > 0.0
            && self.threshold <= MAX_GAIN
            && positive_ms(self.release_ms)
    }
}

/// Serde default: a project without a `limiter` field keeps the safety ceiling.
#[allow(clippy::unnecessary_wraps)]
fn default_limiter() -> Option<Limiter> {
    Some(Limiter::default())
}

fn zero() -> Animated<f32> {
    Animated::Constant { value: 0.0 }
}

fn full_range() -> Animated<f32> {
    Animated::Constant {
        value: MAX_EXPANDER_RANGE_DB,
    }
}

fn ms_ticks(milliseconds: f32) -> u64 {
    if milliseconds > 0.0 {
        // A 32-bit value times 120 is exact in 64 bits, so rounding it up is too.
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let ticks = (f64::from(milliseconds) * f64::from(TICKS_PER_MS)).ceil() as u64;
        ticks
    } else {
        0
    }
}

fn unit_gain() -> Animated<f32> {
    Animated::Constant { value: 1.0 }
}

fn center_pan() -> Animated<f32> {
    Animated::Constant { value: 0.0 }
}

fn unit(value: f32) -> bool {
    value.is_finite() && (0.0..=1.0).contains(&value)
}

fn positive_ms(value: f32) -> bool {
    value.is_finite() && value > 0.0 && value <= MAX_ENVELOPE_MS
}

fn valid_gain(gain: &Animated<f32>) -> bool {
    valid_range(gain, Domain::GAIN)
}

fn valid_pan(pan: &Animated<f32>) -> bool {
    valid_range(pan, Domain::PAN)
}

fn valid_range(animation: &Animated<f32>, domain: Domain) -> bool {
    let valid = |value: f32| domain.contains(value);
    match animation {
        Animated::Constant { value } => valid(*value),
        Animated::Keyframes {
            keyframes,
            before,
            after,
        } => {
            crate::animation::valid_keyframes(keyframes, *before, *after)
                && keyframes.iter().all(|keyframe| valid(keyframe.value))
        }
        Animated::Split { .. } => false,
        Animated::Data(_) => true,
    }
}