Skip to content

armgit / clipy

Public Imported from GitHub
0

The AI-native screen recorder. Record your screen and talk; the people you share it with and your AI agents both get it.

31.9 KB
Raw Blame
/**
 * startCapture: one ffmpeg process recording a display (or, on Linux, a
 * window) into a fragmented MP4, plus the pointer sidecar next to it.
 *
 * Stopping writes "q" to ffmpeg's stdin so the file finalizes; if ffmpeg does
 * not exit, SIGINT and then SIGKILL follow. Because the MP4 is fragmented
 * (moov first, a fragment per keyframe), even a killed ffmpeg leaves a
 * playable file up to its last fragment.
 */
import { spawn, type ChildProcess } from "node:child_process";
import { mkdirSync, mkdtempSync, renameSync, rmSync, statSync, writeFileSync, type Stats } from "node:fs";
import { basename, dirname, join, resolve } from "node:path";
import { isWaylandSession, hasDevice, SCREEN_RECORDING_HINT } from "./check.js";
import { trackChild } from "./children.js";
import { xEnv } from "./xauth.js";
import {
  buildFfmpegArgs,
  checkGain,
  inputThreadQueue,
  parseFfmpegMajorVersion,
  pickH264Encoder,
  supportsAmixNormalize,
  type AudioInput,
  type CapturePlan,
  type H264Encoder,
  type Rect,
  type VideoInput,
} from "./ffmpegArgs.js";
import { currentPlatform, ffmpegPath, ffprobePath, realRunner, sleep, type Runner } from "./proc.js";
import { pointerGapWarning, samplesToEventsInSegments, startPointerSampler, type PointerSampler, type RecordedSegment } from "./sidecar.js";
import {
  avfoundationScreens,
  deviceIndexFor,
  defaultSinkMonitor,
  linuxScreens,
  listAvfoundation,
  listDshowAudio,
  parsePactlMonitors,
  parseSourceId,
  parseWindowGeometry,
  pickAvfoundationMicrophone,
  primaryFirst,
  windowsScreens,
  type ScreenInfo,
} from "./sources.js";
import type { CaptureGeometry, CaptureOptions, CaptureResult, CaptureSession, Platform } from "./types.js";

/** How long ffmpeg may take to open its inputs (a macOS permission prompt counts). */
const START_TIMEOUT_MS = 20_000;
/** After it starts, how long to watch for an immediate failure. */
const SETTLE_MS = 600;

const BANNER = /Press \[q\] to stop/;

/**
 * Patterns ffmpeg prints when macOS has not granted Screen Recording or
 * Microphone. Without the Screen Recording grant, recent macOS lists no
 * "Capture screen" devices at all, so opening one by name fails as "Video
 * device not found".
 */
export function looksLikeMacPermissionError(stderr: string): boolean {
  if (/Video device not found[\s\S]*Capture screen \d/i.test(stderr)) return true;
  return /not (?:been )?(?:authorized|permitted)|Operation not permitted|Failed to create AV capture input device|Could not create (?:video|audio) capture|kTCC|privacy/i.test(stderr);
}

function tail(text: string, lines = 8): string {
  return text.trim().split(/\r?\n/).filter((l) => !/^\s*(?:Input|Output|Stream|Metadata|Duration|encoder|handler_name|vendor_id|major_brand|minor_version|compatible_brands|Side data|cpb:|Press \[q\])/.test(l)).slice(-lines).join("\n");
}

interface Launched {
  child: ChildProcess;
  startedAt: number;
  exited: Promise<{ code: number | null; signal: NodeJS.Signals | null; at: number }>;
  stderr(): string;
}

class StartError extends Error {
  constructor(
    message: string,
    readonly stderr: string,
  ) {
    super(message);
  }
}

/** Spawn ffmpeg and wait until it is recording (or has failed). */
async function launch(ffmpeg: string, plan: CapturePlan, env: NodeJS.ProcessEnv): Promise<Launched> {
  const child = trackChild(spawn(ffmpeg, buildFfmpegArgs(plan), { env, stdio: ["pipe", "ignore", "pipe"], windowsHide: true }));
  let stderr = "";
  let bannerAt: number | null = null;
  let onBanner: () => void = () => {};
  const banner = new Promise<void>((r) => {
    onBanner = r;
  });
  child.stderr!.on("data", (chunk: Buffer) => {
    stderr += chunk.toString("utf8");
    if (stderr.length > 32_768) stderr = stderr.slice(-16_384);
    if (bannerAt === null && BANNER.test(stderr)) {
      bannerAt = Date.now();
      onBanner();
    }
  });
  const exited = new Promise<{ code: number | null; signal: NodeJS.Signals | null; at: number }>((r) => {
    child.on("exit", (code, signal) => r({ code, signal, at: Date.now() }));
    child.on("error", () => r({ code: null, signal: null, at: Date.now() }));
  });
  // ffmpeg reads "q" from stdin; a broken pipe after it exits is harmless.
  child.stdin!.on("error", () => {});

  // A cleared timer, not sleep(): a pending 20 s sleep would keep the process
  // alive that long after a short recording has finished.
  let startTimer: NodeJS.Timeout | undefined;
  const timeout = new Promise<"timeout">((r) => {
    startTimer = setTimeout(() => r("timeout"), START_TIMEOUT_MS);
  });
  const first = await Promise.race([banner.then(() => "banner" as const), exited.then(() => "exit" as const), timeout]);
  clearTimeout(startTimer);
  if (first === "exit") throw new StartError("ffmpeg stopped before recording started", stderr);
  if (first === "timeout") {
    child.kill("SIGKILL");
    throw new StartError(`ffmpeg did not start recording within ${START_TIMEOUT_MS / 1000} s`, stderr);
  }
  const earlyExit = await Promise.race([exited, sleep(SETTLE_MS).then(() => undefined)]);
  // A duration-limited recording can finish successfully during the startup check.
  if (earlyExit && (earlyExit.code !== 0 || plan.maxSeconds === undefined)) {
    throw new StartError("ffmpeg stopped right after it started", stderr);
  }
  return { child, startedAt: bannerAt ?? Date.now(), exited, stderr: () => stderr };
}

/** Ask ffmpeg to finish its file ("q"), then insist. */
async function stopFfmpeg(l: Launched, graceMs = 5000): Promise<void> {
  if (l.child.exitCode !== null || l.child.signalCode !== null) return;
  try {
    l.child.stdin!.write("q");
    l.child.stdin!.end();
  } catch {
    // stdin already closed
  }
  const int = setTimeout(() => l.child.kill("SIGINT"), graceMs);
  const kill = setTimeout(() => l.child.kill("SIGKILL"), graceMs * 2);
  await l.exited;
  clearTimeout(int);
  clearTimeout(kill);
}

export interface ProbeInfo {
  durationMs: number | null;
  width: number | null;
  height: number | null;
  codec: string | null;
}

export function parseProbeJson(json: string): ProbeInfo {
  try {
    const data = JSON.parse(json) as { format?: { duration?: string }; streams?: { codec_type?: string; codec_name?: string; width?: number; height?: number }[] };
    const video = data.streams?.find((s) => s.codec_type === "video");
    const duration = data.format?.duration;
    const seconds = duration != null && String(duration).trim() !== "" ? Number(duration) : NaN;
    const milliseconds = Math.round(seconds * 1000);
    return {
      durationMs: seconds >= 0 && Number.isSafeInteger(milliseconds) ? milliseconds : null,
      width: video?.width ?? null,
      height: video?.height ?? null,
      codec: video?.codec_name ?? null,
    };
  } catch {
    return { durationMs: null, width: null, height: null, codec: null };
  }
}

export async function probe(path: string, run: Runner = realRunner, env: NodeJS.ProcessEnv = process.env): Promise<ProbeInfo | null> {
  const ffprobe = ffprobePath(currentPlatform(), env);
  if (!ffprobe) return null;
  // file: keeps a name such as take2:final.mp4 from being read as a protocol.
  const input = `file:${resolve(path)}`;
  const r = await run(ffprobe, ["-v", "error", "-show_entries", "format=duration:stream=codec_type,codec_name,width,height", "-of", "json", input], env);
  return r.status === 0 ? parseProbeJson(r.stdout) : null;
}

interface FfmpegFeatures {
  encoder: H264Encoder | null;
  devices: string;
  amixNormalize: boolean;
  /** Whether this ffmpeg takes `-thread_queue_size` on its inputs (see inputThreadQueue). */
  inputThreadQueue: boolean;
}

const encoderCache = new Map<string, FfmpegFeatures>();

async function ffmpegFeatures(ffmpeg: string, platform: Platform, env: NodeJS.ProcessEnv): Promise<FfmpegFeatures> {
  const cached = encoderCache.get(ffmpeg);
  if (cached) return cached;
  const [encoders, devices, amixHelp, version] = await Promise.all([
    realRunner(ffmpeg, ["-hide_banner", "-encoders"], env),
    realRunner(ffmpeg, ["-hide_banner", "-devices"], env),
    realRunner(ffmpeg, ["-hide_banner", "-h", "filter=amix"], env),
    realRunner(ffmpeg, ["-version"], env),
  ]);
  const features = {
    encoder: pickH264Encoder(encoders.stdout + encoders.stderr, platform),
    devices: devices.stdout + devices.stderr,
    amixNormalize: amixHelp.status === 0 && supportsAmixNormalize(amixHelp.stdout + amixHelp.stderr),
    inputThreadQueue: inputThreadQueue(parseFfmpegMajorVersion(version.stdout + version.stderr)),
  };
  encoderCache.set(ffmpeg, features);
  return features;
}

/**
 * Resolve Linux audio inputs (microphone and/or PulseAudio system monitor).
 * Missing `pactl`, missing sinks, or missing `pulse` input degrade to warnings
 * so the recording still proceeds.
 */
export async function resolveLinuxAudio(
  options: Pick<CaptureOptions, "microphone" | "systemAudio">,
  devices: string,
  run: Runner = realRunner,
  env: NodeJS.ProcessEnv = process.env,
): Promise<{ audio?: AudioInput; systemAudio?: AudioInput; warnings: string[] }> {
  const warnings: string[] = [];
  let audio: AudioInput | undefined;
  if (options.microphone) {
    const device = typeof options.microphone === "string" ? options.microphone : "default";
    if (hasDevice(devices, "pulse")) audio = { backend: "pulse", device };
    else if (hasDevice(devices, "alsa")) audio = { backend: "alsa", device };
    else warnings.push("this ffmpeg has neither pulse nor alsa input; recording without the microphone");
  }

  let systemAudio: AudioInput | undefined;
  if (options.systemAudio) {
    // System audio requires PulseAudio/PipeWire monitor sources; ALSA cannot tap speaker output directly.
    if (!hasDevice(devices, "pulse")) {
      warnings.push("this ffmpeg has no pulse input; recording without system audio");
    } else if (typeof options.systemAudio === "string") {
      const want = options.systemAudio.trim();
      if (!want) {
        warnings.push("system audio monitor name was empty; recording without system audio");
      } else {
        const monitor = want.endsWith(".monitor") ? want : `${want}.monitor`;
        const r = await run("pactl", ["list", "short", "sources"], env);
        if (r.status !== 0) {
          warnings.push(
            r.status === null
              ? "pactl was not found; recording without system audio"
              : "pactl failed to list audio sources; recording without system audio",
          );
        } else if (parsePactlMonitors(r.stdout).includes(monitor)) {
          systemAudio = { backend: "pulse", device: monitor };
        } else {
          warnings.push(`system audio monitor "${monitor}" was not found; recording without system audio`);
        }
      }
    } else {
      const monitor = await defaultSinkMonitor(run, env);
      if (monitor) {
        systemAudio = { backend: "pulse", device: monitor };
      } else {
        warnings.push("could not find the default PulseAudio sink monitor (pactl missing or no default sink); recording without system audio");
      }
    }
  }

  return { audio, systemAudio, warnings };
}

interface Resolved {
  plans: { plan: CapturePlan; label: string }[];
  geometry: Rect | null;
  warnings: string[];
  windowCapture: boolean;
}

async function resolveLinux(options: CaptureOptions, base: Omit<CapturePlan, "video" | "audio">, devices: string, sampler: PointerSampler, env: NodeJS.ProcessEnv): Promise<Resolved> {
  const warnings: string[] = [];
  const xDisplay = options.xDisplay ?? env.DISPLAY;
  if (!xDisplay) {
    throw new Error(
      isWaylandSession(env)
        ? "this is a Wayland session without XWayland (DISPLAY is unset): ffmpeg cannot record it. Log in to an X11 session, enable XWayland, or record a virtual display."
        : "no X display to record: DISPLAY is unset. Pass xDisplay or start a virtual display.",
    );
  }
  if (isWaylandSession(env) && !options.xDisplay) warnings.push("Wayland session: native Wayland windows record as black; only XWayland apps appear.");
  const source = parseSourceId(options.source);
  let video: VideoInput;
  let geometry: Rect | null = null;
  if (source.kind === "window") {
    video = { backend: "x11grab", xDisplay, windowId: source.id };
    const info = await realRunner("xwininfo", ["-id", `0x${source.id.toString(16)}`], xEnv(env, xDisplay));
    const g = info.status === 0 ? parseWindowGeometry(info.stdout) : null;
    if (g) geometry = { x: g.x, y: g.y, width: g.width, height: g.height };
    else warnings.push("window geometry is unknown (install x11-utils for xwininfo), so pointer positions cannot be placed on the video");
  } else {
    const screens = await linuxScreens(xDisplay, realRunner, env);
    if (source.index >= Math.max(1, screens.length)) {
      throw new Error(`display:${source.index} does not exist on ${xDisplay} (${screens.length || 1} display${screens.length === 1 ? "" : "s"})`);
    }
    const screen = screens[source.index];
    // A single display that is the whole X screen records without a crop.
    const whole = screens.length <= 1 && screen && screen.x === 0 && screen.y === 0;
    video = { backend: "x11grab", xDisplay, rect: whole || !screen ? undefined : screen };
    geometry = screen ? { x: screen.x, y: screen.y, width: screen.width, height: screen.height } : null;
    if (!geometry) {
      await sampler.ready;
      const s = sampler.screens()[0];
      if (s) geometry = { x: 0, y: 0, width: s.width, height: s.height };
    }
  }
  const { audio, systemAudio, warnings: audioWarnings } = await resolveLinuxAudio(options, devices, realRunner, env);
  warnings.push(...audioWarnings);
  return { plans: [{ plan: { ...base, video, audio, systemAudio }, label: "x11grab" }], geometry, warnings, windowCapture: source.kind === "window" };
}

async function resolveMac(options: CaptureOptions, base: Omit<CapturePlan, "video" | "audio">, sampler: PointerSampler, env: NodeJS.ProcessEnv): Promise<Resolved> {
  const warnings: string[] = [];
  const source = parseSourceId(options.source);
  if (source.kind === "window") throw new Error("macOS capture records whole displays only; pick a display:N source");
  const devices = await listAvfoundation(realRunner, env);
  const screens = devices ? avfoundationScreens(devices) : [];
  let device: string;
  if (screens.length > 0) {
    const screen = screens[source.index];
    if (!screen) throw new Error(`display:${source.index} does not exist (${screens.length} screen${screens.length === 1 ? "" : "s"})`);
    device = String(screen.index);
  } else {
    device = `Capture screen ${source.index}`;
    warnings.push("ffmpeg listed no screens; trying the screen by name. " + SCREEN_RECORDING_HINT);
  }
  let audio: AudioInput | undefined;
  if (options.microphone) {
    if (typeof options.microphone === "string") {
      audio = { backend: "avfoundation", device: pickAvfoundationMicrophone(options.microphone, devices?.audio) };
    } else {
      audio = { backend: "avfoundation", device: "default" };
    }
  }
  await sampler.ready;
  const s = sampler.screens()[source.index];
  const geometry = s ? { x: s.x, y: s.y, width: s.width, height: s.height } : null;
  return { plans: [{ plan: { ...base, video: { backend: "avfoundation", device }, audio }, label: "avfoundation" }], geometry, warnings, windowCapture: false };
}

/**
 * The Windows plans for `display:N`, the preferred backend first.
 *
 * The two backends are addressed differently, and `screens` is in Clipy's
 * `display:N` order (main display first), which is not the order Windows
 * enumerated them in:
 *
 * - ddagrab names a DXGI output by number, so it needs the number Windows
 *   gave that screen; passing the `display:N` position instead records a
 *   different monitor whenever the main display is not enumerated first.
 * - gdigrab crops the virtual desktop, so it takes the screen's rectangle and
 *   does not care about either order.
 *
 * Pure, so the mapping is unit tested on any OS.
 */
export function windowsPlans(
  base: Omit<CapturePlan, "video" | "audio">,
  screens: ScreenInfo[],
  index: number,
  audio?: AudioInput,
): { plan: CapturePlan; label: string }[] {
  const screen = screens[index] ?? undefined;
  return [
    { plan: { ...base, video: { backend: "ddagrab", outputIndex: deviceIndexFor(screens, index) }, audio }, label: "ddagrab" },
    { plan: { ...base, video: { backend: "gdigrab", rect: screen }, audio }, label: "gdigrab" },
  ];
}

async function resolveWindows(options: CaptureOptions, base: Omit<CapturePlan, "video" | "audio">, devices: string, sampler: PointerSampler, env: NodeJS.ProcessEnv): Promise<Resolved> {
  const warnings: string[] = [];
  const source = parseSourceId(options.source);
  if (source.kind === "window") throw new Error("Windows capture records whole displays only; pick a display:N source");
  await sampler.ready;
  let screens: ScreenInfo[] = primaryFirst(sampler.screens());
  if (screens.length === 0) screens = await windowsScreens(realRunner, env);
  if (screens.length > 0 && !screens[source.index]) {
    throw new Error(`display:${source.index} does not exist (${screens.length} display${screens.length === 1 ? "" : "s"})`);
  }
  const screen = screens[source.index] ?? null;
  let audio: AudioInput | undefined;
  if (options.microphone) {
    if (!hasDevice(devices, "dshow")) {
      warnings.push("this ffmpeg has no dshow input; recording without the microphone");
    } else {
      const names = await listDshowAudio(realRunner, env);
      if (typeof options.microphone === "string") {
        const want = options.microphone.toLowerCase();
        const match = names.find((n) => n.toLowerCase() === want) ?? names.find((n) => n.toLowerCase().includes(want));
        if (!match) throw new Error(`no microphone named "${options.microphone}" (available: ${names.map((n) => `"${n}"`).join(", ") || "none listed"})`);
        audio = { backend: "dshow", device: match };
      } else if (names[0]) {
        audio = { backend: "dshow", device: names[0] };
      } else {
        warnings.push("no microphone was found; recording without it");
      }
    }
  }
  const geometry = screen ? { x: screen.x, y: screen.y, width: screen.width, height: screen.height } : null;
  return { plans: windowsPlans(base, screens, source.index, audio), geometry, warnings, windowCapture: false };
}

function statOrNull(path: string): Stats | null {
  try {
    return statSync(path);
  } catch {
    return null;
  }
}

/**
 * After a capture that never started: remove the output only if this capture
 * wrote it (absent before, or changed since). A file the user already had
 * there and ffmpeg never opened is left alone.
 */
export function removeFailedOutput(path: string, before: Stats | null): void {
  const after = statOrNull(path);
  if (!after) return;
  if (before && after.size === before.size && after.mtimeMs === before.mtimeMs && after.ino === before.ino) return;
  rmSync(path, { force: true });
}

/**
 * The list and all seg-N.mp4 inputs live in the same private directory.
 * Relative names work even if its parent contains ffconcat control characters.
 */
async function concatSegments(ffmpeg: string, paths: readonly string[], outPath: string, listDir: string, env: NodeJS.ProcessEnv): Promise<void> {
  const listPath = join(listDir, "concat.txt");
  const body = paths.map((p) => `file ${basename(p)}`).join("\n");
  writeFileSync(listPath, `${body}\n`, "utf8");
  // A later unreadable input can otherwise produce a short MP4 and exit 0.
  const joined = join(listDir, "joined.tmp.mp4");
  const r = await realRunner(
    ffmpeg,
    ["-hide_banner", "-loglevel", "error", "-nostats", "-xerror", "-y", "-f", "concat", "-i", listPath, "-c", "copy", "-movflags", "+faststart", joined],
    env,
  );
  if (r.status !== 0) throw new Error(`ffmpeg could not join the recording's segments${r.stderr.trim() ? `: ${r.stderr.trim()}` : ""}`);
  if (!statOrNull(joined)?.size) throw new Error("ffmpeg joined the recording's segments but wrote no video");
  renameSync(joined, outPath);
}

export interface StartOptionsInternal {
  env?: NodeJS.ProcessEnv;
}

export async function startCapture(options: CaptureOptions, internal: StartOptionsInternal = {}): Promise<CaptureSession> {
  const platform = currentPlatform();
  const env = internal.env ?? process.env;
  const ffmpeg = ffmpegPath(platform, env);
  if (!ffmpeg) throw new Error("ffmpeg was not found on PATH (run checkCapture for install steps)");
  const fps = options.fps ?? 30;
  if (!Number.isFinite(fps) || fps < 1 || fps > 120) throw new Error(`fps must be between 1 and 120 (got ${fps})`);
  if (options.maxSeconds !== undefined && (!Number.isFinite(options.maxSeconds) || options.maxSeconds <= 0)) {
    throw new Error("maxSeconds must be a finite positive number");
  }
  checkGain("micGain", options.micGain);
  checkGain("systemGain", options.systemGain);
  const outPath = resolve(options.outPath);
  mkdirSync(dirname(outPath), { recursive: true });

  const features = await ffmpegFeatures(ffmpeg, platform, env);
  if (!features.encoder) throw new Error("this ffmpeg has no H.264 encoder (libx264); run checkCapture for install steps");
  const base = {
    fps,
    encoder: features.encoder,
    quality: options.quality,
    amixNormalize: features.amixNormalize,
    micGain: options.micGain,
    systemGain: options.systemGain,
    maxSeconds: options.maxSeconds,
    cursor: options.cursor,
    inputThreadQueue: features.inputThreadQueue,
    output: outPath,
  };

  const xDisplay = options.xDisplay ?? env.DISPLAY;
  const sampler = startPointerSampler(platform, { xDisplay, env });
  let resolved: Resolved;
  try {
    resolved =
      platform === "linux"
        ? await resolveLinux(options, base, features.devices, sampler, env)
        : platform === "darwin"
          ? await resolveMac(options, base, sampler, env)
          : await resolveWindows(options, base, features.devices, sampler, env);
    await sampler.ready;
  } catch (err) {
    await sampler.stop();
    throw err;
  }

  const warnings = [...resolved.warnings];
  const existingOutput = statOrNull(outPath);
  const launchEnv = platform === "linux" ? xEnv(env, xDisplay) : env;
  let launched: Launched | null = null;
  let chosenPlan: CapturePlan | null = null;
  let lastError: StartError | null = null;
  for (const { plan, label } of resolved.plans) {
    try {
      launched = await launch(ffmpeg, plan, launchEnv);
      chosenPlan = plan;
      if (lastError) warnings.push(`${resolved.plans[0].label} could not start, recorded with ${label} instead: ${tail(lastError.stderr, 2)}`);
      break;
    } catch (err) {
      if (!(err instanceof StartError)) {
        try {
          await sampler.stop();
        } catch {
          // Keep the original startup error if pointer cleanup fails.
        }
        throw err;
      }
      lastError = err;
    }
  }
  if (!launched || !chosenPlan) {
    await sampler.stop();
    removeFailedOutput(outPath, existingOutput);
    const detail = tail(lastError?.stderr ?? "");
    const hint = platform === "darwin" && looksLikeMacPermissionError(lastError?.stderr ?? "") ? `\n${SCREEN_RECORDING_HINT}` : "";
    throw new Error(`${lastError?.message ?? "ffmpeg did not start"}${detail ? `:\n${detail}` : ""}${hint}`);
  }

  const resumePlan: CapturePlan = chosenPlan;
  // A capture is one or more recorded segments. Without a pause it is a single
  // segment written straight to outPath; pause() ends the current segment and
  // resume() records the next one into a scratch directory, and stop() joins
  // them. Each segment's file is closed before the next one begins.
  interface Segment {
    path: string;
    startedAt: number;
    endedAt: number;
    exit: { code: number | null; signal: NodeJS.Signals | null; at: number };
    stderr: string;
    videoMs?: number;
  }

  let active: Launched | null = launched;
  let activePath = outPath;
  let paused = false;
  const segments: Segment[] = [];
  let segDir: string | null = null;
  let stopRequestedAt: number | null = null;
  let finished: Promise<CaptureResult> | null = null;
  let aborted: Promise<void> | null = null;

  // `ended` resolves when a recording segment exits on its own (maxSeconds or a
  // failure), not when one is ended for a pause or stop; the WeakSet marks the
  // segments ended deliberately so the watcher ignores their exit.
  let markEnded: () => void = () => {};
  const ended = new Promise<void>((r) => {
    markEnded = r;
  });
  const intentional = new WeakSet<Launched>();
  const watch = (seg: Launched): void =>
    void seg.exited.then(() => {
      if (!intentional.has(seg)) markEnded();
    });
  watch(launched);

  // pause(), resume(), stop() and abort() all mutate the segment state, so they
  // run one at a time through this queue.
  let queue: Promise<unknown> = Promise.resolve();
  const serial = <T>(fn: () => Promise<T>): Promise<T> => {
    const run = queue.then(fn);
    queue = run.then(
      () => undefined,
      () => undefined,
    );
    return run;
  };

  const segmentDir = (): string => (segDir ??= mkdtempSync(join(dirname(outPath), ".clipy-seg-")));

  /** End the active recorder and keep its file as a finished segment. */
  const finalizeActive = async (requestedAt: number): Promise<void> => {
    const seg = active;
    if (!seg) return;
    active = null;
    intentional.add(seg);
    await stopFfmpeg(seg);
    const exit = await seg.exited;
    segments.push({
      path: activePath,
      startedAt: seg.startedAt,
      endedAt: Math.max(seg.startedAt, Math.min(exit.at, requestedAt)),
      exit,
      stderr: seg.stderr(),
    });
  };

  const pauseNow = async (): Promise<void> => {
    if (paused || !active) return;
    await finalizeActive(Date.now());
    // Move the first segment off the output name so resume() and stop() can
    // build the final file there.
    if (segments.length === 1 && segments[0].path === outPath && statOrNull(outPath)) {
      const moved = join(segmentDir(), "seg-0.mp4");
      renameSync(outPath, moved);
      segments[0].path = moved;
    }
    paused = true;
  };

  const resumeNow = async (): Promise<void> => {
    if (!paused) return;
    let maxSeconds = options.maxSeconds;
    if (maxSeconds !== undefined) {
      const recordedSec = segments.reduce((n, s) => n + Math.max(0, s.endedAt - s.startedAt), 0) / 1000;
      maxSeconds = Math.max(0.1, maxSeconds - recordedSec);
    }
    const path = join(segmentDir(), `seg-${segments.length}.mp4`);
    const next = await launch(ffmpeg, { ...resumePlan, output: path, maxSeconds }, launchEnv);
    active = next;
    activePath = path;
    paused = false;
    watch(next);
  };

  const finish = async (): Promise<CaptureResult> => {
    if (stopRequestedAt === null) stopRequestedAt = Date.now();
    // True when a segment is still recording at stop(); false if we are paused.
    const wasRecording = active !== null;
    if (active) await finalizeActive(stopRequestedAt);
    markEnded();
    const { samples, warnings: sidecarWarnings } = await sampler.stop();
    warnings.push(...sidecarWarnings);
    let recoveryDir: string | null = null;
    try {
      const noVideo = () => {
        const stderr = segments.at(-1)?.stderr ?? "";
        return new Error(`ffmpeg wrote no video${tail(stderr) ? `:\n${tail(stderr)}` : ""}`);
      };
      const kept = segments.filter((s) => (statOrNull(s.path)?.size ?? 0) > 0);
      if (kept.length === 0) throw noVideo();
      recoveryDir = segDir;

      // Each segment's real video length places the next one on the timeline.
      const infos = await Promise.all(kept.map((s) => probe(s.path, realRunner, env)));
      kept.forEach((s, i) => {
        const d = infos[i]?.durationMs;
        if (d != null) s.videoMs = d;
      });
      if (kept.length === 1) {
        if (kept[0].path !== outPath) renameSync(kept[0].path, outPath);
      } else {
        await concatSegments(ffmpeg, kept.map((s) => s.path), outPath, segmentDir(), env);
      }
      if ((statOrNull(outPath)?.size ?? 0) === 0) throw noVideo();
      recoveryDir = null;

      const recordedMs = kept.reduce((n, s) => n + Math.max(0, s.endedAt - s.startedAt), 0);
      // Only the segment that was recording at stop() can have ended early or
      // crashed; a segment ended by pause() stopped on purpose.
      const recording = wasRecording ? segments[segments.length - 1] : undefined;
      const live = recording && kept.includes(recording) ? recording : undefined;
      if (live) {
        const selfStopped = live.exit.at < stopRequestedAt;
        if (selfStopped) {
          const hitLimit = options.maxSeconds !== undefined && recordedMs >= options.maxSeconds * 1000 - 1500 && live.exit.code === 0;
          if (!hitLimit) {
            warnings.push(
              resolved.windowCapture
                ? "the window changed size or closed, so the recording stopped early"
                : `ffmpeg stopped early (exit ${live.exit.code ?? live.exit.signal}): ${tail(live.stderr, 3)}`,
            );
          }
        } else if (live.exit.code !== 0 && live.exit.code !== 255) {
          warnings.push(`ffmpeg exited with ${live.exit.code ?? live.exit.signal}; the file was kept up to its last complete fragment`);
        }
      }

      const info = await probe(outPath, realRunner, env);
      let durationMs = info?.durationMs ?? null;
      if (durationMs === null) {
        durationMs = kept.reduce((n, s) => n + Math.max(0, s.videoMs ?? s.endedAt - s.startedAt), 0);
        warnings.push("ffprobe was unavailable; the duration comes from the wall clock");
      }
      const timeline: RecordedSegment[] = kept.map((s) => ({ startedAt: s.startedAt, endedAt: s.endedAt, videoMs: s.videoMs }));
      const interactions = samplesToEventsInSegments(samples, timeline, durationMs);
      // Measured against when the last segment stopped: samples are not taken while paused.
      const pointerGap = pointerGapWarning(samples, kept[kept.length - 1].endedAt);
      if (pointerGap) warnings.push(pointerGap);
      let geometry: CaptureGeometry | null = resolved.geometry ? { ...resolved.geometry } : null;
      if (!geometry && platform !== "darwin" && info?.width && info.height) {
        geometry = { x: 0, y: 0, width: info.width, height: info.height };
      }
      if (geometry && info?.width && info.height) {
        geometry.output_width = info.width;
        geometry.output_height = info.height;
      }
      return { path: outPath, durationMs, interactions, geometry, warnings };
    } catch (cause) {
      if (!recoveryDir) throw cause;
      const detail = cause instanceof Error ? cause.message : String(cause);
      throw new Error(`${detail}\nRecording segments were kept in ${recoveryDir}`, { cause });
    } finally {
      if (segDir && !recoveryDir) rmSync(segDir, { recursive: true, force: true });
    }
  };

  return {
    startedAt: launched.startedAt,
    ended,
    pause() {
      if (aborted) return aborted.then(() => Promise.reject(new Error("the capture was aborted")));
      if (finished) return Promise.reject(new Error("the capture has already stopped"));
      return serial(pauseNow);
    },
    resume() {
      if (aborted) return aborted.then(() => Promise.reject(new Error("the capture was aborted")));
      if (finished) return Promise.reject(new Error("the capture has already stopped"));
      return serial(resumeNow);
    },
    // Both are idempotent: a second stop() returns the first one's result,
    // a second abort() waits for the first. stop() after abort() rejects
    // (there is no file any more); abort() after stop() leaves the finished
    // file alone and only waits for stop() to settle.
    stop() {
      if (aborted) return aborted.then(() => Promise.reject(new Error("the capture was aborted")));
      finished ??= serial(finish);
      return finished;
    },
    abort() {
      if (finished) return finished.then(() => undefined, () => undefined);
      aborted ??= serial(async () => {
        if (stopRequestedAt === null) stopRequestedAt = Date.now();
        if (active) {
          const seg = active;
          active = null;
          intentional.add(seg);
          if (seg.child.exitCode === null && seg.child.signalCode === null) {
            seg.child.kill("SIGKILL");
            await seg.exited;
          }
        }
        markEnded();
        await sampler.stop();
        rmSync(outPath, { force: true });
        for (const s of segments) rmSync(s.path, { force: true });
        if (segDir) rmSync(segDir, { recursive: true, force: true });
      });
      return aborted;
    },
  };
}