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.

Recording (Windows): the call is also recorded from the default communication device when it isn't the default output, where Teams plays calls, mixed into the same track (#167)

christianmat1b016b09a694
diff --git a/app/native/yogurt-audio-win/src/main.rs b/app/native/yogurt-audio-win/src/main.rs
index 63d8538c..f6dd31df 100644
--- a/app/native/yogurt-audio-win/src/main.rs
+++ b/app/native/yogurt-audio-win/src/main.rs
@@ -1,6 +1,7 @@
// Yogurt's recorder on Windows, speaking the same protocol as the Mac's (native/yogurt-audio/main.swift): the microphone
// (WASAPI shared mode, no communications role, so the call app keeps its mic as it was) and the computer's sound
-// (the whole default output; process loopback, every app except Yogurt, on YOGURT_AUDIO_LOOPBACK=process: it missed Teams, #35).
+// (the default output, plus the default communication device when it differs, where Teams plays calls (#167); process
+// loopback, every app except Yogurt, on YOGURT_AUDIO_LOOPBACK=process: it missed Teams, #35).
// yogurt-audio record --dir DIR [--part N --start-ms X] [--mic-muted] [--mic ID] [--speech LOCALE]
// yogurt-audio join --dir DIR | inspect --dir DIR | mic-devices | speech-locales | speech-install LOCALE
// Writes DIR/me.ogg and DIR/them.ogg (Opus 20 kb/s mono, 48 kHz), a page a second so a crash keeps what was recorded.
@@ -15,6 +16,7 @@
// mute ID and unmute ID reply with {"t":"mic-muted","id":ID,"muted":bool,"ms":meeting time}.
// stdin: pause, resume, stop (end of input also stops), mic ID or mic auto (switch without stopping). Problems go to stderr.
mod gap;
+mod mix;
mod join;
mod ogg;
mod oggopus;
diff --git a/app/native/yogurt-audio-win/src/mix.rs b/app/native/yogurt-audio-win/src/mix.rs
new file mode 100644
index 00000000..7987facb
--- /dev/null
+++ b/app/native/yogurt-audio-win/src/mix.rs
@@ -0,0 +1,208 @@
+//! The computer's sound from more than one output (the default output and the default communication device, #167):
+//! which outputs to record, and one track mixed from them on meeting time.
+
+/// The outputs to record from: the default output, and the communication device when it is a different one
+/// (Teams plays calls there). The same device twice is recorded once, so nothing is doubled.
+pub fn outputs(console: Option<String>, comms: Option<String>) -> Vec<String> {
+ let mut v: Vec<String> = Vec::new();
+ for id in [console, comms].into_iter().flatten() {
+ if !v.contains(&id) {
+ v.push(id);
+ }
+ }
+ v
+}
+
+/// A pause longer than this inside one output's audio is kept as silence (Track does the same)
+const GAP_FRAMES: i64 = 250 * 48;
+/// An output this far behind the others (a stalled stream) stops holding the mix back; it counts as silence
+const LAG_FRAMES: i64 = 1000 * 48;
+
+#[derive(Default)]
+struct Lane {
+ /// 48 kHz frame (meeting time) of buf[0]
+ start: i64,
+ buf: Vec<f32>,
+ started: bool,
+}
+
+impl Lane {
+ fn end(&self) -> i64 {
+ self.start + self.buf.len() as i64
+ }
+}
+
+/// Mixes several 48 kHz mono streams. Each stream is placed by the time its audio was heard and then runs on
+/// sample by sample (device clocks jitter); the mix goes out as far as every stream has reached.
+pub struct Mix {
+ lanes: Vec<Lane>,
+ /// the frame the mix has gone out to
+ out: Option<i64>,
+}
+
+impl Mix {
+ pub fn new(n: usize) -> Mix {
+ Mix { lanes: (0..n).map(|_| Lane::default()).collect(), out: None }
+ }
+
+ /// Audio from output `lane`, heard at heard_ms. Returns mixed audio that is ready, and the meeting time it starts at.
+ pub fn push(&mut self, lane: usize, samples: &[f32], heard_ms: f64) -> Option<(Vec<f32>, f64)> {
+ let at = (heard_ms * 48.0).round() as i64;
+ let out = *self.out.get_or_insert(at);
+ let l = self.lanes.get_mut(lane)?;
+ if !l.started {
+ l.started = true;
+ l.start = at.max(out);
+ let skip = (out - at).clamp(0, samples.len() as i64) as usize;
+ l.buf.extend_from_slice(&samples[skip..]);
+ } else {
+ if at - l.end() > GAP_FRAMES {
+ l.buf.resize((at - l.start) as usize, 0.0);
+ }
+ l.buf.extend_from_slice(samples);
+ }
+ self.take()
+ }
+
+ fn take(&mut self) -> Option<(Vec<f32>, f64)> {
+ let out = self.out?;
+ let ends: Vec<i64> = self.lanes.iter().map(|l| if l.started { l.end() } else { out }).collect();
+ let most = *ends.iter().max()?;
+ let least = *ends.iter().min()?;
+ let upto = least.max(most - LAG_FRAMES);
+ if upto <= out {
+ return None;
+ }
+ let n = (upto - out) as usize;
+ let mut mixed = vec![0f32; n];
+ for l in &mut self.lanes {
+ if !l.started {
+ continue;
+ }
+ // what this output has before upto, from out on (a lagging one is short: silence)
+ let from = (out - l.start).max(0) as usize;
+ let offset = (l.start - out).max(0) as usize;
+ let avail = l.buf.len().saturating_sub(from);
+ for i in 0..avail.min(n.saturating_sub(offset)) {
+ mixed[offset + i] += l.buf[from + i];
+ }
+ // drop what went out
+ let used = (upto - l.start).clamp(0, l.buf.len() as i64) as usize;
+ l.buf.drain(..used);
+ l.start += used as i64;
+ // a stalled output was left behind: placed again by its time when it comes back
+ if l.start < upto {
+ *l = Lane::default();
+ }
+ }
+ for x in &mut mixed {
+ *x = x.clamp(-1.0, 1.0);
+ }
+ self.out = Some(upto);
+ Some((mixed, out as f64 / 48.0))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_communication_device_is_recorded_when_it_differs() {
+ assert_eq!(outputs(Some("speakers".into()), Some("headset".into())), vec!["speakers", "headset"]);
+ // one device for both: recorded once
+ assert_eq!(outputs(Some("headset".into()), Some("headset".into())), vec!["headset"]);
+ assert_eq!(outputs(None, Some("headset".into())), vec!["headset"]);
+ assert_eq!(outputs(Some("speakers".into()), None), vec!["speakers"]);
+ assert!(outputs(None, None).is_empty());
+ }
+
+ #[test]
+ fn two_outputs_are_added_together_on_meeting_time() {
+ let mut m = Mix::new(2);
+ // speakers first: nothing goes out until the headset reaches the same time
+ assert_eq!(m.push(0, &[0.1; 480], 0.0), None);
+ let (s, at) = m.push(1, &[0.2; 480], 0.0).unwrap();
+ assert_eq!(at, 0.0);
+ assert_eq!(s.len(), 480);
+ assert!(s.iter().all(|x| (x - 0.3).abs() < 1e-6));
+ // the next 10 ms
+ assert_eq!(m.push(1, &[0.5; 480], 10.0), None);
+ let (s, at) = m.push(0, &[0.0; 480], 10.0).unwrap();
+ assert_eq!(at, 10.0);
+ assert!(s.iter().all(|x| (x - 0.5).abs() < 1e-6));
+ }
+
+ #[test]
+ fn the_call_on_one_output_comes_through_whole() {
+ // the headset carries the call, the speakers stay silent (as the gap filler sends it)
+ let mut m = Mix::new(2);
+ let mut got = Vec::new();
+ for i in 0..100 {
+ let t = i as f64 * 10.0;
+ got.extend(m.push(0, &[0.0; 480], t).map(|x| x.0).unwrap_or_default());
+ let tone: Vec<f32> = (0..480).map(|k| ((i * 480 + k) as f32 * 0.01).sin() * 0.5).collect();
+ got.extend(m.push(1, &tone, t).map(|x| x.0).unwrap_or_default());
+ }
+ assert_eq!(got.len(), 48_000);
+ let want: Vec<f32> = (0..48_000).map(|k| (k as f32 * 0.01).sin() * 0.5).collect();
+ assert!(got.iter().zip(&want).all(|(a, b)| (a - b).abs() < 1e-6));
+ }
+
+ #[test]
+ fn a_late_starting_output_joins_at_its_time() {
+ let mut m = Mix::new(2);
+ assert_eq!(m.push(0, &[0.1; 480], 0.0), None);
+ // the headset starts 5 ms in: the first 5 ms are speakers only
+ let (s, at) = m.push(1, &[0.2; 480], 5.0).unwrap();
+ assert_eq!(at, 0.0);
+ assert_eq!(s.len(), 480);
+ assert!(s[..240].iter().all(|x| (x - 0.1).abs() < 1e-6));
+ assert!(s[240..].iter().all(|x| (x - 0.3).abs() < 1e-6));
+ // and audio from before the mix began is dropped
+ let mut m = Mix::new(2);
+ m.push(0, &[0.1; 480], 100.0);
+ let (s, at) = m.push(1, &[0.2; 960], 90.0).unwrap();
+ assert_eq!((at, s.len()), (100.0, 480));
+ assert!(s.iter().all(|x| (x - 0.3).abs() < 1e-6));
+ }
+
+ #[test]
+ fn a_stalled_output_does_not_hold_the_call_back() {
+ let mut m = Mix::new(2);
+ let mut total = 0;
+ m.push(1, &[0.0; 480], 0.0);
+ // the headset sends 2 s, the speakers nothing more
+ for i in 0..200 {
+ if let Some((s, _)) = m.push(0, &[0.4; 480], i as f64 * 10.0) {
+ assert!(s.iter().all(|x| x.abs() <= 0.4 + 1e-6));
+ total += s.len();
+ }
+ }
+ // everything but the last second is out
+ assert_eq!(total, 48_000);
+ // the stalled one coming back late is not mixed into time already sent
+ let (s, at) = m.push(1, &[0.2; 480], 1500.0).map(|x| x).unwrap_or((vec![], 0.0));
+ assert!(s.is_empty() || at >= 1000.0);
+ }
+
+ #[test]
+ fn a_pause_inside_one_output_stays_silence() {
+ let mut m = Mix::new(1);
+ m.push(0, &[0.1; 480], 0.0).unwrap();
+ // nothing for 500 ms: silence, then the audio at its time
+ let (s, at) = m.push(0, &[0.2; 480], 510.0).unwrap();
+ assert_eq!(at, 10.0);
+ assert_eq!(s.len(), 500 * 48 + 480);
+ assert!(s[..500 * 48].iter().all(|&x| x == 0.0));
+ assert!(s[500 * 48..].iter().all(|x| (x - 0.2).abs() < 1e-6));
+ }
+
+ #[test]
+ fn loud_sound_on_both_stays_in_range() {
+ let mut m = Mix::new(2);
+ m.push(0, &[0.9; 48], 0.0);
+ let (s, _) = m.push(1, &[0.9; 48], 0.0).unwrap();
+ assert!(s.iter().all(|&x| x == 1.0));
+ }
+}
diff --git a/app/native/yogurt-audio-win/src/record.rs b/app/native/yogurt-audio-win/src/record.rs
index c9483b0c..0bb77214 100644
--- a/app/native/yogurt-audio-win/src/record.rs
+++ b/app/native/yogurt-audio-win/src/record.rs
@@ -4,6 +4,7 @@ use std::path::Path;
use std::sync::mpsc::{channel, RecvTimeoutError};
use std::time::{Duration, Instant};
+use crate::mix::Mix;
use crate::out::{self, log};
use crate::track::Track;
use crate::win::{self, Clock, Ev, StartError, Stream};
@@ -23,7 +24,9 @@ struct Recorder {
me: Track,
them: Track,
mic: Option<Stream>,
- sys: Option<Stream>,
+ /// one stream per output; more than one is mixed
+ sys: Vec<Stream>,
+ mix: Option<Mix>,
paused: bool,
mic_muted: bool,
mic_generation: u64,
@@ -45,7 +48,8 @@ pub fn run(dir: &Path, o: Options) -> i32 {
me: Track::new("me", dir, o.part, o.start_ms),
them: Track::new("them", dir, o.part, o.start_ms),
mic: None,
- sys: None,
+ sys: Vec::new(),
+ mix: None,
paused: false,
mic_muted: o.mic_muted,
mic_generation: 0,
@@ -100,9 +104,17 @@ pub fn run(dir: &Path, o: Options) -> i32 {
}
}
}
- Ok(Ev::Sys(b, heard)) => {
+ Ok(Ev::Sys(lane, b, heard)) => {
if !r.paused {
- r.them.append(&b, Some(heard), r.clock.now_ms())
+ let now = r.clock.now_ms();
+ match &mut r.mix {
+ Some(m) => {
+ if let Some((s, at)) = m.push(lane, &b, heard) {
+ r.them.append(&s, Some(at), now)
+ }
+ }
+ None => r.them.append(&b, Some(heard), now),
+ }
}
}
Ok(Ev::MicLost(generation)) => { if generation == r.mic_generation { r.mic.take(); r.schedule_mic(SETTLE) } }
@@ -205,7 +217,10 @@ impl Recorder {
fn start_system(&mut self) {
match win::start_system(self.tx.clone(), self.clock) {
- Ok(s) => self.sys = Some(s),
+ Ok(s) => {
+ self.sys = s;
+ self.new_mix();
+ }
Err(e) => {
log(&format!("system audio failed: {e:?}"));
out::warn("no-system-audio");
@@ -213,12 +228,17 @@ impl Recorder {
}
}
+ /// A fresh mix of the outputs recording now (none for one)
+ fn new_mix(&mut self) {
+ self.mix = (self.sys.len() > 1).then(|| Mix::new(self.sys.len()));
+ }
+
fn schedule_mic(&mut self, after: Duration) {
self.mic_rebuild = Some(Instant::now() + after);
}
fn rebuild_system(&mut self) {
- if let Some(s) = self.sys.take() {
+ for s in self.sys.drain(..) {
s.stop();
}
self.them.resync();
@@ -294,6 +314,7 @@ impl Recorder {
self.paused = false;
self.me.resync();
self.them.resync();
+ self.new_mix();
}
_ if c.starts_with("mute ") || c.starts_with("unmute ") => {
let Some((action, id)) = c.split_once(' ') else { return false };
@@ -323,7 +344,7 @@ impl Recorder {
if let Some(s) = self.mic.take() {
s.stop();
}
- if let Some(s) = self.sys.take() {
+ for s in self.sys.drain(..) {
s.stop();
}
self.me.flush_pending();
diff --git a/app/native/yogurt-audio-win/src/win/mod.rs b/app/native/yogurt-audio-win/src/win/mod.rs
index 3e45534e..32f9c323 100644
--- a/app/native/yogurt-audio-win/src/win/mod.rs
+++ b/app/native/yogurt-audio-win/src/win/mod.rs
@@ -1,4 +1,5 @@
-//! WASAPI: microphones, the computer's sound (process loopback that leaves Yogurt out, else the whole output), device events.
+//! WASAPI: microphones, the computer's sound (the default output and communication device, or process loopback that
+//! leaves Yogurt out when asked for), device events.
//! Shared mode only, never the communications role or exclusive mode, so a call app keeps its mic just as it was.
#![allow(non_snake_case)]
@@ -24,10 +25,10 @@ use crate::out::log;
pub enum Ev {
Mic(Vec<f32>, u64, Option<f64>),
MicLost(u64),
- /// the computer's sound and the meeting time it was heard at
- Sys(Vec<f32>, f64),
+ /// the computer's sound from one output (its place in the mix) and the meeting time it was heard at
+ Sys(usize, Vec<f32>, f64),
SysLost,
- /// the default output (true) or input changed
+ /// the default output or communication device (true), or the default input, changed
Default(bool),
/// some device came, went or changed state
Devices,
@@ -342,19 +343,53 @@ pub fn start_mic(uid: Option<String>, tx: Sender<Ev>, generation: u64, clock: Cl
)
}
-/// The computer's sound: the whole default output, Yogurt's own sound included (Yogurt plays nothing while recording
-/// unless asked). Process loopback, every app except Yogurt (Windows 10 2004 and newer), only on YOGURT_AUDIO_LOOPBACK=process:
-/// it heard nothing of Teams on some computers (#35).
-pub fn start_system(tx: Sender<Ev>, clock: Clock) -> Result<Stream, StartError> {
+/// The outputs to record: the default output, and the default communication device when it's another one (#167)
+pub fn default_outputs() -> Vec<String> {
+ let Ok(e) = enumerator() else { return Vec::new() };
+ let id = |role| unsafe { e.GetDefaultAudioEndpoint(eRender, role) }.ok().as_ref().and_then(device_id);
+ crate::mix::outputs(id(eConsole), id(eCommunications))
+}
+
+/// The computer's sound, one stream per output it plays to; more than one is mixed into `them`.
+/// Every output by default: the default output, and the default communication device where Teams plays calls when it
+/// differs (#167), Yogurt's own sound included (Yogurt plays nothing while recording unless asked).
+/// Process loopback, every app except Yogurt (Windows 10 2004 and newer), only on YOGURT_AUDIO_LOOPBACK=process:
+/// it heard nothing of the new Teams on the very device it played to on some computers (#35, a Jabra headset).
+pub fn start_system(tx: Sender<Ev>, clock: Clock) -> Result<Vec<Stream>, StartError> {
+ if std::env::var("YOGURT_AUDIO_LOOPBACK").as_deref() == Ok("process") {
+ return start_output(0, None, true, tx, clock).map(|s| vec![s]);
+ }
+ let ids = default_outputs();
+ if ids.is_empty() {
+ return Err(StartError::NoDevice);
+ }
+ let mut streams = Vec::new();
+ let mut last = StartError::NoDevice;
+ for id in ids {
+ // its place in the mix: only outputs that started count
+ match start_output(streams.len(), Some(id), false, tx.clone(), clock) {
+ Ok(s) => streams.push(s),
+ Err(e) => {
+ log(&format!("an output couldn't be recorded: {e:?}"));
+ last = e;
+ }
+ }
+ }
+ if streams.is_empty() {
+ Err(last)
+ } else {
+ Ok(streams)
+ }
+}
+
+/// One output's sound: the device with this ID (else the default output), or process loopback when asked for
+fn start_output(lane: usize, id: Option<String>, process: bool, tx: Sender<Ev>, clock: Clock) -> Result<Stream, StartError> {
let lost_tx = tx.clone();
let mut gap = GapFiller::new(clock.now_ms());
spawn(
move || {
- let parent = parent_pid();
- // The whole output by default: process loopback ("every app except Yogurt") heard nothing of the new Teams
- // on the very device it played to (#35, a Jabra headset as the default output). YOGURT_AUDIO_LOOPBACK=process
- // still asks for it (CI tests both).
- if parent != 0 && std::env::var("YOGURT_AUDIO_LOOPBACK").as_deref() == Ok("process") {
+ let parent = if process { parent_pid() } else { 0 };
+ if parent != 0 {
match process_loopback(parent) {
Ok(client) => match initialize(&client, true) {
Ok(ch) => {
@@ -366,10 +401,20 @@ pub fn start_system(tx: Sender<Ev>, clock: Clock) -> Result<Stream, StartError>
Err(e) => log(&format!("process loopback isn't available ({e}): recording the whole output")),
}
}
- let dev = unsafe { enumerator().map_err(start_error)?.GetDefaultAudioEndpoint(eRender, eConsole) }.map_err(|_| StartError::NoDevice)?;
+ let e = enumerator().map_err(start_error)?;
+ let dev = match &id {
+ Some(id) => unsafe { e.GetDevice(&HSTRING::from(id.as_str())) },
+ None => unsafe { e.GetDefaultAudioEndpoint(eRender, eConsole) },
+ }
+ .map_err(|_| StartError::NoDevice)?;
let client: IAudioClient = unsafe { dev.Activate(CLSCTX_ALL, None) }.map_err(start_error)?;
let ch = initialize(&client, true).map_err(start_error)?;
- log("system audio: the whole output, Yogurt's own sound included");
+ let name = friendly_name(&dev).unwrap_or_default();
+ if lane == 0 {
+ log(&format!("system audio: the whole output, Yogurt's own sound included ({name})"));
+ } else {
+ log(&format!("system audio: the communication device too, where calls play ({name})"));
+ }
Ok((client, ch, false))
},
move |p| match p {
@@ -378,12 +423,12 @@ pub fn start_system(tx: Sender<Ev>, clock: Clock) -> Result<Stream, StartError>
let heard = if qpc != 0 { clock.qpc_ms(qpc) } else { clock.now_ms() - frames as f64 / 48.0 };
let skip = gap.packet(heard, frames);
if skip < frames {
- let _ = tx.send(Ev::Sys(s[skip..].to_vec(), heard + skip as f64 / 48.0));
+ let _ = tx.send(Ev::Sys(lane, s[skip..].to_vec(), heard + skip as f64 / 48.0));
}
}
None => {
if let Some((at, frames)) = gap.idle(clock.now_ms()) {
- let _ = tx.send(Ev::Sys(vec![0.0; frames], at));
+ let _ = tx.send(Ev::Sys(lane, vec![0.0; frames], at));
}
}
},
@@ -502,8 +547,11 @@ impl IMMNotificationClient_Impl for Watcher_Impl {
Ok(())
}
fn OnDefaultDeviceChanged(&self, flow: EDataFlow, role: ERole, _id: &PCWSTR) -> WinResult<()> {
- if role == eConsole {
- let _ = self.0.send(Ev::Default(flow == eRender));
+ // calls play on the communication device (#167), so a new one is recorded too
+ if flow == eRender && (role == eConsole || role == eCommunications) {
+ let _ = self.0.send(Ev::Default(true));
+ } else if flow == eCapture && role == eConsole {
+ let _ = self.0.send(Ev::Default(false));
}
Ok(())
}