182 lines
6.5 KiB
Rust
182 lines
6.5 KiB
Rust
use std::{error::Error, io, sync::mpsc::RecvTimeoutError, time::Duration};
|
|
|
|
use fader_core::{BackendEpoch, Gain, MetadataField, Mute};
|
|
use volume_lib::{
|
|
AdapterChoice, AudioBackend, CompiledAdapterProbe, PulseClient, PulseNotification, PulseStream,
|
|
PulseWorker, SelectionPolicy, TargetRequirements, WorkerEvent, select_adapter,
|
|
};
|
|
|
|
fn main() -> Result<(), Box<dyn Error>> {
|
|
let mut arguments = std::env::args().skip(1);
|
|
let command = arguments.next().unwrap_or_else(|| "list".to_owned());
|
|
if command == "probe" {
|
|
let choice = arguments.next().unwrap_or_else(|| "auto".to_owned());
|
|
return probe(&choice);
|
|
}
|
|
if command == "worker-watch" {
|
|
let seconds = arguments.next().as_deref().unwrap_or("15").parse::<u64>()?;
|
|
return worker_watch(Duration::from_secs(seconds));
|
|
}
|
|
let mut client = PulseClient::connect()?;
|
|
|
|
match command.as_str() {
|
|
"list" => list(&mut client)?,
|
|
"watch" => {
|
|
let seconds = arguments.next().as_deref().unwrap_or("15").parse::<u64>()?;
|
|
watch(&mut client, Duration::from_secs(seconds))?;
|
|
}
|
|
"volume" => {
|
|
let index = parse_required(&mut arguments, "sink-input index")?.parse::<u32>()?;
|
|
let gain = Gain::new(parse_required(&mut arguments, "linear gain")?.parse::<f64>()?)?;
|
|
let current = client.stream(index)?;
|
|
if !current.volume_writable {
|
|
return Err(invalid_input("selected sink input is not volume-writable"));
|
|
}
|
|
let channels = current.channels.scaled_to(gain, Gain::UNITY)?;
|
|
print_stream(&client.set_volume(index, &channels)?);
|
|
}
|
|
"mute" => {
|
|
let index = parse_required(&mut arguments, "sink-input index")?.parse::<u32>()?;
|
|
let muted = match parse_required(&mut arguments, "on or off")?.as_str() {
|
|
"on" => Mute::Muted,
|
|
"off" => Mute::Unmuted,
|
|
_ => return Err(invalid_input("mute value must be 'on' or 'off'")),
|
|
};
|
|
print_stream(&client.set_mute(index, muted)?);
|
|
}
|
|
_ => {
|
|
return Err(invalid_input(
|
|
"usage: pulse_fixture [probe [auto|pulse|pipewire|alsa-mixer]|list|watch [SECONDS]|worker-watch [SECONDS]|volume INDEX GAIN|mute INDEX on|off]",
|
|
));
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn probe(value: &str) -> Result<(), Box<dyn Error>> {
|
|
let choice = match value {
|
|
"auto" => AdapterChoice::Auto,
|
|
"pulse" => AdapterChoice::Manual(AudioBackend::Pulse),
|
|
"pipewire" => AdapterChoice::Manual(AudioBackend::PipeWire),
|
|
"alsa-mixer" => AdapterChoice::Manual(AudioBackend::AlsaMixer),
|
|
_ => {
|
|
return Err(invalid_input(
|
|
"adapter must be auto, pulse, pipewire, or alsa-mixer",
|
|
));
|
|
}
|
|
};
|
|
let policy = SelectionPolicy::new(
|
|
choice,
|
|
vec![AudioBackend::Pulse, AudioBackend::PipeWire],
|
|
None,
|
|
)?;
|
|
let selected = select_adapter(
|
|
&policy,
|
|
TargetRequirements::APPLICATION_MIXER,
|
|
&mut CompiledAdapterProbe::default(),
|
|
)
|
|
.map_err(|error| invalid_input(&error.to_string()))?;
|
|
println!(
|
|
"selected={} server={:?} version={:?} capabilities={:?}",
|
|
selected.backend,
|
|
selected.server_name.as_deref(),
|
|
selected.server_version.as_deref(),
|
|
selected.capabilities
|
|
);
|
|
for diagnostic in selected.diagnostics {
|
|
println!("probe={diagnostic:?}");
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn worker_watch(duration: Duration) -> Result<(), Box<dyn Error>> {
|
|
let mut worker = PulseWorker::spawn(BackendEpoch::new(1), 256);
|
|
let deadline = std::time::Instant::now() + duration;
|
|
while let Some(remaining) = deadline.checked_duration_since(std::time::Instant::now()) {
|
|
match worker.receive_timeout(remaining.min(Duration::from_millis(250))) {
|
|
Ok(event) => {
|
|
let disconnected = matches!(event, WorkerEvent::Disconnected { .. });
|
|
println!("{event:?}");
|
|
if disconnected {
|
|
return Err(invalid_input("Pulse worker disconnected"));
|
|
}
|
|
}
|
|
Err(RecvTimeoutError::Timeout) => {}
|
|
Err(RecvTimeoutError::Disconnected) => break,
|
|
}
|
|
}
|
|
let stopped = worker.shutdown();
|
|
if worker.event_overflowed() {
|
|
return Err(invalid_input("Pulse worker event lane overflowed"));
|
|
}
|
|
if !stopped {
|
|
return Err(invalid_input("Pulse worker owner thread panicked"));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn list(client: &mut PulseClient) -> Result<(), Box<dyn Error>> {
|
|
for stream in client.streams()? {
|
|
print_stream(&stream);
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn watch(client: &mut PulseClient, duration: Duration) -> Result<(), Box<dyn Error>> {
|
|
client.subscribe()?;
|
|
list(client)?;
|
|
let deadline = std::time::Instant::now() + duration;
|
|
while let Some(remaining) = deadline.checked_duration_since(std::time::Instant::now()) {
|
|
match client.poll_notification(remaining.min(Duration::from_millis(250)))? {
|
|
Some(PulseNotification::Added(stream) | PulseNotification::Changed(stream)) => {
|
|
print_stream(&stream);
|
|
}
|
|
Some(PulseNotification::Removed(index)) => println!("removed index={index}"),
|
|
Some(
|
|
PulseNotification::OutputChanged(_)
|
|
| PulseNotification::OutputRemoved(_)
|
|
| PulseNotification::DefaultOutputChanged(_),
|
|
) => {}
|
|
None => {}
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
fn print_stream(stream: &PulseStream) {
|
|
let application = stream
|
|
.metadata
|
|
.value(MetadataField::ApplicationName)
|
|
.unwrap_or("<unknown application>");
|
|
let binary = stream
|
|
.metadata
|
|
.value(MetadataField::ProcessBinary)
|
|
.unwrap_or("<unknown binary>");
|
|
let gains = stream
|
|
.channels
|
|
.as_slice()
|
|
.iter()
|
|
.map(|gain| format!("{:.4}", gain.get()))
|
|
.collect::<Vec<_>>()
|
|
.join(",");
|
|
println!(
|
|
"index={} application={application:?} binary={binary:?} channels=[{gains}] muted={} writable={}",
|
|
stream.index,
|
|
stream.muted == Mute::Muted,
|
|
stream.volume_writable
|
|
);
|
|
}
|
|
|
|
fn parse_required(
|
|
arguments: &mut impl Iterator<Item = String>,
|
|
name: &str,
|
|
) -> Result<String, Box<dyn Error>> {
|
|
arguments
|
|
.next()
|
|
.ok_or_else(|| invalid_input(&format!("missing {name}")))
|
|
}
|
|
|
|
fn invalid_input(message: &str) -> Box<dyn Error> {
|
|
Box::new(io::Error::new(io::ErrorKind::InvalidInput, message))
|
|
}
|