feat(M4.5): control the default output master
Add a first-class default-output target across the profile, Pulse worker, live mixer, IPC, and TUI. Route APC CC 56 / Note 98 to Master and move Media to CC 50 / Note 66.\n\nTests: cargo test --workspace --all-targets --all-features\nTests: cargo test --workspace --doc --all-features\nTests: cargo clippy --workspace --all-targets --all-features -- -D warnings\nTests: cargo build --workspace --release --all-features\nTests: default, no-default-feature, and individual backend matrix passed
This commit is contained in:
parent
9648fdf5db
commit
fda38f6f17
|
|
@ -72,9 +72,9 @@ converts software volumes through `VolumeLinear`; it does not parse `pactl`.
|
|||
|
||||
## Purpose and scope
|
||||
|
||||
Run a per-user Linux server that receives controls from multiple USB MIDI surfaces, records requested state, resolves virtual application/group targets, and dispatches volume/mute commands through one selected audio adapter. Observe external audio changes and send confirmed state to every relevant TUI and MIDI output.
|
||||
Run a per-user Linux server that receives controls from multiple USB MIDI surfaces, records requested state, resolves virtual application/group/default-output targets, and dispatches volume/mute commands through one selected audio adapter. Observe external audio changes and send confirmed state to every relevant TUI and MIDI output.
|
||||
|
||||
The MVP controls application playback streams, not microphone capture, routing, DSP, or audio samples. An application may have zero, one, or many streams. ALSA hardware mixer targets are an explicit extension, not a substitute for application control.
|
||||
The MVP controls application playback streams and the selected backend's default output sink, not microphone capture, routing, DSP, or audio samples. An application may have zero, one, or many streams. The output target follows the server's current default sink and remains distinct from ALSA hardware mixer elements, which are an explicit extension rather than a substitute for application control.
|
||||
|
||||
## Structure
|
||||
|
||||
|
|
@ -111,7 +111,7 @@ All outer crates depend inward on domain contracts; core depends on none of them
|
|||
## Domain model and matching
|
||||
|
||||
- `SurfaceId`, `FaderId`, `ApplicationId`, `GroupId`, and `ProfileId` are stable persisted user IDs. Renaming a display label preserves its ID.
|
||||
- A physical binding is `(surface ID, MIDI channel, message kind, control number) -> fader ID + action`. A logical fader targets exactly one `Application` or `Group` (later `HardwareMixer`). Several faders/surfaces may target the same object.
|
||||
- A physical binding is `(surface ID, MIDI channel, message kind, control number) -> fader ID + action`. A logical fader targets exactly one `Application`, `Group`, or the `default` output (later, an explicit `HardwareMixer`). Several faders/surfaces may target the same object.
|
||||
- An application object has selectors on explicit normalized fields: `application.name`, `application.id`, `application.process.binary`, or `media.name`. Preserve raw backend metadata for inspection. Never silently substitute one field for another.
|
||||
- Matchers are `exact` (case-sensitive whole-string equality) or `regex` (Rust regex syntax, substring search unless anchored). Multiple selectors for an application are ORed. Missing properties do not match. Compile patterns once at config validation, with length/complexity limits; show actual matches in the editor.
|
||||
- A matching application controls all its current playback streams. Stopped applications remain configured and display offline; new streams are discovered dynamically. Runtime handles include backend connection epoch plus object ID and an incarnation where needed to prevent ID-reuse bugs. PIDs, backend indices, and discovery order are never durable identity.
|
||||
|
|
@ -159,7 +159,7 @@ Subscribe before enumeration, buffer intervening events, and reconcile using an
|
|||
|
||||
| Adapter | Scope and selection |
|
||||
| --- | --- |
|
||||
| `pulse` | First implementation. Enumerate playback sink inputs, read properties/channel volumes/mute, change volume/mute, subscribe to changes. Supports PulseAudio and PipeWire's PulseAudio-compatible service. Native PipeWire-only stream coverage needs explicit testing; do not claim completeness. |
|
||||
| `pulse` | First implementation. Enumerate playback sink inputs plus the current default output sink; read channel volumes/mute, change them, and subscribe to both stream and default-output changes. Supports PulseAudio and PipeWire's PulseAudio-compatible service. Native PipeWire-only stream coverage needs explicit testing; do not claim completeness. |
|
||||
| `pipewire` | Native playback stream discovery and SPA parameter control/observation. Implement after a spike proves writable parameters, correct linear gain/mute handling, metadata, and reconnect behavior with the active session manager. |
|
||||
| `alsa-mixer` | Optional explicit hardware mixer targets only; report playback switch/mute support per element. Reject application/group targets requiring application discovery. Never silently fall back to system Master volume. |
|
||||
|
||||
|
|
|
|||
|
|
@ -130,6 +130,7 @@ pub struct Surface {
|
|||
pub enum TargetKind {
|
||||
Application,
|
||||
Group,
|
||||
Output,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
|
|
@ -139,7 +140,7 @@ struct Target {
|
|||
id: String,
|
||||
}
|
||||
|
||||
/// A logical fader targeting one application or group.
|
||||
/// A logical fader targeting one application, group, or audio output.
|
||||
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Fader {
|
||||
|
|
@ -616,6 +617,7 @@ fn validate_profile_members(raw: &RawProfile) -> Result<(), ConfigError> {
|
|||
let found = match fader.target.kind {
|
||||
TargetKind::Application => applications.contains_key(&fader.target.id),
|
||||
TargetKind::Group => groups.contains_key(&fader.target.id),
|
||||
TargetKind::Output => fader.target.id == "default",
|
||||
};
|
||||
if !found {
|
||||
return Err(ConfigError::validation(
|
||||
|
|
|
|||
|
|
@ -80,10 +80,10 @@ fn arch_pipewire_profile_matches_reported_qobuz_metadata() {
|
|||
assert_eq!(surface.usb_vendor_id(), Some("09e8"));
|
||||
assert_eq!(surface.usb_product_id(), Some("0028"));
|
||||
assert_eq!(surface.usb_serial(), Some("Ver00.10"));
|
||||
assert_eq!(profile.faders().len(), 3);
|
||||
assert_eq!(profile.bindings().len(), 6);
|
||||
assert_eq!(profile.faders().len(), 4);
|
||||
assert_eq!(profile.bindings().len(), 8);
|
||||
assert_eq!(profile.bindings()[0].number(), 48);
|
||||
assert_eq!(profile.bindings()[5].number(), 98);
|
||||
assert_eq!(profile.bindings()[7].number(), 98);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -109,6 +109,12 @@ fn rejects_dangling_references_and_duplicate_physical_bindings() {
|
|||
let missing_target = EXAMPLE.replace("id = \"media\" }", "id = \"missing\" }");
|
||||
assert_error_contains(Profile::parse(&missing_target), "faders[0].target.id");
|
||||
|
||||
let unknown_output = ARCH_PIPEWIRE.replace(
|
||||
"target = { kind = \"output\", id = \"default\" }",
|
||||
"target = { kind = \"output\", id = \"headphones\" }",
|
||||
);
|
||||
assert_error_contains(Profile::parse(&unknown_output), "faders[3].target.id");
|
||||
|
||||
let duplicate = EXAMPLE.replace(
|
||||
"kind = \"note\", channel = 1, number = 32",
|
||||
"kind = \"cc\", channel = 1, number = 0",
|
||||
|
|
|
|||
|
|
@ -57,6 +57,12 @@ target = { kind = "group", id = "media" }
|
|||
pickup = true
|
||||
pickup_tolerance = 0.02
|
||||
|
||||
[[faders]]
|
||||
id = "master-fader"
|
||||
target = { kind = "output", id = "default" }
|
||||
pickup = true
|
||||
pickup_tolerance = 0.02
|
||||
|
||||
[[bindings]]
|
||||
surface = "apc-mini"
|
||||
fader = "music-fader"
|
||||
|
|
@ -73,6 +79,12 @@ message = { kind = "cc", channel = 1, number = 49 }
|
|||
surface = "apc-mini"
|
||||
fader = "media-fader"
|
||||
action = "volume"
|
||||
message = { kind = "cc", channel = 1, number = 50 }
|
||||
|
||||
[[bindings]]
|
||||
surface = "apc-mini"
|
||||
fader = "master-fader"
|
||||
action = "volume"
|
||||
message = { kind = "cc", channel = 1, number = 56 }
|
||||
|
||||
[[bindings]]
|
||||
|
|
@ -94,4 +106,11 @@ surface = "apc-mini"
|
|||
fader = "media-fader"
|
||||
action = "toggle_mute"
|
||||
edge = "press"
|
||||
message = { kind = "note", channel = 1, number = 66 }
|
||||
|
||||
[[bindings]]
|
||||
surface = "apc-mini"
|
||||
fader = "master-fader"
|
||||
action = "toggle_mute"
|
||||
edge = "press"
|
||||
message = { kind = "note", channel = 1, number = 98 }
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ use std::io::{self, Read, Write};
|
|||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||
use thiserror::Error;
|
||||
|
||||
pub const PROTOCOL_VERSION: u16 = 2;
|
||||
pub const PROTOCOL_VERSION: u16 = 3;
|
||||
pub const MAX_FRAME_BYTES: usize = 64 * 1024;
|
||||
|
||||
/// Kind of mixer object addressed by a client.
|
||||
|
|
@ -12,6 +12,7 @@ pub const MAX_FRAME_BYTES: usize = 64 * 1024;
|
|||
pub enum MixerObjectKind {
|
||||
Application,
|
||||
Group,
|
||||
Output,
|
||||
}
|
||||
|
||||
/// Stable configured mixer-object identity.
|
||||
|
|
|
|||
|
|
@ -43,6 +43,13 @@ struct ConfiguredFader {
|
|||
tolerance: f64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct OutputView {
|
||||
stream: StreamHandle,
|
||||
label: String,
|
||||
writable: bool,
|
||||
}
|
||||
|
||||
/// Pure profile-aware mixer state between the audio worker and IPC clients.
|
||||
#[derive(Debug)]
|
||||
pub struct LiveMixerState {
|
||||
|
|
@ -50,6 +57,8 @@ pub struct LiveMixerState {
|
|||
metadata: BTreeMap<StreamHandle, MetadataView>,
|
||||
applications: Vec<ConfiguredApplication>,
|
||||
groups: Vec<ConfiguredGroup>,
|
||||
has_default_output: bool,
|
||||
output: Option<OutputView>,
|
||||
faders: BTreeMap<FaderId, ConfiguredFader>,
|
||||
pickups: BTreeMap<(SurfaceId, FaderId), Pickup>,
|
||||
devices: Vec<MidiDevice>,
|
||||
|
|
@ -113,7 +122,7 @@ impl LiveMixerState {
|
|||
volume_mode: group.volume_mode(),
|
||||
})
|
||||
.collect();
|
||||
let faders = profile
|
||||
let faders: BTreeMap<FaderId, ConfiguredFader> = profile
|
||||
.faders()
|
||||
.iter()
|
||||
.map(|fader| {
|
||||
|
|
@ -127,6 +136,7 @@ impl LiveMixerState {
|
|||
MixerObjectKind::Application
|
||||
}
|
||||
fader_config::TargetKind::Group => MixerObjectKind::Group,
|
||||
fader_config::TargetKind::Output => MixerObjectKind::Output,
|
||||
},
|
||||
id: fader.target_id().to_owned(),
|
||||
},
|
||||
|
|
@ -136,11 +146,16 @@ impl LiveMixerState {
|
|||
))
|
||||
})
|
||||
.collect::<Result<_, LiveMixerError>>()?;
|
||||
let has_default_output = faders
|
||||
.values()
|
||||
.any(|fader| fader.target.kind == MixerObjectKind::Output);
|
||||
Ok(Self {
|
||||
reducer: ServerReducer::new(write_ceiling),
|
||||
metadata: BTreeMap::new(),
|
||||
applications,
|
||||
groups,
|
||||
has_default_output,
|
||||
output: None,
|
||||
faders,
|
||||
pickups: BTreeMap::new(),
|
||||
devices: Vec::new(),
|
||||
|
|
@ -172,6 +187,17 @@ impl LiveMixerState {
|
|||
},
|
||||
);
|
||||
}
|
||||
WorkerEvent::OutputMetadata {
|
||||
stream,
|
||||
label,
|
||||
volume_writable,
|
||||
} => {
|
||||
self.output = Some(OutputView {
|
||||
stream,
|
||||
label,
|
||||
writable: volume_writable,
|
||||
});
|
||||
}
|
||||
WorkerEvent::Adapter(event) => {
|
||||
let affected_faders = match &event {
|
||||
AdapterEvent::Observed {
|
||||
|
|
@ -184,6 +210,13 @@ impl LiveMixerState {
|
|||
};
|
||||
if let AdapterEvent::StreamRemoved { stream } = &event {
|
||||
self.metadata.remove(stream);
|
||||
if self
|
||||
.output
|
||||
.as_ref()
|
||||
.is_some_and(|output| output.stream == *stream)
|
||||
{
|
||||
self.output = None;
|
||||
}
|
||||
}
|
||||
let commands = self.reducer.event(event)?.adapter;
|
||||
self.rearm_faders(&affected_faders);
|
||||
|
|
@ -198,7 +231,9 @@ impl LiveMixerState {
|
|||
|
||||
#[must_use]
|
||||
pub fn snapshot(&self) -> MixerSnapshot {
|
||||
let mut objects = Vec::with_capacity(self.applications.len() + self.groups.len());
|
||||
let mut objects = Vec::with_capacity(
|
||||
self.applications.len() + self.groups.len() + usize::from(self.has_default_output),
|
||||
);
|
||||
objects.extend(self.applications.iter().map(|application| {
|
||||
self.object_snapshot(
|
||||
MixerObjectKey {
|
||||
|
|
@ -219,6 +254,27 @@ impl LiveMixerState {
|
|||
self.group_handles(group),
|
||||
)
|
||||
}));
|
||||
if self.has_default_output {
|
||||
let handles = self
|
||||
.output
|
||||
.as_ref()
|
||||
.map(|output| BTreeSet::from([output.stream]))
|
||||
.unwrap_or_default();
|
||||
let mut output = self.object_snapshot(
|
||||
MixerObjectKey {
|
||||
kind: MixerObjectKind::Output,
|
||||
id: "default".to_owned(),
|
||||
},
|
||||
"Master".to_owned(),
|
||||
handles,
|
||||
);
|
||||
output.detail = self
|
||||
.output
|
||||
.as_ref()
|
||||
.map(|output| output.label.clone())
|
||||
.unwrap_or_else(|| "offline".to_owned());
|
||||
objects.push(output);
|
||||
}
|
||||
MixerSnapshot {
|
||||
revision: self.reducer.revision().get(),
|
||||
backend: self.backend.clone(),
|
||||
|
|
@ -439,6 +495,17 @@ impl LiveMixerState {
|
|||
.iter()
|
||||
.find(|group| group.id == object.id)
|
||||
.map(|group| (self.group_handles(group), group.volume_mode)),
|
||||
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,
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
.ok_or_else(|| LiveMixerError::UnknownObject {
|
||||
kind: object.kind,
|
||||
|
|
@ -482,15 +549,21 @@ impl LiveMixerState {
|
|||
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)
|
||||
}),
|
||||
&& handles.iter().all(|handle| self.handle_writable(*handle)),
|
||||
error: views.iter().find_map(|view| view.error.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_writable(&self, handle: StreamHandle) -> bool {
|
||||
self.metadata
|
||||
.get(&handle)
|
||||
.is_some_and(|metadata| metadata.writable)
|
||||
|| self
|
||||
.output
|
||||
.as_ref()
|
||||
.is_some_and(|output| output.stream == handle && output.writable)
|
||||
}
|
||||
|
||||
fn check_revision(&self, expected: u64) -> Result<(), LiveMixerError> {
|
||||
let current = self.reducer.revision().get();
|
||||
if current == expected {
|
||||
|
|
@ -514,12 +587,7 @@ impl LiveMixerState {
|
|||
id: object.id.clone(),
|
||||
});
|
||||
}
|
||||
if handles.iter().any(|handle| {
|
||||
!self
|
||||
.metadata
|
||||
.get(handle)
|
||||
.is_some_and(|metadata| metadata.writable)
|
||||
}) {
|
||||
if handles.iter().any(|handle| !self.handle_writable(*handle)) {
|
||||
return Err(LiveMixerError::ReadOnlyObject {
|
||||
kind: object.kind,
|
||||
id: object.id.clone(),
|
||||
|
|
|
|||
|
|
@ -288,5 +288,42 @@ mod tests {
|
|||
mute,
|
||||
Some(MidiIntent::ToggleMute { fader, .. }) if fader.as_str() == "music-fader"
|
||||
));
|
||||
let media = runtime.router.route(
|
||||
&surface,
|
||||
MidiMessage::ControlChange {
|
||||
channel: MidiChannel::new(1).unwrap(),
|
||||
number: MidiData::new(50).unwrap(),
|
||||
value: MidiData::new(64).unwrap(),
|
||||
},
|
||||
);
|
||||
assert!(matches!(
|
||||
media,
|
||||
Some(MidiIntent::AbsoluteVolume { fader, .. }) if fader.as_str() == "media-fader"
|
||||
));
|
||||
let master = runtime.router.route(
|
||||
&surface,
|
||||
MidiMessage::ControlChange {
|
||||
channel: MidiChannel::new(1).unwrap(),
|
||||
number: MidiData::new(56).unwrap(),
|
||||
value: MidiData::new(64).unwrap(),
|
||||
},
|
||||
);
|
||||
assert!(matches!(
|
||||
master,
|
||||
Some(MidiIntent::AbsoluteVolume { fader, .. }) if fader.as_str() == "master-fader"
|
||||
));
|
||||
let master_mute = runtime.router.route(
|
||||
&surface,
|
||||
MidiMessage::Note {
|
||||
channel: MidiChannel::new(1).unwrap(),
|
||||
number: MidiData::new(98).unwrap(),
|
||||
velocity: MidiData::new(127).unwrap(),
|
||||
edge: ButtonEdge::Press,
|
||||
},
|
||||
);
|
||||
assert!(matches!(
|
||||
master_mute,
|
||||
Some(MidiIntent::ToggleMute { fader, .. }) if fader.as_str() == "master-fader"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -53,6 +53,7 @@ impl IpcMixerClient {
|
|||
kind: match object.object.kind {
|
||||
IpcObjectKind::Application => MixerObjectKind::Application,
|
||||
IpcObjectKind::Group => MixerObjectKind::Group,
|
||||
IpcObjectKind::Output => MixerObjectKind::Output,
|
||||
},
|
||||
id: object.object.id,
|
||||
},
|
||||
|
|
@ -108,6 +109,7 @@ fn key(id: MixerObjectId) -> MixerObjectKey {
|
|||
kind: match id.kind {
|
||||
MixerObjectKind::Application => IpcObjectKind::Application,
|
||||
MixerObjectKind::Group => IpcObjectKind::Group,
|
||||
MixerObjectKind::Output => IpcObjectKind::Output,
|
||||
},
|
||||
id: id.id,
|
||||
}
|
||||
|
|
|
|||
|
|
@ -277,3 +277,42 @@ fn controller_disconnect_forgets_the_tracked_physical_position() {
|
|||
assert!(state.midi_intent(intent(0.2), 2).unwrap().is_empty());
|
||||
assert_eq!(state.midi_intent(intent(0.4), 3).unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_output_is_visible_and_master_fader_uses_pickup() {
|
||||
let profile =
|
||||
Profile::parse(include_str!("../../examples/profiles/arch-pipewire.toml")).unwrap();
|
||||
let mut state = LiveMixerState::new(Gain::UNITY, "pulse", &profile).unwrap();
|
||||
let output = StreamHandle::new(BackendEpoch::new(1), 1_u64 << 63, 1);
|
||||
state
|
||||
.worker_event(WorkerEvent::OutputMetadata {
|
||||
stream: output,
|
||||
label: "Scarlett Solo".to_owned(),
|
||||
volume_writable: true,
|
||||
})
|
||||
.unwrap();
|
||||
state
|
||||
.worker_event(observed_for(output, [0.6, 0.4], Mute::Unmuted, None))
|
||||
.unwrap();
|
||||
|
||||
let snapshot = state.snapshot();
|
||||
let master = snapshot.objects.last().unwrap();
|
||||
assert_eq!(master.object.kind, MixerObjectKind::Output);
|
||||
assert_eq!(master.label, "Master");
|
||||
assert_eq!(master.detail, "Scarlett Solo");
|
||||
assert_eq!(master.gain, Some(0.6));
|
||||
|
||||
let surface = SurfaceId::new("apc-mini").unwrap();
|
||||
let fader = FaderId::new("master-fader").unwrap();
|
||||
let intent = |value| MidiIntent::AbsoluteVolume {
|
||||
surface: surface.clone(),
|
||||
fader: fader.clone(),
|
||||
gain: gain(value),
|
||||
};
|
||||
assert!(state.midi_intent(intent(0.2), 1).unwrap().is_empty());
|
||||
let commands = state.midi_intent(intent(0.6), 2).unwrap();
|
||||
assert!(matches!(
|
||||
commands.as_slice(),
|
||||
[fader_core::AdapterCommand::SetVolume { stream, .. }] if *stream == output
|
||||
));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -132,6 +132,11 @@ fn watch(client: &mut PulseClient, duration: Duration) -> Result<(), Box<dyn Err
|
|||
print_stream(&stream);
|
||||
}
|
||||
Some(PulseNotification::Removed(index)) => println!("removed index={index}"),
|
||||
Some(
|
||||
PulseNotification::OutputChanged(_)
|
||||
| PulseNotification::OutputRemoved(_)
|
||||
| PulseNotification::DefaultOutputChanged(_),
|
||||
) => {}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,7 +14,9 @@ pub use policy::{
|
|||
SelectionPolicy, SelectionPolicyError, TargetRequirements, TargetScope, select_adapter,
|
||||
};
|
||||
#[cfg(feature = "pulse")]
|
||||
pub use pulse::{PulseClient, PulseError, PulseNotification, PulseServerIdentity, PulseStream};
|
||||
pub use pulse::{
|
||||
PulseClient, PulseError, PulseNotification, PulseOutput, PulseServerIdentity, PulseStream,
|
||||
};
|
||||
#[cfg(feature = "pulse")]
|
||||
pub use pulse_worker::PulseWorker;
|
||||
|
||||
|
|
@ -49,6 +51,11 @@ pub enum WorkerEvent {
|
|||
metadata: fader_core::StreamMetadata,
|
||||
volume_writable: bool,
|
||||
},
|
||||
OutputMetadata {
|
||||
stream: StreamHandle,
|
||||
label: String,
|
||||
volume_writable: bool,
|
||||
},
|
||||
Adapter(AdapterEvent),
|
||||
SnapshotEnd(BackendEpoch),
|
||||
Disconnected {
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ use pulse::{
|
|||
use thiserror::Error;
|
||||
|
||||
const OPERATION_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
type NotificationQueue = Rc<RefCell<std::collections::VecDeque<(Operation, u32)>>>;
|
||||
type NotificationQueue = Rc<RefCell<std::collections::VecDeque<(Facility, Operation, u32)>>>;
|
||||
|
||||
/// Copied PulseAudio playback-stream information.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
|
|
@ -30,6 +30,16 @@ pub struct PulseStream {
|
|||
pub volume_writable: bool,
|
||||
}
|
||||
|
||||
/// Copied state of one PulseAudio output sink.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct PulseOutput {
|
||||
pub index: u32,
|
||||
pub name: String,
|
||||
pub label: String,
|
||||
pub channels: ChannelGains,
|
||||
pub muted: Mute,
|
||||
}
|
||||
|
||||
/// Copied identity reported by the connected PulseAudio-compatible server.
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct PulseServerIdentity {
|
||||
|
|
@ -43,6 +53,9 @@ pub enum PulseNotification {
|
|||
Added(PulseStream),
|
||||
Changed(PulseStream),
|
||||
Removed(u32),
|
||||
OutputChanged(PulseOutput),
|
||||
OutputRemoved(u32),
|
||||
DefaultOutputChanged(Option<PulseOutput>),
|
||||
}
|
||||
|
||||
/// Failures at the Pulse protocol boundary.
|
||||
|
|
@ -66,6 +79,8 @@ pub enum PulseError {
|
|||
MissingStream(u32),
|
||||
#[error("sink input {0} does not expose writable volume")]
|
||||
ReadOnlyStream(u32),
|
||||
#[error("output sink is unavailable")]
|
||||
MissingOutput,
|
||||
#[error("PulseAudio rejected the operation")]
|
||||
Rejected,
|
||||
#[error("invalid PulseAudio channel volume: {0}")]
|
||||
|
|
@ -110,18 +125,25 @@ impl PulseClient {
|
|||
let callback = Rc::clone(¬ifications);
|
||||
self.context
|
||||
.set_subscribe_callback(Some(Box::new(move |facility, operation, index| {
|
||||
if facility == Some(Facility::SinkInput)
|
||||
&& let Some(operation) = operation
|
||||
if let (Some(facility), Some(operation)) = (facility, operation)
|
||||
&& matches!(
|
||||
facility,
|
||||
Facility::SinkInput | Facility::Sink | Facility::Server
|
||||
)
|
||||
{
|
||||
callback.borrow_mut().push_back((operation, index));
|
||||
callback
|
||||
.borrow_mut()
|
||||
.push_back((facility, operation, index));
|
||||
}
|
||||
})));
|
||||
let subscribed = Rc::new(RefCell::new(None));
|
||||
let result = Rc::clone(&subscribed);
|
||||
self.context
|
||||
.subscribe(InterestMaskSet::SINK_INPUT, move |success| {
|
||||
self.context.subscribe(
|
||||
InterestMaskSet::SINK_INPUT | InterestMaskSet::SINK | InterestMaskSet::SERVER,
|
||||
move |success| {
|
||||
*result.borrow_mut() = Some(success);
|
||||
});
|
||||
},
|
||||
);
|
||||
self.wait_for(|| subscribed.borrow().is_some())?;
|
||||
if subscribed.borrow().is_none_or(|success| !success) {
|
||||
return Err(PulseError::Rejected);
|
||||
|
|
@ -151,21 +173,41 @@ impl PulseClient {
|
|||
}
|
||||
self.iterate(deadline)?;
|
||||
}
|
||||
let Some((operation, index)) = notifications.borrow_mut().pop_front() else {
|
||||
let Some((facility, operation, index)) = notifications.borrow_mut().pop_front() else {
|
||||
return Ok(None);
|
||||
};
|
||||
match operation {
|
||||
Operation::Removed => Ok(Some(PulseNotification::Removed(index))),
|
||||
Operation::New => match self.stream(index) {
|
||||
Ok(stream) => Ok(Some(PulseNotification::Added(stream))),
|
||||
Err(PulseError::MissingStream(_)) => Ok(Some(PulseNotification::Removed(index))),
|
||||
Err(error) => Err(error),
|
||||
match facility {
|
||||
Facility::SinkInput => match operation {
|
||||
Operation::Removed => Ok(Some(PulseNotification::Removed(index))),
|
||||
Operation::New => match self.stream(index) {
|
||||
Ok(stream) => Ok(Some(PulseNotification::Added(stream))),
|
||||
Err(PulseError::MissingStream(_)) => {
|
||||
Ok(Some(PulseNotification::Removed(index)))
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
},
|
||||
Operation::Changed => match self.stream(index) {
|
||||
Ok(stream) => Ok(Some(PulseNotification::Changed(stream))),
|
||||
Err(PulseError::MissingStream(_)) => {
|
||||
Ok(Some(PulseNotification::Removed(index)))
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
},
|
||||
},
|
||||
Operation::Changed => match self.stream(index) {
|
||||
Ok(stream) => Ok(Some(PulseNotification::Changed(stream))),
|
||||
Err(PulseError::MissingStream(_)) => Ok(Some(PulseNotification::Removed(index))),
|
||||
Err(error) => Err(error),
|
||||
Facility::Sink => match operation {
|
||||
Operation::Removed => Ok(Some(PulseNotification::OutputRemoved(index))),
|
||||
Operation::New | Operation::Changed => match self.output(index) {
|
||||
Ok(output) => Ok(Some(PulseNotification::OutputChanged(output))),
|
||||
Err(PulseError::MissingOutput) => {
|
||||
Ok(Some(PulseNotification::OutputRemoved(index)))
|
||||
}
|
||||
Err(error) => Err(error),
|
||||
},
|
||||
},
|
||||
Facility::Server => Ok(Some(PulseNotification::DefaultOutputChanged(
|
||||
self.default_output()?,
|
||||
))),
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -209,6 +251,108 @@ impl PulseClient {
|
|||
result.borrow_mut().take().ok_or(PulseError::Introspection)
|
||||
}
|
||||
|
||||
/// Reads the server's current default output sink.
|
||||
pub fn default_output(&mut self) -> Result<Option<PulseOutput>, PulseError> {
|
||||
let result = Rc::new(RefCell::new(None));
|
||||
let callback = Rc::clone(&result);
|
||||
self.context.introspect().get_server_info(move |info| {
|
||||
*callback.borrow_mut() = Some(info.default_sink_name.as_deref().map(str::to_owned));
|
||||
});
|
||||
self.wait_for(|| result.borrow().is_some())?;
|
||||
let Some(name) = result.borrow_mut().take().flatten() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let sink = Rc::new(RefCell::new(ListState::<PulseOutput>::default()));
|
||||
let callback = Rc::clone(&sink);
|
||||
self.context
|
||||
.introspect()
|
||||
.get_sink_info_by_name(&name, move |item| match item {
|
||||
ListResult::Item(info) => match copy_output(info) {
|
||||
Ok(output) => callback.borrow_mut().items.push(output),
|
||||
Err(error) => callback.borrow_mut().error = Some(error),
|
||||
},
|
||||
ListResult::End => callback.borrow_mut().done = true,
|
||||
ListResult::Error => {
|
||||
let mut callback = callback.borrow_mut();
|
||||
callback.error = Some(PulseError::MissingOutput);
|
||||
callback.done = true;
|
||||
}
|
||||
});
|
||||
self.wait_for(|| sink.borrow().done)?;
|
||||
let mut sink = sink.borrow_mut();
|
||||
if let Some(error) = sink.error.take() {
|
||||
return Err(error);
|
||||
}
|
||||
Ok(sink.items.pop())
|
||||
}
|
||||
|
||||
/// Reads one output sink by index.
|
||||
pub fn output(&mut self, index: u32) -> Result<PulseOutput, PulseError> {
|
||||
let result = Rc::new(RefCell::new(ListState::<PulseOutput>::default()));
|
||||
let callback = Rc::clone(&result);
|
||||
self.context
|
||||
.introspect()
|
||||
.get_sink_info_by_index(index, move |item| match item {
|
||||
ListResult::Item(info) => match copy_output(info) {
|
||||
Ok(output) => callback.borrow_mut().items.push(output),
|
||||
Err(error) => callback.borrow_mut().error = Some(error),
|
||||
},
|
||||
ListResult::End => callback.borrow_mut().done = true,
|
||||
ListResult::Error => {
|
||||
let mut callback = callback.borrow_mut();
|
||||
callback.error = Some(PulseError::MissingOutput);
|
||||
callback.done = true;
|
||||
}
|
||||
});
|
||||
self.wait_for(|| result.borrow().done)?;
|
||||
let mut result = result.borrow_mut();
|
||||
if let Some(error) = result.error.take() {
|
||||
return Err(error);
|
||||
}
|
||||
result.items.pop().ok_or(PulseError::MissingOutput)
|
||||
}
|
||||
|
||||
/// Writes default-output channel gains, then reads confirmed state.
|
||||
pub fn set_output_volume(
|
||||
&mut self,
|
||||
index: u32,
|
||||
channels: &ChannelGains,
|
||||
) -> Result<PulseOutput, PulseError> {
|
||||
let native = to_native_channels(channels)?;
|
||||
let result = Rc::new(RefCell::new(None));
|
||||
let callback = Rc::clone(&result);
|
||||
self.context.introspect().set_sink_volume_by_index(
|
||||
index,
|
||||
&native,
|
||||
Some(Box::new(move |success| {
|
||||
*callback.borrow_mut() = Some(success)
|
||||
})),
|
||||
);
|
||||
self.wait_for(|| result.borrow().is_some())?;
|
||||
if result.borrow().is_none_or(|success| !success) {
|
||||
return Err(PulseError::Rejected);
|
||||
}
|
||||
self.output(index)
|
||||
}
|
||||
|
||||
/// Writes default-output mute, then reads confirmed state.
|
||||
pub fn set_output_mute(&mut self, index: u32, muted: Mute) -> Result<PulseOutput, PulseError> {
|
||||
let result = Rc::new(RefCell::new(None));
|
||||
let callback = Rc::clone(&result);
|
||||
self.context.introspect().set_sink_mute_by_index(
|
||||
index,
|
||||
muted == Mute::Muted,
|
||||
Some(Box::new(move |success| {
|
||||
*callback.borrow_mut() = Some(success)
|
||||
})),
|
||||
);
|
||||
self.wait_for(|| result.borrow().is_some())?;
|
||||
if result.borrow().is_none_or(|success| !success) {
|
||||
return Err(PulseError::Rejected);
|
||||
}
|
||||
self.output(index)
|
||||
}
|
||||
|
||||
/// Reads one sink input after a write or subscription notification.
|
||||
pub fn stream(&mut self, index: u32) -> Result<PulseStream, PulseError> {
|
||||
let result = Rc::new(RefCell::new(ListState::<PulseStream>::default()));
|
||||
|
|
@ -397,6 +541,34 @@ fn copy_stream(
|
|||
})
|
||||
}
|
||||
|
||||
fn copy_output(info: &pulse::context::introspect::SinkInfo<'_>) -> Result<PulseOutput, PulseError> {
|
||||
let gains = info
|
||||
.volume
|
||||
.get()
|
||||
.iter()
|
||||
.copied()
|
||||
.map(|volume| Gain::new(VolumeLinear::from(volume).0))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|error| PulseError::Volume(error.to_string()))?;
|
||||
Ok(PulseOutput {
|
||||
index: info.index,
|
||||
name: info.name.as_deref().unwrap_or("unknown-output").to_owned(),
|
||||
label: info
|
||||
.description
|
||||
.as_deref()
|
||||
.or(info.name.as_deref())
|
||||
.unwrap_or("Default output")
|
||||
.to_owned(),
|
||||
channels: ChannelGains::new(gains)
|
||||
.map_err(|error| PulseError::Volume(error.to_string()))?,
|
||||
muted: if info.mute {
|
||||
Mute::Muted
|
||||
} else {
|
||||
Mute::Unmuted
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn to_native_channels(channels: &ChannelGains) -> Result<ChannelVolumes, PulseError> {
|
||||
let count = u8::try_from(channels.as_slice().len())
|
||||
.map_err(|error| PulseError::Volume(error.to_string()))?;
|
||||
|
|
|
|||
|
|
@ -12,7 +12,8 @@ use std::{
|
|||
use fader_core::{AdapterCommand, AdapterEvent, BackendEpoch, OperationId, StreamHandle};
|
||||
|
||||
use crate::{
|
||||
AdapterCapabilities, PulseClient, PulseError, PulseNotification, PulseStream, WorkerEvent,
|
||||
AdapterCapabilities, PulseClient, PulseError, PulseNotification, PulseOutput, PulseStream,
|
||||
WorkerEvent,
|
||||
};
|
||||
|
||||
const NOTIFICATION_POLL: Duration = Duration::from_millis(10);
|
||||
|
|
@ -21,6 +22,8 @@ trait PulseConnection {
|
|||
fn subscribe(&mut self) -> Result<(), PulseError>;
|
||||
fn streams(&mut self) -> Result<Vec<PulseStream>, PulseError>;
|
||||
fn stream(&mut self, index: u32) -> Result<PulseStream, PulseError>;
|
||||
fn default_output(&mut self) -> Result<Option<PulseOutput>, PulseError>;
|
||||
fn output(&mut self, index: u32) -> Result<PulseOutput, PulseError>;
|
||||
fn poll_notification(
|
||||
&mut self,
|
||||
timeout: Duration,
|
||||
|
|
@ -31,6 +34,16 @@ trait PulseConnection {
|
|||
channels: &fader_core::ChannelGains,
|
||||
) -> Result<PulseStream, PulseError>;
|
||||
fn set_mute(&mut self, index: u32, muted: fader_core::Mute) -> Result<PulseStream, PulseError>;
|
||||
fn set_output_volume(
|
||||
&mut self,
|
||||
index: u32,
|
||||
channels: &fader_core::ChannelGains,
|
||||
) -> Result<PulseOutput, PulseError>;
|
||||
fn set_output_mute(
|
||||
&mut self,
|
||||
index: u32,
|
||||
muted: fader_core::Mute,
|
||||
) -> Result<PulseOutput, PulseError>;
|
||||
}
|
||||
|
||||
impl PulseConnection for PulseClient {
|
||||
|
|
@ -46,6 +59,14 @@ impl PulseConnection for PulseClient {
|
|||
Self::stream(self, index)
|
||||
}
|
||||
|
||||
fn default_output(&mut self) -> Result<Option<PulseOutput>, PulseError> {
|
||||
Self::default_output(self)
|
||||
}
|
||||
|
||||
fn output(&mut self, index: u32) -> Result<PulseOutput, PulseError> {
|
||||
Self::output(self, index)
|
||||
}
|
||||
|
||||
fn poll_notification(
|
||||
&mut self,
|
||||
timeout: Duration,
|
||||
|
|
@ -64,6 +85,22 @@ impl PulseConnection for PulseClient {
|
|||
fn set_mute(&mut self, index: u32, muted: fader_core::Mute) -> Result<PulseStream, PulseError> {
|
||||
Self::set_mute(self, index, muted)
|
||||
}
|
||||
|
||||
fn set_output_volume(
|
||||
&mut self,
|
||||
index: u32,
|
||||
channels: &fader_core::ChannelGains,
|
||||
) -> Result<PulseOutput, PulseError> {
|
||||
Self::set_output_volume(self, index, channels)
|
||||
}
|
||||
|
||||
fn set_output_mute(
|
||||
&mut self,
|
||||
index: u32,
|
||||
muted: fader_core::Mute,
|
||||
) -> Result<PulseOutput, PulseError> {
|
||||
Self::set_output_mute(self, index, muted)
|
||||
}
|
||||
}
|
||||
|
||||
struct EventLane {
|
||||
|
|
@ -131,6 +168,61 @@ impl StreamTracker {
|
|||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct OutputTracker {
|
||||
epoch: BackendEpoch,
|
||||
next_incarnation: u64,
|
||||
current: Option<(u32, StreamHandle)>,
|
||||
}
|
||||
|
||||
impl OutputTracker {
|
||||
fn new(epoch: BackendEpoch) -> Self {
|
||||
Self {
|
||||
epoch,
|
||||
next_incarnation: 1,
|
||||
current: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn replace(
|
||||
&mut self,
|
||||
index: u32,
|
||||
) -> Result<(Option<StreamHandle>, StreamHandle), &'static str> {
|
||||
if let Some((current_index, handle)) = self.current
|
||||
&& current_index == index
|
||||
{
|
||||
return Ok((None, handle));
|
||||
}
|
||||
let removed = self.current.map(|(_, handle)| handle);
|
||||
let incarnation = self.next_incarnation;
|
||||
self.next_incarnation = self
|
||||
.next_incarnation
|
||||
.checked_add(1)
|
||||
.ok_or("Pulse output incarnation counter exhausted")?;
|
||||
let handle = StreamHandle::new(self.epoch, (1_u64 << 63) | u64::from(index), incarnation);
|
||||
self.current = Some((index, handle));
|
||||
Ok((removed, handle))
|
||||
}
|
||||
|
||||
fn remove(&mut self, index: u32) -> Option<StreamHandle> {
|
||||
if self.current.is_some_and(|(current, _)| current == index) {
|
||||
self.current.take().map(|(_, handle)| handle)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn clear(&mut self) -> Option<StreamHandle> {
|
||||
self.current.take().map(|(_, handle)| handle)
|
||||
}
|
||||
|
||||
fn resolve(&self, handle: StreamHandle) -> Option<u32> {
|
||||
self.current
|
||||
.filter(|(_, current)| *current == handle)
|
||||
.map(|(index, _)| index)
|
||||
}
|
||||
}
|
||||
|
||||
/// Pulse adapter whose native context and mainloop remain on one owner thread.
|
||||
#[derive(Debug)]
|
||||
pub struct PulseWorker {
|
||||
|
|
@ -254,6 +346,7 @@ fn run_connection<C: PulseConnection>(
|
|||
}
|
||||
|
||||
let mut tracker = StreamTracker::new(epoch);
|
||||
let mut output_tracker = OutputTracker::new(epoch);
|
||||
for stream in connection.streams()? {
|
||||
let handle = tracker
|
||||
.current_or_insert(stream.index)
|
||||
|
|
@ -262,8 +355,16 @@ fn run_connection<C: PulseConnection>(
|
|||
return Ok(());
|
||||
}
|
||||
}
|
||||
if let Some(output) = connection.default_output()? {
|
||||
let (_, handle) = output_tracker
|
||||
.replace(output.index)
|
||||
.map_err(|message| PulseError::Volume(message.to_owned()))?;
|
||||
if !emit_output(events, handle, output, None) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
while let Some(notification) = connection.poll_notification(Duration::ZERO)? {
|
||||
if !process_notification(notification, &mut tracker, events)? {
|
||||
if !process_notification(notification, &mut tracker, &mut output_tracker, events)? {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
|
@ -274,7 +375,13 @@ fn run_connection<C: PulseConnection>(
|
|||
loop {
|
||||
match commands.try_recv() {
|
||||
Ok(command) => {
|
||||
if !process_command(command, connection, &mut tracker, events) {
|
||||
if !process_command(
|
||||
command,
|
||||
connection,
|
||||
&mut tracker,
|
||||
&mut output_tracker,
|
||||
events,
|
||||
) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
|
@ -282,7 +389,7 @@ fn run_connection<C: PulseConnection>(
|
|||
Err(TryRecvError::Empty) => {}
|
||||
}
|
||||
if let Some(notification) = connection.poll_notification(NOTIFICATION_POLL)?
|
||||
&& !process_notification(notification, &mut tracker, events)?
|
||||
&& !process_notification(notification, &mut tracker, &mut output_tracker, events)?
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
|
|
@ -292,6 +399,7 @@ fn run_connection<C: PulseConnection>(
|
|||
fn process_notification(
|
||||
notification: PulseNotification,
|
||||
tracker: &mut StreamTracker,
|
||||
output_tracker: &mut OutputTracker,
|
||||
events: &EventLane,
|
||||
) -> Result<bool, PulseError> {
|
||||
match notification {
|
||||
|
|
@ -316,6 +424,49 @@ fn process_notification(
|
|||
};
|
||||
Ok(events.emit(WorkerEvent::Adapter(AdapterEvent::StreamRemoved { stream })))
|
||||
}
|
||||
PulseNotification::OutputChanged(output) => {
|
||||
if output_tracker
|
||||
.current
|
||||
.is_none_or(|(index, _)| index != output.index)
|
||||
{
|
||||
return Ok(true);
|
||||
}
|
||||
let (_, handle) = output_tracker
|
||||
.replace(output.index)
|
||||
.map_err(|message| PulseError::Volume(message.to_owned()))?;
|
||||
Ok(emit_output(events, handle, output, None))
|
||||
}
|
||||
PulseNotification::OutputRemoved(index) => {
|
||||
let Some(stream) = output_tracker.remove(index) else {
|
||||
return Ok(true);
|
||||
};
|
||||
Ok(events.emit(WorkerEvent::Adapter(AdapterEvent::StreamRemoved { stream })))
|
||||
}
|
||||
PulseNotification::DefaultOutputChanged(output) => {
|
||||
if let Some(output) = output.as_ref()
|
||||
&& output_tracker
|
||||
.current
|
||||
.is_some_and(|(index, _)| index == output.index)
|
||||
{
|
||||
let (_, handle) = output_tracker
|
||||
.replace(output.index)
|
||||
.map_err(|message| PulseError::Volume(message.to_owned()))?;
|
||||
return Ok(emit_output(events, handle, output.clone(), None));
|
||||
}
|
||||
let removed = output_tracker.clear();
|
||||
if let Some(stream) = removed
|
||||
&& !events.emit(WorkerEvent::Adapter(AdapterEvent::StreamRemoved { stream }))
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(output) = output else {
|
||||
return Ok(true);
|
||||
};
|
||||
let (_, handle) = output_tracker
|
||||
.replace(output.index)
|
||||
.map_err(|message| PulseError::Volume(message.to_owned()))?;
|
||||
Ok(emit_output(events, handle, output, None))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -323,6 +474,7 @@ fn process_command<C: PulseConnection>(
|
|||
command: AdapterCommand,
|
||||
connection: &mut C,
|
||||
tracker: &mut StreamTracker,
|
||||
output_tracker: &mut OutputTracker,
|
||||
events: &EventLane,
|
||||
) -> bool {
|
||||
let (operation, handle) = match &command {
|
||||
|
|
@ -334,17 +486,39 @@ fn process_command<C: PulseConnection>(
|
|||
}
|
||||
| AdapterCommand::Readback { operation, stream } => (*operation, *stream),
|
||||
};
|
||||
let Some(index) = tracker.resolve(handle) else {
|
||||
let is_readback = matches!(command, AdapterCommand::Readback { .. });
|
||||
if let Some(index) = tracker.resolve(handle) {
|
||||
let result = match command {
|
||||
AdapterCommand::SetVolume { channels, .. } => connection.set_volume(index, &channels),
|
||||
AdapterCommand::SetMute { muted, .. } => connection.set_mute(index, muted),
|
||||
AdapterCommand::Readback { .. } => connection.stream(index),
|
||||
};
|
||||
return match result {
|
||||
Ok(stream) => {
|
||||
if !is_readback
|
||||
&& !events.emit(WorkerEvent::Adapter(AdapterEvent::WriteAccepted {
|
||||
operation,
|
||||
}))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
emit_stream(events, handle, stream, Some(operation))
|
||||
}
|
||||
Err(error) => emit_failure(events, operation, error.to_string()),
|
||||
};
|
||||
}
|
||||
let Some(index) = output_tracker.resolve(handle) else {
|
||||
return emit_failure(events, operation, "stream handle is stale or unavailable");
|
||||
};
|
||||
let is_readback = matches!(command, AdapterCommand::Readback { .. });
|
||||
let result = match command {
|
||||
AdapterCommand::SetVolume { channels, .. } => connection.set_volume(index, &channels),
|
||||
AdapterCommand::SetMute { muted, .. } => connection.set_mute(index, muted),
|
||||
AdapterCommand::Readback { .. } => connection.stream(index),
|
||||
AdapterCommand::SetVolume { channels, .. } => {
|
||||
connection.set_output_volume(index, &channels)
|
||||
}
|
||||
AdapterCommand::SetMute { muted, .. } => connection.set_output_mute(index, muted),
|
||||
AdapterCommand::Readback { .. } => connection.output(index),
|
||||
};
|
||||
match result {
|
||||
Ok(stream) => {
|
||||
Ok(output) => {
|
||||
if !is_readback
|
||||
&& !events.emit(WorkerEvent::Adapter(AdapterEvent::WriteAccepted {
|
||||
operation,
|
||||
|
|
@ -352,12 +526,30 @@ fn process_command<C: PulseConnection>(
|
|||
{
|
||||
return false;
|
||||
}
|
||||
emit_stream(events, handle, stream, Some(operation))
|
||||
emit_output(events, handle, output, Some(operation))
|
||||
}
|
||||
Err(error) => emit_failure(events, operation, error.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn emit_output(
|
||||
events: &EventLane,
|
||||
handle: StreamHandle,
|
||||
output: PulseOutput,
|
||||
operation: Option<OperationId>,
|
||||
) -> bool {
|
||||
events.emit(WorkerEvent::OutputMetadata {
|
||||
stream: handle,
|
||||
label: output.label,
|
||||
volume_writable: true,
|
||||
}) && events.emit(WorkerEvent::Adapter(AdapterEvent::Observed {
|
||||
stream: handle,
|
||||
channels: output.channels,
|
||||
muted: output.muted,
|
||||
operation,
|
||||
}))
|
||||
}
|
||||
|
||||
fn emit_failure(events: &EventLane, operation: OperationId, message: impl Into<String>) -> bool {
|
||||
events.emit(WorkerEvent::Adapter(AdapterEvent::WriteFailed {
|
||||
operation,
|
||||
|
|
@ -399,6 +591,7 @@ mod tests {
|
|||
struct FakeControl {
|
||||
notifications: Arc<Mutex<VecDeque<PulseNotification>>>,
|
||||
streams: Arc<Mutex<BTreeMap<u32, PulseStream>>>,
|
||||
output: Arc<Mutex<Option<PulseOutput>>>,
|
||||
reject_writes: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
|
|
@ -414,6 +607,18 @@ mod tests {
|
|||
PulseNotification::Removed(index) => {
|
||||
self.streams.lock().expect("fake stream lock").remove(index);
|
||||
}
|
||||
PulseNotification::OutputChanged(output) => {
|
||||
*self.output.lock().expect("fake output lock") = Some(output.clone());
|
||||
}
|
||||
PulseNotification::OutputRemoved(index) => {
|
||||
let mut output = self.output.lock().expect("fake output lock");
|
||||
if output.as_ref().is_some_and(|output| output.index == *index) {
|
||||
*output = None;
|
||||
}
|
||||
}
|
||||
PulseNotification::DefaultOutputChanged(output) => {
|
||||
*self.output.lock().expect("fake output lock") = output.clone();
|
||||
}
|
||||
}
|
||||
self.notifications
|
||||
.lock()
|
||||
|
|
@ -438,6 +643,7 @@ mod tests {
|
|||
let control = FakeControl {
|
||||
notifications: Arc::new(Mutex::new(VecDeque::new())),
|
||||
streams: Arc::new(Mutex::new(streams)),
|
||||
output: Arc::new(Mutex::new(None)),
|
||||
reject_writes: Arc::new(AtomicBool::new(false)),
|
||||
};
|
||||
let owner_thread = Arc::new(Mutex::new(None));
|
||||
|
|
@ -477,6 +683,25 @@ mod tests {
|
|||
self.checked_stream(index)
|
||||
}
|
||||
|
||||
fn default_output(&mut self) -> Result<Option<PulseOutput>, PulseError> {
|
||||
Ok(self
|
||||
.control
|
||||
.output
|
||||
.lock()
|
||||
.expect("fake output lock")
|
||||
.clone())
|
||||
}
|
||||
|
||||
fn output(&mut self, index: u32) -> Result<PulseOutput, PulseError> {
|
||||
self.control
|
||||
.output
|
||||
.lock()
|
||||
.expect("fake output lock")
|
||||
.clone()
|
||||
.filter(|output| output.index == index)
|
||||
.ok_or(PulseError::MissingOutput)
|
||||
}
|
||||
|
||||
fn poll_notification(
|
||||
&mut self,
|
||||
_timeout: Duration,
|
||||
|
|
@ -516,6 +741,30 @@ mod tests {
|
|||
stream.muted = muted;
|
||||
Ok(stream.clone())
|
||||
}
|
||||
|
||||
fn set_output_volume(
|
||||
&mut self,
|
||||
index: u32,
|
||||
channels: &ChannelGains,
|
||||
) -> Result<PulseOutput, PulseError> {
|
||||
let mut output = self.control.output.lock().expect("fake output lock");
|
||||
let output = output
|
||||
.as_mut()
|
||||
.filter(|output| output.index == index)
|
||||
.ok_or(PulseError::MissingOutput)?;
|
||||
output.channels = channels.clone();
|
||||
Ok(output.clone())
|
||||
}
|
||||
|
||||
fn set_output_mute(&mut self, index: u32, muted: Mute) -> Result<PulseOutput, PulseError> {
|
||||
let mut output = self.control.output.lock().expect("fake output lock");
|
||||
let output = output
|
||||
.as_mut()
|
||||
.filter(|output| output.index == index)
|
||||
.ok_or(PulseError::MissingOutput)?;
|
||||
output.muted = muted;
|
||||
Ok(output.clone())
|
||||
}
|
||||
}
|
||||
|
||||
fn channels(values: &[f64]) -> ChannelGains {
|
||||
|
|
@ -540,6 +789,16 @@ mod tests {
|
|||
}
|
||||
}
|
||||
|
||||
fn output(index: u32, values: &[f64], muted: Mute) -> PulseOutput {
|
||||
PulseOutput {
|
||||
index,
|
||||
name: format!("output-{index}"),
|
||||
label: "Fixture output".to_owned(),
|
||||
channels: channels(values),
|
||||
muted,
|
||||
}
|
||||
}
|
||||
|
||||
fn receive(worker: &PulseWorker) -> WorkerEvent {
|
||||
worker
|
||||
.receive_timeout(Duration::from_secs(1))
|
||||
|
|
@ -708,6 +967,81 @@ mod tests {
|
|||
assert!(worker.shutdown());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_output_is_distinct_and_accepts_confirmed_writes() {
|
||||
let (connection, control, _) = FakeConnection::new(Vec::new());
|
||||
let mut worker = PulseWorker::spawn_with(BackendEpoch::new(6), 32, move || Ok(connection));
|
||||
initial_snapshot(&worker);
|
||||
|
||||
control.notify(PulseNotification::DefaultOutputChanged(Some(output(
|
||||
3,
|
||||
&[0.3, 0.6],
|
||||
Mute::Unmuted,
|
||||
))));
|
||||
assert!(matches!(
|
||||
receive(&worker),
|
||||
WorkerEvent::OutputMetadata { label, .. } if label == "Fixture output"
|
||||
));
|
||||
let handle = match receive(&worker) {
|
||||
WorkerEvent::Adapter(AdapterEvent::Observed { stream, .. }) => stream,
|
||||
event => panic!("unexpected event: {event:?}"),
|
||||
};
|
||||
assert!(handle.backend_id() > u64::from(u32::MAX));
|
||||
|
||||
worker
|
||||
.try_submit(AdapterCommand::SetVolume {
|
||||
operation: OperationId::new(20),
|
||||
stream: handle,
|
||||
channels: channels(&[0.2, 0.4]),
|
||||
})
|
||||
.expect("queued output write");
|
||||
assert!(matches!(
|
||||
receive(&worker),
|
||||
WorkerEvent::Adapter(AdapterEvent::WriteAccepted { operation })
|
||||
if operation == OperationId::new(20)
|
||||
));
|
||||
let _metadata = receive(&worker);
|
||||
assert!(matches!(
|
||||
receive(&worker),
|
||||
WorkerEvent::Adapter(AdapterEvent::Observed {
|
||||
stream,
|
||||
channels: actual,
|
||||
operation: Some(operation),
|
||||
..
|
||||
}) if stream == handle
|
||||
&& actual == channels(&[0.2, 0.4])
|
||||
&& operation == OperationId::new(20)
|
||||
));
|
||||
|
||||
control.notify(PulseNotification::DefaultOutputChanged(Some(output(
|
||||
4,
|
||||
&[0.7, 0.7],
|
||||
Mute::Unmuted,
|
||||
))));
|
||||
assert!(matches!(
|
||||
receive(&worker),
|
||||
WorkerEvent::Adapter(AdapterEvent::StreamRemoved { stream }) if stream == handle
|
||||
));
|
||||
let _metadata = receive(&worker);
|
||||
let replacement = match receive(&worker) {
|
||||
WorkerEvent::Adapter(AdapterEvent::Observed { stream, .. }) => stream,
|
||||
event => panic!("unexpected event: {event:?}"),
|
||||
};
|
||||
assert_ne!(replacement, handle);
|
||||
worker
|
||||
.try_submit(AdapterCommand::Readback {
|
||||
operation: OperationId::new(21),
|
||||
stream: handle,
|
||||
})
|
||||
.expect("queued stale output readback");
|
||||
assert!(matches!(
|
||||
receive(&worker),
|
||||
WorkerEvent::Adapter(AdapterEvent::WriteFailed { operation, .. })
|
||||
if operation == OperationId::new(21)
|
||||
));
|
||||
assert!(worker.shutdown());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unavailable_server_and_reconnect_epochs_are_explicit() {
|
||||
let unavailable =
|
||||
|
|
|
|||
15
task.md
15
task.md
|
|
@ -130,6 +130,15 @@ Dependencies: M3.
|
|||
That disruptive phase passed on 2026-10-15: it observed epoch 20 disconnect,
|
||||
epoch 21 reconnect, and a complete fresh snapshot. The same stream fixture can
|
||||
target an isolated standalone PulseAudio server through `PULSE_SERVER`.
|
||||
- [ ] **M4.5 Default output master:** expose the Pulse server's current default
|
||||
output as a stable logical target; subscribe to sink/default changes and keep
|
||||
application streams distinct. Tests: balanced output volume and mute use
|
||||
confirmed readback, external changes re-arm pickup, a default-sink switch
|
||||
invalidates the old handle, and application commands cannot reach an output.
|
||||
The Pulse worker, profile schema, live mixer, IPC, and TUI now carry a
|
||||
dedicated `output/default` object. The Arch profile assigns the APC master
|
||||
strip CC 56 / Note 98 to it and moves Media to CC 50 / Note 66. Keep this
|
||||
item open until the physical output checklist passes on PipeWire/Pulse.
|
||||
|
||||
M4.2 verification on 2026-10-14: the scripted worker contract suite passes
|
||||
without an audio daemon, and a read-only owner-thread smoke run against PipeWire
|
||||
|
|
@ -180,9 +189,9 @@ Dependencies: M3; M4 for full end-to-end acceptance.
|
|||
The pure pickup state machine and routed live server cover startup inhibition,
|
||||
tolerance and crossing activation, external-change/reconnect resets,
|
||||
competing surfaces, and above-range endpoint pickup. The Arch profile routes
|
||||
APC MINI CC 48/49/56 and notes 64/65/98 to Music, Browser, and Media. Keep
|
||||
this item open until pickup state is published to the TUI and profile-switch
|
||||
rearming is implemented.
|
||||
APC MINI CC 48/49/50/56 and notes 64/65/66/98 to Music, Browser, Media, and
|
||||
the default output master. Keep this item open until pickup state is
|
||||
published to the TUI and profile-switch rearming is implemented.
|
||||
- [ ] **M5.5 Physical smoke test:** one controller -> server -> application audio; then two controllers with overlapping MIDI message numbers. Acceptance: correct applications respond, bindings persist, and USB loss leaves server running. Record controller/firmware and environment.
|
||||
|
||||
M5.1 verification on 2026-10-14: nine decoder/router/transport tests pass with
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ const REFRESH_INTERVAL: Duration = Duration::from_millis(100);
|
|||
pub enum MixerObjectKind {
|
||||
Application,
|
||||
Group,
|
||||
Output,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||
|
|
@ -236,7 +237,7 @@ impl<C> Widget for &LiveTui<C> {
|
|||
.render(header, buf);
|
||||
|
||||
let mixer = Block::bordered()
|
||||
.title(" Live application streams ".bold())
|
||||
.title(" Live mixer objects ".bold())
|
||||
.title_bottom(
|
||||
self.client_error
|
||||
.as_deref()
|
||||
|
|
@ -269,7 +270,7 @@ impl<C> Widget for &LiveTui<C> {
|
|||
impl<C> LiveTui<C> {
|
||||
fn render_streams(&self, area: Rect, buf: &mut Buffer) {
|
||||
if self.snapshot.items.is_empty() {
|
||||
Paragraph::new("No playback streams are currently visible.")
|
||||
Paragraph::new("No mixer objects are currently visible.")
|
||||
.alignment(Alignment::Center)
|
||||
.render(area, buf);
|
||||
return;
|
||||
|
|
@ -305,6 +306,7 @@ impl<C> LiveTui<C> {
|
|||
match item.id.kind {
|
||||
MixerObjectKind::Application => "application",
|
||||
MixerObjectKind::Group => "group",
|
||||
MixerObjectKind::Output => "output",
|
||||
},
|
||||
item.detail,
|
||||
if item.pending { " … pending" } else { "" }
|
||||
|
|
|
|||
Loading…
Reference in New Issue