Repository Public
1/**2 * ffprobe / ffmpeg: input validation and the encode of one master into what the player expects —3 * the layout of scripts/make-test-capsule.ts:4 *5 * master.m3u8 one EXT-X-STREAM-INF per rendition (measured BANDWIDTH, RESOLUTION, CODECS)6 * v<height>/index.m3u8, seg_*.ts H.264 + AAC, 4 s segments, key frames aligned across renditions7 * fallback.mp4 progressive MP4 (≤ 720p, faststart)8 * poster.jpg, thumbs/t_*.jpg poster and a strip of thumbnails9 *10 * The master file is only ever read. ffmpeg and ffprobe are started without a shell, with a time limit, and11 * are killed by PID when the job is cancelled or times out.12 */13import { spawn } from "node:child_process";14import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";15import { join } from "node:path";16import { z } from "zod";17import { env } from "../lib/env";18import { JobCancelled, PermanentJobError } from "./jobs";1920export interface Rung { height: number; videoKbps: number; audioKbps: number }21export const DEFAULT_LADDER: Rung[] = [22 { height: 360, videoKbps: 800, audioKbps: 96 },23 { height: 720, videoKbps: 2800, audioKbps: 128 },24 { height: 1080, videoKbps: 5000, audioKbps: 160 },25];26const LadderSchema = z.array(z.object({ height: z.number().int().min(144).max(4320), videoKbps: z.number().int().min(100).max(60_000), audioKbps: z.number().int().min(32).max(512) })).min(1).max(8);2728/** The ladder from ATLAS_LADDER, or the built-in one. An invalid value is reported, never silently replaced. */29export function configuredLadder(raw = env.ladder): { ladder: Rung[]; error: string | null } {30 if (!raw.trim()) return { ladder: DEFAULT_LADDER, error: null };31 try {32 const p = LadderSchema.safeParse(JSON.parse(raw));33 if (p.success) return { ladder: [...p.data].sort((a, b) => a.height - b.height), error: null };34 return { ladder: DEFAULT_LADDER, error: `ATLAS_LADDER invalide (${p.error.issues[0]?.message}) : échelle par défaut utilisée.` };35 } catch { return { ladder: DEFAULT_LADDER, error: "ATLAS_LADDER n'est pas du JSON : échelle par défaut utilisée." }; }36}3738const even = (n: number) => Math.max(2, Math.round(n / 2) * 2);3940/**41 * Renditions for a source of the given height. Never upscales: only rungs at or below the source are kept;42 * a source that sits clearly above the last kept rung (or below the first) gets one rung at its own height.43 */44export function ladderFor(sourceHeight: number, ladder: Rung[] = configuredLadder().ladder): Rung[] {45 const h = even(sourceHeight), sorted = [...ladder].sort((a, b) => a.height - b.height), top = sorted[sorted.length - 1]!;46 const kept = sorted.filter((r) => r.height <= h);47 const last = kept[kept.length - 1];48 if (h < top.height && (!last || h >= last.height * 1.2)) {49 // Bitrate of the native rung: proportional to its pixel count, relative to the rung just above it.50 const above = sorted.find((r) => r.height > h)!;51 kept.push({ height: h, videoKbps: Math.max(150, Math.round(above.videoKbps * (h / above.height) ** 2 / 50) * 50), audioKbps: last?.audioKbps ?? sorted[0]!.audioKbps });52 }53 return kept;54}5556/* ---- Process handling ---- */5758export interface RunOptions { timeoutMs: number; signal?: AbortSignal; onStdout?: (line: string) => void }59/** Runs a program without a shell. Rejects with the tail of stderr on a non-zero exit, on timeout or on abort. */60export function runProgram(cmd: string, args: string[], o: RunOptions): Promise<{ stdout: string; stderr: string }> {61 return new Promise((resolve, reject) => {62 if (o.signal?.aborted) { reject(new JobCancelled()); return; }63 let child;64 try { child = spawn(cmd, args, { stdio: ["ignore", "pipe", "pipe"] }); } catch (e) { reject(e as Error); return; }65 let stdout = "", stderr = "", rest = "", done = false, why: Error | null = null;66 const kill = (reason: Error) => { why = reason; if (child.pid) try { process.kill(child.pid, "SIGKILL"); } catch { /* already gone */ } };67 const timer = setTimeout(() => kill(new Error(`Délai dépassé (${Math.round(o.timeoutMs / 1000)} s) : ${cmd} a été arrêté.`)), o.timeoutMs);68 const onAbort = () => kill(new JobCancelled());69 o.signal?.addEventListener("abort", onAbort, { once: true });70 child.stdout.on("data", (d: Buffer) => {71 const text = d.toString("utf8");72 if (stdout.length < 4_000_000) stdout += text;73 if (o.onStdout) { const lines = (rest + text).split("\n"); rest = lines.pop() ?? ""; for (const l of lines) o.onStdout(l); }74 });75 child.stderr.on("data", (d: Buffer) => { stderr = (stderr + d.toString("utf8")).slice(-6000); });76 const finish = (err: Error | null) => { if (done) return; done = true; clearTimeout(timer); o.signal?.removeEventListener("abort", onAbort); if (err) reject(err); else resolve({ stdout, stderr }); };77 child.on("error", (e: NodeJS.ErrnoException) => finish(e.code === "ENOENT" ? new PermanentJobError(`${cmd} est introuvable sur ce serveur.`) : e));78 child.on("close", (code) => finish(why ?? (code === 0 ? null : new Error(`${cmd} a échoué (code ${code}) : ${stderr.trim().split("\n").slice(-4).join(" | ").slice(0, 600)}`))));79 });80}8182export interface FfmpegStatus { ok: boolean; ffmpeg: string | null; ffprobe: string | null; x264: boolean; aac: boolean; message: string | null }83type G = typeof globalThis & { __atlasFf?: { at: number; key: string; value: FfmpegStatus } };8485/** Is the media toolchain usable on this machine? Checked at run time and reported, never assumed. */86export async function ffmpegStatus(fresh = false): Promise<FfmpegStatus> {87 const g = globalThis as G, key = `${env.ffmpeg}|${env.ffprobe}`;88 if (!fresh && g.__atlasFf?.key === key && Date.now() - g.__atlasFf.at < 60_000) return g.__atlasFf.value;89 const version = async (cmd: string) => { try { return /version (\S+)/.exec((await runProgram(cmd, ["-version"], { timeoutMs: 10_000 })).stdout)?.[1] ?? "inconnue"; } catch { return null; } };90 const [ffmpeg, ffprobe] = await Promise.all([version(env.ffmpeg), version(env.ffprobe)]);91 let x264 = false, aac = false;92 if (ffmpeg) { try { const enc = (await runProgram(env.ffmpeg, ["-hide_banner", "-encoders"], { timeoutMs: 10_000 })).stdout; x264 = /\blibx264\b/.test(enc); aac = /\baac\b/.test(enc); } catch { /* reported below */ } }93 const message = !ffmpeg ? "ffmpeg est introuvable : les vidéos téléversées resteront en attente. Installez ffmpeg sur le nœud (brew install ffmpeg) ou réglez ATLAS_FFMPEG."94 : !ffprobe ? "ffprobe est introuvable : les vidéos ne peuvent pas être validées. Il est livré avec ffmpeg ; réglez ATLAS_FFPROBE au besoin."95 : !x264 ? "Ce ffmpeg n'a pas l'encodeur libx264 : l'encodage H.264 est impossible."96 : !aac ? "Ce ffmpeg n'a pas d'encodeur AAC : l'encodage audio est impossible." : null;97 const value = { ok: message === null, ffmpeg, ffprobe, x264, aac, message };98 g.__atlasFf = { at: Date.now(), key, value };99 return value;100}101102/* ---- Probe ---- */103104export interface Probe { duration: number; width: number; height: number; fps: number; videoCodec: string; audioCodec: string | null; bitrate: number | null; format: string }105106/** Validates a master with ffprobe. Anything that is not a playable video of acceptable length is a permanent error. */107export async function probe(file: string, o: { signal?: AbortSignal; maxSeconds?: number } = {}): Promise<Probe> {108 let out: string;109 try { out = (await runProgram(env.ffprobe, ["-v", "error", "-print_format", "json", "-show_format", "-show_streams", file], { timeoutMs: 120_000, signal: o.signal })).stdout; }110 catch (e) { if (e instanceof JobCancelled || e instanceof PermanentJobError) throw e; throw new PermanentJobError(`Ce fichier n'est pas une vidéo lisible (${e instanceof Error ? e.message.slice(0, 200) : "ffprobe a échoué"}).`); }111 interface S { codec_type?: string; codec_name?: string; width?: number; height?: number; avg_frame_rate?: string; r_frame_rate?: string; duration?: string; disposition?: { attached_pic?: number }; side_data_list?: { rotation?: number }[]; tags?: { rotate?: string } }112 let data: { streams?: S[]; format?: { duration?: string; bit_rate?: string; format_name?: string } };113 try { data = JSON.parse(out) as typeof data; } catch { throw new PermanentJobError("ffprobe a rendu une réponse illisible pour ce fichier."); }114 const video = data.streams?.find((s) => s.codec_type === "video" && !s.disposition?.attached_pic), audio = data.streams?.find((s) => s.codec_type === "audio");115 if (!video || !video.width || !video.height) throw new PermanentJobError("Aucune piste vidéo dans ce fichier.");116 const duration = Number(data.format?.duration ?? video.duration ?? 0);117 if (!Number.isFinite(duration) || duration < 0.5) throw new PermanentJobError("La vidéo est vide ou sa durée est illisible.");118 const max = o.maxSeconds ?? env.maxVideoSeconds;119 if (duration > max) throw new PermanentJobError(`La vidéo dure ${Math.round(duration / 60)} min : la limite est de ${Math.round(max / 60)} min (ATLAS_MAX_VIDEO_MIN).`);120 const rate = (r?: string) => { const [a, b] = (r ?? "").split("/").map(Number); return a && b ? a / b : 0; };121 const rotation = Math.abs(Number(video.side_data_list?.find((d) => d.rotation !== undefined)?.rotation ?? video.tags?.rotate ?? 0)) % 180 === 90;122 return {123 duration, width: rotation ? video.height : video.width, height: rotation ? video.width : video.height,124 fps: Math.round((rate(video.avg_frame_rate) || rate(video.r_frame_rate) || 25) * 1000) / 1000,125 videoCodec: video.codec_name ?? "inconnu", audioCodec: audio?.codec_name ?? null,126 bitrate: Number(data.format?.bit_rate) || null, format: data.format?.format_name ?? "inconnu",127 };128}129130/* ---- Encode ---- */131132export interface TranscodeResult {133 duration: number; renditions: { height: number; width: number; bandwidth: number; codecs: string }[];134 files: { hls: string; mp4: string; poster: string; thumbs: string[] }; bytes: number;135}136export interface TranscodeOptions {137 master: string; outDir: string; probe: Probe; ladder?: Rung[]; preset?: string; crf?: number;138 timeoutMs: number; signal?: AbortSignal; onProgress?: (fraction: number, step: string) => void;139}140const SEGMENT = 4;141142async function codecsOf(segment: string, hasAudio: boolean, signal?: AbortSignal): Promise<string> {143 const out = (await runProgram(env.ffprobe, ["-v", "error", "-select_streams", "v:0", "-show_entries", "stream=profile,level", "-of", "json", segment], { timeoutMs: 30_000, signal })).stdout;144 const s = (JSON.parse(out) as { streams?: { profile?: string; level?: number }[] }).streams?.[0];145 const idc = /high/i.test(s?.profile ?? "") ? "6400" : /baseline/i.test(s?.profile ?? "") ? "42e0" : "4d40";146 return `avc1.${idc}${(s?.level ?? 30).toString(16).padStart(2, "0")}${hasAudio ? ",mp4a.40.2" : ""}`;147}148149export async function transcode(o: TranscodeOptions): Promise<TranscodeResult> {150 const { probe: p, outDir } = o, rungs = ladderFor(p.height, o.ladder), hasAudio = p.audioCodec !== null;151 if (!rungs.length) throw new PermanentJobError("Aucune définition de sortie possible pour cette vidéo.");152 const preset = o.preset ?? env.x264Preset, crf = String(o.crf ?? 21);153 await mkdir(outDir, { recursive: true });154 for (const r of rungs) await mkdir(join(outDir, `v${r.height}`), { recursive: true });155 await mkdir(join(outDir, "thumbs"), { recursive: true });156 // The fallback is the best rendition that a phone on a poor connection can still play: at most 720 lines.157 const fallback = [...rungs].reverse().find((r) => r.height <= 720) ?? rungs[0]!;158 const video = (r: Rung) => ["-c:v", "libx264", "-preset", preset, "-profile:v", r.height >= 720 ? "high" : "main", "-crf", crf, "-maxrate", `${r.videoKbps}k`, "-bufsize", `${r.videoKbps * 2}k`,159 "-force_key_frames", `expr:gte(t,n_forced*${SEGMENT})`, "-sc_threshold", "0", "-pix_fmt", "yuv420p"];160 const audio = (r: Rung) => (hasAudio ? ["-c:a", "aac", "-b:a", `${r.audioKbps}k`, "-ac", "2", "-ar", "48000"] : []);161 const maps = (label: string) => ["-map", `[${label}]`, ...(hasAudio ? ["-map", "0:a:0"] : [])];162 const labels = rungs.map((r) => `v${r.height}`);163 const filter = [`[0:v:0]split=${rungs.length + 1}${labels.map((l) => `[s${l}]`).join("")}[smp4]`, ...rungs.map((r) => `[sv${r.height}]scale=-2:${r.height}:flags=bicubic[v${r.height}]`), `[smp4]scale=-2:${fallback.height}:flags=bicubic[mp4]`].join(";");164 const args = ["-hide_banner", "-loglevel", "error", "-nostdin", "-y", "-progress", "pipe:1", "-nostats", "-i", o.master, "-filter_complex", filter, "-map_metadata", "-1", "-sn", "-dn",165 ...rungs.flatMap((r) => [...maps(`v${r.height}`), ...video(r), ...audio(r), "-f", "hls", "-hls_time", String(SEGMENT), "-hls_playlist_type", "vod", "-hls_segment_filename", join(outDir, `v${r.height}`, "seg_%05d.ts"), join(outDir, `v${r.height}`, "index.m3u8")]),166 ...maps("mp4"), ...video(fallback), ...audio(fallback), "-movflags", "+faststart", join(outDir, "fallback.mp4")];167 o.onProgress?.(0.02, `encodage (${rungs.map((r) => `${r.height}p`).join(", ")})`);168 await runProgram(env.ffmpeg, args, {169 timeoutMs: o.timeoutMs, signal: o.signal,170 onStdout: (line) => { const m = /^out_time_(?:us|ms)=(\d+)/.exec(line); if (m) o.onProgress?.(0.02 + 0.9 * Math.min(1, Number(m[1]) / 1e6 / p.duration), `encodage (${rungs.map((r) => `${r.height}p`).join(", ")})`); },171 });172173 o.onProgress?.(0.93, "affiche et vignettes");174 const mp4 = join(outDir, "fallback.mp4"), at = Math.min(3, p.duration * 0.1);175 await runProgram(env.ffmpeg, ["-hide_banner", "-loglevel", "error", "-nostdin", "-y", "-ss", at.toFixed(2), "-i", mp4, "-frames:v", "1", "-q:v", "3", join(outDir, "poster.jpg")], { timeoutMs: 120_000, signal: o.signal });176 const every = Math.max(1, p.duration / 12);177 await runProgram(env.ffmpeg, ["-hide_banner", "-loglevel", "error", "-nostdin", "-y", "-i", mp4, "-vf", `fps=1/${every.toFixed(3)},scale=320:-2`, "-frames:v", "12", "-q:v", "6", join(outDir, "thumbs", "t_%03d.jpg")], { timeoutMs: Math.max(120_000, o.timeoutMs / 4), signal: o.signal });178179 o.onProgress?.(0.97, "liste de lecture");180 const renditions: TranscodeResult["renditions"] = [];181 for (const r of rungs) {182 const dir = join(outDir, `v${r.height}`), segs = (await readdir(dir)).filter((f) => f.endsWith(".ts")).sort();183 if (!segs.length) throw new Error(`Aucun segment produit pour la définition ${r.height}p.`);184 // BANDWIDTH is the measured peak: the heaviest segment over the duration the playlist gives it.185 const playlist = await readFile(join(dir, "index.m3u8"), "utf8"), durations = [...playlist.matchAll(/#EXTINF:([\d.]+)/g)].map((m) => Number(m[1]));186 const sizes = await Promise.all(segs.map(async (f) => (await stat(join(dir, f))).size));187 const peak = Math.max(...sizes.map((s, i) => (s * 8) / Math.max(durations[i] ?? SEGMENT, 0.5)));188 renditions.push({ height: r.height, width: even((p.width * r.height) / p.height), bandwidth: Math.ceil(peak / 1000) * 1000, codecs: await codecsOf(join(dir, segs[0]!), hasAudio, o.signal) });189 }190 await writeFile(join(outDir, "master.m3u8"), ["#EXTM3U", "#EXT-X-VERSION:3", "#EXT-X-INDEPENDENT-SEGMENTS",191 ...renditions.flatMap((r) => [`#EXT-X-STREAM-INF:BANDWIDTH=${r.bandwidth},RESOLUTION=${r.width}x${r.height},CODECS="${r.codecs}"`, `v${r.height}/index.m3u8`]), ""].join("\n"));192193 const thumbs = (await readdir(join(outDir, "thumbs"))).filter((f) => f.endsWith(".jpg")).sort().map((f) => `thumbs/${f}`);194 const total = async (d: string): Promise<number> => (await Promise.all((await readdir(d, { withFileTypes: true })).map(async (e) => (e.isDirectory() ? total(join(d, e.name)) : (await stat(join(d, e.name))).size)))).reduce((a, b) => a + b, 0);195 const out = await probe(mp4, { signal: o.signal, maxSeconds: Infinity });196 return { duration: Math.round(out.duration * 1000) / 1000, renditions, files: { hls: "master.m3u8", mp4: "fallback.mp4", poster: "poster.jpg", thumbs }, bytes: await total(outDir) };197}198