From 1fae9bef733aff7a37cb3c5c1a30e232262728c4 Mon Sep 17 00:00:00 2001 From: Dandaedre Date: Thu, 15 Oct 2026 03:14:36 +0200 Subject: [PATCH] feat(M1.4): reserve stateful relative groups Keep absolute/sync as the only runtime-selectable group mode while defining and testing the future relative model. Relative members retain their last independent or external channel vector as a maximum and scale reversibly from zero to that maximum. Reject relative profiles until origin-aware runtime lifecycle support is implemented.\n\nTests: cargo fmt --all -- --check; cargo check --workspace --all-targets --all-features; cargo test --workspace --all-targets --all-features; cargo test --workspace --doc --all-features; cargo clippy --workspace --all-targets --all-features -- -D warnings; cargo build --workspace --release --all-features; default/no-default/individual-backend matrix (all pass). --- architecture.md | 22 +++++++-- config/src/profile.rs | 6 +++ config/tests/schema.rs | 7 +++ core/src/group.rs | 85 ++++++++++++++++++++++++++--------- core/src/lib.rs | 2 +- core/tests/group_volume.rs | 92 +++++++++++++++++++++++++++----------- fader_master/src/live.rs | 40 +++++++---------- task.md | 17 ++++++- 8 files changed, 194 insertions(+), 77 deletions(-) diff --git a/architecture.md b/architecture.md index b4a3354..940d449 100644 --- a/architecture.md +++ b/architecture.md @@ -126,10 +126,26 @@ The initial physical fader curve maps its normalized position linearly to gain i For an application or group, display maximum member stream gain as the aggregate fader position plus a mixed indicator when gains differ. Display mute as `all-muted`, `all-unmuted`, `mixed`, or `unavailable`. A toggle mutes all when any member is unmuted; otherwise it unmutes all. Unmute leaves volumes untouched and clears mute on all members, including independently muted members; there is no hidden pre-group mute restore in v1. -Support two explicit group volume modes: +Recognize two group volume models, but enable only sync groups in the current +runtime: -1. `absolute` (default): a move to `g` sets each resolved stream's scalar gain to `g`, preserving each stream's channel balance. This is predictable for absolute USB faders. -2. `relative`: derive `g / old_max` from the latest member snapshot and scale members together, preserving relative gains until a limit clips. If `old_max == 0`, set all to `g`. External edits rebase the next move. A move to zero loses cross-stream ratios; recovery uses the defined equal-gain fallback. Document this in the editor. +1. `absolute` (also called **sync**, current default and only accepted profile + mode): a move to `g` sets each resolved stream's scalar gain to `g`, + preserving each stream's channel balance. This is predictable for absolute + USB faders. +2. `relative` (reserved): each member remembers the channel vector from its + last independent application-fader or external edit as that member's + maximum. A normalized group position `p` scales the member between silence + and that maximum (`p * member_max`), preserving channel balance. A group + write or its confirmation never rebases the remembered maximum; a later + independent/external edit rebases only that member. Moving to zero therefore + remains reversible. Newly resolved members adopt their live state as their + initial maximum, and removed members lose their anchor. + +The pure domain planner for the reserved relative model exists and is tested, +but profile validation rejects `volume_mode = "relative"` until the runtime can +track write origin and lifecycle for those anchors. Examples and live routing +use `volume_mode = "absolute"` only. Group dispatch is best effort because audio APIs do not offer a transaction across arbitrary streams. Track results per stream, keep successful changes, show failures, and refresh observations. Do not pretend to roll back atomically. Backend workers preserve server write ordering per stream and per property; volume and mute can be tracked independently. diff --git a/config/src/profile.rs b/config/src/profile.rs index 0558f10..38fd1cc 100644 --- a/config/src/profile.rs +++ b/config/src/profile.rs @@ -543,6 +543,12 @@ fn validate_profile_members(raw: &RawProfile) -> Result<(), ConfigError> { let groups = unique_ids::(raw.groups.iter().map(|item| item.id.as_str()), "groups")?; for (index, group) in raw.groups.iter().enumerate() { + if group.volume_mode == VolumeMode::Relative { + return Err(ConfigError::validation( + format!("groups[{index}].volume_mode"), + "relative groups are reserved for a future stateful runtime; use absolute", + )); + } let mut members = BTreeSet::new(); for (member_index, member) in group.members.iter().enumerate() { let member_id = parse_id::( diff --git a/config/tests/schema.rs b/config/tests/schema.rs index 29bfc2b..5b3725d 100644 --- a/config/tests/schema.rs +++ b/config/tests/schema.rs @@ -122,6 +122,13 @@ fn rejects_dangling_references_and_duplicate_physical_bindings() { assert_error_contains(Profile::parse(&duplicate), "bindings[1].message"); } +#[test] +fn relative_groups_are_reserved_but_not_runtime_selectable() { + let relative = EXAMPLE.replace("volume_mode = \"absolute\"", "volume_mode = \"relative\""); + assert_error_contains(Profile::parse(&relative), "groups[0].volume_mode"); + assert_error_contains(Profile::parse(&relative), "use absolute"); +} + #[test] fn rejects_incomplete_or_malformed_usb_surface_hints() { let missing_product = ARCH_PIPEWIRE.replace("usb_product_id = \"0028\"\n", ""); diff --git a/core/src/group.rs b/core/src/group.rs index 8fe83e3..90226aa 100644 --- a/core/src/group.rs +++ b/core/src/group.rs @@ -5,13 +5,70 @@ 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. + /// Sync group: each stream reaches the requested scalar gain. #[default] Absolute, - /// Stream maxima retain relative ratios until the write ceiling clips them. + /// Reserved VCA-style group backed by [`RelativeGroupState`]. Relative, } +/// Prepared state for a future VCA-style relative group. +/// +/// Each member's last independently controlled or externally observed channel +/// vector is its maximum. A normalized group position scales every member from +/// silence to that remembered maximum. Group-generated confirmations must not +/// be passed to [`Self::observe_independent`], because moving the group does not +/// redefine a member's maximum. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct RelativeGroupState { + maxima: BTreeMap, +} + +impl RelativeGroupState { + /// Creates an empty relative group state. + #[must_use] + pub const fn new() -> Self { + Self { + maxima: BTreeMap::new(), + } + } + + /// Records a member's latest independent fader or external position. + pub fn observe_independent(&mut self, stream: StreamHandle, channels: ChannelGains) { + self.maxima.insert(stream, channels); + } + + /// Forgets a member that is no longer resolved by this group. + pub fn remove(&mut self, stream: StreamHandle) { + self.maxima.remove(&stream); + } + + /// Plans member gains at a normalized group position in `0..=1`. + /// + /// The stored maxima are not mutated, so lowering and raising the group is + /// reversible until an independent member edit explicitly rebases one. + pub fn plan( + &self, + position: Gain, + ceiling: Gain, + ) -> Result, ChannelGainError> { + if position > Gain::UNITY { + return Err(ChannelGainError::AboveWriteCeiling { + target: position.get(), + ceiling: Gain::UNITY.get(), + }); + } + self.maxima + .iter() + .map(|(handle, maximum)| { + let desired = + Gain::new((maximum.maximum().get() * position.get()).min(ceiling.get()))?; + Ok((*handle, maximum.scaled_to(desired, ceiling)?)) + }) + .collect() + } +} + /// Aggregate gain view; absence of this value means no stream is observable. #[derive(Clone, Copy, Debug, PartialEq)] pub struct VolumeView { @@ -40,29 +97,17 @@ pub fn volume_view(live: &BTreeMap) -> Option, - mode: VolumeMode, target: Gain, ceiling: Gain, ) -> Result, ChannelGainError> { - let Some(view) = volume_view(live) else { - return Ok(BTreeMap::new()); - }; + let bounded = Gain::new(target.get().min(ceiling.get()))?; 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)?)) - }) + .map(|(handle, channels)| Ok((*handle, channels.scaled_to(bounded, ceiling)?))) .collect() } diff --git a/core/src/lib.rs b/core/src/lib.rs index d58379e..f603b2f 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -27,7 +27,7 @@ pub use bindings::{ Binding, BindingAction, BindingError, BindingKey, Bindings, MessageKind, MidiChannel, MidiData, MidiRangeError, }; -pub use group::{VolumeMode, VolumeView, plan_volume, volume_view}; +pub use group::{RelativeGroupState, 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 index 57f20a7..0081c41 100644 --- a/core/tests/group_volume.rs +++ b/core/tests/group_volume.rs @@ -1,5 +1,5 @@ use fader_core::{ - BackendEpoch, ChannelGains, Gain, StreamHandle, VolumeMode, plan_volume, volume_view, + BackendEpoch, ChannelGains, Gain, RelativeGroupState, StreamHandle, plan_volume, volume_view, }; use std::collections::BTreeMap; @@ -14,61 +14,99 @@ fn handle(id: u64) -> StreamHandle { } #[test] -fn absolute_and_relative_plans_preserve_channel_balance_without_mutation() { +fn absolute_plan_preserves_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(); + let absolute = plan_volume(&live, 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])); + let clipped = plan_volume(&live, gain(2.0), Gain::UNITY).unwrap(); + assert_eq!(clipped[&handle(1)], channels(&[1.0, 0.5])); + assert_eq!(clipped[&handle(2)], channels(&[1.0])); 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() { +fn empty_absolute_groups_have_explicit_behavior() { let empty = BTreeMap::new(); assert_eq!(volume_view(&empty), None); assert!( - plan_volume(&empty, VolumeMode::Relative, Gain::UNITY, Gain::UNITY) + plan_volume(&empty, 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_group_scales_zero_to_each_members_remembered_maximum() { + let mut group = RelativeGroupState::new(); + group.observe_independent(handle(1), channels(&[0.8, 0.4])); + group.observe_independent(handle(2), channels(&[0.2])); + + let half = group.plan(gain(0.5), Gain::UNITY).unwrap(); + assert_eq!(half[&handle(1)], channels(&[0.4, 0.2])); + assert_eq!(half[&handle(2)], channels(&[0.1])); + + let silent = group.plan(Gain::SILENCE, Gain::UNITY).unwrap(); + assert_eq!(silent[&handle(1)], channels(&[0.0, 0.0])); + assert_eq!(silent[&handle(2)], channels(&[0.0])); + + let restored = group.plan(Gain::UNITY, Gain::UNITY).unwrap(); + assert_eq!(restored[&handle(1)], channels(&[0.8, 0.4])); + assert_eq!(restored[&handle(2)], channels(&[0.2])); +} + +#[test] +fn relative_group_position_is_normalized() { + let group = RelativeGroupState::new(); + let error = group.plan(gain(1.01), Gain::UNITY).unwrap_err(); + assert!(matches!( + error, + fader_core::ChannelGainError::AboveWriteCeiling { + target: 1.01, + ceiling: 1.0 + } + )); +} + +#[test] +fn independent_or_external_changes_rebase_only_that_relative_member() { + let mut group = RelativeGroupState::new(); + group.observe_independent(handle(1), channels(&[0.8])); + group.observe_independent(handle(2), channels(&[0.2])); + let _ = group.plan(gain(0.5), Gain::UNITY).unwrap(); + + group.observe_independent(handle(2), channels(&[0.6])); + let next = group.plan(gain(0.5), Gain::UNITY).unwrap(); + assert_eq!(next[&handle(1)], channels(&[0.4])); + assert_eq!(next[&handle(2)], channels(&[0.3])); + + group.remove(handle(1)); + assert!( + !group + .plan(Gain::UNITY, Gain::UNITY) + .unwrap() + .contains_key(&handle(1)) ); } #[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() { +fn partial_confirmation_and_new_members_do_not_change_absolute_semantics() { 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(); + let plan = plan_volume(&live, 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])); + let next = plan_volume(&live, gain(0.5), Gain::UNITY).unwrap(); + assert_eq!(next[&handle(1)], channels(&[0.5])); + assert_eq!(next[&handle(2)], channels(&[0.5])); assert_eq!(next[&handle(3)], channels(&[0.5])); } diff --git a/fader_master/src/live.rs b/fader_master/src/live.rs index ef091f0..130f0cb 100644 --- a/fader_master/src/live.rs +++ b/fader_master/src/live.rs @@ -4,7 +4,7 @@ use fader_config::Profile; use fader_core::{ AdapterCommand, AdapterEvent, ApplicationMatcher, ChannelGains, CommandOrigin, FaderId, Gain, Mute, Pickup, PickupState, ServerCommand, ServerReducer, StreamHandle, StreamMetadata, - SurfaceId, ValueState, VolumeMode, mute_view, plan_volume, volume_view, + SurfaceId, ValueState, mute_view, plan_volume, volume_view, }; use midi::MidiIntent; use thiserror::Error; @@ -33,7 +33,6 @@ struct ConfiguredGroup { id: String, label: String, members: Vec, - volume_mode: VolumeMode, } #[derive(Clone, Debug)] @@ -119,7 +118,6 @@ impl LiveMixerState { id: group.id().to_owned(), label: group.label().to_owned(), members: group.members().to_vec(), - volume_mode: group.volume_mode(), }) .collect(); let faders: BTreeMap = profile @@ -370,7 +368,7 @@ impl LiveMixerState { } fn object_gain(&self, object: &MixerObjectKey) -> Option { - let (handles, _) = self.resolve(object).ok()?; + let handles = self.resolve(object).ok()?; handles .into_iter() .filter_map(|handle| self.reducer.view(handle)) @@ -384,7 +382,7 @@ impl LiveMixerState { .filter_map(|(fader, configured)| { self.resolve(&configured.target) .ok() - .filter(|(handles, _)| handles.contains(&stream)) + .filter(|handles| handles.contains(&stream)) .map(|_| fader.clone()) }) .collect() @@ -480,30 +478,24 @@ impl LiveMixerState { .collect() } - fn resolve( - &self, - object: &MixerObjectKey, - ) -> Result<(BTreeSet, VolumeMode), LiveMixerError> { + fn resolve(&self, object: &MixerObjectKey) -> Result, LiveMixerError> { match object.kind { MixerObjectKind::Application => self .applications .iter() .find(|application| application.id == object.id) - .map(|_| (self.application_handles(&object.id), VolumeMode::Absolute)), + .map(|_| self.application_handles(&object.id)), MixerObjectKind::Group => self .groups .iter() .find(|group| group.id == object.id) - .map(|group| (self.group_handles(group), group.volume_mode)), + .map(|group| self.group_handles(group)), MixerObjectKind::Output => { (object.id == "default" && self.has_default_output).then(|| { - ( - self.output - .as_ref() - .map(|output| BTreeSet::from([output.stream])) - .unwrap_or_default(), - VolumeMode::Absolute, - ) + self.output + .as_ref() + .map(|output| BTreeSet::from([output.stream])) + .unwrap_or_default() }) } } @@ -579,8 +571,8 @@ impl LiveMixerState { fn writable_handles( &self, object: &MixerObjectKey, - ) -> Result<(BTreeSet, VolumeMode), LiveMixerError> { - let (handles, mode) = self.resolve(object)?; + ) -> Result, LiveMixerError> { + let handles = self.resolve(object)?; if handles.is_empty() { return Err(LiveMixerError::OfflineObject { kind: object.kind, @@ -593,7 +585,7 @@ impl LiveMixerState { id: object.id.clone(), }); } - Ok((handles, mode)) + Ok(handles) } fn set_volume( @@ -604,7 +596,7 @@ impl LiveMixerState { request: u64, ) -> Result, LiveMixerError> { self.check_revision(expected_revision)?; - let (handles, mode) = self.writable_handles(&object)?; + let handles = self.writable_handles(&object)?; let observed: BTreeMap<_, ChannelGains> = handles .iter() .filter_map(|handle| { @@ -613,7 +605,7 @@ impl LiveMixerState { .map(|view| (*handle, view.channels)) }) .collect(); - let plan = plan_volume(&observed, mode, target, self.write_ceiling)?; + let plan = plan_volume(&observed, target, self.write_ceiling)?; let mut commands = Vec::with_capacity(plan.len()); for (stream, channels) in plan { commands.extend( @@ -637,7 +629,7 @@ impl LiveMixerState { request: u64, ) -> Result, LiveMixerError> { self.check_revision(expected_revision)?; - let (handles, _) = self.writable_handles(&object)?; + let handles = self.writable_handles(&object)?; let should_mute = handles.iter().any(|handle| { self.reducer .view(*handle) diff --git a/task.md b/task.md index 7a8d582..56428b4 100644 --- a/task.md +++ b/task.md @@ -30,7 +30,13 @@ Dependencies: M0. - [x] **M1.1 Typed values:** stable IDs, finite gain, channel vectors, mute/availability/mixed states, revisions and backend epochs. Tests: invalid ranges/NaN/infinity rejected; gain/silence/channel-balance properties hold; IDs cannot be interchanged accidentally. - [x] **M1.2 Application selectors:** normalized metadata, exact/regex matching, OR selectors, multiple live streams and offline objects. Tests: anchored/unanchored/case-sensitive cases, missing fields, malformed regex, stream creation/removal and backend ID reuse. - [x] **M1.3 Fader resolution:** surface binding -> fader -> application/group -> deduplicated live streams. Tests: identical CCs on different surfaces stay separate, multiple faders can share an object, and overlap never writes the same stream twice per operation. -- [x] **M1.4 Group gain:** absolute and relative modes with channel balance, aggregate max/mixed state, zero fallback and clipping. Tests: heterogeneous members, externally changed members, all-zero recovery, empty group, late joiner adopting live state, and partial failure. +- [x] **M1.4 Group gain:** active absolute/sync planning plus a prepared + relative-group domain state with per-member independent/external maxima, + channel balance, reversible zero, normalized position, lifecycle removal, + aggregate max/mixed state, and clipping. Tests: heterogeneous members, + externally changed member anchors, zero-to-maximum recovery, empty group, + late joiner behavior, and partial failure. Runtime profile validation keeps + `relative` reserved and accepts only `absolute` groups. - [x] **M1.5 Mute:** explicit set/toggle independent of volume. Tests: mixed-group toggle mutes all, fully muted toggle unmutes all, two rapid toggles cancel logically, zero gain does not imply mute, and unmute does not alter gain. M1 verification on 2026-10-05: 30 unit/integration/property tests and one @@ -250,7 +256,7 @@ Dependencies: M7, M4 for real use. - [ ] **M8.1 Mixer:** replace blocking prototype with event-driven client views and volume/mute actions. Test-backend assertions: groups/applications, mixed/offline/pending/error indicators, pickup state, resize and keyboard navigation reflect snapshots accurately. The live slice now lists stable configured applications and groups, preserves offline and mixed gain/mute states, deduplicates overlapping group streams, - and fans group writes out with absolute/relative policy. It refreshes without + and fans sync-group writes out with absolute policy. It refreshes without blocking rendering or server operation, updates accepted input locally, and shows pending, read-only, and error indicators. Keep this item open until pickup state is integrated and the profile-aware @@ -262,6 +268,13 @@ Dependencies: M7, M4 for real use. Blocking IPC now runs on a joined worker and a delayed request cannot block redraw access; keep this item open for explicit terminal-restoration failure injection and log routing. +- [ ] **M8.4 Relative-group activation (reserved):** wire the prepared + per-member maximum state into origin-aware runtime observations, lifecycle, + snapshots, pickup, and editor help before allowing `volume_mode = "relative"` + in profiles. Tests: group confirmations never rebase maxima; application MIDI, + TUI, and external edits rebase only the affected member; zero is reversible; + joins adopt live maxima and removals discard anchors. Do not enable this mode + in shipped profiles without a separate product decision. First live TUI slice verification on 2026-10-15: a real server selected Pulse against PipeWire, reached `ready`, and published the active Qobuz playback stream