Repository Public
1import { mkdir, rm, writeFile } from "node:fs/promises";2import path from "node:path";3import { BRAND_TEXT, type Cue, type Lang, type Ratio } from "../lib/contracts";4import type { Canvas } from "@napi-rs/canvas";5import { renderEndCard, renderWatermark } from "./brand";6import { easeInCubic, easeInOutSine, easeOutCubic, easeOutExpo, ellipsize, fitText, font, hashString, lerp, newCanvas, prog, renderCanvasVideo, roundRect, wrapText, type Ctx } from "./canvas";7import { INK, kindOf } from "./design";8import { ff, intermediateArgs, pipeFrames, probe, run, runBinary } from "./ffmpeg";910/**11 * Montage : conformation des plans, assemblage du programme, master final.12 *13 * Générations d'encodage : source → conformClip (H.264 CRF 12) → assembleProgram (CRF 12) → finishMaster (encodage de diffusion).14 * Les deux intermédiaires sont visuellement sans perte ; l'audio reste en PCM jusqu'au master.15 */1617const f3 = (n: number) => n.toFixed(3);18const even = (n: number) => Math.max(2, Math.round(n / 2) * 2);19const STEREO = "aresample=48000,aformat=sample_fmts=fltp:channel_layouts=stereo";20/**21 * Préparation d'un calque RGBA avant `overlay` : il est converti en YUV + alpha, et l'incrustation se fait en YUV (`format=yuv420`).22 * Avec `format=auto`, FFmpeg faisait passer TOUTE l'image de fond par un aller-retour de matrice couleur : les teintes saturées de la23 * vidéo changeaient dès qu'un titre, un sous-titre ou le filigrane était posé dessus (écart mesuré : 5,6 / 255 en moyenne sur une mire).24 */25const OVERLAY_IN = "format=yuva420p";2627// ── habillage des plans réels : titre bas d'écran, crédit ────────────────────28interface LowerThird { x: number; y: number; w: number; h: number; bar: number; padX: number; padY: number; size: number; lh: number; lines: string[]; radius: number }29function lowerThirdLayout(W: number, H: number, raw: string): LowerThird {30 const kind = kindOf(W, H);31 const u = Math.min(W, H) / 1080;32 const { ctx } = newCanvas(8, 8);33 const x = W * (kind === "wide" ? 0.06 : 0.07);34 const bottom = H * (kind === "wide" ? 0.775 : kind === "tall" ? 0.66 : 0.74);35 const padX = 30 * u, padY = 20 * u, bar = Math.max(3, 6 * u);36 const fit = fitText(ctx, raw.trim(), { weight: 600, max: 46 * u, min: 30 * u, maxWidth: W * (kind === "wide" ? 0.6 : 0.84) - 2 * padX - bar, maxLines: 2, letterSpacing: (px) => -px * 0.01 });37 ctx.font = font(600, fit.size);38 ctx.letterSpacing = `${(-fit.size * 0.01).toFixed(2)}px`;39 const lh = fit.size * 1.24;40 const tw = Math.max(...fit.lines.map((l) => ctx.measureText(l).width));41 const w = tw + 2 * padX + bar, h = fit.lines.length * lh + 2 * padY - fit.size * 0.08;42 return { x, y: bottom - h, w, h, bar, padX, padY, size: fit.size, lh, lines: fit.lines, radius: 12 * u };43}44/**45 * Dessine le titre bas d'écran à l'instant `t` d'un plan de durée `dur` : le filet or pousse, la plaque s'ouvre de gauche à droite,46 * le texte monte ligne à ligne derrière un masque ; sortie symétrique avant la fin du plan. Plaque sombre à 82 % + liseré clair :47 * lisible sur une image claire comme sombre.48 */49function drawLowerThird(ctx: Ctx, L: LowerThird, t: number, dur: number): void {50 const k = Math.min(1, dur / 3);51 const t0 = Math.min(0.35, dur * 0.1);52 const out = easeInCubic(prog(t, dur - 0.5 * k - Math.min(0.12, dur * 0.04), 0.5 * k));53 const barP = easeOutExpo(prog(t, t0, 0.45 * k)) * (1 - out);54 const plateP = easeOutExpo(prog(t, t0 + 0.12 * k, 0.75 * k)) * (1 - out);55 if (barP <= 0.001) return;56 ctx.save();57 if (plateP > 0.001) {58 ctx.save();59 ctx.beginPath();60 ctx.rect(L.x - 2, L.y - 2, (L.w + 4) * plateP, L.h + 4);61 ctx.clip();62 roundRect(ctx, L.x, L.y, L.w, L.h, L.radius);63 ctx.fillStyle = "rgba(11,12,15,0.82)";64 ctx.fill();65 ctx.strokeStyle = "rgba(255,255,255,0.12)";66 ctx.lineWidth = Math.max(1, L.bar / 5);67 ctx.stroke();68 ctx.restore();69 }70 ctx.fillStyle = INK.gold;71 const bh = (L.h - 2 * L.radius * 0.9) * barP;72 roundRect(ctx, L.x + L.bar * 1.6, L.y + (L.h - bh) / 2, L.bar, bh, L.bar / 2);73 ctx.fill();74 ctx.font = font(600, L.size);75 ctx.letterSpacing = `${(-L.size * 0.01).toFixed(2)}px`;76 ctx.textAlign = "left";77 ctx.textBaseline = "alphabetic";78 L.lines.forEach((line, i) => {79 const p = easeOutExpo(prog(t, t0 + (0.28 + i * 0.1) * k, 0.7 * k)) * (1 - out);80 if (p <= 0.001) return;81 const base = L.y + L.padY + L.size * 0.86 + i * L.lh;82 ctx.save();83 ctx.beginPath();84 ctx.rect(L.x, base - L.size * 1.0, L.w, L.size * 1.34);85 ctx.clip();86 ctx.globalAlpha *= Math.min(1, p * 1.5);87 ctx.fillStyle = INK.text;88 ctx.fillText(line, L.x + L.bar * 2.6 + L.padX, base + (1 - p) * L.size * 0.9);89 ctx.restore();90 });91 ctx.restore();92}9394/** PNG pleine trame transparent : titre bas d'écran dans son état posé (aperçus, tests). Le rendu vidéo, lui, est animé. */95export async function renderLowerThird(o: { width: number; height: number; text: string }): Promise<Buffer> {96 const { canvas, ctx } = newCanvas(o.width, o.height);97 drawLowerThird(ctx, lowerThirdLayout(o.width, o.height, o.text), 1.5, 3);98 return canvas.encode("png");99}100101interface Credit { x: number; y: number; w: number; h: number; size: number; text: string; pad: number }102/**103 * Crédit de source à l'écran (« Image : … · licence ») : petite pastille discrète. 16:9 et 1:1 : coin bas droit, SOUS la bande des104 * sous-titres ; 9:16 : à gauche, entre le titre bas d'écran et la bande des sous-titres (le bas de l'écran y est couvert par les applis).105 */106function creditLayout(W: number, H: number, raw: string): Credit {107 const kind = kindOf(W, H);108 const u = Math.min(W, H) / 1080;109 const { ctx } = newCanvas(8, 8);110 const size = 21 * u, pad = 11 * u;111 ctx.font = font(500, size);112 const text = ellipsize(ctx, raw.trim().replace(/\s+/g, " "), W * (kind === "wide" ? 0.5 : 0.82) - 2 * pad);113 const w = ctx.measureText(text).width + 2 * pad, h = size * 1.62;114 return kind === "tall"115 ? { x: W * 0.07, y: H * 0.672, w, h, size, text, pad }116 : { x: W * 0.975 - w, y: H * 0.975 - h, w, h, size, text, pad };117}118function drawCredit(ctx: Ctx, C: Credit, t: number, dur: number): void {119 const a = easeOutCubic(prog(t, Math.min(0.5, dur * 0.12), 0.5)) * (1 - easeInCubic(prog(t, dur - 0.4, 0.3)));120 if (a <= 0.003) return;121 ctx.save();122 ctx.globalAlpha *= a;123 roundRect(ctx, C.x, C.y, C.w, C.h, C.h / 2.6);124 ctx.fillStyle = "rgba(11,12,15,0.55)";125 ctx.fill();126 ctx.font = font(500, C.size);127 ctx.letterSpacing = "0px";128 ctx.textAlign = "left";129 ctx.textBaseline = "alphabetic";130 ctx.fillStyle = "rgba(242,243,245,0.9)";131 ctx.fillText(C.text, C.x + C.pad, C.y + C.h / 2 + C.size * 0.35);132 ctx.restore();133}134135// ── cadrage : recadrage ou fond flouté ───────────────────────────────────────136export type FitMode = "auto" | "crop" | "blur";137export interface Framing {138 mode: "crop" | "blur";139 /** Part de l'image source conservée par un recadrage plein cadre (1 = même ratio). */140 kept: number;141 /** Rectangle du sujet dans la trame (plein cadre en mode `crop`). */142 fg: { x: number; y: number; w: number; h: number };143 /** Facteur d'échelle appliqué à la source pour le sujet. */144 scale: number;145}146/** Seuil du mode automatique : sous 62 % d'image conservée, le recadrage coupe trop le sujet → fond flouté. */147export const BLUR_FIT_BELOW = 0.62;148/**149 * Choisit le cadrage d'une source `sw`×`sh` dans une trame `W`×`H`.150 * - `crop` : recadrage centré plein cadre (comportement historique) ;151 * - `blur` : la source entière (au plus 22 % rognés dans le sens du débord, pour qu'elle occupe mieux la trame) posée au centre sur sa152 * propre copie agrandie et floutée ;153 * - `auto` : `blur` si le recadrage garderait moins de 62 % de l'image (16:9 → 9:16 n'en garde que 32 %, 16:9 → 1:1 56 %), ou si une154 * IMAGE est trop petite pour remplir la trame sans agrandissement visible (`maxUpscale`, 1,35 par défaut) ; sinon `crop`.155 * Une image n'est jamais agrandie au-delà de `maxUpscale` : trop petite, elle est présentée à sa taille sur le fond flouté.156 */157export function chooseFraming(sw: number, sh: number, W: number, H: number, mode: FitMode = "auto", o: { maxUpscale?: number } = {}): Framing {158 const cover = Math.max(W / sw, H / sh), contain = Math.min(W / sw, H / sh);159 const kept = contain / cover;160 const maxUp = o.maxUpscale ?? Infinity;161 const blur = mode === "blur" || (mode === "auto" && (kept < BLUR_FIT_BELOW || cover > maxUp));162 if (!blur) return { mode: "crop", kept, fg: { x: 0, y: 0, w: W, h: H }, scale: cover };163 const scale = Math.min(cover, contain / 0.78, maxUp);164 const even2 = (n: number) => Math.max(2, Math.round(n / 2) * 2);165 const w = Math.min(W, even2(sw * scale)), h = Math.min(H, even2(sh * scale));166 return { mode: "blur", kept, fg: { x: Math.round((W - w) / 2 / 2) * 2, y: Math.round((H - h) / 2 / 2) * 2, w, h }, scale };167}168169/** Ombre portée + liseré autour du sujet en mode fond flouté (calque statique transparent). */170function fgFrame(W: number, H: number, fg: Framing["fg"], radius: number): Canvas {171 const { canvas, ctx } = newCanvas(W, H);172 const u = Math.min(W, H) / 1080;173 ctx.save();174 // l'ombre seule : on dessine le rectangle puis on l'efface, il ne reste que le flou autour175 ctx.shadowColor = "rgba(0,0,0,0.6)";176 ctx.shadowBlur = 46 * u;177 ctx.shadowOffsetY = 14 * u;178 roundRect(ctx, fg.x, fg.y, fg.w, fg.h, radius);179 ctx.fillStyle = "#000";180 ctx.fill();181 ctx.restore();182 ctx.globalCompositeOperation = "destination-out";183 roundRect(ctx, fg.x, fg.y, fg.w, fg.h, radius);184 ctx.fill();185 ctx.globalCompositeOperation = "source-over";186 roundRect(ctx, fg.x + 0.5, fg.y + 0.5, fg.w - 1, fg.h - 1, radius);187 ctx.strokeStyle = "rgba(255,255,255,0.16)";188 ctx.lineWidth = Math.max(1, 1.5 * u);189 ctx.stroke();190 return canvas;191}192193/** Étalonnage commun des sources réelles : contraste et saturation légèrement relevés (unifie des sources hétérogènes). */194const GRADE = "eq=contrast=1.06:saturation=1.08:gamma=0.98";195const VIGNETTE = "vignette=angle=0.42";196197// ── conformClip ──────────────────────────────────────────────────────────────198export interface ConformOptions {199 input: string; output: string; srcIn: number; seconds: number; width: number; height: number; fps: number;200 sourceAudio: "mute" | "duck" | "full"; hasAudio: boolean; isImage?: boolean; kenBurns?: boolean; onScreenText?: string; language: Lang;201 /** Crédit de source affiché discrètement à l'écran (« Image : Auteur · CC BY 4.0 »). */202 credit?: string;203 /** Cadrage : `auto` (défaut) choisit le fond flouté quand le recadrage perdrait trop d'image ; `crop` / `blur` pour forcer. */204 fit?: FitMode;205 /** Étalonnage léger + vignettage (défaut : oui). */206 grade?: boolean;207 /** Graine du mouvement Ken Burns (sens et amplitude). Par défaut : dérivée du nom du fichier et de la durée. */208 seed?: number;209}210211/**212 * Conforme un plan : extrait [srcIn, srcIn + seconds] d'une vidéo, ou image fixe (Ken Burns en sous-pixel si `kenBurns`), cadré vers213 * `width`×`height` (recadrage centré ou fond flouté, voir `chooseFraming`), étalonné, `fps` constant, exactement214 * round(seconds × fps) trames, audio 48 kHz stéréo. Habillage facultatif : titre bas d'écran animé (`onScreenText`), crédit (`credit`).215 *216 * Audio : `mute` (ou source sans piste, ou image) → silence ; `duck` / `full` → son de la source, niveau inchangé. Le mode est217 * inscrit dans la métadonnée `sp_source_audio` du fichier : `assembleProgram` s'en sert pour router le son (`duck` passe sous la voix,218 * `full` reste au premier plan).219 * Si la source est plus courte que demandé, la dernière image est prolongée et le son complété par du silence.220 */221export async function conformClip(o: ConformOptions): Promise<void> {222 if (!(o.seconds > 0)) throw new Error("conformClip : durée invalide");223 if (o.isImage) return conformStill(o);224 const { width: W, height: H, fps } = o;225 const frames = Math.max(1, Math.round(o.seconds * fps));226 const dur = frames / fps;227 const audioMode = !o.hasAudio ? "mute" : o.sourceAudio;228 const grade = o.grade ?? true;229 const src = await probe(o.input);230 const rotated = Math.abs(src.rotation ?? 0) % 180 === 90;231 const sw = (rotated ? src.height : src.width) || W, sh = (rotated ? src.width : src.height) || H;232 const fr = chooseFraming(sw, sh, W, H, o.fit ?? "auto");233 const tail = `tpad=stop_mode=clone:stop_duration=${f3(dur)},trim=end_frame=${frames},setpts=PTS-STARTPTS`;234 const inputs: string[] = ["-ss", f3(Math.max(0, o.srcIn)), "-i", o.input];235 const graph: string[] = [];236 let next = 1;237 let framePng: string | null = null;238 if (fr.mode === "crop") {239 graph.push(`[0:v:0]scale=${W}:${H}:force_original_aspect_ratio=increase:flags=lanczos,crop=${W}:${H},setsar=1,fps=${fps},${tail}${grade ? `,${GRADE},${VIGNETTE}` : ""},format=yuv420p[base]`);240 } else {241 const bw = even(W / 8), bh = even(H / 8);242 framePng = `${o.output}.frame.png`;243 await writeFile(framePng, await fgFrame(W, H, fr.fg, 0).encode("png"));244 inputs.push("-loop", "1", "-framerate", String(fps), "-t", f3(dur), "-i", framePng);245 graph.push(`[0:v:0]fps=${fps},${tail},setsar=1,split=2[s0][s1]`);246 // fond : la source elle-même, agrandie pour couvrir, floutée (calcul au 1/8), assombrie et un peu plus saturée247 graph.push(`[s0]scale=${bw}:${bh}:force_original_aspect_ratio=increase:flags=bilinear,crop=${bw}:${bh},gblur=sigma=4.5,scale=${W}:${H}:flags=bicubic,eq=saturation=1.2:contrast=0.92,lutyuv=y=16+(val-16)*0.56,format=yuv420p[bg]`);248 graph.push(`[s1]scale=${fr.fg.w}:${fr.fg.h}:force_original_aspect_ratio=increase:flags=lanczos,crop=${fr.fg.w}:${fr.fg.h}${grade ? `,${GRADE}` : ""},format=yuv420p[fg]`);249 graph.push(`[bg][fg]overlay=${fr.fg.x}:${fr.fg.y}:format=yuv420[c0]`, `[${next}:v]${OVERLAY_IN}[fr]`, `[c0][fr]overlay=0:0:format=yuv420:eof_action=pass,format=yuv420p[base]`);250 next++;251 }252 // habillage animé (titre bas d'écran, crédit) : bandeau RGBA dessiné au canvas, envoyé trame à trame253 const text = o.onScreenText?.trim(), credit = o.credit?.trim();254 const lt = text ? lowerThirdLayout(W, H, text) : null, cr = credit ? creditLayout(W, H, credit) : null;255 let vOut = "[base]";256 let strip: { y: number; h: number; index: number } | null = null;257 if (lt || cr) {258 const top = Math.max(0, Math.floor(Math.min(lt ? lt.y - 6 : H, cr ? cr.y - 4 : H) / 2) * 2);259 const bottom = Math.min(H, Math.ceil(Math.max(lt ? lt.y + lt.h + 6 : 0, cr ? cr.y + cr.h + 4 : 0) / 2) * 2);260 strip = { y: top, h: bottom - top, index: next };261 graph.push(`[${next}:v]${OVERLAY_IN}[hab]`, `[base][hab]overlay=0:${top}:format=yuv420:eof_action=pass,format=yuv420p[vt]`);262 vOut = "[vt]";263 next++;264 }265 const edge = Math.min(0.02, dur / 4);266 let silence: string[] = [];267 if (audioMode === "mute") {268 silence = ["-f", "lavfi", "-t", f3(dur), "-i", "anullsrc=r=48000:cl=stereo"];269 graph.push(`[${next}:a:0]atrim=duration=${f3(dur)}[a]`);270 } else {271 graph.push(`[0:a:0]${STEREO},apad,atrim=duration=${f3(dur)},asetpts=PTS-STARTPTS,afade=t=in:st=0:d=${f3(edge)},afade=t=out:st=${f3(dur - edge)}:d=${f3(edge)}[a]`);272 }273 const out = ["-filter_complex", graph.join(";"), "-map", vOut, "-map", "[a]", "-frames:v", String(frames), "-t", f3(dur), "-metadata", `sp_source_audio=${audioMode}`, ...intermediateArgs(fps, o.output)];274 try {275 if (!strip) { await ff([...inputs, ...silence, ...out]); return; }276 const s = strip;277 const { canvas, ctx } = newCanvas(W, s.h);278 let i = 0;279 await pipeFrames({280 width: W, height: s.h, fps,281 args: (raw) => [...inputs, ...raw, ...silence, ...out],282 next: () => {283 if (i >= frames) return null;284 ctx.clearRect(0, 0, W, s.h);285 ctx.save();286 ctx.translate(0, -s.y);287 if (lt) drawLowerThird(ctx, lt, i / fps, dur);288 if (cr) drawCredit(ctx, cr, i / fps, dur);289 ctx.restore();290 i++;291 return canvas.data();292 },293 });294 } finally {295 if (framePng) await rm(framePng, { force: true });296 }297}298299/** Décode une image en RGBA brut à la taille voulue (FFmpeg : tous formats, orientation EXIF, rééchantillonnage Lanczos). */300async function decodeImage(input: string, vf: string, w: number, h: number): Promise<Canvas> {301 const buf = await runBinary("ffmpeg", ["-hide_banner", "-nostdin", "-v", "error", "-i", input, "-frames:v", "1", "-vf", `${vf},format=rgba`, "-f", "rawvideo", "-pix_fmt", "rgba", "-"], 300_000);302 if (buf.length < w * h * 4) throw new Error(`conformClip : image illisible (${input})`);303 const { canvas, ctx } = newCanvas(w, h);304 const img = ctx.createImageData(w, h);305 img.data.set(buf.subarray(0, w * h * 4));306 ctx.putImageData(img, 0, 0);307 return canvas;308}309310/** Mouvements Ken Burns : zoom avant, zoom arrière, travellings avec léger zoom. Valeurs = (échelle, décalage en fraction du jeu disponible). */311const KB_MOVES: { z0: number; z1: number; x0: number; x1: number; y0: number; y1: number }[] = [312 { z0: 1.0, z1: 1.085, x0: 0, x1: 0.25, y0: 0, y1: -0.2 }, // zoom avant, dérive vers le haut droit313 { z0: 1.085, z1: 1.0, x0: -0.25, x1: 0, y0: 0.2, y1: 0 }, // zoom arrière314 { z0: 1.07, z1: 1.09, x0: -0.85, x1: 0.85, y0: 0, y1: 0 }, // travelling gauche → droite315 { z0: 1.09, z1: 1.07, x0: 0.85, x1: -0.85, y0: 0, y1: 0 }, // travelling droite → gauche316 { z0: 1.0, z1: 1.085, x0: 0, x1: -0.25, y0: 0, y1: 0.2 }, // zoom avant, dérive vers le bas gauche317 { z0: 1.06, z1: 1.09, x0: 0, x1: 0, y0: 0.8, y1: -0.8 }, // travelling bas → haut318];319const KB_MAX = 1.09;320321/**322 * Image fixe : rendue trame par trame au canvas. Le mouvement (Ken Burns) est calculé en flottants et rééchantillonné à chaque trame :323 * aucun arrondi entier des coordonnées, donc aucun tremblement (défaut de `zoompan`). L'image de travail est préparée une seule fois324 * (Lanczos) à la taille maximale utile ; elle n'est donc jamais agrandie pendant le mouvement.325 */326async function conformStill(o: ConformOptions): Promise<void> {327 const { width: W, height: H, fps } = o;328 const frames = Math.max(1, Math.round(o.seconds * fps));329 const dur = frames / fps;330 const u = Math.min(W, H) / 1080;331 const grade = o.grade ?? true;332 const src = await probe(o.input);333 if (!src.width || !src.height) throw new Error(`conformClip : image illisible (${o.input})`);334 const moving = o.kenBurns ?? true;335 const zMax = moving ? KB_MAX : 1;336 const fr = chooseFraming(src.width, src.height, W, H, o.fit ?? "auto", { maxUpscale: 1.35 });337 // image de travail : couvre le rectangle du sujet au zoom maximal338 const need = Math.max((fr.fg.w * zMax) / src.width, (fr.fg.h * zMax) / src.height);339 const ws = Math.min(need, Math.max(fr.scale * zMax, 1));340 const iw = even(src.width * ws), ih = even(src.height * ws);341 const g = grade ? `,${GRADE}` : "";342 const image = await decodeImage(o.input, `scale=${iw}:${ih}:flags=lanczos${g}`, iw, ih);343 let bg: Canvas | null = null, shadow: Canvas | null = null;344 const radius = 14 * u;345 if (fr.mode === "blur") {346 const bw = even(W / 8), bh = even(H / 8);347 bg = await decodeImage(o.input, `scale=${bw}:${bh}:force_original_aspect_ratio=increase:flags=bilinear,crop=${bw}:${bh},gblur=sigma=4.5,eq=saturation=1.2:contrast=0.92,lutyuv=y=16+(val-16)*0.56`, bw, bh);348 shadow = fgFrame(W, H, fr.fg, radius);349 }350 const seed = o.seed ?? hashString(`${path.basename(o.input)}:${frames}`);351 const move = KB_MOVES[seed % KB_MOVES.length];352 const text = o.onScreenText?.trim(), credit = o.credit?.trim();353 const lt = text ? lowerThirdLayout(W, H, text) : null, cr = credit ? creditLayout(W, H, credit) : null;354 // échelle de base : l'image de travail couvre le sujet à z = 1355 const base = Math.max(fr.fg.w / iw, fr.fg.h / ih);356 const cx = fr.fg.x + fr.fg.w / 2, cy = fr.fg.y + fr.fg.h / 2;357 const vignette = (ctx: Ctx) => {358 const v = ctx.createRadialGradient(W / 2, H / 2, Math.min(W, H) * 0.42, W / 2, H / 2, Math.hypot(W, H) * 0.56);359 v.addColorStop(0, "rgba(0,0,0,0)");360 v.addColorStop(1, "rgba(0,0,0,0.3)");361 ctx.fillStyle = v;362 ctx.fillRect(0, 0, W, H);363 };364 await renderCanvasVideo({365 width: W, height: H, fps, seconds: dur, output: o.output, outputArgs: ["-metadata", "sp_source_audio=mute"],366 draw: (ctx, t) => {367 const x = frames > 1 ? t / ((frames - 1) / fps) : 0;368 // progression quasi linéaire, à peine adoucie aux extrémités : le mouvement ne s'arrête jamais dans le plan369 const p = moving ? 0.8 * x + 0.2 * easeInOutSine(x) : 0;370 const z = moving ? lerp(move.z0, move.z1, p) : 1;371 const s = base * z;372 // jeu disponible autour du sujet à cette échelle (l'image ne découvre jamais ses bords)373 const slackX = Math.max(0, (iw * s - fr.fg.w) / 2), slackY = Math.max(0, (ih * s - fr.fg.h) / 2);374 const dx = moving ? lerp(move.x0, move.x1, p) * slackX : 0, dy = moving ? lerp(move.y0, move.y1, p) * slackY : 0;375 ctx.imageSmoothingEnabled = true;376 ctx.imageSmoothingQuality = "high";377 if (bg && shadow) {378 const bz = 1.06 + (moving ? 0.04 * p : 0);379 ctx.drawImage(bg, W / 2 - (W * bz) / 2, H / 2 - (H * bz) / 2, W * bz, H * bz);380 ctx.drawImage(shadow, 0, 0);381 ctx.save();382 roundRect(ctx, fr.fg.x, fr.fg.y, fr.fg.w, fr.fg.h, radius);383 ctx.clip();384 ctx.drawImage(image, cx - (iw * s) / 2 + dx, cy - (ih * s) / 2 + dy, iw * s, ih * s);385 ctx.restore();386 } else {387 ctx.drawImage(image, cx - (iw * s) / 2 + dx, cy - (ih * s) / 2 + dy, iw * s, ih * s);388 if (grade) vignette(ctx);389 }390 if (lt) drawLowerThird(ctx, lt, t, dur);391 if (cr) drawCredit(ctx, cr, t, dur);392 },393 });394}395396// ── ligne de temps du programme ──────────────────────────────────────────────397export const DISSOLVE_SECONDS = 0.5;398export const FADE_SECONDS = 0.3;399/** Transitions acceptées par `assembleProgram` (sur-ensemble de `Transition` des contrats). */400export type SceneTransition = "cut" | "fade" | "dissolve" | "dip" | "wipe" | "blur";401/** Transitions qui CHEVAUCHENT la scène précédente (elles raccourcissent le programme, comme `dissolve`) → filtre xfade. */402const XFADE: Partial<Record<SceneTransition, string>> = { dissolve: "fade", wipe: "smoothleft", blur: "hblur" };403const overlapping = (t: SceneTransition) => t in XFADE;404/** Transitions en fondu par une couleur, sans incidence sur la durée : noir (`fade`) ou fond de marque (`dip`). */405const THROUGH: Partial<Record<SceneTransition, string>> = { fade: "black", dip: "0x0b0c0f" };406407export interface ProgramTimeline {408 /** Durée réelle du programme (après chevauchement des fondus enchaînés). */409 seconds: number;410 /** Début réel de chaque scène. */411 starts: number[];412 /** Début nominal de chaque scène (somme des durées précédentes, sans chevauchement). */413 nominalStarts: number[];414 durations: number[];415 /** Chevauchement à l'entrée de chaque scène (0 sauf `dissolve`). */416 overlaps: number[];417 /** Convertit un temps nominal en temps réel du programme. */418 mapTime: (nominal: number) => number;419}420421/**422 * CONVENTION DES TRANSITIONS — `scenes[i].transition` décrit l'ENTRÉE dans la scène i :423 * - `cut` : coupe franche, aucune incidence sur la durée ;424 * - `fade` : fondu au noir (la scène précédente s'éteint sur ses 0,3 dernières secondes, la scène i s'ouvre du noir en 0,3 s),425 * aucune incidence sur la durée ; sur la première scène : ouverture du noir ;426 * - `dissolve` : fondu enchaîné de 0,5 s (au plus 40 % de la plus courte des deux scènes) qui CHEVAUCHE la fin de la scène427 * précédente : le programme est raccourci d'autant ; sur la première scène : équivaut à `fade` ;428 * - `dip` : comme `fade`, mais par le fond de marque #0b0c0f au lieu du noir (raccord naturel vers ou depuis une animation,429 * dont le décor est de cette teinte) ; aucune incidence sur la durée ;430 * - `wipe` : volet doux de droite à gauche (bord estompé), même chevauchement et même effet sur la durée que `dissolve` ;431 * - `blur` : fondu enchaîné avec flou horizontal (effet de filé), même chevauchement que `dissolve`.432 * Les trois premières valeurs sont celles du contrat `Transition` ; `dip`, `wipe` et `blur` sont des extensions facultatives.433 *434 * CONVENTION DE LA NARRATION — `narration[].at` est exprimé sur la ligne de temps NOMINALE (somme des durées des scènes, comme si435 * tout était en coupe franche). `assembleProgram` le convertit avec `mapTime` : une voix prévue 0,2 s après le début nominal d'une436 * scène démarre 0,2 s après son début réel. Pour placer des sous-titres, utiliser `programTimeline(...).mapTime` ou les valeurs437 * `narrationAt` renvoyées par `assembleProgram`.438 */439export function programTimeline(scenes: { seconds: number; transition: SceneTransition }[], fps = 30): ProgramTimeline {440 const q = (s: number) => Math.max(1, Math.round(s * fps)) / fps;441 const durations = scenes.map((s) => q(s.seconds));442 const starts: number[] = [], nominalStarts: number[] = [], overlaps: number[] = [];443 let t = 0, nominal = 0;444 scenes.forEach((s, i) => {445 const ov = i > 0 && overlapping(s.transition) ? Math.max(1, Math.round(Math.min(DISSOLVE_SECONDS, 0.4 * Math.min(durations[i - 1], durations[i])) * fps)) / fps : 0;446 overlaps.push(ov);447 t -= ov;448 starts.push(t);449 nominalStarts.push(nominal);450 t += durations[i];451 nominal += durations[i];452 });453 const mapTime = (x: number) => {454 let i = 0;455 while (i + 1 < scenes.length && x >= nominalStarts[i + 1] - 1e-9) i++;456 return Math.max(0, starts[i] + (x - nominalStarts[i]));457 };458 return { seconds: t, starts, nominalStarts, durations, overlaps, mapTime };459}460461// ── assembleProgram ──────────────────────────────────────────────────────────462/**463 * Enchaîne les scènes conformées (transitions : voir `programTimeline`), mixe narration + son des sources + musique facultative.464 *465 * Mixage : voix à 0 dB ; son des scènes `duck` (×0,7), musique (×`music.gain`, 0,22 par défaut — prévu pour une musique du commerce466 * masterisée fort ; 0,5 convient à la nappe de `renderMusicBed`, livrée à −20 LUFS —, en boucle, fondus 0,8 s / 1,5 s) et effets467 * sonores (`sfx`, instants sur la ligne de temps NOMINALE comme la narration, ×`gain`, 0,5 par défaut) passent dans un compresseur468 * asservi à la voix (sidechaincompress, seuil −30 dB, rapport 8:1, relâchement 450 ms) ; son des scènes `full` hors compresseur ;469 * limiteur final à −1 dBFS (pas d'écrêtage). La normalisation de sonie est faite par `finishMaster`.470 *471 * Sortie : intermédiaire (H.264 CRF 12 + PCM), `.mkv` recommandé. Renvoie la durée RÉELLE (mesurée) et, en supplément du contrat,472 * les débuts réels des scènes et des narrations.473 */474export async function assembleProgram(o: { scenes: { file: string; seconds: number; transition: SceneTransition }[]; narration: { file: string; at: number }[]; music?: { file: string; gain?: number } | null; sfx?: { file: string; at: number; gain?: number }[]; output: string; workDir: string }): Promise<{ seconds: number; sceneStarts: number[]; narrationAt: number[]; overlaps: number[] }> {475 if (!o.scenes.length) throw new Error("assembleProgram : aucune scène");476 await mkdir(o.workDir, { recursive: true });477 const probes = await Promise.all(o.scenes.map((s) => probe(s.file)));478 const first = probes[0];479 if (!first.hasVideo) throw new Error(`assembleProgram : ${o.scenes[0].file} n'a pas de piste vidéo`);480 const fps = Math.round(first.fps) || 30;481 const W = first.width, H = first.height;482 // Les durées réelles des fichiers font foi (conformClip quantifie à la trame).483 const tl = programTimeline(o.scenes.map((s, i) => ({ seconds: probes[i].videoDuration || probes[i].duration || s.seconds, transition: s.transition })), fps);484 const nominal = programTimeline(o.scenes, fps);485 const total = tl.seconds;486 const n = o.scenes.length;487 const tr = (i: number): SceneTransition => (i <= 0 || i >= n ? "cut" : o.scenes[i].transition);488 /** Couleur du fondu d'ouverture de la scène i (null = pas de fondu). Une transition chevauchante sur la première scène = `fade`. */489 const opens = (i: number) => THROUGH[o.scenes[i].transition] ?? (i === 0 && overlapping(o.scenes[i].transition) ? "black" : null);490 const fadeDur = (i: number) => Math.min(FADE_SECONDS, tl.durations[i] * 0.3);491492 const inputs: string[] = o.scenes.flatMap((s) => ["-i", s.file]);493 const graph: string[] = [];494495 // vidéo496 o.scenes.forEach((s, i) => {497 const d = tl.durations[i];498 const chain = [`scale=${W}:${H}:force_original_aspect_ratio=increase`, `crop=${W}:${H}`, "setsar=1", `fps=${fps}`, `trim=end_frame=${Math.round(d * fps)}`, "setpts=PTS-STARTPTS", "format=yuv420p"];499 const inColor = opens(i), outColor = THROUGH[tr(i + 1)];500 if (inColor) chain.push(`fade=t=in:st=0:d=${f3(fadeDur(i))}:color=${inColor}`);501 if (outColor) chain.push(`fade=t=out:st=${f3(d - fadeDur(i))}:d=${f3(fadeDur(i))}:color=${outColor}`);502 chain.push("settb=AVTB");503 graph.push(`[${i}:v:0]${chain.join(",")}[v${i}]`);504 });505 // segments séparés par les fondus enchaînés506 const segments: { label: string; seconds: number; overlap: number; xfade: string }[] = [];507 let group: number[] = [];508 const flush = (overlap: number, xfade = "fade") => {509 if (!group.length) return;510 const label = `seg${segments.length}`;511 const seconds = group.reduce((a, i) => a + tl.durations[i], 0);512 if (group.length === 1) graph.push(`[v${group[0]}]null[${label}]`);513 else graph.push(`${group.map((i) => `[v${i}]`).join("")}concat=n=${group.length}:v=1:a=0,fps=${fps},settb=AVTB[${label}]`);514 segments.push({ label, seconds, overlap, xfade });515 group = [];516 };517 let pendingOverlap = 0, pendingXfade = "fade";518 o.scenes.forEach((sc, i) => {519 if (tl.overlaps[i] > 0) { flush(pendingOverlap, pendingXfade); pendingOverlap = tl.overlaps[i]; pendingXfade = XFADE[sc.transition] ?? "fade"; }520 group.push(i);521 });522 flush(pendingOverlap, pendingXfade);523 let acc = segments[0].label, accSeconds = segments[0].seconds;524 segments.slice(1).forEach((seg, k) => {525 const out = `x${k}`;526 graph.push(`[${acc}][${seg.label}]xfade=transition=${seg.xfade}:duration=${f3(seg.overlap)}:offset=${f3(accSeconds - seg.overlap)},fps=${fps},settb=AVTB[${out}]`);527 acc = out;528 accSeconds += seg.seconds - seg.overlap;529 });530 graph.push(`[${acc}]format=yuv420p[v]`);531532 // audio533 const ms = (s: number) => Math.max(0, Math.round(s * 1000));534 const duckBus: string[] = [], fullBus: string[] = [];535 o.scenes.forEach((_, i) => {536 const mode = (probes[i].tags?.sp_source_audio ?? (probes[i].hasAudio ? "duck" : "mute")) as "mute" | "duck" | "full";537 if (mode === "mute" || !probes[i].hasAudio) return;538 const d = tl.durations[i];539 const fin = tl.overlaps[i] > 0 ? tl.overlaps[i] : opens(i) ? fadeDur(i) : 0.015;540 const fout = i + 1 < n && tl.overlaps[i + 1] > 0 ? tl.overlaps[i + 1] : THROUGH[tr(i + 1)] ? fadeDur(i) : 0.015;541 graph.push(`[${i}:a:0]${STEREO},atrim=duration=${f3(d)},asetpts=PTS-STARTPTS,afade=t=in:st=0:d=${f3(fin)},afade=t=out:st=${f3(d - fout)}:d=${f3(fout)},volume=${mode === "duck" ? 0.7 : 1},adelay=${ms(tl.starts[i])}:all=1[sa${i}]`);542 (mode === "duck" ? duckBus : fullBus).push(`[sa${i}]`);543 });544 let idx = n;545 const narrationAt: number[] = [];546 const narr: string[] = [];547 // temps nominal → scène → temps réel548 const real = (nominalAt: number) => {549 let si = 0;550 while (si + 1 < n && nominalAt >= nominal.nominalStarts[si + 1] - 1e-9) si++;551 return Math.max(0, tl.starts[si] + (nominalAt - nominal.nominalStarts[si]));552 };553 o.narration.forEach((nr, k) => {554 inputs.push("-i", nr.file);555 const at = real(nr.at);556 narrationAt.push(at);557 graph.push(`[${idx}:a:0]${STEREO},adelay=${ms(at)}:all=1[n${k}]`);558 narr.push(`[n${k}]`);559 idx++;560 });561 if (o.music?.file) {562 inputs.push("-stream_loop", "-1", "-i", o.music.file);563 const fo = Math.min(1.5, total / 4);564 graph.push(`[${idx}:a:0]${STEREO},atrim=duration=${f3(total)},asetpts=PTS-STARTPTS,volume=${Math.max(0, o.music.gain ?? 0.22).toFixed(4)},afade=t=in:st=0:d=${f3(Math.min(0.8, total / 4))},afade=t=out:st=${f3(total - fo)}:d=${f3(fo)}[mus]`);565 duckBus.push("[mus]");566 idx++;567 }568 (o.sfx ?? []).forEach((fx, k) => {569 const at = real(fx.at);570 if (at >= total - 0.05) return;571 inputs.push("-i", fx.file);572 graph.push(`[${idx}:a:0]${STEREO},volume=${Math.max(0, fx.gain ?? 0.5).toFixed(4)},adelay=${ms(at)}:all=1[fx${k}]`);573 duckBus.push(`[fx${k}]`);574 idx++;575 });576 const mixOf = (labels: string[], out: string) => graph.push(labels.length === 1 ? `${labels[0]}anull[${out}]` : `${labels.join("")}amix=inputs=${labels.length}:normalize=0:dropout_transition=0:duration=longest[${out}]`);577 const finals: string[] = [];578 const pad = `apad=whole_dur=${f3(total)},atrim=duration=${f3(total)}`;579 if (narr.length) {580 mixOf(narr, "narrmix");581 if (duckBus.length) {582 graph.push(`[narrmix]${pad},asplit=2[narr][key]`);583 mixOf(duckBus, "bedraw");584 graph.push(`[bedraw]${pad}[bedpad]`);585 graph.push(`[bedpad][key]sidechaincompress=threshold=0.03:ratio=8:attack=20:release=450:makeup=1[bed]`);586 finals.push("[narr]", "[bed]");587 } else finals.push("[narrmix]");588 } else if (duckBus.length) { mixOf(duckBus, "bed"); finals.push("[bed]"); }589 if (fullBus.length) { mixOf(fullBus, "full"); finals.push("[full]"); }590 if (!finals.length) {591 inputs.push("-f", "lavfi", "-t", f3(total), "-i", "anullsrc=r=48000:cl=stereo");592 graph.push(`[${idx}:a:0]anull[a]`);593 } else {594 mixOf(finals, "premix");595 graph.push(`[premix]alimiter=limit=0.891:attack=5:release=60:level=false,${STEREO.replace("fltp", "s16")},${pad}[a]`);596 }597598 await ff([...inputs, "-filter_complex", graph.join(";"), "-map", "[v]", "-map", "[a]", "-map_metadata", "-1", "-t", f3(total), ...intermediateArgs(fps, o.output)], 1_800_000);599 const out = await probe(o.output);600 return { seconds: out.duration, sceneStarts: tl.starts, narrationAt, overlaps: tl.overlaps };601}602603/**604 * Place des effets sonores sur des débuts de scène : renvoie la liste `sfx` attendue par `assembleProgram` (temps NOMINAUX).605 * `lead` = avance de l'effet sur la coupe (0,34 s pour le souffle de `renderSfx`, dont le point fort est à 0,34 s ; 0 pour un tic).606 */607export function sceneSfx(scenes: { seconds: number }[], picks: { index: number; file: string; lead?: number; gain?: number }[], fps = 30): { file: string; at: number; gain?: number }[] {608 const starts: number[] = [];609 scenes.reduce((t, s) => { starts.push(t); return t + Math.max(1, Math.round(s.seconds * fps)) / fps; }, 0);610 return picks.filter((p) => p.index >= 0 && p.index < scenes.length).map((p) => {611 // l'avance reste dans la scène précédente (jamais avant son début : la conversion nominal → réel resterait exacte)612 const floor = p.index > 0 ? starts[p.index - 1] : 0;613 return { file: p.file, at: Math.max(floor, starts[p.index] - (p.lead ?? 0)), gain: p.gain };614 });615}616617// ── sous-titres incrustés (facultatif) ───────────────────────────────────────618/**619 * Bande des sous-titres incrustés : bas de l'image, au-dessus des interfaces sociales en 9:16 (20 % du bas laissés libres), sous le620 * titre bas d'écran et loin du filigrane (haut). Hauteur : deux lignes au corps du ratio.621 */622function captionBand(width: number, height: number): { y: number; h: number } {623 const kind = kindOf(width, height);624 const h = even(Math.min(width, height) * 0.17);625 const bottom = height * (kind === "tall" ? 0.2 : kind === "wide" ? 0.06 : 0.07);626 return { y: Math.round(height - bottom - h), h };627}628/**629 * Mise en page d'une réplique : corps généreux (plus grand en 9:16, lu sur mobile), deux lignes au plus. Le texte est recoupé à la630 * largeur utile (les retours à la ligne fournis sont respectés s'ils tiennent) ; s'il ne tient pas en deux lignes, le corps est réduit631 * jusqu'à 80 %, puis la réplique est découpée en PAGES successives de deux lignes — jamais de texte écrasé, tronqué ni hors cadre.632 */633function captionPages(ctx: Ctx, text: string, width: number, bandH: number, kind: "wide" | "tall" | "square"): { size: number; pages: string[][] } {634 const u = bandH / (1080 * 0.17);635 const base = (kind === "tall" ? 52 : kind === "square" ? 48 : 46) * u;636 const maxW = width * (kind === "wide" ? 0.74 : 0.86) - 48 * u;637 const given = text.trim().split("\n").map((l) => l.trim()).filter(Boolean);638 let size = base, lines: string[] = [];639 for (;;) {640 ctx.font = font(600, size);641 lines = given.length <= 2 && given.every((l) => ctx.measureText(l).width <= maxW) ? given : wrapText(ctx, given.join(" "), maxW);642 if (lines.length <= 2 || size <= base * 0.8) break;643 size *= 0.96;644 }645 if (lines.length <= 2) return { size, pages: [lines] };646 size = base * 0.9;647 ctx.font = font(600, size);648 lines = wrapText(ctx, given.join(" "), maxW);649 const pages: string[][] = [];650 for (let i = 0; i < lines.length; i += 2) pages.push(lines.slice(i, i + 2));651 // pas de dernière page d'un seul mot : on rééquilibre avec la précédente652 const last = pages[pages.length - 1];653 if (pages.length > 1 && last.length === 1 && last[0].split(" ").length < 3) { const prev = pages[pages.length - 2]; last.unshift(prev.pop()!); }654 return { size, pages };655}656/** Une page de sous-titre : plaque sombre arrondie (78 %) + texte Inter SemiBold clair, calée en bas de la bande. */657async function captionPng(width: number, bandH: number, lines: string[] | null, size: number, active?: { line: number; word: number } | null, done?: { line: number; word: number } | null): Promise<Buffer> {658 const { canvas, ctx } = newCanvas(width, bandH);659 if (lines?.length) {660 const u = bandH / (1080 * 0.17);661 ctx.font = font(600, size);662 const lh = size * 1.26;663 const tw = Math.max(...lines.map((l) => ctx.measureText(l).width));664 const padX = 24 * u, padY = 13 * u;665 const w = tw + 2 * padX, h = lines.length * lh + 2 * padY - size * 0.06;666 const y = bandH - h;667 roundRect(ctx, (width - w) / 2, y, w, h, 16 * u);668 ctx.fillStyle = "rgba(11,12,15,0.78)";669 ctx.fill();670 ctx.fillStyle = INK.text;671 ctx.textAlign = "center";672 if (!active) lines.forEach((l, i) => ctx.fillText(l, width / 2, y + padY + size * 0.9 + i * lh));673 else {674 // Sous-titre animé : les mots déjà dits sont pleins, le mot en cours est en or sur une pastille, les mots à venir sont atténués.675 const space = ctx.measureText(" ").width;676 ctx.textAlign = "left";677 lines.forEach((l, i) => {678 const ws = l.split(" "), lw = ctx.measureText(l).width, by = y + padY + size * 0.9 + i * lh;679 let x = width / 2 - lw / 2;680 ws.forEach((wd, k) => {681 const ww = ctx.measureText(wd).width, isActive = i === active.line && k === active.word, past = i < active.line || (i === active.line && k < active.word);682 if (isActive) { roundRect(ctx, x - 7 * u, by - size * 0.92, ww + 14 * u, size * 1.22, 9 * u); ctx.fillStyle = "rgba(232,194,122,0.2)"; ctx.fill(); }683 ctx.fillStyle = isActive ? "#f8d68c" : past ? INK.text : "rgba(242,243,245,0.5)";684 ctx.fillText(wd, x, by);685 x += ww + space;686 });687 });688 void done;689 }690 }691 return canvas.encode("png");692}693/** Fabrique une liste ffconcat de bandeaux PNG (un par page de réplique, bandeau vide entre deux) couvrant [0, total]. */694async function buildCaptionTrack(cues: (Cue & { words?: { start: number; end: number; text: string }[] })[], o: { width: number; height: number; total: number; workDir: string }): Promise<{ list: string; y: number } | null> {695 const sorted = cues.filter((c) => c.end > c.start && c.start < o.total && c.text.trim()).sort((a, b) => a.start - b.start);696 if (!sorted.length) return null;697 const band = captionBand(o.width, o.height);698 const kind = kindOf(o.width, o.height);699 const probeCtx = newCanvas(8, 8).ctx;700 const dir = path.join(o.workDir, "captions");701 await mkdir(dir, { recursive: true });702 const blank = path.join(dir, "blank.png");703 await writeFile(blank, await captionPng(o.width, band.h, null, 0));704 const lines = ["ffconcat version 1.0"];705 const add = (file: string, d: number) => { if (d > 0.001) lines.push(`file '${file.replace(/'/g, "'\\''")}'`, `duration ${d.toFixed(3)}`); };706 let t = 0;707 for (const [i, c] of sorted.entries()) {708 const start = Math.max(c.start, t), end = Math.min(c.end, o.total, sorted[i + 1]?.start ?? Infinity);709 if (end <= start) continue;710 add(blank, start - t);711 // une réplique trop longue pour deux lignes est affichée en pages successives, au prorata du nombre de caractères712 const { size, pages } = captionPages(probeCtx, c.text, o.width, band.h, kind);713 const chars = pages.map((p) => p.join(" ").length), sum = chars.reduce((a, b) => a + b, 0) || 1;714 let at = start;715 // Sous-titre animé : si la réplique porte ses mots minutés et qu'ils correspondent au texte affiché, une image par mot.716 const flat = pages.flatMap((pg, k) => pg.flatMap((ln, li) => ln.split(" ").map((_, wi) => ({ page: k, line: li, word: wi }))));717 const kw = c.words && c.words.length === flat.length ? c.words : null;718 if (kw) {719 for (const [n, pos] of flat.entries()) {720 const ws = Math.max(start, Math.min(end, kw[n].start)), we = n === flat.length - 1 ? end : Math.max(ws, Math.min(end, kw[n + 1].start));721 if (n === 0 && ws > at) { const f0 = path.join(dir, `cue-${String(i).padStart(4, "0")}-pre.png`); await writeFile(f0, await captionPng(o.width, band.h, pages[0], size, { line: 0, word: -1 })); add(f0, ws - at); at = ws; }722 const file = path.join(dir, `cue-${String(i).padStart(4, "0")}-w${String(n).padStart(3, "0")}.png`);723 await writeFile(file, await captionPng(o.width, band.h, pages[pos.page], size, { line: pos.line, word: pos.word }));724 add(file, Math.max(0, we - at)); at = Math.max(at, we);725 }726 } else for (const [k, page] of pages.entries()) {727 const d = k === pages.length - 1 ? end - at : ((end - start) * chars[k]) / sum;728 const file = path.join(dir, `cue-${String(i).padStart(4, "0")}-${k}.png`);729 await writeFile(file, await captionPng(o.width, band.h, page, size));730 add(file, d);731 at += d;732 }733 t = end;734 }735 add(blank, Math.max(0.04, o.total - t));736 lines.push(`file '${blank.replace(/'/g, "'\\''")}'`); // le démultiplexeur concat ignore la durée du dernier fichier : on le répète737 const list = path.join(dir, "captions.ffconcat");738 await writeFile(list, lines.join("\n"));739 return { list, y: band.y };740}741742// ── finishMaster ─────────────────────────────────────────────────────────────743interface Loudness { input_i: string; input_tp: string; input_lra: string; input_thresh: string; target_offset: string }744async function measureLoudness(file: string): Promise<Loudness | null> {745 const { stderr } = await run("ffmpeg", ["-hide_banner", "-nostdin", "-i", file, "-vn", "-map", "0:a:0", "-af", "loudnorm=I=-14:TP=-1.5:LRA=11:print_format=json", "-f", "null", "-"], 900_000);746 const m = stderr.match(/\{[^{}]*"input_i"[^{}]*\}/);747 if (!m) return null;748 const j = JSON.parse(m[0]) as Loudness;749 const i = Number(j.input_i);750 return Number.isFinite(i) && i > -60 && Number.isFinite(Number(j.input_tp)) ? j : null;751}752753export const LOUDNESS_TARGET = { integrated: -14, truePeak: -1.5 } as const;754755/**756 * DERNIÈRE étape d'encodage de tout fichier livré : programme + carton de fin, filigrane `clip.spboucher.ai` sur TOUTE la durée757 * (carton compris ; `endCard.sting` y ajoute la signature sonore), sous-titres incrustés facultatifs (`burnCaptions`, temps du programme), sonie normalisée en deux passes758 * (−14 LUFS intégré, −1,5 dBTP ; ignorée si le programme est muet), MP4 H.264 High yuv420p + AAC 48 kHz stéréo, +faststart, métadonnées.759 * `preview` : encodage rapide et léger (veryfast, CRF 27, AAC 128 kb/s), même chaîne de marque.760 * Le programme est recadré vers `width`×`height` s'il n'a pas déjà cette taille (aperçus).761 */762export async function finishMaster(o: { program: string; output: string; width: number; height: number; fps: number; ratio: Ratio; language: Lang; endCard: { seconds: number; tagline: string; sting?: boolean }; preview?: boolean; metadata: Record<string, string>; workDir: string; burnCaptions?: (Cue & { words?: { start: number; end: number; text: string }[] })[] }): Promise<{ seconds: number; watermark: Record<string, unknown> }> {763 await mkdir(o.workDir, { recursive: true });764 const { width: W, height: H, fps } = o;765 if (W % 2 || H % 2) throw new Error("finishMaster : dimensions impaires");766 const p = await probe(o.program);767 if (!p.hasVideo || !(p.duration > 0)) throw new Error("finishMaster : programme illisible");768 const programSeconds = Math.round((p.videoDuration ?? p.duration) * fps) / fps;769 const cardSeconds = Math.max(0, Math.round(o.endCard.seconds * fps) / fps);770771 const wmFile = path.join(o.workDir, "watermark.png");772 const wm = await renderWatermark({ width: W, height: H, ratio: o.ratio });773 await writeFile(wmFile, wm.png);774775 const inputs = ["-i", o.program];776 const graph: string[] = [];777 const norm = `scale=${W}:${H}:force_original_aspect_ratio=increase:flags=lanczos,crop=${W}:${H},setsar=1,fps=${fps},format=yuv420p,settb=AVTB`;778 graph.push(`[0:v:0]${norm},trim=end_frame=${Math.round(programSeconds * fps)},setpts=PTS-STARTPTS[pv]`);779 let idx = 1;780 let video = "[pv]";781782 const captions = o.burnCaptions?.length ? await buildCaptionTrack(o.burnCaptions, { width: W, height: H, total: programSeconds, workDir: o.workDir }) : null;783 if (captions) {784 inputs.push("-f", "concat", "-safe", "0", "-i", captions.list);785 graph.push(`[${idx}:v:0]fps=${fps},${OVERLAY_IN}[cap]`, `${video}[cap]overlay=0:${captions.y}:format=yuv420:eof_action=pass,format=yuv420p,settb=AVTB[pc]`);786 video = "[pc]";787 idx++;788 }789790 // audio du programme (silence s'il n'a pas de piste)791 let progAudio: string;792 if (p.hasAudio) {793 const fo = Math.min(0.12, programSeconds / 4);794 graph.push(`[0:a:0]${STEREO},apad=whole_dur=${f3(programSeconds)},atrim=duration=${f3(programSeconds)},afade=t=out:st=${f3(programSeconds - fo)}:d=${f3(fo)}[pa]`);795 progAudio = "[pa]";796 } else {797 inputs.push("-f", "lavfi", "-t", f3(programSeconds), "-i", "anullsrc=r=48000:cl=stereo");798 graph.push(`[${idx}:a:0]${STEREO}[pa]`);799 progAudio = "[pa]";800 idx++;801 }802803 let audio = progAudio;804 if (cardSeconds > 0) {805 const card = path.join(o.workDir, "endcard.mkv");806 await renderEndCard({ width: W, height: H, language: o.language, tagline: o.endCard.tagline, seconds: cardSeconds, fps, output: card, sting: o.endCard.sting });807 inputs.push("-i", card);808 graph.push(`[${idx}:v:0]fps=${fps},format=yuv420p,setsar=1,settb=AVTB[ev]`, `[${idx}:a:0]${STEREO}[ea]`);809 graph.push(`${video}[ev]concat=n=2:v=1:a=0[pev]`, `${progAudio}[ea]concat=n=2:v=0:a=1[pea]`);810 video = "[pev]";811 audio = "[pea]";812 idx++;813 }814815 // filigrane : dernière couche vidéo, sur toute la durée (programme + carton)816 inputs.push("-i", wmFile);817 graph.push(`[${idx}:v:0]${OVERLAY_IN}[wm]`, `${video}[wm]overlay=0:0:format=yuv420:eof_action=repeat,format=yuv420p[v]`);818 idx++;819820 // sonie : mesure (passe 1) puis normalisation linéaire (passe 2)821 const loud = p.hasAudio ? await measureLoudness(o.program) : null;822 if (loud) {823 const lra = Math.min(50, Math.max(11, Math.ceil(Number(loud.input_lra)) + 1));824 graph.push(`${audio}loudnorm=I=${LOUDNESS_TARGET.integrated}:TP=${LOUDNESS_TARGET.truePeak}:LRA=${lra}:measured_I=${loud.input_i}:measured_TP=${loud.input_tp}:measured_LRA=${loud.input_lra}:measured_thresh=${loud.input_thresh}:offset=${loud.target_offset}:linear=true,${STEREO}[a]`);825 } else {826 graph.push(`${audio}anull[a]`);827 }828829 const metadata = { comment: BRAND_TEXT, ...o.metadata };830 const meta = Object.entries(metadata).flatMap(([k, v]) => ["-metadata", `${k}=${v}`]);831 const venc = o.preview832 ? ["-preset", "veryfast", "-crf", "27"]833 : ["-preset", "medium", "-crf", "18"];834 const total = programSeconds + cardSeconds;835 await ff([...inputs, "-filter_complex", graph.join(";"), "-map", "[v]", "-map", "[a]", "-map_metadata", "-1", "-t", f3(total),836 "-c:v", "libx264", ...venc, "-profile:v", "high", "-pix_fmt", "yuv420p", "-r", String(fps), "-g", String(fps * 2), "-keyint_min", String(fps * 2), "-sc_threshold", "0",837 "-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709",838 "-c:a", "aac", "-b:a", o.preview ? "128k" : "192k", "-ar", "48000", "-ac", "2",839 "-movflags", "+faststart+use_metadata_tags", ...meta, "-f", "mp4", o.output], 3_600_000);840841 const out = await probe(o.output);842 return {843 seconds: out.duration,844 watermark: {845 ...wm.params, programSeconds, endCardStart: programSeconds, endCardSeconds: cardSeconds, preview: !!o.preview,846 loudness: loud ? { measuredI: Number(loud.input_i), measuredTP: Number(loud.input_tp), measuredLRA: Number(loud.input_lra), targetI: LOUDNESS_TARGET.integrated, targetTP: LOUDNESS_TARGET.truePeak } : null,847 burnedCaptions: captions ? o.burnCaptions?.length ?? 0 : 0,848 },849 };850}851