Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(capture): record the microphone the user picked, in one mixed track

Etienne Lescote1123e1bf4d3
diff --git a/electron/native/pipewire-capture/csrc/pw_audio.c b/electron/native/pipewire-capture/csrc/pw_audio.c
index 6c3531599..9c86c673e 100644
--- a/electron/native/pipewire-capture/csrc/pw_audio.c
+++ b/electron/native/pipewire-capture/csrc/pw_audio.c
@@ -261,3 +261,157 @@ void osc_pw_audio_stop(struct osc_pw_audio *audio)
osc_audio_api.thread_loop_destroy(audio->loop);
free(audio);
}
+
+/* ---------------------------------------------------------------------------
+ * Enumeration of audio sources
+ *
+ * WHY THIS IS NEEDED AT ALL. The app's microphone picker lists Chromium's
+ * `MediaDeviceInfo`, whose `deviceId` is an opaque hash and whose `label` is a
+ * human string. Neither is a PipeWire `node.name`, and `PW_KEY_TARGET_OBJECT`
+ * accepts only a node name (or a serial). With no target, pw_stream connects to
+ * the session DEFAULT source — which is why a user who picked their built-in
+ * microphone in the HUD got the empty headphone jack recorded instead.
+ *
+ * So the helper enumerates the graph itself and resolves the label against
+ * `node.description`, which is exactly the string Chromium surfaces as the
+ * device label on a PipeWire system.
+ * ------------------------------------------------------------------------- */
+
+struct osc_pw_enum {
+ struct pw_main_loop *loop;
+ struct pw_context *context;
+ struct pw_core *core;
+ struct pw_registry *registry;
+ struct spa_hook registry_listener;
+ struct spa_hook core_listener;
+ int sync_seq;
+ /* Caller's buffer, filled as "name\037description\036" records. */
+ char *out;
+ size_t out_len;
+ size_t out_used;
+};
+
+static void osc_enum_append(struct osc_pw_enum *e, const char *name, const char *desc)
+{
+ size_t need;
+
+ if (name == NULL || name[0] == '\0') {
+ return;
+ }
+ if (desc == NULL) {
+ desc = "";
+ }
+ /* +2 for the two separators, +1 for the trailing NUL the Rust side reads. */
+ need = strlen(name) + strlen(desc) + 3;
+ if (e->out_used + need > e->out_len) {
+ return; /* Buffer full: report what fits rather than truncating a record. */
+ }
+ e->out_used += (size_t)snprintf(e->out + e->out_used, e->out_len - e->out_used,
+ "%s\037%s\036", name, desc);
+}
+
+static void osc_enum_on_global(void *data, uint32_t id, uint32_t permissions, const char *type,
+ uint32_t version, const struct spa_dict *props)
+{
+ struct osc_pw_enum *e = data;
+ const char *media_class;
+
+ (void)id;
+ (void)permissions;
+ (void)version;
+ if (props == NULL || type == NULL || strcmp(type, PW_TYPE_INTERFACE_Node) != 0) {
+ return;
+ }
+ media_class = spa_dict_lookup(props, PW_KEY_MEDIA_CLASS);
+ /* Only real capture devices. "Audio/Source" covers microphones and line-in;
+ * a sink's monitor is "Audio/Sink" and is reached via capture_sink instead,
+ * so listing it here would offer the user a duplicate of system audio. */
+ if (media_class == NULL || strcmp(media_class, "Audio/Source") != 0) {
+ return;
+ }
+ osc_enum_append(e, spa_dict_lookup(props, PW_KEY_NODE_NAME),
+ spa_dict_lookup(props, PW_KEY_NODE_DESCRIPTION));
+}
+
+static const struct pw_registry_events osc_enum_registry_events = {
+ PW_VERSION_REGISTRY_EVENTS,
+ .global = osc_enum_on_global,
+};
+
+static void osc_enum_on_core_done(void *data, uint32_t id, int seq)
+{
+ struct osc_pw_enum *e = data;
+
+ /* The registry replays every existing global BEFORE answering our sync, so
+ * a matching `done` means the initial dump is complete. Without this we
+ * would have to guess at a timeout and would race a busy graph. */
+ if (id == PW_ID_CORE && seq == e->sync_seq) {
+ osc_audio_api.main_loop_quit(e->loop);
+ }
+}
+
+static const struct pw_core_events osc_enum_core_events = {
+ PW_VERSION_CORE_EVENTS,
+ .done = osc_enum_on_core_done,
+};
+
+int osc_pw_list_audio_sources(char *out, size_t out_len, char *err, size_t err_len)
+{
+ struct osc_pw_enum e;
+ int result = -1;
+
+ if (osc_audio_api.main_loop_new == NULL) {
+ osc_pw_set_error(err, err_len, "osc_pw_list_audio_sources called before osc_pw_load");
+ return -1;
+ }
+ memset(&e, 0, sizeof(e));
+ e.out = out;
+ e.out_len = out_len;
+ if (out_len > 0) {
+ out[0] = '\0';
+ }
+
+ /* A plain main loop, not the thread loop the streams use: this call is
+ * synchronous by design — it runs the loop until the registry dump is done
+ * and then returns, so there is no thread to hand off to. */
+ e.loop = osc_audio_api.main_loop_new(NULL);
+ if (e.loop == NULL) {
+ osc_pw_set_error(err, err_len, "pw_main_loop_new failed");
+ return -1;
+ }
+ e.context = osc_audio_api.context_new(osc_audio_api.main_loop_get_loop(e.loop), NULL, 0);
+ if (e.context == NULL) {
+ osc_pw_set_error(err, err_len, "pw_context_new failed");
+ goto out;
+ }
+ e.core = osc_audio_api.context_connect(e.context, NULL, 0);
+ if (e.core == NULL) {
+ osc_pw_set_error(err, err_len, "pw_context_connect failed: no PipeWire session reachable");
+ goto out;
+ }
+ e.registry = pw_core_get_registry(e.core, PW_VERSION_REGISTRY, 0);
+ if (e.registry == NULL) {
+ osc_pw_set_error(err, err_len, "pw_core_get_registry failed");
+ goto out;
+ }
+
+ pw_registry_add_listener(e.registry, &e.registry_listener, &osc_enum_registry_events, &e);
+ pw_core_add_listener(e.core, &e.core_listener, &osc_enum_core_events, &e);
+ e.sync_seq = pw_core_sync(e.core, PW_ID_CORE, 0);
+
+ osc_audio_api.main_loop_run(e.loop);
+ result = 0;
+
+out:
+ if (e.registry != NULL) {
+ osc_audio_api.proxy_destroy((struct pw_proxy *)e.registry);
+ }
+ if (e.core != NULL) {
+ osc_audio_api.core_disconnect(e.core);
+ }
+ if (e.context != NULL) {
+ osc_audio_api.context_destroy(e.context);
+ }
+ osc_audio_api.main_loop_destroy(e.loop);
+ return result;
+}
diff --git a/electron/native/pipewire-capture/csrc/pw_internal.h b/electron/native/pipewire-capture/csrc/pw_internal.h
index e9bc02c49..a78f08779 100644
--- a/electron/native/pipewire-capture/csrc/pw_internal.h
+++ b/electron/native/pipewire-capture/csrc/pw_internal.h
@@ -48,6 +48,14 @@ struct osc_pw_audio_api {
struct pw_buffer *(*stream_dequeue_buffer)(struct pw_stream *stream);
int (*stream_queue_buffer)(struct pw_stream *stream, struct pw_buffer *buffer);
const char *(*stream_state_as_string)(enum pw_stream_state state);
+ /* Enumeration only (osc_pw_list_audio_sources): a synchronous main loop
+ * rather than the thread loop the streams use. */
+ struct pw_main_loop *(*main_loop_new)(const struct spa_dict *props);
+ void (*main_loop_destroy)(struct pw_main_loop *loop);
+ struct pw_loop *(*main_loop_get_loop)(struct pw_main_loop *loop);
+ int (*main_loop_run)(struct pw_main_loop *loop);
+ int (*main_loop_quit)(struct pw_main_loop *loop);
+ void (*proxy_destroy)(struct pw_proxy *proxy);
};
extern struct osc_pw_audio_api osc_audio_api;
diff --git a/electron/native/pipewire-capture/csrc/pw_shim.c b/electron/native/pipewire-capture/csrc/pw_shim.c
index b96cdb5ff..d12665f35 100644
--- a/electron/native/pipewire-capture/csrc/pw_shim.c
+++ b/electron/native/pipewire-capture/csrc/pw_shim.c
@@ -250,6 +250,12 @@ int osc_pw_load(char *err, size_t err_len)
OSC_LOAD_AUDIO(stream_dequeue_buffer, "pw_stream_dequeue_buffer");
OSC_LOAD_AUDIO(stream_queue_buffer, "pw_stream_queue_buffer");
OSC_LOAD_AUDIO(stream_state_as_string, "pw_stream_state_as_string");
+ OSC_LOAD_AUDIO(main_loop_new, "pw_main_loop_new");
+ OSC_LOAD_AUDIO(main_loop_destroy, "pw_main_loop_destroy");
+ OSC_LOAD_AUDIO(main_loop_get_loop, "pw_main_loop_get_loop");
+ OSC_LOAD_AUDIO(main_loop_run, "pw_main_loop_run");
+ OSC_LOAD_AUDIO(main_loop_quit, "pw_main_loop_quit");
+ OSC_LOAD_AUDIO(proxy_destroy, "pw_proxy_destroy");
#undef OSC_LOAD_AUDIO
#undef OSC_LOAD
diff --git a/electron/native/pipewire-capture/csrc/pw_shim.h b/electron/native/pipewire-capture/csrc/pw_shim.h
index ad12b81d3..f67cd33f0 100644
--- a/electron/native/pipewire-capture/csrc/pw_shim.h
+++ b/electron/native/pipewire-capture/csrc/pw_shim.h
@@ -202,6 +202,20 @@ struct osc_pw_audio *osc_pw_audio_start(const char *target_object, int capture_s
/* Stops the thread loop, joins it, and frees everything. Safe with NULL. */
void osc_pw_audio_stop(struct osc_pw_audio *audio);
+/*
+ * Lists the graph's audio CAPTURE nodes into `out` as records
+ * "node.name\037node.description\036", NUL-terminated.
+ *
+ * Synchronous: it runs a main loop until the registry has replayed every
+ * existing global, then returns. Needed because the app's microphone picker
+ * carries Chromium device labels, and PW_KEY_TARGET_OBJECT only accepts a
+ * PipeWire node name — without this the stream falls back to the session
+ * default source, which is rarely the microphone the user picked.
+ *
+ * Returns 0 on success, -1 with a message in `err`.
+ */
+int osc_pw_list_audio_sources(char *out, size_t out_len, char *err, size_t err_len);
+
#ifdef __cplusplus
}
#endif
diff --git a/electron/native/pipewire-capture/src/capture.rs b/electron/native/pipewire-capture/src/capture.rs
index e129d6e78..aaed89278 100644
--- a/electron/native/pipewire-capture/src/capture.rs
+++ b/electron/native/pipewire-capture/src/capture.rs
@@ -41,16 +41,111 @@ pub struct AudioSource {
pub bitrate: i64,
}
-struct AudioTrack {
+/// One capture feeding the mix.
+struct AudioInput {
label: &'static str,
ring: Arc<AudioRing>,
gain: f32,
+ /// Samples drained but not yet mixed, because the other inputs had fewer.
+ pending: Vec<f32>,
+}
+
+/// The single AAC track, and everything mixed into it.
+///
+/// ONE TRACK, NOT ONE PER SOURCE. The first shape of this code followed macOS
+/// and wrote system audio and the microphone as two separate AAC tracks, on the
+/// grounds that the export mixes every track it finds
+/// (`crates/compositor/src/audio.rs`). What that missed is that THE PREVIEW DOES
+/// NOT: it plays an HTML5 `<video>` element, which plays only the default audio
+/// track and cannot be told to switch, because Chromium does not implement the
+/// `audioTracks` API. With system audio first and nothing playing, the preview
+/// was silent while the microphone sat in a track nothing would ever select.
+///
+/// The Windows helper has always written one mixed track
+/// (`mf_encoder.cpp` has a single `audioStreamIndex_`, fed by `AudioMixer`).
+/// This now matches it. macOS still has the two-track bug.
+struct AudioMix {
+ inputs: Vec<AudioInput>,
encoder: AudioEncoder,
track: TrackId,
/// Reused across drains so the steady state allocates nothing.
scratch: Vec<f32>,
}
+/// How far one input may lag behind another before it is treated as silent
+/// rather than allowed to stall the track.
+///
+/// Mixing consumes `min(available)` across inputs so that neither runs ahead of
+/// the other. Taken literally that means one dead input — a microphone
+/// unplugged mid-recording — freezes the whole track, because its `min` stays
+/// zero forever. A quarter of a second of slack is far more than the jitter
+/// between two streams of the same 48 kHz graph, and far less than anyone can
+/// hear as a gap.
+const AUDIO_STARVE_SAMPLES: usize = AUDIO_SAMPLE_RATE as usize / 4 * AUDIO_CHANNELS;
+
+impl AudioMix {
+ /// Drains every input, mixes what they have in common, and encodes it.
+ ///
+ /// `flush` is set once at stop: it mixes whatever remains even when the
+ /// inputs are unevenly filled, because there will be no more samples to even
+ /// them out.
+ fn pump(&mut self, muxer: &mut Muxer, flush: bool) -> Result<(), String> {
+ for input in &mut self.inputs {
+ input.ring.drain_into(&mut input.pending);
+ }
+
+ let shortest = self.inputs.iter().map(|i| i.pending.len()).min().unwrap_or(0);
+ let longest = self.inputs.iter().map(|i| i.pending.len()).max().unwrap_or(0);
+ // Normally consume only what every input can supply, so none runs ahead.
+ // When one has fallen far behind — or at flush, when nothing more is
+ // coming — take the longest and let the short ones contribute silence,
+ // rather than letting a dead input freeze the track. See
+ // AUDIO_STARVE_SAMPLES.
+ let take = if flush || longest.saturating_sub(shortest) > AUDIO_STARVE_SAMPLES {
+ longest
+ } else {
+ shortest
+ };
+ if take == 0 {
+ return Ok(());
+ }
+
+ self.scratch.clear();
+ self.scratch.resize(take, 0.0);
+ for input in &mut self.inputs {
+ let n = input.pending.len().min(take);
+ for (out, sample) in self.scratch.iter_mut().zip(input.pending.drain(..n)) {
+ // Summed, then clamped ONCE at the end rather than per input:
+ // clamping each contribution would quietly attenuate the mix
+ // whenever one source alone is already near full scale.
+ *out += sample * input.gain;
+ }
+ }
+ for sample in &mut self.scratch {
+ // A boosted microphone over loud system audio must clip flat. An
+ // out-of-range float survives until AAC quantises it and then wraps
+ // to the opposite polarity, which sounds like a burst of noise.
+ *sample = sample.clamp(-1.0, 1.0);
+ }
+
+ let id = self.track;
+ let scratch = std::mem::take(&mut self.scratch);
+ let result = self.encoder.push(&scratch, |packet| muxer.write(id, packet));
+ self.scratch = scratch;
+ result
+ }
+
+ /// Samples the rings had to discard, per input. Audible, unlike a dropped
+ /// video frame.
+ fn dropped(&self) -> Vec<(&'static str, u64)> {
+ self.inputs
+ .iter()
+ .map(|input| (input.label, input.ring.dropped_samples()))
+ .filter(|(_, dropped)| *dropped > 0)
+ .collect()
+ }
+}
+
/// Frames encoded in one `advance` before returning to the event loop.
///
/// Without a bound, a long stall would be paid back in a single burst that also
@@ -97,7 +192,7 @@ pub struct Summary {
pub struct Capture {
encoder: VideoEncoder,
video_track: TrackId,
- audio: Vec<AudioTrack>,
+ audio: Option<AudioMix>,
/// `None` only between [`Self::finish`] taking it and the struct dropping.
muxer: Option<Muxer>,
path: PathBuf,
@@ -142,19 +237,28 @@ impl Capture {
// there, so an audio stream opened later could not be added at all.
let mut muxer = Muxer::create(path)?;
let video_track = muxer.add_stream(encoder.codec_context())?;
- let mut audio = Vec::with_capacity(audio_sources.len());
- for source in audio_sources {
- let encoder = AudioEncoder::open(source.bitrate)?;
+ // ONE encoder and ONE track for however many captures there are.
+ let audio = if audio_sources.is_empty() {
+ None
+ } else {
+ let bitrate = audio_sources.iter().map(|s| s.bitrate).max().unwrap_or(128_000);
+ let encoder = AudioEncoder::open(bitrate)?;
let track = muxer.add_stream(encoder.codec_context())?;
- audio.push(AudioTrack {
- label: source.label,
- ring: source.ring,
- gain: source.gain,
+ Some(AudioMix {
+ inputs: audio_sources
+ .into_iter()
+ .map(|source| AudioInput {
+ label: source.label,
+ ring: source.ring,
+ gain: source.gain,
+ pending: Vec::new(),
+ })
+ .collect(),
encoder,
track,
scratch: Vec::new(),
- });
- }
+ })
+ };
muxer.write_header()?;
Ok((
@@ -187,8 +291,11 @@ impl Capture {
// it belongs to the recording: video frame 0 is now, so audio
// sample 0 is now too. Keeping the backlog would shift the whole
// track earlier by however long the user took to click.
- for track in &self.audio {
- track.ring.clear();
+ if let Some(mix) = &mut self.audio {
+ for input in &mut mix.inputs {
+ input.ring.clear();
+ input.pending.clear();
+ }
}
}
Ok(())
@@ -224,24 +331,8 @@ impl Capture {
// recreated at any time; a missed audio sample cannot, and the ring
// drops the oldest once it fills. Draining every wakeup keeps it far
// from that cap — at 48 kHz a 16 ms tick carries about 768 samples.
- for track in &mut self.audio {
- track.scratch.clear();
- track.ring.drain_into(&mut track.scratch);
- if track.scratch.is_empty() {
- continue;
- }
- if track.gain != 1.0 {
- for sample in &mut track.scratch {
- // Clamped: a boosted microphone that clips should clip
- // flat, not wrap around to the opposite polarity, which is
- // what an out-of-range float does once AAC quantises it.
- *sample = (*sample * track.gain).clamp(-1.0, 1.0);
- }
- }
- let id = track.track;
- track
- .encoder
- .push(&track.scratch, |packet| muxer.write(id, packet))?;
+ if let Some(mix) = self.audio.as_mut() {
+ mix.pump(muxer, false)?;
}
Ok(written)
}
@@ -259,8 +350,11 @@ impl Capture {
// the video timeline did not advance across the pause, so keeping
// the audio would push every later sample out of sync by the length
// of the pause.
- for track in &self.audio {
- track.ring.clear();
+ if let Some(mix) = &mut self.audio {
+ for input in &mut mix.inputs {
+ input.ring.clear();
+ input.pending.clear();
+ }
}
}
}
@@ -268,11 +362,7 @@ impl Capture {
/// Samples the rings had to discard because the encoder fell behind, per
/// track. Audible if non-zero, unlike a dropped video frame.
pub fn dropped_audio(&self) -> Vec<(&'static str, u64)> {
- self.audio
- .iter()
- .map(|track| (track.label, track.ring.dropped_samples()))
- .filter(|(_, dropped)| *dropped > 0)
- .collect()
+ self.audio.as_ref().map(AudioMix::dropped).unwrap_or_default()
}
pub fn is_paused(&self) -> bool {
@@ -287,21 +377,13 @@ impl Capture {
.ok_or_else(|| "capture was already finished".to_owned())?;
// Audio first: whatever is still in the rings is real recorded sound,
- // and draining it after the video flush keeps both tracks ending at
- // roughly the same timestamp.
- for track in &mut self.audio {
- track.scratch.clear();
- track.ring.drain_into(&mut track.scratch);
- if track.gain != 1.0 {
- for sample in &mut track.scratch {
- *sample = (*sample * track.gain).clamp(-1.0, 1.0);
- }
- }
- let id = track.track;
- track
- .encoder
- .push(&track.scratch, |packet| muxer.write(id, packet))?;
- track.encoder.finish(|packet| muxer.write(id, packet))?;
+ // and draining it before the video flush keeps both ending at roughly
+ // the same timestamp. `flush` lets the mix take unevenly-filled inputs,
+ // since no more samples are coming to even them out.
+ if let Some(mix) = self.audio.as_mut() {
+ mix.pump(&mut muxer, true)?;
+ let id = mix.track;
+ mix.encoder.finish(|packet| muxer.write(id, packet))?;
}
let video_track = self.video_track;
@@ -526,9 +608,10 @@ mod tests {
.expect("stage");
// stage() cleared the pre-roll, so feed the samples the run will see.
- capture.audio[0].ring.push_for_test(&[0.9, -0.9, 0.4, -0.4]);
+ let mix = capture.audio.as_ref().expect("a mix exists");
+ mix.inputs[0].ring.push_for_test(&[0.9, -0.9, 0.4, -0.4]);
capture.advance().expect("advance");
- for sample in &capture.audio[0].scratch {
+ for sample in &capture.audio.as_ref().unwrap().scratch {
assert!(
(-1.0..=1.0).contains(sample),
"gain produced {sample}, which is outside the representable range"
@@ -537,6 +620,94 @@ mod tests {
let _ = std::fs::remove_file(&output);
}
+ #[test]
+ fn two_captures_become_one_muxed_track() {
+ // THE regression this guards. Two separate AAC tracks meant the preview
+ // — an HTML5 <video>, which plays only the default track and cannot
+ // switch — heard whichever came first. With system audio silent, that
+ // was silence, while the microphone sat in a track nothing selects.
+ let system = Arc::new(AudioRing::new(1, AUDIO_SAMPLE_RATE as usize, AUDIO_CHANNELS));
+ let mic = Arc::new(AudioRing::new(1, AUDIO_SAMPLE_RATE as usize, AUDIO_CHANNELS));
+ let output = std::env::temp_dir().join("openscreen-capture-one-track.mp4");
+ let (mut capture, _) = Capture::start(
+ &output,
+ 320,
+ 240,
+ 30,
+ Some(1_000_000),
+ Some(Backend::Software),
+ vec![
+ AudioSource { label: "system", ring: system.clone(), gain: 1.0, bitrate: 128_000 },
+ AudioSource { label: "microphone", ring: mic.clone(), gain: 1.0, bitrate: 128_000 },
+ ],
+ )
+ .expect("start");
+
+ let mix = capture.audio.as_ref().expect("a mix exists");
+ assert_eq!(mix.inputs.len(), 2, "both captures feed the mix");
+ let track = mix.track;
+
+ capture
+ .stage(&frame(320, 240, shim::constants().video_format_bgrx))
+ .expect("stage");
+ // stage() cleared the pre-roll, so feed after it.
+ system.push_for_test(&vec![0.25; 4096]);
+ mic.push_for_test(&vec![0.5; 4096]);
+ capture.advance().expect("advance");
+
+ let mix = capture.audio.as_ref().unwrap();
+ assert_eq!(mix.track, track, "there is exactly one audio track, and it never changes");
+ // The mixed scratch must carry BOTH contributions summed, not one of them.
+ assert!(
+ mix.scratch.iter().any(|s| (*s - 0.75).abs() < 1e-4),
+ "system 0.25 + mic 0.5 should sum to 0.75; got {:?}",
+ &mix.scratch[..mix.scratch.len().min(4)]
+ );
+
+ let summary = capture.finish().expect("finish");
+ assert!(summary.frames > 0);
+ let _ = std::fs::remove_file(&output);
+ }
+
+ #[test]
+ fn a_silent_input_cannot_freeze_the_track() {
+ // A microphone unplugged mid-recording stops filling its ring. Mixing
+ // strictly on min(available) would then wait for it forever and the
+ // whole audio track would stop — including the system audio that is
+ // still arriving. AUDIO_STARVE_SAMPLES is what breaks that deadlock.
+ let system = Arc::new(AudioRing::new(2, AUDIO_SAMPLE_RATE as usize, AUDIO_CHANNELS));
+ let dead = Arc::new(AudioRing::new(2, AUDIO_SAMPLE_RATE as usize, AUDIO_CHANNELS));
+ let output = std::env::temp_dir().join("openscreen-capture-starve.mp4");
+ let (mut capture, _) = Capture::start(
+ &output,
+ 320,
+ 240,
+ 30,
+ Some(1_000_000),
+ Some(Backend::Software),
+ vec![
+ AudioSource { label: "system", ring: system.clone(), gain: 1.0, bitrate: 128_000 },
+ AudioSource { label: "microphone", ring: dead, gain: 1.0, bitrate: 128_000 },
+ ],
+ )
+ .expect("start");
+ capture
+ .stage(&frame(320, 240, shim::constants().video_format_bgrx))
+ .expect("stage");
+
+ // Well past the quarter-second slack, with the other input silent.
+ system.push_for_test(&vec![0.4; AUDIO_STARVE_SAMPLES + 8192]);
+ capture.advance().expect("advance");
+
+ let mix = capture.audio.as_ref().unwrap();
+ assert!(
+ mix.inputs[0].pending.len() < AUDIO_STARVE_SAMPLES,
+ "the live input should have been consumed, not held hostage: {} left",
+ mix.inputs[0].pending.len()
+ );
+ let _ = std::fs::remove_file(&output);
+ }
+
#[test]
fn catch_up_is_bounded_so_a_stall_cannot_block_stop() {
let output = std::env::temp_dir().join("openscreen-capture-catchup.mp4");
diff --git a/electron/native/pipewire-capture/src/main.rs b/electron/native/pipewire-capture/src/main.rs
index 7d2db6ce6..7f120d1bf 100644
--- a/electron/native/pipewire-capture/src/main.rs
+++ b/electron/native/pipewire-capture/src/main.rs
@@ -311,6 +311,27 @@ fn start_audio<W: Write>(
) -> (Vec<shim::AudioSession>, Vec<capture::AudioSource>) {
let mut sessions = Vec::new();
let mut sources = Vec::new();
+ // Enumerated ONCE for the whole recording, not per stream: it opens its own
+ // PipeWire connection and runs a loop to completion, so doing it per source
+ // would pay that cost twice for no new information.
+ let graph = if configs.iter().any(|c| c.target.is_some()) {
+ match shim::list_audio_sources() {
+ Ok(list) => list,
+ Err(message) => {
+ let _ = emitter.emit(&Event::Warning {
+ code: "audio-enumeration-failed".to_owned(),
+ message: format!(
+ "the PipeWire graph could not be listed, so the requested microphone \
+ cannot be resolved and the session default will be used instead: {message}"
+ ),
+ });
+ Vec::new()
+ }
+ }
+ } else {
+ Vec::new()
+ };
+
for config in configs {
let ring = Arc::new(shim::AudioRing::new(
AUDIO_RING_SECONDS,
@@ -318,8 +339,35 @@ fn start_audio<W: Write>(
encoder::AUDIO_CHANNELS,
));
let label = config.label;
+ // A label we cannot place resolves to None, which means "no target" —
+ // PipeWire then links to the session default source. That is the old
+ // behaviour and the right fallback: a default microphone beats none.
+ let resolved = config
+ .target
+ .as_deref()
+ .and_then(|wanted| resolve_microphone_node(wanted, &graph));
+ if let Some(wanted) = config.target.as_deref() {
+ let _ = emitter.emit(&Event::Debug {
+ code: "audio-target".to_owned(),
+ data: json_map([
+ ("label", wanted.into()),
+ ("resolvedNode", resolved.clone().into()),
+ ("graphSize", graph.len().into()),
+ ]),
+ });
+ if resolved.is_none() {
+ let _ = emitter.emit(&Event::Warning {
+ code: "microphone-not-found".to_owned(),
+ message: format!(
+ "no PipeWire capture node matches {wanted:?}, so the session default \
+ source will be recorded instead — which is often not the microphone \
+ the user picked."
+ ),
+ });
+ }
+ }
let session = shim::AudioSession::start(
- config.target.as_deref(),
+ resolved.as_deref(),
config.capture_sink,
encoder::AUDIO_SAMPLE_RATE as u32,
encoder::AUDIO_CHANNELS as u32,
@@ -942,3 +990,112 @@ fn json_map<const N: usize>(
.collect()
}
+
+/// Resolves the microphone the user picked in the app to a PipeWire `node.name`.
+///
+/// WHY A MATCH AND NOT A LOOKUP. The picker lists Chromium `MediaDeviceInfo`,
+/// whose `deviceId` is an opaque per-origin hash and whose `label` is a human
+/// string. Neither is a PipeWire node name, and `PW_KEY_TARGET_OBJECT` takes
+/// nothing else. On a PipeWire system Chromium's label IS the node's
+/// `node.description`, so matching on that is the bridge between the two
+/// namespaces — there is no id to look up.
+///
+/// Returning `None` is a real answer, not a failure: the caller then passes no
+/// target and PipeWire links to the session default source. That is the old
+/// behaviour, and it is the right fallback for a label we cannot place.
+fn resolve_microphone_node(label: &str, sources: &[shim::AudioSourceInfo]) -> Option<String> {
+ let wanted = label.trim();
+ if wanted.is_empty() {
+ return None;
+ }
+ // A caller that already knows the node name (a config file, a future
+ // picker) should not be forced through fuzzy matching.
+ if let Some(exact) = sources.iter().find(|s| s.name == wanted) {
+ return Some(exact.name.clone());
+ }
+ let folded = wanted.to_lowercase();
+ if let Some(exact) = sources.iter().find(|s| s.description.to_lowercase() == folded) {
+ return Some(exact.name.clone());
+ }
+ // Chromium decorates labels ("Digital Microphone (Family 17h/19h ...)"),
+ // and some descriptions are longer than the label, so containment is
+ // checked BOTH ways. Longest description first, so that when several nodes
+ // match a short label the most specific one wins rather than whichever the
+ // registry happened to announce first.
+ let mut candidates: Vec<&shim::AudioSourceInfo> = sources
+ .iter()
+ .filter(|s| {
+ let d = s.description.to_lowercase();
+ !d.is_empty() && (d.contains(&folded) || folded.contains(&d))
+ })
+ .collect();
+ candidates.sort_by_key(|s| std::cmp::Reverse(s.description.len()));
+ candidates.first().map(|s| s.name.clone())
+}
+
+#[cfg(test)]
+mod microphone_resolution_tests {
+ use super::*;
+
+ fn sources() -> Vec<shim::AudioSourceInfo> {
+ // The real graph of the machine this was debugged on.
+ vec![
+ shim::AudioSourceInfo {
+ name: "alsa_input.pci-0000_03_00.6.HiFi__hw_Generic_1__source".into(),
+ description: "Family 17h/19h HD Audio Controller Headphones Stereo Microphone"
+ .into(),
+ },
+ shim::AudioSourceInfo {
+ name: "alsa_input.pci-0000_03_00.6.HiFi__hw_acp6x__source".into(),
+ description: "Family 17h/19h HD Audio Controller Digital Microphone".into(),
+ },
+ ]
+ }
+
+ #[test]
+ fn matches_the_description_chromium_reports_as_the_label() {
+ // THE bug this exists for: the user picked the built-in microphone and
+ // the recording captured the empty headphone jack, because no target was
+ // passed and PipeWire fell back to the default source.
+ let node = resolve_microphone_node(
+ "Family 17h/19h HD Audio Controller Digital Microphone",
+ &sources(),
+ );
+ assert_eq!(node.as_deref(), Some("alsa_input.pci-0000_03_00.6.HiFi__hw_acp6x__source"));
+ }
+
+ #[test]
+ fn matches_a_decorated_or_shortened_label() {
+ // Chromium is not obliged to hand back the description verbatim.
+ assert_eq!(
+ resolve_microphone_node("Digital Microphone", &sources()).as_deref(),
+ Some("alsa_input.pci-0000_03_00.6.HiFi__hw_acp6x__source")
+ );
+ }
+
+ #[test]
+ fn a_node_name_passes_straight_through() {
+ let name = "alsa_input.pci-0000_03_00.6.HiFi__hw_Generic_1__source";
+ assert_eq!(resolve_microphone_node(name, &sources()).as_deref(), Some(name));
+ }
+
+ #[test]
+ fn an_unknown_label_falls_back_to_the_default_source() {
+ // `None` means "pass no target", which is the pre-fix behaviour. Better
+ // a default microphone than no audio at all.
+ assert_eq!(resolve_microphone_node("Blue Yeti", &sources()), None);
+ assert_eq!(resolve_microphone_node(" ", &sources()), None);
+ }
+
+ #[test]
+ fn prefers_the_most_specific_description_when_several_contain_the_label() {
+ // "Microphone" is a substring of both. Picking the first announced would
+ // make the result depend on registry ordering, which is not stable.
+ let node = resolve_microphone_node("Microphone", &sources());
+ assert_eq!(
+ node.as_deref(),
+ Some("alsa_input.pci-0000_03_00.6.HiFi__hw_Generic_1__source"),
+ "the longer description should win, deterministically"
+ );
+ }
+}
diff --git a/electron/native/pipewire-capture/src/shim.rs b/electron/native/pipewire-capture/src/shim.rs
index e7751f38a..0b30768c8 100644
--- a/electron/native/pipewire-capture/src/shim.rs
+++ b/electron/native/pipewire-capture/src/shim.rs
@@ -359,6 +359,55 @@ extern "C" {
err_len: usize,
) -> *mut RawAudioSession;
fn osc_pw_audio_stop(session: *mut RawAudioSession);
+ fn osc_pw_list_audio_sources(
+ out: *mut c_char,
+ out_len: usize,
+ err: *mut c_char,
+ err_len: usize,
+ ) -> i32;
+}
+
+/// One capture node in the PipeWire graph.
+#[derive(Debug, Clone, PartialEq)]
+pub struct AudioSourceInfo {
+ /// `node.name` — the only thing PW_KEY_TARGET_OBJECT accepts.
+ pub name: String,
+ /// `node.description` — the human string, and the one Chromium surfaces as
+ /// a device label on a PipeWire system. This is what makes matching the
+ /// app's microphone picker to a graph node possible at all.
+ pub description: String,
+}
+
+/// Lists the graph's audio capture nodes.
+///
+/// Synchronous and self-contained: it opens its own connection, runs a main loop
+/// until the registry has replayed every global, and tears down. Called once per
+/// recording, before the streams start.
+pub fn list_audio_sources() -> Result<Vec<AudioSourceInfo>, String> {
+ // 16 KiB holds ~200 nodes; a graph that large is already pathological, and
+ // the C side stops at a record boundary rather than truncating one.
+ let mut buffer = vec![0 as c_char; 16 * 1024];
+ let mut err = [0 as c_char; ERR_LEN];
+ // SAFETY: both buffers are live and correctly sized for the duration.
+ let result = unsafe {
+ osc_pw_list_audio_sources(buffer.as_mut_ptr(), buffer.len(), err.as_mut_ptr(), ERR_LEN)
+ };
+ if result != 0 {
+ return Err(take_error(&err));
+ }
+ // SAFETY: the C side always NUL-terminates within the buffer it was given.
+ let text = unsafe { CStr::from_ptr(buffer.as_ptr()) }.to_string_lossy().into_owned();
+ Ok(text
+ .split('\u{1e}')
+ .filter(|record| !record.is_empty())
+ .filter_map(|record| {
+ let (name, description) = record.split_once('\u{1f}')?;
+ Some(AudioSourceInfo {
+ name: name.to_owned(),
+ description: description.to_owned(),
+ })
+ })
+ .collect())
}
/// What an audio stream reports besides samples.
@@ -912,3 +961,23 @@ mod tests {
);
}
}
+
+#[cfg(test)]
+mod source_tests {
+ /// Prints the graph's capture nodes. Opt-in — it needs a live PipeWire
+ /// session, so CI skips it; run it by hand when the microphone a user picked
+ /// does not match what got recorded.
+ #[test]
+ fn lists_the_audio_sources_of_a_live_session() {
+ if std::env::var("OPENSCREEN_PIPEWIRE_LIST").is_err() {
+ eprintln!("skipped: set OPENSCREEN_PIPEWIRE_LIST=1 with a running PipeWire");
+ return;
+ }
+ super::load().expect("libpipewire must load");
+ let sources = super::list_audio_sources().expect("enumeration");
+ for source in &sources {
+ println!(" {} <- {}", source.name, source.description);
+ }
+ assert!(!sources.is_empty(), "a desktop session always has at least one capture node");
+ }
+}
diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.ts
index c42b2f8d4..4b397823e 100644
--- a/src/hooks/useScreenRecorder.ts
+++ b/src/hooks/useScreenRecorder.ts
@@ -1273,6 +1273,15 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
system: { enabled: systemAudioEnabled },
microphone: {
enabled: microphoneEnabled,
+ // The device LABEL, not the id. Chromium's deviceId is an
+ // opaque per-origin hash that means nothing to PipeWire,
+ // whereas on a PipeWire system the label IS the node's
+ // `node.description` — which is what the helper matches
+ // against the graph it enumerates. Sending nothing here is
+ // what made a user who picked their built-in microphone
+ // get the empty headphone jack recorded, because the
+ // helper then fell back to the session default source.
+ ...(microphoneDeviceName ? { deviceName: microphoneDeviceName } : {}),
gain: MIC_GAIN_BOOST,
},
},