diff --git a/README.md b/README.md index fcc77ba..1a43d36 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,9 @@ cargo run --release * **`pactl`** (Ubuntu/Debian/Fedora: `pulseaudio-utils`). The audio backend shells out to it; it also ships with `pipewire-pulse`. Without it Slidr - starts but every volume/mute action is a no-op. + starts but every volume/mute action is a no-op. The mixer also uses `parec` + and `pacat` from the same package; it needs no virtual-cable driver (it + creates its devices, including the "Slidr Mic", in the sound server). * **Serial port access.** Opening `/dev/ttyUSB*` / `/dev/ttyACM*` needs permission, or the connection banner shows "Access denied". Either install the bundled udev rule (preferred - applies on replug, no group, no re-login): diff --git a/docs/mixer-plan.md b/docs/mixer-plan.md index 9337078..75dab22 100644 --- a/docs/mixer-plan.md +++ b/docs/mixer-plan.md @@ -111,10 +111,24 @@ Linux needs no driver (see below). ## Linux -PipeWire/Pulse needs no driver and has no cable limit: `module-null-sink` as -the sink, `move-sink-input` for rerouting, monitor sources for capture, -`module-remap-source` / a null sink's monitor as the Slidr Mic. Can be developed -alongside Windows or right after it; the engine and DSP are shared. +`src/mixer/pulse_io.rs`. PipeWire/Pulse needs no driver and has no cable +limit. Driven through `pactl`, `parec` and `pacat` (all in `pulseaudio-utils`, +which Slidr already needs), so the binary links no audio library: + +- each channel is a null sink `slidr_mixer_ch_`; its programs' streams are + moved there (`move-sink-input`) and its monitor is recorded into the channel. + With "Replace original" off, a `module-loopback` also plays the original; +- the mix plays as one `pacat` stream on the default output and follows it; +- the Slidr Mic is a null sink the mic bus plays into, plus a + `module-remap-source` of its monitor named "Slidr Mic"; +- the played streams run on the wall clock; their "Buffer Latency" (read in + the 1 s scan) drops or doubles a block to keep them ~40 ms ahead; +- every module Slidr loads has `slidr_mixer` in its arguments. Unloading a + null sink moves its streams back to the default output, so switching off, + quitting and cleaning up after a crash (at start) are all "unload ours". + +The engine, DSP, effects and switch sounds are shared with Windows. The +Settings "Mixer devices" card and the VB-CABLE hint are Windows-only. ## Phases diff --git a/src/audio/pulse_parse.rs b/src/audio/pulse_parse.rs index 53d4d33..64b83b8 100644 --- a/src/audio/pulse_parse.rs +++ b/src/audio/pulse_parse.rs @@ -18,6 +18,12 @@ pub struct Record { pub muted: bool, /// Sources only: true for the `.monitor` loopback of an output device. pub monitor: bool, + /// Sink inputs only: index of the sink the stream plays on. + pub sink: String, + /// Streams: `media.name` (what the stream calls itself). + pub media_name: String, + /// Streams: buffered audio ahead of the device ("Buffer Latency"), ms. + pub buffer_ms: Option, } impl Record { @@ -86,6 +92,12 @@ pub fn parse_records(text: &str, header_prefix: &str) -> Vec { c.volume = parse_first_percent(v).map(|p| (p as f32 / 100.0).clamp(0.0, 1.0)); } else if let Some(v) = line.strip_prefix("Monitor of Sink: ") { c.monitor = v.trim() != "n/a"; + } else if let Some(v) = line.strip_prefix("Sink: ") { + c.sink = v.trim().to_string(); + } else if let Some(v) = line.strip_prefix("Buffer Latency: ") { + c.buffer_ms = v.split_whitespace().next().and_then(|us| us.parse::().ok()).map(|us| (us / 1000.0) as u32); + } else if let Some(v) = property(line, "media.name") { + c.media_name = v; } else if let Some(v) = property(line, "application.process.binary") { c.process_binary = v; } else if let Some(v) = property(line, "application.name") { @@ -100,6 +112,26 @@ pub fn parse_records(text: &str, header_prefix: &str) -> Vec { out } +/// `pactl list short ` → (index, name) per line (tab-separated). +pub fn parse_short(text: &str) -> Vec<(String, String)> { + text.lines() + .filter_map(|l| { + let mut cols = l.split('\t'); + Some((cols.next()?.trim().to_string(), cols.next()?.trim().to_string())) + }) + .filter(|(i, n)| !i.is_empty() && !n.is_empty()) + .collect() +} + +/// `pactl list short modules` → ids of modules whose arguments contain +/// `marker` (how Slidr finds the devices it left behind after a crash). +pub fn modules_with(text: &str, marker: &str) -> Vec { + text.lines() + .filter(|l| l.contains(marker)) + .filter_map(|l| l.split('\t').next()?.trim().parse().ok()) + .collect() +} + fn parse_first_percent(s: &str) -> Option { let bytes = s.as_bytes(); for i in 0..bytes.len() { @@ -129,6 +161,35 @@ fn property(line: &str, key: &str) -> Option { mod tests { use super::*; + #[test] + fn sink_inputs_say_where_they_play_and_how_far_ahead() { + let text = "\ +Sink Input #57 +\tDriver: protocol-native.c +\tSink: 3 +\tBuffer Latency: 41333 usec +\tSink Latency: 12000 usec +\tProperties: +\t\tmedia.name = \"Slidr mix\" +\t\tapplication.name = \"Slidr\" +\t\tapplication.process.binary = \"pacat\" +"; + let r = &parse_records(text, "Sink Input #")[0]; + assert_eq!((r.id.as_str(), r.sink.as_str(), r.media_name.as_str()), ("57", "3", "Slidr mix")); + assert_eq!(r.buffer_ms, Some(41)); + } + + #[test] + fn short_lists_and_leftover_modules() { + let sinks = "0\talsa_output.pci.analog-stereo\tPipeWire\ts32le 2ch 48000Hz\tSUSPENDED\n\ + 12\tslidr_mixer_ch_1\tmodule-null-sink.c\tfloat32le 2ch 48000Hz\tRUNNING\n"; + assert_eq!(parse_short(sinks)[1], ("12".to_string(), "slidr_mixer_ch_1".to_string())); + let modules = "22\tmodule-null-sink\tsink_name=slidr_mixer_ch_1 sink_properties=device.description='Slidr Music'\n\ + 23\tmodule-loopback\tsource=alsa.monitor\n\ + 536870913\tlibpipewire-module-null-sink\tsink_name=slidr_mixer_mic\n"; + assert_eq!(modules_with(modules, "slidr_mixer"), vec![22, 536870913]); + } + const SINKS: &str = "\ Sink #0 \tState: RUNNING diff --git a/src/mixer/mod.rs b/src/mixer/mod.rs index c0b6720..16dd6e7 100644 --- a/src/mixer/mod.rs +++ b/src/mixer/mod.rs @@ -9,6 +9,9 @@ pub mod dsp; mod engine; mod fx; +// Compiled everywhere so it is type-checked and tested on any host; only +// Linux runs it. +mod pulse_io; mod sfx; mod ring; #[cfg(target_os = "windows")] @@ -84,7 +87,18 @@ fn spawn() -> Option> { Some(tx) } -#[cfg(not(target_os = "windows"))] +#[cfg(target_os = "linux")] +fn spawn() -> Option> { + let (tx, rx) = crossbeam_channel::unbounded(); + std::thread::Builder::new() + .name("mixer".into()) + .spawn(move || pulse_io::run(rx)) + .map_err(|e| log::error!("mixer: could not start thread: {e}")) + .ok()?; + Some(tx) +} + +#[cfg(not(any(target_os = "windows", target_os = "linux")))] fn spawn() -> Option> { None } diff --git a/src/mixer/pulse_io.rs b/src/mixer/pulse_io.rs new file mode 100644 index 0000000..7ab072e --- /dev/null +++ b/src/mixer/pulse_io.rs @@ -0,0 +1,892 @@ +//! Linux: the mixer over PulseAudio / PipeWire-Pulse. +//! +//! Like the rest of the Linux audio code (`audio/pulse.rs`) this drives the +//! sound server through its command-line tools — `pactl` to manage devices +//! and move streams, `parec` / `pacat` to record and play raw PCM — so the +//! binary needs no native library (they all come with `pulseaudio-utils`). +//! +//! * Each channel gets a null sink, `slidr_mixer_ch_`. Its programs' streams +//! are moved there and its monitor is recorded into the channel. Nothing of +//! them reaches the speakers directly, so this is "Replace original" by +//! itself; with that switch off a loopback plays the original too. +//! * The mix plays as one stream on the default output (and follows it). +//! * The Slidr Mic is a null sink the mic bus plays into, plus a source +//! remapped from its monitor and named "Slidr Mic" — no driver needed. +//! * Everything Slidr loads carries `slidr_mixer` in its arguments. Unloading +//! a null sink moves its streams back to the default output, so switching +//! off, quitting, and cleaning up after a crash are all "unload ours". +//! +//! Compiled on every platform (it uses only `std::process`) so it is +//! type-checked and its pure parts tested anywhere; only Linux starts it. + +#![cfg_attr(not(target_os = "linux"), allow(dead_code))] + +use std::collections::{HashMap, HashSet}; +use std::io::{Read, Write}; +use std::process::{Child, ChildStdin, Command, Stdio}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use crossbeam_channel::{Receiver, RecvTimeoutError, Sender}; + +use crate::audio::pulse_parse::{modules_with, parse_defaults, parse_records, parse_short, strip_exe, Record}; +use crate::model::{MixTarget, MixerConfig, MixerDevices}; + +use super::dsp::{Fade, BLOCK_FRAMES, BLOCK_SAMPLES, RATE}; +use super::engine::Engine; +use super::ring::Ring; +use super::sfx::{self, Library, Player, Sounds}; +use super::Cmd; + +/// In the arguments of every module Slidr loads. +const MARKER: &str = "slidr_mixer"; +const MIC_SINK: &str = "slidr_mixer_mic"; +const MIC_SOURCE: &str = "slidr_mixer_mic_source"; +/// `media.name` of the two streams Slidr plays. +const MIX_STREAM: &str = "Slidr mix"; +const MIC_STREAM: &str = "Slidr Mic"; +/// How far ahead of the device the played streams should run. +const TARGET_MS: u32 = 40; +const SCAN_EVERY: Duration = Duration::from_secs(1); + +fn channel_sink(id: u32) -> String { + format!("{MARKER}_ch_{id}") +} + +/// A device description safe inside module arguments (no quotes). +fn description(text: &str) -> String { + text.chars().filter(|c| c.is_alphanumeric() || " -_.()".contains(*c)).collect() +} + +/// `="device.description='