Skip to content

Commit 14da97a

Browse files
refactor: clean up.
Signed-off-by: Maika Namuo <httpworldview@gmail.com>
1 parent 40d507c commit 14da97a

8 files changed

Lines changed: 72 additions & 99 deletions

File tree

‎src/infra/pipewire.rs‎

Lines changed: 16 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -95,17 +95,19 @@ impl CaptureControl {
9595
}
9696

9797
pub struct AudioBackend {
98-
control: CaptureControl,
99-
audio: Option<AudioReader>,
98+
commands: mpsc::Sender<Command>,
10099
thread: Option<thread::JoinHandle<()>>,
101100
}
102101

103102
impl AudioBackend {
104-
pub fn start(config: CaptureConfig) -> io::Result<Self> {
103+
pub fn start(config: CaptureConfig) -> io::Result<(Self, CaptureControl, AudioReader)> {
105104
Self::start_with_socket(config, None)
106105
}
107106

108-
fn start_with_socket(config: CaptureConfig, socket: Option<PathBuf>) -> io::Result<Self> {
107+
fn start_with_socket(
108+
config: CaptureConfig,
109+
socket: Option<PathBuf>,
110+
) -> io::Result<(Self, CaptureControl, AudioReader)> {
109111
let (writer, audio) = transport::channel();
110112
let (channels, positions) = match config.mode {
111113
CaptureMode::Applications => (MAX_CAPTURE_CHANNELS, ChannelPosition::SURROUND),
@@ -115,33 +117,28 @@ impl AudioBackend {
115117
let (commands, receiver) = mpsc::channel();
116118
let public = Arc::new(PublicState::default());
117119
let control = CaptureControl {
118-
commands,
120+
commands: commands.clone(),
119121
public: Arc::clone(&public),
120122
};
121123
let thread = thread::Builder::new()
122124
.name("openmeters-pipewire".into())
123125
.spawn(move || runtime::run(receiver, config, writer, public, socket))?;
124126

125-
Ok(Self {
127+
Ok((
128+
Self {
129+
commands,
130+
thread: Some(thread),
131+
},
126132
control,
127-
audio: Some(audio),
128-
thread: Some(thread),
129-
})
130-
}
131-
132-
pub fn control(&self) -> CaptureControl {
133-
self.control.clone()
134-
}
135-
136-
pub fn take_audio(&mut self) -> AudioReader {
137-
self.audio.take().expect("audio reader already taken")
133+
audio,
134+
))
138135
}
139136

140137
pub fn shutdown(&mut self) {
141138
let Some(thread) = self.thread.take() else {
142139
return;
143140
};
144-
let _ = self.control.commands.send(Command::Shutdown);
141+
let _ = self.commands.send(Command::Shutdown);
145142
if thread.join().is_err() {
146143
error!("[pipewire] backend thread panicked");
147144
}
@@ -163,13 +160,11 @@ mod tests {
163160
#[test]
164161
fn unavailable_socket_faults_and_stops_cleanly() {
165162
let runtime = tempfile::tempdir().unwrap();
166-
let mut backend = AudioBackend::start_with_socket(
163+
let (mut backend, control, mut audio) = AudioBackend::start_with_socket(
167164
CaptureConfig::default(),
168165
Some(runtime.path().join("missing")),
169166
)
170167
.unwrap();
171-
let control = backend.control();
172-
let mut audio = backend.take_audio();
173168
let deadline = Instant::now() + Duration::from_secs(1);
174169
let (mut reset, mut seeded) = (false, false);
175170
while !(reset && seeded) && Instant::now() < deadline {

‎src/infra/pipewire/live_tests.rs‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -530,11 +530,9 @@ fn wait_for_mapped_signal(
530530
#[ignore = "requires pipewire, pw-cli, pw-link, pw-loopback, pw-dump, and wireplumber"]
531531
fn live_backend_recovers_after_server_restart() {
532532
let mut server = IsolatedPipeWire::new();
533-
let mut backend =
533+
let (mut backend, control, mut audio) =
534534
AudioBackend::start_with_socket(CaptureConfig::default(), Some(server.remote.clone()))
535535
.expect("start backend");
536-
let control = backend.control();
537-
let mut audio = backend.take_audio();
538536
let tap_name = format!("openmeters.tap.{}", std::process::id());
539537
let initial_tap = server.wait_dump("initial backend session", |graph| graph.node_id(&tap_name));
540538

@@ -589,11 +587,9 @@ fn live_backend_recovers_after_server_restart() {
589587
#[ignore = "requires pipewire, pw-cli, pw-link, pw-loopback, pw-dump, and wireplumber"]
590588
fn live_capture_preserves_graph_invariants() {
591589
let server = IsolatedPipeWire::new();
592-
let mut backend =
590+
let (mut backend, control, mut audio) =
593591
AudioBackend::start_with_socket(CaptureConfig::default(), Some(server.remote.clone()))
594592
.expect("start backend");
595-
let control = backend.control();
596-
let mut audio = backend.take_audio();
597593
let tap_name = format!("openmeters.tap.{}", std::process::id());
598594
let tap_id = server.wait_audio("capture tap", &mut audio, |graph| graph.node_id(&tap_name));
599595
let graph = server.dump();

‎src/infra/pipewire/transport.rs‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,16 +63,16 @@ pub(super) enum StreamStatus {
6363
}
6464

6565
#[derive(Clone)]
66-
pub(crate) struct AudioWake(async_channel::Receiver<()>, usize);
66+
pub(crate) struct AudioWake(Arc<Shared>);
6767

6868
impl Hash for AudioWake {
6969
fn hash<H: Hasher>(&self, state: &mut H) {
70-
self.1.hash(state);
70+
Arc::as_ptr(&self.0).hash(state);
7171
}
7272
}
7373

7474
pub(crate) fn audio_wake(wake: &AudioWake) -> async_channel::Receiver<()> {
75-
wake.0.clone()
75+
wake.0.wake_receiver.clone()
7676
}
7777

7878
#[derive(Clone, Copy, PartialEq, Eq)]
@@ -695,8 +695,7 @@ impl AudioReader {
695695
}
696696

697697
pub(crate) fn wake_handle(&self) -> AudioWake {
698-
let identity = Arc::as_ptr(&self.shared) as usize;
699-
AudioWake(self.shared.wake_receiver.clone(), identity)
698+
AudioWake(Arc::clone(&self.shared))
700699
}
701700

702701
pub fn discard(&mut self, now: Instant) {

‎src/main.rs‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -21,10 +21,8 @@ use tracing_subscriber::{EnvFilter, fmt};
2121
use ui::UiConfig;
2222

2323
fn main() -> ExitCode {
24-
let env_filter = match EnvFilter::try_from_default_env() {
25-
Ok(filter) => filter,
26-
Err(_) => EnvFilter::new("openmeters=info"),
27-
};
24+
let env_filter =
25+
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("openmeters=info"));
2826
if let Err(err) = fmt()
2927
.with_env_filter(env_filter)
3028
.with_target(false)
@@ -37,16 +35,16 @@ fn main() -> ExitCode {
3735

3836
let settings_handle = SettingsHandle::load_or_default();
3937
let capture_config = settings_handle.borrow().data.capture_config();
40-
let mut backend = match AudioBackend::start(capture_config) {
38+
let (mut backend, capture, audio) = match AudioBackend::start(capture_config) {
4139
Ok(backend) => backend,
4240
Err(err) => {
4341
error!("[capture] failed to start PipeWire backend: {err}");
4442
return ExitCode::FAILURE;
4543
}
4644
};
4745
let ui_config = UiConfig {
48-
capture: backend.control(),
49-
audio: Rc::new(RefCell::new(Some(backend.take_audio()))),
46+
capture,
47+
audio: Rc::new(RefCell::new(Some(audio))),
5048
settings_handle,
5149
};
5250
let exit_code = match ui::run(ui_config) {

‎src/util/audio.rs‎

Lines changed: 45 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,28 +3,67 @@
33

44
pub mod musical;
55

6-
mod channel;
7-
mod format;
86
mod frequency;
97
mod level;
10-
mod rate;
118
mod window;
129

1310
pub use self::{
14-
channel::Channel,
15-
format::{fmt_duration, fmt_freq},
1611
frequency::FrequencyScale,
1712
level::{DB_FLOOR, LN_TO_DB, db_to_power, power_to_db, sanitize_negative_db},
18-
rate::{DEFAULT_SAMPLE_RATE, MAX_SAMPLE_RATE, sanitize_sample_rate},
1913
window::{WindowKind, compute_fft_bin_normalization, copy_dc_removed_windowed_from_deque},
2014
};
2115
pub(crate) use self::{
2216
level::{flush_denormal_f32, flush_denormal_f64},
2317
window::{mean_f32, window_coefficients},
2418
};
2519

20+
pub const DEFAULT_SAMPLE_RATE: f32 = 48_000.0;
21+
pub const MAX_SAMPLE_RATE: f32 = 768_000.0;
2622
pub const BAND_SPLITS_HZ: [f32; 2] = [200.0, 2000.0];
2723

24+
crate::macros::choice_enum!(no_default pub enum Channel {
25+
Left => "Left",
26+
Right => "Right",
27+
Mid => "Mid",
28+
Side => "Side",
29+
None => "None",
30+
});
31+
32+
impl Channel {
33+
pub(crate) fn project(self, [left, right]: [f32; 2]) -> f32 {
34+
match self {
35+
Self::Left => left,
36+
Self::Right => right,
37+
Self::Mid => (left + right) * 0.5,
38+
Self::Side => (left - right) * 0.5,
39+
Self::None => 0.0,
40+
}
41+
}
42+
}
43+
44+
pub fn sanitize_sample_rate(sample_rate: f32) -> f32 {
45+
crate::util::finite_positive(sample_rate)
46+
.unwrap_or(DEFAULT_SAMPLE_RATE)
47+
.clamp(1.0, MAX_SAMPLE_RATE)
48+
}
49+
50+
pub fn fmt_freq(frequency: f32) -> String {
51+
match frequency {
52+
f if f >= 10_000.0 => format!("{:.1}kHz", f / 1000.0),
53+
f if f >= 1_000.0 => format!("{:.2}kHz", f / 1000.0),
54+
f if f >= 100.0 => format!("{f:.1}Hz"),
55+
f => format!("{f:.2}Hz"),
56+
}
57+
}
58+
59+
pub fn fmt_duration(seconds: f32) -> String {
60+
if seconds >= 60.0 {
61+
format!("{:.0}m {:.0}s", (seconds / 60.0).floor(), seconds % 60.0)
62+
} else {
63+
format!("{seconds:.2}s")
64+
}
65+
}
66+
2867
#[cfg(test)]
2968
pub fn sine_wave(frequency: f32, sample_rate: f32, count: usize, amplitude: f32) -> Vec<f32> {
3069
(0..count)

‎src/util/audio/channel.rs‎

Lines changed: 0 additions & 22 deletions
This file was deleted.

‎src/util/audio/format.rs‎

Lines changed: 0 additions & 19 deletions
This file was deleted.

‎src/util/audio/rate.rs‎

Lines changed: 0 additions & 13 deletions
This file was deleted.

0 commit comments

Comments
 (0)