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.

11.9 KB
Raw Blame
/**
 * ffmpeg argument building, one backend per OS. Pure functions, so every
 * platform's command line is unit tested on any machine.
 */
import type { Platform, CaptureOptions } from "./types.js";

export type Backend = "x11grab" | "avfoundation" | "ddagrab" | "gdigrab";

/** H.264 encoders in order of preference per platform. */
export type H264Encoder = "libx264" | "h264_videotoolbox" | "h264_mf";

export interface Rect {
  x: number;
  y: number;
  width: number;
  height: number;
}

export type VideoInput =
  /** Linux. `rect` absent: the whole X screen. */
  | { backend: "x11grab"; xDisplay: string; rect?: Rect; windowId?: number }
  /** macOS. `device` is the avfoundation video index or name ("Capture screen 0"). */
  | { backend: "avfoundation"; device: string }
  /** Windows. DXGI output index. */
  | { backend: "ddagrab"; outputIndex: number }
  /** Windows fallback. `rect` absent: the whole virtual desktop. */
  | { backend: "gdigrab"; rect?: Rect };

export type AudioInput =
  | { backend: "pulse"; device: string }
  | { backend: "alsa"; device: string }
  /** macOS: the audio half of the avfoundation input, an index, a name or "default". */
  | { backend: "avfoundation"; device: string }
  | { backend: "dshow"; device: string };

export interface CapturePlan {
  video: VideoInput;
  audio?: AudioInput;
  /** Second audio input (e.g. a PulseAudio `.monitor` source) mixed with `audio`. */
  systemAudio?: AudioInput;
  /** Gain multiplier applied to `audio` when mixing two inputs (default 1). */
  micGain?: number;
  /** Gain multiplier applied to `systemAudio` when mixing two inputs (default 1). */
  systemGain?: number;
  /** Whether `amix` supports `normalize=0` (ffmpeg >= 4.4, default true). */
  amixNormalize?: boolean;
  fps: number;
  encoder: H264Encoder;
  quality?: CaptureOptions["quality"];
  maxSeconds?: number;
  /** Draw the cursor in the captured video. Default: true. */
  cursor?: boolean;
  /**
   * Give each input a larger packet queue (`-thread_queue_size` before `-i`).
   * Only FFmpeg 6 and older read it there: 7.0 made it a no-op on inputs and
   * 9.1 refuses to start with it. Default: false. See inputThreadQueue.
   */
  inputThreadQueue?: boolean;
  output: string;
}

/**
 * The major version from `ffmpeg -version`: "ffmpeg version 6.1.1-3ubuntu5",
 * "ffmpeg version n7.1" (Arch) or "ffmpeg version 9.1-full_build-www.gyan.dev".
 * null for a build that names no release, such as a git snapshot
 * ("N-118000-g…", "2026-11-20-git-…").
 */
export function parseFfmpegMajorVersion(versionText: string): number | null {
  const m = /^ffmpeg version n?(\d+)\.\d+/m.exec(versionText);
  return m ? Number(m[1]) : null;
}

/**
 * Whether inputs get `-thread_queue_size`. Only for FFmpeg 6 and older, where
 * a live device can outrun the default queue of 8 packets. FFmpeg 7.0 ignores
 * it on inputs, 9.1 exits with "cannot be applied to input url", and a build
 * with no release number is a recent snapshot, so it is left out for those.
 */
export function inputThreadQueue(ffmpegMajor: number | null): boolean {
  return ffmpegMajor !== null && ffmpegMajor < 7;
}

/** `-thread_queue_size` for an input, or nothing (see CapturePlan.inputThreadQueue). */
function queue(enabled: boolean | undefined): string[] {
  return enabled ? ["-thread_queue_size", "1024"] : [];
}

/** Whether `ffmpeg -h filter=amix` advertises the `normalize` option (ffmpeg 4.4+). */
export function supportsAmixNormalize(amixHelpText: string): boolean {
  return /^\s*normalize\b/m.test(amixHelpText);
}

/**
 * Filtergraph that mixes input 1 (`audio`) and input 2 (`systemAudio`).
 *
 * - `aresample=async=1:first_pts=0` absorbs clock drift between two independent PulseAudio inputs.
 * - `aformat=sample_rates=48000:channel_layouts=stereo` ensures both branches match before mixing.
 * - `amix` divides every input by N by default, halving the volume; `normalize=0` (ffmpeg >= 4.4)
 *   keeps the original levels, and older builds fall back to plain `amix` followed by `volume=2`.
 */
/** A gain is a plain multiplier: above 0 (0 would be silence) and at most 10 (more only clips). */
export function checkGain(name: string, gain: number | undefined): void {
  if (gain === undefined) return;
  if (!Number.isFinite(gain) || gain <= 0 || gain > 10) throw new Error(`${name} must be a number above 0 and at most 10 (got ${gain})`);
}

export function audioMixFilter(supportsNormalize: boolean, micGain = 1, systemGain = 1): string {
  const branch = (index: number, label: string, gain: number) => {
    const vol = gain !== 1 ? `,volume=${gain}` : "";
    return `[${index}:a]aresample=async=1:first_pts=0,aformat=sample_rates=48000:channel_layouts=stereo${vol}[${label}]`;
  };
  const mix = supportsNormalize
    ? "amix=inputs=2:duration=longest:normalize=0:dropout_transition=0"
    : "amix=inputs=2:duration=longest:dropout_transition=0,volume=2";
  return `${branch(1, "mic", micGain)};${branch(2, "sys", systemGain)};[mic][sys]${mix}[aout]`;
}

/** H.264 and yuv420p both need even dimensions. */
export function even(n: number): number {
  return Math.max(2, Math.floor(n / 2) * 2);
}

/** Pick the H.264 encoder from `ffmpeg -encoders` output. */
export function pickH264Encoder(encodersText: string, platform: Platform): H264Encoder | null {
  if (/^\s*V\S*\s+libx264\s/m.test(encodersText)) return "libx264";
  if (platform === "darwin" && /^\s*V\S*\s+h264_videotoolbox\s/m.test(encodersText)) return "h264_videotoolbox";
  if (platform === "win32" && /^\s*V\S*\s+h264_mf\s/m.test(encodersText)) return "h264_mf";
  return null;
}

function videoInputArgs(v: VideoInput, fps: number, cursor = true, threadQueue = false): string[] {
  const drawCursor = cursor ? "1" : "0";
  switch (v.backend) {
    case "x11grab": {
      const args = [...queue(threadQueue), "-f", "x11grab", "-draw_mouse", drawCursor, "-framerate", String(fps)];
      if (v.windowId !== undefined) {
        args.push("-window_id", `0x${v.windowId.toString(16)}`);
      } else if (v.rect) {
        args.push(
          "-video_size",
          `${even(v.rect.width)}x${even(v.rect.height)}`,
          "-grab_x",
          String(Math.max(0, v.rect.x)),
          "-grab_y",
          String(Math.max(0, v.rect.y)),
        );
      }
      args.push("-i", v.xDisplay);
      return args;
    }
    case "avfoundation":
      // The audio half of the device string is filled in by buildFfmpegArgs.
      return [
        ...queue(threadQueue),
        "-f",
        "avfoundation",
        "-capture_cursor",
        drawCursor,
        "-capture_mouse_clicks",
        drawCursor,
        "-framerate",
        String(fps),
      ];
    case "ddagrab":
      return [...queue(threadQueue), "-f", "lavfi", "-i", `ddagrab=output_idx=${v.outputIndex}:framerate=${fps}:draw_mouse=${drawCursor}`];
    case "gdigrab": {
      const args = [...queue(threadQueue), "-f", "gdigrab", "-draw_mouse", drawCursor, "-framerate", String(fps)];
      if (v.rect) {
        args.push(
          "-offset_x",
          String(v.rect.x),
          "-offset_y",
          String(v.rect.y),
          "-video_size",
          `${even(v.rect.width)}x${even(v.rect.height)}`,
        );
      }
      args.push("-i", "desktop");
      return args;
    }
  }
}

function audioInputArgs(a: AudioInput, threadQueue = false): string[] {
  switch (a.backend) {
    case "pulse":
      return [...queue(threadQueue), "-f", "pulse", "-i", a.device];
    case "alsa":
      return [...queue(threadQueue), "-f", "alsa", "-i", a.device];
    case "dshow":
      return [...queue(threadQueue), "-f", "dshow", "-i", `audio=${a.device}`];
    case "avfoundation":
      return [];
  }
}

function encoderArgs(encoder: H264Encoder, fps: number, quality: CaptureOptions["quality"] = "balanced"): string[] {
  // A keyframe every two seconds: each MP4 fragment starts on one, so a crash
  // loses at most the last couple of seconds.
  const gop = ["-g", String(Math.max(1, Math.round(fps * 2)))];

  const crf = { small: "28", balanced: "23", high: "18" };
  const bitrate = { small: "4M", balanced: "8M", high: "16M" };

  switch (encoder) {
    case "libx264":
      return ["-c:v", "libx264", "-preset", "veryfast", "-crf", crf[quality], "-pix_fmt", "yuv420p", ...gop];
    case "h264_videotoolbox":
      return ["-c:v", "h264_videotoolbox", "-realtime", "1", "-b:v", bitrate[quality], "-pix_fmt", "yuv420p", ...gop];
    case "h264_mf":
      return ["-c:v", "h264_mf", "-b:v", bitrate[quality], "-pix_fmt", "yuv420p", ...gop];
  }
}

/** Frames to yuv420p at even sizes; ddagrab frames live on the GPU first. */
export function videoFilter(backend: Backend): string {
  const common = "scale=trunc(iw/2)*2:trunc(ih/2)*2,format=yuv420p";
  return backend === "ddagrab" ? `hwdownload,format=bgra,${common}` : common;
}

/**
 * The full ffmpeg command line for one capture. Output is a fragmented MP4
 * (moov first, a fragment per keyframe): playable even if ffmpeg is killed.
 */
export function buildFfmpegArgs(plan: CapturePlan): string[] {
  const args = ["-hide_banner", "-loglevel", "info", "-nostats", "-y"];
  const video = videoInputArgs(plan.video, plan.fps, plan.cursor, plan.inputThreadQueue);
  let videoMap = "0:v:0";
  let audioMap: string | null = null;
  let filterComplex: string | null = null;
  if (plan.video.backend === "avfoundation") {
    if (plan.systemAudio) throw new Error("systemAudio is not supported with the avfoundation video backend");
    args.push(...video);
    const audio = plan.audio?.backend === "avfoundation" ? plan.audio.device : "none";
    args.push("-i", `${plan.video.device}:${audio}`);
    if (plan.audio?.backend === "avfoundation") audioMap = "0:a:0";
  } else if (plan.audio?.backend === "dshow" && !plan.systemAudio) {
    // ffmpeg opens its inputs in order and starts recording once every one is
    // open. A DirectShow microphone can take seconds to open, and a screen
    // grabber opened before it puts those seconds at the start of the video,
    // so the video would run behind the pointer events, which are timed from
    // the start of recording. Opened last, the screen starts with the take.
    args.push(...audioInputArgs(plan.audio, plan.inputThreadQueue), ...video);
    videoMap = "1:v:0";
    audioMap = "0:a:0";
  } else if (plan.audio && plan.systemAudio) {
    if (plan.audio.backend === "avfoundation" || plan.systemAudio.backend === "avfoundation") {
      throw new Error("avfoundation audio needs the avfoundation video backend");
    }
    args.push(...video);
    args.push(...audioInputArgs(plan.audio, plan.inputThreadQueue));
    args.push(...audioInputArgs(plan.systemAudio, plan.inputThreadQueue));
    filterComplex = audioMixFilter(plan.amixNormalize ?? true, plan.micGain ?? 1, plan.systemGain ?? 1);
    audioMap = "[aout]";
  } else {
    args.push(...video);
    const singleAudio = plan.audio ?? plan.systemAudio;
    if (singleAudio) {
      if (singleAudio.backend === "avfoundation") throw new Error("avfoundation audio needs the avfoundation video backend");
      args.push(...audioInputArgs(singleAudio, plan.inputThreadQueue));
      audioMap = "1:a:0";
    }
  }
  if (filterComplex) args.push("-filter_complex", filterComplex);
  args.push("-map", videoMap);
  if (audioMap) args.push("-map", audioMap);
  args.push("-vf", videoFilter(plan.video.backend));
  args.push(...encoderArgs(plan.encoder, plan.fps, plan.quality));
  // Pin the output rate. Without it ffmpeg keeps whatever rate it detects at
  // start-up, so one pause/resume session can end up with segments at different
  // rates and time bases, which the stream-copy join cannot concatenate (#845).
  args.push("-r", String(plan.fps));
  if (audioMap) args.push("-c:a", "aac", "-b:a", "128k", "-ac", "2");
  if (plan.maxSeconds !== undefined && plan.maxSeconds > 0) args.push("-t", String(plan.maxSeconds));
  // A still screen compresses to almost nothing, so without flushing the
  // header and fragments can sit in ffmpeg's output buffer for many seconds
  // and a crash would leave a file with no moov.
  args.push("-flush_packets", "1", "-movflags", "+frag_keyframe+empty_moov+default_base_moof", "-f", "mp4", plan.output);
  return args;
}