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.

22.6 KB
Raw Blame
import { spawnSync } from "node:child_process";
import { describe, expect, it } from "vitest";
import {
  audioMixFilter,
  buildFfmpegArgs,
  checkGain,
  even,
  inputThreadQueue,
  parseFfmpegMajorVersion,
  pickH264Encoder,
  supportsAmixNormalize,
  videoFilter,
  type CapturePlan,
} from "../src/ffmpegArgs.js";
import { ffmpegPath } from "../src/proc.js";
import { windowsPlans } from "../src/capture.js";
import { parseScreensLine, primaryFirst } from "../src/sources.js";

const base = { fps: 30, encoder: "libx264" as const, output: "/tmp/out.mp4" };

/** The value after a flag, for readable assertions. */
function after(args: string[], flag: string, from = 0): string | undefined {
  const i = args.indexOf(flag, from);
  return i >= 0 ? args[i + 1] : undefined;
}

describe("buildFfmpegArgs", () => {
  it("records a whole X screen with x11grab", () => {
    const args = buildFfmpegArgs({ ...base, video: { backend: "x11grab", xDisplay: ":99" } });
    expect(args).toEqual([
      "-hide_banner", "-loglevel", "info", "-nostats", "-y",
      "-f", "x11grab", "-draw_mouse", "1", "-framerate", "30", "-i", ":99",
      "-map", "0:v:0",
      "-vf", "scale=trunc(iw/2)*2:trunc(ih/2)*2,format=yuv420p",
      "-c:v", "libx264", "-preset", "veryfast", "-crf", "23", "-pix_fmt", "yuv420p", "-g", "60",
      "-r", "30",
      "-flush_packets", "1", "-movflags", "+frag_keyframe+empty_moov+default_base_moof", "-f", "mp4", "/tmp/out.mp4",
    ]);
  });

  it("pins the output frame rate so pause/resume segments share one time base", () => {
    const args = buildFfmpegArgs({ ...base, fps: 24, video: { backend: "x11grab", xDisplay: ":99" } });
    expect(after(args, "-r")).toBe("24");
    expect(args.indexOf("-r")).toBeGreaterThan(args.indexOf("-g"));
    expect(args.indexOf("-r")).toBeLessThan(args.indexOf("-flush_packets"));
  });

  it("crops one monitor of an X screen, at even sizes", () => {
    const args = buildFfmpegArgs({ ...base, video: { backend: "x11grab", xDisplay: ":0", rect: { x: 1920, y: 0, width: 1281, height: 1025 } } });
    expect(after(args, "-video_size")).toBe("1280x1024");
    expect(after(args, "-grab_x")).toBe("1920");
    expect(after(args, "-grab_y")).toBe("0");
    expect(after(args, "-i")).toBe(":0");
  });

  it("records one X window by id", () => {
    const args = buildFfmpegArgs({ ...base, video: { backend: "x11grab", xDisplay: ":0", windowId: 0x1a00003 } });
    expect(after(args, "-window_id")).toBe("0x1a00003");
    expect(args).not.toContain("-video_size");
  });

  it("adds a PulseAudio or ALSA microphone as a second input", () => {
    const pulse = buildFfmpegArgs({ ...base, video: { backend: "x11grab", xDisplay: ":0" }, audio: { backend: "pulse", device: "default" } });
    expect(pulse.join(" ")).toContain("-f pulse -i default");
    expect(pulse.join(" ")).toContain("-map 0:v:0 -map 1:a:0");
    expect(after(pulse, "-c:a")).toBe("aac");
    const alsa = buildFfmpegArgs({ ...base, video: { backend: "x11grab", xDisplay: ":0" }, audio: { backend: "alsa", device: "hw:1" } });
    expect(alsa.join(" ")).toContain("-f alsa -i hw:1");
  });

  it("records Linux system audio alone with the same single-audio shape", () => {
    const args = buildFfmpegArgs({
      ...base,
      video: { backend: "x11grab", xDisplay: ":0" },
      systemAudio: { backend: "pulse", device: "alsa_output.pci.analog-stereo.monitor" },
    });
    expect(args.filter((a) => a === "-i")).toHaveLength(2);
    expect(args.join(" ")).toContain("-f pulse -i alsa_output.pci.analog-stereo.monitor");
    expect(args.join(" ")).toContain("-map 0:v:0 -map 1:a:0");
    expect(args).not.toContain("-filter_complex");
    expect(after(args, "-c:a")).toBe("aac");
  });

  it("mixes Linux microphone and system audio with filter_complex", () => {
    const args = buildFfmpegArgs({
      ...base,
      video: { backend: "x11grab", xDisplay: ":0" },
      audio: { backend: "pulse", device: "default" },
      systemAudio: { backend: "pulse", device: "alsa_output.pci.analog-stereo.monitor" },
    });
    expect(args.filter((a) => a === "-i")).toHaveLength(3);
    const i1 = args.indexOf("-i");
    const i2 = args.indexOf("-i", i1 + 1);
    const i3 = args.indexOf("-i", i2 + 1);
    expect(args[i1 + 1]).toBe(":0");
    expect(args.slice(i1 + 2, i2 + 2)).toEqual(["-f", "pulse", "-i", "default"]);
    expect(args.slice(i2 + 2, i3 + 2)).toEqual(["-f", "pulse", "-i", "alsa_output.pci.analog-stereo.monitor"]);

    expect(after(args, "-filter_complex")).toBe(
      "[1:a]aresample=async=1:first_pts=0,aformat=sample_rates=48000:channel_layouts=stereo[mic];" +
        "[2:a]aresample=async=1:first_pts=0,aformat=sample_rates=48000:channel_layouts=stereo[sys];" +
        "[mic][sys]amix=inputs=2:duration=longest:normalize=0:dropout_transition=0[aout]",
    );
    expect(args.join(" ")).toContain("-map 0:v:0 -map [aout]");
    expect(after(args, "-vf")).toBe(videoFilter("x11grab"));
    expect(after(args, "-c:a")).toBe("aac");
  });

  it("applies micGain and systemGain only when not 1", () => {
    const args = buildFfmpegArgs({
      ...base,
      video: { backend: "x11grab", xDisplay: ":0" },
      audio: { backend: "pulse", device: "default" },
      systemAudio: { backend: "pulse", device: "sys.monitor" },
      micGain: 1.5,
      systemGain: 0.4,
    });
    expect(after(args, "-filter_complex")).toBe(
      "[1:a]aresample=async=1:first_pts=0,aformat=sample_rates=48000:channel_layouts=stereo,volume=1.5[mic];" +
        "[2:a]aresample=async=1:first_pts=0,aformat=sample_rates=48000:channel_layouts=stereo,volume=0.4[sys];" +
        "[mic][sys]amix=inputs=2:duration=longest:normalize=0:dropout_transition=0[aout]",
    );
  });

  it("falls back to plain amix + volume=2 when normalize is unsupported", () => {
    const args = buildFfmpegArgs({
      ...base,
      video: { backend: "x11grab", xDisplay: ":0" },
      audio: { backend: "pulse", device: "default" },
      systemAudio: { backend: "pulse", device: "sys.monitor" },
      amixNormalize: false,
    });
    expect(after(args, "-filter_complex")).toBe(
      "[1:a]aresample=async=1:first_pts=0,aformat=sample_rates=48000:channel_layouts=stereo[mic];" +
        "[2:a]aresample=async=1:first_pts=0,aformat=sample_rates=48000:channel_layouts=stereo[sys];" +
        "[mic][sys]amix=inputs=2:duration=longest:dropout_transition=0,volume=2[aout]",
    );
  });

  it("records a macOS screen with avfoundation and no audio", () => {
    const args = buildFfmpegArgs({ ...base, video: { backend: "avfoundation", device: "3" } });
    expect(args.join(" ")).toContain("-f avfoundation -capture_cursor 1 -capture_mouse_clicks 1 -framerate 30 -i 3:none");
    expect(args).not.toContain("-c:a");
  });

  it("takes the macOS microphone from the same avfoundation input", () => {
    const args = buildFfmpegArgs({ ...base, video: { backend: "avfoundation", device: "3" }, audio: { backend: "avfoundation", device: "default" } });
    expect(after(args, "-i")).toBe("3:default");
    expect(args.join(" ")).toContain("-map 0:v:0 -map 0:a:0");
    expect(args.filter((a) => a === "-i")).toHaveLength(1);
  });

  it("refuses avfoundation audio with another video backend", () => {
    expect(() =>
      buildFfmpegArgs({ ...base, video: { backend: "x11grab", xDisplay: ":0" }, audio: { backend: "avfoundation", device: "0" } }),
    ).toThrow(/avfoundation/);
    expect(() =>
      buildFfmpegArgs({ ...base, video: { backend: "avfoundation", device: "3" }, systemAudio: { backend: "pulse", device: "sys.monitor" } }),
    ).toThrow(/avfoundation/);
  });

  it("records Windows with ddagrab, downloading frames from the GPU", () => {
    const args = buildFfmpegArgs({ ...base, video: { backend: "ddagrab", outputIndex: 1 }, audio: { backend: "dshow", device: "Microphone (Realtek(R) Audio)" } });
    expect(args.join(" ")).toContain("-f lavfi -i ddagrab=output_idx=1:framerate=30:draw_mouse=1");
    expect(after(args, "-vf")).toBe("hwdownload,format=bgra,scale=trunc(iw/2)*2:trunc(ih/2)*2,format=yuv420p");
    // The dshow device name stays one argv element, spaces and all.
    expect(args).toContain("audio=Microphone (Realtek(R) Audio)");
  });

  it("opens a Windows microphone before the screen, so the video starts when recording does", () => {
    // ffmpeg opens its inputs in order and starts recording once all are open.
    // A dshow microphone can take seconds to open; opened after the screen,
    // it left the video seconds behind the pointer events (timed from the
    // start of recording) and the file twice as long as the take.
    for (const video of [{ backend: "ddagrab", outputIndex: 0 }, { backend: "gdigrab" }] as const) {
      const args = buildFfmpegArgs({ ...base, video, audio: { backend: "dshow", device: "Microphone (Realtek(R) Audio)" } });
      const inputs = args.flatMap((a, i) => (a === "-i" ? [args[i + 1]] : []));
      expect(inputs[0]).toBe("audio=Microphone (Realtek(R) Audio)");
      expect(inputs).toHaveLength(2);
      expect(args.join(" ")).toContain("-map 1:v:0 -map 0:a:0");
    }
  });

  it("falls back to gdigrab, cropped to a display when its bounds are known", () => {
    const whole = buildFfmpegArgs({ ...base, video: { backend: "gdigrab" } });
    expect(whole.join(" ")).toContain("-f gdigrab -draw_mouse 1 -framerate 30 -i desktop");
    const cropped = buildFfmpegArgs({ ...base, video: { backend: "gdigrab", rect: { x: -1920, y: 0, width: 1920, height: 1080 } } });
    expect(after(cropped, "-offset_x")).toBe("-1920");
    expect(after(cropped, "-video_size")).toBe("1920x1080");
    expect(after(cropped, "-vf")).toBe(videoFilter("gdigrab"));
  });

  it("stops by itself after maxSeconds and keeps the keyframe interval at 2 s", () => {
    const plan: CapturePlan = { ...base, fps: 15, maxSeconds: 90, video: { backend: "x11grab", xDisplay: ":0" } };
    const args = buildFfmpegArgs(plan);
    expect(after(args, "-t")).toBe("90");
    expect(after(args, "-g")).toBe("30");
    expect(after(args, "-framerate")).toBe("15");
  });

  it("uses the platform hardware encoder when there is no libx264", () => {
    const mac = buildFfmpegArgs({ ...base, encoder: "h264_videotoolbox", video: { backend: "avfoundation", device: "1" } });
    expect(after(mac, "-c:v")).toBe("h264_videotoolbox");
    const win = buildFfmpegArgs({ ...base, encoder: "h264_mf", video: { backend: "gdigrab" } });
    expect(after(win, "-c:v")).toBe("h264_mf");
    expect(after(win, "-pix_fmt")).toBe("yuv420p");
  });

  it("always writes a fragmented MP4 to the output path last", () => {
    const args = buildFfmpegArgs({ ...base, video: { backend: "ddagrab", outputIndex: 0 } });
    expect(args.slice(-7)).toEqual(["-flush_packets", "1", "-movflags", "+frag_keyframe+empty_moov+default_base_moof", "-f", "mp4", "/tmp/out.mp4"]);
  });

  it("draws the cursor by default and when cursor is true", () => {
    expect(after(buildFfmpegArgs({ ...base, video: { backend: "x11grab", xDisplay: ":0" } }), "-draw_mouse")).toBe("1");
    expect(after(buildFfmpegArgs({ ...base, cursor: true, video: { backend: "x11grab", xDisplay: ":0" } }), "-draw_mouse")).toBe("1");
    expect(after(buildFfmpegArgs({ ...base, video: { backend: "avfoundation", device: "3" } }), "-capture_cursor")).toBe("1");
    expect(after(buildFfmpegArgs({ ...base, video: { backend: "ddagrab", outputIndex: 0 } }), "-i")).toBe("ddagrab=output_idx=0:framerate=30:draw_mouse=1");
    expect(after(buildFfmpegArgs({ ...base, video: { backend: "gdigrab" } }), "-draw_mouse")).toBe("1");
  });

  it("hides the cursor for x11grab when cursor is false", () => {
    const args = buildFfmpegArgs({ ...base, cursor: false, video: { backend: "x11grab", xDisplay: ":0" } });
    expect(after(args, "-draw_mouse")).toBe("0");
  });

  it("hides the cursor and click rings for avfoundation when cursor is false", () => {
    const args = buildFfmpegArgs({ ...base, cursor: false, video: { backend: "avfoundation", device: "3" } });
    expect(after(args, "-capture_cursor")).toBe("0");
    expect(after(args, "-capture_mouse_clicks")).toBe("0");
  });

  it("hides the cursor for ddagrab when cursor is false", () => {
    const args = buildFfmpegArgs({ ...base, cursor: false, video: { backend: "ddagrab", outputIndex: 0 } });
    expect(after(args, "-i")).toBe("ddagrab=output_idx=0:framerate=30:draw_mouse=0");
  });

  it("hides the cursor for gdigrab when cursor is false", () => {
    const args = buildFfmpegArgs({ ...base, cursor: false, video: { backend: "gdigrab" } });
    expect(after(args, "-draw_mouse")).toBe("0");
  });

  it.each([
    ["small", "28"],
    ["balanced", "23"],
    ["high", "18"],
  ] as const)("uses %s quality for libx264", (quality, crf) => {
    const args = buildFfmpegArgs({
      ...base,
      quality,
      video: { backend: "x11grab", xDisplay: ":0" },
    });

    expect(after(args, "-c:v")).toBe("libx264");
    expect(after(args, "-crf")).toBe(crf);
    expect(after(args, "-preset")).toBe("veryfast");
    expect(after(args, "-g")).toBe("60");
  });

  it.each([
    ["small", "4M"],
    ["balanced", "8M"],
    ["high", "16M"],
  ] as const)("uses %s quality for VideoToolbox", (quality, bitrate) => {
    const args = buildFfmpegArgs({
      ...base,
      encoder: "h264_videotoolbox",
      quality,
      video: { backend: "avfoundation", device: "1" },
    });

    expect(after(args, "-c:v")).toBe("h264_videotoolbox");
    expect(after(args, "-b:v")).toBe(bitrate);
    expect(after(args, "-realtime")).toBe("1");
    expect(after(args, "-g")).toBe("60");
  });

  it.each([
    ["small", "4M"],
    ["balanced", "8M"],
    ["high", "16M"],
  ] as const)("uses %s quality for Media Foundation", (quality, bitrate) => {
    const args = buildFfmpegArgs({
      ...base,
      encoder: "h264_mf",
      quality,
      video: { backend: "gdigrab" },
    });

    expect(after(args, "-c:v")).toBe("h264_mf");
    expect(after(args, "-b:v")).toBe(bitrate);
    expect(after(args, "-g")).toBe("60");
  });

  it("defaults to balanced quality for libx264", () => {
    const plan: CapturePlan = {
      ...base,
      video: { backend: "x11grab", xDisplay: ":0" },
    };

    expect(buildFfmpegArgs(plan)).toEqual(
      buildFfmpegArgs({ ...plan, quality: "balanced" }),
    );
    expect(after(buildFfmpegArgs(plan), "-crf")).toBe("23");
  });

  it("defaults to balanced quality for VideoToolbox", () => {
    const plan: CapturePlan = {
      ...base,
      encoder: "h264_videotoolbox",
      video: { backend: "avfoundation", device: "1" },
    };

    expect(buildFfmpegArgs(plan)).toEqual(
      buildFfmpegArgs({ ...plan, quality: "balanced" }),
    );
    expect(after(buildFfmpegArgs(plan), "-b:v")).toBe("8M");
  });

  it("defaults to balanced quality for Media Foundation", () => {
    const plan: CapturePlan = {
      ...base,
      encoder: "h264_mf",
      video: { backend: "gdigrab" },
    };

    expect(buildFfmpegArgs(plan)).toEqual(
      buildFfmpegArgs({ ...plan, quality: "balanced" }),
    );
    expect(after(buildFfmpegArgs(plan), "-b:v")).toBe("8M");
  });
});

describe("-thread_queue_size on inputs", () => {
  // One plan per input backend, with one or two audio inputs where the OS has them.
  const plans: CapturePlan[] = [
    { ...base, video: { backend: "x11grab", xDisplay: ":0" }, audio: { backend: "pulse", device: "default" } },
    {
      ...base,
      video: { backend: "x11grab", xDisplay: ":0", rect: { x: 0, y: 0, width: 800, height: 600 } },
      audio: { backend: "pulse", device: "default" },
      systemAudio: { backend: "pulse", device: "sink.monitor" },
    },
    { ...base, video: { backend: "x11grab", xDisplay: ":0" }, audio: { backend: "alsa", device: "hw:1" } },
    { ...base, video: { backend: "avfoundation", device: "3" }, audio: { backend: "avfoundation", device: "default" } },
    { ...base, video: { backend: "ddagrab", outputIndex: 0 }, audio: { backend: "dshow", device: "Microphone (Realtek(R) Audio)" } },
    { ...base, video: { backend: "gdigrab", rect: { x: 0, y: 0, width: 1920, height: 1080 } }, audio: { backend: "dshow", device: "Headset" } },
  ];

  it("is left off every input by default, so FFmpeg 9.1 does not refuse to start", () => {
    // FFmpeg 9.1: "Option thread_queue_size ... cannot be applied to input url desktop".
    for (const plan of plans) expect(buildFfmpegArgs(plan)).not.toContain("-thread_queue_size");
  });

  it("is given to each input, before its -f, when the plan asks for it (FFmpeg 6 and older)", () => {
    for (const plan of plans) {
      const args = buildFfmpegArgs({ ...plan, inputThreadQueue: true });
      const inputs = args.filter((a) => a === "-f").length - 1; // the last -f is the mp4 output
      const queues = args.flatMap((a, i) => (a === "-thread_queue_size" ? [i] : []));
      expect(queues).toHaveLength(inputs);
      for (const i of queues) {
        expect(args[i + 1]).toBe("1024");
        expect(args[i + 2]).toBe("-f");
      }
    }
  });
});

describe("parseFfmpegMajorVersion", () => {
  it("reads the release from the first line of ffmpeg -version", () => {
    expect(parseFfmpegMajorVersion("ffmpeg version 6.1.1-3ubuntu5 Copyright (c) 2000-2023 the FFmpeg developers\nbuilt with gcc 13")).toBe(6);
    expect(parseFfmpegMajorVersion("ffmpeg version 4.4.2-0ubuntu0.22.04.1 Copyright (c) 2000-2021")).toBe(4);
    expect(parseFfmpegMajorVersion("ffmpeg version n7.1 Copyright (c) 2000-2024")).toBe(7);
    expect(parseFfmpegMajorVersion("ffmpeg version 8.0 Copyright (c) 2000-2025")).toBe(8);
    expect(parseFfmpegMajorVersion("ffmpeg version 9.1-full_build-www.gyan.dev Copyright (c) 2000-2026\r\n")).toBe(9);
  });

  it("is null for snapshot builds and for output that is not ffmpeg -version", () => {
    expect(parseFfmpegMajorVersion("ffmpeg version N-118000-g1a2b3c4d5e Copyright (c) 2000-2026")).toBeNull();
    expect(parseFfmpegMajorVersion("ffmpeg version 2026-11-20-git-0123456789-full_build-www.gyan.dev")).toBeNull();
    expect(parseFfmpegMajorVersion("")).toBeNull();
    expect(parseFfmpegMajorVersion("'ffmpeg' is not recognized as an internal or external command")).toBeNull();
  });
});

describe("inputThreadQueue", () => {
  it("is on only for FFmpeg 6 and older", () => {
    expect(inputThreadQueue(4)).toBe(true);
    expect(inputThreadQueue(6)).toBe(true);
    expect(inputThreadQueue(7)).toBe(false);
    expect(inputThreadQueue(9)).toBe(false);
    expect(inputThreadQueue(null)).toBe(false);
  });

  // The installed ffmpeg, when there is one, must accept what the policy gives it.
  const ffmpeg = ffmpegPath();
  it.skipIf(!ffmpeg)("matches what the ffmpeg on this machine accepts", () => {
    const version = spawnSync(ffmpeg!, ["-version"], { encoding: "utf8" });
    const withQueue = inputThreadQueue(parseFfmpegMajorVersion(version.stdout));
    const run = spawnSync(
      ffmpeg!,
      ["-hide_banner", "-nostdin", ...(withQueue ? ["-thread_queue_size", "1024"] : []), "-f", "lavfi", "-i", "nullsrc=d=0.1", "-f", "null", "-"],
      { encoding: "utf8" },
    );
    expect(run.stderr).not.toMatch(/cannot be applied to input/);
    expect(run.status).toBe(0);
  });
});

describe("pickH264Encoder", () => {
  const encoders = [
    "Encoders:",
    " V..... = Video",
    " ------",
    " V....D libx264              libx264 H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10 (codec h264)",
    " V....D h264_videotoolbox    VideoToolbox H.264 Encoder (codec h264)",
  ].join("\n");

  it("prefers libx264", () => {
    expect(pickH264Encoder(encoders, "darwin")).toBe("libx264");
  });

  it("falls back to the OS encoder only on its own OS", () => {
    const noX264 = encoders.replace(/^.*libx264.*$/m, "");
    expect(pickH264Encoder(noX264, "darwin")).toBe("h264_videotoolbox");
    expect(pickH264Encoder(noX264, "linux")).toBeNull();
    expect(pickH264Encoder(" V....D h264_mf              H264 via MediaFoundation (codec h264)", "win32")).toBe("h264_mf");
  });
});

describe("even", () => {
  it("rounds down to an even size of at least 2", () => {
    expect(even(1281)).toBe(1280);
    expect(even(1)).toBe(2);
    expect(even(720)).toBe(720);
  });
});

describe("windowsPlans", () => {
  // Windows does not promise the main display is enumerated first, and
  // display:N counts the main one first, so the two orders differ: here the
  // main display is DISPLAY1, which Windows enumerated second.
  const screens = primaryFirst(
    parseScreensLine(
      'S [{"name":"DISPLAY2","x":-1920,"y":0,"width":1920,"height":1080,"primary":false},' +
        '{"name":"DISPLAY1","x":0,"y":0,"width":2560,"height":1440,"primary":true}]',
    ),
  );

  it("gives ddagrab the DXGI output number, not the display:N position", () => {
    const [ddagrab] = windowsPlans(base, screens, 0);
    expect(ddagrab.label).toBe("ddagrab");
    // display:0 is the main display, DISPLAY1, which is DXGI output 1.
    expect(buildFfmpegArgs(ddagrab.plan).join(" ")).toContain("ddagrab=output_idx=1:");

    const [second] = windowsPlans(base, screens, 1);
    expect(buildFfmpegArgs(second.plan).join(" ")).toContain("ddagrab=output_idx=0:");
  });

  it("gives the gdigrab fallback the same screen's rectangle", () => {
    const [, gdigrab] = windowsPlans(base, screens, 0);
    expect(gdigrab.label).toBe("gdigrab");
    const args = buildFfmpegArgs(gdigrab.plan);
    expect(after(args, "-offset_x")).toBe("0");
    expect(after(args, "-video_size")).toBe("2560x1440");
  });

  it("falls back to the position when the screens were never enumerated", () => {
    const [ddagrab, gdigrab] = windowsPlans(base, [], 2);
    expect(buildFfmpegArgs(ddagrab.plan).join(" ")).toContain("ddagrab=output_idx=2:");
    // No screen, so gdigrab records the whole virtual desktop.
    expect(buildFfmpegArgs(gdigrab.plan)).not.toContain("-offset_x");
  });
});

describe("audioMixFilter and supportsAmixNormalize", () => {
  it("switches between normalize=0 and the volume=2 fallback", () => {
    expect(audioMixFilter(true)).toContain("normalize=0:dropout_transition=0[aout]");
    expect(audioMixFilter(false)).toContain("dropout_transition=0,volume=2[aout]");
    expect(audioMixFilter(false)).not.toContain("normalize=0");
  });

  it("detects normalize support from ffmpeg -h filter=amix output", () => {
    expect(supportsAmixNormalize("   weights           <string>\n   normalize         <boolean>    ..F.A....T. Scale inputs\n")).toBe(true);
    expect(supportsAmixNormalize("   weights           <string>\n")).toBe(false);
  });
});

describe("checkGain", () => {
  it("accepts an unset gain and any multiplier above 0 up to 10", () => {
    expect(() => checkGain("micGain", undefined)).not.toThrow();
    expect(() => checkGain("micGain", 0.5)).not.toThrow();
    expect(() => checkGain("micGain", 10)).not.toThrow();
  });

  it("rejects zero, negatives, NaN, Infinity and anything above 10, naming the option", () => {
    for (const bad of [0, -1, Number.NaN, Number.POSITIVE_INFINITY, 10.1]) {
      expect(() => checkGain("systemGain", bad)).toThrow(/systemGain must be a number above 0 and at most 10/);
    }
  });
});