Skip to content

Create polished demo videos without editing skills. Mac/Windows/Linux

feat(library): add recording storage, thumbnails and sequence imports

webadderall7d0f478ca826
diff --git a/electron/ipc/constants.ts b/electron/ipc/constants.ts
index 2c5cf8f1..9e438b4b 100644
--- a/electron/ipc/constants.ts
+++ b/electron/ipc/constants.ts
@@ -12,8 +12,6 @@ export const RECORDINGS_SETTINGS_FILE = path.join(USER_DATA_PATH, "recordings-se
export const COUNTDOWN_SETTINGS_FILE = path.join(USER_DATA_PATH, "countdown-settings.json");
export const APP_SETTINGS_FILE = path.join(USER_DATA_PATH, "app-settings.json");
export const AUTO_RECORDING_PREFIX = "recording-";
-export const AUTO_RECORDING_RETENTION_COUNT = 20;
-export const AUTO_RECORDING_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000;
export const ALLOW_RECORDLY_WINDOW_CAPTURE = Boolean(process.env["VITE_DEV_SERVER_URL"]);
export const RECORDING_SESSION_MANIFEST_SUFFIX = ".recordly-session.json";
export const WHISPER_MODEL_DOWNLOAD_URL =
diff --git a/electron/ipc/export/native-video.ts b/electron/ipc/export/native-video.ts
index 81b56b48..1aa5fc4e 100644
--- a/electron/ipc/export/native-video.ts
+++ b/electron/ipc/export/native-video.ts
@@ -1,3 +1,11 @@
+import { probeNativeVideoMetadata, type NativeVideoMetadataProbe } from "../ffmpeg/metadata";
+export {
+ probeNativeVideoMetadata,
+ parseNativeVideoMetadataProbeOutput,
+ parseFfmpegDurationSeconds,
+ parseFfmpegFrameRate,
+ type NativeVideoMetadataProbe,
+} from "../ffmpeg/metadata";
import type { ChildProcessByStdio } from "node:child_process";
import { execFile, spawn } from "node:child_process";
import fs from "node:fs/promises";
@@ -308,20 +316,6 @@ export interface NvidiaCudaExportSummary {
outputAudio?: unknown;
}
-export interface NativeVideoMetadataProbe {
- width: number;
- height: number;
- duration: number;
- mediaStartTime?: number;
- streamStartTime?: number;
- streamDuration?: number;
- frameRate: number;
- codec: string;
- hasAudio: boolean;
- audioCodec?: string;
- audioSampleRate?: number;
-}
-
export interface NativeVideoStreamStatsProbe {
durationSec: number | null;
frameCount: number | null;
@@ -961,116 +955,6 @@ export interface NativeExportCapabilities {
};
}
-export function parseFfmpegDurationSeconds(value: string): number | null {
- const parts = value.trim().split(":");
- if (parts.length !== 3) {
- return null;
- }
-
- const [hours, minutes, seconds] = parts.map(Number);
- if (![hours, minutes, seconds].every(Number.isFinite)) {
- return null;
- }
-
- return hours * 3600 + minutes * 60 + seconds;
-}
-
-export function parseFfmpegFrameRate(line: string): number | null {
- const fpsMatch = line.match(/,\s*([0-9]+(?:\.[0-9]+)?)\s*fps\b/i);
- if (fpsMatch) {
- const frameRate = Number(fpsMatch[1]);
- return Number.isFinite(frameRate) && frameRate > 0 ? frameRate : null;
- }
-
- const tbrMatch = line.match(/,\s*([0-9]+(?:\.[0-9]+)?)\s*tbr\b/i);
- if (tbrMatch) {
- const frameRate = Number(tbrMatch[1]);
- return Number.isFinite(frameRate) && frameRate > 0 ? frameRate : null;
- }
-
- return null;
-}
-
-export function parseNativeVideoMetadataProbeOutput(
- output: string,
-): NativeVideoMetadataProbe | null {
- const durationMatch = output.match(
- /Duration:\s*([0-9:.]+),\s*start:\s*(-?[0-9]+(?:\.[0-9]+)?)/i,
- );
- const duration = durationMatch ? parseFfmpegDurationSeconds(durationMatch[1]) : null;
- if (!duration || duration <= 0) {
- return null;
- }
-
- const mediaStartTime = durationMatch ? Number(durationMatch[2]) : 0;
- const lines = output.split(/\r?\n/);
- const videoLine = lines.find((line) => /\bVideo:\s*/i.test(line));
- if (!videoLine) {
- return null;
- }
-
- const dimensionsMatch = videoLine.match(/,\s*([0-9]{2,5})x([0-9]{2,5})(?:[,\s]|$)/);
- if (!dimensionsMatch) {
- return null;
- }
-
- const width = Number(dimensionsMatch[1]);
- const height = Number(dimensionsMatch[2]);
- if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
- return null;
- }
-
- const videoCodecMatch = videoLine.match(/Video:\s*([^,\r\n]+)/i);
- const videoStartMatch = videoLine.match(/\bstart:\s*(-?[0-9]+(?:\.[0-9]+)?)/i);
- const frameRate = parseFfmpegFrameRate(videoLine) ?? 60;
- const audioLine = lines.find((line) => /\bAudio:\s*/i.test(line));
- const audioCodecMatch = audioLine?.match(/Audio:\s*([^,\r\n]+)/i);
- const audioSampleRateMatch = audioLine?.match(/,\s*([0-9]+)\s*Hz\b/i);
-
- return {
- width,
- height,
- duration,
- mediaStartTime: Number.isFinite(mediaStartTime) ? mediaStartTime : 0,
- streamStartTime: videoStartMatch ? Number(videoStartMatch[1]) : mediaStartTime,
- streamDuration: duration,
- frameRate,
- codec: videoCodecMatch?.[1]?.trim() || "unknown",
- hasAudio: Boolean(audioLine),
- audioCodec: audioCodecMatch?.[1]?.trim(),
- audioSampleRate: audioSampleRateMatch ? Number(audioSampleRateMatch[1]) : undefined,
- };
-}
-
-export async function probeNativeVideoMetadata(
- ffmpegPath: string,
- inputPath: string,
-): Promise<NativeVideoMetadataProbe> {
- let output = "";
- try {
- const result = await execFileAsync(ffmpegPath, ["-hide_banner", "-i", inputPath], {
- timeout: 30_000,
- maxBuffer: 4 * 1024 * 1024,
- });
- output = `${result.stdout}\n${result.stderr}`;
- } catch (error) {
- const processOutput = error as { stdout?: unknown; stderr?: unknown };
- output = [processOutput.stdout, processOutput.stderr]
- .filter((value): value is string => typeof value === "string")
- .join("\n");
- if (!output) {
- throw error;
- }
- }
-
- const metadata = parseNativeVideoMetadataProbeOutput(output);
- if (!metadata) {
- throw new Error("Unable to parse native video metadata from FFmpeg output");
- }
-
- return metadata;
-}
-
export async function probeNativeVideoStreamStats(
ffprobePath: string,
inputPath: string,
diff --git a/electron/ipc/ffmpeg/metadata.ts b/electron/ipc/ffmpeg/metadata.ts
new file mode 100644
index 00000000..10b68f8b
--- /dev/null
+++ b/electron/ipc/ffmpeg/metadata.ts
@@ -0,0 +1,127 @@
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+const execFileAsync = promisify(execFile);
+
+export interface NativeVideoMetadataProbe {
+ width: number;
+ height: number;
+ duration: number;
+ mediaStartTime?: number;
+ streamStartTime?: number;
+ streamDuration?: number;
+ frameRate: number;
+ codec: string;
+ hasAudio: boolean;
+ audioCodec?: string;
+ audioSampleRate?: number;
+}
+
+export function parseFfmpegDurationSeconds(value: string): number | null {
+ const parts = value.trim().split(":");
+ if (parts.length !== 3) {
+ return null;
+ }
+
+ const [hours, minutes, seconds] = parts.map(Number);
+ if (![hours, minutes, seconds].every(Number.isFinite)) {
+ return null;
+ }
+
+ return hours * 3600 + minutes * 60 + seconds;
+}
+
+export function parseFfmpegFrameRate(line: string): number | null {
+ const fpsMatch = line.match(/,\s*([0-9]+(?:\.[0-9]+)?)\s*fps\b/i);
+ if (fpsMatch) {
+ const frameRate = Number(fpsMatch[1]);
+ return Number.isFinite(frameRate) && frameRate > 0 ? frameRate : null;
+ }
+
+ const tbrMatch = line.match(/,\s*([0-9]+(?:\.[0-9]+)?)\s*tbr\b/i);
+ if (tbrMatch) {
+ const frameRate = Number(tbrMatch[1]);
+ return Number.isFinite(frameRate) && frameRate > 0 ? frameRate : null;
+ }
+
+ return null;
+}
+
+export function parseNativeVideoMetadataProbeOutput(
+ output: string,
+): NativeVideoMetadataProbe | null {
+ const durationMatch = output.match(
+ /Duration:\s*([0-9:.]+),\s*start:\s*(-?[0-9]+(?:\.[0-9]+)?)/i,
+ );
+ const duration = durationMatch ? parseFfmpegDurationSeconds(durationMatch[1]) : null;
+ if (!duration || duration <= 0) {
+ return null;
+ }
+
+ const mediaStartTime = durationMatch ? Number(durationMatch[2]) : 0;
+ const lines = output.split(/\r?\n/);
+ const videoLine = lines.find((line) => /\bVideo:\s*/i.test(line));
+ if (!videoLine) {
+ return null;
+ }
+
+ const dimensionsMatch = videoLine.match(/,\s*([0-9]{2,5})x([0-9]{2,5})(?:[,\s]|$)/);
+ if (!dimensionsMatch) {
+ return null;
+ }
+
+ const width = Number(dimensionsMatch[1]);
+ const height = Number(dimensionsMatch[2]);
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
+ return null;
+ }
+
+ const videoCodecMatch = videoLine.match(/Video:\s*([^,\r\n]+)/i);
+ const videoStartMatch = videoLine.match(/\bstart:\s*(-?[0-9]+(?:\.[0-9]+)?)/i);
+ const frameRate = parseFfmpegFrameRate(videoLine) ?? 60;
+ const audioLine = lines.find((line) => /\bAudio:\s*/i.test(line));
+ const audioCodecMatch = audioLine?.match(/Audio:\s*([^,\r\n]+)/i);
+ const audioSampleRateMatch = audioLine?.match(/,\s*([0-9]+)\s*Hz\b/i);
+
+ return {
+ width,
+ height,
+ duration,
+ mediaStartTime: Number.isFinite(mediaStartTime) ? mediaStartTime : 0,
+ streamStartTime: videoStartMatch ? Number(videoStartMatch[1]) : mediaStartTime,
+ streamDuration: duration,
+ frameRate,
+ codec: videoCodecMatch?.[1]?.trim() || "unknown",
+ hasAudio: Boolean(audioLine),
+ audioCodec: audioCodecMatch?.[1]?.trim(),
+ audioSampleRate: audioSampleRateMatch ? Number(audioSampleRateMatch[1]) : undefined,
+ };
+}
+
+export async function probeNativeVideoMetadata(
+ ffmpegPath: string,
+ inputPath: string,
+): Promise<NativeVideoMetadataProbe> {
+ let output = "";
+ try {
+ const result = await execFileAsync(ffmpegPath, ["-hide_banner", "-i", inputPath], {
+ timeout: 30_000,
+ maxBuffer: 4 * 1024 * 1024,
+ });
+ output = `${result.stdout}\n${result.stderr}`;
+ } catch (error) {
+ const processOutput = error as { stdout?: unknown; stderr?: unknown };
+ output = [processOutput.stdout, processOutput.stderr]
+ .filter((value): value is string => typeof value === "string")
+ .join("\n");
+ if (!output) {
+ throw error;
+ }
+ }
+
+ const metadata = parseNativeVideoMetadataProbeOutput(output);
+ if (!metadata) {
+ throw new Error("Unable to parse native video metadata from FFmpeg output");
+ }
+
+ return metadata;
+}
diff --git a/electron/ipc/recording/diagnostics.ts b/electron/ipc/recording/diagnostics.ts
index 76a9a343..2c7c7cd6 100644
--- a/electron/ipc/recording/diagnostics.ts
+++ b/electron/ipc/recording/diagnostics.ts
@@ -1,3 +1,4 @@
+import { isLibrarySequenceSource } from "./sequenceSource";
import { execFile } from "node:child_process";
import fs from "node:fs/promises";
import { promisify } from "node:util";
@@ -513,7 +514,9 @@ export async function getCompanionAudioFallbackInfo(videoPath: string) {
}
let paths: string[];
- if (await hasEmbeddedAudioStream(videoPath)) {
+ if (isLibrarySequenceSource(videoPath)) {
+ paths = companionCandidates.flatMap((candidate) => candidate.usablePaths);
+ } else if (await hasEmbeddedAudioStream(videoPath)) {
const hasUsableMacSystemCompanion = companionCandidates.some(
(candidate) =>
candidate.platform === "mac" &&
diff --git a/electron/ipc/recording/importRecording.ts b/electron/ipc/recording/importRecording.ts
new file mode 100644
index 00000000..a12fce58
--- /dev/null
+++ b/electron/ipc/recording/importRecording.ts
@@ -0,0 +1,240 @@
+import { composeSequenceWebcam, sequenceWebcamOutputs } from "./sequenceWebcam";
+import { probeNativeVideoMetadata } from "../ffmpeg/metadata";
+import { isLibrarySequenceSource } from "./sequenceSource";
+import { execFile } from "node:child_process";
+import { randomUUID } from "node:crypto";
+import fs from "node:fs/promises";
+import path from "node:path";
+import { promisify } from "node:util";
+import { buildMediaUrl, getMediaServerBaseUrl } from "../../mediaServer";
+import { getFfmpegBinaryPath } from "../ffmpeg/binary";
+import { rememberApprovedLocalReadPath, resolveApprovedLocalMediaPath } from "../project/manager";
+import { getRecordingsDir, getTelemetryPathForVideo } from "../utils";
+import { getUsableCompanionAudioCandidates } from "./diagnostics";
+import { normalizeCursorTelemetrySamples, writeCursorTelemetry } from "../cursor/telemetry";
+import { listRecordings } from "./library";
+import type {
+ RecordingImportResult,
+ RecordingWebcamSource,
+} from "../../../src/types/recordingLibrary";
+
+const run = promisify(execFile);
+async function ffmpeg(args: string[]) {
+ await run(
+ getFfmpegBinaryPath(),
+ ["-hide_banner", "-loglevel", "error", "-nostdin", "-y", ...args],
+ { timeout: 60 * 60 * 1000, maxBuffer: 1024 * 1024, windowsHide: true },
+ );
+}
+async function probe(file: string) {
+ const meta = await probeNativeVideoMetadata(getFfmpegBinaryPath(), file);
+ return {
+ width: meta.width,
+ height: meta.height,
+ fps: meta.frameRate,
+ duration: meta.duration,
+ audio: meta.hasAudio,
+ };
+}
+type Format = { width: number; height: number; fps: number };
+
+/** Normalize new media once. Existing sequence video is copied, avoiding generation loss. */
+async function normalize(file: string, out: string, format: Format, copyVideo: boolean) {
+ const meta = await probe(file);
+ const candidates = await getUsableCompanionAudioCandidates(file);
+ const companion = candidates[0];
+ const system = companion?.usablePaths.includes(companion.systemPath)
+ ? companion.systemPath
+ : null;
+ const mic = companion?.usablePaths.includes(companion.micPath) ? companion.micPath : null;
+ const args = ["-i", file];
+ const filters: string[] = [];
+ let input = 1;
+ for (const [kind, source] of [
+ ["system", system],
+ ["mic", mic],
+ ] as const) {
+ let label: string;
+ let delay = 0;
+ if (source) {
+ args.push("-i", source);
+ label = `${input++}:a:0`;
+ try {
+ delay = Math.max(
+ 0,
+ Number(JSON.parse(await fs.readFile(`${source}.json`, "utf8")).startDelayMs) ||
+ 0,
+ );
+ } catch {
+ /* Optional capture timing. */
+ }
+ } else if (kind === "system" && meta.audio) {
+ label = "0:a:0";
+ } else {
+ args.push("-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo");
+ label = `${input++}:a:0`;
+ }
+ filters.push(
+ `[${label}]aresample=48000,aformat=sample_fmts=s16:channel_layouts=stereo,asetpts=PTS-STARTPTS,adelay=${Math.round(delay)}:all=1,apad,atrim=duration=${meta.duration}[${kind}]`,
+ );
+ }
+ if (!copyVideo)
+ filters.push(
+ `[0:v:0]setpts=PTS-STARTPTS,scale=${format.width}:${format.height}:force_original_aspect_ratio=decrease,pad=${format.width}:${format.height}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=${format.fps},format=yuv420p[v]`,
+ );
+ args.push(
+ "-filter_complex",
+ filters.join(";"),
+ "-map",
+ copyVideo ? "0:v:0" : "[v]",
+ "-map",
+ "[system]",
+ "-map",
+ "[mic]",
+ "-c:v",
+ copyVideo ? "copy" : "libx264",
+ );
+ if (!copyVideo) args.push("-preset", "fast", "-crf", "18");
+ args.push("-c:a", "pcm_s16le", "-t", String(meta.duration), out);
+ await ffmpeg(args);
+}
+
+/** The editor and export share one immutable source, with stable offsets across imports. */
+export async function importRecording(
+ currentPath: string,
+ recordingPath: string,
+ currentWebcam?: RecordingWebcamSource,
+): Promise<RecordingImportResult> {
+ const entry = (await listRecordings()).find((entry) => entry.path === recordingPath);
+ if (!entry) throw new Error("Recording is no longer in Videos");
+ const current = await resolveApprovedLocalMediaPath(currentPath);
+ if (!current) throw new Error("Current video is no longer available");
+ const server = getMediaServerBaseUrl();
+ if (!server) throw new Error("Media server is not ready");
+ const root = path.join(await getRecordingsDir(), ".recordly-media");
+ await fs.mkdir(root, { recursive: true });
+ const base = await probe(current);
+ const format = {
+ width: Math.ceil(base.width / 2) * 2,
+ height: Math.ceil(base.height / 2) * 2,
+ fps: base.fps,
+ };
+ const id = randomUUID();
+ const work = await fs.mkdtemp(path.join(root, "import-"));
+ const output = path.join(root, `${id}.mp4`);
+ const stem = output.slice(0, -4);
+ const outputs = [
+ ...sequenceWebcamOutputs(output),
+ output,
+ `${stem}.system.wav`,
+ `${stem}.mic.wav`,
+ `${output}.cursor.json`,
+ ];
+ try {
+ const normalizedBase = path.join(work, "base.mkv");
+ const normalizedNew = path.join(work, "new.mkv");
+ // Only our own normalized source format may be copied across appends.
+ const copyVideo = isLibrarySequenceSource(current);
+ await normalize(current, normalizedBase, format, copyVideo);
+ await normalize(entry.path, normalizedNew, format, false);
+ const baseMeta = await probe(normalizedBase);
+ const newMeta = await probe(normalizedNew);
+ await fs.writeFile(path.join(work, "list.txt"), "file 'base.mkv'\nfile 'new.mkv'\n");
+ const combined = path.join(work, "combined.mkv");
+ await ffmpeg([
+ "-f",
+ "concat",
+ "-safe",
+ "1",
+ "-i",
+ path.join(work, "list.txt"),
+ "-map",
+ "0",
+ "-c",
+ "copy",
+ combined,
+ ]);
+ await ffmpeg([
+ "-i",
+ combined,
+ "-filter_complex",
+ "[0:a:0][0:a:1]amix=inputs=2:normalize=0[mix]",
+ "-map",
+ "0:v:0",
+ "-map",
+ "[mix]",
+ "-c:v",
+ "copy",
+ "-c:a",
+ "aac",
+ "-b:a",
+ "192k",
+ "-movflags",
+ "+faststart",
+ output,
+ "-map",
+ "0:a:0",
+ "-c:a",
+ "pcm_s16le",
+ `${stem}.system.wav`,
+ "-map",
+ "0:a:1",
+ "-c:a",
+ "pcm_s16le",
+ `${stem}.mic.wav`,
+ ]);
+ const sourceStartMs = Math.round(baseMeta.duration * 1000);
+ const samples = [];
+ for (const [file, offset, meta] of [
+ [current, 0, base],
+ [entry.path, sourceStartMs, await probe(entry.path)],
+ ] as const) {
+ let points: ReturnType<typeof normalizeCursorTelemetrySamples> = [];
+ try {
+ points = normalizeCursorTelemetrySamples(
+ JSON.parse(await fs.readFile(getTelemetryPathForVideo(file), "utf8")),
+ );
+ } catch {
+ /* Recording may not contain cursor telemetry. */
+ }
+ const scale = Math.min(format.width / meta.width, format.height / meta.height);
+ samples.push(
+ ...points.map((point) => ({
+ ...point,
+ timeMs: point.timeMs + offset,
+ cx:
+ (point.cx * meta.width * scale + (format.width - meta.width * scale) / 2) /
+ format.width,
+ cy:
+ (point.cy * meta.height * scale +
+ (format.height - meta.height * scale) / 2) /
+ format.height,
+ })),
+ );
+ }
+ await writeCursorTelemetry(output, samples);
+ const webcam = await composeSequenceWebcam(
+ current,
+ entry.path,
+ output,
+ work,
+ sourceStartMs,
+ Math.round(newMeta.duration * 1000),
+ currentWebcam,
+ );
+ await rememberApprovedLocalReadPath(output);
+ return {
+ path: output,
+ webcam,
+ url: buildMediaUrl(server, output),
+ sourceStartMs,
+ durationMs: Math.round(newMeta.duration * 1000),
+ totalDurationMs: sourceStartMs + Math.round(newMeta.duration * 1000),
+ };
+ } catch (error) {
+ await Promise.all(outputs.map((file) => fs.rm(file, { force: true })));
+ throw error;
+ } finally {
+ await fs.rm(work, { recursive: true, force: true });
+ }
+}
diff --git a/electron/ipc/recording/library.test.ts b/electron/ipc/recording/library.test.ts
new file mode 100644
index 00000000..39d547fe
--- /dev/null
+++ b/electron/ipc/recording/library.test.ts
@@ -0,0 +1,205 @@
+import { execFile } from "node:child_process";
+import { createRequire } from "node:module";
+import fs from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { promisify } from "node:util";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+
+const state = vi.hoisted(() => ({ root: "", approved: new Set<string>() }));
+vi.mock("electron", () => ({
+ app: { getPath: () => state.root },
+ shell: { trashItem: vi.fn(async (file: string) => {
+ await fs.mkdir(path.join(state.root, ".test-trash"), { recursive: true });
+ await fs.rename(file, path.join(state.root, ".test-trash", path.basename(file)));
+ }) },
+}));
+vi.mock("../../appPaths", () => ({
+ USER_DATA_PATH: "/tmp/recordly-test",
+ RECORDINGS_DIR: "/tmp/recordly-test",
+}));
+vi.mock("../utils", () => ({
+ getRecordingsDir: async () => state.root,
+ getTelemetryPathForVideo: (file: string) => `${file}.cursor.json`,
+ parseJsonWithByteOrderMark: JSON.parse,
+ normalizeVideoSourcePath: (file: string) => file,
+ getScreen: vi.fn(),
+}));
+vi.mock("../../mediaServer", () => ({
+ getMediaServerBaseUrl: () => "http://127.0.0.1:9999",
+ buildMediaUrl: (server: string, file: string) =>
+ `${server}/video?path=${encodeURIComponent(file)}`,
+}));
+vi.mock("../project/manager", () => ({
+ rememberApprovedLocalReadPath: async (file: string) => {
+ state.approved.add(file);
+ },
+ resolveApprovedLocalMediaPath: async (file: string) => (state.approved.has(file) ? file : null),
+ isPathInsideDirectory: (file: string, root: string) => file.startsWith(`${root}${path.sep}`),
+}));
+vi.mock("../ffmpeg/binary", async () => {
+ const require = createRequire(import.meta.url);
+ return {
+ getFfmpegBinaryPath: () => require("ffmpeg-static"),
+ getFfprobeBinaryPath: () => require("ffprobe-static").path,
+ };
+});
+import { listRecordings, setRecordingsRemoved } from "./library";
+import { importRecording } from "./importRecording";
+import { getRecordingThumbnail } from "./thumbnail";
+import { getCompanionAudioFallbackInfo } from "./diagnostics";
+const require = createRequire(import.meta.url);
+const ffmpeg = require("ffmpeg-static") as string;
+const run = promisify(execFile);
+beforeEach(async () => {
+ state.root = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "recordly-library-")));
+ state.approved.clear();
+});
+afterEach(async () => {
+ await fs.rm(state.root, { recursive: true, force: true });
+});
+
+it("lists recordings, moves recordings and their companions to Trash with reversible removals, and excludes companion media and symlinks", async () => {
+ const first = path.join(state.root, "recording-old.mp4");
+ const second = path.join(state.root, "recording-new.mov");
+ for (const name of [
+ first,
+ second,
+ path.join(state.root, "recording-new.webcam.mp4"),
+ path.join(state.root, "recording-new.mic.wav"),
+ ])
+ await fs.writeFile(name, "fixture");
+ await fs.symlink(first, path.join(state.root, "linked.mp4"));
+ expect((await listRecordings()).map((entry) => entry.path).sort()).toEqual(
+ [first, second].sort(),
+ );
+ await setRecordingsRemoved([first, second], true);
+ expect(await listRecordings()).toEqual([]);
+ await expect(fs.access(first)).rejects.toThrow();
+ await expect(fs.access(path.join(state.root, "recording-new.mic.wav"))).rejects.toThrow();
+ expect(await fs.readdir(path.join(state.root, ".test-trash"))).toHaveLength(1);
+ await setRecordingsRemoved([first, second], false);
+ expect(await listRecordings()).toHaveLength(2);
+ expect(await fs.readFile(first, "utf8")).toBe("fixture");
+ expect(await fs.readFile(path.join(state.root, "recording-new.mic.wav"), "utf8")).toBe("fixture");
+ await expect(setRecordingsRemoved(["/tmp/outside.mp4"], true)).rejects.toThrow("outside");
+});
+
+it("imports different-sized recordings with playable video, separate audio, stable offsets, and untouched originals", async () => {
+ const base = path.join(state.root, "recording-base.mp4");
+ const added = path.join(state.root, "recording-added.mp4");
+ await run(ffmpeg, [
+ "-v",
+ "error",
+ "-f",
+ "lavfi",
+ "-i",
+ "color=c=red:s=160x90:r=30:d=1",
+ "-f",
+ "lavfi",
+ "-i",
+ "sine=frequency=440:duration=1",
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ "-c:a",
+ "aac",
+ "-shortest",
+ base,
+ ]);
+ await run(ffmpeg, [
+ "-v",
+ "error",
+ "-f",
+ "lavfi",
+ "-i",
+ "color=c=blue:s=90x160:r=30:d=1",
+ "-c:v",
+ "libx264",
+ "-pix_fmt",
+ "yuv420p",
+ added,
+ ]);
+ const webcam = added.replace(".mp4", "-webcam.mp4");
+ await run(ffmpeg, ["-v", "error", "-f", "lavfi", "-i", "color=c=lime:s=80x60:r=30:d=0.8", "-c:v", "libx264", "-pix_fmt", "yuv420p", webcam]);
+ await fs.writeFile(added.replace(".mp4", ".recordly-session.json"), JSON.stringify({ version: 2, webcamFileName: path.basename(webcam), timeOffsetMs: 200 }));
+ await fs.writeFile(`${added}.cursor.json`, JSON.stringify({ samples: [
+ { timeMs: 200, cx: 0.2, cy: 0.4, interactionType: "click", cursorType: "pointer" },
+ { timeMs: 260, cx: 0.2, cy: 0.4, interactionType: "mouseup", cursorType: "pointer" },
+ { timeMs: 600, cx: 0.4, cy: 0.5, interactionType: "right-click" },
+ ] }));
+ const original = await fs.readFile(base);
+ await listRecordings();
+ const thumbnail = await getRecordingThumbnail(base);
+ expect(thumbnail).toMatch(/^data:image\/jpeg;base64,/);
+ const jpeg = Buffer.from(thumbnail.split(",")[1], "base64");
+ expect([...jpeg.subarray(0, 2)]).toEqual([0xff, 0xd8]);
+ expect(await getRecordingThumbnail(base)).toBe(thumbnail);
+ await expect(getRecordingThumbnail("/tmp/unapproved.mp4")).rejects.toThrow("outside");
+ const result = await importRecording(base, added);
+ expect(result.sourceStartMs).toBeCloseTo(1000, -1);
+ expect(result.durationMs).toBeCloseTo(1000, -1);
+ expect(result.webcam?.visibleRanges).toEqual([{ startMs: 1200, endMs: 2000 }]);
+ const cursor = JSON.parse(await fs.readFile(`${result.path}.cursor.json`, "utf8")).samples;
+ expect(cursor.map((point: { timeMs: number; interactionType: string }) => [point.timeMs, point.interactionType])).toEqual([[1200, "click"], [1260, "mouseup"], [1600, "right-click"]]);
+ expect(cursor[0].cursorType).toBe("pointer");
+ expect(cursor[0].cx).toBeCloseTo(0.405078125);
+ const webcamPixels = await run(ffmpeg, ["-v", "error", "-ss", "1.5", "-i", result.webcam!.sourcePath!, "-vf", "crop=2:2:40:30", "-frames:v", "1", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"], { encoding: "buffer" });
+ expect(webcamPixels.stdout[1]).toBeGreaterThan(200);
+ const companions = await getCompanionAudioFallbackInfo(result.path);
+ expect(companions.paths).toHaveLength(2);
+ expect(companions.paths.every((file) => file.endsWith(".wav"))).toBe(true);
+ await run(ffmpeg, ["-v", "error", "-i", result.path, "-f", "null", "-"]);
+ const pixels = await run(
+ ffmpeg,
+ [
+ "-v",
+ "error",
+ "-ss",
+ "1.5",
+ "-i",
+ result.path,
+ "-vf",
+ "crop=2:2:80:44",
+ "-frames:v",
+ "1",
+ "-f",
+ "rawvideo",
+ "-pix_fmt",
+ "rgb24",
+ "-",
+ ],
+ { encoding: "buffer" },
+ );
+ expect(pixels.stdout[2]).toBeGreaterThan(200); // blue centre survives aspect-ratio fitting
+ const second = await importRecording(result.path, added);
+ expect(second.sourceStartMs).toBeCloseTo(2000, -1);
+ expect(second.webcam?.visibleRanges).toEqual([{ startMs: 1200, endMs: 2000 }, { startMs: 2200, endMs: 3000 }]);
+ expect(await fs.readFile(base)).toEqual(original);
+ expect((await listRecordings()).map((entry) => entry.path).sort()).toEqual(
+ [base, added].sort(),
+ );
+ await expect(importRecording("/tmp/unapproved.mp4", added)).rejects.toThrow(
+ "no longer available",
+ );
+}, 60000);
+
+
+it("restores every original when the OS refuses to trash the bundle", async () => {
+ const { shell } = await import("electron");
+ const file = path.join(state.root, "recording-failure.mp4");
+ await fs.writeFile(file, "original");
+ vi.mocked(shell.trashItem).mockRejectedValueOnce(new Error("Trash unavailable"));
+ await expect(setRecordingsRemoved([file], true)).rejects.toThrow("Trash unavailable");
+ expect(await fs.readFile(file, "utf8")).toBe("original");
+});
+
+it("undo never overwrites a new file at the original location", async () => {
+ const file = path.join(state.root, "recording-conflict.mp4");
+ await fs.writeFile(file, "original");
+ await setRecordingsRemoved([file], true);
+ await fs.writeFile(file, "new recording");
+ await expect(setRecordingsRemoved([file], false)).rejects.toThrow("already exists");
+ expect(await fs.readFile(file, "utf8")).toBe("new recording");
+});
diff --git a/electron/ipc/recording/library.ts b/electron/ipc/recording/library.ts
new file mode 100644
index 00000000..81322be8
--- /dev/null
+++ b/electron/ipc/recording/library.ts
@@ -0,0 +1,161 @@
+import fs from "node:fs/promises";
+import { constants } from "node:fs";
+import path from "node:path";
+import { app, shell } from "electron";
+import { buildMediaUrl, getMediaServerBaseUrl } from "../../mediaServer";
+import { rememberApprovedLocalReadPath } from "../project/manager";
+import { getRecordingsDir } from "../utils";
+import type { RecordingLibraryEntry } from "../../../src/types/recordingLibrary";
+
+let mutation = Promise.resolve();
+const undoBatches = new Map<string, { backup: string; files: string[] }>();
+const isRecording = (name: string) =>
+ /\.(mp4|mov|webm|mkv|m4v)$/i.test(name) && !/[.-]webcam[.-]/i.test(name);
+const batchKey = (paths: string[]) => JSON.stringify([...new Set(paths)].sort());
+
+export async function listRecordings(): Promise<RecordingLibraryEntry[]> {
+ const root = await fs.realpath(await getRecordingsDir());
+ const server = getMediaServerBaseUrl();
+ if (!server) throw new Error("Media server is not ready. Try again.");
+ const entries = await fs.readdir(root, { withFileTypes: true });
+ const result: RecordingLibraryEntry[] = [];
+ for (const entry of entries) {
+ if (!entry.isFile() || !isRecording(entry.name)) continue;
+ const filePath = path.join(root, entry.name);
+ const stat = await fs.stat(filePath);
+ if (!stat.size) continue;
+ await rememberApprovedLocalReadPath(filePath);
+ result.push({
+ path: filePath,
+ name: entry.name,
+ bytes: stat.size,
+ createdAt: stat.mtimeMs,
+ url: buildMediaUrl(server, filePath),
+ });
+ }
+ return result.sort((a, b) => b.createdAt - a.createdAt);
+}
+
+// Only capture sidecars belonging to this exact recording, never adjacent recordings or projects.
+function belongsToRecording(name: string, video: string) {
+ const stem = video.slice(0, -path.extname(video).length);
+ return (
+ name === video ||
+ name === `${video}.cursor.json` ||
+ (name.startsWith(`${stem}.`) &&
+ /\.(?:system|mic|microphone|audio|webcam)\.(?:wav|webm|mp4|m4a)(?:\.json)?$/i.test(
+ name,
+ )) ||
+ name === `${stem}.recordly-session.json` ||
+ name === `${stem}.recording-session.json` ||
+ (name.startsWith(`${stem}-webcam.`) && /\.(?:mp4|webm|mov|mkv|avi)$/i.test(name))
+ );
+}
+
+/** Move the recording bundle into the system Trash. Session backups allow cross-platform Undo. */
+export function setRecordingsRemoved(paths: string[], removed: boolean): Promise<void> {
+ const task = mutation.then(async () => {
+ if (
+ typeof removed !== "boolean" ||
+ !Array.isArray(paths) ||
+ !paths.length ||
+ paths.some((value) => typeof value !== "string")
+ )
+ throw new Error("Invalid recording selection");
+ const root = await fs.realpath(await getRecordingsDir());
+ const selected = [...new Set(paths)];
+ for (const candidate of selected) {
+ if (path.dirname(candidate) !== root || !isRecording(path.basename(candidate)))
+ throw new Error("Recording is outside the Videos library");
+ }
+ const key = batchKey(selected);
+ if (!removed) {
+ const batch = undoBatches.get(key);
+ if (!batch)
+ throw new Error(
+ "This removal can no longer be undone. Restore the files from Trash.",
+ );
+ // Check every destination before restoring any file; never overwrite newer media.
+ for (const file of batch.files) {
+ if (
+ await fs.lstat(file).then(
+ () => true,
+ (error) => {
+ if (error.code === "ENOENT") return false;
+ throw error;
+ },
+ )
+ )
+ throw new Error(
+ "A file with this name already exists. Restore it from Trash instead.",
+ );
+ }
+ const restored: string[] = [];
+ try {
+ for (const file of batch.files) {
+ await fs.copyFile(
+ path.join(batch.backup, path.basename(file)),
+ file,
+ constants.COPYFILE_EXCL,
+ );
+ restored.push(file);
+ }
+ } catch (error) {
+ await Promise.all(restored.map((file) => fs.rm(file, { force: true })));
+ throw error;
+ }
+ undoBatches.delete(key);
+ await fs.rm(batch.backup, { recursive: true, force: true });
+ return;
+ }
+ const available = await fs.readdir(root, { withFileTypes: true });
+ for (const file of selected) {
+ if (!available.some((entry) => entry.name === path.basename(file) && entry.isFile()))
+ throw new Error("Recording is missing or is not a regular file");
+ }
+ const files = available
+ .filter(
+ (entry) =>
+ entry.isFile() &&
+ selected.some((file) => belongsToRecording(entry.name, path.basename(file))),
+ )
+ .map((entry) => path.join(root, entry.name));
+ const backup = await fs.mkdtemp(path.join(app.getPath("temp"), "recordly-trash-undo-"));
+ const bundle = await fs.mkdtemp(path.join(root, "Recordly videos "));
+ const moved: string[] = [];
+ try {
+ for (const file of files)
+ await fs.copyFile(
+ file,
+ path.join(backup, path.basename(file)),
+ constants.COPYFILE_FICLONE,
+ );
+ for (const file of files) {
+ await fs.rename(file, path.join(bundle, path.basename(file)));
+ moved.push(file);
+ }
+ await shell.trashItem(bundle);
+ undoBatches.set(key, { backup, files });
+ } catch (error) {
+ for (const file of moved) await fs.rename(path.join(bundle, path.basename(file)), file);
+ await fs.rm(backup, { recursive: true, force: true });
+ throw error;
+ } finally {
+ await fs.rmdir(bundle).catch((error) => {
+ if (error.code !== "ENOENT") throw error;
+ });
+ }
+ });
+ mutation = task.catch(() => undefined);
+ return task;
+}
+
+export async function clearRecordingTrashUndo() {
+ await mutation;
+ await Promise.all(
+ [...undoBatches.values()].map(({ backup }) =>
+ fs.rm(backup, { recursive: true, force: true }),
+ ),
+ );
+ undoBatches.clear();
+}
diff --git a/electron/ipc/recording/mac.ts b/electron/ipc/recording/mac.ts
index 57a9e688..bec79bc0 100644
--- a/electron/ipc/recording/mac.ts
+++ b/electron/ipc/recording/mac.ts
@@ -23,7 +23,7 @@ import {
setNativeCaptureTargetPath,
setNativeScreenRecordingActive,
} from "../state";
-import { isAutoRecordingPath, moveFileWithOverwrite } from "../utils";
+import { moveFileWithOverwrite } from "../utils";
import {
getFileSizeIfPresent,
recordNativeCaptureDiagnostics,
@@ -31,7 +31,6 @@ import {
} from "./diagnostics";
import { emitRecordingInterrupted } from "./events";
import { getFinalMacCompanionAudioPath } from "./macCompanionAudio";
-import { pruneAutoRecordings } from "./prune";
export function waitForNativeCaptureStart(process: ChildProcessWithoutNullStreams) {
return new Promise<void>((resolve, reject) => {
@@ -270,9 +269,6 @@ export async function finalizeStoredVideo(videoPath: string) {
} catch (error) {
console.warn("[mac-stop] Failed to persist cursor telemetry:", error);
}
- if (isAutoRecordingPath(videoPath)) {
- await pruneAutoRecordings([videoPath]);
- }
if (
lastNativeCaptureDiagnostics?.backend === "mac-screencapturekit" ||
diff --git a/electron/ipc/recording/prune.test.ts b/electron/ipc/recording/prune.test.ts
deleted file mode 100644
index 8c1c6683..00000000
--- a/electron/ipc/recording/prune.test.ts
+++ /dev/null
@@ -1,130 +0,0 @@
-import fs from "node:fs/promises";
-import os from "node:os";
-import path from "node:path";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-describe("pruneAutoRecordings", () => {
- let tempRoot: string;
- let appDataPath: string;
- let userDataPath: string;
- let tempPath: string;
- let appPath: string;
-
- beforeEach(async () => {
- tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), "recordly-prune-"));
- appDataPath = path.join(tempRoot, "AppData");
- userDataPath = path.join(tempRoot, "UserData");
- tempPath = path.join(tempRoot, "Temp");
- appPath = path.join(tempRoot, "App");
-
- await Promise.all(
- [appDataPath, userDataPath, tempPath, appPath].map((dirPath) =>
- fs.mkdir(dirPath, { recursive: true }),
- ),
- );
-
- vi.resetModules();
- vi.doMock("electron", () => ({
- app: {
- isPackaged: false,
- getAppPath: () => appPath,
- getPath: (name: string) => {
- if (name === "appData") return appDataPath;
- if (name === "userData") return userDataPath;
- if (name === "temp") return tempPath;
- return tempRoot;
- },
- setPath: () => undefined,
- },
- }));
- });
-
- afterEach(async () => {
- vi.resetModules();
- vi.doUnmock("electron");
- if (tempRoot) {
- await fs.rm(tempRoot, { recursive: true, force: true });
- }
- });
-
- it("preserves recordings referenced by saved projects in the Projects directory", async () => {
- const { getRecordingsDir } = await import("../utils");
- const { PROJECTS_DIRECTORY_NAME, PROJECT_FILE_EXTENSION } = await import("../constants");
- const { pruneAutoRecordings } = await import("./prune");
-
- const recordingsDir = await getRecordingsDir();
- const projectsDir = path.join(recordingsDir, PROJECTS_DIRECTORY_NAME);
- await fs.mkdir(projectsDir, { recursive: true });
-
- const recordingPaths: string[] = [];
- for (let index = 0; index < 23; index += 1) {
- const recordingPath = path.join(recordingsDir, `recording-${index}.mp4`);
- recordingPaths.push(recordingPath);
- await fs.writeFile(recordingPath, `video-${index}`);
- const timestamp = new Date(Date.now() - index * 60_000);
- await fs.utimes(recordingPath, timestamp, timestamp);
- }
-
- const protectedVideoRecordingPath = recordingPaths.at(-3);
- const protectedWebcamRecordingPath = recordingPaths.at(-2);
- const prunableRecordingPath = recordingPaths.at(-1);
-
- await fs.writeFile(
- path.join(projectsDir, `saved-project-video.${PROJECT_FILE_EXTENSION}`),
- JSON.stringify(
- {
- videoPath: protectedVideoRecordingPath,
- },
- null,
- 2,
- ),
- "utf-8",
- );
-
- await fs.writeFile(
- path.join(projectsDir, `saved-project-webcam.${PROJECT_FILE_EXTENSION}`),
- JSON.stringify(
- {
- editor: {
- webcam: {
- sourcePath: protectedWebcamRecordingPath,
- },
- },
- },
- null,
- 2,
- ),
- "utf-8",
- );
-
- await pruneAutoRecordings();
-
- await expect(fs.access(protectedVideoRecordingPath!)).resolves.toBeUndefined();
- await expect(fs.access(protectedWebcamRecordingPath!)).resolves.toBeUndefined();
- await expect(fs.access(prunableRecordingPath!)).rejects.toThrow();
- });
-
- it("aborts pruning when a saved project cannot be parsed", async () => {
- const { getRecordingsDir } = await import("../utils");
- const { PROJECTS_DIRECTORY_NAME, PROJECT_FILE_EXTENSION } = await import("../constants");
- const { pruneAutoRecordings } = await import("./prune");
-
- const recordingsDir = await getRecordingsDir();
- const projectsDir = path.join(recordingsDir, PROJECTS_DIRECTORY_NAME);
- await fs.mkdir(projectsDir, { recursive: true });
-
- const recordingPath = path.join(recordingsDir, "recording-stale.mp4");
- await fs.writeFile(recordingPath, "video");
- const staleTimestamp = new Date(Date.now() - 48 * 60 * 60 * 1_000);
- await fs.utimes(recordingPath, staleTimestamp, staleTimestamp);
-
- await fs.writeFile(
- path.join(projectsDir, `broken-project.${PROJECT_FILE_EXTENSION}`),
- "{ invalid json",
- "utf-8",
- );
-
- await expect(pruneAutoRecordings()).rejects.toThrow();
- await expect(fs.access(recordingPath)).resolves.toBeUndefined();
- });
-});
diff --git a/electron/ipc/recording/prune.ts b/electron/ipc/recording/prune.ts
deleted file mode 100644
index 29787e8e..00000000
--- a/electron/ipc/recording/prune.ts
+++ /dev/null
@@ -1,190 +0,0 @@
-import fs from "node:fs/promises";
-import path from "node:path";
-import {
- AUTO_RECORDING_MAX_AGE_MS,
- AUTO_RECORDING_RETENTION_COUNT,
- COMPANION_AUDIO_LAYOUTS,
- LEGACY_PROJECT_FILE_EXTENSIONS,
- PROJECT_FILE_EXTENSION,
- PROJECTS_DIRECTORY_NAME,
-} from "../constants";
-import { currentVideoPath } from "../state";
-import {
- getRecordingsDir,
- getTelemetryPathForVideo,
- isAutoRecordingPath,
- normalizePath,
- normalizeVideoSourcePath,
- parseJsonWithByteOrderMark,
-} from "../utils";
-
-export async function hasSiblingProjectFile(videoPath: string) {
- const baseName = path.basename(videoPath, path.extname(videoPath));
- const candidateExtensions = [PROJECT_FILE_EXTENSION, ...LEGACY_PROJECT_FILE_EXTENSIONS];
-
- for (const extension of candidateExtensions) {
- const projectPath = path.join(path.dirname(videoPath), `${baseName}.${extension}`);
-
- try {
- await fs.access(projectPath);
- return true;
- } catch {
- continue;
- }
- }
-
- return false;
-}
-
-export { isAutoRecordingPath };
-
-async function loadSavedProjectMediaPaths() {
- const recordingsDir = await getRecordingsDir();
- const projectsDir = path.join(recordingsDir, PROJECTS_DIRECTORY_NAME);
- const protectedPaths = new Set<string>();
- const candidateExtensions = new Set([
- PROJECT_FILE_EXTENSION,
- ...LEGACY_PROJECT_FILE_EXTENSIONS,
- ]);
-
- let projectEntries: Array<{ isFile(): boolean; name: string }>;
- try {
- projectEntries = await fs.readdir(projectsDir, { withFileTypes: true });
- } catch (error) {
- const code =
- typeof error === "object" && error !== null && "code" in error ? error.code : undefined;
- if (code === "ENOENT") {
- return protectedPaths;
- }
-
- throw error;
- }
-
- await Promise.all(
- projectEntries
- .filter((entry) => {
- if (!entry.isFile()) {
- return false;
- }
-
- const extension = path.extname(entry.name).replace(/^\./, "").toLowerCase();
- return candidateExtensions.has(extension);
- })
- .map(async (entry) => {
- const projectPath = path.join(projectsDir, entry.name);
- let rawProject: {
- videoPath?: unknown;
- editor?: { webcam?: { sourcePath?: unknown } };
- };
- try {
- rawProject = parseJsonWithByteOrderMark<{
- videoPath?: unknown;
- editor?: { webcam?: { sourcePath?: unknown } };
- }>(await fs.readFile(projectPath, "utf-8"));
- } catch (error) {
- console.warn(
- "[prune] Aborting recording prune because a saved project is unreadable",
- {
- projectPath,
- error,
- },
- );
- throw error;
- }
- const candidatePaths = [
- rawProject.videoPath,
- rawProject.editor?.webcam?.sourcePath,
- ];
-
- for (const candidatePath of candidatePaths) {
- if (typeof candidatePath !== "string" || candidatePath.trim().length === 0) {
- continue;
- }
-
- const normalizedCandidatePath = normalizePath(
- normalizeVideoSourcePath(candidatePath) ?? candidatePath,
- );
- protectedPaths.add(normalizedCandidatePath);
- try {
- protectedPaths.add(await fs.realpath(normalizedCandidatePath));
- } catch {
- // Ignore missing project media; project loading already surfaces that error.
- }
- }
- }),
- );
-
- return protectedPaths;
-}
-
-export async function pruneAutoRecordings(exemptPaths: string[] = []) {
- const recordingsDir = await getRecordingsDir();
- await fs.mkdir(recordingsDir, { recursive: true });
- const protectedProjectMediaPaths = await loadSavedProjectMediaPaths();
- const exempt = new Set(
- [currentVideoPath, ...exemptPaths]
- .filter((value): value is string => Boolean(value))
- .map((value) => normalizePath(value)),
- );
-
- const entries = await fs.readdir(recordingsDir, { withFileTypes: true });
- const autoRecordingStats = await Promise.all(
- entries
- .filter((entry) => entry.isFile() && /^recording-.*\.(mp4|mov|webm)$/i.test(entry.name))
- .map(async (entry) => {
- const filePath = path.join(recordingsDir, entry.name);
- const stats = await fs.stat(filePath);
- return { filePath, stats };
- }),
- );
-
- const sorted = autoRecordingStats.sort(
- (left, right) => right.stats.mtimeMs - left.stats.mtimeMs,
- );
- const now = Date.now();
-
- for (const [index, entry] of sorted.entries()) {
- const normalizedFilePath = normalizePath(entry.filePath);
- if (exempt.has(normalizedFilePath)) {
- continue;
- }
-
- if (await hasSiblingProjectFile(entry.filePath)) {
- continue;
- }
-
- const resolvedFilePath = await fs.realpath(entry.filePath).catch(() => normalizedFilePath);
- if (
- protectedProjectMediaPaths.has(normalizedFilePath) ||
- protectedProjectMediaPaths.has(resolvedFilePath)
- ) {
- continue;
- }
-
- const tooOld = now - entry.stats.mtimeMs > AUTO_RECORDING_MAX_AGE_MS;
- const overLimit = index >= AUTO_RECORDING_RETENTION_COUNT;
- if (!tooOld && !overLimit) {
- continue;
- }
-
- try {
- await fs.rm(entry.filePath, { force: true });
- await fs.rm(getTelemetryPathForVideo(entry.filePath), { force: true });
- // Clean up companion audio files left from recording (macOS .m4a, Windows .wav)
- const base = entry.filePath.replace(/\.(mp4|mov|webm)$/i, "");
- const companionSuffixes = Array.from(
- new Set(
- COMPANION_AUDIO_LAYOUTS.flatMap((layout) => [
- layout.systemSuffix,
- layout.micSuffix,
- ]),
- ),
- );
- for (const suffix of companionSuffixes) {
- await fs.rm(base + suffix, { force: true }).catch(() => undefined);
- }
- } catch (error) {
- console.warn("Failed to prune old auto recording:", entry.filePath, error);
- }
- }
-}
diff --git a/electron/ipc/recording/sequenceSource.ts b/electron/ipc/recording/sequenceSource.ts
new file mode 100644
index 00000000..45abfee3
--- /dev/null
+++ b/electron/ipc/recording/sequenceSource.ts
@@ -0,0 +1,9 @@
+import path from "node:path";
+
+/** Sources generated by Videos imports have independent, lossless audio companions. */
+export function isLibrarySequenceSource(file: string): boolean {
+ return (
+ path.basename(path.dirname(file)) === ".recordly-media" &&
+ /^[0-9a-f-]{36}\.mp4$/.test(path.basename(file))
+ );
+}
diff --git a/electron/ipc/recording/sequenceWebcam.ts b/electron/ipc/recording/sequenceWebcam.ts
new file mode 100644
index 00000000..81bb1835
--- /dev/null
+++ b/electron/ipc/recording/sequenceWebcam.ts
@@ -0,0 +1,131 @@
+import fs from "node:fs/promises";
+import path from "node:path";
+import { execFile } from "node:child_process";
+import { promisify } from "node:util";
+import { getFfmpegBinaryPath } from "../ffmpeg/binary";
+import { probeNativeVideoMetadata } from "../ffmpeg/metadata";
+import { resolveRecordingSession, persistRecordingSessionManifest } from "../project/session";
+import { rememberApprovedLocalReadPath, resolveApprovedLocalMediaPath } from "../project/manager";
+import type { RecordingWebcamSource } from "../../../src/types/recordingLibrary";
+
+const run = promisify(execFile);
+type Range = { startMs: number; endMs: number };
+const rangesPath = (video: string) => `${video}.webcam-ranges.json`;
+export const sequenceWebcamOutputs = (video: string) => [
+ video.replace(/\.mp4$/, "-webcam.mp4"),
+ video.replace(/\.mp4$/, ".recordly-session.json"),
+ rangesPath(video),
+];
+async function linked(video: string): Promise<RecordingWebcamSource | undefined> {
+ const session = await resolveRecordingSession(video);
+ if (!session?.webcamPath) return undefined;
+ const webcamPath = await fs.realpath(session.webcamPath);
+ if (path.dirname(webcamPath) !== path.dirname(video))
+ throw new Error("Linked webcam is outside the recording folder");
+ let visibleRanges: Range[] | undefined;
+ try {
+ visibleRanges = JSON.parse(await fs.readFile(rangesPath(video), "utf8"));
+ } catch {
+ /* Original recordings have no range file. */
+ }
+ return { sourcePath: webcamPath, timeOffsetMs: session.timeOffsetMs ?? 0, visibleRanges };
+}
+async function ffmpeg(args: string[]) {
+ await run(
+ getFfmpegBinaryPath(),
+ ["-hide_banner", "-loglevel", "error", "-nostdin", "-y", ...args],
+ { timeout: 60 * 60 * 1000, maxBuffer: 1024 * 1024 },
+ );
+}
+
+/** Keep webcam media separate from the screen, including blank spans for screen-only clips. */
+export async function composeSequenceWebcam(
+ current: string,
+ added: string,
+ output: string,
+ work: string,
+ baseDurationMs: number,
+ addedDurationMs: number,
+ currentWebcam?: RecordingWebcamSource,
+) {
+ const base = currentWebcam === undefined ? await linked(current) : currentWebcam;
+ if (currentWebcam?.sourcePath) {
+ const approved = await resolveApprovedLocalMediaPath(currentWebcam.sourcePath);
+ if (!approved) throw new Error("Current webcam is no longer available");
+ base!.sourcePath = approved;
+ }
+ const next = await linked(added);
+ const firstPath = base?.sourcePath || next?.sourcePath;
+ if (!firstPath) return undefined;
+ const meta = await probeNativeVideoMetadata(getFfmpegBinaryPath(), firstPath);
+ const width = Math.ceil(meta.width / 2) * 2;
+ const height = Math.ceil(meta.height / 2) * 2;
+ const ranges: Range[] = [];
+ for (const [index, source, durationMs, offsetMs] of [
+ [0, base, baseDurationMs, 0],
+ [1, next, addedDurationMs, baseDurationMs],
+ ] as const) {
+ const duration = durationMs / 1000;
+ const args: string[] = [];
+ let filter = `scale=${width}:${height}:force_original_aspect_ratio=decrease,pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2,setsar=1,fps=30,format=yuv420p`;
+ if (source?.sourcePath) {
+ const info = await probeNativeVideoMetadata(getFfmpegBinaryPath(), source.sourcePath);
+ const delayMs = Number.isFinite(source.timeOffsetMs) ? source.timeOffsetMs : 0;
+ args.push("-i", source.sourcePath);
+ filter = `trim=start=${Math.max(0, -delayMs) / 1000},setpts=PTS-STARTPTS,${filter},tpad=start_mode=add:start_duration=${Math.max(0, delayMs) / 1000}:stop_mode=add:stop_duration=${duration},trim=duration=${duration}`;
+ const active = source.visibleRanges ?? [
+ {
+ startMs: Math.max(0, delayMs),
+ endMs: Math.min(durationMs, info.duration * 1000 + delayMs),
+ },
+ ];
+ for (const range of active) {
+ if (!Number.isFinite(range.startMs) || !Number.isFinite(range.endMs)) continue;
+ const startMs = Math.max(0, range.startMs);
+ const endMs = Math.min(durationMs, range.endMs);
+ if (endMs > startMs)
+ ranges.push({ startMs: offsetMs + startMs, endMs: offsetMs + endMs });
+ }
+ } else {
+ args.push("-f", "lavfi", "-i", `color=c=black:s=${width}x${height}:r=30:d=${duration}`);
+ }
+ await ffmpeg([
+ ...args,
+ "-an",
+ "-vf",
+ filter,
+ "-t",
+ String(duration),
+ "-c:v",
+ "libx264",
+ "-preset",
+ "fast",
+ "-crf",
+ "18",
+ path.join(work, `webcam-${index}.mp4`),
+ ]);
+ }
+ await fs.writeFile(
+ path.join(work, "webcam-list.txt"),
+ "file 'webcam-0.mp4'\nfile 'webcam-1.mp4'\n",
+ );
+ const webcamPath = sequenceWebcamOutputs(output)[0];
+ await ffmpeg([
+ "-f",
+ "concat",
+ "-safe",
+ "1",
+ "-i",
+ path.join(work, "webcam-list.txt"),
+ "-an",
+ "-c:v",
+ "copy",
+ "-movflags",
+ "+faststart",
+ webcamPath,
+ ]);
+ await persistRecordingSessionManifest({ videoPath: output, webcamPath, timeOffsetMs: 0 });
+ await fs.writeFile(rangesPath(output), JSON.stringify(ranges));
+ await rememberApprovedLocalReadPath(webcamPath);
+ return { sourcePath: webcamPath, timeOffsetMs: 0, visibleRanges: ranges };
+}
diff --git a/electron/ipc/recording/thumbnail.ts b/electron/ipc/recording/thumbnail.ts
new file mode 100644
index 00000000..5397b3b3
--- /dev/null
+++ b/electron/ipc/recording/thumbnail.ts
@@ -0,0 +1,76 @@
+import { createHash } from "node:crypto";
+import { execFile } from "node:child_process";
+import fs from "node:fs/promises";
+import path from "node:path";
+import { promisify } from "node:util";
+import { app } from "electron";
+import { getFfmpegBinaryPath } from "../ffmpeg/binary";
+import { resolveApprovedLocalMediaPath } from "../project/manager";
+import { getRecordingsDir } from "../utils";
+
+const run = promisify(execFile);
+const pending = new Map<string, Promise<string>>();
+let queue = Promise.resolve();
+
+/** Decode one small still, never a video player per library row. */
+export async function getRecordingThumbnail(candidate: string): Promise<string> {
+ const root = await fs.realpath(await getRecordingsDir());
+ const file = await resolveApprovedLocalMediaPath(candidate);
+ if (!file || path.dirname(file) !== root || !/\.(mp4|mov|webm|mkv|m4v)$/i.test(file))
+ throw new Error("Recording is outside the Videos library");
+ const stat = await fs.stat(file);
+ if (!stat.isFile()) throw new Error("Recording is not a file");
+ const key = createHash("sha256").update(`${file}:${stat.mtimeMs}:${stat.size}`).digest("hex");
+ const existing = pending.get(key);
+ if (existing) return existing;
+ const cache = path.join(app.getPath("userData"), "recording-thumbnails", `${key}.jpg`);
+ const task = queue.then(async () => {
+ let jpeg: Buffer;
+ try {
+ jpeg = await fs.readFile(cache);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
+ const result = await run(
+ getFfmpegBinaryPath(),
+ [
+ "-hide_banner",
+ "-loglevel",
+ "error",
+ "-nostdin",
+ "-threads",
+ "1",
+ "-i",
+ file,
+ "-frames:v",
+ "1",
+ "-an",
+ "-vf",
+ "scale=160:90:force_original_aspect_ratio=increase,crop=160:90",
+ "-q:v",
+ "5",
+ "-f",
+ "image2pipe",
+ "-c:v",
+ "mjpeg",
+ "pipe:1",
+ ],
+ { encoding: "buffer", maxBuffer: 512 * 1024, timeout: 15000, windowsHide: true },
+ );
+ jpeg = result.stdout;
+ if (!jpeg.length) throw new Error("Recording has no preview frame");
+ await fs.mkdir(path.dirname(cache), { recursive: true });
+ await fs.writeFile(cache, jpeg);
+ }
+ return `data:image/jpeg;base64,${jpeg.toString("base64")}`;
+ });
+ pending.set(key, task);
+ queue = task.then(
+ () => undefined,
+ () => undefined,
+ );
+ try {
+ return await task;
+ } finally {
+ pending.delete(key);
+ }
+}
diff --git a/src/types/recordingLibrary.ts b/src/types/recordingLibrary.ts
new file mode 100644
index 00000000..5d8f48e0
--- /dev/null
+++ b/src/types/recordingLibrary.ts
@@ -0,0 +1,22 @@
+export interface RecordingWebcamSource {
+ sourcePath: string | null;
+ timeOffsetMs: number;
+ visibleRanges?: { startMs: number; endMs: number }[];
+}
+export interface RecordingLibraryEntry {
+ path: string;
+ name: string;
+ createdAt: number;
+ bytes: number;
+ url: string;
+}
+export interface RecordingImportResult {
+ path: string;
+ url: string;
+ sourceStartMs: number;
+ durationMs: number;
+ totalDurationMs: number;
+ webcam?: RecordingWebcamSource;
+}
+export type LibraryResult<T> = { success: true; value: T } | { success: false; error: string };
+export const RECORDING_DRAG_TYPE = "application/x-recordly-recording";