diff --git a/core/src/group.rs b/core/src/group.rs new file mode 100644 index 0000000..8fe83e3 --- /dev/null +++ b/core/src/group.rs @@ -0,0 +1,68 @@ +//! Pure plans over current observations; creating a plan never confirms a write. +use crate::{ChannelGainError, ChannelGains, Gain, StreamHandle}; +use std::collections::BTreeMap; + +/// Application group gain semantics. +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub enum VolumeMode { + /// Each stream reaches the requested scalar gain. + #[default] + Absolute, + /// Stream maxima retain relative ratios until the write ceiling clips them. + Relative, +} + +/// Aggregate gain view; absence of this value means no stream is observable. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct VolumeView { + /// Maximum channel gain across all resolved streams. + pub maximum: Gain, + /// Whether stream maxima disagree. + pub mixed: bool, +} + +/// Aggregates stream maxima without manufacturing a zero for offline targets. +pub fn volume_view(live: &BTreeMap) -> Option { + let mut maxima = live.values().map(ChannelGains::maximum); + let first = maxima.next()?; + let mut view = VolumeView { + maximum: first, + mixed: false, + }; + for maximum in maxima { + view.mixed |= maximum != first; + if maximum > view.maximum { + view.maximum = maximum; + } + } + Some(view) +} + +/// Computes one bounded channel-vector command per resolved stream. +/// +/// The caller supplies the newest observations on every command, so external +/// changes and newly attached streams immediately affect relative scaling. +/// Requests above the configured ceiling clip per stream; no observation is +/// modified. Successful and failed writes must later be reconciled separately. +pub fn plan_volume( + live: &BTreeMap, + mode: VolumeMode, + target: Gain, + ceiling: Gain, +) -> Result, ChannelGainError> { + let Some(view) = volume_view(live) else { + return Ok(BTreeMap::new()); + }; + live.iter() + .map(|(handle, channels)| { + // Divide first: target/maximum may overflow for tiny observed gains. + let desired = if mode == VolumeMode::Relative && !view.maximum.is_silent() { + (channels.maximum().get() / view.maximum.get()) * target.get() + } else { + target.get() + }; + let bounded = Gain::new(desired.min(ceiling.get()))?; + Ok((*handle, channels.scaled_to(bounded, ceiling)?)) + }) + .collect() +} diff --git a/core/src/lib.rs b/core/src/lib.rs index 395e009..7487fa3 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -6,6 +6,7 @@ #![forbid(unsafe_code)] mod bindings; +mod group; mod id; mod matching; mod revision; @@ -17,6 +18,7 @@ pub use bindings::{ Binding, BindingAction, BindingError, BindingKey, Bindings, MessageKind, MidiChannel, MidiData, MidiRangeError, }; +pub use group::{VolumeMode, VolumeView, plan_volume, volume_view}; pub use id::{ApplicationId, FaderId, GroupId, IdError, ProfileId, SurfaceId}; pub use matching::{ ApplicationMatcher, ApplicationRuntime, ApplicationSelector, MetadataField, SelectorError, diff --git a/core/tests/group_volume.rs b/core/tests/group_volume.rs new file mode 100644 index 0000000..57f20a7 --- /dev/null +++ b/core/tests/group_volume.rs @@ -0,0 +1,74 @@ +use fader_core::{ + BackendEpoch, ChannelGains, Gain, StreamHandle, VolumeMode, plan_volume, volume_view, +}; +use std::collections::BTreeMap; + +fn gain(value: f64) -> Gain { + Gain::new(value).unwrap() +} +fn channels(values: &[f64]) -> ChannelGains { + ChannelGains::new(values.iter().copied().map(gain).collect()).unwrap() +} +fn handle(id: u64) -> StreamHandle { + StreamHandle::new(BackendEpoch::new(1), id, 1) +} + +#[test] +fn absolute_and_relative_plans_preserve_channel_balance_without_mutation() { + let live = BTreeMap::from([ + (handle(1), channels(&[0.8, 0.4])), + (handle(2), channels(&[0.2])), + ]); + let before = live.clone(); + let absolute = plan_volume(&live, VolumeMode::Absolute, gain(0.4), Gain::UNITY).unwrap(); + let relative = plan_volume(&live, VolumeMode::Relative, gain(0.4), Gain::UNITY).unwrap(); + assert_eq!(absolute[&handle(1)], channels(&[0.4, 0.2])); + assert_eq!(absolute[&handle(2)], channels(&[0.4])); + assert_eq!(relative[&handle(2)], channels(&[0.1])); + assert_eq!(live, before); + assert!(volume_view(&live).unwrap().mixed); + assert_eq!(volume_view(&live).unwrap().maximum, gain(0.8)); +} + +#[test] +fn silent_and_empty_groups_have_explicit_behavior() { + let empty = BTreeMap::new(); + assert_eq!(volume_view(&empty), None); + assert!( + plan_volume(&empty, VolumeMode::Relative, Gain::UNITY, Gain::UNITY) + .unwrap() + .is_empty() + ); + let silent = BTreeMap::from([(handle(1), channels(&[0.0, 0.0]))]); + assert_eq!( + plan_volume(&silent, VolumeMode::Relative, gain(0.5), Gain::UNITY).unwrap()[&handle(1)], + channels(&[0.5, 0.5]) + ); +} + +#[test] +fn relative_scaling_handles_extreme_finite_observations_and_clips_requests() { + let live = BTreeMap::from([ + (handle(1), channels(&[f64::MAX])), + (handle(2), channels(&[f64::MAX / 2.0])), + ]); + let plan = plan_volume(&live, VolumeMode::Relative, gain(2.0), Gain::UNITY).unwrap(); + assert_eq!(plan[&handle(1)], channels(&[1.0])); + assert_eq!(plan[&handle(2)], channels(&[1.0])); +} + +#[test] +fn partial_confirmation_and_new_members_rebase_the_next_plan() { + let mut live = BTreeMap::from([(handle(1), channels(&[0.8])), (handle(2), channels(&[0.2]))]); + let plan = plan_volume(&live, VolumeMode::Absolute, gain(0.4), Gain::UNITY).unwrap(); + // Only the first stream confirms; the failed second stream stays truthful. + live.insert(handle(1), plan[&handle(1)].clone()); + assert!(volume_view(&live).unwrap().mixed); + assert_eq!(live[&handle(2)], channels(&[0.2])); + // New streams are adopted without replaying the previous absolute intent. + live.insert(handle(3), channels(&[1.0])); + let next = plan_volume(&live, VolumeMode::Relative, gain(0.5), Gain::UNITY).unwrap(); + assert_eq!(next[&handle(1)], channels(&[0.2])); + assert_eq!(next[&handle(2)], channels(&[0.1])); + assert_eq!(next[&handle(3)], channels(&[0.5])); +}