feat(M8.1): mix configured applications and groups
Tests: cargo test --locked -p fader_master --test live_mixer --all-features Tests: cargo test --locked -p fader_master --test ipc_frames --all-features Tests: cargo test --locked -p fader_master --test local_socket --all-features Tests: cargo test --locked -p tui --all-targets --all-features Lint: cargo clippy --locked -p fader_master -p tui --all-targets --all-features -- -D warnings
This commit is contained in:
parent
d21a57f4d5
commit
0a0be30651
|
|
@ -3,15 +3,22 @@ use std::io::{self, Read, Write};
|
|||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||
use thiserror::Error;
|
||||
|
||||
pub const PROTOCOL_VERSION: u16 = 1;
|
||||
pub const PROTOCOL_VERSION: u16 = 2;
|
||||
pub const MAX_FRAME_BYTES: usize = 64 * 1024;
|
||||
|
||||
/// Stable wire representation of an ephemeral stream handle.
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
|
||||
pub struct StreamKey {
|
||||
pub epoch: u64,
|
||||
pub backend_id: u64,
|
||||
pub incarnation: u64,
|
||||
/// Kind of mixer object addressed by a client.
|
||||
#[derive(Clone, Copy, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum MixerObjectKind {
|
||||
Application,
|
||||
Group,
|
||||
}
|
||||
|
||||
/// Stable configured mixer-object identity.
|
||||
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
|
||||
pub struct MixerObjectKey {
|
||||
pub kind: MixerObjectKind,
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
|
|
@ -26,12 +33,12 @@ pub struct ClientRequest {
|
|||
pub enum RequestCommand {
|
||||
Snapshot,
|
||||
SetVolume {
|
||||
stream: StreamKey,
|
||||
object: MixerObjectKey,
|
||||
gain: f64,
|
||||
expected_revision: u64,
|
||||
},
|
||||
ToggleMute {
|
||||
stream: StreamKey,
|
||||
object: MixerObjectKey,
|
||||
expected_revision: u64,
|
||||
},
|
||||
}
|
||||
|
|
@ -55,16 +62,18 @@ pub struct MixerSnapshot {
|
|||
pub revision: u64,
|
||||
pub backend: String,
|
||||
pub status: String,
|
||||
pub streams: Vec<MixerStream>,
|
||||
pub objects: Vec<MixerObject>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
pub struct MixerStream {
|
||||
pub stream: StreamKey,
|
||||
pub struct MixerObject {
|
||||
pub object: MixerObjectKey,
|
||||
pub label: String,
|
||||
pub process: Option<String>,
|
||||
pub gain: f64,
|
||||
pub muted: bool,
|
||||
pub detail: String,
|
||||
pub gain: Option<f64>,
|
||||
pub gain_mixed: bool,
|
||||
pub muted: Option<bool>,
|
||||
pub mute_mixed: bool,
|
||||
pub pending: bool,
|
||||
pub writable: bool,
|
||||
pub error: Option<String>,
|
||||
|
|
|
|||
|
|
@ -1,15 +1,17 @@
|
|||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use fader_config::Profile;
|
||||
use fader_core::{
|
||||
AdapterCommand, AdapterEvent, CommandOrigin, Gain, MetadataField, Mute, Revision,
|
||||
ServerCommand, ServerReducer, StreamHandle, StreamMetadata,
|
||||
AdapterCommand, AdapterEvent, ApplicationMatcher, ChannelGains, CommandOrigin, Gain, Mute,
|
||||
ServerCommand, ServerReducer, StreamHandle, StreamMetadata, ValueState, VolumeMode, mute_view,
|
||||
plan_volume, volume_view,
|
||||
};
|
||||
use thiserror::Error;
|
||||
use volume_lib::WorkerEvent;
|
||||
|
||||
use crate::ipc::{
|
||||
ClientRequest, MixerSnapshot, MixerStream, PROTOCOL_VERSION, RequestCommand, ResponseResult,
|
||||
ServerResponse, StreamKey,
|
||||
ClientRequest, MixerObject, MixerObjectKey, MixerObjectKind, MixerSnapshot, PROTOCOL_VERSION,
|
||||
RequestCommand, ResponseResult, ServerResponse,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
|
|
@ -18,11 +20,29 @@ struct MetadataView {
|
|||
writable: bool,
|
||||
}
|
||||
|
||||
/// Pure live-mixer state between the Pulse worker and IPC clients.
|
||||
#[derive(Clone, Debug)]
|
||||
struct ConfiguredApplication {
|
||||
id: String,
|
||||
label: String,
|
||||
matcher: ApplicationMatcher,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct ConfiguredGroup {
|
||||
id: String,
|
||||
label: String,
|
||||
members: Vec<String>,
|
||||
volume_mode: VolumeMode,
|
||||
}
|
||||
|
||||
/// Pure profile-aware mixer state between the audio worker and IPC clients.
|
||||
#[derive(Debug)]
|
||||
pub struct LiveMixerState {
|
||||
reducer: ServerReducer,
|
||||
metadata: BTreeMap<StreamHandle, MetadataView>,
|
||||
applications: Vec<ConfiguredApplication>,
|
||||
groups: Vec<ConfiguredGroup>,
|
||||
write_ceiling: Gain,
|
||||
backend: String,
|
||||
status: String,
|
||||
}
|
||||
|
|
@ -33,19 +53,58 @@ pub enum LiveMixerError {
|
|||
Reducer(#[from] fader_core::ReducerError),
|
||||
#[error(transparent)]
|
||||
Gain(#[from] fader_core::GainError),
|
||||
#[error(transparent)]
|
||||
Channels(#[from] fader_core::ChannelGainError),
|
||||
#[error(transparent)]
|
||||
Config(#[from] fader_config::ConfigError),
|
||||
#[error("unsupported IPC protocol version {actual}; expected {expected}")]
|
||||
Protocol { actual: u16, expected: u16 },
|
||||
#[error("stale revision {actual}; current revision is {current}")]
|
||||
StaleRevision { actual: u64, current: u64 },
|
||||
#[error("mixer object {kind:?} {id:?} is not configured")]
|
||||
UnknownObject { kind: MixerObjectKind, id: String },
|
||||
#[error("mixer object {kind:?} {id:?} is offline")]
|
||||
OfflineObject { kind: MixerObjectKind, id: String },
|
||||
#[error("mixer object {kind:?} {id:?} contains a read-only stream")]
|
||||
ReadOnlyObject { kind: MixerObjectKind, id: String },
|
||||
}
|
||||
|
||||
impl LiveMixerState {
|
||||
#[must_use]
|
||||
pub fn new(write_ceiling: Gain, backend: impl Into<String>) -> Self {
|
||||
Self {
|
||||
pub fn new(
|
||||
write_ceiling: Gain,
|
||||
backend: impl Into<String>,
|
||||
profile: &Profile,
|
||||
) -> Result<Self, LiveMixerError> {
|
||||
let applications = profile
|
||||
.applications()
|
||||
.iter()
|
||||
.map(|application| {
|
||||
Ok(ConfiguredApplication {
|
||||
id: application.id().to_owned(),
|
||||
label: application.label().to_owned(),
|
||||
matcher: application.matcher()?,
|
||||
})
|
||||
})
|
||||
.collect::<Result<_, LiveMixerError>>()?;
|
||||
let groups = profile
|
||||
.groups()
|
||||
.iter()
|
||||
.map(|group| ConfiguredGroup {
|
||||
id: group.id().to_owned(),
|
||||
label: group.label().to_owned(),
|
||||
members: group.members().to_vec(),
|
||||
volume_mode: group.volume_mode(),
|
||||
})
|
||||
.collect();
|
||||
Ok(Self {
|
||||
reducer: ServerReducer::new(write_ceiling),
|
||||
metadata: BTreeMap::new(),
|
||||
applications,
|
||||
groups,
|
||||
write_ceiling,
|
||||
backend: backend.into(),
|
||||
status: "connecting".to_owned(),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Applies one copied adapter event and returns any follow-up commands.
|
||||
|
|
@ -85,31 +144,32 @@ impl LiveMixerState {
|
|||
|
||||
#[must_use]
|
||||
pub fn snapshot(&self) -> MixerSnapshot {
|
||||
let streams = self
|
||||
.metadata
|
||||
.iter()
|
||||
.filter_map(|(handle, metadata)| {
|
||||
let view = self.reducer.view(*handle)?;
|
||||
Some(MixerStream {
|
||||
stream: key(*handle),
|
||||
label: stream_label(&metadata.metadata, *handle),
|
||||
process: metadata
|
||||
.metadata
|
||||
.value(MetadataField::ProcessBinary)
|
||||
.map(str::to_owned),
|
||||
gain: view.channels.maximum().get(),
|
||||
muted: view.muted == Mute::Muted,
|
||||
pending: view.pending,
|
||||
writable: metadata.writable,
|
||||
error: view.error,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut objects = Vec::with_capacity(self.applications.len() + self.groups.len());
|
||||
objects.extend(self.applications.iter().map(|application| {
|
||||
self.object_snapshot(
|
||||
MixerObjectKey {
|
||||
kind: MixerObjectKind::Application,
|
||||
id: application.id.clone(),
|
||||
},
|
||||
application.label.clone(),
|
||||
self.application_handles(&application.id),
|
||||
)
|
||||
}));
|
||||
objects.extend(self.groups.iter().map(|group| {
|
||||
self.object_snapshot(
|
||||
MixerObjectKey {
|
||||
kind: MixerObjectKind::Group,
|
||||
id: group.id.clone(),
|
||||
},
|
||||
group.label.clone(),
|
||||
self.group_handles(group),
|
||||
)
|
||||
}));
|
||||
MixerSnapshot {
|
||||
revision: self.reducer.revision().get(),
|
||||
backend: self.backend.clone(),
|
||||
status: self.status.clone(),
|
||||
streams,
|
||||
objects,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -123,53 +183,23 @@ impl LiveMixerState {
|
|||
expected: PROTOCOL_VERSION,
|
||||
});
|
||||
}
|
||||
let request_id = request.request_id;
|
||||
let commands = match request.command {
|
||||
RequestCommand::Snapshot => Vec::new(),
|
||||
RequestCommand::SetVolume {
|
||||
stream,
|
||||
object,
|
||||
gain,
|
||||
expected_revision,
|
||||
} => {
|
||||
self.reducer
|
||||
.command(ServerCommand::SetVolume {
|
||||
origin: CommandOrigin::Client {
|
||||
request: request.request_id,
|
||||
},
|
||||
expected_revision: Revision::new(expected_revision),
|
||||
stream: handle(stream),
|
||||
target: Gain::new(gain)?,
|
||||
})?
|
||||
.adapter
|
||||
}
|
||||
} => self.set_volume(object, Gain::new(gain)?, expected_revision, request_id)?,
|
||||
RequestCommand::ToggleMute {
|
||||
stream,
|
||||
object,
|
||||
expected_revision,
|
||||
} => {
|
||||
let stream = handle(stream);
|
||||
let current = self
|
||||
.reducer
|
||||
.view(stream)
|
||||
.ok_or(fader_core::ReducerError::Offline(stream))?;
|
||||
self.reducer
|
||||
.command(ServerCommand::SetMute {
|
||||
origin: CommandOrigin::Client {
|
||||
request: request.request_id,
|
||||
},
|
||||
expected_revision: Revision::new(expected_revision),
|
||||
stream,
|
||||
muted: if current.muted == Mute::Muted {
|
||||
Mute::Unmuted
|
||||
} else {
|
||||
Mute::Muted
|
||||
},
|
||||
})?
|
||||
.adapter
|
||||
}
|
||||
} => self.toggle_mute(object, expected_revision, request_id)?,
|
||||
};
|
||||
Ok((
|
||||
ServerResponse {
|
||||
version: PROTOCOL_VERSION,
|
||||
request_id: request.request_id,
|
||||
request_id,
|
||||
result: ResponseResult::Snapshot {
|
||||
snapshot: self.snapshot(),
|
||||
},
|
||||
|
|
@ -177,28 +207,195 @@ impl LiveMixerState {
|
|||
commands,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn key(handle: StreamHandle) -> StreamKey {
|
||||
StreamKey {
|
||||
epoch: handle.epoch().get(),
|
||||
backend_id: handle.backend_id(),
|
||||
incarnation: handle.incarnation(),
|
||||
fn application_handles(&self, id: &str) -> BTreeSet<StreamHandle> {
|
||||
let Some(application) = self.applications.iter().find(|item| item.id == id) else {
|
||||
return BTreeSet::new();
|
||||
};
|
||||
self.metadata
|
||||
.iter()
|
||||
.filter(|(_, metadata)| application.matcher.matches(&metadata.metadata))
|
||||
.filter_map(|(handle, _)| self.reducer.view(*handle).map(|_| *handle))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn group_handles(&self, group: &ConfiguredGroup) -> BTreeSet<StreamHandle> {
|
||||
group
|
||||
.members
|
||||
.iter()
|
||||
.flat_map(|member| self.application_handles(member))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn resolve(
|
||||
&self,
|
||||
object: &MixerObjectKey,
|
||||
) -> Result<(BTreeSet<StreamHandle>, VolumeMode), LiveMixerError> {
|
||||
match object.kind {
|
||||
MixerObjectKind::Application => self
|
||||
.applications
|
||||
.iter()
|
||||
.find(|application| application.id == object.id)
|
||||
.map(|_| (self.application_handles(&object.id), VolumeMode::Absolute)),
|
||||
MixerObjectKind::Group => self
|
||||
.groups
|
||||
.iter()
|
||||
.find(|group| group.id == object.id)
|
||||
.map(|group| (self.group_handles(group), group.volume_mode)),
|
||||
}
|
||||
.ok_or_else(|| LiveMixerError::UnknownObject {
|
||||
kind: object.kind,
|
||||
id: object.id.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
fn object_snapshot(
|
||||
&self,
|
||||
object: MixerObjectKey,
|
||||
label: String,
|
||||
handles: BTreeSet<StreamHandle>,
|
||||
) -> MixerObject {
|
||||
let views: Vec<_> = handles
|
||||
.iter()
|
||||
.filter_map(|handle| self.reducer.view(*handle))
|
||||
.collect();
|
||||
let channels: BTreeMap<_, _> = views
|
||||
.iter()
|
||||
.map(|view| (view.stream, view.channels.clone()))
|
||||
.collect();
|
||||
let volume = volume_view(&channels);
|
||||
let mute = mute_view(views.iter().map(|view| view.muted));
|
||||
let stream_count = views.len();
|
||||
MixerObject {
|
||||
object,
|
||||
label,
|
||||
detail: if stream_count == 0 {
|
||||
"offline".to_owned()
|
||||
} else if stream_count == 1 {
|
||||
"1 stream".to_owned()
|
||||
} else {
|
||||
format!("{stream_count} streams")
|
||||
},
|
||||
gain: volume.map(|view| view.maximum.get()),
|
||||
gain_mixed: volume.is_some_and(|view| view.mixed),
|
||||
muted: match mute {
|
||||
ValueState::Uniform(value) => Some(value == Mute::Muted),
|
||||
ValueState::Mixed | ValueState::Unavailable => None,
|
||||
},
|
||||
mute_mixed: mute == ValueState::Mixed,
|
||||
pending: views.iter().any(|view| view.pending),
|
||||
writable: !views.is_empty()
|
||||
&& handles.iter().all(|handle| {
|
||||
self.metadata
|
||||
.get(handle)
|
||||
.is_some_and(|metadata| metadata.writable)
|
||||
}),
|
||||
error: views.iter().find_map(|view| view.error.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
fn check_revision(&self, expected: u64) -> Result<(), LiveMixerError> {
|
||||
let current = self.reducer.revision().get();
|
||||
if current == expected {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(LiveMixerError::StaleRevision {
|
||||
actual: expected,
|
||||
current,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn writable_handles(
|
||||
&self,
|
||||
object: &MixerObjectKey,
|
||||
) -> Result<(BTreeSet<StreamHandle>, VolumeMode), LiveMixerError> {
|
||||
let (handles, mode) = self.resolve(object)?;
|
||||
if handles.is_empty() {
|
||||
return Err(LiveMixerError::OfflineObject {
|
||||
kind: object.kind,
|
||||
id: object.id.clone(),
|
||||
});
|
||||
}
|
||||
if handles.iter().any(|handle| {
|
||||
!self
|
||||
.metadata
|
||||
.get(handle)
|
||||
.is_some_and(|metadata| metadata.writable)
|
||||
}) {
|
||||
return Err(LiveMixerError::ReadOnlyObject {
|
||||
kind: object.kind,
|
||||
id: object.id.clone(),
|
||||
});
|
||||
}
|
||||
Ok((handles, mode))
|
||||
}
|
||||
|
||||
fn set_volume(
|
||||
&mut self,
|
||||
object: MixerObjectKey,
|
||||
target: Gain,
|
||||
expected_revision: u64,
|
||||
request: u64,
|
||||
) -> Result<Vec<AdapterCommand>, LiveMixerError> {
|
||||
self.check_revision(expected_revision)?;
|
||||
let (handles, mode) = self.writable_handles(&object)?;
|
||||
let observed: BTreeMap<_, ChannelGains> = handles
|
||||
.iter()
|
||||
.filter_map(|handle| {
|
||||
self.reducer
|
||||
.view(*handle)
|
||||
.map(|view| (*handle, view.channels))
|
||||
})
|
||||
.collect();
|
||||
let plan = plan_volume(&observed, mode, target, self.write_ceiling)?;
|
||||
let mut commands = Vec::with_capacity(plan.len());
|
||||
for (stream, channels) in plan {
|
||||
commands.extend(
|
||||
self.reducer
|
||||
.command(ServerCommand::SetVolume {
|
||||
origin: CommandOrigin::Client { request },
|
||||
expected_revision: self.reducer.revision(),
|
||||
stream,
|
||||
target: channels.maximum(),
|
||||
})?
|
||||
.adapter,
|
||||
);
|
||||
}
|
||||
Ok(commands)
|
||||
}
|
||||
|
||||
fn toggle_mute(
|
||||
&mut self,
|
||||
object: MixerObjectKey,
|
||||
expected_revision: u64,
|
||||
request: u64,
|
||||
) -> Result<Vec<AdapterCommand>, LiveMixerError> {
|
||||
self.check_revision(expected_revision)?;
|
||||
let (handles, _) = self.writable_handles(&object)?;
|
||||
let should_mute = handles.iter().any(|handle| {
|
||||
self.reducer
|
||||
.view(*handle)
|
||||
.is_some_and(|view| view.muted == Mute::Unmuted)
|
||||
});
|
||||
let muted = if should_mute {
|
||||
Mute::Muted
|
||||
} else {
|
||||
Mute::Unmuted
|
||||
};
|
||||
let mut commands = Vec::with_capacity(handles.len());
|
||||
for stream in handles {
|
||||
commands.extend(
|
||||
self.reducer
|
||||
.command(ServerCommand::SetMute {
|
||||
origin: CommandOrigin::Client { request },
|
||||
expected_revision: self.reducer.revision(),
|
||||
stream,
|
||||
muted,
|
||||
})?
|
||||
.adapter,
|
||||
);
|
||||
}
|
||||
Ok(commands)
|
||||
}
|
||||
}
|
||||
|
||||
fn handle(key: StreamKey) -> StreamHandle {
|
||||
StreamHandle::new(
|
||||
fader_core::BackendEpoch::new(key.epoch),
|
||||
key.backend_id,
|
||||
key.incarnation,
|
||||
)
|
||||
}
|
||||
|
||||
fn stream_label(metadata: &StreamMetadata, handle: StreamHandle) -> String {
|
||||
metadata
|
||||
.value(MetadataField::ApplicationName)
|
||||
.or_else(|| metadata.value(MetadataField::MediaName))
|
||||
.or_else(|| metadata.value(MetadataField::ProcessBinary))
|
||||
.map_or_else(|| format!("Stream {}", handle.backend_id()), str::to_owned)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ use std::{
|
|||
time::Duration,
|
||||
};
|
||||
|
||||
use fader_config::{XdgEnvironment, XdgPaths};
|
||||
use fader_config::{Profile, XdgEnvironment, XdgPaths};
|
||||
use fader_core::{BackendEpoch, Gain};
|
||||
use thiserror::Error;
|
||||
use volume_lib::PulseWorker;
|
||||
|
|
@ -164,11 +164,15 @@ pub struct LocalServer {
|
|||
}
|
||||
|
||||
impl LocalServer {
|
||||
pub fn pulse(socket: impl Into<PathBuf>, write_ceiling: Gain) -> Result<Self, LocalError> {
|
||||
pub fn pulse(
|
||||
socket: impl Into<PathBuf>,
|
||||
write_ceiling: Gain,
|
||||
profile: &Profile,
|
||||
) -> Result<Self, LocalError> {
|
||||
Ok(Self {
|
||||
listener: OwnedListener::bind(socket)?,
|
||||
worker: PulseWorker::spawn(BackendEpoch::new(1), 256),
|
||||
mixer: LiveMixerState::new(write_ceiling, "pulse"),
|
||||
mixer: LiveMixerState::new(write_ceiling, "pulse", profile)?,
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -80,7 +80,7 @@ fn serve(
|
|||
selected.backend,
|
||||
socket.display()
|
||||
);
|
||||
LocalServer::pulse(socket, Gain::new(profile.max_gain())?)?.run()?;
|
||||
LocalServer::pulse(socket, Gain::new(profile.max_gain())?, &profile)?.run()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -112,21 +112,22 @@ fn status(socket_override: Option<&Path>) -> Result<()> {
|
|||
snapshot.backend,
|
||||
snapshot.status,
|
||||
snapshot.revision,
|
||||
snapshot.streams.len()
|
||||
snapshot.objects.len()
|
||||
);
|
||||
for stream in snapshot.streams {
|
||||
for object in snapshot.objects {
|
||||
println!(
|
||||
"id={}:{}:{} label={:?} process={:?} gain={:.3} muted={} pending={} writable={} error={:?}",
|
||||
stream.stream.epoch,
|
||||
stream.stream.backend_id,
|
||||
stream.stream.incarnation,
|
||||
stream.label,
|
||||
stream.process,
|
||||
stream.gain,
|
||||
stream.muted,
|
||||
stream.pending,
|
||||
stream.writable,
|
||||
stream.error
|
||||
"kind={:?} id={:?} label={:?} detail={:?} gain={:?} gain_mixed={} muted={:?} mute_mixed={} pending={} writable={} error={:?}",
|
||||
object.object.kind,
|
||||
object.object.id,
|
||||
object.label,
|
||||
object.detail,
|
||||
object.gain,
|
||||
object.gain_mixed,
|
||||
object.muted,
|
||||
object.mute_mixed,
|
||||
object.pending,
|
||||
object.writable,
|
||||
object.error
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
|
|
|
|||
|
|
@ -1,9 +1,12 @@
|
|||
use std::{io, path::PathBuf};
|
||||
|
||||
use tui::{MixerClient, MixerItem, MixerSnapshot, StreamId};
|
||||
use tui::{MixerClient, MixerItem, MixerObjectId, MixerObjectKind, MixerSnapshot};
|
||||
|
||||
use crate::{
|
||||
ipc::{ClientRequest, PROTOCOL_VERSION, RequestCommand, ResponseResult, StreamKey},
|
||||
ipc::{
|
||||
ClientRequest, MixerObjectKey, MixerObjectKind as IpcObjectKind, PROTOCOL_VERSION,
|
||||
RequestCommand, ResponseResult,
|
||||
},
|
||||
local::client_request,
|
||||
};
|
||||
|
||||
|
|
@ -43,21 +46,25 @@ impl IpcMixerClient {
|
|||
backend: snapshot.backend,
|
||||
status: snapshot.status,
|
||||
items: snapshot
|
||||
.streams
|
||||
.objects
|
||||
.into_iter()
|
||||
.map(|stream| MixerItem {
|
||||
id: StreamId {
|
||||
epoch: stream.stream.epoch,
|
||||
backend_id: stream.stream.backend_id,
|
||||
incarnation: stream.stream.incarnation,
|
||||
.map(|object| MixerItem {
|
||||
id: MixerObjectId {
|
||||
kind: match object.object.kind {
|
||||
IpcObjectKind::Application => MixerObjectKind::Application,
|
||||
IpcObjectKind::Group => MixerObjectKind::Group,
|
||||
},
|
||||
id: object.object.id,
|
||||
},
|
||||
label: stream.label,
|
||||
process: stream.process,
|
||||
gain: stream.gain,
|
||||
muted: stream.muted,
|
||||
pending: stream.pending,
|
||||
writable: stream.writable,
|
||||
error: stream.error,
|
||||
label: object.label,
|
||||
detail: object.detail,
|
||||
gain: object.gain,
|
||||
gain_mixed: object.gain_mixed,
|
||||
muted: object.muted,
|
||||
mute_mixed: object.mute_mixed,
|
||||
pending: object.pending,
|
||||
writable: object.writable,
|
||||
error: object.error,
|
||||
})
|
||||
.collect(),
|
||||
}),
|
||||
|
|
@ -73,29 +80,35 @@ impl MixerClient for IpcMixerClient {
|
|||
|
||||
fn set_volume(
|
||||
&mut self,
|
||||
id: StreamId,
|
||||
id: MixerObjectId,
|
||||
gain: f64,
|
||||
expected_revision: u64,
|
||||
) -> io::Result<MixerSnapshot> {
|
||||
self.send(RequestCommand::SetVolume {
|
||||
stream: key(id),
|
||||
object: key(id),
|
||||
gain,
|
||||
expected_revision,
|
||||
})
|
||||
}
|
||||
|
||||
fn toggle_mute(&mut self, id: StreamId, expected_revision: u64) -> io::Result<MixerSnapshot> {
|
||||
fn toggle_mute(
|
||||
&mut self,
|
||||
id: MixerObjectId,
|
||||
expected_revision: u64,
|
||||
) -> io::Result<MixerSnapshot> {
|
||||
self.send(RequestCommand::ToggleMute {
|
||||
stream: key(id),
|
||||
object: key(id),
|
||||
expected_revision,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const fn key(id: StreamId) -> StreamKey {
|
||||
StreamKey {
|
||||
epoch: id.epoch,
|
||||
backend_id: id.backend_id,
|
||||
incarnation: id.incarnation,
|
||||
fn key(id: MixerObjectId) -> MixerObjectKey {
|
||||
MixerObjectKey {
|
||||
kind: match id.kind {
|
||||
MixerObjectKind::Application => IpcObjectKind::Application,
|
||||
MixerObjectKind::Group => IpcObjectKind::Group,
|
||||
},
|
||||
id: id.id,
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,8 @@
|
|||
use std::io::Cursor;
|
||||
|
||||
use fader_master::ipc::{
|
||||
ClientRequest, FrameError, MAX_FRAME_BYTES, PROTOCOL_VERSION, RequestCommand, StreamKey,
|
||||
read_frame, write_frame,
|
||||
ClientRequest, FrameError, MAX_FRAME_BYTES, MixerObjectKey, MixerObjectKind, PROTOCOL_VERSION,
|
||||
RequestCommand, read_frame, write_frame,
|
||||
};
|
||||
|
||||
fn request() -> ClientRequest {
|
||||
|
|
@ -10,10 +10,9 @@ fn request() -> ClientRequest {
|
|||
version: PROTOCOL_VERSION,
|
||||
request_id: 42,
|
||||
command: RequestCommand::SetVolume {
|
||||
stream: StreamKey {
|
||||
epoch: 2,
|
||||
backend_id: 9,
|
||||
incarnation: 3,
|
||||
object: MixerObjectKey {
|
||||
kind: MixerObjectKind::Application,
|
||||
id: "music".to_owned(),
|
||||
},
|
||||
gain: 0.25,
|
||||
expected_revision: 7,
|
||||
|
|
|
|||
|
|
@ -1,8 +1,12 @@
|
|||
use fader_config::Profile;
|
||||
use fader_core::{
|
||||
AdapterEvent, BackendEpoch, ChannelGains, Gain, Mute, StreamHandle, StreamMetadata,
|
||||
};
|
||||
use fader_master::{
|
||||
ipc::{ClientRequest, PROTOCOL_VERSION, RequestCommand, ResponseResult},
|
||||
ipc::{
|
||||
ClientRequest, MixerObjectKey, MixerObjectKind, PROTOCOL_VERSION, RequestCommand,
|
||||
ResponseResult,
|
||||
},
|
||||
live::LiveMixerState,
|
||||
};
|
||||
use volume_lib::WorkerEvent;
|
||||
|
|
@ -15,22 +19,32 @@ fn stream() -> StreamHandle {
|
|||
StreamHandle::new(BackendEpoch::new(1), 12, 1)
|
||||
}
|
||||
|
||||
fn observed(operation: Option<fader_core::OperationId>) -> WorkerEvent {
|
||||
fn observed_for(
|
||||
stream: StreamHandle,
|
||||
gain_values: [f64; 2],
|
||||
muted: Mute,
|
||||
operation: Option<fader_core::OperationId>,
|
||||
) -> WorkerEvent {
|
||||
WorkerEvent::Adapter(AdapterEvent::Observed {
|
||||
stream: stream(),
|
||||
channels: ChannelGains::new(vec![gain(0.4), gain(0.2)]).unwrap(),
|
||||
muted: Mute::Unmuted,
|
||||
stream,
|
||||
channels: ChannelGains::new(gain_values.into_iter().map(gain).collect()).unwrap(),
|
||||
muted,
|
||||
operation,
|
||||
})
|
||||
}
|
||||
|
||||
fn observed(operation: Option<fader_core::OperationId>) -> WorkerEvent {
|
||||
observed_for(stream(), [0.4, 0.2], Mute::Unmuted, operation)
|
||||
}
|
||||
|
||||
fn ready_state() -> LiveMixerState {
|
||||
let mut state = LiveMixerState::new(Gain::UNITY, "pulse");
|
||||
let profile = Profile::parse(include_str!("../../examples/profiles/desktop.toml")).unwrap();
|
||||
let mut state = LiveMixerState::new(Gain::UNITY, "pulse", &profile).unwrap();
|
||||
state
|
||||
.worker_event(WorkerEvent::StreamMetadata {
|
||||
stream: stream(),
|
||||
metadata: StreamMetadata::new()
|
||||
.with_application_name("Music")
|
||||
.with_application_name("Music Player")
|
||||
.with_process_binary("player"),
|
||||
volume_writable: true,
|
||||
})
|
||||
|
|
@ -43,15 +57,19 @@ fn ready_state() -> LiveMixerState {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn observations_publish_labeled_revisioned_streams() {
|
||||
fn observations_publish_configured_objects_and_offline_state() {
|
||||
let state = ready_state();
|
||||
let snapshot = state.snapshot();
|
||||
assert_eq!(snapshot.status, "ready");
|
||||
assert_eq!(snapshot.streams.len(), 1);
|
||||
assert_eq!(snapshot.streams[0].label, "Music");
|
||||
assert_eq!(snapshot.streams[0].process.as_deref(), Some("player"));
|
||||
assert_eq!(snapshot.streams[0].gain, 0.4);
|
||||
assert!(!snapshot.streams[0].muted);
|
||||
assert_eq!(snapshot.objects.len(), 3);
|
||||
assert_eq!(snapshot.objects[0].label, "Music");
|
||||
assert_eq!(snapshot.objects[0].gain, Some(0.4));
|
||||
assert_eq!(snapshot.objects[0].muted, Some(false));
|
||||
assert_eq!(snapshot.objects[1].label, "Browser");
|
||||
assert_eq!(snapshot.objects[1].gain, None);
|
||||
assert_eq!(snapshot.objects[1].detail, "offline");
|
||||
assert_eq!(snapshot.objects[2].label, "Media");
|
||||
assert_eq!(snapshot.objects[2].gain, Some(0.4));
|
||||
assert!(snapshot.revision > 0);
|
||||
}
|
||||
|
||||
|
|
@ -59,11 +77,12 @@ fn observations_publish_labeled_revisioned_streams() {
|
|||
fn client_volume_is_pending_until_correlated_readback() {
|
||||
let mut state = ready_state();
|
||||
let snapshot = state.snapshot();
|
||||
let object = snapshot.objects[0].object.clone();
|
||||
let request = ClientRequest {
|
||||
version: PROTOCOL_VERSION,
|
||||
request_id: 8,
|
||||
command: RequestCommand::SetVolume {
|
||||
stream: snapshot.streams[0].stream,
|
||||
object,
|
||||
gain: 0.75,
|
||||
expected_revision: snapshot.revision,
|
||||
},
|
||||
|
|
@ -71,7 +90,7 @@ fn client_volume_is_pending_until_correlated_readback() {
|
|||
let (response, commands) = state.request(request).unwrap();
|
||||
assert_eq!(commands.len(), 1);
|
||||
assert!(matches!(response.result, ResponseResult::Snapshot { .. }));
|
||||
assert!(state.snapshot().streams[0].pending);
|
||||
assert!(state.snapshot().objects[0].pending);
|
||||
|
||||
let operation = match commands[0] {
|
||||
fader_core::AdapterCommand::SetVolume { operation, .. } => operation,
|
||||
|
|
@ -87,22 +106,61 @@ fn client_volume_is_pending_until_correlated_readback() {
|
|||
[fader_core::AdapterCommand::Readback { .. }]
|
||||
));
|
||||
state.worker_event(observed(Some(operation))).unwrap();
|
||||
assert!(!state.snapshot().streams[0].pending);
|
||||
assert!(!state.snapshot().objects[0].pending);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_client_revision_is_rejected_for_resnapshot() {
|
||||
let mut state = ready_state();
|
||||
let stream = state.snapshot().streams[0].stream;
|
||||
let error = state
|
||||
.request(ClientRequest {
|
||||
version: PROTOCOL_VERSION,
|
||||
request_id: 9,
|
||||
command: RequestCommand::ToggleMute {
|
||||
stream,
|
||||
object: MixerObjectKey {
|
||||
kind: MixerObjectKind::Application,
|
||||
id: "music".to_owned(),
|
||||
},
|
||||
expected_revision: 0,
|
||||
},
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(error.to_string().contains("stale revision"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn group_aggregates_mixed_members_and_fans_out_one_action() {
|
||||
let mut state = ready_state();
|
||||
let browser = StreamHandle::new(BackendEpoch::new(1), 13, 1);
|
||||
state
|
||||
.worker_event(WorkerEvent::StreamMetadata {
|
||||
stream: browser,
|
||||
metadata: StreamMetadata::new().with_process_binary("firefox"),
|
||||
volume_writable: true,
|
||||
})
|
||||
.unwrap();
|
||||
state
|
||||
.worker_event(observed_for(browser, [0.7, 0.7], Mute::Muted, None))
|
||||
.unwrap();
|
||||
|
||||
let snapshot = state.snapshot();
|
||||
let group = &snapshot.objects[2];
|
||||
assert_eq!(group.detail, "2 streams");
|
||||
assert_eq!(group.gain, Some(0.7));
|
||||
assert!(group.gain_mixed);
|
||||
assert_eq!(group.muted, None);
|
||||
assert!(group.mute_mixed);
|
||||
|
||||
let (_, volume_commands) = state
|
||||
.request(ClientRequest {
|
||||
version: PROTOCOL_VERSION,
|
||||
request_id: 10,
|
||||
command: RequestCommand::SetVolume {
|
||||
object: group.object.clone(),
|
||||
gain: 0.6,
|
||||
expected_revision: snapshot.revision,
|
||||
},
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(volume_commands.len(), 2);
|
||||
}
|
||||
|
|
|
|||
136
tui/src/lib.rs
136
tui/src/lib.rs
|
|
@ -16,20 +16,27 @@ use ratatui::{
|
|||
const VOLUME_STEP: f64 = 0.05;
|
||||
const REFRESH_INTERVAL: Duration = Duration::from_millis(100);
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct StreamId {
|
||||
pub epoch: u64,
|
||||
pub backend_id: u64,
|
||||
pub incarnation: u64,
|
||||
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||
pub enum MixerObjectKind {
|
||||
Application,
|
||||
Group,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||
pub struct MixerObjectId {
|
||||
pub kind: MixerObjectKind,
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct MixerItem {
|
||||
pub id: StreamId,
|
||||
pub id: MixerObjectId,
|
||||
pub label: String,
|
||||
pub process: Option<String>,
|
||||
pub gain: f64,
|
||||
pub muted: bool,
|
||||
pub detail: String,
|
||||
pub gain: Option<f64>,
|
||||
pub gain_mixed: bool,
|
||||
pub muted: Option<bool>,
|
||||
pub mute_mixed: bool,
|
||||
pub pending: bool,
|
||||
pub writable: bool,
|
||||
pub error: Option<String>,
|
||||
|
|
@ -48,11 +55,15 @@ pub trait MixerClient {
|
|||
fn snapshot(&mut self) -> io::Result<MixerSnapshot>;
|
||||
fn set_volume(
|
||||
&mut self,
|
||||
id: StreamId,
|
||||
id: MixerObjectId,
|
||||
gain: f64,
|
||||
expected_revision: u64,
|
||||
) -> io::Result<MixerSnapshot>;
|
||||
fn toggle_mute(&mut self, id: StreamId, expected_revision: u64) -> io::Result<MixerSnapshot>;
|
||||
fn toggle_mute(
|
||||
&mut self,
|
||||
id: MixerObjectId,
|
||||
expected_revision: u64,
|
||||
) -> io::Result<MixerSnapshot>;
|
||||
}
|
||||
|
||||
/// Runs the live terminal client and restores terminal state on every return.
|
||||
|
|
@ -117,7 +128,11 @@ impl<C: MixerClient> LiveTui<C> {
|
|||
}
|
||||
|
||||
fn replace_snapshot(&mut self, snapshot: MixerSnapshot) {
|
||||
let selected_id = self.snapshot.items.get(self.selected).map(|item| item.id);
|
||||
let selected_id = self
|
||||
.snapshot
|
||||
.items
|
||||
.get(self.selected)
|
||||
.map(|item| item.id.clone());
|
||||
self.snapshot = snapshot;
|
||||
self.selected = selected_id
|
||||
.and_then(|id| self.snapshot.items.iter().position(|item| item.id == id))
|
||||
|
|
@ -155,7 +170,9 @@ impl<C: MixerClient> LiveTui<C> {
|
|||
|
||||
fn change_volume(&mut self, delta: f64) {
|
||||
if let Some(item) = self.snapshot.items.get(self.selected) {
|
||||
self.set_selected_volume((item.gain + delta).clamp(0.0, 1.0));
|
||||
if let Some(gain) = item.gain {
|
||||
self.set_selected_volume((gain + delta).clamp(0.0, 1.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -164,12 +181,12 @@ impl<C: MixerClient> LiveTui<C> {
|
|||
return;
|
||||
};
|
||||
if !item.writable {
|
||||
self.client_error = Some("selected stream is read-only".to_owned());
|
||||
self.client_error = Some("selected object is offline or read-only".to_owned());
|
||||
return;
|
||||
}
|
||||
match self
|
||||
.client
|
||||
.set_volume(item.id, gain, self.snapshot.revision)
|
||||
.set_volume(item.id.clone(), gain, self.snapshot.revision)
|
||||
{
|
||||
Ok(snapshot) => self.replace_snapshot(snapshot),
|
||||
Err(error) => self.client_error = Some(error.to_string()),
|
||||
|
|
@ -180,7 +197,14 @@ impl<C: MixerClient> LiveTui<C> {
|
|||
let Some(item) = self.snapshot.items.get(self.selected) else {
|
||||
return;
|
||||
};
|
||||
match self.client.toggle_mute(item.id, self.snapshot.revision) {
|
||||
if !item.writable {
|
||||
self.client_error = Some("selected object is offline or read-only".to_owned());
|
||||
return;
|
||||
}
|
||||
match self
|
||||
.client
|
||||
.toggle_mute(item.id.clone(), self.snapshot.revision)
|
||||
{
|
||||
Ok(snapshot) => self.replace_snapshot(snapshot),
|
||||
Err(error) => self.client_error = Some(error.to_string()),
|
||||
}
|
||||
|
|
@ -275,13 +299,14 @@ impl<C> LiveTui<C> {
|
|||
}
|
||||
let selected = index == self.selected;
|
||||
let title = format!(
|
||||
"{} {}{}{}",
|
||||
"{} {} [{} · {}]{}",
|
||||
if selected { "▶" } else { " " },
|
||||
item.label,
|
||||
item.process
|
||||
.as_deref()
|
||||
.map(|process| format!(" [{process}]"))
|
||||
.unwrap_or_default(),
|
||||
match item.id.kind {
|
||||
MixerObjectKind::Application => "application",
|
||||
MixerObjectKind::Group => "group",
|
||||
},
|
||||
item.detail,
|
||||
if item.pending { " … pending" } else { "" }
|
||||
);
|
||||
let block = Block::bordered().title(title).border_style(if selected {
|
||||
|
|
@ -291,8 +316,14 @@ impl<C> LiveTui<C> {
|
|||
});
|
||||
let meter = block.inner(row_area);
|
||||
block.render(row_area, buf);
|
||||
let percent = (item.gain.clamp(0.0, 1.0) * 100.0).round() as u16;
|
||||
let state = if item.muted {
|
||||
let percent = item
|
||||
.gain
|
||||
.map_or(0, |gain| (gain.clamp(0.0, 1.0) * 100.0).round() as u16);
|
||||
let state = if item.gain.is_none() {
|
||||
"OFFLINE"
|
||||
} else if item.mute_mixed || item.gain_mixed {
|
||||
"MIXED"
|
||||
} else if item.muted == Some(true) {
|
||||
"MUTED"
|
||||
} else if !item.writable {
|
||||
"READ ONLY"
|
||||
|
|
@ -304,7 +335,7 @@ impl<C> LiveTui<C> {
|
|||
|error| format!("ERROR: {error}"),
|
||||
);
|
||||
Gauge::default()
|
||||
.gauge_style(Style::default().fg(if item.muted {
|
||||
.gauge_style(Style::default().fg(if item.muted == Some(true) {
|
||||
Color::Yellow
|
||||
} else {
|
||||
Color::Cyan
|
||||
|
|
@ -330,15 +361,16 @@ impl DemoClient {
|
|||
backend: "demo".into(),
|
||||
status: "preview".into(),
|
||||
items: vec![MixerItem {
|
||||
id: StreamId {
|
||||
epoch: 1,
|
||||
backend_id: 1,
|
||||
incarnation: 1,
|
||||
id: MixerObjectId {
|
||||
kind: MixerObjectKind::Application,
|
||||
id: "desktop".into(),
|
||||
},
|
||||
label: "Desktop audio".into(),
|
||||
process: None,
|
||||
gain: if self.revision == 0 { 0.65 } else { self.gain },
|
||||
muted: self.muted,
|
||||
detail: "1 stream".into(),
|
||||
gain: Some(if self.revision == 0 { 0.65 } else { self.gain }),
|
||||
gain_mixed: false,
|
||||
muted: Some(self.muted),
|
||||
mute_mixed: false,
|
||||
pending: false,
|
||||
writable: true,
|
||||
error: None,
|
||||
|
|
@ -354,7 +386,7 @@ impl MixerClient for DemoClient {
|
|||
|
||||
fn set_volume(
|
||||
&mut self,
|
||||
_id: StreamId,
|
||||
_id: MixerObjectId,
|
||||
gain: f64,
|
||||
_expected_revision: u64,
|
||||
) -> io::Result<MixerSnapshot> {
|
||||
|
|
@ -363,7 +395,11 @@ impl MixerClient for DemoClient {
|
|||
Ok(self.view())
|
||||
}
|
||||
|
||||
fn toggle_mute(&mut self, _id: StreamId, _expected_revision: u64) -> io::Result<MixerSnapshot> {
|
||||
fn toggle_mute(
|
||||
&mut self,
|
||||
_id: MixerObjectId,
|
||||
_expected_revision: u64,
|
||||
) -> io::Result<MixerSnapshot> {
|
||||
self.revision += 1;
|
||||
self.muted = !self.muted;
|
||||
Ok(self.view())
|
||||
|
|
@ -382,9 +418,9 @@ mod tests {
|
|||
fn volume_and_mute_keys_update_through_the_client() {
|
||||
let mut app = LiveTui::new(DemoClient::default()).unwrap();
|
||||
app.handle_key_event(press(KeyCode::End));
|
||||
assert_eq!(app.snapshot.items[0].gain, 1.0);
|
||||
assert_eq!(app.snapshot.items[0].gain, Some(1.0));
|
||||
app.handle_key_event(press(KeyCode::Char('m')));
|
||||
assert!(app.snapshot.items[0].muted);
|
||||
assert_eq!(app.snapshot.items[0].muted, Some(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -413,4 +449,34 @@ mod tests {
|
|||
assert!(rendered.contains("65%"));
|
||||
assert!(rendered.contains("Q/Esc"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_and_offline_objects_render_without_panicking_at_small_sizes() {
|
||||
let mut app = LiveTui::new(DemoClient::default()).unwrap();
|
||||
app.snapshot.items[0].gain_mixed = true;
|
||||
app.snapshot.items.push(MixerItem {
|
||||
id: MixerObjectId {
|
||||
kind: MixerObjectKind::Group,
|
||||
id: "offline".into(),
|
||||
},
|
||||
label: "Offline group".into(),
|
||||
detail: "offline".into(),
|
||||
gain: None,
|
||||
gain_mixed: false,
|
||||
muted: None,
|
||||
mute_mixed: false,
|
||||
pending: false,
|
||||
writable: false,
|
||||
error: None,
|
||||
});
|
||||
let area = Rect::new(0, 0, 48, 11);
|
||||
let mut buffer = Buffer::empty(area);
|
||||
(&app).render(area, &mut buffer);
|
||||
let rendered = buffer
|
||||
.content
|
||||
.iter()
|
||||
.map(|cell| cell.symbol())
|
||||
.collect::<String>();
|
||||
assert!(rendered.contains("MIXED"));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue