Skip to content

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

feat(recording): route Linux capture through the native helper

Etienne Lescotef71c970583d
diff --git a/electron-builder.json5 b/electron-builder.json5
index 72ee1ea42..b12185877 100644
--- a/electron-builder.json5
+++ b/electron-builder.json5
@@ -108,7 +108,13 @@
{
"from": "electron/native/bin",
"to": "electron/native/bin",
- "filter": ["linux-*/*"]
+ // `**`, not `*`: the capture helper's ffmpeg libraries live one level
+ // deeper, in `linux-x64/ffmpeg/`. They are in their own directory
+ // because `linux-x64/` also holds the compositor addon's copies of the
+ // same sonames with every symbol renamed to `osff_*`, and the helper
+ // must not find those — see scripts/build-linux-pipewire-helper.mjs.
+ // A single-level filter ships a helper that cannot start.
+ "filter": ["linux-*/**"]
}
]
},
diff --git a/electron/electron-env.d.ts b/electron/electron-env.d.ts
index 0cad8d4c1..dd761b0b0 100644
--- a/electron/electron-env.d.ts
+++ b/electron/electron-env.d.ts
@@ -185,6 +185,45 @@ interface Window {
message?: string;
error?: string;
}>;
+ isNativeLinuxCaptureAvailable: () => Promise<{
+ success: boolean;
+ available: boolean;
+ helperPath?: string;
+ reason?: "unsupported-platform" | "missing-helper" | string;
+ error?: string;
+ }>;
+ startNativeLinuxRecording: (
+ request: import("../src/lib/nativeLinuxRecording").NativeLinuxRecordingRequest,
+ ) => Promise<import("../src/lib/nativeLinuxRecording").NativeLinuxRecordingStartResult>;
+ pauseNativeLinuxRecording: () => Promise<{
+ success: boolean;
+ error?: string;
+ }>;
+ resumeNativeLinuxRecording: () => Promise<{
+ success: boolean;
+ error?: string;
+ }>;
+ stopNativeLinuxRecording: (discard?: boolean) => Promise<{
+ success: boolean;
+ path?: string;
+ session?: import("../src/lib/recordingSession").RecordingSession;
+ message?: string;
+ discarded?: boolean;
+ error?: string;
+ }>;
+ attachNativeLinuxWebcamRecording: (payload: {
+ screenVideoPath: string;
+ recordingId: number;
+ webcam: import("../src/lib/recordingSession").RecordedVideoAssetInput;
+ cursorCaptureMode?: import("../src/lib/recordingSession").CursorCaptureMode;
+ webcamOffsetMs?: number;
+ }) => Promise<{
+ success: boolean;
+ path?: string;
+ session?: import("../src/lib/recordingSession").RecordingSession;
+ message?: string;
+ error?: string;
+ }>;
discardCursorTelemetry: (recordingId: number) => Promise<void>;
getCursorTelemetry: (videoPath?: string) => Promise<{
success: boolean;
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index 308784c1d..4a285394d 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -16,6 +16,10 @@ import {
shell,
systemPreferences,
} from "electron";
+import {
+ type NativeLinuxRecordingRequest,
+ portalCursorMode,
+} from "../../src/lib/nativeLinuxRecording";
import type { NativeMacRecordingRequest } from "../../src/lib/nativeMacRecording";
import type { NativeWindowsRecordingRequest } from "../../src/lib/nativeWindowsRecording";
import {
@@ -52,8 +56,10 @@ import { mainLogBuffer } from "../diagnostics/main-log-buffer";
import { mainT } from "../i18n";
import { RECORDINGS_DIR } from "../main";
import { findMediaLinksByFingerprint, registerMediaLinks } from "../media/mediaLinksRegistry";
+import { LinuxNativeCaptureSession } from "../native-bridge/capture/linuxNativeCaptureSession";
import { createCursorRecordingSession } from "../native-bridge/cursor/recording/factory";
import { requestMacCursorAccessibilityAccess } from "../native-bridge/cursor/recording/macNativeCursorRecordingSession";
+import { findPipeWireCursorHelperPath } from "../native-bridge/cursor/recording/pipeWireCursorRecordingSession";
import type { CursorRecordingSession } from "../native-bridge/cursor/recording/session";
import { patchWebmDurationOnDisk } from "../recording/webm-duration";
import { reindexRecordingOnDisk } from "../recording/webm-seek-index";
@@ -498,6 +504,51 @@ let nativeMacPauseRanges: Array<{ startMs: number; endMs: number }> = [];
let nativeMacIsPaused = false;
// Global frame of the region captured by the SCK helper (see getSelectedSourceBounds).
let activeMacCaptureBounds: Rectangle | null = null;
+let linuxNativeCaptureSession: LinuxNativeCaptureSession | null = null;
+let linuxNativeCaptureRecordingId: number | null = null;
+let linuxNativeCaptureCursorMode: CursorCaptureMode = "editable-overlay";
+/**
+ * The portal's restore token, kept between recordings.
+ *
+ * Without it the compositor raises its source picker on EVERY recording, which
+ * on Wayland is the single most intrusive thing about capturing at all. The
+ * portal issues the token only after a successful session and honours it until
+ * the user revokes it in system settings, so it is safe to persist and useless
+ * to anyone else.
+ */
+const LINUX_RESTORE_TOKEN_FILE = "linux-capture-restore-token.json";
+
+async function readLinuxRestoreToken(): Promise<string | undefined> {
+ try {
+ const raw = await fs.readFile(
+ path.join(app.getPath("userData"), LINUX_RESTORE_TOKEN_FILE),
+ "utf-8",
+ );
+ const parsed = JSON.parse(raw) as { restoreToken?: unknown };
+ return typeof parsed.restoreToken === "string" && parsed.restoreToken
+ ? parsed.restoreToken
+ : undefined;
+ } catch {
+ // Absent or unreadable: the picker appears, which is the old behaviour
+ // and not worth failing a recording over.
+ return undefined;
+ }
+}
+
+async function writeLinuxRestoreToken(restoreToken?: string) {
+ if (!restoreToken) {
+ return;
+ }
+ try {
+ await fs.writeFile(
+ path.join(app.getPath("userData"), LINUX_RESTORE_TOKEN_FILE),
+ JSON.stringify({ restoreToken }, null, 2),
+ "utf-8",
+ );
+ } catch (error) {
+ console.warn("Could not persist the Linux portal restore token:", error);
+ }
+}
function normalizeCursorSample(sample: unknown): CursorRecordingSample | null {
if (!sample || typeof sample !== "object") {
@@ -898,6 +949,16 @@ async function resolveDirectShowWebcamClsid(deviceName?: string) {
}
async function startCursorRecording(recordingId?: number) {
+ // On Linux the native capture helper already produces cursor samples, from
+ // the SAME portal session that produces the pixels. Spawning the cursor-only
+ // helper alongside it would open a SECOND portal session — and since
+ // SelectSources may be called once per session, that means a second picker
+ // in front of the user, for a stream nothing consumes. The double prompt is
+ // precisely what the native path exists to remove.
+ if (linuxNativeCaptureSession) {
+ return;
+ }
+
if (cursorRecordingSession) {
pendingCursorRecordingData = await cursorRecordingSession.stop();
cursorRecordingSession = null;
@@ -1811,6 +1872,187 @@ export function registerIpcHandlers(
: { success: true, available: false, reason: "missing-helper" };
});
+ ipcMain.handle("is-native-linux-capture-available", async () => {
+ if (process.platform !== "linux") {
+ return { success: true, available: false, reason: "unsupported-platform" };
+ }
+
+ const helperPath = findPipeWireCursorHelperPath();
+ return helperPath
+ ? { success: true, available: true, helperPath }
+ : { success: true, available: false, reason: "missing-helper" };
+ });
+
+ ipcMain.handle(
+ "start-native-linux-recording",
+ async (_, request: NativeLinuxRecordingRequest) => {
+ try {
+ if (process.platform !== "linux") {
+ return { success: false, error: "Native Linux capture requires Linux." };
+ }
+ if (linuxNativeCaptureSession) {
+ return { success: false, error: "Native Linux capture is already running." };
+ }
+ if (!findPipeWireCursorHelperPath()) {
+ return { success: false, error: "Native Linux capture helper is not available." };
+ }
+
+ const recordingId =
+ typeof request?.recordingId === "number" && Number.isFinite(request.recordingId)
+ ? request.recordingId
+ : Date.now();
+ const outputPath = path.join(RECORDINGS_DIR, `${RECORDING_FILE_PREFIX}${recordingId}.mp4`);
+ const cursorCaptureMode =
+ normalizeCursorCaptureMode(request?.cursor?.mode) ?? "editable-overlay";
+
+ await fs.mkdir(RECORDINGS_DIR, { recursive: true });
+ const restoreToken = await readLinuxRestoreToken();
+
+ const session = new LinuxNativeCaptureSession({
+ outputPath,
+ cursorMode: portalCursorMode(cursorCaptureMode),
+ fps: request.video.fps,
+ ...(request.video.bitrate ? { bitrate: request.video.bitrate } : {}),
+ audio: {
+ system: { enabled: request.audio.system.enabled },
+ microphone: {
+ enabled: request.audio.microphone.enabled,
+ ...(request.audio.microphone.deviceName
+ ? { deviceName: request.audio.microphone.deviceName }
+ : {}),
+ gain: request.audio.microphone.gain,
+ },
+ },
+ maxCursorSamples: MAX_CURSOR_SAMPLES,
+ ...(restoreToken ? { restoreToken } : {}),
+ });
+
+ console.info("[native-linux] starting capture", {
+ outputPath,
+ cursor: { mode: cursorCaptureMode },
+ audio: request.audio,
+ video: request.video,
+ });
+
+ await session.start();
+ // Blocks until the user answers the portal picker, which has no
+ // upper bound — the countdown UI is already showing by now.
+ await session.waitUntilCapturing();
+
+ linuxNativeCaptureSession = session;
+ linuxNativeCaptureRecordingId = recordingId;
+ linuxNativeCaptureCursorMode = cursorCaptureMode;
+
+ const source = selectedSource || { name: "Screen" };
+ if (onRecordingStateChange) {
+ onRecordingStateChange(true, source.name);
+ }
+
+ return { success: true, recordingId, path: outputPath };
+ } catch (error) {
+ console.error("Failed to start native Linux recording:", error);
+ linuxNativeCaptureSession = null;
+ linuxNativeCaptureRecordingId = null;
+ linuxNativeCaptureCursorMode = "editable-overlay";
+ return { success: false, error: String(error) };
+ }
+ },
+ );
+
+ ipcMain.handle("pause-native-linux-recording", async () => {
+ if (!linuxNativeCaptureSession) {
+ return { success: false, error: "Native Linux capture is not running." };
+ }
+ linuxNativeCaptureSession.pause();
+ return { success: true };
+ });
+
+ ipcMain.handle("resume-native-linux-recording", async () => {
+ if (!linuxNativeCaptureSession) {
+ return { success: false, error: "Native Linux capture is not running." };
+ }
+ linuxNativeCaptureSession.resume();
+ return { success: true };
+ });
+
+ ipcMain.handle("stop-native-linux-recording", async (_, discard?: boolean) => {
+ const session = linuxNativeCaptureSession;
+ const recordingId = linuxNativeCaptureRecordingId ?? Date.now();
+ const cursorCaptureMode = linuxNativeCaptureCursorMode;
+
+ if (!session) {
+ return { success: false, error: "Native Linux capture is not running." };
+ }
+
+ try {
+ if (discard) {
+ session.discard();
+ const discarded = path.join(RECORDINGS_DIR, `${RECORDING_FILE_PREFIX}${recordingId}.mp4`);
+ await Promise.all([
+ fs.rm(discarded, { force: true }),
+ fs.rm(`${discarded}.cursor.json`, { force: true }),
+ ]);
+ return { success: true, discarded: true };
+ }
+
+ const result = await session.stop();
+ await writeLinuxRestoreToken(result.restoreToken);
+
+ // The helper collects cursor samples itself, from the same portal
+ // session that produced the pixels, so there is no separate sampler
+ // to stop and no clock offset to correct — the two are one recording.
+ if (cursorCaptureMode === "editable-overlay" && result.cursor.samples.length > 0) {
+ await fs.writeFile(
+ `${result.path}.cursor.json`,
+ JSON.stringify(result.cursor, null, 2),
+ "utf-8",
+ );
+ }
+
+ const session_: RecordingSession = {
+ screenVideoPath: result.path,
+ createdAt: recordingId,
+ cursorCaptureMode,
+ };
+ setCurrentRecordingSessionState(session_);
+ currentProjectPath = null;
+
+ const sessionManifestPath = path.join(
+ RECORDINGS_DIR,
+ `${path.parse(result.path).name}${RECORDING_SESSION_SUFFIX}`,
+ );
+ await fs.writeFile(sessionManifestPath, JSON.stringify(session_, null, 2), "utf-8");
+ await registerRecordingMediaLinks(result.path, { cursorCaptureMode });
+
+ console.info("[native-linux] capture stored", {
+ path: result.path,
+ frames: result.frames,
+ droppedFrames: result.droppedFrames,
+ durationMs: result.durationMs,
+ videoEncoder: result.videoEncoder,
+ cursorSamples: result.cursor.samples.length,
+ });
+
+ return {
+ success: true,
+ path: result.path,
+ session: session_,
+ message: "Native Linux recording session stored successfully",
+ };
+ } catch (error) {
+ console.error("Failed to stop native Linux recording:", error);
+ return { success: false, error: String(error) };
+ } finally {
+ linuxNativeCaptureSession = null;
+ linuxNativeCaptureRecordingId = null;
+ linuxNativeCaptureCursorMode = "editable-overlay";
+ const source = selectedSource || { name: "Screen" };
+ if (onRecordingStateChange) {
+ onRecordingStateChange(false, source.name);
+ }
+ }
+ });
+
ipcMain.handle(
"start-native-windows-recording",
async (_, request: NativeWindowsRecordingRequest) => {
@@ -2426,26 +2668,40 @@ export function registerIpcHandlers(
}
});
- ipcMain.handle(
- "attach-native-mac-webcam-recording",
- async (_, payload: AttachNativeMacWebcamRecordingInput) => {
- try {
- if (process.platform !== "darwin") {
- return { success: false, error: "Native macOS webcam attachment requires macOS." };
- }
-
+ /**
+ * Writes a browser-recorded webcam clip next to a natively-recorded screen
+ * video and rewrites the session manifest to include both.
+ *
+ * Shared by macOS and Linux, whose native helpers both leave the camera to
+ * the renderer's `MediaRecorder`: opening the device a second time from the
+ * helper would fight the preview for an exclusive claim, and buys nothing
+ * that the screen capture needs. (Windows is the exception — its helper takes
+ * the webcam through DirectShow so both streams share one start clock.)
+ *
+ * Nothing in here is platform-specific; the two `ipcMain.handle` calls below
+ * differ only in which platform they accept.
+ */
+ const attachNativeWebcamRecording = async (
+ platformLabel: string,
+ payload: AttachNativeMacWebcamRecordingInput,
+ ) => {
+ try {
+ {
const screenVideoPath = normalizeVideoSourcePath(payload.screenVideoPath);
if (!screenVideoPath || !isPathWithinDir(screenVideoPath, RECORDINGS_DIR)) {
return {
success: false,
- error: "Native macOS webcam attachment requires a recording output path.",
+ error: `Native ${platformLabel} webcam attachment requires a recording output path.`,
};
}
await fs.access(screenVideoPath, fsConstants.R_OK);
if (!payload.webcam?.fileName || !payload.webcam.videoData) {
- return { success: false, error: "Native macOS webcam attachment is missing video data." };
+ return {
+ success: false,
+ error: `Native ${platformLabel} webcam attachment is missing video data.`,
+ };
}
const webcamVideoPath = resolveRecordingOutputPath(payload.webcam.fileName);
@@ -2484,15 +2740,35 @@ export function registerIpcHandlers(
success: true,
path: screenVideoPath,
session,
- message: "Native macOS webcam recording attached successfully",
- };
- } catch (error) {
- console.error("Failed to attach native macOS webcam recording:", error);
- return {
- success: false,
- error: error instanceof Error ? error.message : String(error),
+ message: `Native ${platformLabel} webcam recording attached successfully`,
};
}
+ } catch (error) {
+ console.error(`Failed to attach native ${platformLabel} webcam recording:`, error);
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : String(error),
+ };
+ }
+ };
+
+ ipcMain.handle(
+ "attach-native-mac-webcam-recording",
+ async (_, payload: AttachNativeMacWebcamRecordingInput) => {
+ if (process.platform !== "darwin") {
+ return { success: false, error: "Native macOS webcam attachment requires macOS." };
+ }
+ return attachNativeWebcamRecording("macOS", payload);
+ },
+ );
+
+ ipcMain.handle(
+ "attach-native-linux-webcam-recording",
+ async (_, payload: AttachNativeMacWebcamRecordingInput) => {
+ if (process.platform !== "linux") {
+ return { success: false, error: "Native Linux webcam attachment requires Linux." };
+ }
+ return attachNativeWebcamRecording("Linux", payload);
},
);
diff --git a/electron/native-bridge/capture/linuxNativeCaptureSession.ts b/electron/native-bridge/capture/linuxNativeCaptureSession.ts
new file mode 100644
index 000000000..6a7a1a0dc
--- /dev/null
+++ b/electron/native-bridge/capture/linuxNativeCaptureSession.ts
@@ -0,0 +1,384 @@
+import { type ChildProcessByStdio, spawn } from "node:child_process";
+import type { Readable, Writable } from "node:stream";
+import type { CursorRecordingData } from "../../../src/native/contracts";
+import {
+ NdjsonLineReader,
+ PipeWireCursorAccumulator,
+ type PipeWireHelperEvent,
+} from "../cursor/recording/pipeWireCursorAccumulator";
+import { findPipeWireCursorHelperPath } from "../cursor/recording/pipeWireCursorRecordingSession";
+
+/**
+ * Drives the Linux capture helper for a full recording: video, audio and cursor
+ * telemetry from ONE portal session.
+ *
+ * WHY ONE SESSION MATTERS ENOUGH TO BUILD THIS. `SelectSources` may be called
+ * once per portal session, so a second process means a second picker. Before
+ * this, Linux users picked a source twice — once for Chromium's
+ * `getDisplayMedia` and once for the cursor helper — and the two captures could
+ * legitimately be of different things, because each picker was answered
+ * separately. That is also why the cursor overlay never lined up: the telemetry
+ * described one stream and the pixels came from another.
+ *
+ * TIMEOUTS. `ready` arrives in milliseconds and means the helper loaded
+ * libpipewire and reached the portal. `capture-started` cannot arrive until a
+ * human has clicked through the compositor's dialog, which has no upper bound —
+ * so it is deliberately NOT on a timer. The caller shows its own UI for that
+ * wait; a timeout here would cancel recordings whose user was merely reading the
+ * dialog.
+ */
+
+const READY_TIMEOUT_MS = 5_000;
+const STOP_TIMEOUT_MS = 15_000;
+
+export interface LinuxCaptureConfig {
+ outputPath: string;
+ cursorMode: "metadata" | "embedded";
+ fps: number;
+ bitrate?: number;
+ audio: {
+ system: { enabled: boolean };
+ microphone: { enabled: boolean; deviceName?: string; gain: number };
+ };
+ maxCursorSamples: number;
+ /** From a previous recording. Lets the portal skip its picker. */
+ restoreToken?: string;
+}
+
+export interface LinuxCaptureResult {
+ path: string;
+ durationMs: number;
+ frames: number;
+ droppedFrames: number;
+ cursor: CursorRecordingData;
+ /** Present when the portal issued one; persist it for the next recording. */
+ restoreToken?: string;
+ videoEncoder?: string;
+}
+
+export class LinuxNativeCaptureSession {
+ private readonly cursor: PipeWireCursorAccumulator;
+ private readonly lines = new NdjsonLineReader();
+ private process: ChildProcessByStdio<Writable, Readable, Readable> | null = null;
+
+ private readyResolve: (() => void) | null = null;
+ private readyReject: ((error: Error) => void) | null = null;
+ private readyTimer: NodeJS.Timeout | null = null;
+
+ private startedResolve: (() => void) | null = null;
+ private startedReject: ((error: Error) => void) | null = null;
+
+ private stopped: LinuxCaptureResult | null = null;
+ private stoppedResolve: (() => void) | null = null;
+ private stoppedReject: ((error: Error) => void) | null = null;
+
+ private restoreToken: string | undefined;
+ private videoEncoder: string | undefined;
+ private lastError: string | null = null;
+ private paused = false;
+
+ constructor(private readonly config: LinuxCaptureConfig) {
+ this.cursor = new PipeWireCursorAccumulator(config.maxCursorSamples);
+ }
+
+ /**
+ * Spawns the helper and resolves once it reports `ready` — which is BEFORE
+ * the portal picker is raised. Call [`waitUntilCapturing`] to wait for the
+ * user to answer it.
+ */
+ async start(): Promise<void> {
+ const helperPath = findPipeWireCursorHelperPath();
+ if (!helperPath) {
+ throw new Error(
+ "The Linux capture helper is not available. Build it with `npm run build:native:linux`.",
+ );
+ }
+
+ this.cursor.reset(Date.now());
+ this.lines.reset();
+
+ const request = {
+ outputPath: this.config.outputPath,
+ cursorMode: this.config.cursorMode,
+ video: {
+ fps: this.config.fps,
+ ...(this.config.bitrate ? { bitrate: this.config.bitrate } : {}),
+ },
+ audio: this.config.audio,
+ ...(this.config.restoreToken ? { restoreToken: this.config.restoreToken } : {}),
+ };
+
+ const child = spawn(helperPath, [JSON.stringify(request)], {
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ this.process = child;
+
+ child.stdout.setEncoding("utf8");
+ child.stdout.on("data", (chunk: string) => this.handleStdout(chunk));
+ child.stderr.setEncoding("utf8");
+ child.stderr.on("data", (chunk: string) => {
+ const message = chunk.trim();
+ if (message) {
+ console.error("[capture-linux]", message);
+ }
+ });
+ child.once("exit", (code, signal) => {
+ this.process = null;
+ const reason =
+ this.lastError ??
+ `the Linux capture helper exited (code=${code ?? "null"}, signal=${signal ?? "null"})`;
+ this.rejectReady(new Error(reason));
+ this.startedReject?.(new Error(reason));
+ this.startedReject = null;
+ this.startedResolve = null;
+ // A clean exit after `capture-stopped` is the normal path; anything
+ // else means the file may not have its trailer.
+ if (this.stopped) {
+ this.stoppedResolve?.();
+ } else {
+ this.stoppedReject?.(new Error(reason));
+ }
+ this.stoppedResolve = null;
+ this.stoppedReject = null;
+ });
+ child.once("error", (error) => {
+ this.process = null;
+ this.rejectReady(error);
+ });
+
+ try {
+ await new Promise<void>((resolve, reject) => {
+ this.readyResolve = resolve;
+ this.readyReject = reject;
+ this.readyTimer = setTimeout(() => {
+ this.rejectReady(new Error("Timed out waiting for the Linux capture helper"));
+ }, READY_TIMEOUT_MS);
+ });
+ } catch (error) {
+ this.kill();
+ throw error;
+ }
+ }
+
+ /**
+ * Resolves when the first frame has been encoded — i.e. once the user has
+ * answered the portal picker. No timeout, on purpose: see the class doc.
+ */
+ waitUntilCapturing(): Promise<void> {
+ if (!this.process) {
+ return Promise.reject(new Error("The Linux capture helper is not running."));
+ }
+ return new Promise<void>((resolve, reject) => {
+ this.startedResolve = resolve;
+ this.startedReject = reject;
+ });
+ }
+
+ pause() {
+ if (this.paused) {
+ return;
+ }
+ this.paused = true;
+ this.write("pause");
+ }
+
+ resume() {
+ if (!this.paused) {
+ return;
+ }
+ this.paused = false;
+ this.write("resume");
+ }
+
+ get isPaused() {
+ return this.paused;
+ }
+
+ /**
+ * Asks the helper to write the trailer and exit, then returns what it made.
+ *
+ * Waits for the PROCESS to exit rather than for `capture-stopped` alone: the
+ * MP4's moov atom is written during teardown, and returning a path to a file
+ * whose index is still being written would hand the app an unplayable
+ * recording.
+ */
+ async stop(): Promise<LinuxCaptureResult> {
+ const child = this.process;
+ if (!child) {
+ if (this.stopped) {
+ return this.stopped;
+ }
+ throw new Error("The Linux capture helper is not running.");
+ }
+
+ const exited = new Promise<void>((resolve, reject) => {
+ this.stoppedResolve = resolve;
+ this.stoppedReject = reject;
+ });
+ this.write("stop");
+ try {
+ child.stdin.end();
+ } catch {
+ // Already closed if the helper died on its own; the exit handler runs.
+ }
+
+ const timer = setTimeout(() => {
+ console.error("[capture-linux] helper did not exit in time; terminating");
+ this.kill();
+ }, STOP_TIMEOUT_MS);
+ try {
+ await exited;
+ } finally {
+ clearTimeout(timer);
+ }
+
+ if (!this.stopped) {
+ throw new Error(this.lastError ?? "The Linux capture helper produced no output file.");
+ }
+ return this.stopped;
+ }
+
+ /** Kills the helper and discards whatever it wrote. */
+ discard() {
+ this.kill();
+ }
+
+ private write(command: string) {
+ try {
+ this.process?.stdin.write(`${command}\n`);
+ } catch {
+ // The helper is gone; stop()/exit already reports that.
+ }
+ }
+
+ private kill() {
+ const child = this.process;
+ if (!child || child.killed) {
+ return;
+ }
+ child.kill("SIGTERM");
+ setTimeout(() => {
+ if (!child.killed) {
+ child.kill("SIGKILL");
+ }
+ }, 500).unref();
+ }
+
+ private handleStdout(chunk: string) {
+ this.lines.push(chunk, (line) => {
+ let payload: PipeWireHelperEvent;
+ try {
+ payload = JSON.parse(line) as PipeWireHelperEvent;
+ } catch (error) {
+ console.error("Failed to parse Linux capture helper output:", error, line);
+ return;
+ }
+ this.handleEvent(payload);
+ });
+ }
+
+ private handleEvent(payload: PipeWireHelperEvent) {
+ switch (payload.event) {
+ case "ready":
+ this.resolveReady();
+ return;
+
+ case "stream-started":
+ if (payload.restoreToken) {
+ this.restoreToken = payload.restoreToken;
+ }
+ console.info(
+ "[capture-linux] portal stream started",
+ JSON.stringify({ width: payload.width, height: payload.height }),
+ );
+ return;
+
+ case "encoder-selection":
+ this.videoEncoder = payload.video;
+ console.info(
+ "[capture-linux] encoder",
+ JSON.stringify({ video: payload.video, rejected: payload.rejected ?? [] }),
+ );
+ return;
+
+ case "capture-started":
+ // Cursor samples started flowing when the helper did, which was
+ // before the portal picker. The recording's zero is HERE, so the
+ // telemetry is re-based onto it and anything from during the
+ // picker is dropped rather than left pinned to the start.
+ this.cursor.rebase(payload.timestampMs);
+ console.info(
+ "[capture-linux] capture started",
+ JSON.stringify({ width: payload.width, height: payload.height, fps: payload.fps }),
+ );
+ this.startedResolve?.();
+ this.startedResolve = null;
+ this.startedReject = null;
+ return;
+
+ case "cursor-sample":
+ this.cursor.addSample(payload);
+ return;
+
+ case "capture-stopped":
+ this.stopped = {
+ path: payload.path,
+ durationMs: payload.durationMs,
+ frames: payload.frames,
+ droppedFrames: payload.dropped,
+ cursor: this.cursor.toRecordingData(),
+ ...(this.restoreToken ? { restoreToken: this.restoreToken } : {}),
+ ...(this.videoEncoder ? { videoEncoder: this.videoEncoder } : {}),
+ };
+ console.info(
+ "[capture-linux] capture stopped",
+ JSON.stringify({
+ frames: payload.frames,
+ dropped: payload.dropped,
+ durationMs: payload.durationMs,
+ convertMs: payload.convertMs,
+ uploadMs: payload.uploadMs,
+ encodeMs: payload.encodeMs,
+ }),
+ );
+ return;
+
+ case "warning":
+ console.warn(`[capture-linux] ${payload.code}: ${payload.message}`);
+ return;
+
+ case "error":
+ console.error(`[capture-linux] ${payload.code}: ${payload.message}`);
+ // Kept so the process-exit handler can report the CAUSE rather
+ // than just the exit code, which on its own says nothing useful.
+ this.lastError = payload.message;
+ this.rejectReady(new Error(payload.message));
+ return;
+
+ case "debug":
+ console.info("[capture-linux][debug]", JSON.stringify(payload));
+ return;
+ }
+ }
+
+ private resolveReady() {
+ const resolve = this.readyResolve;
+ this.clearReadyState();
+ resolve?.();
+ }
+
+ private rejectReady(error: Error) {
+ const reject = this.readyReject;
+ this.clearReadyState();
+ reject?.(error);
+ }
+
+ private clearReadyState() {
+ if (this.readyTimer) {
+ clearTimeout(this.readyTimer);
+ this.readyTimer = null;
+ }
+ this.readyResolve = null;
+ this.readyReject = null;
+ }
+}
diff --git a/electron/native-bridge/cursor/recording/pipeWireCursorAccumulator.test.ts b/electron/native-bridge/cursor/recording/pipeWireCursorAccumulator.test.ts
new file mode 100644
index 000000000..69ae80e3a
--- /dev/null
+++ b/electron/native-bridge/cursor/recording/pipeWireCursorAccumulator.test.ts
@@ -0,0 +1,166 @@
+import { describe, expect, it } from "vitest";
+import { NdjsonLineReader, PipeWireCursorAccumulator } from "./pipeWireCursorAccumulator";
+
+function sample(timestampMs: number, x: number, y: number, extra: Record<string, unknown> = {}) {
+ return {
+ event: "cursor-sample" as const,
+ timestampMs,
+ x,
+ y,
+ width: 1920,
+ height: 1080,
+ visible: true,
+ ...extra,
+ };
+}
+
+describe("NdjsonLineReader", () => {
+ it("reassembles a line split across chunks", () => {
+ // The helper writes one JSON object per line and flushes per line, but a
+ // pipe read can still land mid-line. Splitting on newline per chunk and
+ // discarding the remainder would drop a sample every time that happened.
+ const reader = new NdjsonLineReader();
+ const lines: string[] = [];
+ reader.push('{"event":"a"}\n{"ev', (line) => lines.push(line));
+ expect(lines).toEqual(['{"event":"a"}']);
+ reader.push('ent":"b"}\n', (line) => lines.push(line));
+ expect(lines).toEqual(['{"event":"a"}', '{"event":"b"}']);
+ });
+
+ it("emits nothing for a chunk with no newline", () => {
+ const reader = new NdjsonLineReader();
+ const lines: string[] = [];
+ reader.push('{"partial"', (line) => lines.push(line));
+ expect(lines).toEqual([]);
+ });
+
+ it("drops a half-line on reset so a new recording cannot inherit it", () => {
+ const reader = new NdjsonLineReader();
+ const lines: string[] = [];
+ reader.push('{"stale', (line) => lines.push(line));
+ reader.reset();
+ reader.push('{"event":"fresh"}\n', (line) => lines.push(line));
+ expect(lines).toEqual(['{"event":"fresh"}']);
+ });
+});
+
+describe("PipeWireCursorAccumulator", () => {
+ it("normalises positions against the stream size the helper reports", () => {
+ const accumulator = new PipeWireCursorAccumulator(100);
+ accumulator.reset(1_000);
+ accumulator.addSample(sample(1_500, 960, 540));
+
+ const [point] = accumulator.toRecordingData().samples;
+ expect(point.cx).toBeCloseTo(0.5, 5);
+ expect(point.cy).toBeCloseTo(0.5, 5);
+ expect(point.timeMs).toBe(500);
+ });
+
+ it("reports every sample as a move, because Wayland exposes no buttons", () => {
+ const accumulator = new PipeWireCursorAccumulator(100);
+ accumulator.reset(0);
+ accumulator.addSample(sample(10, 5, 5));
+ expect(accumulator.toRecordingData().samples[0].interactionType).toBe("move");
+ });
+
+ it("re-bases onto the video's start and drops what came before it", () => {
+ // This is the single-session case. Cursor samples start flowing as soon
+ // as the helper does, but the video's frame 0 is only stamped once the
+ // user has answered the portal picker — an unbounded wait. Samples taken
+ // during it belong to no part of the recording.
+ const accumulator = new PipeWireCursorAccumulator(100);
+ accumulator.reset(1_000);
+ accumulator.addSample(sample(1_200, 100, 100)); // during the picker
+ accumulator.addSample(sample(2_000, 200, 200)); // exactly at capture start
+ accumulator.addSample(sample(2_500, 300, 300)); // after
+
+ accumulator.rebase(2_000);
+
+ const { samples } = accumulator.toRecordingData();
+ expect(samples).toHaveLength(2);
+ expect(samples[0].timeMs).toBe(0);
+ expect(samples[1].timeMs).toBe(500);
+ });
+
+ it("leaves samples alone when the origin has not moved", () => {
+ const accumulator = new PipeWireCursorAccumulator(100);
+ accumulator.reset(1_000);
+ accumulator.addSample(sample(1_400, 10, 10));
+ accumulator.rebase(1_000);
+ expect(accumulator.toRecordingData().samples[0].timeMs).toBe(400);
+ });
+
+ it("reports provider 'none' until a sprite arrives", () => {
+ // The editor uses this to decide whether it has real cursor art to draw
+ // or must fall back. A recording with positions but no bitmap is the
+ // normal state for the first few frames.
+ const accumulator = new PipeWireCursorAccumulator(100);
+ accumulator.reset(0);
+ accumulator.addSample(sample(10, 5, 5));
+ expect(accumulator.toRecordingData().provider).toBe("none");
+
+ accumulator.addSample(
+ sample(20, 6, 6, {
+ assetId: "abc",
+ asset: {
+ id: "abc",
+ imageDataUrl: "data:image/png;base64,AAAA",
+ width: 24,
+ height: 24,
+ hotspotX: 4,
+ hotspotY: 2,
+ },
+ }),
+ );
+ const data = accumulator.toRecordingData();
+ expect(data.provider).toBe("native");
+ expect(data.assets).toHaveLength(1);
+ expect(data.assets[0]).toMatchObject({ platform: "linux", hotspotX: 4, scaleFactor: 1 });
+ });
+
+ it("keeps the first sprite when the same id is sent again", () => {
+ const accumulator = new PipeWireCursorAccumulator(100);
+ accumulator.reset(0);
+ const asset = {
+ id: "same",
+ imageDataUrl: "data:image/png;base64,FIRST",
+ width: 24,
+ height: 24,
+ hotspotX: 1,
+ hotspotY: 1,
+ };
+ accumulator.addSample(sample(10, 1, 1, { assetId: "same", asset }));
+ accumulator.addSample(
+ sample(20, 2, 2, {
+ assetId: "same",
+ asset: { ...asset, imageDataUrl: "data:image/png;base64,SECOND" },
+ }),
+ );
+ const { assets } = accumulator.toRecordingData();
+ expect(assets).toHaveLength(1);
+ expect(assets[0].imageDataUrl).toBe("data:image/png;base64,FIRST");
+ });
+
+ it("caps the sample list by dropping the oldest", () => {
+ const accumulator = new PipeWireCursorAccumulator(3);
+ accumulator.reset(0);
+ for (let index = 0; index < 5; index++) {
+ accumulator.addSample(sample(index * 10, index, index));
+ }
+ const { samples } = accumulator.toRecordingData();
+ expect(samples).toHaveLength(3);
+ expect(samples[0].timeMs).toBe(20);
+ });
+
+ it("clamps positions outside the stream instead of emitting them", () => {
+ // A cursor can legitimately be reported outside a window capture's
+ // bounds. Un-clamped, cx/cy leave 0..1 and the editor draws the overlay
+ // off-canvas rather than at the edge.
+ const accumulator = new PipeWireCursorAccumulator(10);
+ accumulator.reset(0);
+ accumulator.addSample(sample(10, -50, 5000));
+ const [point] = accumulator.toRecordingData().samples;
+ expect(point.cx).toBe(0);
+ expect(point.cy).toBe(1);
+ });
+});
diff --git a/electron/native-bridge/cursor/recording/pipeWireCursorAccumulator.ts b/electron/native-bridge/cursor/recording/pipeWireCursorAccumulator.ts
new file mode 100644
index 000000000..2cbe197be
--- /dev/null
+++ b/electron/native-bridge/cursor/recording/pipeWireCursorAccumulator.ts
@@ -0,0 +1,192 @@
+import type {
+ CursorRecordingData,
+ CursorRecordingSample,
+ NativeCursorAsset,
+} from "../../../../src/native/contracts";
+import { clamp } from "../../../../src/utils/math";
+
+/**
+ * Turns the Linux helper's NDJSON stdout into `CursorRecordingData`.
+ *
+ * Extracted from `PipeWireCursorRecordingSession` because there are now two
+ * callers and only one helper. The cursor-only session spawns the helper for
+ * telemetry alone; the native capture session spawns it for video AND telemetry,
+ * from the same portal session. Sharing this class is what keeps them from
+ * drifting — and, more importantly, is what lets the second one exist at all:
+ * `SelectSources` may be called once per portal session, so two processes would
+ * mean two pickers, which is exactly the double-prompt this replaces.
+ */
+
+export interface PipeWireCursorAssetPayload {
+ id: string;
+ imageDataUrl: string;
+ width: number;
+ height: number;
+ hotspotX: number;
+ hotspotY: number;
+}
+
+export type PipeWireHelperEvent =
+ | { event: "ready"; timestampMs: number; pipewireVersion?: string | null }
+ | {
+ event: "stream-started";
+ timestampMs: number;
+ nodeId: number;
+ width: number;
+ height: number;
+ restoreToken?: string | null;
+ }
+ | {
+ event: "cursor-sample";
+ timestampMs: number;
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ visible: boolean;
+ assetId?: string;
+ asset?: PipeWireCursorAssetPayload;
+ }
+ | { event: "encoder-selection"; video: string; rejected?: string[] }
+ | {
+ event: "capture-started";
+ timestampMs: number;
+ path: string;
+ width: number;
+ height: number;
+ fps: number;
+ }
+ | {
+ event: "capture-stopped";
+ timestampMs: number;
+ path: string;
+ durationMs: number;
+ frames: number;
+ dropped: number;
+ convertMs?: number;
+ uploadMs?: number;
+ encodeMs?: number;
+ }
+ | { event: "warning"; code: string; message: string }
+ | { event: "error"; code: string; message: string }
+ | { event: "debug"; code: string; [key: string]: unknown };
+
+/** Splits a stdout stream into whole NDJSON lines across chunk boundaries. */
+export class NdjsonLineReader {
+ private buffer = "";
+
+ push(chunk: string, onLine: (line: string) => void) {
+ this.buffer += chunk;
+ const lines = this.buffer.split(/\r?\n/);
+ // The last element is whatever came after the final newline — a partial
+ // line, or "" when the chunk ended cleanly. Either way it is not ready.
+ this.buffer = lines.pop() ?? "";
+ for (const line of lines) {
+ const trimmed = line.trim();
+ if (trimmed) {
+ onLine(trimmed);
+ }
+ }
+ }
+
+ reset() {
+ this.buffer = "";
+ }
+}
+
+export class PipeWireCursorAccumulator {
+ private samples: CursorRecordingSample[] = [];
+ private assets = new Map<string, NativeCursorAsset>();
+ private startTimeMs = 0;
+
+ constructor(private readonly maxSamples: number) {}
+
+ reset(startTimeMs: number) {
+ this.samples = [];
+ this.assets.clear();
+ this.startTimeMs = startTimeMs;
+ }
+
+ /**
+ * Re-bases every sample already collected onto a new time origin.
+ *
+ * Needed because the helper's cursor stream starts before its video does: the
+ * portal picker, the format negotiation and the encoder open all happen first,
+ * and only then does `capture-started` fire. Samples taken in between belong
+ * to the recording's negative time, so the origin moves to the video's and
+ * anything now before zero is dropped rather than clamped — a clamped sample
+ * would pin the pointer to wherever it happened to be during the picker.
+ */
+ rebase(startTimeMs: number) {
+ const shiftMs = startTimeMs - this.startTimeMs;
+ this.startTimeMs = startTimeMs;
+ if (shiftMs === 0) {
+ return;
+ }
+ this.samples = this.samples
+ .map((sample) => ({ ...sample, timeMs: sample.timeMs - shiftMs }))
+ .filter((sample) => sample.timeMs >= 0);
+ }
+
+ addSample(payload: Extract<PipeWireHelperEvent, { event: "cursor-sample" }>) {
+ this.rememberAsset(payload.asset);
+
+ // Normalised against the stream's own dimensions, which the helper repeats
+ // on every sample. Electron's display bounds are deliberately NOT used:
+ // they are in DIPs, whereas the portal reports stream pixels, and the
+ // portal's source is whatever the user picked in its own dialog, which
+ // need not be the display the app thinks it is recording.
+ const width = Math.max(1, payload.width);
+ const height = Math.max(1, payload.height);
+
+ this.samples.push({
+ // Clamped, matching the behaviour this was extracted from: a sample
+ // stamped a few milliseconds before the recording's own start is a
+ // clock artefact, not a sample from before the recording.
+ timeMs: Math.max(0, payload.timestampMs - this.startTimeMs),
+ cx: clamp(payload.x / width, 0, 1),
+ cy: clamp(payload.y / height, 0, 1),
+ visible: payload.visible,
+ // Wayland exposes no click events to an unprivileged process.
+ interactionType: "move",
+ ...(payload.assetId ? { assetId: payload.assetId } : {}),
+ });
+
+ if (this.samples.length > this.maxSamples) {
+ this.samples.shift();
+ }
+ }
+
+ private rememberAsset(asset: PipeWireCursorAssetPayload | undefined) {
+ if (!asset?.id || this.assets.has(asset.id)) {
+ return;
+ }
+
+ this.assets.set(asset.id, {
+ id: asset.id,
+ platform: "linux",
+ imageDataUrl: asset.imageDataUrl,
+ width: asset.width,
+ height: asset.height,
+ hotspotX: asset.hotspotX,
+ hotspotY: asset.hotspotY,
+ // The portal reports cursor bitmaps in stream pixels, the same space
+ // the positions are in, so no extra scaling applies.
+ scaleFactor: 1,
+ });
+ }
+
+ /** Drops samples taken before zero, which `rebase` can produce. */
+ get sampleCount() {
+ return this.samples.length;
+ }
+
+ toRecordingData(): CursorRecordingData {
+ return {
+ version: 2,
+ provider: this.assets.size > 0 ? "native" : "none",
+ samples: this.samples,
+ assets: [...this.assets.values()],
+ };
+ }
+}
diff --git a/electron/native-bridge/cursor/recording/pipeWireCursorRecordingSession.ts b/electron/native-bridge/cursor/recording/pipeWireCursorRecordingSession.ts
index ccc150b84..16815071c 100644
--- a/electron/native-bridge/cursor/recording/pipeWireCursorRecordingSession.ts
+++ b/electron/native-bridge/cursor/recording/pipeWireCursorRecordingSession.ts
@@ -2,12 +2,12 @@ import { type ChildProcessByStdio, spawn } from "node:child_process";
import { accessSync, constants as fsConstants } from "node:fs";
import path from "node:path";
import type { Readable, Writable } from "node:stream";
-import type {
- CursorRecordingData,
- CursorRecordingSample,
- NativeCursorAsset,
-} from "../../../../src/native/contracts";
-import { clamp } from "../../../../src/utils/math";
+import type { CursorRecordingData } from "../../../../src/native/contracts";
+import {
+ NdjsonLineReader,
+ PipeWireCursorAccumulator,
+ type PipeWireHelperEvent,
+} from "./pipeWireCursorAccumulator";
import type { CursorRecordingSession } from "./session";
/**
@@ -39,39 +39,6 @@ const HELPER_NAME = "openscreen-pipewire-helper";
const READY_TIMEOUT_MS = 5_000;
const STOP_GRACE_MS = 500;
-interface PipeWireCursorAssetPayload {
- id: string;
- imageDataUrl: string;
- width: number;
- height: number;
- hotspotX: number;
- hotspotY: number;
-}
-
-type PipeWireHelperEvent =
- | { event: "ready"; timestampMs: number; pipewireVersion?: string | null }
- | {
- event: "stream-started";
- timestampMs: number;
- nodeId: number;
- width: number;
- height: number;
- }
- | {
- event: "cursor-sample";
- timestampMs: number;
- x: number;
- y: number;
- width: number;
- height: number;
- visible: boolean;
- assetId?: string;
- asset?: PipeWireCursorAssetPayload;
- }
- | { event: "warning"; code: string; message: string }
- | { event: "error"; code: string; message: string }
- | { event: "debug"; code: string; [key: string]: unknown };
-
interface PipeWireCursorRecordingSessionOptions {
maxSamples: number;
sampleIntervalMs: number;
@@ -113,22 +80,20 @@ export function findPipeWireCursorHelperPath() {
}
export class PipeWireCursorRecordingSession implements CursorRecordingSession {
- private samples: CursorRecordingSample[] = [];
- private assets = new Map<string, NativeCursorAsset>();
+ private readonly cursor: PipeWireCursorAccumulator;
+ private readonly lines = new NdjsonLineReader();
private process: ChildProcessByStdio<Writable, Readable, Readable> | null = null;
- private lineBuffer = "";
- private startTimeMs = 0;
private readyResolve: (() => void) | null = null;
private readyReject: ((error: Error) => void) | null = null;
private readyTimer: NodeJS.Timeout | null = null;
- constructor(private readonly options: PipeWireCursorRecordingSessionOptions) {}
+ constructor(private readonly options: PipeWireCursorRecordingSessionOptions) {
+ this.cursor = new PipeWireCursorAccumulator(options.maxSamples);
+ }
async start(): Promise<void> {
- this.samples = [];
- this.assets.clear();
- this.lineBuffer = "";
- this.startTimeMs = this.options.startTimeMs ?? Date.now();
+ this.cursor.reset(this.options.startTimeMs ?? Date.now());
+ this.lines.reset();
const helperPath = findPipeWireCursorHelperPath();
if (!helperPath) {
@@ -190,31 +155,17 @@ export class PipeWireCursorRecordingSession implements CursorRecordingSession {
this.killHelperProcess(child, STOP_GRACE_MS);
}
- return {
- version: 2,
- provider: this.assets.size > 0 ? "native" : "none",
- samples: this.samples,
- assets: [...this.assets.values()],
- };
+ return this.cursor.toRecordingData();
}
private handleStdoutChunk(chunk: string) {
- this.lineBuffer += chunk;
- const lines = this.lineBuffer.split(/\r?\n/);
- this.lineBuffer = lines.pop() ?? "";
-
- for (const line of lines) {
- const trimmedLine = line.trim();
- if (!trimmedLine) {
- continue;
- }
-
+ this.lines.push(chunk, (line) => {
try {
- this.handleEvent(JSON.parse(trimmedLine) as PipeWireHelperEvent);
+ this.handleEvent(JSON.parse(line) as PipeWireHelperEvent);
} catch (error) {
- console.error("Failed to parse Linux cursor helper output:", error, trimmedLine);
+ console.error("Failed to parse Linux cursor helper output:", error, line);
}
- }
+ });
}
private handleEvent(payload: PipeWireHelperEvent) {
@@ -233,7 +184,7 @@ export class PipeWireCursorRecordingSession implements CursorRecordingSession {
);
return;
case "cursor-sample":
- this.captureSample(payload);
+ this.cursor.addSample(payload);
return;
case "warning":
console.warn(`[cursor-linux] ${payload.code}: ${payload.message}`);
@@ -248,51 +199,6 @@ export class PipeWireCursorRecordingSession implements CursorRecordingSession {
}
}
- private captureSample(payload: Extract<PipeWireHelperEvent, { event: "cursor-sample" }>) {
- this.rememberAsset(payload.asset);
-
- // Normalised against the stream's own dimensions, which the helper repeats
- // on every sample. Electron's display bounds are deliberately NOT used:
- // they are in DIPs, whereas the portal reports stream pixels, and the
- // portal's source is whatever the user picked in its own dialog, which
- // need not be the display the app thinks it is recording.
- const width = Math.max(1, payload.width);
- const height = Math.max(1, payload.height);
-
- this.samples.push({
- timeMs: Math.max(0, payload.timestampMs - this.startTimeMs),
- cx: clamp(payload.x / width, 0, 1),
- cy: clamp(payload.y / height, 0, 1),
- visible: payload.visible,
- // Wayland exposes no click events to an unprivileged process.
- interactionType: "move",
- ...(payload.assetId ? { assetId: payload.assetId } : {}),
- });
-
- if (this.samples.length > this.options.maxSamples) {
- this.samples.shift();
- }
- }
-
- private rememberAsset(asset: PipeWireCursorAssetPayload | undefined) {
- if (!asset?.id || this.assets.has(asset.id)) {
- return;
- }
-
- this.assets.set(asset.id, {
- id: asset.id,
- platform: "linux",
- imageDataUrl: asset.imageDataUrl,
- width: asset.width,
- height: asset.height,
- hotspotX: asset.hotspotX,
- hotspotY: asset.hotspotY,
- // The portal reports cursor bitmaps in stream pixels, the same space
- // the positions are in, so no extra scaling applies.
- scaleFactor: 1,
- });
- }
-
private waitUntilReady() {
return new Promise<void>((resolve, reject) => {
this.readyResolve = resolve;
diff --git a/electron/native/pipewire-capture/build.rs b/electron/native/pipewire-capture/build.rs
index a3a78d204..5aecdb941 100644
--- a/electron/native/pipewire-capture/build.rs
+++ b/electron/native/pipewire-capture/build.rs
@@ -115,13 +115,22 @@ fn link_ffmpeg(root: &Path) {
for name in ["avcodec", "avformat", "avutil", "swscale", "swresample"] {
println!("cargo:rustc-link-lib={name}");
}
- // `-rpath` twice: `$ORIGIN` for the packaged layout (the .so files sit next
- // to the binary in electron/native/bin/linux-x64), the absolute vendored
- // path so `cargo run` works straight out of the repo. `--disable-new-dtags`
- // is what makes these RUNPATH entries apply to the transitive ffmpeg libs
- // too; with the default DT_RUNPATH they would not.
+ // `$ORIGIN/ffmpeg`, NOT `$ORIGIN`. The helper is staged into
+ // electron/native/bin/linux-x64/, and that directory ALREADY contains
+ // libavcodec.so.62 and friends — the copies whose every symbol was renamed
+ // to `osff_*` by scripts/build-linux-compositor-addon.mjs so the compositor
+ // addon does not collide with Chromium's ffmpeg inside Electron. Searching
+ // `$ORIGIN` finds those first and the helper dies at startup with
+ // "undefined symbol: avcodec_send_frame, version LIBAVCODEC_62". The
+ // renaming trick is what makes the ADDON work and what would break the
+ // HELPER, so the two sets of libraries must not share a directory.
+ //
+ // The absolute vendored path comes second so `cargo run` works straight out
+ // of the repo. `--disable-new-dtags` is what makes these RUNPATH entries
+ // apply to the transitive ffmpeg libs too; with the default DT_RUNPATH they
+ // would not.
println!("cargo:rustc-link-arg=-Wl,--disable-new-dtags");
- println!("cargo:rustc-link-arg=-Wl,-rpath,$ORIGIN");
+ println!("cargo:rustc-link-arg=-Wl,-rpath,$ORIGIN/ffmpeg");
println!("cargo:rustc-link-arg=-Wl,-rpath,{}", lib.display());
let mut builder = bindgen::Builder::default();
diff --git a/electron/preload.ts b/electron/preload.ts
index 937607cbe..dfc9db84f 100644
--- a/electron/preload.ts
+++ b/electron/preload.ts
@@ -1,4 +1,5 @@
import { contextBridge, ipcRenderer, webUtils } from "electron";
+import type { NativeLinuxRecordingRequest } from "../src/lib/nativeLinuxRecording";
import type { NativeMacRecordingRequest } from "../src/lib/nativeMacRecording";
import type { NativeWindowsRecordingRequest } from "../src/lib/nativeWindowsRecording";
import type { RecordingSession, StoreRecordedSessionInput } from "../src/lib/recordingSession";
@@ -182,6 +183,30 @@ contextBridge.exposeInMainWorld("electronAPI", {
isNativeMacCaptureAvailable: () => {
return ipcRenderer.invoke("is-native-mac-capture-available");
},
+ isNativeLinuxCaptureAvailable: () => {
+ return ipcRenderer.invoke("is-native-linux-capture-available");
+ },
+ startNativeLinuxRecording: (request: NativeLinuxRecordingRequest) => {
+ return ipcRenderer.invoke("start-native-linux-recording", request);
+ },
+ pauseNativeLinuxRecording: () => {
+ return ipcRenderer.invoke("pause-native-linux-recording");
+ },
+ resumeNativeLinuxRecording: () => {
+ return ipcRenderer.invoke("resume-native-linux-recording");
+ },
+ stopNativeLinuxRecording: (discard?: boolean) => {
+ return ipcRenderer.invoke("stop-native-linux-recording", discard);
+ },
+ attachNativeLinuxWebcamRecording: (payload: {
+ screenVideoPath: string;
+ recordingId: number;
+ webcam: { fileName: string; videoData: ArrayBuffer };
+ cursorCaptureMode?: import("../src/lib/recordingSession").CursorCaptureMode;
+ webcamOffsetMs?: number;
+ }) => {
+ return ipcRenderer.invoke("attach-native-linux-webcam-recording", payload);
+ },
startNativeWindowsRecording: (request: NativeWindowsRecordingRequest) => {
return ipcRenderer.invoke("start-native-windows-recording", request);
},
diff --git a/scripts/build-linux-pipewire-helper.mjs b/scripts/build-linux-pipewire-helper.mjs
index 5b39d7c0b..1f5144d36 100644
--- a/scripts/build-linux-pipewire-helper.mjs
+++ b/scripts/build-linux-pipewire-helper.mjs
@@ -3,18 +3,20 @@
// pipeWireCursorRecordingSession.ts resolves at runtime.
//
// The Linux counterpart of build-macos-screencapturekit-helper.mjs and
-// build-windows-wgc-helper.mjs. Two things are deliberately absent compared to
-// the compositor addon's Linux build script:
+// build-windows-wgc-helper.mjs.
//
-// 1. No pkg-config, no FFMPEG_DIR, no libclang. The helper's C shim compiles
-// against headers vendored in the repo and resolves libpipewire with
-// dlopen at runtime, so `cargo` and a C compiler are the entire toolchain.
-// That is the point: libpipewire-0.3-dev is not installable on every
-// contributor's box, and requiring it would gate the Linux build on a
-// package Ubuntu does not ship by default.
+// PIPEWIRE needs no pkg-config and no dev package: the C shim compiles against
+// headers vendored in the repo and resolves libpipewire with dlopen at runtime.
+// That is the point — libpipewire-0.3-dev is not installed on a stock Ubuntu,
+// and requiring it would gate the whole Linux build on a package the base
+// system does not ship.
//
-// 2. No RUNPATH surgery. Nothing is dynamically linked beyond libc, so the
-// binary is relocatable as-is.
+// FFMPEG is different, and has been since the helper started encoding H.264.
+// It is linked normally, its libraries are staged next to the binary by
+// stageFfmpeg() below, and the RUNPATH points at them. Unlike the compositor
+// addon there is no symbol renaming: the helper is a separate PROCESS, so
+// Chromium's libffmpeg.so is never in its address space and cannot collide.
+// See its Cargo.toml.
//
// The crate is NOT part of the crates/ workspace (see its Cargo.toml for why),
// so it is built by pointing cargo at its own manifest.
@@ -91,6 +93,63 @@ for (const dir of [outDir, devDir]) {
fs.copyFileSync(builtBinary, dest);
fs.chmodSync(dest, 0o755);
console.log(`Copied ${dest}`);
+ stageFfmpeg(dir);
+}
+
+/**
+ * Copies the vendored ffmpeg shared libraries into `<dir>/ffmpeg/`.
+ *
+ * THE SUBDIRECTORY IS THE WHOLE POINT. `electron/native/bin/linux-x64/` already
+ * holds libavcodec.so.62 and friends — but those are the copies whose every
+ * symbol was renamed to `osff_*` by scripts/build-linux-compositor-addon.mjs,
+ * so that the compositor addon does not bind to Chromium's own ffmpeg once
+ * Electron dlopens it. Two different builds of the same soname, needed by two
+ * different consumers, and only one of them can win a directory.
+ *
+ * The addon needs the renamed set next to itself; the helper needs the ordinary
+ * set. So the helper's RUNPATH is `$ORIGIN/ffmpeg` (see build.rs) and its
+ * libraries live here. Putting them side by side produced exactly one symptom,
+ * which the probe below catches:
+ *
+ * undefined symbol: avcodec_send_frame, version LIBAVCODEC_62
+ */
+function stageFfmpeg(dir) {
+ const source = path.join(
+ root,
+ "crates",
+ "thirdparty",
+ "ffmpeg-linux64-lgpl-shared",
+ "lib",
+ );
+ if (!fs.existsSync(source)) {
+ console.warn(
+ `Vendored ffmpeg not found at ${source}; the helper will fall back to its ` +
+ "build-time RUNPATH and will not work once packaged.",
+ );
+ return;
+ }
+
+ const target = path.join(dir, "ffmpeg");
+ fs.mkdirSync(target, { recursive: true });
+ // Only the sonames the helper actually links, and only the real files —
+ // the tree also holds unversioned `.so` symlinks that the loader never
+ // consults at runtime.
+ const wanted = /^lib(avcodec|avformat|avutil|swscale|swresample)\.so\.\d+$/;
+ let copied = 0;
+ for (const entry of fs.readdirSync(source)) {
+ if (!wanted.test(entry)) {
+ continue;
+ }
+ const from = fs.realpathSync(path.join(source, entry));
+ const to = path.join(target, entry);
+ fs.rmSync(to, { force: true });
+ fs.copyFileSync(from, to);
+ copied++;
+ }
+ if (copied === 0) {
+ throw new Error(`No ffmpeg libraries matched in ${source}; the helper cannot run.`);
+ }
+ console.log(`Staged ${copied} ffmpeg libraries into ${target}`);
}
// A helper that cannot dlopen libpipewire is useless, and the failure is
diff --git a/src/components/launch/LaunchWindow.tsx b/src/components/launch/LaunchWindow.tsx
index 261f15109..ce0c0c57f 100644
--- a/src/components/launch/LaunchWindow.tsx
+++ b/src/components/launch/LaunchWindow.tsx
@@ -169,35 +169,28 @@ export function LaunchWindow() {
.getPlatform()
.then((platform) => {
if (!cancelled) {
- // Windows and macOS only, and NOT an oversight — this list is exactly the
- // set of platforms with a native capture helper that can honour the choice.
- // Windows passes `captureCursor` to wgc-capture, macOS passes
- // `hideSystemCursor` to the ScreenCaptureKit helper; both genuinely omit
- // the system cursor from the pixels.
+ // Every platform with a native capture helper that can honour the
+ // choice, which is now all three. Windows passes `captureCursor`
+ // to wgc-capture, macOS passes `hideSystemCursor` to the
+ // ScreenCaptureKit helper, and Linux passes `cursorMode` to the
+ // PipeWire helper, which asks the ScreenCast portal for METADATA
+ // or EMBEDDED. All three genuinely omit the system cursor from
+ // the pixels.
//
- // Linux has no native video helper, so capture goes through Chromium, and
- // Chromium offers no way to suppress the cursor:
- // - `cursor: "never"` is not a constraint Chromium implements. It is
- // absent from `getSupportedConstraints()` (verified on Electron 42 /
- // Chromium 148: the only screen-capture constraints are
- // `displaySurface` and `suppressLocalAudioPlayback`), so WebIDL drops
- // it silently. The `cursor` key on the win32 getDisplayMedia branch in
- // useScreenRecorder is a no-op for the same reason — Windows gets its
- // cursor control from the helper, not from that constraint.
- // - Below the web API it is just as fixed: `DesktopCaptureDevice::Create`
- // wraps every screen and window capturer in a `DesktopAndCursorComposer`
- // unconditionally, with no branch on any cursor option. On Linux
- // `prefer_cursor_embedded` is false (only Windows sets it), so WebRTC
- // asks the portal for METADATA mode — the compositor leaves the cursor
- // out of the pixels and WebRTC paints it back in itself.
- // Confirmed against a real recording: the system cursor is present in the
- // captured pixels at the position the telemetry sidecar reports.
- //
- // Showing the toggle here would therefore ship a control that changes
- // nothing about the pixels while switching the editor's overlay on, which
- // is what produces TWO cursors. Lift this only together with a native
- // PipeWire capture helper that owns the video.
- setSupportsCursorModeToggle(platform === "win32" || platform === "darwin");
+ // Linux was excluded here until the helper existed, and the
+ // reason is worth keeping: capture went through Chromium, and
+ // Chromium offers NO way to suppress the cursor.
+ // `DesktopCaptureDevice::Create` wraps every capturer in a
+ // `DesktopAndCursorComposer` unconditionally; on Linux WebRTC
+ // asks the portal for METADATA mode and then paints the cursor
+ // back in itself. So the toggle would have switched the editor's
+ // overlay on without changing the pixels — which is exactly how
+ // you get two cursors. Verified against a real recording at the
+ // time. The helper is what makes the control mean something,
+ // because it owns the video and never asks WebRTC for anything.
+ setSupportsCursorModeToggle(
+ platform === "win32" || platform === "darwin" || platform === "linux",
+ );
setIsLinuxHud(platform === "linux");
}
})
diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.ts
index 578ad5e78..d51cb261d 100644
--- a/src/hooks/useScreenRecorder.ts
+++ b/src/hooks/useScreenRecorder.ts
@@ -3,6 +3,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { useScopedT } from "@/contexts/I18nContext";
import { MIC_GAIN_BOOST, mixAudioTracks } from "@/lib/audioMix";
+import type { NativeLinuxRecordingRequest } from "@/lib/nativeLinuxRecording";
import {
type NativeMacRecordingRequest,
parseMacDisplayIdFromSourceId,
@@ -99,6 +100,20 @@ type NativeMacRecordingHandle = {
webcamOffsetMs: number | null;
};
+type NativeLinuxRecordingHandle = {
+ recordingId: number;
+ finalizing: boolean;
+ paused: boolean;
+ /**
+ * As on macOS: the webcam MediaRecorder starts immediately in the renderer,
+ * while the helper has to spawn, negotiate a portal session and WAIT FOR THE
+ * USER to answer a picker before its first frame exists. That last part makes
+ * the gap here unbounded rather than merely a process spawn, so trimming it
+ * matters more than it does on macOS. `null` when no webcam was recorded.
+ */
+ webcamOffsetMs: number | null;
+};
+
export function useScreenRecorder(): UseScreenRecorderReturn {
const t = useScopedT("editor");
const [recording, setRecording] = useState(false);
@@ -140,6 +155,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
const webcamRecorder = useRef<RecorderHandle | null>(null);
const nativeWindowsRecording = useRef<NativeWindowsRecordingHandle | null>(null);
const nativeMacRecording = useRef<NativeMacRecordingHandle | null>(null);
+ const nativeLinuxRecording = useRef<NativeLinuxRecordingHandle | null>(null);
const stream = useRef<MediaStream | null>(null);
const screenStream = useRef<MediaStream | null>(null);
const microphoneStream = useRef<MediaStream | null>(null);
@@ -161,6 +177,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
Boolean(
(nativeWindowsRecording.current && !nativeWindowsRecording.current.finalizing) ||
(nativeMacRecording.current && !nativeMacRecording.current.finalizing) ||
+ (nativeLinuxRecording.current && !nativeLinuxRecording.current.finalizing) ||
(screenRecorder.current && screenRecorder.current.recorder.state !== "inactive"),
);
@@ -634,6 +651,122 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
[cursorCaptureMode, getRecordingDurationMs],
);
+ /**
+ * The Linux twin of `finalizeNativeMacRecording`. Same shape, because the two
+ * platforms make the same split: helper owns screen and audio, renderer owns
+ * the webcam, and the two are reconciled here.
+ */
+ const finalizeNativeLinuxRecording = useCallback(
+ async (discard = false) => {
+ const activeNativeRecording = nativeLinuxRecording.current;
+ if (!activeNativeRecording || activeNativeRecording.finalizing) {
+ return false;
+ }
+
+ activeNativeRecording.finalizing = true;
+ if (!discard) {
+ setSaving(true);
+ }
+ const duration = Math.max(0, getRecordingDurationMs());
+ const activeWebcamRecorder = webcamRecorder.current;
+ if (activeWebcamRecorder && webcamRecorder.current === activeWebcamRecorder) {
+ webcamRecorder.current = null;
+ }
+ const webcamAssetPromise = (async (): Promise<RecordedVideoAssetInput | undefined> => {
+ if (!activeWebcamRecorder) {
+ return undefined;
+ }
+
+ try {
+ if (activeWebcamRecorder.recorder.state !== "inactive") {
+ activeWebcamRecorder.recorder.stop();
+ }
+ const webcamBlob = await activeWebcamRecorder.recordedBlobPromise;
+ if (!webcamBlob || webcamBlob.size === 0) {
+ return undefined;
+ }
+ // See the identical comment in finalizeNativeMacRecording: the
+ // leading footage recorded while the portal picker was up must
+ // stay seekable, so the declared duration includes it.
+ const webcamHeadStartMs = Math.max(0, -(activeNativeRecording.webcamOffsetMs ?? 0));
+ const fixedWebcamBlob = await fixWebmDuration(webcamBlob, duration + webcamHeadStartMs);
+ return {
+ videoData: await fixedWebcamBlob.arrayBuffer(),
+ fileName: `${RECORDING_FILE_PREFIX}${activeNativeRecording.recordingId}${WEBCAM_FILE_SUFFIX}${VIDEO_FILE_EXTENSION}`,
+ };
+ } catch (error) {
+ console.error("Failed to finalize native Linux webcam recording:", error);
+ return undefined;
+ }
+ })();
+
+ const clearNativeRecordingState = () => {
+ nativeLinuxRecording.current = null;
+ setRecording(false);
+ setPaused(false);
+ setElapsedSeconds(0);
+ accumulatedDurationMs.current = 0;
+ segmentStartedAt.current = null;
+ };
+
+ try {
+ const result = await window.electronAPI.stopNativeLinuxRecording(discard);
+ const webcamAsset = await webcamAssetPromise;
+ if (discard || result.discarded) {
+ clearNativeRecordingState();
+ return true;
+ }
+ if (!result.success) {
+ console.error("Failed to stop native Linux recording:", result.error);
+ toast.error(result.error ?? "Failed to stop native Linux recording");
+ activeNativeRecording.finalizing = false;
+ return true;
+ }
+
+ if (webcamAsset && result.path) {
+ const attachResult = await window.electronAPI.attachNativeLinuxWebcamRecording({
+ screenVideoPath: result.path,
+ recordingId: activeNativeRecording.recordingId,
+ webcam: webcamAsset,
+ cursorCaptureMode,
+ ...(typeof activeNativeRecording.webcamOffsetMs === "number"
+ ? { webcamOffsetMs: activeNativeRecording.webcamOffsetMs }
+ : {}),
+ });
+ if (attachResult.success) {
+ result.session = attachResult.session;
+ } else {
+ console.error("Failed to attach native Linux webcam recording:", attachResult.error);
+ toast.error(attachResult.error ?? "Failed to store webcam recording");
+ }
+ }
+
+ clearNativeRecordingState();
+ if (result.session) {
+ await window.electronAPI.setCurrentRecordingSession(result.session);
+ } else if (result.path) {
+ await window.electronAPI.setCurrentVideoPath(result.path);
+ }
+
+ await window.electronAPI.switchToEditor();
+ return true;
+ } catch (error) {
+ console.error("Error saving native Linux recording:", error);
+ toast.error(
+ error instanceof Error ? error.message : "Failed to save native Linux recording",
+ );
+ activeNativeRecording.finalizing = false;
+ return true;
+ } finally {
+ if (discardRecordingId.current === activeNativeRecording.recordingId) {
+ discardRecordingId.current = null;
+ }
+ setSaving(false);
+ }
+ },
+ [cursorCaptureMode, getRecordingDurationMs],
+ );
+
const stopRecording = useRef(() => {
if (nativeWindowsRecording.current) {
void finalizeNativeWindowsRecording(false);
@@ -643,6 +776,10 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
void finalizeNativeMacRecording(false);
return;
}
+ if (nativeLinuxRecording.current) {
+ void finalizeNativeLinuxRecording(false);
+ return;
+ }
const activeScreenRecorder = screenRecorder.current;
if (!activeScreenRecorder) {
@@ -715,6 +852,9 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
if (nativeMacRecording.current) {
void finalizeNativeMacRecording(true);
}
+ if (nativeLinuxRecording.current) {
+ void finalizeNativeLinuxRecording(true);
+ }
if (
screenRecorder.current?.recorder.state === "recording" ||
@@ -745,6 +885,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
safeHideCountdownOverlay,
finalizeNativeWindowsRecording,
finalizeNativeMacRecording,
+ finalizeNativeLinuxRecording,
]);
const safeShowCountdownOverlay = async (value: number, runId: number) => {
@@ -1058,6 +1199,116 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
}
};
+ /**
+ * The Linux native path.
+ *
+ * Two things make it shorter than its Windows and macOS siblings, and both
+ * come from Wayland rather than from anything being unfinished:
+ *
+ * * No `source`. The ScreenCast portal raises its OWN picker and the
+ * compositor decides what it hands over. `selectedSource` is a
+ * placeholder there, so passing it along would be passing a guess.
+ * * The IPC call does not resolve until the user has answered that picker,
+ * which has no upper bound. That is also what makes the returned instant
+ * a trustworthy t=0 for the webcam offset below.
+ */
+ const startNativeLinuxRecordingIfAvailable = async (countdownRunToken?: number) => {
+ try {
+ const platform = window.electronAPI.getPlatform();
+ if (platform !== "linux") {
+ return false;
+ }
+
+ const availability = await window.electronAPI.isNativeLinuxCaptureAvailable();
+ if (!availability.success || !availability.available) {
+ if (availability.reason === "unsupported-platform") {
+ return false;
+ }
+ if (availability.reason === "missing-helper") {
+ // The browser path still works, just without hardware encode,
+ // cursor telemetry or a single picker. Falling back beats
+ // refusing to record.
+ console.warn("Native Linux capture helper is not available; using browser capture.");
+ return false;
+ }
+ throw new Error(availability.error ?? "Native Linux capture is not available.");
+ }
+
+ if (!isCountdownRunActive(countdownRunToken)) {
+ return true;
+ }
+
+ const activeRecordingId = Date.now();
+ let nativeWebcamRecorder: RecorderHandle | null = null;
+ let nativeWebcamRecorderStartedAtMs: number | null = null;
+ if (webcamEnabled) {
+ await waitForWebcamReady();
+ if (!isCountdownRunActive(countdownRunToken)) {
+ return true;
+ }
+ if (webcamStream.current) {
+ nativeWebcamRecorderStartedAtMs = performance.now();
+ nativeWebcamRecorder = createRecorderHandle(webcamStream.current, {
+ mimeType: selectMimeType(),
+ videoBitsPerSecond: BITRATE_BASE,
+ });
+ } else {
+ webcamAcquireId.current++;
+ setWebcamEnabledState(false);
+ }
+ }
+
+ const request: NativeLinuxRecordingRequest = {
+ recordingId: activeRecordingId,
+ video: {
+ fps: TARGET_FRAME_RATE,
+ bitrate: computeBitrate(TARGET_WIDTH, TARGET_HEIGHT),
+ },
+ audio: {
+ system: { enabled: systemAudioEnabled },
+ microphone: {
+ enabled: microphoneEnabled,
+ gain: MIC_GAIN_BOOST,
+ },
+ },
+ cursor: { mode: cursorCaptureMode },
+ };
+ const result = await window.electronAPI.startNativeLinuxRecording(request);
+ if (!result.success || !result.recordingId) {
+ throw new Error(result.error ?? "Native Linux capture failed.");
+ }
+ if (!isCountdownRunActive(countdownRunToken)) {
+ await window.electronAPI.stopNativeLinuxRecording(true);
+ return true;
+ }
+
+ // Resolved only after the helper's first encoded frame, so this is the
+ // native recording's real t=0 in the same clock the webcam used above.
+ const nativeRecordingConfirmedStartedAtMs = performance.now();
+ recordingId.current = result.recordingId;
+ nativeLinuxRecording.current = {
+ recordingId: result.recordingId,
+ finalizing: false,
+ paused: false,
+ webcamOffsetMs:
+ nativeWebcamRecorder && nativeWebcamRecorderStartedAtMs !== null
+ ? -(nativeRecordingConfirmedStartedAtMs - nativeWebcamRecorderStartedAtMs)
+ : null,
+ };
+ webcamRecorder.current = nativeWebcamRecorder;
+ accumulatedDurationMs.current = 0;
+ segmentStartedAt.current = Date.now();
+ allowAutoFinalize.current = true;
+ setRecording(true);
+ setPaused(false);
+ setElapsedSeconds(0);
+ return true;
+ } catch (error) {
+ console.error("Native Linux capture failed:", error);
+ throw error;
+ }
+ };
+
const startRecordCountdown = async () => {
if (countdownActive || recording) {
return;
@@ -1171,6 +1422,11 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
if (await startNativeMacRecordingIfAvailable(selectedSource, countdownRunToken)) {
return;
}
+ // No `selectedSource`: on Wayland the portal picker is the source of
+ // truth and Electron's entry is a placeholder.
+ if (await startNativeLinuxRecordingIfAvailable(countdownRunToken)) {
+ return;
+ }
// Capture screen + microphone in parallel: the gap between the two
// `getUserMedia` calls is the dominant source of the mic-vs-video lag at the
@@ -1522,6 +1778,46 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
return;
}
+ const activeNativeLinuxRecording = nativeLinuxRecording.current;
+ if (activeNativeLinuxRecording && !activeNativeLinuxRecording.finalizing) {
+ void (async () => {
+ const activeWebcamRecorder = webcamRecorder.current?.recorder;
+ try {
+ if (activeNativeLinuxRecording.paused) {
+ const result = await window.electronAPI.resumeNativeLinuxRecording();
+ if (!result.success) {
+ throw new Error(result.error ?? "Failed to resume native Linux recording");
+ }
+ if (activeWebcamRecorder?.state === "paused") {
+ activeWebcamRecorder.resume();
+ }
+ activeNativeLinuxRecording.paused = false;
+ segmentStartedAt.current = Date.now();
+ setPaused(false);
+ return;
+ }
+
+ const pausedAtMs = getRecordingDurationMs();
+ const result = await window.electronAPI.pauseNativeLinuxRecording();
+ if (!result.success) {
+ throw new Error(result.error ?? "Failed to pause native Linux recording");
+ }
+ if (activeWebcamRecorder?.state === "recording") {
+ activeWebcamRecorder.pause();
+ }
+ activeNativeLinuxRecording.paused = true;
+ accumulatedDurationMs.current = pausedAtMs;
+ segmentStartedAt.current = null;
+ setElapsedSeconds(Math.floor(accumulatedDurationMs.current / 1000));
+ setPaused(true);
+ } catch (error) {
+ console.error("Failed to toggle native Linux pause state:", error);
+ toast.error(error instanceof Error ? error.message : "Failed to toggle pause state");
+ }
+ })();
+ return;
+ }
+
const activeScreenRecorder = screenRecorder.current?.recorder;
if (!activeScreenRecorder || activeScreenRecorder.state === "inactive") {
return;
@@ -1602,6 +1898,18 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
}
return;
}
+ if (nativeLinuxRecording.current) {
+ const activeRecordingId = recordingId.current;
+ restarting.current = true;
+ discardRecordingId.current = activeRecordingId;
+ try {
+ await finalizeNativeLinuxRecording(true);
+ await startRecording();
+ } finally {
+ restarting.current = false;
+ }
+ return;
+ }
const activeScreenRecorder = screenRecorder.current;
if (!activeScreenRecorder || activeScreenRecorder.recorder.state === "inactive") return;
@@ -1674,6 +1982,13 @@ export function useScreenRecorder(): UseScreenRecorderReturn {
void finalizeNativeMacRecording(true);
return;
}
+ if (nativeLinuxRecording.current) {
+ const activeRecordingId = recordingId.current;
+ discardRecordingId.current = activeRecordingId;
+ allowAutoFinalize.current = false;
+ void finalizeNativeLinuxRecording(true);
+ return;
+ }
const activeScreenRecorder = screenRecorder.current;
if (
diff --git a/src/lib/nativeLinuxRecording.ts b/src/lib/nativeLinuxRecording.ts
new file mode 100644
index 000000000..af46a397a
--- /dev/null
+++ b/src/lib/nativeLinuxRecording.ts
@@ -0,0 +1,70 @@
+/**
+ * The request the Linux capture helper takes as argv[1].
+ *
+ * Deliberately narrower than its Windows and macOS counterparts, because on
+ * Wayland the app knows less:
+ *
+ * * There is no `source`. The ScreenCast portal raises its own picker and the
+ * compositor decides what it hands over; `desktopCapturer` on Wayland
+ * returns a single placeholder entry and no usable id. Passing one would be
+ * passing a guess. The helper reports back what was actually picked.
+ * * There is no `webcam`. Like macOS, the camera stays with the renderer's
+ * MediaRecorder — V4L2 in the helper would buy nothing and cost a second
+ * exclusive claim on the device.
+ *
+ * `restoreToken` is the one field with no equivalent elsewhere: the portal hands
+ * one back after a successful session, and passing it next time is what stops
+ * the picker from appearing on every single recording.
+ */
+export type NativeLinuxRecordingRequest = {
+ recordingId?: number;
+ video: {
+ fps: number;
+ bitrate?: number;
+ };
+ audio: {
+ system: {
+ enabled: boolean;
+ };
+ microphone: {
+ enabled: boolean;
+ /**
+ * A PipeWire `node.name`, NOT the browser device id the UI carries.
+ * The two namespaces are unrelated and there is no mapping between
+ * them, so this is left empty until the picker learns to enumerate
+ * PipeWire nodes; empty means the session's default source.
+ */
+ deviceName?: string;
+ gain: number;
+ };
+ };
+ cursor: {
+ mode: import("./recordingSession").CursorCaptureMode;
+ };
+ /** From a previous run's `stream-started`. Lets the portal skip its picker. */
+ restoreToken?: string;
+};
+
+export type NativeLinuxRecordingStartResult = {
+ success: boolean;
+ recordingId?: number;
+ path?: string;
+ helperPath?: string;
+ error?: string;
+ /** "vaapi", "vulkan" or "software" — which rung of the encoder ladder won. */
+ videoEncoder?: string | null;
+};
+
+/**
+ * The portal's cursor modes, as the helper's `cursorMode` field spells them.
+ *
+ * METADATA is what makes the editable cursor possible: the compositor keeps the
+ * pointer out of the captured pixels and describes its position separately, so
+ * the editor can draw its own without the real one showing through underneath.
+ * EMBEDDED is the opposite and matches the HUD's "system cursor" setting.
+ */
+export function portalCursorMode(
+ mode: import("./recordingSession").CursorCaptureMode,
+): "metadata" | "embedded" {
+ return mode === "system" ? "embedded" : "metadata";
+}