Skip to content

Open source CapCut alternative.

TypeScript
25.4 KB
Raw Blame
#!/usr/bin/env bun
/**
 * Browser export eval: the render path a browser-resident (and cloud) project
 * takes — framePlan, FrameCompositor, WebCodecs, the mediabunny muxer, the
 * audio mix — driven end to end in a real Chrome.
 *
 * A fixture project using the renderer's features (cover framing with zoom and
 * pan, a transition, playback speed, a grade, a keyframed pose, a
 * picture-in-picture track, a text element, burned-in captions, a music bed
 * with fades, whole-video fades, a background color) renders through the same
 * `renderProjectToMp4` the export dock calls, and the resulting MP4 is pulled
 * back out and ffprobed: right duration, right dimensions, both streams.
 *
 * Needs `next dev` on :3000. Spends no credits.
 *
 *   npm run eval:cut-export [--headed] [--base URL] [--hermetic] [--webkit]
 *
 * `--webkit` runs the same render in Playwright's WebKit — the Safari engine,
 * whose WebCodecs and origin-private storage differ from Chrome's — so a
 * Safari user's export path gets exercised.
 *
 * `--hermetic` answers every API call inside the browser context — the doc
 * GET with an empty project, the rest with empty stubs — so the run needs no
 * database and no real account. CI runs this mode against a `next dev` booted
 * on placeholder env values; the page shell is the only thing the server
 * serves.
 */

import { chromium, webkit, type Browser, type Page } from "playwright";
import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";

import { defaultSettings } from "../src/lib/config/registry";
import { publicSubset } from "../src/lib/config/resolve";

const SITE = path.resolve(import.meta.dir, "..");
const OUT = path.resolve(SITE, "..", "dist", "cut-export");
const STOCK = path.join(SITE, "public", "cut-stock-video");

const args = process.argv.slice(2);
const arg = (name: string) => {
  const i = args.indexOf(name);
  return i >= 0 ? args[i + 1] : undefined;
};
const has = (name: string) => args.includes(name);
const BASE = arg("--base") ?? "http://localhost:3000";
const HERMETIC = has("--hermetic");
/** Export a Mac-resident project: the fixtures go into a project on the dev
 * server's engine mount, the page starts the export through the store the
 * way the dialog does, and the engine lands the file in the project folder. */
const ENGINE = has("--engine") && !HERMETIC;
/** The dev-only account the API bypass authenticates as. */
const DEV_USER = "donkey-dev-auth-bypass";
/** The project id a hermetic run opens; its doc is answered in-context. */
const HERMETIC_PROJECT = "cut-export-eval";

const CLIP_S = 3;
/** How far the probed file may drift from the doc's own duration. */
const DURATION_TOLERANCE_S = 0.5;
/** Where the click sits in its file, and where the doc puts it on the timeline. */
const CLICK_IN_FILE_S = 0.25;
const CLICK_AT_S = 4.85;
/** Sound against picture: under a fifth of a frame at 24 fps. */
const SYNC_TOLERANCE_S = 0.008;

function run(cmd: string, cmdArgs: string[]): Promise<string> {
  return new Promise((resolve, reject) => {
    const p = spawn(cmd, cmdArgs);
    let out = "";
    let err = "";
    // Bytes land as latin1 so a raw-video or PCM stream reads back intact.
    p.stdout.on("data", (d: Buffer) => (out += d.toString("latin1")));
    p.stderr.on("data", (d) => (err += d.toString()));
    p.on("error", reject);
    p.on("close", (code) => {
      if (code !== 0) reject(new Error(`${cmd} exited ${code}: ${err.slice(-800)}`));
      resolve(out);
    });
  });
}

/** Fixture clips re-encoded from the bundled stock video, with a sine tone as
 * audio so the mix has something real to carry, plus a music bed. */
async function buildFixtures(): Promise<void> {
  await mkdir(OUT, { recursive: true });
  const sources = [
    "animal-dog-sprint.mp4",
    "animal-flock-sky.mp4",
  ].filter((f) => existsSync(path.join(STOCK, f)));
  if (sources.length === 0) throw new Error(`no stock clips found in ${STOCK}`);

  for (let i = 0; i < 2; i++) {
    const dst = path.join(OUT, `clip-${i}.mp4`);
    if (existsSync(dst)) continue;
    await run("ffmpeg", [
      "-y", "-loglevel", "error",
      "-i", path.join(STOCK, sources[i % sources.length]),
      "-f", "lavfi", "-i", `sine=frequency=${440 * (i + 1)}:sample_rate=44100:duration=${CLIP_S}`,
      "-t", String(CLIP_S),
      "-map", "0:v:0", "-map", "1:a:0",
      "-c:v", "libx264", "-preset", "veryfast", "-r", "30",
      "-vf", "scale=1280:-2", "-pix_fmt", "yuv420p",
      "-c:a", "aac",
      dst,
    ]);
  }
  const music = path.join(OUT, "music.m4a");
  if (!existsSync(music)) {
    await run("ffmpeg", [
      "-y", "-loglevel", "error",
      "-f", "lavfi", "-i", "sine=frequency=220:sample_rate=44100:duration=8",
      "-c:a", "aac",
      music,
    ]);
  }
  // A one-sample-wide click 0.25 s into an MP3. The encoder's tag says how
  // much priming opens the file; the click is where the sync check looks.
  const click = path.join(OUT, "click.mp3");
  if (!existsSync(click)) {
    await run("ffmpeg", [
      "-y", "-loglevel", "error",
      "-f", "lavfi", "-i", `aevalsrc='if(between(t,${CLICK_IN_FILE_S},${CLICK_IN_FILE_S}+0.0005),0.9,0)':s=44100:d=0.6`,
      "-c:a", "libmp3lame", "-b:a", "128k",
      click,
    ]);
  }
}

/** A browser with the fixture media served from disk and the session answered. */
async function launch(): Promise<{ browser: Browser; page: Page }> {
  const browser = has("--webkit")
    ? await webkit.launch({ headless: !has("--headed") })
    : await chromium.launch({
        channel: "chrome",
        headless: !has("--headed"),
        args: ["--autoplay-policy=no-user-gesture-required"],
      });
  const context = await browser.newContext({
    extraHTTPHeaders: { "x-donkey-dev-auth-bypass": "1" },
    viewport: { width: 1600, height: 1000 },
  });
  if (HERMETIC) {
    // Registered first, so the specific routes below win: everything else
    // under /api answers as an empty stub and the server is never asked. The
    // engine's port answers nothing at all, so the residency probe resolves
    // the project to the cloud the way a machine without the app would.
    await context.route("**/api/**", (route, request) => {
      if (new URL(request.url()).port === "41417") return route.abort();
      return route.fulfill({ status: 200, contentType: "application/json", body: "{}" });
    });
    // The chat's models probe: Gemini only, no CLIs on this machine.
    await context.route((u) => u.pathname.endsWith("/api/cut/ai/models"), (route) => {
      const off = { available: false, note: "", installed: false };
      return route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify({
          providers: { claude: off, codex: off, test: off, gemini: { available: true, note: "", installed: true } },
        }),
      });
    });
    // "Nothing saved yet" — the onboarding gate reads this and steps aside.
    await context.route("**/api/account/onboarding", (route) =>
      route.fulfill({ status: 200, contentType: "application/json", body: "null" })
    );
    // The session gate's configuration read: defaults, no experiments held.
    await context.route("**/api/account/config", (route) =>
      route.fulfill({
        status: 200,
        contentType: "application/json",
        body: JSON.stringify({
          settings: publicSubset(defaultSettings()),
          experiments: {},
          exposed: [],
        }),
      })
    );
    await context.route(
      (u) => /\/api\/(cut|cut-cloud)\/(projects|export-jobs|library)$/.test(u.pathname),
      (route) =>
        route.fulfill({ status: 200, contentType: "application/json", body: "[]" })
    );
    await context.route(
      (u) => new RegExp(`/api/(cut|cut-cloud)/projects/${HERMETIC_PROJECT}$`).test(u.pathname),
      (route) =>
        route.fulfill({
          status: 200,
          contentType: "application/json",
          headers: { "x-cut-doc-version": "1" },
          body: JSON.stringify({
            name: "cut-export eval",
            assets: [],
            clips: [],
            audioClips: [],
            overlays: [],
          }),
        })
    );
  }
  await context.route("**/api/auth/get-session*", async (route) => {
    const stamp = new Date(0).toISOString();
    const user = {
      id: DEV_USER,
      name: "cut-export eval",
      email: "cut-export@localhost",
      emailVerified: true,
      createdAt: stamp,
      updatedAt: stamp,
      image: null,
    };
    await route.fulfill({
      status: 200,
      contentType: "application/json",
      body: JSON.stringify({
        user,
        session: {
          id: "cut-export-session",
          userId: DEV_USER,
          token: "cut-export",
          expiresAt: new Date(Date.now() + 864e5).toISOString(),
          createdAt: stamp,
          updatedAt: stamp,
        },
      }),
    });
  });
  await context.route("**/__cutexport/*", async (route, request) => {
    const name = path.basename(new URL(request.url()).pathname);
    const body = await readFile(path.join(OUT, name));
    const type = name.endsWith(".m4a") ? "audio/mp4" : "video/mp4";
    await route.fulfill({ status: 200, contentType: type, body });
  });
  const page = await context.newPage();
  page.on("pageerror", (e) => console.log(`[pageerror] ${String(e).slice(0, 200)}`));
  page.on("crash", () => console.log("[crash] the page went down"));
  return { browser, page };
}

async function open(page: Page, projectId: string): Promise<void> {
  await page.goto(`${BASE}/app/p/${projectId}`, { waitUntil: "domcontentloaded", timeout: 120_000 });
  await page.waitForFunction(
    () => {
      const w = window as unknown as {
        __cutDev?: { useEditor: { getState(): { loaded: boolean } } };
      };
      return !!w.__cutDev && w.__cutDev.useEditor.getState().loaded;
    },
    undefined,
    { timeout: 120_000 }
  );
}

/** What this browser can do for a render, as the page sees it: the probes
 * `canRenderInBrowser` runs, reported one by one so a refusal names its cause. */
async function probeInPage(page: Page): Promise<Record<string, unknown>> {
  return page.evaluate(async () => {
    const out: Record<string, unknown> = {};
    try {
      const root = await navigator.storage.getDirectory();
      out.opfs = true;
      const dir = await root.getDirectoryHandle("cut-export-probe", { create: true });
      const h = await dir.getFileHandle("probe.bin", { create: true });
      const w = await h.createWritable();
      await w.write(new Uint8Array(16));
      await w.close();
      out.createWritable = true;
      await root.removeEntry("cut-export-probe", { recursive: true });
    } catch (e) {
      out.opfsError = String(e);
    }
    const vprobe = async (codec: string) => {
      try {
        const r = await VideoEncoder.isConfigSupported({ codec, width: 1280, height: 720, bitrate: 4_000_000, framerate: 24 });
        return r.supported ?? false;
      } catch (e) {
        return String(e);
      }
    };
    out.avc = await vprobe("avc1.640028");
    out.hevc = await vprobe("hvc1.1.6.L120.90");
    try {
      const r = await AudioEncoder.isConfigSupported({ codec: "mp4a.40.2", numberOfChannels: 2, sampleRate: 48000, bitrate: 192_000 });
      out.aac = r.supported ?? false;
    } catch (e) {
      out.aac = String(e);
    }
    return out;
  });
}

/** The fixture cut: every feature the renderer carries, over media named by
 * `url`. */
function fixtureDoc(url: (file: string) => string, clipS = CLIP_S) {
  const asset = (id: string, file: string, type: string, duration: number) => ({
    id,
    fileName: file,
    name: id,
    type,
    url: url(file),
    duration,
    ...(type === "video" ? { width: 1280, height: 720 } : {}),
  });
  const doc = {
    aspect: "16:9",
    background: "#102030",
    assets: [
      asset("v0", "clip-0.mp4", "video", clipS),
      asset("v1", "clip-1.mp4", "video", clipS),
      asset("m0", "music.m4a", "audio", 8),
      asset("k0", "click.mp3", "audio", 0.6),
    ],
    clips: [
      {
        id: "c0", assetId: "v0", track: 0, start: 0, in: 0, out: clipS,
        muted: false, volume: 0.8,
        fit: "fill", zoom: 1.4, panX: 0.3, panY: -0.2,
        speed: 1.25,
        transition: 0.5, transitionStyle: "crossfade",
      },
      {
        id: "c1", assetId: "v1", track: 0, start: clipS / 1.25, in: 0, out: clipS,
        muted: false,
        fit: "fit",
        grade: { brightness: 5, contrast: 8, saturation: -10, temperature: 12, hue: 10 },
        kf: [
          { t: 0, x: 0.5, y: 0.5, scale: 1, rotation: 0, opacity: 1 },
          { t: 2, x: 0.6, y: 0.4, scale: 0.85, rotation: 12, opacity: 1 },
        ],
      },
      {
        id: "c2", assetId: "v0", track: 1, start: 1, in: 0, out: 1.5,
        muted: true,
        frame: { x: 0.55, y: 0.05, w: 0.4, h: 0.4 },
        fit: "fill", rotation: 5, opacity: 0.9,
      },
    ],
    audioClips: [
      {
        id: "a0", assetId: "m0", start: 0, in: 0, out: 5,
        volume: 0.5, fadeIn: 0.3, fadeOut: 0.5, lane: 0,
      },
      {
        id: "k0", assetId: "k0", start: CLICK_AT_S - CLICK_IN_FILE_S, in: 0, out: 0.5,
        volume: 1, lane: 1,
      },
    ],
    overlays: [
      {
        id: "t0", kind: "text", text: "Everything test",
        start: 0.5, end: 3, x: 0.5, y: 0.2, lane: 0,
        size: 64, font: "sf", weight: 700, color: "#FFFFFF",
        shadow: true, plate: true,
      },
    ],
    subtitles: {
      cues: [
        { id: "s0", start: 0.3, end: 1.2, text: "every feature" },
        { id: "s1", start: 1.4, end: 2.2, text: "in one render" },
      ],
      showOnVideo: true,
      showOnTimeline: false,
    },
  };
  return doc;
}

const SETTINGS = { width: 1280, height: 720, fps: 24, crf: 24, preset: "veryfast", codec: "h264", container: "mp4", audioCodec: "aac" } as const;

/** Render the fixture doc in the tab and hand the MP4 bytes back. */
async function renderInPage(page: Page, doc: unknown): Promise<{ b64: string; duration: number }> {
  return page.evaluate(
    async ({ doc, settings }) => {
      const dev = (window as unknown as {
        __cutDev: {
          renderProjectToMp4: (
            doc: unknown,
            settings: unknown,
            opts: {
              resolve: (a: { url: string }) => string;
              onProgress?: (p: { ratio: number; stage: string }) => void;
            }
          ) => Promise<{ file: Blob; discard(): Promise<void> }>;
          projectDuration: (doc: unknown) => number;
        };
      }).__cutDev;


      const duration = dev.projectDuration(doc);
      let stage = "start";
      let rendered: { file: Blob; discard(): Promise<void> };
      try {
        rendered = await dev.renderProjectToMp4(doc, settings, {
          resolve: (a) => a.url,
          onProgress: (p) => (stage = `${p.stage} ${(p.ratio * 100).toFixed(0)}%`),
        });
      } catch (e) {
        throw new Error(`render failed at ${stage}: ${e instanceof Error ? `${e.name}: ${e.message}` : String(e)}`);
      }
      const bytes = new Uint8Array(await rendered.file.arrayBuffer());
      await rendered.discard();
      let bin = "";
      const CHUNK = 0x8000;
      for (let i = 0; i < bytes.length; i += CHUNK) {
        bin += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
      }
      return { b64: btoa(bin), duration };
    },
    { doc, settings: SETTINGS }
  );
}

/** Start the export through the store, the way the dialog does, and watch the
 * dock's rows until the engine's row reads done. */
async function exportThroughStore(page: Page, doc: unknown): Promise<{ duration: number; rows: string[] }> {
  return page.evaluate(
    async ({ doc, settings }) => {
      const dev = (window as unknown as {
        __cutDev: {
          projectDuration: (doc: unknown) => number;
          useEditor: { getState(): { projectId: string; projectName: string } };
          useExports: {
            getState(): {
              start(projectId: string, doc: unknown, settings: unknown, name: string): Promise<void>;
              local: { status: string; progress?: number; error?: string }[];
              jobs: { id: string; status: string; outName?: string; error?: string }[];
              rendering: string[];
            };
          };
        };
      }).__cutDev;
      const editor = dev.useEditor.getState();
      void dev.useExports.getState().start(editor.projectId, doc, settings, editor.projectName);
      const rows: string[] = [];
      const t0 = Date.now();
      while (Date.now() - t0 < 180_000) {
        await new Promise((r) => setTimeout(r, 250));
        const st = dev.useExports.getState();
        const line = [
          ...st.local.map((r) => `tab:${r.status}${r.progress != null ? ` ${(r.progress * 100).toFixed(0)}%` : ""}${r.error ? ` ${r.error}` : ""}`),
          ...st.jobs.map((j) => `engine:${j.status}${st.rendering.includes(j.id) ? " (hidden)" : ""} ${j.outName ?? ""}${j.error ? ` ${j.error}` : ""}`),
        ].join(" | ");
        if (rows[rows.length - 1] !== line) rows.push(line);
        if (st.local.some((r) => r.status === "error")) throw new Error(`export failed: ${rows.join("\n")}`);
        if (st.local.length === 0 && st.jobs.some((j) => j.status === "done")) break;
      }
      if (!dev.useExports.getState().jobs.some((j) => j.status === "done")) throw new Error(`export never finished: ${rows.join("\n")}`);
      return { duration: dev.projectDuration(doc), rows };
    },
    { doc, settings: SETTINGS }
  );
}

async function main(): Promise<void> {
  await buildFixtures();
  console.log(`[fixtures] ready in ${OUT}`);

  const { browser, page } = await launch();
  const probe = () => probeInPage(page).then((r) => console.log(`[probe] ${JSON.stringify(r)}`));
  let projectId = HERMETIC_PROJECT;
  const engine = (p: string, init?: RequestInit) => fetch(`${BASE}${p}${p.includes("?") ? "&" : "?"}u=${DEV_USER}`, init);
  if (!HERMETIC) {
    const res = await engine("/api/cut/projects", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ name: "cut-export eval" }),
    });
    if (!res.ok) throw new Error(`create project failed: ${res.status} (is next dev running?)`);
    projectId = ((await res.json()) as { id: string }).id;
  }
  console.log(`[ready] ${BASE}/app/p/${projectId}${HERMETIC ? " (hermetic)" : ENGINE ? " (engine)" : ""}`);

  const outPath = path.join(OUT, "export.mp4");
  let duration = 0;
  const t0 = Date.now();
  try {
    if (ENGINE) {
      // The media lives in the project on the engine, and the doc names it
      // by the engine's own media URLs, the way an imported file is stored.
      const upload = async (file: string) => {
        const form = new FormData();
        const type = file.endsWith(".m4a") ? "audio/mp4" : "video/mp4";
        form.set("file", new File([await readFile(path.join(OUT, file))], file, { type }));
        const res = await engine(`/api/cut/projects/${projectId}/media`, { method: "POST", body: form });
        if (!res.ok) throw new Error(`upload ${file} failed: ${res.status}`);
        return ((await res.json()) as { fileName: string }).fileName;
      };
      const stored = new Map<string, string>();
      for (const file of ["clip-0.mp4", "clip-1.mp4", "music.m4a"]) stored.set(file, await upload(file));
      const doc = fixtureDoc((file) => `/api/cut/projects/${projectId}/media/${encodeURIComponent(stored.get(file)!)}`);
      const put = await engine(`/api/cut/projects/${projectId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(doc),
      });
      if (!put.ok) throw new Error(`save project failed: ${put.status}`);

      await open(page, projectId);
      await probe();
      const result = await exportThroughStore(page, doc);
      duration = result.duration;
      for (const row of result.rows) console.log(`  ${row}`);
      await browser.close();

      const feed = (await (await engine(`/api/cut/projects/${projectId}/exports`)).json()) as { file: string }[];
      const landed = feed.find((f) => f.file.endsWith(".mp4"));
      if (!landed) throw new Error(`no export in the project folder: ${JSON.stringify(feed)}`);
      const file = await engine(`/api/cut/projects/${projectId}/exports/${encodeURIComponent(landed.file)}`);
      if (!file.ok) throw new Error(`read ${landed.file} failed: ${file.status}`);
      await writeFile(outPath, Buffer.from(await file.arrayBuffer()));
      console.log(`[render] ${((Date.now() - t0) / 1000).toFixed(1)}s → ${landed.file} in the project folder → ${outPath}`);
    } else {
      await open(page, projectId);
      await probe();
      const rendered = await renderInPage(page, fixtureDoc((file) => `/__cutexport/${file}`));
      duration = rendered.duration;
      await browser.close();
      await writeFile(outPath, Buffer.from(rendered.b64, "base64"));
      console.log(`[render] ${((Date.now() - t0) / 1000).toFixed(1)}s → ${outPath}`);
    }
  } finally {
    // The project was this run's; nothing of it stays on the machine.
    if (!HERMETIC) await engine(`/api/cut/projects/${projectId}`, { method: "DELETE" }).catch(() => {});
  }

  const probed = JSON.parse(
    await run("ffprobe", [
      "-v", "error",
      "-show_entries", "format=duration",
      "-show_entries", "stream=codec_type,codec_name,width,height",
      "-of", "json",
      outPath,
    ])
  ) as {
    format: { duration: string };
    streams: { codec_type: string; codec_name?: string; width?: number; height?: number }[];
  };

  const failures: string[] = [];
  const got = Number(probed.format.duration);
  if (!(Math.abs(got - duration) <= DURATION_TOLERANCE_S)) {
    failures.push(`duration ${got.toFixed(2)}s, doc says ${duration.toFixed(2)}s`);
  }
  const video = probed.streams.find((s) => s.codec_type === "video");
  if (video?.width !== 1280 || video?.height !== 720) {
    failures.push(`picture is ${video?.width}x${video?.height}, settings say 1280x720`);
  }
  // The file is for QuickTime and phones as much as for ffprobe: H.264 and
  // AAC, whatever the browser would rather have encoded.
  if (video?.codec_name !== "h264") failures.push(`video is ${video?.codec_name}, settings say h264`);
  const audio = probed.streams.find((s) => s.codec_type === "audio");
  if (audio?.codec_name !== "aac") failures.push(`audio is ${audio?.codec_name}, settings say aac`);
  if (!probed.streams.some((s) => s.codec_type === "audio")) {
    failures.push("no audio stream");
  }

  // The picture at every cut: a frame of bare background between two
  // clips is the black flash a fixed-rate render lands in a gap the timeline
  // never showed. The project fade darkens the first and last frames by
  // design, so the scan stays clear of them.
  const raw = await run("ffmpeg", ["-loglevel", "error", "-i", outPath, "-vf", "scale=1:1:flags=area", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]);
  const bytes = Buffer.from(raw, "binary");
  const frames: number[][] = [];
  for (let i = 0; i + 2 < bytes.length; i += 3) frames.push([bytes[i], bytes[i + 1], bytes[i + 2]]);
  const dark = (c: number[]) => c[0] + c[1] + c[2] < 96;
  const flashes = frames
    .map((c, i) => ({ c, i }))
    .filter(({ c, i }) => i / 24 > 0.5 && i / 24 < duration - 0.5 && dark(c) && !dark(frames[i - 1]) && !dark(frames[i + 1]))
    .map(({ i }) => (i / 24).toFixed(2));
  if (flashes.length) failures.push(`bare frames at ${flashes.join(", ")}s`);

  // The level: the second clip at full volume over the music bed at half,
  // measured where nothing fades, against the sources through the same
  // decode. Half a decibel either way is the preview's own gain math.
  const rmsOf = async (file: string, from: number, to: number) => {
    const pcm = await run("ffmpeg", ["-loglevel", "error", "-ss", String(from), "-t", String(to - from), "-i", file, "-vn", "-af", "pan=mono|c0=c0", "-f", "f32le", "-ar", "48000", "-"]);
    const x = new Float32Array(Buffer.from(pcm, "binary").buffer);
    let sum = 0;
    for (const v of x) sum += v * v;
    return Math.sqrt(sum / Math.max(1, x.length));
  };
  const expected = Math.hypot(await rmsOf(path.join(OUT, "clip-1.mp4"), 0.5, 1.5), 0.5 * (await rmsOf(path.join(OUT, "music.m4a"), 0.5, 1.5)));
  const level = await rmsOf(outPath, 3.5, 4.5);
  const dB = 20 * Math.log10(level / expected);
  if (!(Math.abs(dB) <= 0.5)) failures.push(`level at 3.5–4.5s is ${dB.toFixed(2)} dB off the sources`);
  console.log(`[level] ${dB >= 0 ? "+" : ""}${dB.toFixed(2)} dB against the sources; ${frames.length} frames, ${flashes.length} bare`);

  // Sync: the click lands where the doc puts it. Encoder priming written
  // without an edit list, or an MP3's own priming read as sound, plays every
  // cut's audio late against its picture. The tones under it sit below the
  // high-pass, so the loudest sample left is the click.
  const near = CLICK_AT_S - 0.2;
  const hp = await run("ffmpeg", ["-loglevel", "error", "-ss", String(near), "-t", "0.4", "-i", outPath, "-vn", "-af", "highpass=f=4000,pan=mono|c0=c0", "-f", "f32le", "-ar", "48000", "-"]);
  const hx = new Float32Array(Buffer.from(hp, "binary").buffer);
  let peak = 0;
  for (let i = 1; i < hx.length; i++) if (Math.abs(hx[i]) > Math.abs(hx[peak])) peak = i;
  const clickAt = near + peak / 48000;
  if (!(Math.abs(clickAt - CLICK_AT_S) <= SYNC_TOLERANCE_S)) {
    failures.push(`the click plays at ${clickAt.toFixed(4)}s, the doc puts it at ${CLICK_AT_S}s`);
  }
  console.log(`[sync] click ${((clickAt - CLICK_AT_S) * 1000).toFixed(1)} ms from where the doc puts it`);

  if (failures.length) {
    console.error(`[FAIL] ${failures.join("; ")}`);
    process.exit(1);
  }
  console.log(`[ok] ${got.toFixed(2)}s, 1280x720, video+audio`);
}

main().catch((e) => {
  console.error(e);
  process.exit(1);
});