1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
use ::std::path::{Path, PathBuf};
use ::std::process::ExitCode;
use ::anyhow::Result;
use ::clap::{Parser, Subcommand};
use ::voice_filter::denoise;
use ::voice_filter::param::Param;
use ::voice_filter::{chain, live, offline, settings};
/// Live voice filter for PipeWire.
#[derive(Parser)]
#[command(version, about)]
struct Args {
#[command(subcommand)]
command: Command,
/// Limits how much the noise suppression attenuates, in dB; 100 and above don't limit it.
/// Lower values keep more of the original voice, e.g. its highs. `run` keeps it for the next
/// runs, like a limit set in the app; without it, `run` takes the kept one and `process` 100.
#[arg(long, global = true, value_parser = db)]
atten_lim: Option<f32>,
}
/// A value in dB from the command line: a number, not NaN.
fn db(value: &str) -> Result<f32, String> {
match value.parse::<f32>() {
Ok(db) if !db.is_nan() => Ok(db),
_ => Err(format!("{value} isn't a number")),
}
}
#[derive(Subcommand)]
enum Command {
/// Provides the virtual microphone "Voice Filter": the microphone through the chain. Runs
/// until Ctrl+C.
Run {
/// The microphone, a name from `voice-filter inputs`; kept for the next runs. Without
/// one so far, the default input.
#[arg(long)]
input: Option<String>,
/// The output device (speakers) whose echo gets removed, a name from `voice-filter
/// outputs`; kept for the next runs. Without one so far, the default output.
#[arg(long)]
output: Option<String>,
/// Prints the frames, the longest processing time of one, the dropouts and the latency
/// every 10 s; without it only when there were dropouts or errors.
#[arg(long, short)]
verbose: bool,
},
/// Lists the microphones (and other audio sources) for `run --input`.
Inputs,
/// Lists the output devices for `run --output`.
Outputs,
/// Runs a WAV file (48 kHz, mixed down to mono) through the chain and writes the result, lined
/// up with the input; prints the latency and processing time of every stage.
Process {
input: PathBuf,
output: PathBuf,
/// What the speakers played while `input` was recorded (48 kHz, from the start of it),
/// for the echo cancellation; without it, it leaves the input as it is.
#[arg(long)]
reference: Option<PathBuf>,
},
/// Opens the GNOME app, which switches the stages and settings of `voice-filter run` and shows
/// its latency.
#[cfg(feature = "gui")]
Ui,
/// Installs the desktop entry and the icon of the app into `~/.local/share`
/// (`$XDG_DATA_HOME`), so it's among the apps and has its icon in the dock. The entry starts
/// this binary by its full path.
#[cfg(feature = "gui")]
InstallDesktop,
}
/// The device given on the command line, which is saved, or else the saved one.
fn device(
given: Option<String>,
settings_dir: Option<&Path>,
load: fn(&Path) -> Result<Option<String>>,
save: fn(&Path, &str) -> Result<()>,
) -> Result<Option<String>> {
Ok(match (given, settings_dir) {
(Some(name), Some(dir)) => {
save(dir, &name)?;
Some(name)
}
(Some(name), None) => Some(name),
(None, Some(dir)) => load(dir)?,
(None, None) => None,
})
}
/// Prints the microphones or output devices, the saved one marked with `*`.
fn list(
direction: live::Direction,
settings_dir: Option<&Path>,
load: fn(&Path) -> Result<Option<String>>,
) -> Result<()> {
let saved = settings_dir.map(load).transpose()?.flatten();
for device in live::devices(direction)? {
let mark = if saved.as_deref() == Some(&device.name) {
"*"
} else {
" "
};
println!(
"{mark} {} ({}, priority {})",
device.name, device.description, device.priority
);
}
Ok(())
}
fn main() -> Result<ExitCode> {
let args = Args::parse();
let settings_dir = settings::dir();
let settings_dir = settings_dir.as_deref();
match args.command {
Command::Run {
input,
output,
verbose,
} => {
let input = device(
input,
settings_dir,
settings::load_input,
settings::save_input,
)?;
let output = device(
output,
settings_dir,
settings::load_output,
settings::save_output,
)?;
match &input {
Some(input) => eprintln!("Reading from {input}"),
None => eprintln!("Reading from the default input"),
}
match &output {
Some(output) => eprintln!("Removing the echo of {output}"),
None => eprintln!("Removing the echo of the default output"),
}
let (chain, reference) = chain::build(args.atten_lim)?;
if let Some(dir) = settings_dir {
let (switches, params) = (chain.switches(), chain.params());
for warning in settings::restore_chain(dir, &switches, ¶ms)? {
eprintln!("{warning}");
}
// a limit given on the command line wins over the kept one, and is kept instead
if let Some(db) = args.atten_lim {
if let Some(limit) = Param::find(¶ms, "denoise", "limit") {
limit.set(db.clamp(0., denoise::UNLIMITED))?;
}
settings::save_chain(dir, &switches, ¶ms)?;
}
}
let devices = live::Devices {
input: input.as_deref(),
output: output.as_deref(),
};
live::run(
chain,
reference,
devices,
settings_dir.map(Path::to_owned),
verbose,
)?;
}
Command::Inputs => list(live::Direction::Input, settings_dir, settings::load_input)?,
Command::Outputs => list(live::Direction::Output, settings_dir, settings::load_output)?,
Command::Process {
input,
output,
reference: played,
} => {
let (mut chain, mut reference) = chain::build(args.atten_lim)?;
let reference = played.as_deref().map(|path| (&mut reference, path));
let report = offline::process_file(&mut chain, &input, &output, reference)?;
println!("{report}");
}
#[cfg(feature = "gui")]
Command::Ui => return Ok(::voice_filter::gui::run().into()),
#[cfg(feature = "gui")]
Command::InstallDesktop => {
use ::voice_filter::gui::desktop;
let data_home = desktop::data_home()?;
let exe = ::std::env::current_exe()?;
for path in desktop::install(&data_home, &exe)? {
println!("Wrote {}", path.display());
}
desktop::update_icon_cache(&data_home);
}
}
Ok(ExitCode::SUCCESS)
}