diff --git a/Cargo.lock b/Cargo.lock index 8977d6d..b706a24 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8,6 +8,27 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bit-set" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7" + [[package]] name = "bitflags" version = "2.13.2" @@ -63,7 +84,7 @@ dependencies = [ "crossterm_winapi", "mio", "parking_lot", - "rustix", + "rustix 0.38.44", "signal-hook", "signal-hook-mio", "winapi", @@ -150,6 +171,10 @@ dependencies = [ [[package]] name = "fader-core" version = "0.1.0" +dependencies = [ + "proptest", + "thiserror", +] [[package]] name = "fader_master" @@ -162,12 +187,47 @@ dependencies = [ "volume_lib", ] +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "foldhash" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", +] + [[package]] name = "hashbrown" version = "0.15.5" @@ -240,6 +300,12 @@ version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + [[package]] name = "lock_api" version = "0.4.14" @@ -289,6 +355,15 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + [[package]] name = "num_threads" version = "0.1.7" @@ -298,6 +373,12 @@ dependencies = [ "libc", ] +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + [[package]] name = "parking_lot" version = "0.12.5" @@ -333,6 +414,15 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -342,6 +432,31 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "proptest" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744" +dependencies = [ + "bit-set", + "bit-vec", + "bitflags", + "num-traits", + "rand", + "rand_chacha", + "rand_xorshift", + "regex-syntax", + "rusty-fork", + "tempfile", + "unarray", +] + +[[package]] +name = "quick-error" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0" + [[package]] name = "quote" version = "1.0.47" @@ -351,6 +466,56 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_xorshift" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "513962919efc330f829edb2535844d1b912b0fbe2ca165d613e4e8788bb05a5a" +dependencies = [ + "rand_core", +] + [[package]] name = "ratatui" version = "0.29.0" @@ -383,6 +548,12 @@ dependencies = [ "bitflags", ] +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + [[package]] name = "rustix" version = "0.38.44" @@ -392,8 +563,21 @@ dependencies = [ "bitflags", "errno", "libc", - "linux-raw-sys", - "windows-sys 0.52.0", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", ] [[package]] @@ -402,6 +586,18 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "rusty-fork" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6bf79ff24e648f6da1f8d1f011e9cac26491b619e6b9280f2b47f1774e6ee2" +dependencies = [ + "fnv", + "quick-error", + "tempfile", + "wait-timeout", +] + [[package]] name = "ryu" version = "1.0.23" @@ -537,6 +733,39 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.5", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + [[package]] name = "time" version = "0.3.55" @@ -566,6 +795,12 @@ dependencies = [ "ratatui", ] +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + [[package]] name = "unicode-ident" version = "1.0.26" @@ -608,12 +843,30 @@ dependencies = [ "fader-core", ] +[[package]] +name = "wait-timeout" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ac3b126d3914f9849036f826e054cbabdc8519970b8998ddaf3b5bd3c65f11" +dependencies = [ + "libc", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + [[package]] name = "winapi" version = "0.3.9" @@ -644,9 +897,9 @@ checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" [[package]] name = "windows-sys" -version = "0.52.0" +version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ "windows-targets", ] @@ -723,3 +976,29 @@ name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "zerocopy" +version = "0.8.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6df92bf3d9227be3d53173901ddbffac2babc27ae50f397776ffd6dc33f800cb" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.59" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac4f328cf2f05d084e496c3e9c3f33ed0a183656a16e1fcec4d464d8373aec82" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] diff --git a/Cargo.toml b/Cargo.toml index 38def33..e08901e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ fader-config = { path = "config" } fader-core = { path = "core" } midi = { path = "midi" } ratatui = { version = "0.29.0", features = ["all-widgets", "serde"] } +thiserror = "2.0.21" tui = { path = "tui" } volume_lib = { path = "sound" } diff --git a/core/Cargo.toml b/core/Cargo.toml index ad42891..1de71d2 100644 --- a/core/Cargo.toml +++ b/core/Cargo.toml @@ -8,3 +8,7 @@ repository.workspace = true publish.workspace = true [dependencies] +thiserror.workspace = true + +[dev-dependencies] +proptest = "1.11.0" diff --git a/core/src/id.rs b/core/src/id.rs new file mode 100644 index 0000000..59f5a02 --- /dev/null +++ b/core/src/id.rs @@ -0,0 +1,156 @@ +use std::{fmt, str::FromStr}; + +use thiserror::Error; + +const MAX_ID_LENGTH: usize = 64; + +/// Why a stable user-defined identifier was rejected. +#[derive(Clone, Debug, Error, Eq, PartialEq)] +pub enum IdError { + /// The identifier was empty. + #[error("identifier must not be empty")] + Empty, + /// The identifier exceeded the stable storage limit. + #[error("identifier length {actual} exceeds the maximum {maximum}")] + TooLong { + /// Actual byte length. + actual: usize, + /// Maximum allowed byte length. + maximum: usize, + }, + /// The first character was not ASCII alphanumeric. + #[error("identifier must start with an ASCII letter or digit, found {found:?}")] + InvalidStart { + /// Invalid first character. + found: char, + }, + /// A later character was outside the durable identifier alphabet. + #[error("identifier contains invalid character {found:?} at position {position}")] + InvalidCharacter { + /// Zero-based character position. + position: usize, + /// Invalid character. + found: char, + }, +} + +fn validate(value: &str) -> Result<(), IdError> { + if value.is_empty() { + return Err(IdError::Empty); + } + if value.len() > MAX_ID_LENGTH { + return Err(IdError::TooLong { + actual: value.len(), + maximum: MAX_ID_LENGTH, + }); + } + + let mut characters = value.chars(); + let Some(first) = characters.next() else { + return Err(IdError::Empty); + }; + if !first.is_ascii_alphanumeric() { + return Err(IdError::InvalidStart { found: first }); + } + for (offset, character) in characters.enumerate() { + if !(character.is_ascii_alphanumeric() || matches!(character, '-' | '_')) { + return Err(IdError::InvalidCharacter { + position: offset + 1, + found: character, + }); + } + } + Ok(()) +} + +macro_rules! stable_id { + ($name:ident, $description:literal) => { + #[doc = $description] + #[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] + pub struct $name(String); + + impl $name { + /// Validates and constructs an identifier. + /// + /// # Errors + /// + /// Returns [`IdError`] when `value` is empty, too long, or outside + /// the portable `[A-Za-z0-9_-]` identifier alphabet. + pub fn new(value: impl Into) -> Result { + let value = value.into(); + validate(&value)?; + Ok(Self(value)) + } + + /// Returns the persisted string representation. + #[must_use] + pub fn as_str(&self) -> &str { + &self.0 + } + } + + impl fmt::Display for $name { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(&self.0) + } + } + + impl FromStr for $name { + type Err = IdError; + + fn from_str(value: &str) -> Result { + Self::new(value) + } + } + }; +} + +stable_id!( + ApplicationId, + "Stable identifier for a virtual application." +); +stable_id!(FaderId, "Stable identifier for a logical fader."); +stable_id!(GroupId, "Stable identifier for an application group."); +stable_id!(ProfileId, "Stable identifier for a configuration profile."); +stable_id!(SurfaceId, "Stable identifier for a physical MIDI surface."); + +#[cfg(test)] +mod tests { + use std::any::TypeId; + + use super::*; + + #[test] + fn accepts_portable_stable_ids() { + let id = ApplicationId::new("music-player_2").expect("valid application ID"); + assert_eq!(id.as_str(), "music-player_2"); + assert_eq!(id.to_string(), "music-player_2"); + } + + #[test] + fn rejects_invalid_ids_with_a_precise_reason() { + assert_eq!(GroupId::new(""), Err(IdError::Empty)); + assert_eq!( + GroupId::new("-group"), + Err(IdError::InvalidStart { found: '-' }) + ); + assert_eq!( + GroupId::new("group/name"), + Err(IdError::InvalidCharacter { + position: 5, + found: '/', + }) + ); + assert!(matches!( + GroupId::new("a".repeat(MAX_ID_LENGTH + 1)), + Err(IdError::TooLong { .. }) + )); + } + + #[test] + fn stable_id_types_cannot_be_interchanged() { + assert_ne!(TypeId::of::(), TypeId::of::()); + assert_ne!(TypeId::of::(), TypeId::of::()); + assert_ne!(TypeId::of::(), TypeId::of::()); + } +} diff --git a/core/src/lib.rs b/core/src/lib.rs index 0e16a67..493c3b2 100644 --- a/core/src/lib.rs +++ b/core/src/lib.rs @@ -4,3 +4,13 @@ //! native audio dependencies. #![forbid(unsafe_code)] + +mod id; +mod revision; +mod state; +mod volume; + +pub use id::{ApplicationId, FaderId, GroupId, IdError, ProfileId, SurfaceId}; +pub use revision::{BackendEpoch, Revision}; +pub use state::{Availability, Mute, ValueState}; +pub use volume::{ChannelGainError, ChannelGains, Gain, GainError}; diff --git a/core/src/revision.rs b/core/src/revision.rs new file mode 100644 index 0000000..fae3f19 --- /dev/null +++ b/core/src/revision.rs @@ -0,0 +1,75 @@ +/// Monotonic revision of domain-visible state. +#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub struct Revision(u64); + +impl Revision { + /// Initial revision before any accepted state change. + pub const INITIAL: Self = Self(0); + + /// Creates a revision from its persisted/wire representation. + #[must_use] + pub const fn new(value: u64) -> Self { + Self(value) + } + + /// Returns the numeric wire representation. + #[must_use] + pub const fn get(self) -> u64 { + self.0 + } + + /// Advances the revision, returning `None` rather than wrapping. + #[must_use] + pub const fn checked_next(self) -> Option { + match self.0.checked_add(1) { + Some(next) => Some(Self(next)), + None => None, + } + } +} + +/// Connection generation used to reject events from an obsolete backend. +#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)] +pub struct BackendEpoch(u64); + +impl BackendEpoch { + /// Initial epoch before the first connection is established. + pub const INITIAL: Self = Self(0); + + /// Creates an epoch from its numeric representation. + #[must_use] + pub const fn new(value: u64) -> Self { + Self(value) + } + + /// Returns the numeric representation. + #[must_use] + pub const fn get(self) -> u64 { + self.0 + } + + /// Advances the epoch, returning `None` rather than wrapping. + #[must_use] + pub const fn checked_next(self) -> Option { + match self.0.checked_add(1) { + Some(next) => Some(Self(next)), + None => None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn counters_advance_without_wrapping() { + assert_eq!(Revision::INITIAL.checked_next(), Some(Revision::new(1))); + assert_eq!(Revision::new(u64::MAX).checked_next(), None); + assert_eq!( + BackendEpoch::INITIAL.checked_next(), + Some(BackendEpoch::new(1)) + ); + assert_eq!(BackendEpoch::new(u64::MAX).checked_next(), None); + } +} diff --git a/core/src/state.rs b/core/src/state.rs new file mode 100644 index 0000000..c88a9e8 --- /dev/null +++ b/core/src/state.rs @@ -0,0 +1,42 @@ +/// Per-stream mute value, independent from gain. +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub enum Mute { + /// Audio is muted. + Muted, + /// Audio is not muted, even when its gain is zero. + Unmuted, +} + +/// Whether a configured object currently resolves to live resources. +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +pub enum Availability { + /// At least one live resource is available. + Online, + /// No live resource is currently available. + Offline, +} + +/// Aggregate state that preserves unavailable and heterogeneous values. +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ValueState { + /// No value is currently observable. + Unavailable, + /// Every resolved member has the same value. + Uniform(T), + /// Resolved members have different values. + Mixed, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn zero_gain_does_not_imply_mute() { + let gain_state = ValueState::Uniform(0_u8); + let mute_state = ValueState::Uniform(Mute::Unmuted); + + assert_eq!(gain_state, ValueState::Uniform(0)); + assert_eq!(mute_state, ValueState::Uniform(Mute::Unmuted)); + } +} diff --git a/core/src/volume.rs b/core/src/volume.rs new file mode 100644 index 0000000..32f0f86 --- /dev/null +++ b/core/src/volume.rs @@ -0,0 +1,218 @@ +use thiserror::Error; + +/// Why a scalar gain was rejected. +#[derive(Clone, Copy, Debug, Error, PartialEq)] +pub enum GainError { + /// NaN and infinities cannot represent observable audio state. + #[error("gain must be finite, found {0}")] + NonFinite(f64), + /// Negative amplitude is outside the domain. + #[error("gain must be non-negative, found {0}")] + Negative(f64), +} + +/// Finite, non-negative linear amplitude gain. +/// +/// `1.0` is unity and `0.0` is silence. Values above unity are representable +/// so external observations are not silently clamped; write paths apply their +/// configured ceiling separately. +#[derive(Clone, Copy, Debug, PartialEq, PartialOrd)] +pub struct Gain(f64); + +impl Gain { + /// Silence. + pub const SILENCE: Self = Self(0.0); + /// Unity gain. + pub const UNITY: Self = Self(1.0); + + /// Validates a linear amplitude value. + /// + /// # Errors + /// + /// Returns [`GainError`] for negative, NaN, or infinite values. + pub fn new(value: f64) -> Result { + if !value.is_finite() { + return Err(GainError::NonFinite(value)); + } + if value < 0.0 { + return Err(GainError::Negative(value)); + } + Ok(Self(value)) + } + + /// Returns the linear amplitude value. + #[must_use] + pub const fn get(self) -> f64 { + self.0 + } + + /// Returns whether this value represents silence. + #[must_use] + pub fn is_silent(self) -> bool { + self == Self::SILENCE + } +} + +/// Why a vector of channel gains or a balance-preserving operation failed. +#[derive(Clone, Debug, Error, PartialEq)] +pub enum ChannelGainError { + /// A stream must expose at least one channel. + #[error("channel gain vector must not be empty")] + Empty, + /// The requested maximum exceeds the configured write ceiling. + #[error("target gain {target} exceeds write ceiling {ceiling}")] + AboveWriteCeiling { + /// Requested output maximum. + target: f64, + /// Configured maximum write gain. + ceiling: f64, + }, + /// A calculated scalar failed gain validation. + #[error(transparent)] + InvalidGain(#[from] GainError), +} + +/// Non-empty per-channel gain snapshot. +#[derive(Clone, Debug, PartialEq)] +pub struct ChannelGains(Vec); + +impl ChannelGains { + /// Constructs a non-empty channel vector. + /// + /// # Errors + /// + /// Returns [`ChannelGainError::Empty`] when no channels are provided. + pub fn new(channels: Vec) -> Result { + if channels.is_empty() { + return Err(ChannelGainError::Empty); + } + Ok(Self(channels)) + } + + /// Returns the channel values. + #[must_use] + pub fn as_slice(&self) -> &[Gain] { + &self.0 + } + + /// Consumes the snapshot and returns its channel values. + #[must_use] + pub fn into_vec(self) -> Vec { + self.0 + } + + /// Returns the loudest channel. + #[must_use] + pub fn maximum(&self) -> Gain { + self.0 + .iter() + .copied() + .fold(Gain::SILENCE, |maximum, channel| { + if channel > maximum { channel } else { maximum } + }) + } + + /// Scales every channel so the loudest reaches `target`. + /// + /// Existing balance is preserved. An all-silent vector has no balance to + /// preserve, so every channel is initialized to `target`. + /// + /// # Errors + /// + /// Returns [`ChannelGainError::AboveWriteCeiling`] when `target` exceeds + /// `write_ceiling`. + pub fn scaled_to(&self, target: Gain, write_ceiling: Gain) -> Result { + if target > write_ceiling { + return Err(ChannelGainError::AboveWriteCeiling { + target: target.get(), + ceiling: write_ceiling.get(), + }); + } + + let old_maximum = self.maximum(); + if old_maximum.is_silent() { + return Ok(Self(vec![target; self.0.len()])); + } + + let channels = self + .0 + .iter() + .map(|channel| Gain::new((channel.get() / old_maximum.get()) * target.get())) + .collect::, _>>()?; + Ok(Self(channels)) + } +} + +#[cfg(test)] +mod tests { + use proptest::prelude::*; + + use super::*; + + fn gain(value: f64) -> Gain { + Gain::new(value).expect("test gain must be valid") + } + + #[test] + fn rejects_non_finite_and_negative_gain() { + assert!(matches!(Gain::new(f64::NAN), Err(GainError::NonFinite(_)))); + assert!(matches!( + Gain::new(f64::INFINITY), + Err(GainError::NonFinite(_)) + )); + assert_eq!(Gain::new(-0.01), Err(GainError::Negative(-0.01))); + assert_eq!(Gain::new(-0.0), Ok(Gain::SILENCE)); + } + + #[test] + fn initializes_silent_channels_equally() { + let channels = ChannelGains::new(vec![Gain::SILENCE, Gain::SILENCE]) + .expect("non-empty channel vector"); + let scaled = channels + .scaled_to(gain(0.75), Gain::UNITY) + .expect("target is below ceiling"); + + assert_eq!(scaled.as_slice(), &[gain(0.75), gain(0.75)]); + } + + #[test] + fn rejects_writes_above_the_explicit_ceiling() { + let channels = ChannelGains::new(vec![Gain::UNITY]).expect("non-empty channel vector"); + assert_eq!( + channels.scaled_to(gain(1.5), Gain::UNITY), + Err(ChannelGainError::AboveWriteCeiling { + target: 1.5, + ceiling: 1.0, + }) + ); + } + + proptest! { + #[test] + fn valid_gain_round_trips(value in 0.0_f64..=32.0) { + let value = Gain::new(value).expect("generated gain is valid"); + prop_assert!(value.get().is_finite()); + prop_assert!(value.get() >= 0.0); + } + + #[test] + fn scaling_preserves_balance( + left in 0.000_001_f64..=8.0, + right in 0.000_001_f64..=8.0, + target in 0.0_f64..=4.0, + ) { + let original = ChannelGains::new(vec![gain(left), gain(right)]) + .expect("generated vector is non-empty"); + let scaled = original + .scaled_to(gain(target), gain(4.0)) + .expect("generated target is within ceiling"); + + prop_assert!((scaled.maximum().get() - target).abs() <= f64::EPSILON * 8.0); + if target > 0.0 { + let original_ratio = left / right; + let scaled_ratio = scaled.as_slice()[0].get() / scaled.as_slice()[1].get(); + prop_assert!((original_ratio - scaled_ratio).abs() <= original_ratio.abs() * 1e-12 + 1e-12); + } + } + } +} diff --git a/task.md b/task.md index 32bbb4f..3d9dcfd 100644 --- a/task.md +++ b/task.md @@ -27,7 +27,7 @@ Dependencies: planning. Dependencies: M0. -- [ ] **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.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. - [ ] **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. - [ ] **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. - [ ] **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.