micstudio 0.1.0

High-performance native Rust audio studio, voice preset manager, and real-time DSP pipeline for PipeWire
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! MicStudio clean microphone noise, gate, and level settings persistence.
//! Manages versioned settings at ~/.config/micstudio/settings.toml.

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
use std::process::Command;

const SETTINGS_VERSION: u32 = 3;

fn default_schema_version() -> u32 {
    SETTINGS_VERSION
}

fn default_dpdfnet_attenuation() -> f32 {
    100.0
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CleanMicSettings {
    #[serde(default = "default_schema_version")]
    pub schema_version: u32,

    // Primary live controls
    #[serde(default = "default_dpdfnet_attenuation")]
    pub dpdfnet_attenuation_db: f32, // 0.0 to 100.0 (dB)
    #[serde(default)]
    pub output_gain_db: f32, // -24.0 to +12.0 (dB)
    #[serde(default)]
    pub quiet_voice_boost_enabled: bool,
    #[serde(default)]
    pub quiet_voice_boost_db: f32, // 0.0 to +10.0 (dB)
    #[serde(default)]
    pub hear_voice: bool, // Sidetone / live mic monitor
    #[serde(default)]
    pub meter_enabled: bool, // Live level meter in TUI

    // Legacy fields preserved for TOML compatibility
    #[serde(default)]
    pub rnnoise_enabled: bool,
    #[serde(default)]
    pub denoise_blend: f32,
    #[serde(default)]
    pub gate_enabled: bool,
    #[serde(default)]
    pub gate_aggressiveness: f32,
    #[serde(default)]
    pub silence_attenuation: f32,
    #[serde(default)]
    pub hangover_ms: u32,
    #[serde(default)]
    pub telemetry_enabled: bool,
    #[serde(default)]
    pub create_virtual_device: bool,
    #[serde(default)]
    pub virtual_device_name: String,
}

impl Default for CleanMicSettings {
    fn default() -> Self {
        Self {
            schema_version: SETTINGS_VERSION,
            dpdfnet_attenuation_db: 45.0,
            output_gain_db: 0.0,
            quiet_voice_boost_enabled: true,
            quiet_voice_boost_db: 4.0,
            hear_voice: false,
            meter_enabled: false,
            rnnoise_enabled: true,
            denoise_blend: 100.0,
            gate_enabled: true,
            gate_aggressiveness: 35.0,
            silence_attenuation: -36.0,
            hangover_ms: 500,
            telemetry_enabled: false,
            create_virtual_device: false,
            virtual_device_name: "MicStudio Studio Source".to_string(),
        }
    }
}

impl CleanMicSettings {
    pub fn config_path() -> Result<PathBuf> {
        let home = std::env::var("HOME").context("HOME env var not set")?;
        Ok(PathBuf::from(home).join(".config/micstudio/settings.toml"))
    }

    pub fn load() -> Self {
        match Self::config_path().and_then(|p| fs::read_to_string(&p).context("Read failed")) {
            Ok(content) => match toml::from_str::<CleanMicSettings>(&content) {
                Ok(mut s) => {
                    s.validate_clamp();
                    s
                }
                Err(_) => {
                    let s = Self::default();
                    let _ = s.save();
                    s
                }
            },
            Err(_) => {
                let s = Self::default();
                let _ = s.save();
                s
            }
        }
    }

    pub fn validate_clamp(&mut self) {
        self.schema_version = SETTINGS_VERSION;
        self.dpdfnet_attenuation_db = self.dpdfnet_attenuation_db.clamp(0.0, 100.0);
        self.output_gain_db = self.output_gain_db.clamp(-24.0, 12.0);
        self.quiet_voice_boost_db = self.quiet_voice_boost_db.clamp(0.0, 10.0);
    }

    pub fn save(&self) -> Result<()> {
        let path = Self::config_path()?;
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).context("Failed to create micstudio config dir")?;
        }
        let serialized = toml::to_string_pretty(self).context("Failed to serialize settings")?;
        let tmp_path = path.with_extension("toml.tmp");
        fs::write(&tmp_path, serialized).context("Failed to write temporary settings")?;
        fs::rename(&tmp_path, &path).context("Failed to atomically commit settings")?;
        Ok(())
    }

    /// Live apply: update DPDFNet attenuation, quiet speech leveling, and output gain directly via PipeWire pw-cli Props
    pub fn apply_dsp_params(&self) -> Result<()> {
        let capture_id = match get_node_id("capture.ghelper-audio")? {
            Some(id) => id,
            None => return Ok(()),
        };

        let atten = self.dpdfnet_attenuation_db.clamp(0.0, 100.0);
        let linear_gain = 10.0f32.powf(self.output_gain_db / 20.0);

        let (thresh_linear, makeup_linear) =
            if self.quiet_voice_boost_enabled && self.quiet_voice_boost_db > 0.01 {
                let boost = self.quiet_voice_boost_db.clamp(0.0, 10.0);
                let thresh_db = (-12.0 - (boost * 1.5)).clamp(-24.0, -12.0);
                let makeup_db = (3.0 + boost).clamp(3.0, 12.0);
                (
                    10.0f32.powf(thresh_db / 20.0),
                    10.0f32.powf(makeup_db / 20.0),
                )
            } else {
                // Baseline factory values from 40-mic.conf (-12 dBFS threshold, +3 dB makeup)
                (0.251189, 1.412538)
            };

        let props_payload = format!(
            "{{ params = [ \"dpdfnet:Attenuation Limit (dB)\" {:.1}, \"limiter:Output gain (G)\" {:.4}, \"compressor:Attack threshold (G)\" {:.6}, \"compressor:Makeup gain (G)\" {:.6}, \"compressor:Attack time (ms)\" 5.0, \"compressor:Hold time (ms)\" 120.0, \"compressor:Release time (ms)\" 500.0, \"compressor:Ratio\" 2.0 ] }}",
            atten, linear_gain, thresh_linear, makeup_linear
        );

        let _ = Command::new("pw-cli")
            .args(["s", &capture_id, "Props", &props_payload])
            .output();

        Ok(())
    }

    /// Reset capture.ghelper-audio compressor to factory baseline (-12 dBFS threshold, +3 dB makeup).
    /// Used when applying creative FX presets to guarantee creative FX never inherit extra quiet boost or compression.
    pub fn reset_clean_compressor_baseline() -> Result<()> {
        let capture_id = match get_node_id("capture.ghelper-audio")? {
            Some(id) => id,
            None => return Ok(()),
        };
        let cfg = Self::load();
        let atten = cfg.dpdfnet_attenuation_db.clamp(0.0, 100.0);
        let linear_gain = 10.0f32.powf(cfg.output_gain_db / 20.0);

        let props_payload = format!(
            "{{ params = [ \"dpdfnet:Attenuation Limit (dB)\" {:.1}, \"limiter:Output gain (G)\" {:.4}, \"compressor:Attack threshold (G)\" 0.251189, \"compressor:Makeup gain (G)\" 1.000000, \"compressor:Attack time (ms)\" 5.0, \"compressor:Hold time (ms)\" 120.0, \"compressor:Release time (ms)\" 500.0, \"compressor:Ratio\" 2.5 ] }}",
            atten, linear_gain
        );

        let _ = Command::new("pw-cli")
            .args(["s", &capture_id, "Props", &props_payload])
            .output();

        Ok(())
    }

    /// Full apply: DSP parameters + sidetone routing state
    pub fn apply_to_pipewire(&self) -> Result<()> {
        self.apply_dsp_params()?;
        Self::sync_hear_voice(self.hear_voice);
        Ok(())
    }

    pub fn sync_hear_voice(enable: bool) {
        Self::sync_hear_voice_with_source(enable, is_voice_fx_active());
    }

    pub fn is_sidetone_guarded() -> bool {
        let sink_out = Command::new("pactl").arg("get-default-sink").output();
        let default_sink = if let Ok(out) = sink_out {
            String::from_utf8_lossy(&out.stdout).trim().to_string()
        } else {
            String::new()
        };
        if default_sink.is_empty() {
            return false;
        }
        let lower_sink = default_sink.to_lowercase();
        let mut is_headphone = lower_sink.contains("headphone")
            || lower_sink.contains("headset")
            || lower_sink.contains("bluez");

        // If it's an ALSA sink (e.g. analog-stereo), query its active port to distinguish 3.5mm wired headphones from built-in speakers
        if !is_headphone {
            if let Ok(pactl_sinks) = Command::new("pactl").args(["list", "sinks"]).output() {
                let stdout_str = String::from_utf8_lossy(&pactl_sinks.stdout);
                let mut current_sink_matches = false;
                for line in stdout_str.lines() {
                    let trimmed = line.trim();
                    if trimmed.starts_with("Name: ") {
                        let name = trimmed.trim_start_matches("Name: ").trim();
                        current_sink_matches = name == default_sink;
                    } else if current_sink_matches && trimmed.starts_with("Active Port: ") {
                        let port = trimmed.trim_start_matches("Active Port: ").trim().to_lowercase();
                        if port.contains("headphone") || port.contains("headset") {
                            is_headphone = true;
                        }
                        break;
                    }
                }
            }
        }

        let is_speaker = lower_sink.contains("speaker")
            || lower_sink.contains("peace_gaming")
            || (lower_sink.contains("analog-stereo") && !is_headphone);

        is_speaker && !is_headphone
    }

    pub fn sync_hear_voice_with_source(enable: bool, _fx_active: bool) {
        // Disconnect any existing monitor links unconditionally from both sources
        disconnect_monitor_links("ghelper-audio:capture_MONO");
        disconnect_monitor_links("ghelper-audio-fx:capture_MONO");

        if !enable {
            return;
        }

        // In unified single-device architecture, ghelper-audio provides both clean and active voice FX
        let monitor_source = "ghelper-audio:capture_MONO";

        // Query active default sink
        let sink_out = Command::new("pactl").arg("get-default-sink").output();
        let default_sink = if let Ok(out) = sink_out {
            String::from_utf8_lossy(&out.stdout).trim().to_string()
        } else {
            String::new()
        };

        if !default_sink.is_empty() {
            // Anti-Echo Protection: Never loop microphone audio into built-in laptop speakers
            // or speaker DSP sinks, as acoustic feedback immediately causes infinite echo / squealing.
            if Self::is_sidetone_guarded() {
                return;
            }

            let left_port = format!("{}:playback_FL", default_sink);
            let right_port = format!("{}:playback_FR", default_sink);
            let _ = Command::new("pw-link")
                .args([monitor_source, &left_port])
                .output();
            let _ = Command::new("pw-link")
                .args([monitor_source, &right_port])
                .output();
        }
    }
}

pub fn is_voice_fx_active() -> bool {
    if let Ok(mgr) = crate::presets::PresetManager::new() {
        return !mgr.active_preset_name().eq_ignore_ascii_case("Natural Clean");
    }
    false
}

pub fn disconnect_monitor_links(source_port: &str) {
    if let Ok(out) = Command::new("pw-link").arg("-l").output() {
        let text = String::from_utf8_lossy(&out.stdout);
        let mut cur_port = String::new();
        for line in text.lines() {
            let trimmed = line.trim();
            if trimmed.is_empty() {
                continue;
            }
            if line.starts_with(' ') && line.contains("|->") {
                if cur_port == source_port {
                    if let Some(target) = line.split("|->").nth(1) {
                        let target_clean = target.trim();
                        // Only disconnect sidetone playback destinations (sinks/headphones), NEVER recording/meter streams
                        if target_clean.contains("playback_") {
                            let _ = Command::new("pw-link")
                                .args(["-d", source_port, target_clean])
                                .output();
                        }
                    }
                }
            } else if line.starts_with(' ') && line.contains("|<-") {
                if let Some(src) = line.split("|<-").nth(1) {
                    if src.trim() == source_port {
                        // Only disconnect if destination port is a playback sink, NEVER meter/recording inputs
                        if cur_port.contains("playback_") {
                            let _ = Command::new("pw-link")
                                .args(["-d", source_port, &cur_port])
                                .output();
                        }
                    }
                }
            } else if !line.starts_with(' ') {
                // Header line: port name (unindented)
                cur_port = trimmed.to_string();
            }
        }
    }
}

/// Ensures the live meter and spectrograph input is linked to ghelper-audio
pub fn ensure_meter_linked() {
    let _ = Command::new("pw-link")
        .args(["ghelper-audio:capture_MONO", "micstudio-meter-capture:input_MONO"])
        .output();
}

pub fn get_node_id(node_name: &str) -> Result<Option<String>> {
    let output = Command::new("pw-dump")
        .arg("Node")
        .output()
        .context("Failed to run pw-dump")?;
    let json: serde_json::Value =
        serde_json::from_slice(&output.stdout).unwrap_or(serde_json::Value::Null);
    if let Some(arr) = json.as_array() {
        for item in arr {
            if let Some(name) = item
                .get("info")
                .and_then(|i| i.get("props"))
                .and_then(|p| p.get("node.name"))
                .and_then(|n| n.as_str())
            {
                if name == node_name {
                    if let Some(id) = item.get("id").and_then(|id| id.as_u64()) {
                        return Ok(Some(id.to_string()));
                    }
                }
            }
        }
    }
    Ok(None)
}

/// Dynamically parse 40-mic.conf to list the ordered filter graph stages
pub fn parse_dynamic_stages() -> Vec<String> {
    let home = match std::env::var("HOME") {
        Ok(h) => h,
        Err(_) => return fallback_stages(),
    };
    let conf_path = PathBuf::from(home).join(".config/pipewire/pipewire.conf.d/40-mic.conf");
    let content = match fs::read_to_string(&conf_path) {
        Ok(c) => c,
        Err(_) => return fallback_stages(),
    };

    let mut stages = Vec::new();
    let mut saw_eq = false;

    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with('#') {
            continue;
        }
        if let Some(pos) = trimmed.find("name") {
            let rest = &trimmed[pos + 4..];
            if let Some(eq_pos) = rest.find('=') {
                let val_part = rest[eq_pos + 1..].trim();
                let name = val_part
                    .trim_matches(|c| c == '"' || c == '\'' || c == ' ' || c == '\t' || c == '{')
                    .split_whitespace()
                    .next()
                    .unwrap_or("");

                if name.starts_with("capture") || name.starts_with("ghelper") || name.is_empty() {
                    continue;
                }

                if name.starts_with("eq_") {
                    if !saw_eq {
                        stages.push("9-Band EQ".to_string());
                        saw_eq = true;
                    }
                } else if name == "hpf_70" {
                    stages.push("70Hz HPF".to_string());
                } else if name == "dpdfnet" {
                    stages.push("DPDFNet Denoise".to_string());
                } else if name == "dpdfnet_latency" {
                    // skip latency compensation node for display brevity
                } else if name == "compressor" {
                    stages.push("LSP Compressor".to_string());
                } else if name == "limiter" {
                    stages.push("Peak Limiter".to_string());
                } else {
                    stages.push(name.to_string());
                }
            }
        }
    }

    if stages.is_empty() {
        fallback_stages()
    } else {
        stages
    }
}

fn fallback_stages() -> Vec<String> {
    vec![
        "70Hz HPF".into(),
        "DPDFNet Denoise".into(),
        "9-Band EQ".into(),
        "LSP Compressor".into(),
        "Peak Limiter".into(),
    ]
}