SPB Git

Repository Public

ffmpeg.ts 10.6 KB 171 lines typescript

1import { execFile, spawn } from "node:child_process";2import { rm } from "node:fs/promises";34/** FFmpeg Homebrew (Apple Silicon) : pas de `drawtext` ni `subtitles` ; tout texte passe par le moteur canvas + `overlay`. */5const BIN_PATH = `/opt/homebrew/bin:/usr/local/bin:${process.env.PATH ?? ""}`;6const ENV = () => ({ ...process.env, PATH: BIN_PATH });78function tail(stderr: string, n = 6): string {9  return stderr.split("\n").map((l) => l.trim()).filter(Boolean).slice(-n).join(" | ");10}1112export function run(bin: "ffmpeg" | "ffprobe", args: string[], timeoutMs = 600_000): Promise<{ stdout: string; stderr: string }> {13  return new Promise((resolve, reject) => {14    execFile(bin, args, { env: ENV(), maxBuffer: 256 * 1024 * 1024, timeout: timeoutMs }, (err, stdout, stderr) => {15      if (err) reject(new Error(`${bin} failed: ${tail(stderr || err.message)}`));16      else resolve({ stdout, stderr });17    });18  });19}2021/** ffmpeg silencieux, écrasement autorisé, sans stdin. */22export const ff = (args: string[], timeoutMs?: number) => run("ffmpeg", ["-hide_banner", "-nostdin", "-y", ...args], timeoutMs);2324/** Comme `run`, mais renvoie stdout en binaire (trames brutes). */25export function runBinary(bin: "ffmpeg" | "ffprobe", args: string[], timeoutMs = 120_000): Promise<Buffer> {26  return new Promise((resolve, reject) => {27    execFile(bin, args, { env: ENV(), maxBuffer: 512 * 1024 * 1024, timeout: timeoutMs, encoding: "buffer" }, (err, stdout, stderr) => {28      if (err) reject(new Error(`${bin} failed: ${tail(stderr.toString() || err.message)}`));29      else resolve(stdout);30    });31  });32}3334export interface Probe {35  duration: number; width: number; height: number; fps: number; hasVideo: boolean; hasAudio: boolean;36  videoCodec?: string; audioCodec?: string;37  /** Champs enrichis (v2). */38  format?: string; bitrate?: number; size?: number;39  /** Durée de la piste vidéo (peut différer de `duration`, qui est celle du conteneur : amorce AAC, piste audio plus longue). */40  videoDuration?: number;41  videoProfile?: string; pixFmt?: string; videoBitrate?: number; frames?: number; rotation?: number; isStill?: boolean;42  audioBitrate?: number; channels?: number; sampleRate?: number; channelLayout?: string;43  tags?: Record<string, string>;44}4546interface RawStream {47  codec_type: string; codec_name?: string; profile?: string; width?: number; height?: number; pix_fmt?: string; avg_frame_rate?: string; r_frame_rate?: string;48  bit_rate?: string; nb_frames?: string; duration?: string; channels?: number; sample_rate?: string; channel_layout?: string;49  disposition?: { attached_pic?: number }; side_data_list?: { rotation?: number }[]; tags?: Record<string, string>;50}51const num = (v: unknown): number | undefined => { const n = Number(v); return v !== undefined && v !== null && v !== "" && Number.isFinite(n) ? n : undefined; };52const hms = (s?: string): number | undefined => { const m = s?.match(/^(\d+):(\d+):([\d.]+)$/); return m ? Number(m[1]) * 3600 + Number(m[2]) * 60 + Number(m[3]) : undefined; };53const rate = (s?: string): number => { const [n, d] = (s ?? "0/1").split("/").map(Number); return d ? n / d : 0; };54const STILL_FORMATS = /(^|,)(image2|png_pipe|jpeg_pipe|webp_pipe|bmp_pipe|tiff_pipe|gif|jpegxl_pipe|heif|avif)(,|$)/;5556export async function probe(file: string): Promise<Probe> {57  const { stdout } = await run("ffprobe", ["-v", "error", "-print_format", "json", "-show_format", "-show_streams", file]);58  const d = JSON.parse(stdout) as { format?: { duration?: string; format_name?: string; bit_rate?: string; size?: string; tags?: Record<string, string> }; streams?: RawStream[] };59  const v = d.streams?.find((s) => s.codec_type === "video" && !s.disposition?.attached_pic);60  const a = d.streams?.find((s) => s.codec_type === "audio");61  const duration = num(d.format?.duration) ?? num(v?.duration) ?? num(a?.duration) ?? 0;62  const fps = rate(v?.avg_frame_rate) || rate(v?.r_frame_rate);63  const format = d.format?.format_name;64  const frames = num(v?.nb_frames);65  return {66    duration, width: v?.width ?? 0, height: v?.height ?? 0, fps, hasVideo: !!v, hasAudio: !!a, videoCodec: v?.codec_name, audioCodec: a?.codec_name,67    format, bitrate: num(d.format?.bit_rate), size: num(d.format?.size),68    videoDuration: v ? num(v.duration) ?? hms(v.tags?.DURATION ?? v.tags?.duration) ?? duration : undefined,69    videoProfile: v?.profile, pixFmt: v?.pix_fmt, videoBitrate: num(v?.bit_rate), frames, rotation: v?.side_data_list?.find((s) => s.rotation !== undefined)?.rotation,70    isStill: !!v && (STILL_FORMATS.test(format ?? "") && format !== "gif" ? true : frames === 1 && duration < 0.1),71    audioBitrate: num(a?.bit_rate), channels: a?.channels, sampleRate: num(a?.sample_rate), channelLayout: a?.channel_layout,72    tags: Object.fromEntries(Object.entries(d.format?.tags ?? {}).map(([k, val]) => [k.toLowerCase(), String(val)])),73  };74}7576/** Lance un filtre d'analyse et renvoie le journal de ffmpeg (les filtres rapportent sur stderr). */77export async function analyse(input: string, args: string[]): Promise<string> {78  const { stderr } = await run("ffmpeg", ["-hide_banner", "-nostdin", "-i", input, ...args, "-f", "null", "-"]);79  return stderr;80}8182export const cleanup = (dir: string) => rm(dir, { recursive: true, force: true });8384/**85 * Codec intermédiaire (conformClip, renderMotion, renderEndCard, assembleProgram) : H.264 CRF 12 (visuellement sans perte),86 * une image clé par seconde, PCM 48 kHz stéréo, conteneur Matroska (`.mkv` recommandé ; `.mov` accepté).87 * Le seul encodage « de diffusion » est celui de `finishMaster`.88 */89export function intermediateArgs(fps: number, output: string): string[] {90  const mux = /\.mov$/i.test(output) ? "mov" : /\.mp4$/i.test(output) ? "mp4" : "matroska";91  const audio = mux === "mp4" ? ["-c:a", "aac", "-b:a", "320k"] : ["-c:a", "pcm_s16le"];92  return ["-c:v", "libx264", "-preset", "veryfast", "-crf", "12", "-pix_fmt", "yuv420p", "-g", String(Math.round(fps)), "-bf", "0",93    "-r", String(fps), "-video_track_timescale", "90000", ...audio, "-ar", "48000", "-ac", "2", "-f", mux, output];94}9596/**97 * Envoie des trames RGBA brutes à ffmpeg par stdin (`-f rawvideo`). `args(input)` reçoit les arguments d'entrée du flux brut98 * et renvoie la ligne de commande complète. `next()` renvoie la trame suivante ou null à la fin.99 */100export async function pipeFrames(o: { width: number; height: number; fps: number; args: (rawInput: string[]) => string[]; next: () => Buffer | null | Promise<Buffer | null>; timeoutMs?: number }): Promise<void> {101  const rawInput = ["-f", "rawvideo", "-pix_fmt", "rgba", "-s", `${o.width}x${o.height}`, "-r", String(o.fps), "-i", "pipe:0"];102  const child = spawn("ffmpeg", ["-hide_banner", "-y", ...o.args(rawInput)], { env: ENV(), stdio: ["pipe", "ignore", "pipe"] });103  let stderr = "";104  child.stderr.on("data", (c: Buffer) => { stderr = (stderr + c.toString()).slice(-8000); });105  const done = new Promise<void>((resolve, reject) => {106    child.on("error", reject);107    child.on("close", (code) => (code === 0 ? resolve() : reject(new Error(`ffmpeg failed (${code}): ${tail(stderr)}`))));108  });109  const timer = setTimeout(() => child.kill("SIGKILL"), o.timeoutMs ?? 900_000);110  let pipeError: Error | null = null;111  child.stdin.on("error", (e) => { pipeError = e; });112  try {113    for (;;) {114      const frame = await o.next();115      if (!frame || pipeError) break;116      if (!child.stdin.write(frame)) {117        await new Promise<void>((r) => {118          const on = () => { child.stdin.off("drain", on); child.off("close", on); r(); };119          child.stdin.once("drain", on);120          child.once("close", on);121        });122      }123    }124    child.stdin.end();125    await done;126  } finally {127    clearTimeout(timer);128  }129}130131/**132 * Extrait une trame en niveaux de gris (luminance) recadrée. `at` < 0 = dernière trame du fichier.133 * La recherche rapide (`-ss` avant `-i`) ne rend parfois rien dans le dernier segment d'une playlist HLS : on réessaie alors avec une134 * recherche mixte (saut 5 s avant, puis décodage jusqu'à l'instant voulu), puis avec un décodage depuis le début.135 */136export async function grayFrame(file: string, at: number, crop: { x: number; y: number; w: number; h: number }): Promise<{ data: Buffer; width: number; height: number } | null> {137  // format=gray AVANT crop : sans sous-échantillonnage de chrominance, le recadrage est exact au pixel (coordonnées impaires comprises)138  const vf = `format=gray,crop=${crop.w}:${crop.h}:${crop.x}:${crop.y}`;139  const size = crop.w * crop.h;140  const pre = ["-hide_banner", "-nostdin", "-v", "error"];141  const post = ["-vf", vf, "-f", "rawvideo", "-pix_fmt", "gray", "-"];142  const one = ["-map", "0:v:0", "-frames:v", "1"];143  const back = Math.max(0, at - 5);144  const attempts: string[][] = at < 0145    ? [[...pre, "-sseof", "-1.2", "-i", file, "-map", "0:v:0", ...post], [...pre, "-i", file, "-map", "0:v:0", ...post]]146    : [[...pre, "-ss", at.toFixed(3), "-i", file, ...one, ...post], [...pre, "-ss", back.toFixed(3), "-i", file, "-ss", (at - back).toFixed(3), ...one, ...post], [...pre, "-i", file, "-ss", at.toFixed(3), ...one, ...post]];147  for (const args of attempts) {148    let out: Buffer;149    try { out = await runBinary("ffmpeg", args, 600_000); } catch { continue; }150    if (out.length < size) continue;151    const n = Math.floor(out.length / size);152    return { data: out.subarray((n - 1) * size, n * size), width: crop.w, height: crop.h };153  }154  return null;155}156157/**158 * Extrait en UN SEUL décodage la première trame située à ou après chacun des instants `times` (croissants, espacés d'au moins deux159 * trames), en niveaux de gris, recadrée. Sert aux playlists HLS, où la recherche par `-ss` n'est pas fiable à la trame près160 * (retombe sur une image non clé ou sur le segment suivant). Renvoie null pour les instants situés après la fin.161 */162export async function grayFramesSinglePass(file: string, times: number[], crop: { x: number; y: number; w: number; h: number }): Promise<(Buffer | null)[]> {163  if (!times.length) return [];164  // prev_selected_t vaut NaN tant qu'aucune trame n'est retenue (et NaN contamine une somme) : d'où le if().165  const later = times.slice(1).map((t) => `gte(t,${t.toFixed(3)})*lt(prev_selected_t,${t.toFixed(3)})`).join("+") || "0";166  const vf = `select='if(isnan(prev_selected_t),gte(t,${times[0].toFixed(3)}),${later})',format=gray,crop=${crop.w}:${crop.h}:${crop.x}:${crop.y}`;167  const out = await runBinary("ffmpeg", ["-hide_banner", "-nostdin", "-v", "error", "-i", file, "-map", "0:v:0", "-an", "-vf", vf, "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "gray", "-"], 3_600_000);168  const size = crop.w * crop.h;169  return times.map((_, i) => (out.length >= (i + 1) * size ? out.subarray(i * size, (i + 1) * size) : null));170}171
Files main
Menu

Theme