Skip to content

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

fix(macos): keep a recovered take when the disk is still full, and say what failed

Etienne Lescot527b27eaaa37
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index 409c162dd..7b6d64d2d 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -83,6 +83,7 @@ import { toHelperRect } from "../native-bridge/helperCoordinates";
import { scoreDeviceNameMatch } from "../recording/deviceNameMatching";
import {
describeSalvagedTake,
+ nativeMacSalvageTarget,
salvageNativeMacCapture,
} from "../recording/nativeMacCaptureSalvage";
import {
@@ -3253,8 +3254,8 @@ export function registerIpcHandlers(
// A helper that exited left a file nothing writes to any more, and what its
// writer finished before the failure is usually a playable fragmented take.
// One still running may be mid-write, so it is left alone.
- const salvage =
- stopResult.exited && preferredPath ? await salvageNativeMacCapture(preferredPath) : null;
+ const salvageTarget = nativeMacSalvageTarget(stopResult, preferredPath);
+ const salvage = salvageTarget ? await salvageNativeMacCapture(salvageTarget) : null;
if (!salvage || !salvage.ok) {
pendingCursorRecordingData = null;
console.error("Failed to stop native macOS recording:", {
@@ -3279,10 +3280,29 @@ export function registerIpcHandlers(
}
nativeMacRecordingWarning = warning ? { screenVideoPath, message: warning } : null;
+ // A recovered take most often follows a disk that filled up, and these writes
+ // go to the same volume. The video is already safe on disk, so for a recovered
+ // take a failed side write is logged, and its partial file removed, instead of
+ // turning the recovery back into a lost take.
+ const writeAlongside = async (label: string, target: string, write: () => Promise<void>) => {
+ if (!recovered) {
+ await write();
+ return;
+ }
+ try {
+ await write();
+ } catch (error) {
+ console.warn(`[native-sck] could not write the recovered take's ${label}:`, error);
+ await fs.rm(target, { force: true }).catch(() => undefined);
+ }
+ };
+
if (cursorCaptureMode === "editable-overlay") {
compactPendingCursorTelemetryPauseRanges(nativeMacPauseRanges);
shiftPendingCursorTelemetry(nativeMacCursorOffsetMs);
- await writePendingCursorTelemetry(screenVideoPath);
+ await writeAlongside("cursor telemetry", `${screenVideoPath}.cursor.json`, () =>
+ writePendingCursorTelemetry(screenVideoPath),
+ );
}
const session: RecordingSession = {
@@ -3297,7 +3317,9 @@ export function registerIpcHandlers(
RECORDINGS_DIR,
`${path.parse(screenVideoPath).name}${RECORDING_SESSION_SUFFIX}`,
);
- await fs.writeFile(sessionManifestPath, JSON.stringify(session, null, 2), "utf-8");
+ await writeAlongside("session manifest", sessionManifestPath, () =>
+ fs.writeFile(sessionManifestPath, JSON.stringify(session, null, 2), "utf-8"),
+ );
await registerRecordingMediaLinks(screenVideoPath, { cursorCaptureMode });
return {
diff --git a/electron/recording/nativeMacCaptureSalvage.test.ts b/electron/recording/nativeMacCaptureSalvage.test.ts
index a39454131..1cf39180c 100644
--- a/electron/recording/nativeMacCaptureSalvage.test.ts
+++ b/electron/recording/nativeMacCaptureSalvage.test.ts
@@ -6,6 +6,7 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest";
import {
describeSalvagedTake,
inspectNativeMacCapture,
+ nativeMacSalvageTarget,
salvageNativeMacCapture,
} from "./nativeMacCaptureSalvage";
@@ -176,6 +177,7 @@ describe("salvageNativeMacCapture", () => {
expect(await sizeOf(file)).toBe(KILLED_29S.firstMoof);
});
+ /** Players skip these 4 bytes anyway; the cut is a precaution, and it loses nothing. */
it("cuts off a box header left half-written at the end", async () => {
const file = await take("helper-killed-29s", KILLED_29S.wide + 4);
@@ -195,14 +197,76 @@ describe("salvageNativeMacCapture", () => {
});
});
+describe("nativeMacSalvageTarget", () => {
+ const TARGET = "/rec/recording-1.mp4";
+
+ it("salvages the requested file once the helper has exited", () => {
+ expect(
+ nativeMacSalvageTarget(
+ { ok: false, reason: "helper-failed", message: "x", exited: true },
+ TARGET,
+ ),
+ ).toBe(TARGET);
+ });
+
+ /** Salvage truncates; a helper that did not exit may still be inside finishWriting. */
+ it("never salvages a file a helper that did not exit may still be writing", () => {
+ expect(
+ nativeMacSalvageTarget(
+ { ok: false, reason: "stop-timeout", message: "x", exited: false },
+ TARGET,
+ ),
+ ).toBeNull();
+ });
+
+ it("has nothing to salvage after a stop that worked", () => {
+ expect(nativeMacSalvageTarget({ ok: true, screenVideoPath: TARGET }, TARGET)).toBeNull();
+ });
+
+ it("has nothing to salvage when no file was requested", () => {
+ expect(
+ nativeMacSalvageTarget(
+ { ok: false, reason: "helper-failed", message: "x", exited: true },
+ null,
+ ),
+ ).toBeNull();
+ });
+});
+
describe("describeSalvagedTake", () => {
- it("quotes the readable part of an NSError", () => {
+ /** Verbatim from the helper, in the disk-full end-to-end run. */
+ it("keeps the helper's sentence and adds a description that says something", () => {
expect(
describeSalvagedTake(
- 'Recording stopped: the video file could not be written (video append: Error Domain=AVFoundationErrorDomain Code=-11807 "Disk Full" UserInfo={NSLocalizedDescription=Disk Full, NSUnderlyingError=0x1 {Error Domain=NSPOSIXErrorDomain Code=28}}).',
+ 'Recording stopped: the video file could not be written (writer status: Error Domain=AVFoundationErrorDomain Code=-11807 "Disk Full" UserInfo={NSLocalizedDescription=Disk Full, NSUnderlyingError=0x9e326c930 {Error Domain=NSPOSIXErrorDomain Code=28 "No space left on device"}, NSLocalizedRecoverySuggestion=Make room by deleting existing files and try again., NSLocalizedFailureReason=There is not enough available space to continue the file writing.}).',
35.01,
),
- ).toBe("Recording stopped after 0:35: Disk Full. The part recorded until then was saved.");
+ ).toBe(
+ "Recording stopped after 0:35: the video file could not be written (Disk Full). The part recorded until then was saved.",
+ );
+ });
+
+ /** The -16364 writer death this whole path started from; its description is generic. */
+ it("does not replace the helper's sentence with a generic NSError description", () => {
+ expect(
+ describeSalvagedTake(
+ 'Recording stopped: the video file could not be written (video append: Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could not be completed" UserInfo={NSLocalizedFailureReason=An unknown error occurred (-16364), NSLocalizedDescription=The operation could not be completed, NSUnderlyingError=0x1 {Error Domain=NSOSStatusErrorDomain Code=-16364 "(null)"}}).',
+ 73.01,
+ ),
+ ).toBe(
+ "Recording stopped after 1:13: the video file could not be written. The part recorded until then was saved.",
+ );
+ });
+
+ it("reads a bare NSError by its description", () => {
+ expect(
+ describeSalvagedTake(
+ 'Error Domain=com.apple.ScreenCaptureKit.SCStreamErrorDomain Code=-3815 "The stream was stopped by the system." UserInfo={NSLocalizedDescription=The stream was stopped by the system.}',
+ 12,
+ ),
+ ).toBe(
+ "Recording stopped after 0:12: The stream was stopped by the system. The part recorded until then was saved.",
+ );
});
it("uses the whole message when there is no NSError in it", () => {
@@ -211,6 +275,13 @@ describe("describeSalvagedTake", () => {
);
});
+ /** Measured: a 35 s disk-full take whose frame durations sum to 34.98 s. */
+ it("rounds the length rather than cutting a second off it", () => {
+ expect(describeSalvagedTake("Disk Full", 34.983333)).toBe(
+ "Recording stopped after 0:35: Disk Full. The part recorded until then was saved.",
+ );
+ });
+
it("counts hours on a long take", () => {
expect(describeSalvagedTake("Disk Full", 3725)).toBe(
"Recording stopped after 1:02:05: Disk Full. The part recorded until then was saved.",
diff --git a/electron/recording/nativeMacCaptureSalvage.ts b/electron/recording/nativeMacCaptureSalvage.ts
index 38485f32b..90f3d6dc6 100644
--- a/electron/recording/nativeMacCaptureSalvage.ts
+++ b/electron/recording/nativeMacCaptureSalvage.ts
@@ -28,12 +28,16 @@ import fs from "node:fs/promises";
*
* # The one layout that has to be repaired
*
- * A file cut inside a box other than `mdat` (a torn `moof`) does not open anywhere.
- * Cut back to the start of that box it opens, and keeps every fragment before it.
- * So a torn tail is truncated and the file inspected again — a file is never
- * reported recoverable while bytes that break it are still on disk.
+ * A file cut inside a `moof` opens nowhere: ffmpeg, libavformat and Chromium all
+ * refuse it. Cut back to the start of that `moof` it opens, and keeps every fragment
+ * before it. So a torn tail is truncated and the file inspected again. The same cut
+ * is applied to anything else left unfinished at the end, such as a header of a few
+ * bytes, which players skip anyway: it costs nothing, and a file is never reported
+ * recoverable while bytes that could break it are still on disk.
*/
+import type { NativeMacCaptureStopResult } from "./nativeMacCaptureStop";
+
/** Guards against a corrupt size field making a structural box look enormous. */
const MAX_INDEX_BOX_BYTES = 64 * 1024 * 1024;
@@ -483,23 +487,57 @@ export async function salvageNativeMacCapture(filePath: string): Promise<NativeM
}
function formatDuration(seconds: number) {
- const total = Math.max(0, Math.floor(seconds));
+ // Rounded, not floored: the frame durations of a 35 s take sum to 34.98 s, and
+ // "0:34" would contradict the length the editor then shows.
+ const total = Math.max(0, Math.round(seconds));
const hours = Math.floor(total / 3600);
const minutes = Math.floor((total % 3600) / 60);
const rest = String(total % 60).padStart(2, "0");
return hours > 0 ? `${hours}:${String(minutes).padStart(2, "0")}:${rest}` : `${minutes}:${rest}`;
}
+/**
+ * The file a failed stop may be salvaged from, or null.
+ *
+ * Only once the helper has exited: a stop that timed out leaves a helper that may
+ * still be inside finishWriting, and salvaging truncates.
+ */
+export function nativeMacSalvageTarget(
+ result: NativeMacCaptureStopResult,
+ targetPath: string | null,
+): string | null {
+ return !result.ok && result.exited && targetPath ? targetPath : null;
+}
+
+/** NSError descriptions that say nothing a person can act on. */
+const GENERIC_ERROR_DESCRIPTIONS = new Set(["The operation could not be completed"]);
+
/**
* The warning for a take whose stop failed but whose file was recovered.
*
- * The stop's message usually embeds an NSError; its localized description is the
- * part a person can read ("Disk Full").
+ * The helper's messages are a sentence followed by a raw NSError, e.g. "Recording
+ * stopped: the video file could not be written (video append: Error Domain=…
+ * NSLocalizedDescription=Disk Full …)". The sentence is kept; the NSError is
+ * reduced to its localized description, and only when that says something —
+ * AVFoundation's -11800 says "The operation could not be completed".
*/
export function describeSalvagedTake(failureMessage: string, durationSec: number) {
- const description = /NSLocalizedDescription=([^,}]+)/.exec(failureMessage)?.[1]?.trim();
- const reason = (description ?? failureMessage)
- .replace(/^Recording stopped:\s*/i, "")
- .replace(/[.\s]+$/, "");
+ const text = failureMessage.trim().replace(/^Recording stopped:\s*/i, "");
+ const description = /NSLocalizedDescription=([^,}]+)/.exec(text)?.[1]?.trim();
+ const usefulDescription =
+ description && !GENERIC_ERROR_DESCRIPTIONS.has(description) ? description : undefined;
+
+ let reason = text;
+ const errorStart = text.indexOf("Error Domain=");
+ if (errorStart !== -1) {
+ const openParen = text.lastIndexOf("(", errorStart);
+ const sentence = text.slice(0, openParen === -1 ? errorStart : openParen).trim();
+ if (sentence && usefulDescription) {
+ reason = `${sentence} (${usefulDescription})`;
+ } else {
+ reason = sentence || usefulDescription || description || "the recorder failed";
+ }
+ }
+ reason = reason.replace(/[.\s]+$/, "");
return `Recording stopped after ${formatDuration(durationSec)}: ${reason}. The part recorded until then was saved.`;
}