Skip to content

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

test(recording): measure the Linux audio timeline instead of trusting it

Claude3944054374d7
diff --git a/electron/native/pipewire-capture/src/capture.rs b/electron/native/pipewire-capture/src/capture.rs
index 0b07c34a4..abfcfa668 100644
--- a/electron/native/pipewire-capture/src/capture.rs
+++ b/electron/native/pipewire-capture/src/capture.rs
@@ -62,8 +62,9 @@ struct AudioInput {
/// 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.
+/// (`mf_encoder.cpp` has a single `audioStreamIndex_`, fed by `AudioMixer`), and
+/// macOS has since done the same (`AudioTrackMixer` feeding the helper's single
+/// `AVAssetWriterInput(mediaType: .audio)`). All three now agree.
struct AudioMix {
inputs: Vec<AudioInput>,
encoder: AudioEncoder,
@@ -396,6 +397,17 @@ impl Capture {
pub fn pause(&mut self) {
if self.paused_at.is_none() {
self.paused_at = Some(Instant::now());
+ // The rings stop taking samples here rather than queueing them for
+ // the discard at resume. A queue nobody drains overflows the
+ // two-second cap within two seconds of a pause, and the discard that
+ // used to clear that overflow cleared the tally with it — taking any
+ // real drop from before the pause, which is the one worth reporting.
+ // See AudioRing::pause.
+ if let Some(mix) = &mut self.audio {
+ for input in &mut mix.inputs {
+ input.ring.pause();
+ }
+ }
}
}
@@ -408,7 +420,7 @@ impl Capture {
// of the pause.
if let Some(mix) = &mut self.audio {
for input in &mut mix.inputs {
- input.ring.clear();
+ input.ring.resume();
input.pending.clear();
}
}
@@ -781,6 +793,51 @@ mod tests {
let _ = std::fs::remove_file(&output);
}
+ #[test]
+ fn a_real_drop_before_a_pause_still_reaches_the_warning_after_it() {
+ // Regression: resume() threw away what arrived during the pause by
+ // clearing the ring, and the clear reset `dropped` — so an overflow that
+ // happened for real earlier in the take was forgotten, and the
+ // `audio-dropped` warning (main.rs) never fired for it. Pausing is the
+ // only thing between the user and the only report that a recording lost
+ // audio.
+ let ring = Arc::new(AudioRing::new(1, 8, AUDIO_CHANNELS));
+ let capacity = 1 * 8 * AUDIO_CHANNELS;
+
+ let output = std::env::temp_dir().join("openscreen-capture-audio-pause-drop.mp4");
+ let (mut capture, _) = Capture::start(
+ &output,
+ 320,
+ 240,
+ 30,
+ Some(1_000_000),
+ Some(Backend::Software),
+ vec![AudioSource { label: "system", ring: ring.clone(), gain: 1.0, bitrate: 128_000 }],
+ )
+ .expect("start");
+ capture
+ .stage(&frame(320, 240, shim::constants().video_format_bgrx))
+ .expect("stage");
+
+ // Mid-take: the encoder falls far enough behind that the ring overflows.
+ ring.push_for_test(&vec![0.5; capacity * 3]);
+ let dropped = ring.dropped_samples();
+ assert!(dropped > 0, "the ring must have overflowed for this test to mean anything");
+
+ capture.pause();
+ // A long pause. Nothing that arrives during it belongs to the recording,
+ // and none of it is the encoder falling behind either.
+ ring.push_for_test(&vec![0.5; capacity * 10]);
+ capture.resume();
+
+ assert_eq!(
+ capture.dropped_audio(),
+ vec![("system", dropped)],
+ "the pause must not spend the tally of a drop that happened before it"
+ );
+ let _ = std::fs::remove_file(&output);
+ }
+
#[test]
fn microphone_gain_clamps_instead_of_wrapping() {
// A boosted microphone that clips must clip flat. An out-of-range float
diff --git a/electron/native/pipewire-capture/src/encoder.rs b/electron/native/pipewire-capture/src/encoder.rs
index 6163efff7..e574ae405 100644
--- a/electron/native/pipewire-capture/src/encoder.rs
+++ b/electron/native/pipewire-capture/src/encoder.rs
@@ -925,13 +925,19 @@ struct MuxTrack {
stream_time_base: ff::AVRational,
}
-/// A multi-track MP4 writer: one video stream plus however many audio tracks.
+/// An MP4 writer, taking however many streams [`Self::add_stream`] is called for.
///
-/// Audio is written as separate tracks rather than pre-mixed, matching the macOS
-/// helper — see the note in crates/compositor/src/audio.rs, which decodes and
-/// mixes every audio track it finds on export. Keeping them apart means the two
-/// captures never have to be resampled onto a common clock here: each carries
-/// its own timestamps and the container reconciles them.
+/// WHAT A RECORDING ACTUALLY USES IS TWO: one H.264 video stream and one AAC
+/// track carrying system audio and the microphone already mixed together
+/// (`AudioMix` in crate::capture). This wrote them as two separate audio tracks
+/// once, matching what the macOS helper did, on the grounds that the export path
+/// mixes every track it finds (crates/compositor/src/audio.rs). The preview does
+/// not: it is an HTML5 `<video>`, which plays the default audio track and cannot
+/// be told to switch, because Chromium implements no `audioTracks` API — so a
+/// take with silent system audio played silence while the microphone sat in a
+/// track nothing would ever select. Mixing before the muxer is what fixed it,
+/// and it also removes the question of reconciling two capture clocks in the
+/// container: there is only one audio timeline now, built in `AudioMix::pump`.
///
/// `+faststart` is not used: it rewrites the whole file on close, which on a
/// long recording means copying gigabytes. The moov atom is written at the end
diff --git a/electron/native/pipewire-capture/src/main.rs b/electron/native/pipewire-capture/src/main.rs
index 1576efced..8ec4078c2 100644
--- a/electron/native/pipewire-capture/src/main.rs
+++ b/electron/native/pipewire-capture/src/main.rs
@@ -1108,7 +1108,8 @@ fn finish_capture<W: Write>(
code: "audio-dropped".to_owned(),
message: format!(
"{samples} {label} sample(s) were discarded because the encoder could not \
- keep up. Unlike a dropped video frame, this is audible."
+ keep up, and stand in the recording as that much silence. Unlike a dropped \
+ video frame, this is audible."
),
});
}
diff --git a/electron/native/pipewire-capture/src/shim.rs b/electron/native/pipewire-capture/src/shim.rs
index 8a4806ca4..8d38de962 100644
--- a/electron/native/pipewire-capture/src/shim.rs
+++ b/electron/native/pipewire-capture/src/shim.rs
@@ -295,55 +295,88 @@ impl FrameMailbox {
/// only as a backstop against a consumer that has stopped consuming entirely —
/// 48 kHz stereo f32 is 384 KB/s, so two seconds is under a megabyte.
///
-/// Overflow drops the OLDEST samples. If the encoder is that far behind, the
-/// recent audio is the part still worth keeping, and the alternative — refusing
-/// new samples — would freeze the track at the moment of the stall and leave
-/// everything after it misaligned.
+/// Overflow drops the OLDEST samples and OWES THE SAME NUMBER BACK AS SILENCE.
+/// Dropping the oldest is the easy half: if the encoder is that far behind, the
+/// recent audio is the part still worth keeping, and refusing new samples
+/// instead would freeze the track at the moment of the stall.
+///
+/// The silence is the half that matters, because a drop here leaves no hole.
+/// The encoder's presentation time is a running count of the samples handed to
+/// it (`AudioEncoder::next_pts`, encoder.rs), so removing samples does not shift
+/// the ones after them late — it pulls them EARLY, by the dropped duration, for
+/// the rest of the take. Every later sound would then sit before the picture it
+/// belongs to, permanently and by an amount nothing records. Standing in
+/// silence of exactly the dropped length keeps that count right, so an overflow
+/// costs a gap where it happened and nothing after it. The debt is a counter
+/// until someone drains, which is also the only thing that can stop it growing.
#[derive(Debug)]
pub struct AudioRing {
- inner: std::sync::Mutex<std::collections::VecDeque<f32>>,
+ inner: std::sync::Mutex<RingInner>,
capacity: usize,
dropped: std::sync::atomic::AtomicU64,
+ /// Whether the ring is taking samples at all. Cleared across a pause — see
+ /// [`Self::pause`].
+ accepting: std::sync::atomic::AtomicBool,
+}
+
+/// The queue and the silence owed in front of it, under one lock: a drain that
+/// took the samples without the silence would place them exactly as early as
+/// the silence exists to prevent.
+#[derive(Debug, Default)]
+struct RingInner {
+ queue: std::collections::VecDeque<f32>,
+ /// Samples dropped on overflow and not yet stood in for.
+ silence_owed: usize,
}
impl AudioRing {
pub fn new(seconds: usize, sample_rate: usize, channels: usize) -> Self {
Self {
- inner: std::sync::Mutex::new(std::collections::VecDeque::new()),
+ inner: std::sync::Mutex::new(RingInner::default()),
capacity: seconds * sample_rate * channels,
dropped: std::sync::atomic::AtomicU64::new(0),
+ accepting: std::sync::atomic::AtomicBool::new(true),
}
}
fn push(&self, samples: &[f32]) {
use std::sync::atomic::Ordering;
- let Ok(mut queue) = self.inner.lock() else {
+ // Paused. Refused at the door rather than queued and cleared later, so
+ // that the pause cannot spend the overflow tally — see `pause`.
+ if !self.accepting.load(Ordering::Relaxed) {
+ return;
+ }
+ let Ok(mut inner) = self.inner.lock() else {
self.dropped.fetch_add(samples.len() as u64, Ordering::Relaxed);
return;
};
- queue.extend(samples.iter().copied());
- if queue.len() > self.capacity {
- let excess = queue.len() - self.capacity;
- queue.drain(..excess);
+ inner.queue.extend(samples.iter().copied());
+ if inner.queue.len() > self.capacity {
+ let excess = inner.queue.len() - self.capacity;
+ inner.queue.drain(..excess);
+ inner.silence_owed += excess;
self.dropped.fetch_add(excess as u64, Ordering::Relaxed);
}
}
- /// Moves everything queued into `out`, appending.
+ /// Moves everything queued into `out`, appending — behind any silence the
+ /// ring owes for samples it had to drop.
pub fn drain_into(&self, out: &mut Vec<f32>) {
- let Ok(mut queue) = self.inner.lock() else {
+ let Ok(mut inner) = self.inner.lock() else {
return;
};
- out.reserve(queue.len());
- out.extend(queue.drain(..));
+ let owed = std::mem::take(&mut inner.silence_owed);
+ out.reserve(owed + inner.queue.len());
+ out.resize(out.len() + owed, 0.0);
+ out.extend(inner.queue.drain(..));
}
/// Discards everything queued, and forgets any overflow so far.
///
- /// Called when the video epoch is set and on resume: audio captured before
- /// the first frame, or during a pause, belongs to no part of the recording,
- /// and keeping it would offset the whole track.
+ /// Called when the video epoch is set: audio captured before the first frame
+ /// belongs to no part of the recording, and keeping it would offset the
+ /// whole track.
///
/// Resetting `dropped` is the point, not an afterthought. The stream is
/// opened before the portal picker is raised, so it records for however long
@@ -351,12 +384,45 @@ impl AudioRing {
/// that overflow would report "the encoder could not keep up" on every
/// single recording, for audio that was always going to be thrown away.
pub fn clear(&self) {
- if let Ok(mut queue) = self.inner.lock() {
- queue.clear();
+ if let Ok(mut inner) = self.inner.lock() {
+ inner.queue.clear();
+ inner.silence_owed = 0;
}
self.dropped.store(0, std::sync::atomic::Ordering::Relaxed);
}
+ /// Stops taking samples, and discards what is queued.
+ ///
+ /// Called when the recording is paused. Audio that arrives while it is
+ /// paused belongs to no part of it — the video timeline does not advance
+ /// across a pause, so keeping the audio would push every later sample out of
+ /// sync by the pause's length.
+ ///
+ /// REFUSING IT IS WHAT KEEPS `dropped_samples` HONEST. Leaving the queue
+ /// open through the pause and clearing at resume did the same thing to the
+ /// track, but a queue nobody drains overflows a two-second ring within two
+ /// seconds — so the clear at resume had to reset the tally too, and it took
+ /// any real mid-take overflow from BEFORE the pause with it. That drop then
+ /// never reached the `audio-dropped` warning (main.rs), which is the only
+ /// place a user is told the recording lost audio.
+ pub fn pause(&self) {
+ self.accepting.store(false, std::sync::atomic::Ordering::Relaxed);
+ if let Ok(mut inner) = self.inner.lock() {
+ inner.queue.clear();
+ inner.silence_owed = 0;
+ }
+ }
+
+ /// Takes samples again, from now. The discard covers a buffer a capture
+ /// thread was already inside [`Self::push`] with when [`Self::pause`] ran.
+ pub fn resume(&self) {
+ if let Ok(mut inner) = self.inner.lock() {
+ inner.queue.clear();
+ inner.silence_owed = 0;
+ }
+ self.accepting.store(true, std::sync::atomic::Ordering::Relaxed);
+ }
+
pub fn dropped_samples(&self) -> u64 {
self.dropped.load(std::sync::atomic::Ordering::Relaxed)
}
@@ -1073,3 +1139,96 @@ mod source_tests {
assert!(!sources.is_empty(), "a desktop session always has at least one capture node");
}
}
+
+#[cfg(test)]
+mod audio_ring_tests {
+ use super::AudioRing;
+
+ /// Capacity 16 samples — small enough to overflow by hand, and the unit the
+ /// ring counts in is interleaved samples, not frames.
+ fn ring() -> AudioRing {
+ AudioRing::new(1, 8, 2)
+ }
+
+ #[test]
+ fn overflow_is_stood_in_for_by_silence_rather_than_pulling_the_take_earlier() {
+ // THE regression. The encoder's timestamps are a running count of the
+ // samples it was handed (`AudioEncoder::next_pts`), so samples removed
+ // from the middle of the stream do not leave a hole — every later sound
+ // arrives that much earlier than the picture it belongs to, for the rest
+ // of the take, and nothing in the file records that it happened.
+ let ring = ring();
+ ring.push_for_test(&vec![1.0; 40]);
+ assert_eq!(ring.dropped_samples(), 24, "40 samples into a 16-sample ring drops 24");
+
+ let mut out = Vec::new();
+ ring.drain_into(&mut out);
+
+ assert_eq!(out.len(), 40, "the drain must cover as much time as was pushed");
+ assert!(out[..24].iter().all(|sample| *sample == 0.0), "the drop reads as silence");
+ assert!(out[24..].iter().all(|sample| *sample == 1.0), "the survivors are the newest");
+ }
+
+ #[test]
+ fn the_silence_owed_is_paid_once() {
+ let ring = ring();
+ ring.push_for_test(&vec![1.0; 40]);
+ let mut first = Vec::new();
+ ring.drain_into(&mut first);
+
+ ring.push_for_test(&[0.5, 0.5]);
+ let mut second = Vec::new();
+ ring.drain_into(&mut second);
+ assert_eq!(second, vec![0.5, 0.5], "a settled debt must not be paid again");
+ }
+
+ #[test]
+ fn a_pause_neither_queues_nor_counts_what_arrives() {
+ // What made the `audio-dropped` warning unreachable: audio kept arriving
+ // through a pause, overflowed the ring within two seconds, and the
+ // discard at resume reset the tally — including anything dropped for
+ // real before the pause.
+ let ring = ring();
+ ring.push_for_test(&vec![1.0; 40]);
+ let dropped_before_the_pause = ring.dropped_samples();
+ assert!(dropped_before_the_pause > 0, "the ring must have overflowed for this to mean anything");
+
+ ring.pause();
+ ring.push_for_test(&vec![1.0; 400]);
+ assert_eq!(
+ ring.dropped_samples(),
+ dropped_before_the_pause,
+ "a pause discards, it does not drop: nothing it threw away is the encoder falling behind"
+ );
+
+ ring.resume();
+ assert_eq!(
+ ring.dropped_samples(),
+ dropped_before_the_pause,
+ "and the real drop from before the pause is still there to be reported"
+ );
+
+ let mut out = Vec::new();
+ ring.drain_into(&mut out);
+ assert!(out.is_empty(), "nothing captured during the pause reaches the track");
+
+ ring.push_for_test(&[0.25, 0.25]);
+ ring.drain_into(&mut out);
+ assert_eq!(out, vec![0.25, 0.25], "and the ring takes samples again after it");
+ }
+
+ #[test]
+ fn clearing_forgets_the_overflow_and_the_silence_it_owed() {
+ // The pre-roll case: everything captured before the first video frame is
+ // thrown away wholesale, so neither the drop nor the gap it left is part
+ // of any recording.
+ let ring = ring();
+ ring.push_for_test(&vec![1.0; 40]);
+ ring.clear();
+ assert_eq!(ring.dropped_samples(), 0);
+
+ let mut out = Vec::new();
+ ring.drain_into(&mut out);
+ assert!(out.is_empty(), "a cleared ring owes no silence");
+ }
+}
diff --git a/package.json b/package.json
index da39a03b2..a1e524a36 100644
--- a/package.json
+++ b/package.json
@@ -75,6 +75,7 @@
"test:wgc-full:win": "node scripts/test-windows-wgc-helper.mjs --webcam --system-audio --microphone",
"test:sck-audio-timeline:mac": "node scripts/test-macos-audio-timeline.mjs",
"test:swift:mac": "swift test --package-path electron/native/screencapturekit",
+ "test:pw-audio-timeline:linux": "node scripts/test-linux-audio-timeline.mjs",
"capture:openscreen-preview": "node scripts/capture-openscreen-preview.mjs",
"inspect:cursor-click-bounce": "node scripts/inspect-native-cursor-click-bounce.mjs",
"diagnostic:run": "node scripts/diagnostic-tool/diagnostic.mjs",
diff --git a/scripts/test-linux-audio-timeline.mjs b/scripts/test-linux-audio-timeline.mjs
new file mode 100644
index 000000000..7ff62b1f7
--- /dev/null
+++ b/scripts/test-linux-audio-timeline.mjs
@@ -0,0 +1,483 @@
+/**
+ * Does a sound land where it happened, and does the track cover the whole take?
+ *
+ * The Linux sibling of scripts/test-macos-audio-timeline.mjs, asking the same questions
+ * of a helper that answers them for a different reason. Windows and macOS both had to
+ * move their audio timeline onto a clock (getopenscreen/openscreen#406, and the macOS
+ * anchor after it). Linux never did, and the code is not why: `AudioEncoder::next_pts`
+ * is a running count of the samples handed to the encoder — the same data-driven cursor
+ * Windows had — and `AudioMix::pump` returns early when no input has any. What holds the
+ * timeline up is the TAP. System audio here is the default sink's monitor, and PipeWire
+ * keeps delivering its buffers whether or not anything is playing, silence included,
+ * where the WASAPI loopback tap simply stops. So the count advances at real time and the
+ * cursor cannot stall.
+ *
+ * That is exactly why this is worth running: the property belongs to the capture source,
+ * not to the helper, and nothing in the helper would notice the day the source changed.
+ * The whole record that any of it held was one sentence in a commit message — a live
+ * 29-second capture, an 18-second tone coming back as 18 seconds of steady signal, the
+ * two streams ending 62 ms apart. This is that sentence, re-runnable.
+ *
+ * npm run test:pw-audio-timeline:linux
+ *
+ * Records ten seconds — four silent, three with a tone, three silent again — and measures
+ * where the tone sits and how long each track is. NOT unattended: the portal raises the
+ * compositor's own source picker and the take does not begin until someone answers it.
+ * The tone plays to the DEFAULT SINK, which has to be the sink whose monitor the helper
+ * captured, so this measures the machine as much as the code.
+ *
+ * Two tolerances, because the two measurements are not equally tight:
+ *
+ * - The tone's position is compared against the instant playback was ASKED for, so it
+ * carries the player's start-up latency and the node it creates being linked into the
+ * graph. 250 ms.
+ * - The audio track's length is compared against the VIDEO track's length in the same
+ * file — no wall clock enters that at all. 250 ms rather than the 100 ms macOS uses,
+ * because there the two tracks come out of one writer session and here they do not:
+ * the video track ends at the last `Capture::advance()` and the audio track at
+ * everything the rings still held, plus AAC's final padded block. Those measured
+ * 62 ms apart on a 29-second capture (video 29.100 s, audio 29.162 s), which is the
+ * number this bound is set around. It is still far tighter than the failure it is
+ * here for, which is a track that ends at the last sound and misses three seconds.
+ */
+import { spawn, spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const ROOT = path.join(__dirname, "..");
+
+const PLAY_AT_MS = Number(process.env.OPENSCREEN_PW_TEST_PLAY_AT_MS ?? 4000);
+const TONE_MS = 3000;
+/** Silence after the tone, so the trailing half of the timeline is exercised too. */
+const TAIL_MS = 3000;
+/** How far the tone may sit from where it was asked for before this is a failure. */
+const TONE_TOLERANCE_S = 0.25;
+/** How far the audio track may differ in length from the video track in the same file. */
+const TRACK_TOLERANCE_S = 0.25;
+/** Analysis window for locating the tone. Tight enough to resolve a 250 ms mis-rebase. */
+const WINDOW_MS = 20;
+/**
+ * How long to wait for the compositor's picker to be answered.
+ *
+ * Deliberately generous where the Windows and macOS scripts allow 30 s: those helpers
+ * start recording on their own, and this one cannot start until a human has clicked a
+ * dialog. The wait has no honest upper bound; this one only exists so an abandoned run
+ * eventually stops instead of holding a portal session open forever.
+ */
+const PICKER_TIMEOUT_MS = Number(process.env.OPENSCREEN_PW_TEST_PICKER_TIMEOUT_MS ?? 180_000);
+
+if (process.platform !== "linux") {
+ console.log("Linux only — skipping.");
+ process.exit(0);
+}
+
+const ARCH_TAG = `linux-${process.arch === "arm64" ? "arm64" : "x64"}`;
+/** The shared ffmpeg tree the helper itself links against (build.rs, fetch-ffmpeg.mjs). */
+const VENDORED_FFMPEG = path.join(ROOT, "crates", "thirdparty", "ffmpeg-linux64-lgpl-shared");
+
+/**
+ * A binary and whatever environment it needs to run, or null.
+ *
+ * Three places, in order of how self-contained they are. The vendored SHARED tree is the
+ * one that always answers on a machine that can build the helper at all — build.rs
+ * refuses to compile without it — and it is where ffprobe comes from, since the static
+ * CLI `npm run fetch:ffmpeg` vendors is ffmpeg alone. Its binaries do not resolve their
+ * own libraries, hence the explicit lib directory.
+ */
+function resolveTool(name) {
+ const fromEnv = process.env[`OPENSCREEN_${name.toUpperCase().replaceAll("-", "_")}`];
+ if (fromEnv && fs.existsSync(fromEnv)) return { bin: fromEnv, env: null };
+
+ const staticCli = path.join(ROOT, "electron", "native", "bin", ARCH_TAG, name);
+ if (fs.existsSync(staticCli)) return { bin: staticCli, env: null };
+
+ const shared = path.join(VENDORED_FFMPEG, "bin", name);
+ if (fs.existsSync(shared)) {
+ const libs = [path.join(VENDORED_FFMPEG, "lib"), process.env.LD_LIBRARY_PATH]
+ .filter(Boolean)
+ .join(":");
+ return { bin: shared, env: { LD_LIBRARY_PATH: libs } };
+ }
+
+ const onPath = spawnSync("/usr/bin/which", [name], { encoding: "utf8" });
+ const resolved = (onPath.stdout ?? "").trim();
+ return resolved && fs.existsSync(resolved) ? { bin: resolved, env: null } : null;
+}
+
+function runTool(tool, args, options = {}) {
+ return spawnSync(tool.bin, args, {
+ ...options,
+ env: tool.env ? { ...process.env, ...tool.env } : process.env,
+ });
+}
+
+/** Mirrors helperCandidates() in pipeWireCursorRecordingSession.ts, env var included. */
+function resolveHelper() {
+ const name = "openscreen-pipewire-helper";
+ const candidates = [
+ process.env.OPENSCREEN_LINUX_CURSOR_HELPER_EXE,
+ path.join(ROOT, "electron", "native", "pipewire-capture", "build", name),
+ path.join(ROOT, "electron", "native", "bin", ARCH_TAG, name),
+ ];
+ return candidates.find((candidate) => candidate && fs.existsSync(candidate)) ?? null;
+}
+
+/**
+ * Something that will play a WAV to the session's default sink.
+ *
+ * The order is about which graph the sound lands in. `pw-play` is PipeWire's own client
+ * and always lands on the session default, which is the sink whose monitor the helper is
+ * recording; `paplay` reaches the same graph through pipewire-pulse. ALSA is last because
+ * it can be pointed at a raw device that bypasses the graph entirely, in which case
+ * nothing reaches the monitor and the tone is simply missing from the file.
+ */
+const PLAYERS = [
+ { name: "pw-play", args: (tone) => [tone] },
+ { name: "paplay", args: (tone) => [tone] },
+ {
+ name: "ffplay",
+ args: (tone) => ["-hide_banner", "-loglevel", "error", "-nodisp", "-autoexit", tone],
+ },
+ { name: "aplay", args: (tone) => [tone] },
+];
+
+function resolvePlayer() {
+ const forced = process.env.OPENSCREEN_PW_TEST_PLAYER?.trim();
+ // A player named by hand still gets the argument list its basename is known for, so
+ // pointing at a specific ffplay does not silently lose `-nodisp`.
+ const known = PLAYERS.find((player) => player.name === path.basename(forced ?? ""));
+ const wanted = forced ? [{ name: forced, args: known?.args ?? ((tone) => [tone]) }] : PLAYERS;
+ for (const player of wanted) {
+ const tool = resolveTool(player.name);
+ if (tool) return { ...tool, name: path.basename(player.name), args: player.args };
+ }
+ return null;
+}
+
+const FFMPEG = resolveTool("ffmpeg");
+const FFPROBE = resolveTool("ffprobe");
+const HELPER = resolveHelper();
+const PLAYER = resolvePlayer();
+if (!HELPER) {
+ console.error("No PipeWire helper found. Run: npm run build:native:linux");
+ process.exit(1);
+}
+if (!FFMPEG || !FFPROBE) {
+ console.error(
+ "No ffmpeg/ffprobe found. Run `npm run fetch:ffmpeg:sdk`, which vendors both beside the\n" +
+ "libraries the helper links, or point OPENSCREEN_FFMPEG and OPENSCREEN_FFPROBE at binaries.",
+ );
+ process.exit(1);
+}
+if (!PLAYER) {
+ console.error(
+ `Nothing here can play a WAV. Install one of ${PLAYERS.map((player) => player.name).join(", ")}\n` +
+ "(pw-play ships with pipewire, paplay with pulseaudio-utils), or point\n" +
+ "OPENSCREEN_PW_TEST_PLAYER at a player that takes a file path.",
+ );
+ process.exit(1);
+}
+
+const tonePath = path.join(os.tmpdir(), "openscreen-audio-timeline-tone.wav");
+const madeTone = runTool(FFMPEG, [
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-f",
+ "lavfi",
+ "-i",
+ `sine=frequency=440:duration=${TONE_MS / 1000}`,
+ "-ac",
+ "2",
+ "-ar",
+ "48000",
+ "-acodec",
+ "pcm_s16le",
+ "-y",
+ tonePath,
+]);
+if (madeTone.status !== 0 || !fs.existsSync(tonePath)) {
+ console.error("Could not synthesise the test tone.");
+ process.exit(1);
+}
+
+const outputPath = path.join(os.tmpdir(), "openscreen-audio-timeline.mp4");
+fs.rmSync(outputPath, { force: true });
+
+const request = {
+ outputPath,
+ // `hidden`, not the app's `metadata`. The pointer is irrelevant to this measurement,
+ // while metadata mode is a second, unrelated way for the run to fail — the helper
+ // refuses to start on a compositor that does not advertise it — and it puts a
+ // cursor-sample line on stdout every 33 ms, sprites included as data URLs.
+ cursorMode: "hidden",
+ video: { fps: 30 },
+ audio: {
+ system: { enabled: true },
+ // No microphone on purpose: a live one streams continuously and would keep the
+ // timeline moving on its own, hiding exactly the failure this measures. On
+ // Windows that was not a choice — it is the state a broken microphone left
+ // behind, and the reason #406 surfaced as a system-audio desync.
+ microphone: { enabled: false, deviceName: null, gain: 1 },
+ },
+};
+
+console.log(
+ `Recording ${(PLAY_AT_MS + TONE_MS + TAIL_MS) / 1000}s: ${PLAY_AT_MS / 1000}s of silence, ` +
+ `a ${TONE_MS / 1000}s tone through ${PLAYER.name}, then ${TAIL_MS / 1000}s of silence.`,
+);
+console.log("Answer the compositor's source picker when it appears — the take starts there.");
+
+const proc = spawn(HELPER, [JSON.stringify(request)]);
+let helperOutput = "";
+let spawnError = null;
+let playbackArmed = false;
+const helperEvents = [];
+proc.on("error", (error) => {
+ spawnError = error.message;
+});
+
+/**
+ * Arms the tone once the helper says it is capturing, never from spawn.
+ *
+ * `capture-started` is emitted from the same frame that sets the epoch, and the epoch is
+ * what everything here is measured against: it is the instant the audio rings are cleared
+ * and audio sample 0 begins. Counting from spawn would fold in the portal negotiation,
+ * the picker, and however long the user took to answer it — an interval with no bound at
+ * all, which would fail every run rather than a broken one.
+ */
+function armPlaybackOnce() {
+ if (playbackArmed || !helperEvents.some((event) => event.event === "capture-started")) {
+ return;
+ }
+ playbackArmed = true;
+ setTimeout(() => {
+ // Blocking on purpose: it guarantees the tone really played before the tail is
+ // timed and the stop below is sent, which is the premise of the measurement.
+ runTool(PLAYER, PLAYER.args(tonePath));
+ setTimeout(() => {
+ try {
+ proc.stdin.write("stop\n");
+ } catch {
+ // Already gone; the close handler reports how it ended.
+ }
+ }, TAIL_MS);
+ }, PLAY_AT_MS);
+}
+
+/**
+ * Reassembles the helper's NDJSON across chunk boundaries.
+ *
+ * A `data` chunk is whatever the pipe had ready, not a whole line, so splitting each chunk
+ * on its own newlines drops any event a read happened to bisect — both halves parse as
+ * neither. Losing `capture-started` that way leaves the tone unarmed and the run hangs
+ * until the picker timeout kills the helper, which reads as "nobody answered the picker"
+ * rather than as a framing bug. Only stdout carries events; stderr is diagnostics and is
+ * kept as raw text.
+ */
+let stdoutTail = "";
+function consumeStdout(chunk) {
+ const text = chunk.toString();
+ helperOutput += text;
+ stdoutTail += text;
+ const lines = stdoutTail.split("\n");
+ stdoutTail = lines.pop() ?? "";
+ for (const line of lines) {
+ const trimmed = line.trim();
+ if (!trimmed.startsWith("{")) continue;
+ try {
+ const event = JSON.parse(trimmed);
+ helperEvents.push(event);
+ if (event.event === "stream-started") {
+ console.log(`Streaming ${event.width}x${event.height}; waiting for the first frame...`);
+ }
+ } catch {
+ // Not one of ours; the raw text is kept in helperOutput either way.
+ }
+ }
+ armPlaybackOnce();
+}
+proc.stdout.on("data", consumeStdout);
+proc.stderr.on("data", (chunk) => {
+ helperOutput += chunk.toString();
+});
+
+// If the picker is never answered, nothing would ever stop the helper — and it holds a
+// portal session, so the compositor keeps saying the screen is being shared.
+const startTimeout = setTimeout(() => {
+ if (!playbackArmed) {
+ console.error("Nothing was recorded: the source picker was never answered.");
+ proc.kill();
+ }
+}, PICKER_TIMEOUT_MS);
+
+/** Per-stream durations, which is what "does the audio cover the take" is asked of. */
+function streamDurations() {
+ const probed = runTool(
+ FFPROBE,
+ [
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-show_entries",
+ "stream=codec_type,duration",
+ "-of",
+ "json",
+ outputPath,
+ ],
+ { encoding: "utf8", maxBuffer: 1 << 24 },
+ );
+ try {
+ const streams = JSON.parse(probed.stdout ?? "{}").streams ?? [];
+ const durationOf = (kind) => {
+ const stream = streams.find((candidate) => candidate.codec_type === kind);
+ const seconds = Number(stream?.duration);
+ return Number.isFinite(seconds) ? seconds : null;
+ };
+ return { audio: durationOf("audio"), video: durationOf("video") };
+ } catch {
+ return { audio: null, video: null };
+ }
+}
+
+/** Where the tone actually sits, from the decoded samples rather than the metadata. */
+function firstAudibleSecond() {
+ const rate = 16000;
+ const decoded = runTool(
+ FFMPEG,
+ [
+ "-hide_banner",
+ "-nostats",
+ "-loglevel",
+ "error",
+ "-i",
+ outputPath,
+ "-map",
+ "0:a",
+ "-f",
+ "s16le",
+ "-ac",
+ "1",
+ "-ar",
+ String(rate),
+ "-",
+ ],
+ { maxBuffer: 1 << 28 },
+ );
+ const pcm = decoded.stdout ?? Buffer.alloc(0);
+ const samples = pcm.length / 2;
+ const windowSamples = (rate * WINDOW_MS) / 1000;
+ for (let index = 0; index * windowSamples < samples; index += 1) {
+ let peak = 0;
+ const from = index * windowSamples;
+ const to = Math.min(from + windowSamples, samples);
+ for (let at = from; at < to; at += 1) {
+ peak = Math.max(peak, Math.abs(pcm.readInt16LE(at * 2)));
+ }
+ // Well above dither, well below a real tone.
+ if (peak > 1200) return (index * WINDOW_MS) / 1000;
+ }
+ return null;
+}
+
+proc.on("close", (code, signal) => {
+ clearTimeout(startTimeout);
+ // The summary is the last thing the helper writes, so a final line without its newline
+ // would otherwise sit in the tail buffer and never be read.
+ if (stdoutTail.trim().startsWith("{")) {
+ try {
+ helperEvents.push(JSON.parse(stdoutTail.trim()));
+ } catch {
+ // Truncated on exit; nothing to recover.
+ }
+ }
+ const problems = [];
+ if (!playbackArmed) problems.push("recording never started, so no tone was played");
+ if (spawnError) problems.push(`could not start the helper: ${spawnError}`);
+ if (signal) problems.push(`helper killed by ${signal}`);
+ if (code !== 0 && code !== null) problems.push(`helper exited ${code}`);
+
+ const { audio, video } = streamDurations();
+ const toneAt = firstAudibleSecond();
+ const playedAt = PLAY_AT_MS / 1000;
+
+ // Only if there was a take. A run that never got past the picker has no file to
+ // measure, and "the recording has no audio track" would bury the line that says why.
+ if (playbackArmed) {
+ if (audio === null) {
+ problems.push("the recording has no audio track at all");
+ }
+ if (toneAt === null) {
+ problems.push(
+ "no audible tone in the recording — check the tone played to the same sink the helper " +
+ "monitored, and that it is not muted",
+ );
+ } else if (toneAt < TONE_TOLERANCE_S) {
+ // The failure this exists for, named as itself: a timeline advanced by data
+ // alone emits nothing until something plays, so the file BEGINS at the first
+ // sound and the silence in front of it is not in the file at all.
+ problems.push(
+ `the recording begins at the tone (${toneAt.toFixed(2)}s), so the ${playedAt.toFixed(2)}s ` +
+ "of silence before it is missing entirely",
+ );
+ } else if (Math.abs(toneAt - playedAt) > TONE_TOLERANCE_S) {
+ problems.push(
+ `the tone sits at ${toneAt.toFixed(2)}s, and was played at ${playedAt.toFixed(2)}s`,
+ );
+ }
+ // The whole take has to be IN the audio track: the silence before the tone and the
+ // silence after it, not just the part where something was playing.
+ if (audio !== null && video !== null && Math.abs(audio - video) > TRACK_TOLERANCE_S) {
+ problems.push(
+ `the audio track is ${audio.toFixed(2)}s and the video track is ${video.toFixed(2)}s — ` +
+ "the mixed track does not span the take",
+ );
+ }
+ }
+
+ // The ring stands in silence for anything it had to drop, so an overflow no longer
+ // pulls the rest of the take earlier — but it is still a hole in the audio, and this
+ // is the only place it is ever reported.
+ for (const warning of helperEvents.filter((event) => event.code === "audio-dropped")) {
+ problems.push(`the helper dropped audio: ${warning.message}`);
+ }
+
+ const stopped = helperEvents.findLast((event) => event.event === "capture-stopped");
+ const source = helperEvents.find(
+ (event) => event.event === "audio-source" && event.role === "system",
+ );
+
+ fs.rmSync(outputPath, { force: true });
+ console.log(
+ `\n${problems.length ? "FAIL" : "PASS"} audio=${audio?.toFixed(2) ?? "(none)"}s ` +
+ `video=${video?.toFixed(2) ?? "(none)"}s ` +
+ `tone at ${toneAt === null ? "(none)" : `${toneAt.toFixed(2)}s`}, played at ${playedAt.toFixed(2)}s`,
+ );
+ if (stopped) {
+ console.log(
+ ` ${stopped.frames} frames written, ${(stopped.durationMs / 1000).toFixed(2)}s of video, ` +
+ `${stopped.dropped} frame(s) dropped`,
+ );
+ }
+ if (source) {
+ // The first thing anyone needs when the tone is missing: the tap is the session
+ // default sink's monitor, and the tone has to have played to that same sink.
+ console.log(` system audio came from ${source.node ?? "the session default sink"}`);
+ }
+ for (const problem of problems) console.log(` -> ${problem}`);
+ if (problems.length) {
+ const complaints = helperEvents
+ .filter((event) => event.event === "error" || event.event === "warning")
+ .slice(-5);
+ for (const complaint of complaints) {
+ console.log(` helper: ${complaint.code}: ${complaint.message}`);
+ }
+ if (!complaints.length && helperOutput.trim()) {
+ console.log(` helper: ${helperOutput.trim().split("\n").slice(-3).join(" | ")}`);
+ }
+ }
+ process.exit(problems.length ? 1 : 0);
+});
diff --git a/technical-documentation/architecture/recording.md b/technical-documentation/architecture/recording.md
index 258924e01..5fdcb7381 100644
--- a/technical-documentation/architecture/recording.md
+++ b/technical-documentation/architecture/recording.md
@@ -73,6 +73,8 @@ The Windows helper mixes system loopback and microphone into one track, and time
The macOS helper mixes the same two sources into one AAC track (`AudioTrackMixer`) and runs the same discipline, arrived at from the opposite direction. There the emit cursor is anchored to the writer session start and advanced by a monotonic clock read off `CMClockGetHostTimeClock` — the domain ScreenCaptureKit already timestamps its buffers in — with a 10 ms timer on the sample queue moving it while nothing is arriving to move it. The bug it replaces was the anchor, not the counter: `anchor` was set lazily on the first decoded buffer to `max(firstPresentationTime, sessionStart)`, so audio that first arrived four seconds in made frame zero of the track *be* four seconds in. The trailing half was worse still — `drain()` ran only from `ingest` and `finish`, and the helper never called `writer.endSession(atSourceTime:)` at all, so the file ended at the last sample anything happened to deliver. Both halves and any mid-take gap are now one mechanism: chunks go out for as long as the take runs, from whichever source covers them and from silence where none does, and a source is written off for a chunk only once it has gone 250 ms without delivering anything — a decision about when to stop waiting, which shifts nothing, and not a correction, which would. Measured from that source's own last delivery rather than from how far behind the clock its coverage sits, because those differ for a source that is alive but arriving late: a capture path delivering a fixed delay behind the audio it describes would be "behind" forever, so writing it off for that would emit silence and then drop its real samples, every chunk, for the whole take. A pause freezes the clock rather than resetting it, so what follows keeps the position it would have had. Whether ScreenCaptureKit's system-audio output is silence-gapped the way WASAPI loopback is has never been recorded anywhere, and it decides how much of a take the clock is carrying alone rather than how the mixer should work; the helper now reports it per take as `audio-timeline`, whose `undeliveredSeconds` is the whole track if the tap is gapped and near zero if it streams silence. That figure counts what each source handed over rather than what came out of the mixer — holes under two seconds are zero-filled into the source's own buffer, so a hole read off the mixed output would come back covered, which is the exact case it exists to catch — and `droppedSeconds` beside it is the cost side, counting audio that arrived too late to place and reading zero unless the grace is too short for that tap. `swift test` runs the mixer against a collecting sink and a hand-moved clock on every pull request (`swift-macos-helper` in ci.yml, the first Swift job this repository has had); `npm run test:sck-audio-timeline:mac` measures a real tone through a real device, comparing the audio track's length against the video track's in the same file.
+The Linux helper mixes the same two sources into one AAC track as well (`AudioMix` in `electron/native/pipewire-capture/src/capture.rs`), and its emit cursor is the data-driven one Windows had: `AudioEncoder::next_pts` is a running count of the samples handed to the encoder, advanced only when a block is encoded, and `AudioMix::pump` returns early when no input has any. Nothing in that code makes a chunk go out for every chunk of real time — what does is the tap. System audio here is the default sink's MONITOR, and PipeWire keeps delivering its buffers whether or not anything is playing, silence included, where WASAPI loopback simply stops. So the count advances at real time for as long as the take runs and the cursor cannot stall. That is a property of the capture source and not of the timeline code, which is the thing to know before moving Linux audio off the sink monitor: a source that gates silence would reproduce the Windows failure above exactly (#406). The anchor half is a decision rather than an accident — the first video frame sets the epoch and clears the audio rings at that instant ("video frame 0 is now, so audio sample 0 is now too"), which is what keeps the pre-roll captured while the portal picker was up, an interval with no upper bound, from shifting the whole track earlier; `cargo test` covers it. The tail is covered by `Capture::finish`, which drains the rings and flushes the AAC encoder before the video flush, so the file ends with the take rather than with the last sound in it. What a mid-take overflow costs is bounded the same way: the ring drops its oldest samples and owes back silence of exactly that length, so the encoder falling two seconds behind leaves a gap where it happened instead of pulling every later sound earlier for the rest of the recording, and it is reported as `audio-dropped`. `npm run test:pw-audio-timeline:linux` measures it end to end — a tone played at a known instant, then the audio track's length against the video track's in the same file. Before it, the whole record that any of this held was one sentence in a commit message: a live 29-second capture whose 18-second tone came back as 18 seconds of steady signal, with the two streams ending 62 ms apart (video 29.100 s, audio 29.162 s). That 62 ms is also why the script allows 250 ms between the tracks where the macOS one allows 100: those two come out of a single writer session, and these two do not — the video track ends at the last `advance()` and the audio track at everything the rings still held, plus AAC's final padded block.
+
Cursor samples are persisted as cursor telemetry rather than baked into editable-overlay recordings. The loader resolves the sidecar at `<videoPath>.cursor.json` or through the recording links; see [cursor.md](cursor.md) for the telemetry format and rendering path.
## Known gaps