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);
pub const MAX_GAIN: f32 = 16.0;
pub const MAX_AUDIO_EFFECTS: usize = 8_192;
pub const MAX_AUDIO_DELAY_MS: u32 = 120_000;
pub const AUDIO_EFFECT_STATE_MARGIN_MS: u32 = 1_100;
pub const REVERB_DELAY_MS: u32 = 160;
pub const MAX_EQ_GAIN_DB: f32 = 36.0;
pub const EQ_Q_RANGE: std::ops::RangeInclusive<f32> = 0.05..=50.0;
pub const EQ_FREQUENCY_RANGE_HZ: std::ops::RangeInclusive<f32> = 10.0..=47_040.0;
pub const MAX_COMPRESSOR_RATIO: f32 = 100.0;
pub const MAX_PITCH_CENTS: f32 = 2_400.0;
const CENTS_PER_OCTAVE: f32 = 1_200.0;
pub const MAX_CHAIN_EFFECTS: usize = 16;
pub const MAX_AUDIO_BUSES: usize = 64;
pub const MAX_AUDIO_SENDS: usize = 8;
pub const MAX_EQ_BANDS: usize = 16;
pub const MIN_LEVEL_DB: f32 = -96.0;
pub const MAX_LOOKAHEAD_MS: f32 = 100.0;
pub const MAX_KNEE_DB: f32 = 24.0;
pub const MAX_MAKEUP_DB: f32 = 24.0;
pub const MAX_EXPANDER_RANGE_DB: f32 = 96.0;
pub const MAX_HOLD_MS: f32 = 10_000.0;
pub const MAX_DELAY_MS: f32 = 2_000.0;
pub const MAX_DELAY_FEEDBACK: f32 = 0.95;
pub const MAX_MATRIX_GAIN: f32 = 4.0;
pub const MAX_ENVELOPE_MS: f32 = 10_000.0;
#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum EqBandKind {
Peaking,
LowPass,
HighPass,
LowShelf,
HighShelf,
Notch,
BandPass,
AllPass,
}
#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum Detector {
#[default]
Peak,
Rms,
}
#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct DetectorFilter {
pub kind: EqBandKind,
pub frequency_hz: f32,
pub q: f32,
}
impl DetectorFilter {
fn is_valid(self) -> bool {
Domain::EQ_FREQUENCY_HZ.contains(self.frequency_hz) && Domain::EQ_Q.contains(self.q)
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct EqBand {
pub kind: EqBandKind,
pub frequency_hz: Animated<f32>,
pub q: Animated<f32>,
#[serde(default = "zero")]
pub gain_db: Animated<f32>,
}
#[derive(Clone, Copy, Debug)]
pub struct AudioEffectParam<V> {
pub band: Option<usize>,
pub name: &'static str,
pub place: &'static str,
pub domain: Domain,
pub value: V,
}
impl<V> AudioEffectParam<V> {
#[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),
}
}};
}
#[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 {
Eq {
#[serde(deserialize_with = "crate::bounded::seq::<_, _, { crate::MAX_EQ_BANDS }>")]
#[cfg_attr(feature = "schema", schemars(length(max = crate::MAX_EQ_BANDS)))]
bands: Vec<EqBand>,
},
Compressor {
threshold_db: Animated<f32>,
ratio: Animated<f32>,
#[serde(default = "zero")]
knee_db: Animated<f32>,
#[serde(default = "zero")]
makeup_db: Animated<f32>,
attack_ms: f32,
release_ms: f32,
#[serde(default)]
lookahead_ms: f32,
#[serde(default)]
detector: Detector,
#[serde(default, skip_serializing_if = "Option::is_none")]
detector_filter: Option<DetectorFilter>,
#[serde(default, skip_serializing_if = "Option::is_none")]
sidechain: Option<AudioNodeRef>,
},
Expander {
threshold_db: Animated<f32>,
ratio: Animated<f32>,
#[serde(default = "full_range")]
range_db: Animated<f32>,
attack_ms: f32,
#[serde(default)]
hold_ms: f32,
release_ms: f32,
#[serde(default)]
lookahead_ms: f32,
#[serde(default, skip_serializing_if = "Option::is_none")]
detector_filter: Option<DetectorFilter>,
#[serde(default, skip_serializing_if = "Option::is_none")]
sidechain: Option<AudioNodeRef>,
},
Delay {
time_ms: f32,
feedback: Animated<f32>,
mix: Animated<f32>,
},
Matrix {
left: [Animated<f32>; 2],
right: [Animated<f32>; 2],
},
Ducker {
sidechain: AudioNodeRef,
threshold: Animated<f32>,
depth_db: Animated<f32>,
attack_ms: f32,
release_ms: f32,
},
Reverb {
room_size: f32,
damping: f32,
mix: Animated<f32>,
},
}
impl AudioEffect {
#[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),
}
}
#[must_use]
pub fn lookahead_ticks(&self) -> u64 {
match self {
Self::Compressor { lookahead_ms, .. } | Self::Expander { lookahead_ms, .. } => {
ms_ticks(*lookahead_ms)
}
_ => 0,
}
}
#[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
}
}
}
pub fn for_each_param<'a>(
&'a self,
visit: &mut dyn FnMut(AudioEffectParam<&'a Animated<f32>>),
) {
effect_params!(self, visit, iter);
}
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 }
}
}
#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum FadeShape {
#[default]
Linear,
EqualPower,
}
impl FadeShape {
#[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),
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct AudioProperties {
#[serde(default = "unit_gain")]
pub gain: Animated<f32>,
#[serde(default = "center_pan")]
pub pan: Animated<f32>,
#[serde(default)]
pub fade_in: MediaTime,
#[serde(default)]
pub fade_out: MediaTime,
#[serde(default)]
pub fade_in_shape: FadeShape,
#[serde(default)]
pub fade_out_shape: FadeShape,
#[serde(default)]
pub muted: bool,
#[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>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub preserve_pitch: bool,
#[serde(default, skip_serializing_if = "is_zero")]
pub pitch_cents: f32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub stream: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub channel_map: Option<ChannelMap>,
}
pub const MAX_CHANNEL_GAIN: f32 = 16.0;
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ChannelTerm {
pub channel: u32,
#[serde(default = "one")]
pub gain: f32,
}
impl ChannelTerm {
#[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
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct ChannelMap {
#[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>,
#[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 {
#[must_use]
pub fn mono(channel: u32) -> Self {
Self::pair(channel, channel)
}
#[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 {
#[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
}
#[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,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum AudioRead {
Resampled,
Stretched,
Pitched {
stretch: f64,
pitch: f64,
},
PitchedAlong {
ratio: f64,
preserve: bool,
},
}
impl AudioRead {
#[must_use]
pub const fn stretches(self) -> bool {
!matches!(self, Self::Resampled)
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct TrackAudio {
#[serde(default = "unit_gain")]
pub gain: Animated<f32>,
#[serde(default = "center_pan")]
pub pan: Animated<f32>,
#[serde(default)]
pub muted: bool,
#[serde(default)]
pub solo: bool,
#[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>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub output: Option<BusId>,
#[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
}
}
#[derive(Copy, Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
pub enum SendTap {
#[default]
PostFader,
PreFader,
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct AudioSend {
pub to: BusId,
#[serde(default = "unit_gain")]
pub gain: Animated<f32>,
#[serde(default)]
pub tap: SendTap,
}
impl AudioSend {
pub(crate) fn is_valid(&self) -> bool {
valid_gain(&self.gain)
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct AudioBus {
pub id: BusId,
#[serde(default)]
pub name: String,
#[serde(default = "unit_gain")]
pub gain: Animated<f32>,
#[serde(default = "center_pan")]
pub pan: Animated<f32>,
#[serde(default)]
pub muted: bool,
#[serde(default)]
pub solo: bool,
#[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>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub output: Option<BusId>,
#[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 {
#[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
}
}
#[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 {
Track(TrackId),
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}"),
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct MasterAudio {
#[serde(default = "unit_gain")]
pub gain: Animated<f32>,
#[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>,
#[serde(default = "default_limiter")]
pub limiter: Option<Limiter>,
#[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)
}
}
#[derive(Copy, Clone, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Limiter {
pub threshold: f32,
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)
}
}
#[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 {
#[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,
}
}