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.

19.8 KB
Raw Blame
/**
 * What can be recorded on each OS, from the tools that are already there:
 * ffmpeg itself everywhere, plus xrandr/xdpyinfo/xwininfo on Linux when
 * installed and PowerShell on Windows. Parsers are pure and unit tested.
 */
import { encodePowerShell, windowsScreensScript } from "./scripts.js";
import { currentPlatform, ffmpegPath, findExecutable, realRunner, type Runner } from "./proc.js";
import { xEnv } from "./xauth.js";
import type { CaptureSource, Platform } from "./types.js";
import type { Rect } from "./ffmpegArgs.js";

export interface ScreenInfo extends Rect {
  name: string;
  primary?: boolean;
  /**
   * Where the OS itself listed this screen, before `primaryFirst` reordered
   * the list. A backend addressed by index rather than by geometry -- ffmpeg's
   * `ddagrab=output_idx=N` -- needs this, not the position in Clipy's
   * `display:N` order. Absent when the screen did not come from an
   * enumeration that has one.
   */
  deviceIndex?: number;
}

// ---------------------------------------------------------------------------
// Linux
// ---------------------------------------------------------------------------

/**
 * `xrandr --listmonitors` (or `--listactivemonitors`):
 * ` 0: +*eDP-1 1920/344x1080/194+0+0  eDP-1`. `*` marks the primary.
 */
export function parseXrandrMonitors(text: string): ScreenInfo[] {
  const out: ScreenInfo[] = [];
  for (const line of text.split("\n")) {
    const m = /^\s*(\d+):\s+([+*]*)(\S+)\s+(\d+)\/\d+x(\d+)\/\d+([+-]\d+)([+-]\d+)/.exec(line);
    if (!m) continue;
    out.push({
      name: m[3],
      primary: m[2].includes("*"),
      width: Number(m[4]),
      height: Number(m[5]),
      x: Number(m[6]),
      y: Number(m[7]),
    });
  }
  return out;
}

/** `xdpyinfo`: `  dimensions:    1280x720 pixels (339x191 millimeters)`. */
export function parseXdpyinfoSize(text: string): { width: number; height: number } | null {
  const m = /dimensions:\s+(\d+)x(\d+)\s+pixels/.exec(text);
  return m ? { width: Number(m[1]), height: Number(m[2]) } : null;
}

/** The X screen size from ffmpeg's own probe of the display, so a display
 *  can be recorded without any X11 utilities installed. */
export function parseProbedScreenSize(ffmpegStderr: string): { width: number; height: number } | null {
  const m = /Video: [^\n]*?(\d{2,5})x(\d{2,5})/.exec(ffmpegStderr);
  return m ? { width: Number(m[1]), height: Number(m[2]) } : null;
}

/** `xprop -root _NET_CLIENT_LIST`: the managed top-level windows. */
export function parseClientList(text: string): number[] {
  const m = /_NET_CLIENT_LIST\(WINDOW\): window id # (.*)/.exec(text);
  if (!m) return [];
  return m[1]
    .split(",")
    .map((s) => s.trim())
    .filter((s) => /^0x[0-9a-f]+$/i.test(s))
    .map((s) => parseInt(s, 16));
}

/** `xwininfo -id <id>`: absolute geometry and whether it is on screen. */
export function parseWindowGeometry(text: string): (Rect & { viewable: boolean }) | null {
  // xwininfo prints the window title on its header line, so read each field
  // only from a line that holds nothing but that field. A page titled
  // "Width: 12" must not be taken for the window's size.
  const lines = text.split(/\r?\n/).map((line) => line.trim());
  const num = (label: string) => {
    const re = new RegExp(`^${label}:\\s+(-?\\d+)$`);
    let value: number | null = null;
    for (const line of lines) {
      const m = re.exec(line);
      if (m) value = Number(m[1]);
    }
    return value;
  };
  const x = num("Absolute upper-left X");
  const y = num("Absolute upper-left Y");
  const width = num("Width");
  const height = num("Height");
  if (x === null || y === null || width === null || height === null) return null;
  const viewable = lines.some((line) => /^Map State:\s+IsViewable$/.test(line));
  return { x, y, width, height, viewable };
}

const XPROP_ESCAPES: Readonly<Record<string, number>> = { n: 0x0a, t: 0x09, r: 0x0d, b: 0x08, f: 0x0c, v: 0x0b, a: 0x07 };
const utf8 = new TextDecoder("utf-8", { fatal: true });
const textBytes = new TextEncoder();

/**
 * A string as xprop prints it between quotes, decoded. xprop puts a
 * backslash before `"` and `\`, writes control characters as C escapes
 * (`\n`, `\t`), and writes every other byte it will not print as three octal
 * digits. Outside a UTF-8 locale (LANG unset, as in Docker, CI and systemd
 * services) that is every byte of a non-ASCII character: `café` comes out as
 * `caf\303\251`. The bytes are put back together and read as UTF-8, or as
 * Latin-1 (the encoding of a STRING property) when they are not valid UTF-8.
 */
export function decodeXpropString(value: string): string {
  const bytes: number[] = [];
  const chars = [...value];
  for (let i = 0; i < chars.length; i++) {
    const ch = chars[i];
    if (ch === "\\" && i + 1 < chars.length) {
      const octal = /^[0-3][0-7]{2}/.exec(chars.slice(i + 1, i + 4).join(""));
      if (octal) {
        bytes.push(parseInt(octal[0], 8));
        i += 3;
        continue;
      }
      const next = chars[++i];
      const control = XPROP_ESCAPES[next];
      if (control !== undefined) bytes.push(control);
      else bytes.push(...textBytes.encode(next));
      continue;
    }
    bytes.push(...textBytes.encode(ch));
  }
  const buf = Uint8Array.from(bytes);
  try {
    return utf8.decode(buf);
  } catch {
    return Buffer.from(buf).toString("latin1");
  }
}

/** `xprop -id <id> _NET_WM_NAME WM_NAME WM_CLASS`: title and owning app. */
export function parseWindowProps(text: string): { title: string; app: string } {
  const quoted = (re: RegExp) => {
    const m = re.exec(text);
    return m ? decodeXpropString(m[1]) : "";
  };
  // Anchored: an unanchored WM_NAME also matches inside _NET_WM_NAME and re-reads an empty one.
  const title = quoted(/^_NET_WM_NAME\([^)]*\) = "((?:[^"\\]|\\.)*)"/m) || quoted(/^WM_NAME\([^)]*\) = "((?:[^"\\]|\\.)*)"/m);
  const cls = /WM_CLASS\([^)]*\) = "((?:[^"\\]|\\.)*)", "((?:[^"\\]|\\.)*)"/.exec(text);
  return { title, app: cls ? decodeXpropString(cls[2]) : "" };
}

/** The X display's monitors, or the whole screen as one display. */
export async function linuxScreens(xDisplay: string, run: Runner = realRunner, env: NodeJS.ProcessEnv = process.env): Promise<ScreenInfo[]> {
  const xenv = xEnv(env, xDisplay);
  const monitors = await run("xrandr", ["--listmonitors"], xenv);
  const screens = monitors.status === 0 ? parseXrandrMonitors(monitors.stdout) : [];
  if (screens.length > 0) return primaryFirst(screens);
  let size: { width: number; height: number } | null = null;
  const dpy = await run("xdpyinfo", [], xenv);
  if (dpy.status === 0) size = parseXdpyinfoSize(dpy.stdout);
  if (!size) {
    const ffmpeg = ffmpegPath("linux", env);
    if (ffmpeg) {
      const probe = await run(ffmpeg, ["-hide_banner", "-f", "x11grab", "-i", xDisplay, "-frames:v", "1", "-f", "null", "-"], xenv);
      size = parseProbedScreenSize(probe.stderr);
    }
  }
  return size ? [{ name: `screen ${xDisplay}`, x: 0, y: 0, primary: true, ...size }] : [];
}

async function linuxWindows(xDisplay: string, run: Runner, env: NodeJS.ProcessEnv): Promise<CaptureSource[]> {
  const xenv = xEnv(env, xDisplay);
  const list = await run("xprop", ["-root", "_NET_CLIENT_LIST"], xenv);
  if (list.status !== 0) return [];
  const out: CaptureSource[] = [];
  for (const id of parseClientList(list.stdout)) {
    const hex = `0x${id.toString(16)}`;
    const info = await run("xwininfo", ["-id", hex], xenv);
    const g = info.status === 0 ? parseWindowGeometry(info.stdout) : null;
    if (!g || !g.viewable || g.width < 32 || g.height < 32) continue;
    const props = parseWindowProps((await run("xprop", ["-id", hex, "_NET_WM_NAME", "WM_NAME", "WM_CLASS"], xenv)).stdout);
    if (!props.title && !props.app) continue;
    const name = props.app && props.title ? `${props.app}: ${props.title}` : props.title || props.app;
    out.push({ id: `window:${hex}`, kind: "window", name, width: g.width, height: g.height });
  }
  return out;
}

/** Monitor source names from `pactl list short sources`. */
export function parsePactlMonitors(text: string): string[] {
  const out: string[] = [];
  for (const line of text.split(/\r?\n/)) {
    const trimmed = line.trim();
    if (!trimmed) continue;
    const name = trimmed.split(/\s+/)[1];
    if (name && name.endsWith(".monitor")) out.push(name);
  }
  return out;
}

/**
 * The `.monitor` source name for the default PulseAudio / PipeWire sink, or null
 * when `pactl` is unavailable or no default sink is configured.
 */
export async function defaultSinkMonitor(run: Runner = realRunner, env: NodeJS.ProcessEnv = process.env): Promise<string | null> {
  const direct = await run("pactl", ["get-default-sink"], env);
  const sinkFromDirect = direct.status === 0 ? direct.stdout.trim() : "";
  if (sinkFromDirect) {
    return sinkFromDirect.endsWith(".monitor") ? sinkFromDirect : `${sinkFromDirect}.monitor`;
  }
  // PulseAudio < 14 has no `get-default-sink` subcommand; fall back to `pactl info`.
  const info = await run("pactl", ["info"], env);
  if (info.status !== 0) return null;
  const m = /^Default Sink:[ \t]*(.+)$/m.exec(info.stdout);
  const sinkFromInfo = m ? m[1].trim() : "";
  if (!sinkFromInfo) return null;
  return sinkFromInfo.endsWith(".monitor") ? sinkFromInfo : `${sinkFromInfo}.monitor`;
}

/** PulseAudio / PipeWire monitor sources for recording system audio on Linux. */
export async function listSystemAudioSources(run: Runner = realRunner, env: NodeJS.ProcessEnv = process.env): Promise<string[]> {
  const r = await run("pactl", ["list", "short", "sources"], env);
  return r.status === 0 ? parsePactlMonitors(r.stdout) : [];
}

// ---------------------------------------------------------------------------
// macOS
// ---------------------------------------------------------------------------

export interface AvfoundationDevices {
  video: { index: number; name: string }[];
  audio: { index: number; name: string }[];
}

/** `ffmpeg -f avfoundation -list_devices true -i ""` (stderr). */
export function parseAvfoundationDevices(text: string): AvfoundationDevices {
  const out: AvfoundationDevices = { video: [], audio: [] };
  let section: "video" | "audio" | null = null;
  for (const line of text.split("\n")) {
    if (/AVFoundation video devices/i.test(line)) section = "video";
    else if (/AVFoundation audio devices/i.test(line)) section = "audio";
    else if (section) {
      const m = /\]\s*\[(\d+)\]\s+(.+?)\s*$/.exec(line);
      if (m) out[section].push({ index: Number(m[1]), name: m[2] });
    }
  }
  return out;
}

/** The "Capture screen N" devices, in screen order. */
export function avfoundationScreens(devices: AvfoundationDevices): { index: number; name: string; screen: number }[] {
  return devices.video
    .map((d) => ({ ...d, m: /^Capture screen (\d+)$/i.exec(d.name) }))
    .filter((d) => d.m)
    .map((d) => ({ index: d.index, name: d.name, screen: Number(d.m![1]) }))
    .sort((a, b) => a.screen - b.screen);
}

/**
 * The avfoundation audio device for `startCapture({ microphone })`, as the
 * index string ffmpeg takes. In order: an exact name, a listed device index
 * ("1" is the device at index 1, even when an earlier name contains "1"),
 * then part of a name. A number ffmpeg did not list is passed through as-is.
 */
export function pickAvfoundationMicrophone(microphone: string, audio: AvfoundationDevices["audio"] | undefined): string {
  const want = microphone.toLowerCase();
  const devices = audio ?? [];
  const isIndex = /^\d+$/.test(microphone);
  const match =
    devices.find((d) => d.name.toLowerCase() === want) ??
    (isIndex ? devices.find((d) => d.index === Number(microphone)) : undefined) ??
    devices.find((d) => d.name.toLowerCase().includes(want));
  if (match) return String(match.index);
  if (isIndex) return microphone;
  const names = devices.map((d) => `"${d.name}"`).join(", ") || "none listed";
  throw new Error(`no microphone named "${microphone}" (available: ${names})`);
}

export async function listAvfoundation(run: Runner = realRunner, env: NodeJS.ProcessEnv = process.env): Promise<AvfoundationDevices | null> {
  const ffmpeg = ffmpegPath("darwin", env);
  if (!ffmpeg) return null;
  const r = await run(ffmpeg, ["-hide_banner", "-f", "avfoundation", "-list_devices", "true", "-i", ""], env);
  if (r.status === null) return null;
  return parseAvfoundationDevices(r.stderr + r.stdout);
}

// ---------------------------------------------------------------------------
// Windows
// ---------------------------------------------------------------------------

/** `ffmpeg -f dshow -list_devices true -i dummy` (stderr), old and new formats. */
export function parseDshowAudioDevices(text: string): string[] {
  const out: string[] = [];
  let legacyAudio = false;
  for (const line of text.split(/\r?\n/)) {
    // Strip the `[dshow @ ...]` prefix once so words inside a quoted device name
    // are never mistaken for DirectShow headers or "Alternative name" aliases.
    const prefix = /^\s*\[[^\]]+\]\s+(.*)$/.exec(line);
    if (!prefix) continue;
    const body = prefix[1];
    if (/^DirectShow audio devices\b/i.test(body)) {
      legacyAudio = true;
      continue;
    }
    if (/^DirectShow video devices\b/i.test(body)) {
      legacyAudio = false;
      continue;
    }
    if (/^Alternative name\b/i.test(body)) continue;
    const tagged = /^"(.+)"\s+\(([^()]+)\)\s*$/.exec(body);
    if (tagged) {
      const types = tagged[2].split(",").map((t) => t.trim().toLowerCase());
      if (types.includes("audio")) out.push(tagged[1]);
      continue;
    }
    const legacy = /^"(.+)"\s*$/.exec(body);
    if (legacy && legacyAudio) out.push(legacy[1]);
  }
  return out;
}

/** The `S <json>` line PowerShell prints for Screen.AllScreens. */
export function parseScreensLine(text: string): ScreenInfo[] {
  for (const line of text.split(/\r?\n/)) {
    if (!line.startsWith("S ")) continue;
    try {
      const raw: unknown = JSON.parse(line.slice(2));
      const list = Array.isArray(raw) ? raw : [raw];
      return list
        .filter((s): s is Record<string, unknown> => !!s && typeof s === "object")
        .map((s, i) => ({
          name: typeof s.name === "string" && s.name ? s.name : `Display ${i + 1}`,
          primary: s.primary === true,
          deviceIndex: i,
          x: Number(s.x) || 0,
          y: Number(s.y) || 0,
          width: Number(s.width) || 0,
          height: Number(s.height) || 0,
        }))
        .filter((s) => s.width > 0 && s.height > 0);
    } catch {
      return [];
    }
  }
  return [];
}

export async function windowsScreens(run: Runner = realRunner, env: NodeJS.ProcessEnv = process.env): Promise<ScreenInfo[]> {
  const powershell = findExecutable("powershell.exe", "win32", env) ?? findExecutable("pwsh.exe", "win32", env) ?? "powershell.exe";
  const r = await run(powershell, ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encodePowerShell(windowsScreensScript())], env);
  return r.status === 0 ? primaryFirst(parseScreensLine(r.stdout)) : [];
}

/** The main display first, so display:0 is always the main one. */
export function primaryFirst(screens: ScreenInfo[]): ScreenInfo[] {
  const i = screens.findIndex((s) => s.primary);
  return i > 0 ? [screens[i], ...screens.filter((_, j) => j !== i)] : screens;
}

/**
 * The index the OS gave the screen at `position` of a `primaryFirst` list.
 *
 * `display:N` counts the main display first, so a position in that list is
 * not the number the OS knows the screen by, and a backend selected by index
 * (`ddagrab=output_idx=N`) would otherwise capture a different monitor than
 * the one asked for. Falls back to `position` when the screens carry no
 * enumeration index.
 */
export function deviceIndexFor(screens: ScreenInfo[], position: number): number {
  return screens[position]?.deviceIndex ?? position;
}

export async function listDshowAudio(run: Runner = realRunner, env: NodeJS.ProcessEnv = process.env): Promise<string[]> {
  const ffmpeg = ffmpegPath("win32", env);
  if (!ffmpeg) return [];
  const r = await run(ffmpeg, ["-hide_banner", "-f", "dshow", "-list_devices", "true", "-i", "dummy"], env);
  return parseDshowAudioDevices(r.stderr + r.stdout);
}

// ---------------------------------------------------------------------------
// Microphones
// ---------------------------------------------------------------------------

/**
 * `pactl list short sources`: `0\talsa_input.pci-0000_00_1f.3.analog-stereo\tmodule-alsa-card.c\ts16le 2ch 44100Hz\tSUSPENDED`.
 * `.monitor` sources are the sound an output is playing, not a microphone.
 */
export function parsePactlSources(text: string): string[] {
  const out: string[] = [];
  for (const line of text.split(/\r?\n/)) {
    const name = line.split("\t")[1]?.trim();
    if (!name || name.endsWith(".monitor") || out.includes(name)) continue;
    out.push(name);
  }
  return out;
}

/**
 * Names that `startCapture({ microphone })` accepts: avfoundation audio
 * devices on macOS, dshow audio devices on Windows, PulseAudio sources on
 * Linux (or ALSA's `default` when PulseAudio cannot be asked).
 */
export async function listMicrophones(platform: Platform = currentPlatform(), opts: Omit<ListOptions, "xDisplay"> = {}): Promise<string[]> {
  const run = opts.run ?? realRunner;
  const env = opts.env ?? process.env;
  if (platform === "linux") {
    const r = await run("pactl", ["list", "short", "sources"], env);
    const names = r.status === 0 ? parsePactlSources(r.stdout) : [];
    return names.length > 0 ? names : ["default"];
  }
  if (platform === "darwin") {
    const devices = await listAvfoundation(run, env);
    return unique(devices?.audio.map((d) => d.name) ?? []);
  }
  return unique(await listDshowAudio(run, env));
}

function unique(names: string[]): string[] {
  return [...new Set(names)];
}

// ---------------------------------------------------------------------------
// Source ids
// ---------------------------------------------------------------------------

export type ParsedSource = { kind: "display"; index: number } | { kind: "window"; id: number };

/** "display:0" / "0" / "window:0x1a00003". Prefixes and hex digits are read in any case. */
export function parseSourceId(id: string | undefined): ParsedSource {
  if (id === undefined || id === "" || id === "main") return { kind: "display", index: 0 };
  const display = /^(?:display:)?(\d+)$/i.exec(id);
  if (display) return { kind: "display", index: Number(display[1]) };
  const window = /^window:(0x[0-9a-f]+|\d+)$/i.exec(id);
  if (window) return { kind: "window", id: window[1].startsWith("0x") || window[1].startsWith("0X") ? parseInt(window[1], 16) : Number(window[1]) };
  throw new Error(`unknown capture source "${id}" (expected display:N or window:0x...)`);
}

export interface ListOptions {
  /** Linux: the X display to list. Default $DISPLAY. */
  xDisplay?: string;
  /** For tests. */
  run?: Runner;
  env?: NodeJS.ProcessEnv;
}

export async function listSources(platform: Platform = currentPlatform(), opts: ListOptions = {}): Promise<CaptureSource[]> {
  const run = opts.run ?? realRunner;
  const env = opts.env ?? process.env;
  if (platform === "linux") {
    const xDisplay = opts.xDisplay ?? env.DISPLAY;
    if (!xDisplay) return [];
    const screens = await linuxScreens(xDisplay, run, env);
    const displays: CaptureSource[] = screens.map((s, i) => ({
      id: `display:${i}`,
      kind: "display",
      name: s.primary && screens.length > 1 ? `${s.name} (main)` : s.name,
      width: s.width,
      height: s.height,
    }));
    return [...displays, ...(await linuxWindows(xDisplay, run, env))];
  }
  if (platform === "darwin") {
    const devices = await listAvfoundation(run, env);
    if (!devices) return [];
    return avfoundationScreens(devices).map((d, i) => ({
      id: `display:${i}`,
      kind: "display",
      name: i === 0 ? `${d.name} (main)` : d.name,
    }));
  }
  const screens = await windowsScreens(run, env);
  if (screens.length === 0) return [{ id: "display:0", kind: "display", name: "Display 1 (main)" }];
  return screens.map((s, i) => ({
    id: `display:${i}`,
    kind: "display",
    name: s.primary ? `${s.name} (main)` : s.name,
    width: s.width,
    height: s.height,
  }));
}