Skip to main content

alpha2_model/
audio.rs

1use crate::{Animated, BusId, Domain, Extrapolation, Interpolation, TimeMap, TrackId};
2use alpha2_time::{MediaTime, TICKS_PER_SECOND, TimeRange};
3use serde::{Deserialize, Serialize};
4
5pub(crate) const TICKS_PER_MS: u32 = 120;
6const _: () = assert!(TICKS_PER_SECOND == 1_000 * TICKS_PER_MS as i64);
7
8/// Largest linear amplitude accepted by any authored gain.
9pub const MAX_GAIN: f32 = 16.0;
10
11/// Most audio effects a project holds state for at once: the master's, the buses', the
12/// tracks', and those of clips holding state then (see [`AUDIO_EFFECT_STATE_MARGIN_MS`]). An
13/// equalizer is one effect regardless of bands.
14pub const MAX_AUDIO_EFFECTS: usize = 8_192;
15
16/// Most audio held in delay lines at once, in milliseconds, summed over the effects
17/// [`MAX_AUDIO_EFFECTS`] counts (a compressor's `lookahead_ms`, a reverb's
18/// [`REVERB_DELAY_MS`]) and the routing edges that wait for a longer path (see
19/// [`crate::Project::audio_effect_load`]). At the highest project rate this is under 100 MB of
20/// state.
21pub const MAX_AUDIO_DELAY_MS: u32 = 120_000;
22
23/// How long before its start, beyond its track's and its own compressor lookahead, a clip's
24/// effects count as holding state, in milliseconds. This covers one block of the largest size
25/// at the lowest project rate plus per-lookahead sample rounding. Effects count until the
26/// clip's end.
27pub const AUDIO_EFFECT_STATE_MARGIN_MS: u32 = 1_100;
28
29/// What one reverb counts toward [`MAX_AUDIO_DELAY_MS`]; its comb and allpass lines hold
30/// about 157 ms at any rate.
31pub const REVERB_DELAY_MS: u32 = 160;
32
33/// Largest peaking gain, in decibels either way, an EQ band renders.
34pub const MAX_EQ_GAIN_DB: f32 = 36.0;
35
36/// The resonances an EQ band renders.
37pub const EQ_Q_RANGE: std::ops::RangeInclusive<f32> = 0.05..=50.0;
38
39/// The frequencies an EQ band may name, in hertz: 10 Hz to just under the Nyquist frequency
40/// of the highest project rate. A band renders at most at 0.49 times the project's rate, so
41/// a higher band sounds at that limit.
42pub const EQ_FREQUENCY_RANGE_HZ: std::ops::RangeInclusive<f32> = 10.0..=47_040.0;
43
44/// Largest compressor ratio.
45pub const MAX_COMPRESSOR_RATIO: f32 = 100.0;
46
47/// Largest pitch shift of a clip either way, in cents: two octaves.
48pub const MAX_PITCH_CENTS: f32 = 2_400.0;
49
50const CENTS_PER_OCTAVE: f32 = 1_200.0;
51
52/// Most effects one chain holds: a clip's, a track's, a bus's, or the master's.
53pub const MAX_CHAIN_EFFECTS: usize = 16;
54
55/// Most buses a project holds.
56pub const MAX_AUDIO_BUSES: usize = 64;
57
58/// Most sends one track or bus holds.
59pub const MAX_AUDIO_SENDS: usize = 8;
60
61/// Most bands one equalizer holds.
62pub const MAX_EQ_BANDS: usize = 16;
63
64/// The quietest compressor or expander threshold or ducker depth, in decibels; each is at most
65/// 0 dB.
66pub const MIN_LEVEL_DB: f32 = -96.0;
67
68/// Longest compressor or expander lookahead, in milliseconds.
69pub const MAX_LOOKAHEAD_MS: f32 = 100.0;
70
71/// Widest compressor knee, in decibels.
72pub const MAX_KNEE_DB: f32 = 24.0;
73
74/// Largest compressor makeup gain, in decibels either way.
75pub const MAX_MAKEUP_DB: f32 = 24.0;
76
77/// Deepest expander attenuation, in decibels.
78pub const MAX_EXPANDER_RANGE_DB: f32 = 96.0;
79
80/// Longest expander hold, in milliseconds.
81pub const MAX_HOLD_MS: f32 = 10_000.0;
82
83/// Longest delay effect time, in milliseconds; the shortest is one.
84pub const MAX_DELAY_MS: f32 = 2_000.0;
85
86/// Most feedback a delay effect takes.
87pub const MAX_DELAY_FEEDBACK: f32 = 0.95;
88
89/// Largest magnitude of a matrix effect's gain.
90pub const MAX_MATRIX_GAIN: f32 = 4.0;
91
92/// Longest attack or release time, in milliseconds.
93pub const MAX_ENVELOPE_MS: f32 = 10_000.0;
94
95/// The filter shape of one equalizer band, by the Audio EQ Cookbook's second-order forms.
96#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
97#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
98#[serde(rename_all = "snake_case")]
99pub enum EqBandKind {
100    /// Bell-shaped parametric band.
101    Peaking,
102    /// Second-order low-pass.
103    LowPass,
104    /// Second-order high-pass.
105    HighPass,
106    /// Raises or lowers everything below the corner by `gain_db`, half of it at the corner.
107    LowShelf,
108    /// Raises or lowers everything above the corner by `gain_db`, half of it at the corner.
109    HighShelf,
110    /// Removes the centre frequency and passes the rest.
111    Notch,
112    /// Passes the centre frequency at unity and falls away on both sides.
113    BandPass,
114    /// Passes every frequency at unity and turns the phase through 180 degrees at the centre.
115    AllPass,
116}
117
118/// How a compressor measures the level it compresses by.
119#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
120#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
121#[serde(rename_all = "snake_case")]
122pub enum Detector {
123    /// The largest sample magnitude, smoothed by the attack and release.
124    #[default]
125    Peak,
126    /// The square root of the mean square, smoothed by the attack and release: a sine reads
127    /// 3 dB under its peak.
128    Rms,
129}
130
131/// One static filter before a compressor's or expander's level detector, so that only a band
132/// of the detected signal drives the gain. A compressor with a high-pass here is a de-esser.
133#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
134#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
135#[serde(deny_unknown_fields)]
136pub struct DetectorFilter {
137    /// Filter shape. A peaking or shelving shape has a gain of 0 dB.
138    pub kind: EqBandKind,
139    /// Centre or corner frequency in hertz, within [`EQ_FREQUENCY_RANGE_HZ`].
140    pub frequency_hz: f32,
141    /// Resonance, within [`EQ_Q_RANGE`].
142    pub q: f32,
143}
144
145impl DetectorFilter {
146    fn is_valid(self) -> bool {
147        Domain::EQ_FREQUENCY_HZ.contains(self.frequency_hz) && Domain::EQ_Q.contains(self.q)
148    }
149}
150
151/// A single equalizer section stored independently from its DSP implementation.
152#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
153#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
154#[serde(deny_unknown_fields)]
155pub struct EqBand {
156    /// Filter shape.
157    pub kind: EqBandKind,
158    /// Animated center or corner frequency in hertz, within [`EQ_FREQUENCY_RANGE_HZ`].
159    pub frequency_hz: Animated<f32>,
160    /// Animated resonance, within [`EQ_Q_RANGE`]. Larger values produce narrower bands.
161    pub q: Animated<f32>,
162    /// Animated gain of a peaking or shelving band in decibels, at most [`MAX_EQ_GAIN_DB`]
163    /// either way. Ignored by the other shapes.
164    #[serde(default = "zero")]
165    pub gain_db: Animated<f32>,
166}
167
168/// One parameter of an audio effect that animates.
169#[derive(Clone, Copy, Debug)]
170pub struct AudioEffectParam<V> {
171    /// The equalizer band that holds it, for a band's parameter.
172    pub band: Option<usize>,
173    /// Its field name.
174    pub name: &'static str,
175    /// Its place in the JSON schema, as `Type.field` or `Type[tag].field`.
176    pub place: &'static str,
177    /// The values it takes. A constant or a keyframe outside is refused; an interpolated or
178    /// bound value is clamped.
179    pub domain: Domain,
180    /// The value.
181    pub value: V,
182}
183
184impl<V> AudioEffectParam<V> {
185    /// Its path below the effect: `threshold_db`, `bands[1].gain_db`.
186    #[must_use]
187    pub fn path(&self) -> String {
188        match self.band {
189            Some(band) => format!("bands[{band}].{}", self.name),
190            None => self.name.to_owned(),
191        }
192    }
193}
194
195macro_rules! effect_params {
196    ($effect:expr, $visit:expr, $bands:ident) => {{
197        let mut visit = |band, name, place, domain, value| {
198            $visit(AudioEffectParam {
199                band,
200                name,
201                place,
202                domain,
203                value,
204            });
205        };
206        match $effect {
207            AudioEffect::Eq { bands } => {
208                for (index, band) in bands.$bands().enumerate() {
209                    let at = Some(index);
210                    let EqBand {
211                        kind: _,
212                        frequency_hz,
213                        q,
214                        gain_db,
215                    } = band;
216                    visit(
217                        at,
218                        "frequency_hz",
219                        "EqBand.frequency_hz",
220                        Domain::EQ_FREQUENCY_HZ,
221                        frequency_hz,
222                    );
223                    visit(at, "q", "EqBand.q", Domain::EQ_Q, q);
224                    visit(at, "gain_db", "EqBand.gain_db", Domain::EQ_GAIN_DB, gain_db);
225                }
226            }
227            AudioEffect::Compressor {
228                threshold_db,
229                ratio,
230                knee_db,
231                makeup_db,
232                attack_ms: _,
233                release_ms: _,
234                lookahead_ms: _,
235                detector: _,
236                detector_filter: _,
237                sidechain: _,
238            } => {
239                visit(
240                    None,
241                    "threshold_db",
242                    "AudioEffect[compressor].threshold_db",
243                    Domain::LEVEL_DB,
244                    threshold_db,
245                );
246                visit(
247                    None,
248                    "ratio",
249                    "AudioEffect[compressor].ratio",
250                    Domain::COMPRESSOR_RATIO,
251                    ratio,
252                );
253                visit(
254                    None,
255                    "knee_db",
256                    "AudioEffect[compressor].knee_db",
257                    Domain::KNEE_DB,
258                    knee_db,
259                );
260                visit(
261                    None,
262                    "makeup_db",
263                    "AudioEffect[compressor].makeup_db",
264                    Domain::MAKEUP_DB,
265                    makeup_db,
266                );
267            }
268            AudioEffect::Expander {
269                threshold_db,
270                ratio,
271                range_db,
272                attack_ms: _,
273                hold_ms: _,
274                release_ms: _,
275                lookahead_ms: _,
276                detector_filter: _,
277                sidechain: _,
278            } => {
279                visit(
280                    None,
281                    "threshold_db",
282                    "AudioEffect[expander].threshold_db",
283                    Domain::LEVEL_DB,
284                    threshold_db,
285                );
286                visit(
287                    None,
288                    "ratio",
289                    "AudioEffect[expander].ratio",
290                    Domain::COMPRESSOR_RATIO,
291                    ratio,
292                );
293                visit(
294                    None,
295                    "range_db",
296                    "AudioEffect[expander].range_db",
297                    Domain::EXPANDER_RANGE_DB,
298                    range_db,
299                );
300            }
301            AudioEffect::Delay {
302                time_ms: _,
303                feedback,
304                mix,
305            } => {
306                visit(
307                    None,
308                    "feedback",
309                    "AudioEffect[delay].feedback",
310                    Domain::DELAY_FEEDBACK,
311                    feedback,
312                );
313                visit(None, "mix", "AudioEffect[delay].mix", Domain::UNIT, mix);
314            }
315            AudioEffect::Matrix { left, right } => {
316                let [from_left, from_right] = left;
317                visit(
318                    None,
319                    "left[0]",
320                    "AudioEffect[matrix].left",
321                    Domain::MATRIX_GAIN,
322                    from_left,
323                );
324                visit(
325                    None,
326                    "left[1]",
327                    "AudioEffect[matrix].left",
328                    Domain::MATRIX_GAIN,
329                    from_right,
330                );
331                let [from_left, from_right] = right;
332                visit(
333                    None,
334                    "right[0]",
335                    "AudioEffect[matrix].right",
336                    Domain::MATRIX_GAIN,
337                    from_left,
338                );
339                visit(
340                    None,
341                    "right[1]",
342                    "AudioEffect[matrix].right",
343                    Domain::MATRIX_GAIN,
344                    from_right,
345                );
346            }
347            AudioEffect::Ducker {
348                sidechain: _,
349                threshold,
350                depth_db,
351                attack_ms: _,
352                release_ms: _,
353            } => {
354                visit(
355                    None,
356                    "threshold",
357                    "AudioEffect[ducker].threshold",
358                    Domain::POSITIVE,
359                    threshold,
360                );
361                visit(
362                    None,
363                    "depth_db",
364                    "AudioEffect[ducker].depth_db",
365                    Domain::LEVEL_DB,
366                    depth_db,
367                );
368            }
369            AudioEffect::Reverb {
370                room_size: _,
371                damping: _,
372                mix,
373            } => visit(None, "mix", "AudioEffect[reverb].mix", Domain::UNIT, mix),
374        }
375    }};
376}
377
378/// A serializable audio effect applied to a clip, a track, a bus or the master.
379///
380/// An effect with a `sidechain` follows the level of that track or bus instead of its own
381/// input: its signal after its effects and before its fader and pan. A clip's effects take
382/// none.
383///
384/// A parameter documented as animated is keyed in timeline time and evaluated at every 32nd
385/// sample of the effect's own input, counted from timeline zero; the effect moves in a straight
386/// line between two such points. A constant parameter keeps its exact value.
387#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
388#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
389#[serde(deny_unknown_fields)]
390#[serde(tag = "type", rename_all = "snake_case")]
391pub enum AudioEffect {
392    /// Cascaded biquad sections.
393    Eq {
394        /// Ordered filter sections, 1 to [`MAX_EQ_BANDS`] of them.
395        #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_EQ_BANDS }>")]
396        #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_EQ_BANDS)))]
397        bands: Vec<EqBand>,
398    },
399    /// Lookahead dynamic range compression with linked channels.
400    ///
401    /// With the level `x`, the threshold `T`, the ratio `R` and the knee `W` in decibels, the
402    /// gain is 0 dB while `2 (x - T) < -W`, `(1/R - 1) (x - T + W/2)^2 / (2 W)` while
403    /// `2 |x - T| <= W`, and `T + (x - T) / R - x` above; the makeup gain is added to it.
404    Compressor {
405        /// Animated level above which gain reduction begins, in decibels from [`MIN_LEVEL_DB`]
406        /// to 0.
407        threshold_db: Animated<f32>,
408        /// Animated downward ratio, from one (unity) to [`MAX_COMPRESSOR_RATIO`].
409        ratio: Animated<f32>,
410        /// Animated width of the knee centred on the threshold, in decibels from 0 (a hard
411        /// knee) to [`MAX_KNEE_DB`].
412        #[serde(default = "zero")]
413        knee_db: Animated<f32>,
414        /// Animated gain applied after the reduction, in decibels, at most [`MAX_MAKEUP_DB`]
415        /// either way.
416        #[serde(default = "zero")]
417        makeup_db: Animated<f32>,
418        /// Attack time in milliseconds, positive and at most [`MAX_ENVELOPE_MS`].
419        attack_ms: f32,
420        /// Release time in milliseconds, positive and at most [`MAX_ENVELOPE_MS`].
421        release_ms: f32,
422        /// Lookahead in milliseconds, at most [`MAX_LOOKAHEAD_MS`]. Reported as graph latency.
423        #[serde(default)]
424        lookahead_ms: f32,
425        /// How the level is measured.
426        #[serde(default)]
427        detector: Detector,
428        /// A filter before the detector.
429        #[serde(default, skip_serializing_if = "Option::is_none")]
430        detector_filter: Option<DetectorFilter>,
431        /// The track or bus whose level drives the reduction; absent, the effect's own input.
432        #[serde(default, skip_serializing_if = "Option::is_none")]
433        sidechain: Option<AudioNodeRef>,
434    },
435    /// Downward expansion with linked channels; with a high ratio, a gate.
436    ///
437    /// The level is a peak follower with the attack and release times. Under the threshold
438    /// `T` a level `x` in decibels asks for `min((T - x) (R - 1), range_db)` decibels of
439    /// attenuation. The gain opens with the attack time; before it closes it holds for
440    /// `hold_ms`, then closes with the release time.
441    Expander {
442        /// Animated level below which attenuation begins, in decibels from [`MIN_LEVEL_DB`]
443        /// to 0.
444        threshold_db: Animated<f32>,
445        /// Animated ratio, from one (unity) to [`MAX_COMPRESSOR_RATIO`]: under the threshold
446        /// the output falls this many decibels for each decibel the level falls.
447        ratio: Animated<f32>,
448        /// Animated limit of the attenuation, in decibels from 0 to
449        /// [`MAX_EXPANDER_RANGE_DB`], which is the default.
450        #[serde(default = "full_range")]
451        range_db: Animated<f32>,
452        /// Attack time in milliseconds, positive and at most [`MAX_ENVELOPE_MS`].
453        attack_ms: f32,
454        /// Hold time in milliseconds, at most [`MAX_HOLD_MS`].
455        #[serde(default)]
456        hold_ms: f32,
457        /// Release time in milliseconds, positive and at most [`MAX_ENVELOPE_MS`].
458        release_ms: f32,
459        /// Lookahead in milliseconds, at most [`MAX_LOOKAHEAD_MS`]. Reported as graph latency.
460        #[serde(default)]
461        lookahead_ms: f32,
462        /// A filter before the detector.
463        #[serde(default, skip_serializing_if = "Option::is_none")]
464        detector_filter: Option<DetectorFilter>,
465        /// The track or bus whose level drives the gain; absent, the effect's own input.
466        #[serde(default, skip_serializing_if = "Option::is_none")]
467        sidechain: Option<AudioNodeRef>,
468    },
469    /// A feedback delay line: each channel repeats after `time_ms`. With the sample `x` and
470    /// the line's oldest sample `d`, the line takes `x + feedback * d` and the output is
471    /// `x * (1 - mix) + d * mix`. It adds no latency.
472    Delay {
473        /// Delay time in milliseconds, from 1 to [`MAX_DELAY_MS`].
474        time_ms: f32,
475        /// Animated share of the delayed signal fed back into the line, from 0 to
476        /// [`MAX_DELAY_FEEDBACK`].
477        feedback: Animated<f32>,
478        /// Animated wet mix, in `0..=1`.
479        mix: Animated<f32>,
480    },
481    /// A two-by-two gain matrix over the stereo pair: the left output is
482    /// `left[0] * L + left[1] * R` and the right `right[0] * L + right[1] * R`. Width, swap,
483    /// mono, polarity and balance are settings of it. A mono mix takes
484    /// `((left[0] + left[1]) + (right[0] + right[1])) / 2` times the sample.
485    Matrix {
486        /// The animated gains the left output takes from left and right, each at most
487        /// [`MAX_MATRIX_GAIN`] either way.
488        left: [Animated<f32>; 2],
489        /// The animated gains the right output takes from left and right, each at most
490        /// [`MAX_MATRIX_GAIN`] either way.
491        right: [Animated<f32>; 2],
492    },
493    /// Lowers the signal while its key sounds.
494    Ducker {
495        /// The track or bus whose level drives the attenuation.
496        sidechain: AudioNodeRef,
497        /// Animated linear key level above which attenuation begins. Positive.
498        threshold: Animated<f32>,
499        /// Animated maximum attenuation in decibels, from [`MIN_LEVEL_DB`] to 0.
500        depth_db: Animated<f32>,
501        /// Attack time in milliseconds, positive and at most [`MAX_ENVELOPE_MS`].
502        attack_ms: f32,
503        /// Release time in milliseconds, positive and at most [`MAX_ENVELOPE_MS`].
504        release_ms: f32,
505    },
506    /// Schroeder reverberation.
507    Reverb {
508        /// Room size, in `0..=1`.
509        room_size: f32,
510        /// High-frequency damping, in `0..=1`.
511        damping: f32,
512        /// Animated wet mix, in `0..=1`.
513        mix: Animated<f32>,
514    },
515}
516
517impl AudioEffect {
518    /// What this effect counts toward [`MAX_AUDIO_DELAY_MS`], in ticks (120 per millisecond),
519    /// rounded up. Tick counts are exact, so a project's effects sum the same in any order.
520    #[must_use]
521    pub fn delay_ticks(&self) -> u64 {
522        match self {
523            Self::Eq { .. } | Self::Ducker { .. } | Self::Matrix { .. } => 0,
524            Self::Compressor { .. } | Self::Expander { .. } => self.lookahead_ticks(),
525            Self::Delay { time_ms, .. } => ms_ticks(*time_ms),
526            Self::Reverb { .. } => u64::from(REVERB_DELAY_MS) * u64::from(TICKS_PER_MS),
527        }
528    }
529
530    /// How early a mixer reads this effect's input, in ticks, rounded up: a compressor's or
531    /// expander's `lookahead_ms`.
532    #[must_use]
533    pub fn lookahead_ticks(&self) -> u64 {
534        match self {
535            Self::Compressor { lookahead_ms, .. } | Self::Expander { lookahead_ms, .. } => {
536                ms_ticks(*lookahead_ms)
537            }
538            _ => 0,
539        }
540    }
541
542    /// The track or bus this effect is keyed by, if any.
543    #[must_use]
544    pub const fn sidechain(&self) -> Option<&AudioNodeRef> {
545        match self {
546            Self::Compressor { sidechain, .. } | Self::Expander { sidechain, .. } => {
547                sidechain.as_ref()
548            }
549            Self::Ducker { sidechain, .. } => Some(sidechain),
550            Self::Eq { .. } | Self::Reverb { .. } | Self::Delay { .. } | Self::Matrix { .. } => {
551                None
552            }
553        }
554    }
555
556    /// Calls `visit` with each parameter that animates, in the effect's field order, band by
557    /// band for an equalizer.
558    pub fn for_each_param<'a>(
559        &'a self,
560        visit: &mut dyn FnMut(AudioEffectParam<&'a Animated<f32>>),
561    ) {
562        effect_params!(self, visit, iter);
563    }
564
565    /// [`Self::for_each_param`], to change the values.
566    pub fn for_each_param_mut<'a>(
567        &'a mut self,
568        visit: &mut dyn FnMut(AudioEffectParam<&'a mut Animated<f32>>),
569    ) {
570        effect_params!(self, visit, iter_mut);
571    }
572
573    pub(crate) fn is_valid(&self) -> bool {
574        let mut params_valid = true;
575        self.for_each_param(&mut |param| {
576            params_valid &= valid_range(param.value, param.domain);
577        });
578        params_valid
579            && match self {
580                Self::Eq { bands } => !bands.is_empty() && bands.len() <= MAX_EQ_BANDS,
581                Self::Compressor {
582                    threshold_db: _,
583                    ratio: _,
584                    knee_db: _,
585                    makeup_db: _,
586                    attack_ms,
587                    release_ms,
588                    lookahead_ms,
589                    detector: _,
590                    detector_filter,
591                    sidechain: _,
592                } => {
593                    positive_ms(*attack_ms)
594                        && positive_ms(*release_ms)
595                        && (0.0..=MAX_LOOKAHEAD_MS).contains(lookahead_ms)
596                        && detector_filter.is_none_or(DetectorFilter::is_valid)
597                }
598                Self::Expander {
599                    threshold_db: _,
600                    ratio: _,
601                    range_db: _,
602                    attack_ms,
603                    hold_ms,
604                    release_ms,
605                    lookahead_ms,
606                    detector_filter,
607                    sidechain: _,
608                } => {
609                    positive_ms(*attack_ms)
610                        && (0.0..=MAX_HOLD_MS).contains(hold_ms)
611                        && positive_ms(*release_ms)
612                        && (0.0..=MAX_LOOKAHEAD_MS).contains(lookahead_ms)
613                        && detector_filter.is_none_or(DetectorFilter::is_valid)
614                }
615                Self::Delay {
616                    time_ms,
617                    feedback: _,
618                    mix: _,
619                } => (1.0..=MAX_DELAY_MS).contains(time_ms),
620                Self::Matrix { left: _, right: _ } => true,
621                Self::Reverb {
622                    room_size,
623                    damping,
624                    mix: _,
625                } => unit(*room_size) && unit(*damping),
626                Self::Ducker {
627                    sidechain: _,
628                    threshold: _,
629                    depth_db: _,
630                    attack_ms,
631                    release_ms,
632                } => positive_ms(*attack_ms) && positive_ms(*release_ms),
633            }
634    }
635}
636
637impl From<f32> for Animated<f32> {
638    fn from(value: f32) -> Self {
639        Self::Constant { value }
640    }
641}
642
643/// Curve applied by a clip's fade in and fade out.
644#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
645#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
646#[serde(rename_all = "snake_case")]
647pub enum FadeShape {
648    /// Amplitude moves linearly. Two linear fades over one overlap dip by 6 dB.
649    #[default]
650    Linear,
651    /// Amplitude follows a quarter sine. Two of these crossfade at constant power.
652    EqualPower,
653}
654
655impl FadeShape {
656    /// Maps linear fade progress in `0..=1` to an amplitude multiplier.
657    #[must_use]
658    pub fn amplitude(self, progress: f32) -> f32 {
659        let progress = progress.clamp(0.0, 1.0);
660        match self {
661            Self::Linear => progress,
662            Self::EqualPower => libm::sinf(progress * core::f32::consts::FRAC_PI_2),
663        }
664    }
665}
666
667/// Per-clip audio presentation controls.
668#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
669#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
670#[serde(deny_unknown_fields)]
671pub struct AudioProperties {
672    /// Animated linear amplitude constrained to `0..=MAX_GAIN`.
673    #[serde(default = "unit_gain")]
674    pub gain: Animated<f32>,
675    /// Animated stereo position from `-1` (left) to `1` (right).
676    #[serde(default = "center_pan")]
677    pub pan: Animated<f32>,
678    /// Fade-in duration measured from the clip's timeline start. Non-negative.
679    #[serde(default)]
680    pub fade_in: MediaTime,
681    /// Fade-out duration measured back from the clip's timeline end. Non-negative.
682    #[serde(default)]
683    pub fade_out: MediaTime,
684    /// Curve of the fade in.
685    #[serde(default)]
686    pub fade_in_shape: FadeShape,
687    /// Curve of the fade out.
688    #[serde(default)]
689    pub fade_out_shape: FadeShape,
690    /// Silences this clip without removing it.
691    #[serde(default)]
692    pub muted: bool,
693    /// Ordered effects applied before the track bus, at most [`MAX_CHAIN_EFFECTS`]. None takes
694    /// a `sidechain`.
695    #[serde(default)]
696    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_CHAIN_EFFECTS }>")]
697    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_CHAIN_EFFECTS)))]
698    pub effects: Vec<AudioEffect>,
699    /// Keeps the clip's pitch when its speed is not 1 by time-stretching instead of resampling.
700    /// No effect at speed 1, on loops or on freezes.
701    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
702    pub preserve_pitch: bool,
703    /// Shifts the clip's pitch by this many cents (100 to a semitone, 1,200 to an octave) without
704    /// changing its length, within [`MAX_PITCH_CENTS`] either way. With `preserve_pitch` the
705    /// result sits this far from the source's pitch; without it, this far from the pitch the
706    /// clip's speed gives. The shift time-stretches and then resamples, so formants move with
707    /// the pitch: it suits speech and intervals of a few semitones, and sounds rougher on music
708    /// and over wide intervals. No effect on loops or on freezes.
709    #[serde(default, skip_serializing_if = "is_zero")]
710    pub pitch_cents: f32,
711    /// The source's audio stream the clip plays, counted from 0 over the file's audio streams in
712    /// container order. Absent plays the stream the host picks by default.
713    #[serde(default, skip_serializing_if = "Option::is_none")]
714    pub stream: Option<u32>,
715    /// What each project channel plays of the stream's channels. Absent plays every channel,
716    /// folded by speaker position.
717    #[serde(default, skip_serializing_if = "Option::is_none")]
718    pub channel_map: Option<ChannelMap>,
719}
720
721/// Largest magnitude of a [`ChannelTerm`] gain.
722pub const MAX_CHANNEL_GAIN: f32 = 16.0;
723
724/// One channel of a stream and its weight in a row of a [`ChannelMap`].
725#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
726#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
727#[serde(deny_unknown_fields)]
728pub struct ChannelTerm {
729    /// A channel of the stream, by index from 0, below [`alpha2_media::MAX_AUDIO_CHANNELS`].
730    pub channel: u32,
731    /// Its weight, at most [`MAX_CHANNEL_GAIN`] either way; negative inverts polarity.
732    #[serde(default = "one")]
733    pub gain: f32,
734}
735
736impl ChannelTerm {
737    /// `channel` at unity.
738    #[must_use]
739    pub const fn new(channel: u32) -> Self {
740        Self { channel, gain: 1.0 }
741    }
742
743    fn is_valid(self) -> bool {
744        (self.channel as usize) < alpha2_media::MAX_AUDIO_CHANNELS
745            && self.gain.is_finite()
746            && self.gain.abs() <= MAX_CHANNEL_GAIN
747    }
748}
749
750/// What the left and right channels play of a stream's channels: each a sum of weighted
751/// channels, where terms naming one channel add. A mono project plays the average of the two
752/// rows. At least one row has a term.
753#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
754#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
755#[serde(deny_unknown_fields)]
756pub struct ChannelMap {
757    /// What the left channel plays, at most [`alpha2_media::MAX_AUDIO_CHANNELS`] terms; empty is
758    /// silence.
759    #[serde(
760        deserialize_with = "crate::bounded::seq::<_, _, { alpha2_media::MAX_AUDIO_CHANNELS }>"
761    )]
762    #[cfg_attr(
763        feature = "schema",
764        schemars(length(max = alpha2_media::MAX_AUDIO_CHANNELS))
765    )]
766    pub left: Vec<ChannelTerm>,
767    /// What the right channel plays, at most [`alpha2_media::MAX_AUDIO_CHANNELS`] terms; empty
768    /// is silence.
769    #[serde(
770        deserialize_with = "crate::bounded::seq::<_, _, { alpha2_media::MAX_AUDIO_CHANNELS }>"
771    )]
772    #[cfg_attr(
773        feature = "schema",
774        schemars(length(max = alpha2_media::MAX_AUDIO_CHANNELS))
775    )]
776    pub right: Vec<ChannelTerm>,
777}
778
779impl ChannelMap {
780    /// One channel on both sides, as a mono source plays.
781    #[must_use]
782    pub fn mono(channel: u32) -> Self {
783        Self::pair(channel, channel)
784    }
785
786    /// `left` on the left and `right` on the right, as a stereo pair plays.
787    #[must_use]
788    pub fn pair(left: u32, right: u32) -> Self {
789        Self {
790            left: vec![ChannelTerm::new(left)],
791            right: vec![ChannelTerm::new(right)],
792        }
793    }
794
795    fn is_valid(&self) -> bool {
796        let rows = [&self.left, &self.right];
797        rows.iter().any(|row| !row.is_empty())
798            && rows.iter().all(|row| {
799                row.len() <= alpha2_media::MAX_AUDIO_CHANNELS
800                    && row.iter().all(|term| term.is_valid())
801            })
802    }
803}
804
805const fn one() -> f32 {
806    1.0
807}
808
809#[expect(
810    clippy::trivially_copy_pass_by_ref,
811    reason = "serde passes the field by reference"
812)]
813fn is_zero(value: &f32) -> bool {
814    *value == 0.0
815}
816
817impl Default for AudioProperties {
818    fn default() -> Self {
819        Self {
820            gain: unit_gain(),
821            pan: center_pan(),
822            fade_in: MediaTime::ZERO,
823            fade_out: MediaTime::ZERO,
824            fade_in_shape: FadeShape::Linear,
825            fade_out_shape: FadeShape::Linear,
826            muted: false,
827            effects: Vec::new(),
828            preserve_pitch: false,
829            pitch_cents: 0.0,
830            stream: None,
831            channel_map: None,
832        }
833    }
834}
835
836impl AudioProperties {
837    /// Returns whether this clip can contribute signal at any timestamp.
838    #[must_use]
839    pub fn is_audible(&self) -> bool {
840        !self.muted
841            && match &self.gain {
842                Animated::Constant { value } => *value > 0.0,
843                Animated::Keyframes {
844                    keyframes,
845                    before,
846                    after,
847                } => {
848                    [*before, *after].contains(&Extrapolation::Linear)
849                        || keyframes.iter().any(|keyframe| keyframe.value > 0.0)
850                        || keyframes
851                            .windows(2)
852                            .any(|pair| match pair[0].interpolation {
853                                Interpolation::ValueBezier(curve) => {
854                                    curve.range(pair[0].value, pair[1].value)[1] > 0.0
855                                }
856                                _ => false,
857                            })
858                }
859                Animated::Split { .. } => false,
860                Animated::Data(_) => true,
861            }
862    }
863
864    pub(crate) fn validate(&self) -> bool {
865        valid_gain(&self.gain)
866            && valid_pan(&self.pan)
867            && self.fade_in.ticks() >= 0
868            && self.fade_out.ticks() >= 0
869            && self.effects.len() <= MAX_CHAIN_EFFECTS
870            && self
871                .effects
872                .iter()
873                .all(|effect| effect.is_valid() && effect.sidechain().is_none())
874            && self.channel_map.as_ref().is_none_or(ChannelMap::is_valid)
875            && self.pitch_cents.abs() <= MAX_PITCH_CENTS
876    }
877
878    /// How a clip with these controls reads `source_range` over `timeline_range` under
879    /// `time_map`.
880    ///
881    /// With `s` the clip's speed and `r` the ratio `pitch_cents` names, the pitch moves by `r`
882    /// with `preserve_pitch` and by `s r` without it, and the read stretches by the speed over
883    /// that. A stage whose factor is exactly 1 is left out: `r` is rational only at whole
884    /// octaves, so only there can it cancel against a speed.
885    ///
886    /// A time curve has no one speed, so nothing cancels on it: it reads `Stretched` with
887    /// `preserve_pitch`, `Resampled` without, and `PitchedAlong` for any `pitch_cents`.
888    #[must_use]
889    pub fn read(
890        &self,
891        time_map: &TimeMap,
892        timeline_range: TimeRange,
893        source_range: TimeRange,
894    ) -> AudioRead {
895        let ratio = || libm::exp2(f64::from(self.pitch_cents) / f64::from(CENTS_PER_OCTAVE));
896        match time_map {
897            TimeMap::Forward | TimeMap::Reverse => {}
898            TimeMap::Curve { .. } if self.pitch_cents != 0.0 => {
899                return AudioRead::PitchedAlong {
900                    ratio: ratio(),
901                    preserve: self.preserve_pitch,
902                };
903            }
904            TimeMap::Curve { .. } if self.preserve_pitch => return AudioRead::Stretched,
905            TimeMap::Curve { .. } | TimeMap::Loop { .. } | TimeMap::Freeze { .. } => {
906                return AudioRead::Resampled;
907            }
908        }
909        let ticks = |range: TimeRange| range.duration().map_or(0, MediaTime::ticks);
910        let (timeline, source) = (ticks(timeline_range), ticks(source_range));
911        if self.pitch_cents == 0.0 {
912            return if self.preserve_pitch && timeline != source {
913                AudioRead::Stretched
914            } else {
915                AudioRead::Resampled
916            };
917        }
918        let speed_is_octaves = |octaves: i8| {
919            let (timeline, source) = (i128::from(timeline), i128::from(source));
920            source << octaves.min(0).unsigned_abs() == timeline << octaves.max(0).unsigned_abs()
921        };
922        #[expect(
923            clippy::float_cmp,
924            reason = "a whole number of octaves is an exact value"
925        )]
926        let octaves =
927            (-2_i8..=2).find(|&octaves| self.pitch_cents == CENTS_PER_OCTAVE * f32::from(octaves));
928        match octaves {
929            Some(octaves) if self.preserve_pitch && speed_is_octaves(octaves) => {
930                return AudioRead::Resampled;
931            }
932            Some(octaves) if !self.preserve_pitch && speed_is_octaves(-octaves) => {
933                return AudioRead::Stretched;
934            }
935            _ => {}
936        }
937        #[expect(
938            clippy::cast_precision_loss,
939            reason = "a speed is a ratio of durations, not an exact count"
940        )]
941        let speed = if timeline > 0 && source > 0 {
942            source as f64 / timeline as f64
943        } else {
944            1.0
945        };
946        let pitch = if self.preserve_pitch {
947            ratio()
948        } else {
949            speed * ratio()
950        };
951        AudioRead::Pitched {
952            stretch: speed / pitch,
953            pitch,
954        }
955    }
956}
957
958/// How a clip's sound is read from its source.
959#[derive(Clone, Copy, Debug, PartialEq)]
960pub enum AudioRead {
961    /// Resampled at the clip's speed, so its pitch moves with the speed. Loops and freezes read
962    /// this way.
963    Resampled,
964    /// Time-stretched to the clip's speed, at the source's pitch.
965    Stretched,
966    /// Time-stretched, then resampled.
967    Pitched {
968        /// Source time per unit of the stretched signal's time: the clip's speed over `pitch`.
969        stretch: f64,
970        /// The frequency ratio the resampling moves the stretched signal by.
971        pitch: f64,
972    },
973    /// On a time curve: time-stretched along the curve, then resampled.
974    PitchedAlong {
975        /// The frequency ratio `pitch_cents` names.
976        ratio: f64,
977        /// Whether the pitch stays at the source's times `ratio` whatever the curve's speed;
978        /// otherwise it also moves with the speed.
979        preserve: bool,
980    },
981}
982
983impl AudioRead {
984    /// Whether the read holds a time stretch's state.
985    #[must_use]
986    pub const fn stretches(self) -> bool {
987        !matches!(self, Self::Resampled)
988    }
989}
990
991/// Per-track audio bus controls.
992#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
993#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
994#[serde(deny_unknown_fields)]
995pub struct TrackAudio {
996    /// Animated linear bus amplitude constrained to `0..=MAX_GAIN`.
997    #[serde(default = "unit_gain")]
998    pub gain: Animated<f32>,
999    /// Animated stereo position applied after the clip mix, from `-1` (left) to `1` (right).
1000    #[serde(default = "center_pan")]
1001    pub pan: Animated<f32>,
1002    /// Silences this bus on its output, its sends and as a key.
1003    #[serde(default)]
1004    pub muted: bool,
1005    /// Restricts the mix to what flows through soloed tracks and buses when any sets this.
1006    #[serde(default)]
1007    pub solo: bool,
1008    /// Ordered effects applied to the summed clip signal, at most [`MAX_CHAIN_EFFECTS`].
1009    #[serde(default)]
1010    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_CHAIN_EFFECTS }>")]
1011    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_CHAIN_EFFECTS)))]
1012    pub effects: Vec<AudioEffect>,
1013
1014    /// The bus this track outputs to; absent is the master.
1015    #[serde(default, skip_serializing_if = "Option::is_none")]
1016    pub output: Option<BusId>,
1017    /// Copies of this track's signal sent into buses, at most [`MAX_AUDIO_SENDS`].
1018    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1019    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_AUDIO_SENDS }>")]
1020    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_AUDIO_SENDS)))]
1021    pub sends: Vec<AudioSend>,
1022}
1023
1024impl Default for TrackAudio {
1025    fn default() -> Self {
1026        Self {
1027            gain: unit_gain(),
1028            pan: center_pan(),
1029            muted: false,
1030            solo: false,
1031            effects: Vec::new(),
1032            output: None,
1033            sends: Vec::new(),
1034        }
1035    }
1036}
1037
1038impl TrackAudio {
1039    pub(crate) fn validate(&self) -> bool {
1040        valid_gain(&self.gain)
1041            && valid_pan(&self.pan)
1042            && self.effects.len() <= MAX_CHAIN_EFFECTS
1043            && self.effects.iter().all(AudioEffect::is_valid)
1044            && self.sends.len() <= MAX_AUDIO_SENDS
1045    }
1046}
1047
1048/// Where a send takes its copy of the signal.
1049#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
1050#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1051#[serde(rename_all = "snake_case")]
1052pub enum SendTap {
1053    /// After the fader and pan.
1054    #[default]
1055    PostFader,
1056    /// After the effects, before the fader and pan.
1057    PreFader,
1058}
1059
1060/// A copy of a track's or bus's signal added into a bus.
1061#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1062#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1063#[serde(deny_unknown_fields)]
1064pub struct AudioSend {
1065    /// The bus that receives the copy.
1066    pub to: BusId,
1067    /// Animated linear amplitude of the copy, constrained to `0..=MAX_GAIN`.
1068    #[serde(default = "unit_gain")]
1069    pub gain: Animated<f32>,
1070    /// Where the copy is taken.
1071    #[serde(default)]
1072    pub tap: SendTap,
1073}
1074
1075impl AudioSend {
1076    pub(crate) fn is_valid(&self) -> bool {
1077        valid_gain(&self.gain)
1078    }
1079}
1080
1081/// A named bus: it sums what tracks and other buses route into it, runs its effects, and
1082/// outputs through its fader to another bus or the master.
1083#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1084#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1085#[serde(deny_unknown_fields)]
1086pub struct AudioBus {
1087    /// Stable identity, unique among the project's buses.
1088    pub id: BusId,
1089    /// Display name.
1090    #[serde(default)]
1091    pub name: String,
1092    /// Animated linear bus amplitude constrained to `0..=MAX_GAIN`.
1093    #[serde(default = "unit_gain")]
1094    pub gain: Animated<f32>,
1095    /// Animated stereo position applied after the effects, from `-1` (left) to `1` (right).
1096    #[serde(default = "center_pan")]
1097    pub pan: Animated<f32>,
1098    /// Silences this bus on its output, its sends and as a key.
1099    #[serde(default)]
1100    pub muted: bool,
1101    /// Restricts the mix to what flows through soloed tracks and buses when any sets this.
1102    #[serde(default)]
1103    pub solo: bool,
1104    /// Ordered effects applied to the summed input, at most [`MAX_CHAIN_EFFECTS`].
1105    #[serde(default)]
1106    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_CHAIN_EFFECTS }>")]
1107    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_CHAIN_EFFECTS)))]
1108    pub effects: Vec<AudioEffect>,
1109    /// The bus this one outputs to; absent is the master.
1110    #[serde(default, skip_serializing_if = "Option::is_none")]
1111    pub output: Option<BusId>,
1112    /// Copies of this bus's signal sent into other buses, at most [`MAX_AUDIO_SENDS`].
1113    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1114    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_AUDIO_SENDS }>")]
1115    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_AUDIO_SENDS)))]
1116    pub sends: Vec<AudioSend>,
1117}
1118
1119impl AudioBus {
1120    /// A bus with unity gain, centre pan, no effects and its output on the master.
1121    #[must_use]
1122    pub fn new(id: BusId) -> Self {
1123        Self {
1124            id,
1125            name: String::new(),
1126            gain: unit_gain(),
1127            pan: center_pan(),
1128            muted: false,
1129            solo: false,
1130            effects: Vec::new(),
1131            output: None,
1132            sends: Vec::new(),
1133        }
1134    }
1135
1136    pub(crate) fn validate(&self) -> bool {
1137        valid_gain(&self.gain)
1138            && valid_pan(&self.pan)
1139            && self.effects.len() <= MAX_CHAIN_EFFECTS
1140            && self.effects.iter().all(AudioEffect::is_valid)
1141            && self.sends.len() <= MAX_AUDIO_SENDS
1142    }
1143}
1144
1145/// A track or a bus, named by its id.
1146#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
1147#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1148#[serde(rename_all = "snake_case", deny_unknown_fields)]
1149pub enum AudioNodeRef {
1150    /// A track.
1151    Track(TrackId),
1152    /// A bus.
1153    Bus(BusId),
1154}
1155
1156impl core::fmt::Display for AudioNodeRef {
1157    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1158        match self {
1159            Self::Track(track) => write!(formatter, "track {track}"),
1160            Self::Bus(bus) => write!(formatter, "bus {bus}"),
1161        }
1162    }
1163}
1164
1165/// Project-wide master bus settings.
1166#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1167#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1168#[serde(deny_unknown_fields)]
1169pub struct MasterAudio {
1170    /// Animated linear master amplitude constrained to `0..=MAX_GAIN`.
1171    #[serde(default = "unit_gain")]
1172    pub gain: Animated<f32>,
1173    /// Ordered effects applied to what is routed to the master, at most [`MAX_CHAIN_EFFECTS`].
1174    #[serde(default)]
1175    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_CHAIN_EFFECTS }>")]
1176    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_CHAIN_EFFECTS)))]
1177    pub effects: Vec<AudioEffect>,
1178    /// Final peak limiter. Omitted means [`Limiter::default`]; an explicit `null` leaves the mix
1179    /// unlimited.
1180    #[serde(default = "default_limiter")]
1181    pub limiter: Option<Limiter>,
1182    /// Buses that tracks and other buses route into before the master, at most
1183    /// [`MAX_AUDIO_BUSES`].
1184    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1185    #[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_AUDIO_BUSES }>")]
1186    #[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_AUDIO_BUSES)))]
1187    pub buses: Vec<AudioBus>,
1188}
1189
1190impl Default for MasterAudio {
1191    fn default() -> Self {
1192        Self {
1193            gain: unit_gain(),
1194            effects: Vec::new(),
1195            limiter: default_limiter(),
1196            buses: Vec::new(),
1197        }
1198    }
1199}
1200
1201impl MasterAudio {
1202    pub(crate) fn validate(&self) -> bool {
1203        valid_gain(&self.gain)
1204            && self.effects.len() <= MAX_CHAIN_EFFECTS
1205            && self.effects.iter().all(AudioEffect::is_valid)
1206            && self.limiter.is_none_or(Limiter::is_valid)
1207    }
1208}
1209
1210/// Final peak limiter placed at the end of the master bus.
1211#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
1212#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1213#[serde(deny_unknown_fields)]
1214pub struct Limiter {
1215    /// Linear ceiling, positive and at most [`MAX_GAIN`]. One is full scale.
1216    pub threshold: f32,
1217    /// Release time in milliseconds, positive and at most [`MAX_ENVELOPE_MS`].
1218    pub release_ms: f32,
1219}
1220
1221impl Default for Limiter {
1222    fn default() -> Self {
1223        Self {
1224            threshold: 1.0,
1225            release_ms: 50.0,
1226        }
1227    }
1228}
1229
1230impl Limiter {
1231    fn is_valid(self) -> bool {
1232        self.threshold.is_finite()
1233            && self.threshold > 0.0
1234            && self.threshold <= MAX_GAIN
1235            && positive_ms(self.release_ms)
1236    }
1237}
1238
1239/// Serde default: a project without a `limiter` field keeps the safety ceiling.
1240#[allow(clippy::unnecessary_wraps)]
1241fn default_limiter() -> Option<Limiter> {
1242    Some(Limiter::default())
1243}
1244
1245fn zero() -> Animated<f32> {
1246    Animated::Constant { value: 0.0 }
1247}
1248
1249fn full_range() -> Animated<f32> {
1250    Animated::Constant {
1251        value: MAX_EXPANDER_RANGE_DB,
1252    }
1253}
1254
1255fn ms_ticks(milliseconds: f32) -> u64 {
1256    if milliseconds > 0.0 {
1257        // A 32-bit value times 120 is exact in 64 bits, so rounding it up is too.
1258        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
1259        let ticks = (f64::from(milliseconds) * f64::from(TICKS_PER_MS)).ceil() as u64;
1260        ticks
1261    } else {
1262        0
1263    }
1264}
1265
1266fn unit_gain() -> Animated<f32> {
1267    Animated::Constant { value: 1.0 }
1268}
1269
1270fn center_pan() -> Animated<f32> {
1271    Animated::Constant { value: 0.0 }
1272}
1273
1274fn unit(value: f32) -> bool {
1275    value.is_finite() && (0.0..=1.0).contains(&value)
1276}
1277
1278fn positive_ms(value: f32) -> bool {
1279    value.is_finite() && value > 0.0 && value <= MAX_ENVELOPE_MS
1280}
1281
1282fn valid_gain(gain: &Animated<f32>) -> bool {
1283    valid_range(gain, Domain::GAIN)
1284}
1285
1286fn valid_pan(pan: &Animated<f32>) -> bool {
1287    valid_range(pan, Domain::PAN)
1288}
1289
1290fn valid_range(animation: &Animated<f32>, domain: Domain) -> bool {
1291    let valid = |value: f32| domain.contains(value);
1292    match animation {
1293        Animated::Constant { value } => valid(*value),
1294        Animated::Keyframes {
1295            keyframes,
1296            before,
1297            after,
1298        } => {
1299            crate::animation::valid_keyframes(keyframes, *before, *after)
1300                && keyframes.iter().all(|keyframe| valid(keyframe.value))
1301        }
1302        Animated::Split { .. } => false,
1303        Animated::Data(_) => true,
1304    }
1305}