fix: handle first MIDI sweep after startup

Apply queued audio snapshot events before MIDI intents collected in the same server turn so pickup can evaluate the controller's first sweep against live state.

Tests: cargo test --workspace --all-targets --all-features; cargo test --workspace --doc --all-features; cargo clippy --workspace --all-targets --all-features -- -D warnings; cargo build --workspace --release --all-features; feature-matrix cargo checks
This commit is contained in:
Dandaedre 2026-10-16 18:56:37 +02:00
parent 51565940a9
commit 944e005914
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
2 changed files with 92 additions and 30 deletions

View File

@ -218,6 +218,10 @@ current refresh. Pending intent is never treated as confirmation.
Non-motorized absolute controls default to pickup: after startup, external changes, another surface's move, or profile switch, wait until the physical value crosses or enters a configured tolerance around the observed target before sending volume commands. First input establishes position; an out-of-range external volume uses the nearest physical endpoint. Relative encoders do not need pickup. Reset pickup on disconnect/rebind. For motors, add touch-aware inhibition before enabling motor output; unsupported touch means no claimed touch protection.
At startup, apply already-queued audio snapshot events before MIDI messages
collected in the same server turn. This gives pickup a live target for the
controller's first sweep without replaying input or issuing a startup write.
Avoid feedback loops with direction/origin tracking, quantization-aware equality, rate limiting, and device-specific echo suppression. MIDI has no universal request IDs: generic time-window byte suppression can swallow real input, so only enable it for documented echoing device profiles and test it. Server observations never themselves generate audio commands.
## TOML configuration, persistence, and switching

View File

@ -13,7 +13,8 @@ use std::{
};
use fader_config::{ProfileDocument, XdgEnvironment, XdgPaths};
use fader_core::{BackendEpoch, FaderId, Gain, SurfaceId};
use fader_core::{AdapterCommand, BackendEpoch, FaderId, Gain, SurfaceId};
use midi::MidiIntent;
use thiserror::Error;
use volume_lib::{AdapterQueue, Enqueue, PulseWorker, WorkerEvent};
@ -254,15 +255,29 @@ impl LocalServer {
pub fn tick(&mut self) -> Result<(), LocalError> {
let midi_tick = self.midi.tick();
for intent in midi_tick.intents {
let sequence = self.midi_sequence;
self.midi_sequence = self
.midi_sequence
.checked_add(1)
.ok_or(LocalError::MidiSequence)?;
let commands = self.mixer.midi_intent(intent, sequence)?;
self.enqueue(commands)?;
self.flush_dispatch();
let mut worker_events = Vec::new();
match self.worker.receive_timeout(self.poll_interval) {
Ok(event) => worker_events.push(event),
Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => return Err(self.worker_stop_error()),
}
loop {
match self.worker.try_receive() {
Ok(event) => worker_events.push(event),
Err(std::sync::mpsc::TryRecvError::Empty) => break,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
return Err(self.worker_stop_error());
}
}
}
let commands = apply_runtime_batch(
&mut self.mixer,
&mut self.midi_sequence,
worker_events,
midi_tick.intents,
)?;
self.enqueue(commands)?;
if let Some(binding) = midi_tick.learned {
let edit = crate::ipc::ConfigurationEdit::SetBinding {
surface: binding.surface,
@ -295,27 +310,6 @@ impl LocalServer {
}
}
self.flush_dispatch();
match self.worker.receive_timeout(self.poll_interval) {
Ok(event) => {
let commands = self.mixer.worker_event(event)?;
self.enqueue(commands)?;
}
Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => return Err(self.worker_stop_error()),
}
loop {
match self.worker.try_receive() {
Ok(event) => {
let commands = self.mixer.worker_event(event)?;
self.enqueue(commands)?;
}
Err(std::sync::mpsc::TryRecvError::Empty) => break,
Err(std::sync::mpsc::TryRecvError::Disconnected) => {
return Err(self.worker_stop_error());
}
}
}
self.flush_dispatch();
self.midi.sync_feedback(&self.mixer.snapshot());
self.mixer.set_devices(self.midi.snapshot());
while let Some(mut client) = self.listener.accept()? {
@ -670,6 +664,26 @@ impl LocalServer {
}
}
fn apply_runtime_batch(
mixer: &mut LiveMixerState,
midi_sequence: &mut u64,
worker_events: impl IntoIterator<Item = WorkerEvent>,
midi_intents: impl IntoIterator<Item = MidiIntent>,
) -> Result<Vec<AdapterCommand>, LocalError> {
let mut commands = Vec::new();
for event in worker_events {
commands.extend(mixer.worker_event(event)?);
}
for intent in midi_intents {
let sequence = *midi_sequence;
*midi_sequence = midi_sequence
.checked_add(1)
.ok_or(LocalError::MidiSequence)?;
commands.extend(mixer.midi_intent(intent, sequence)?);
}
Ok(commands)
}
fn available_profile_ids(directory: &Path, active: &str) -> Vec<String> {
let mut profiles = fs::read_dir(directory)
.into_iter()
@ -749,8 +763,52 @@ mod tests {
use super::*;
use crate::ipc::RequestCommand;
use fader_core::{AdapterEvent, ChannelGains, Mute, StreamHandle, StreamMetadata};
use tempfile::tempdir;
#[test]
fn startup_audio_snapshot_is_applied_before_queued_midi_motion() {
let profile = fader_config::Profile::parse(include_str!(
"../../examples/profiles/arch-pipewire.toml"
))
.unwrap();
let mut mixer = LiveMixerState::new(Gain::UNITY, "pulse", &profile).unwrap();
let epoch = BackendEpoch::new(1);
let stream = StreamHandle::new(epoch, 7, 1);
let events = [
WorkerEvent::SnapshotBegin(epoch),
WorkerEvent::StreamMetadata {
stream,
metadata: StreamMetadata::new()
.with_application_name("Music Player")
.with_process_binary("player"),
volume_writable: true,
},
WorkerEvent::Adapter(AdapterEvent::Observed {
stream,
channels: ChannelGains::new(vec![Gain::new(0.4).unwrap()]).unwrap(),
muted: Mute::Unmuted,
operation: None,
}),
WorkerEvent::SnapshotEnd(epoch),
];
let intents = [MidiIntent::AbsoluteVolume {
surface: SurfaceId::new("apc-mini").unwrap(),
fader: FaderId::new("music-fader").unwrap(),
gain: Gain::new(0.4).unwrap(),
}];
let mut sequence = 1;
let commands = apply_runtime_batch(&mut mixer, &mut sequence, events, intents).unwrap();
assert!(matches!(
commands.as_slice(),
[AdapterCommand::SetVolume { stream: target, .. }] if *target == stream
));
assert_eq!(sequence, 2);
assert_eq!(mixer.snapshot().status, "ready");
}
#[test]
fn accepted_unix_peer_credentials_match_the_server_user() {
let (server, _client) = UnixStream::pair().unwrap();