Skip to content

Private AI meeting notes that stay on your computer. No meeting bot. Free and open source for Mac, Windows and Linux. An alternative to Granola, Otter and Fireflies.

Linux: a Bluetooth headset switching to hands-free no longer makes the recorder reopen its streams over and over; it waits for the changes to stop, reopens only a device that really changed, and logs each change and what it did (#152)

christianmatd6083adc0cb0
diff --git a/app/native/yogurt-audio-linux/smoke/smoke.py b/app/native/yogurt-audio-linux/smoke/smoke.py
index d63604dc..47b65aa5 100644
--- a/app/native/yogurt-audio-linux/smoke/smoke.py
+++ b/app/native/yogurt-audio-linux/smoke/smoke.py
@@ -173,6 +173,24 @@ time.sleep(1)
pactl("set-default-sink", "speakers")
time.sleep(1.5)
+# a burst that comes back where it started (a Bluetooth headset switching mode and back, #152): nothing reopened
+n0 = len(r.lines)
+for sink in ["speakers2", "speakers", "speakers2", "speakers"]:
+ pactl("set-default-sink", sink)
+ time.sleep(0.2)
+time.sleep(2)
+check(not any(m["t"] == "warn" and m["code"] == "device-changed" for m in r.lines[n0:]), "a burst of changes back to the same output reopens nothing")
+check(any("computer sound still from speakers.monitor: kept" in e for e in r.err), "the log says the computer sound was kept")
+# a burst that ends somewhere new: reopened once
+n0 = len(r.lines)
+for sink in ["speakers2", "speakers", "speakers2"]:
+ pactl("set-default-sink", sink)
+ time.sleep(0.2)
+time.sleep(2)
+check(sum(1 for m in r.lines[n0:] if m["t"] == "warn" and m["code"] == "device-changed") == 1, "a burst of changes ending on a new output reopens once")
+pactl("set-default-sink", "speakers")
+time.sleep(2)
+
# a second mic, chosen, then unplugged: back to Auto with mic-gone
mod = pactl("load-module", "module-remap-source", "master=micfeed.monitor", "source_name=virtmic2", "source_properties=device.description=SecondMic")
time.sleep(0.5)
diff --git a/app/native/yogurt-audio-linux/src/main.rs b/app/native/yogurt-audio-linux/src/main.rs
index 8912c418..f8fb0549 100644
--- a/app/native/yogurt-audio-linux/src/main.rs
+++ b/app/native/yogurt-audio-linux/src/main.rs
@@ -16,10 +16,12 @@ mod json;
mod ogg_opus;
mod pulse;
mod resample;
+mod settle;
mod track;
use json::{n, obj, opt, s, J};
use pulse::{Capture, Change, Snapshot};
+use settle::{On, Settle};
use std::io::{BufRead, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::mpsc::{channel, Receiver, Sender};
@@ -92,8 +94,15 @@ struct Recorder {
tx: Sender<Msg>,
out: Sender<Vec<u8>>,
clock: Arc<Clock>,
- mic_rebuild: Option<Instant>,
- sys_rebuild: Option<Instant>,
+ /// the devices the open streams record from, to tell a real change from one that came back (#152)
+ mic_on: Option<On>,
+ sys_on: Option<On>,
+ /// device changes come in bursts: look once they stop
+ settle: Settle,
+}
+
+fn on_text(on: Option<&On>) -> String {
+ match on { Some(o) => format!("{} #{}", o.name, o.index.map(|i| i.to_string()).unwrap_or_else(|| "?".into())), None => "not recording".into() }
}
fn line(j: J) -> Vec<u8> { let mut d = j.text().into_bytes(); d.push(b'\n'); d }
@@ -120,14 +129,21 @@ impl Recorder {
// Auto with no real mic: PulseAudio makes a monitor the default input, which would record the speakers as "me"
if self.mic_uid.is_none() && snap.ready && snap.default_mic().is_none() { eprintln!("no microphone"); return false }
self.mic = self.start_capture(Tr::Me, self.mic_uid.clone());
+ self.mic_on = self.mic.as_ref().and_then(|_| self.mic_wanted(&snap)).map(|n| On::of(&n, &snap));
self.mic.is_some()
}
fn start_system(&mut self) -> bool {
if let Some(c) = self.sys.take() { c.stop() }
- let monitor = self.snapshot().monitor();
- self.sys = self.start_capture(Tr::Them, Some(monitor));
+ let snap = self.snapshot();
+ let monitor = snap.monitor();
+ self.sys = self.start_capture(Tr::Them, Some(monitor.clone()));
+ self.sys_on = self.sys.as_ref().map(|_| On::of(&monitor, &snap));
self.sys.is_some()
}
+ /// the mic to record from: the chosen one, or the default input when it is a real mic
+ fn mic_wanted(&self, snap: &Snapshot) -> Option<String> {
+ match &self.mic_uid { Some(u) => Some(u.clone()), None => snap.default_mic().map(|m| m.name.clone()) }
+ }
fn start(&mut self, speech: bool) {
self.me.open_writer();
@@ -152,22 +168,37 @@ impl Recorder {
self.send(obj([("t", s("mic")), ("uid", opt(self.mic_uid.as_deref())), ("name", opt(dev.map(|d| d.description.as_str())))]));
}
- // device changes come in bursts; rebuild once they settle, without stopping the recording
- fn schedule_mic(&mut self, after_ms: u64) { self.mic_rebuild = Some(Instant::now() + Duration::from_millis(after_ms)) }
- fn schedule_sys(&mut self) { self.sys_rebuild = Some(Instant::now() + Duration::from_millis(300)) }
+ /// The changes stopped: reopen only the streams whose device is really different now, without stopping the
+ /// recording. A headset that switched mode and came back as it was changes nothing (#152).
+ fn settled(&mut self) {
+ if self.finishing { return }
+ if let Some(uid) = self.mic_uid.clone() {
+ if !self.mic_here(&uid) { eprintln!("the chosen microphone went away: using the default"); self.mic_uid = None; self.warn("mic-gone") }
+ }
+ let snap = self.snapshot();
+ let monitor = snap.monitor();
+ if settle::reopen(self.sys.as_ref().and(self.sys_on.as_ref()), Some(&monitor), &snap) {
+ eprintln!("devices settled: computer sound from {monitor} (was {}): opening it again", on_text(self.sys.as_ref().and(self.sys_on.as_ref())));
+ self.rebuild_system();
+ } else if self.sys.is_some() { eprintln!("devices settled: computer sound still from {monitor}: kept") }
+ let want = self.mic_wanted(&snap);
+ if settle::reopen(self.mic.as_ref().and(self.mic_on.as_ref()), want.as_deref(), &snap) {
+ eprintln!("devices settled: microphone {} (was {}): opening it again", want.as_deref().unwrap_or("none"), on_text(self.mic.as_ref().and(self.mic_on.as_ref())));
+ self.rebuild_mic();
+ } else {
+ if self.mic.is_some() { eprintln!("devices settled: microphone still {}: kept", want.as_deref().unwrap_or("the default")) }
+ else if want.is_none() { eprintln!("devices settled: no microphone to record from") }
+ self.report_mic();
+ }
+ }
fn rebuild_system(&mut self) {
- if self.finishing { return }
self.them.resync();
if !self.start_system() { self.warn("no-system-audio") }
self.warn("device-changed");
}
/// A new stream on the chosen mic (or the default). The time in between is silence in me.ogg.
fn rebuild_mic(&mut self) {
- if self.finishing { return }
- if let Some(uid) = self.mic_uid.clone() {
- if !self.mic_here(&uid) { eprintln!("the chosen microphone went away: using the default"); self.mic_uid = None; self.warn("mic-gone") }
- }
self.me.resync();
if !self.start_mic() {
// the chosen mic can't be recorded from: Auto, and the picker is told
@@ -186,7 +217,7 @@ impl Recorder {
self.me.resync();
if self.start_mic() { self.warn("device-changed"); self.report_mic(); return }
eprintln!("moving the microphone failed: building it again");
- self.schedule_mic(0);
+ self.settle.now(Instant::now());
}
fn command(&mut self, c: &str) {
@@ -210,18 +241,17 @@ impl Recorder {
_ => {}
}
}
- Msg::Lost { track: Tr::Me, gen } if gen == self.mic_gen => { self.mic = None; self.schedule_mic(300) }
- Msg::Lost { track: Tr::Them, gen } if gen == self.sys_gen => { self.sys = None; self.schedule_sys() }
+ Msg::Lost { track: Tr::Me, gen } if gen == self.mic_gen => { self.mic = None; self.settle.poke(Instant::now()) }
+ Msg::Lost { track: Tr::Them, gen } if gen == self.sys_gen => { self.sys = None; self.settle.poke(Instant::now()) }
Msg::Lost { .. } => {}
Msg::Cmd(c) => self.command(&c),
Msg::End => self.finish(),
- Msg::Server(Change::Sink) => self.schedule_sys(),
- // Auto follows the default input; a chosen mic stays put
- Msg::Server(Change::Source) => if self.mic_uid.is_none() { self.schedule_mic(300) },
- // a chosen mic unplugged: back to Auto
- Msg::Server(Change::Sources) => {
- if let Some(u) = self.mic_uid.clone() { if self.snapshot().mic(&u).is_none() { self.schedule_mic(300) } }
- else if self.mic.is_none() && self.snapshot().default_mic().is_some() { self.schedule_mic(300) }
+ // every change goes in the log, and waits for the burst to end (settled decides what, if anything, to reopen)
+ Msg::Server(c) => {
+ let snap = self.snapshot();
+ eprintln!("device change ({c:?}): default output {}, default input {}, {} sources",
+ snap.default_sink.as_deref().unwrap_or("none"), snap.default_source.as_deref().unwrap_or("none"), snap.sources.len());
+ self.settle.poke(Instant::now());
}
}
}
@@ -245,7 +275,7 @@ impl Recorder {
let mut next_level = Instant::now() + Duration::from_millis(100);
while !self.finishing {
let mut wake = next_level;
- for d in [self.mic_rebuild, self.sys_rebuild].into_iter().flatten() { wake = wake.min(d) }
+ if let Some(d) = self.settle.deadline() { wake = wake.min(d) }
let wait = wake.saturating_duration_since(Instant::now());
match rx.recv_timeout(wait) {
Ok(m) => self.handle(m),
@@ -254,8 +284,7 @@ impl Recorder {
}
if self.finishing { break }
let now = Instant::now();
- if self.sys_rebuild.is_some_and(|d| d <= now) { self.sys_rebuild = None; self.rebuild_system() }
- if self.mic_rebuild.is_some_and(|d| d <= now) { self.mic_rebuild = None; self.rebuild_mic() }
+ if self.settle.take(now) { self.settled() }
if now >= next_level {
next_level += Duration::from_millis(100);
if next_level < now { next_level = now + Duration::from_millis(100) }
@@ -336,7 +365,7 @@ fn record(args: &[String], dir: &Path) {
them: Track::new("them", dir, part, start_ms, Box::new(move |d| { let _ = o2.send(d); })),
mic: None, sys: None, mic_gen: 0, sys_gen: 0, paused: false, finishing: false,
mic_uid: arg_value(args, "--mic"), snap, tx: tx.clone(), out, clock,
- mic_rebuild: None, sys_rebuild: None,
+ mic_on: None, sys_on: None, settle: Settle::default(),
};
rec.start(arg_value(args, "--speech").is_some());
diff --git a/app/native/yogurt-audio-linux/src/pulse.rs b/app/native/yogurt-audio-linux/src/pulse.rs
index 61ee35e3..b7540e46 100644
--- a/app/native/yogurt-audio-linux/src/pulse.rs
+++ b/app/native/yogurt-audio-linux/src/pulse.rs
@@ -19,7 +19,8 @@ use std::sync::{Arc, Mutex};
use std::time::Duration;
#[derive(Clone, Debug, PartialEq)]
-pub struct Source { pub name: String, pub description: String, pub monitor: bool }
+/// index: the server's number for it, new each time the device is built again (a Bluetooth profile switch)
+pub struct Source { pub name: String, pub description: String, pub monitor: bool, pub index: u32 }
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Snapshot {
@@ -36,6 +37,8 @@ impl Snapshot {
pub fn mics(&self) -> impl Iterator<Item = &Source> { self.sources.iter().filter(|s| !s.monitor) }
/// The default input, when it is a real mic (with no mic, PulseAudio makes a monitor the default)
pub fn default_mic(&self) -> Option<&Source> { self.default_source.as_deref().and_then(|n| self.mic(n)) }
+ /// The server's index for the source (mic or monitor) with this name
+ pub fn index_of(&self, name: &str) -> Option<u32> { self.sources.iter().find(|s| s.name == name).map(|s| s.index) }
/// What to record the computer's sound from: the default output's monitor
pub fn monitor(&self) -> String {
match &self.default_sink { Some(s) => format!("{s}.monitor"), None => "@DEFAULT_MONITOR@".into() }
@@ -84,7 +87,7 @@ fn refresh(ml: &mut Mainloop, ctx: &Context) -> Option<Snapshot> {
ListResult::Item(s) => {
if let Some(name) = s.name.as_ref() {
let description = s.description.as_ref().map(|d| d.to_string()).unwrap_or_else(|| name.to_string());
- l2.borrow_mut().push(Source { name: name.to_string(), description, monitor: s.monitor_of_sink.is_some() });
+ l2.borrow_mut().push(Source { name: name.to_string(), description, monitor: s.monitor_of_sink.is_some(), index: s.index });
}
}
ListResult::Error => f2.set(true),
@@ -187,7 +190,7 @@ pub fn capture(device: Option<String>, stream_name: &'static str, on_audio: impl
mod tests {
use super::*;
- fn src(name: &str, monitor: bool) -> Source { Source { name: name.into(), description: format!("{name} desc"), monitor } }
+ fn src(name: &str, monitor: bool) -> Source { Source { name: name.into(), description: format!("{name} desc"), monitor, index: 0 } }
#[test]
fn mics_leave_out_monitors() {
diff --git a/app/native/yogurt-audio-linux/src/settle.rs b/app/native/yogurt-audio-linux/src/settle.rs
new file mode 100644
index 00000000..e263ad74
--- /dev/null
+++ b/app/native/yogurt-audio-linux/src/settle.rs
@@ -0,0 +1,144 @@
+//! When to reopen a stream after the sound devices change (#152). A Bluetooth headset switching between music
+//! and hands-free mode (WirePlumber's autoswitch) tears its output down and builds it again, and the defaults
+//! flip back and forth for a second or two. Reopening on each change made Yogurt close and open streams all
+//! through the switch, and the call app lost its devices. So: wait until the changes stop, then reopen only a
+//! stream whose device is really different from the one it was opened on.
+
+use crate::pulse::Snapshot;
+use std::time::{Duration, Instant};
+
+/// Quiet this long after the last change before looking again
+pub const QUIET: Duration = Duration::from_millis(1000);
+/// Never wait longer than this after the first change of a burst, so a device that keeps changing is still followed
+pub const CAP: Duration = Duration::from_millis(5000);
+
+/// A trailing wait that restarts on each change, up to CAP after the first one
+#[derive(Default, Debug)]
+pub struct Settle { first: Option<Instant>, due: Option<Instant> }
+
+impl Settle {
+ /// something changed at now
+ pub fn poke(&mut self, now: Instant) {
+ let first = *self.first.get_or_insert(now);
+ self.due = Some((now + QUIET).min(first + CAP));
+ }
+ /// look right away (a stream that could not be opened, a chosen mic that failed)
+ pub fn now(&mut self, now: Instant) { self.first.get_or_insert(now); self.due = Some(now) }
+ pub fn deadline(&self) -> Option<Instant> { self.due }
+ /// true once, when the wait is over
+ pub fn take(&mut self, now: Instant) -> bool {
+ if self.due.is_none_or(|d| d > now) { return false }
+ *self = Settle::default();
+ true
+ }
+}
+
+/// The device a stream was opened on: its name, and the server's index for it then (a device built again gets a new one)
+#[derive(Clone, Debug, PartialEq)]
+pub struct On { pub name: String, pub index: Option<u32> }
+
+impl On {
+ pub fn of(name: &str, snap: &Snapshot) -> On { On { name: name.to_string(), index: snap.index_of(name) } }
+}
+
+/// Whether the stream opened on `open` (None: none is open) has to be opened again to record from `want`
+/// (None: nothing to record from, so trying is pointless).
+pub fn reopen(open: Option<&On>, want: Option<&str>, snap: &Snapshot) -> bool {
+ let Some(want) = want else { return false };
+ let Some(open) = open else { return true };
+ if open.name != want { return true }
+ snap.ready && snap.index_of(want) != open.index
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::pulse::Source;
+
+ fn src(name: &str, index: u32) -> Source { Source { name: name.into(), description: name.into(), monitor: name.ends_with(".monitor"), index } }
+ fn snap(sources: Vec<Source>) -> Snapshot { Snapshot { ready: true, default_sink: None, default_source: None, sources } }
+ fn ms(t: Instant, n: u64) -> Instant { t + Duration::from_millis(n) }
+
+ #[test]
+ fn a_burst_of_changes_gives_one_look_after_it_settles() {
+ let t = Instant::now();
+ let mut s = Settle::default();
+ assert!(!s.take(t));
+ // five changes 300 ms apart, like the headset switching to hands-free and back
+ for i in 0..5 { s.poke(ms(t, i * 300)); assert!(!s.take(ms(t, i * 300 + 299))) }
+ assert_eq!(s.deadline(), Some(ms(t, 1200 + 1000)));
+ assert!(!s.take(ms(t, 2199)));
+ assert!(s.take(ms(t, 2200)));
+ // once only
+ assert!(!s.take(ms(t, 2300)));
+ assert_eq!(s.deadline(), None);
+ }
+
+ #[test]
+ fn changes_that_never_stop_are_still_followed() {
+ let t = Instant::now();
+ let mut s = Settle::default();
+ let mut looks = 0;
+ for i in 0..100 {
+ let now = ms(t, i * 200);
+ if s.take(now) { looks += 1 }
+ s.poke(now);
+ }
+ // 20 s of a change every 200 ms: a look every 5 s, not one per change and not never
+ assert_eq!(looks, 3);
+ // a new burst after a look starts its own wait
+ let mut s = Settle::default();
+ s.poke(t);
+ assert!(s.take(ms(t, 1000)));
+ s.poke(ms(t, 1500));
+ assert_eq!(s.deadline(), Some(ms(t, 2500)));
+ }
+
+ #[test]
+ fn looking_now_does_not_wait() {
+ let t = Instant::now();
+ let mut s = Settle::default();
+ s.poke(t);
+ s.now(ms(t, 10));
+ assert!(s.take(ms(t, 10)));
+ }
+
+ #[test]
+ fn the_same_device_is_kept() {
+ let a = snap(vec![src("bluez_output.AA.1.monitor", 40), src("bluez_input.AA", 41)]);
+ let on = On::of("bluez_output.AA.1.monitor", &a);
+ assert_eq!(on.index, Some(40));
+ // the defaults flipped and came back: same device, same index, nothing to do
+ assert!(!reopen(Some(&on), Some("bluez_output.AA.1.monitor"), &a));
+ }
+
+ #[test]
+ fn a_device_built_again_or_a_new_default_is_reopened() {
+ let a = snap(vec![src("bluez_output.AA.1.monitor", 40)]);
+ let on = On::of("bluez_output.AA.1.monitor", &a);
+ // the headset's output torn down and built again under the same name
+ let rebuilt = snap(vec![src("bluez_output.AA.1.monitor", 57)]);
+ assert!(reopen(Some(&on), Some("bluez_output.AA.1.monitor"), &rebuilt));
+ // gone
+ assert!(reopen(Some(&on), Some("bluez_output.AA.1.monitor"), &snap(vec![])));
+ // a different default output
+ let other = snap(vec![src("bluez_output.AA.1.monitor", 40), src("speakers.monitor", 3)]);
+ assert!(reopen(Some(&on), Some("speakers.monitor"), &other));
+ // nothing open (the stream broke, or never opened)
+ assert!(reopen(None, Some("speakers.monitor"), &other));
+ }
+
+ #[test]
+ fn nothing_to_record_from_or_no_answer_changes_nothing() {
+ let a = snap(vec![src("mic", 5)]);
+ let on = On::of("mic", &a);
+ assert!(!reopen(None, None, &a));
+ assert!(!reopen(Some(&on), None, &a));
+ // the server is reconnecting: wait for its answer (a broken stream says so on its own)
+ assert!(!reopen(Some(&on), Some("mic"), &Snapshot::default()));
+ // a name the server has no list entry for (@DEFAULT_MONITOR@ when there was no default output)
+ let none = On::of("@DEFAULT_MONITOR@", &a);
+ assert_eq!(none.index, None);
+ assert!(!reopen(Some(&none), Some("@DEFAULT_MONITOR@"), &a));
+ }
+}
diff --git a/docs/README.md b/docs/README.md
index f83872d5..d93d7496 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -24,6 +24,20 @@ The other permissions are optional:
If a permission is off, use its button in Yogurt's Settings to open the right system pane. After changing it, return to Yogurt. Recording always waits for your click.
+## Linux: Bluetooth headsets
+
+With PipeWire, a Bluetooth headset switches from music mode to hands-free mode when an app records from its microphone. The headset's sound output is rebuilt during the switch, so the call app can lose its devices for a moment, and both sides sound lower quality while hands-free is on. Yogurt keeps recording through the switch.
+
+If your call keeps dropping its devices, turn the automatic switch off and use your computer's built-in microphone. Create `~/.config/wireplumber/wireplumber.conf.d/51-no-bt-autoswitch.conf` with:
+
+```
+wireplumber.settings = {
+ bluetooth.autoswitch-to-headset-profile = false
+}
+```
+
+Then run `systemctl --user restart wireplumber` and reconnect the headset. This is for WirePlumber 0.5 and newer (`wireplumber --version`). On 0.4, set `["media-role.use-headset-profile"] = false` in `bluetooth_policy.policy` in a copy of `policy.lua.d/10-default-policy.lua` under `~/.config/wireplumber/`.
+
## Privacy
Audio, transcripts, notes, and questions are processed locally. Yogurt does not upload your meetings, and there is no telemetry.