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
8pub const MAX_GAIN: f32 = 16.0;
10
11pub const MAX_AUDIO_EFFECTS: usize = 8_192;
15
16pub const MAX_AUDIO_DELAY_MS: u32 = 120_000;
22
23pub const AUDIO_EFFECT_STATE_MARGIN_MS: u32 = 1_100;
28
29pub const REVERB_DELAY_MS: u32 = 160;
32
33pub const MAX_EQ_GAIN_DB: f32 = 36.0;
35
36pub const EQ_Q_RANGE: std::ops::RangeInclusive<f32> = 0.05..=50.0;
38
39pub const EQ_FREQUENCY_RANGE_HZ: std::ops::RangeInclusive<f32> = 10.0..=47_040.0;
43
44pub const MAX_COMPRESSOR_RATIO: f32 = 100.0;
46
47pub const MAX_PITCH_CENTS: f32 = 2_400.0;
49
50const CENTS_PER_OCTAVE: f32 = 1_200.0;
51
52pub const MAX_CHAIN_EFFECTS: usize = 16;
54
55pub const MAX_AUDIO_BUSES: usize = 64;
57
58pub const MAX_AUDIO_SENDS: usize = 8;
60
61pub const MAX_EQ_BANDS: usize = 16;
63
64pub const MIN_LEVEL_DB: f32 = -96.0;
67
68pub const MAX_LOOKAHEAD_MS: f32 = 100.0;
70
71pub const MAX_KNEE_DB: f32 = 24.0;
73
74pub const MAX_MAKEUP_DB: f32 = 24.0;
76
77pub const MAX_EXPANDER_RANGE_DB: f32 = 96.0;
79
80pub const MAX_HOLD_MS: f32 = 10_000.0;
82
83pub const MAX_DELAY_MS: f32 = 2_000.0;
85
86pub const MAX_DELAY_FEEDBACK: f32 = 0.95;
88
89pub const MAX_MATRIX_GAIN: f32 = 4.0;
91
92pub const MAX_ENVELOPE_MS: f32 = 10_000.0;
94
95#[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 Peaking,
102 LowPass,
104 HighPass,
106 LowShelf,
108 HighShelf,
110 Notch,
112 BandPass,
114 AllPass,
116}
117
118#[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 #[default]
125 Peak,
126 Rms,
129}
130
131#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
134#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
135#[serde(deny_unknown_fields)]
136pub struct DetectorFilter {
137 pub kind: EqBandKind,
139 pub frequency_hz: f32,
141 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#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
153#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
154#[serde(deny_unknown_fields)]
155pub struct EqBand {
156 pub kind: EqBandKind,
158 pub frequency_hz: Animated<f32>,
160 pub q: Animated<f32>,
162 #[serde(default = "zero")]
165 pub gain_db: Animated<f32>,
166}
167
168#[derive(Clone, Copy, Debug)]
170pub struct AudioEffectParam<V> {
171 pub band: Option<usize>,
173 pub name: &'static str,
175 pub place: &'static str,
177 pub domain: Domain,
180 pub value: V,
182}
183
184impl<V> AudioEffectParam<V> {
185 #[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#[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 Eq {
394 #[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 Compressor {
405 threshold_db: Animated<f32>,
408 ratio: Animated<f32>,
410 #[serde(default = "zero")]
413 knee_db: Animated<f32>,
414 #[serde(default = "zero")]
417 makeup_db: Animated<f32>,
418 attack_ms: f32,
420 release_ms: f32,
422 #[serde(default)]
424 lookahead_ms: f32,
425 #[serde(default)]
427 detector: Detector,
428 #[serde(default, skip_serializing_if = "Option::is_none")]
430 detector_filter: Option<DetectorFilter>,
431 #[serde(default, skip_serializing_if = "Option::is_none")]
433 sidechain: Option<AudioNodeRef>,
434 },
435 Expander {
442 threshold_db: Animated<f32>,
445 ratio: Animated<f32>,
448 #[serde(default = "full_range")]
451 range_db: Animated<f32>,
452 attack_ms: f32,
454 #[serde(default)]
456 hold_ms: f32,
457 release_ms: f32,
459 #[serde(default)]
461 lookahead_ms: f32,
462 #[serde(default, skip_serializing_if = "Option::is_none")]
464 detector_filter: Option<DetectorFilter>,
465 #[serde(default, skip_serializing_if = "Option::is_none")]
467 sidechain: Option<AudioNodeRef>,
468 },
469 Delay {
473 time_ms: f32,
475 feedback: Animated<f32>,
478 mix: Animated<f32>,
480 },
481 Matrix {
486 left: [Animated<f32>; 2],
489 right: [Animated<f32>; 2],
492 },
493 Ducker {
495 sidechain: AudioNodeRef,
497 threshold: Animated<f32>,
499 depth_db: Animated<f32>,
501 attack_ms: f32,
503 release_ms: f32,
505 },
506 Reverb {
508 room_size: f32,
510 damping: f32,
512 mix: Animated<f32>,
514 },
515}
516
517impl AudioEffect {
518 #[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 #[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 #[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 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 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#[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 #[default]
650 Linear,
651 EqualPower,
653}
654
655impl FadeShape {
656 #[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#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
669#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
670#[serde(deny_unknown_fields)]
671pub struct AudioProperties {
672 #[serde(default = "unit_gain")]
674 pub gain: Animated<f32>,
675 #[serde(default = "center_pan")]
677 pub pan: Animated<f32>,
678 #[serde(default)]
680 pub fade_in: MediaTime,
681 #[serde(default)]
683 pub fade_out: MediaTime,
684 #[serde(default)]
686 pub fade_in_shape: FadeShape,
687 #[serde(default)]
689 pub fade_out_shape: FadeShape,
690 #[serde(default)]
692 pub muted: bool,
693 #[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 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
702 pub preserve_pitch: bool,
703 #[serde(default, skip_serializing_if = "is_zero")]
710 pub pitch_cents: f32,
711 #[serde(default, skip_serializing_if = "Option::is_none")]
714 pub stream: Option<u32>,
715 #[serde(default, skip_serializing_if = "Option::is_none")]
718 pub channel_map: Option<ChannelMap>,
719}
720
721pub const MAX_CHANNEL_GAIN: f32 = 16.0;
723
724#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
726#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
727#[serde(deny_unknown_fields)]
728pub struct ChannelTerm {
729 pub channel: u32,
731 #[serde(default = "one")]
733 pub gain: f32,
734}
735
736impl ChannelTerm {
737 #[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#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
754#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
755#[serde(deny_unknown_fields)]
756pub struct ChannelMap {
757 #[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 #[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 #[must_use]
782 pub fn mono(channel: u32) -> Self {
783 Self::pair(channel, channel)
784 }
785
786 #[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 #[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 #[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#[derive(Clone, Copy, Debug, PartialEq)]
960pub enum AudioRead {
961 Resampled,
964 Stretched,
966 Pitched {
968 stretch: f64,
970 pitch: f64,
972 },
973 PitchedAlong {
975 ratio: f64,
977 preserve: bool,
980 },
981}
982
983impl AudioRead {
984 #[must_use]
986 pub const fn stretches(self) -> bool {
987 !matches!(self, Self::Resampled)
988 }
989}
990
991#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
993#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
994#[serde(deny_unknown_fields)]
995pub struct TrackAudio {
996 #[serde(default = "unit_gain")]
998 pub gain: Animated<f32>,
999 #[serde(default = "center_pan")]
1001 pub pan: Animated<f32>,
1002 #[serde(default)]
1004 pub muted: bool,
1005 #[serde(default)]
1007 pub solo: bool,
1008 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
1016 pub output: Option<BusId>,
1017 #[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#[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 #[default]
1055 PostFader,
1056 PreFader,
1058}
1059
1060#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1062#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1063#[serde(deny_unknown_fields)]
1064pub struct AudioSend {
1065 pub to: BusId,
1067 #[serde(default = "unit_gain")]
1069 pub gain: Animated<f32>,
1070 #[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#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1084#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1085#[serde(deny_unknown_fields)]
1086pub struct AudioBus {
1087 pub id: BusId,
1089 #[serde(default)]
1091 pub name: String,
1092 #[serde(default = "unit_gain")]
1094 pub gain: Animated<f32>,
1095 #[serde(default = "center_pan")]
1097 pub pan: Animated<f32>,
1098 #[serde(default)]
1100 pub muted: bool,
1101 #[serde(default)]
1103 pub solo: bool,
1104 #[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 #[serde(default, skip_serializing_if = "Option::is_none")]
1111 pub output: Option<BusId>,
1112 #[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 #[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#[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 Track(TrackId),
1152 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#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
1167#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1168#[serde(deny_unknown_fields)]
1169pub struct MasterAudio {
1170 #[serde(default = "unit_gain")]
1172 pub gain: Animated<f32>,
1173 #[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 #[serde(default = "default_limiter")]
1181 pub limiter: Option<Limiter>,
1182 #[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#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
1212#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
1213#[serde(deny_unknown_fields)]
1214pub struct Limiter {
1215 pub threshold: f32,
1217 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#[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 #[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}