SPB Git

Repository Public

htmlscene.ts 46.5 KB 636 lines typescript

1import { spawn } from "node:child_process";2import { readFile } from "node:fs/promises";3import { existsSync } from "node:fs";4import os from "node:os";5import path from "node:path";6import { chromium, type Browser, type BrowserContext, type CDPSession, type Page } from "playwright-core";7import { transform } from "esbuild";8import { intermediateArgs } from "./ffmpeg";910/**11 * MOTEUR D'ANIMATION HTML — joue une scène HTML + SVG + CSS (écrite par l'agent Animator, donc NON FIABLE) dans Chromium sans tête,12 * de façon déterministe, et en tire des images (JPEG) ou une vidéo au codec intermédiaire du pipeline.13 *14 *  - Déterminisme : un script d'amorçage remplace `Date`, `performance.now`, `requestAnimationFrame`, `setTimeout`, `setInterval`,15 *    `Math.random` et `crypto.getRandomValues` par une HORLOGE VIRTUELLE que seul le moteur fait avancer, trame par trame. À chaque16 *    trame, toutes les animations du document (`document.getAnimations()` : animations et transitions CSS, Web Animations) sont mises17 *    en pause puis positionnées à `temps virtuel − instant de naissance` ; les animations SMIL sont positionnées par `setCurrentTime`.18 *    Même HTML → mêmes images, quel que soit le découpage en pages parallèles.19 *  - Bac à sable : contexte de navigation jetable par page, toute requête est interceptée — seuls le document et le kit20 *    (`https://scene.clip/kit/*`, servi depuis `src/media/scene-kit` et `assets/fonts`) reçoivent une réponse ; CSP stricte ;21 *    service workers, téléchargements, fenêtres et navigation refusés ; taille du HTML plafonnée ; délais sur chaque opération22 *    (un script qui boucle fait échouer la scène et le navigateur est relancé).23 *  - Vitesse : `Page.captureScreenshot` (CDP, JPEG) sur plusieurs pages entrelacées (la page k rend les trames k, k+N, k+2N…),24 *    trames envoyées dans l'ordre à FFmpeg par stdin.25 */2627export const SCENE_ORIGIN = "https://scene.clip";28const SCENE_URL = `${SCENE_ORIGIN}/index.html`;29export const MAX_HTML_BYTES = 400_000;30const KIT_DIR = process.env.CLIP_SCENE_KIT_DIR ?? path.join(/* turbopackIgnore: true */ process.cwd(), "src/media/scene-kit");31const FONT_DIR = process.env.CLIP_FONT_DIR ?? path.join(/* turbopackIgnore: true */ process.cwd(), "assets/fonts");32/** Jointure opaque pour l'empaqueteur (évite le traçage de tout le projet par Turbopack). */33const pj = (...parts: string[]) => path.join(...parts);34const BIN_PATH = `/opt/homebrew/bin:/usr/local/bin:${process.env.PATH ?? ""}`;3536export class HtmlSceneError extends Error {37  constructor(message: string, public code: "too_large" | "timeout" | "load_failed" | "bad_input" | "encode_failed" | "browser", public diagnostics?: SceneDiagnostics) { super(message); }38}3940/** Ce que la scène a fait de travers pendant le rendu : nourrit la boucle de correction de l'Animator. */41export interface SceneDiagnostics {42  /** Exceptions JavaScript non rattrapées (y compris dans les minuteries et rappels d'animation). */43  errors: string[];44  /** `console.error` / `console.warn` de la scène. */45  console: string[];46  /** URL que la scène a tenté de charger et que le bac à sable a refusées. */47  blocked: string[];48}4950export type RatioClass = "wide" | "tall" | "square";51export const ratioClass = (w: number, h: number): RatioClass => (w / h > 1.2 ? "wide" : w / h < 0.85 ? "tall" : "square");5253export interface SafeZones {54  kind: RatioClass;55  /** Rectangle du contenu important (texte, objets clés), en pixels. */56  safe: { x: number; y: number; w: number; h: number };57  /** Zone du filigrane de marque incrusté plus tard par le pipeline (aucun contenu important dedans). */58  watermark: { x: number; y: number; w: number; h: number };59  /** Bande basse réservée aux sous-titres (et aux interfaces sociales en 9:16) : ordonnée de son bord haut. */60  captionTop: number;61}6263/**64 * Zones sûres par format. Bas : aligné sur `captionBand` (compose.ts : bande de deux lignes + marge sociale en 9:16).65 * Filigrane : haut droite en 16:9 et 1:1, haut gauche vers 11 % du haut en 9:16 (brand.ts), avec une garde autour de la plaque.66 */67export function safeZones(width: number, height: number, compact = false): SafeZones {68  const kind = ratioClass(width, height);69  // `compact` (scènes v3) : en paysage, les sous-titres ne sont pas incrustés (piste du lecteur, deux lignes en bas) — la bande réservée passe de70  // 23,5 % à 15 % de la hauteur, ce qui rend au dessin la zone que la v2 laissait vide. En vertical et en carré (sous-titres incrustés), rien ne change.71  const f = kind === "wide" ? { side: 0.055, top: 0.065, bottom: compact ? 0.15 : 0.235 } : kind === "tall" ? { side: 0.07, top: 0.165, bottom: 0.305 } : { side: 0.06, top: 0.065, bottom: 0.245 };72  const r = Math.round;73  const safe = { x: r(width * f.side), y: r(height * f.top), w: r(width * (1 - 2 * f.side)), h: r(height * (1 - f.top - f.bottom)) };74  const watermark = kind === "wide" ? { x: r(width * 0.755), y: 0, w: r(width * 0.245), h: r(height * 0.135) }75    : kind === "tall" ? { x: 0, y: r(height * 0.09), w: r(width * 0.42), h: r(height * 0.065) }76      : { x: r(width * 0.6), y: 0, w: r(width * 0.4), h: r(height * 0.125) };77  return { kind, safe, watermark, captionTop: r(height * (1 - f.bottom)) };78}7980// ── données d'exécution d'une scène v3 (moteur universel) ────────────────────81/**82 * Ce que le pipeline injecte dans une scène v3 (`window.__SCENE`) : la voix RÉELLE (mots alignés, phrases), les repères nommés résolus en83 * secondes, le thème du projet (mémoire visuelle), ses symboles réutilisables, et les données validées d'un calcul. Changer la voix ne84 * demande donc pas de réécrire la scène : on résout de nouveau les repères et on rend.85 */86export interface SceneRuntime {87  v: 3;88  fps?: number;89  words?: { w: string; start: number; end: number }[];90  cues?: { start: number; end: number; text: string }[];91  beats?: Record<string, number>;92  theme?: Record<string, unknown> | null;93  /** Symboles SVG du projet (`<symbol id="o-…">…</symbol>`), ajoutés à la planche du kit. */94  symbols?: string;95  /** Résultat JSON d'un calcul validé (Python en bac à sable ou SKN) : lu par la scène dans `SK.data`. */96  data?: unknown;97}9899// ── document ─────────────────────────────────────────────────────────────────100const kitCache = new Map<string, Promise<Buffer>>();101function kitFile(name: string): Promise<Buffer> {102  let p = kitCache.get(name);103  if (!p || process.env.CLIP_SCENE_KIT_NOCACHE) { p = readFile(pj(KIT_DIR, name)); kitCache.set(name, p); }104  return p;105}106107/** Retire l'enveloppe de document si le modèle en a écrit une : seule la scène (styles, balisage, scripts) est gardée. */108export function sceneFragment(html: string): string {109  return html.replace(/<!doctype[^>]*>/gi, "").replace(/<\/?(html|head|body)\b[^>]*>/gi, "").replace(/<meta\b[^>]*>/gi, "").replace(/<title\b[^>]*>[\s\S]*?<\/title>/gi, "").trim();110}111112const CSP = [113  "default-src 'none'", `script-src 'unsafe-inline' ${SCENE_ORIGIN}/kit/`, `style-src 'unsafe-inline' ${SCENE_ORIGIN}/kit/`, `font-src ${SCENE_ORIGIN}/kit/`,114  "img-src data: blob:", "media-src 'none'", "connect-src 'none'", "frame-src 'none'", "child-src 'none'", "worker-src 'none'", "object-src 'none'",115  "base-uri 'none'", "form-action 'none'",116].join("; ");117118/**119 * Document complet joué par le moteur : kit (feuille de style, bibliothèque, symboles), variables de format, puis la scène dans `#stage`.120 * `kitBase` = préfixe des ressources du kit (`/kit/` dans le moteur ; un chemin `file://` pour un aperçu autonome).121 */122/** Les blocs `<script type="text/typescript">` d'une scène sont transpilés (types retirés, rien n'est exécuté ici) avant d'entrer dans la page. */123export async function transpileScene(html: string): Promise<string> {124  const re = /<script\b([^>]*)\btype\s*=\s*["'](?:text\/typescript|ts|application\/typescript)["']([^>]*)>([\s\S]*?)<\/script>/gi;125  if (!re.test(html)) return html;126  re.lastIndex = 0;127  const parts: string[] = []; let last = 0;128  for (let m = re.exec(html); m; m = re.exec(html)) {129    let js: string;130    try { js = (await transform(m[3], { loader: "ts", target: "es2022", charset: "utf8" })).code; }131    catch (e) { js = `console.error(${JSON.stringify(`TypeScript invalide : ${(e as Error).message.split("\n").slice(0, 3).join(" ")}`)});`; }132    parts.push(html.slice(last, m.index), `<script>${js.replace(/<\/script/gi, "<\\/script")}</script>`);133    last = m.index + m[0].length;134  }135  return parts.join("") + html.slice(last);136}137const symbolsOnly = (svg: string) => (svg.match(/<symbol\b[\s\S]*?<\/symbol>/gi) ?? []).filter((x) => !/<script|\son\w+\s*=|href\s*=\s*["'](?!#)/i.test(x)).join("");138139export async function sceneDocument(o: { html: string; width: number; height: number; seconds: number; kitBase?: string; inline?: boolean; scene?: SceneRuntime | null }): Promise<string> {140  const z = safeZones(o.width, o.height, !!o.scene), base = o.kitBase ?? "/kit/";141  const sprite = (await kitFile("symbols.svg")).toString("utf8");142  const vars = `:root{--w:${o.width}px;--h:${o.height}px;--d:${o.seconds}s;--safe-x:${z.safe.x}px;--safe-y:${z.safe.y}px;--safe-w:${z.safe.w}px;--safe-h:${z.safe.h}px;` +143    `--safe-r:${o.width - z.safe.x - z.safe.w}px;--safe-b:${o.height - z.safe.y - z.safe.h}px;--wm-x:${z.watermark.x}px;--wm-y:${z.watermark.y}px;--wm-w:${z.watermark.w}px;--wm-h:${z.watermark.h}px}`;144  const css = o.inline ? `<style>${(await kitFile("kit.css")).toString("utf8").replaceAll("url(fonts/", `url(${base}fonts/`)}</style>` : `<link rel="stylesheet" href="${base}kit.css">`;145  const js = o.inline ? `<script>${(await kitFile("kit.js")).toString("utf8")}</script>` : `<script src="${base}kit.js"></script>`;146  const rt = o.scene ?? null;147  const safeJson = (v: unknown) => JSON.stringify(v).replace(/</g, "\\u003c").replace(/[\u2028\u2029]/g, "");148  const scene = safeJson({ w: o.width, h: o.height, d: o.seconds, ratio: z.kind, safe: z.safe, watermark: z.watermark, captionTop: z.captionTop,149    ...(rt ? { v: 3, fps: rt.fps ?? 30, words: rt.words ?? [], cues: rt.cues ?? [], beats: rt.beats ?? {}, theme: rt.theme ?? null, data: rt.data ?? null, kitBase: base } : {}) });150  let extra = "", sprite3 = "";151  if (rt) {152    // v3 : thème, équations (KaTeX), calcul scientifique validé (SKN), moteur d'animation étendu, bibliothèque de visualisation. Three.js est chargé à la demande.153    const file = async (n: string) => (await kitFile(n)).toString("utf8");154    extra = (o.inline ? `<style>${(await file("vendor/katex.min.css")).replaceAll("url(fonts/", `url(${base}vendor/fonts/`)}</style><style>${(await file("kit3.css")).replaceAll("url(fonts/", `url(${base}fonts/`)}</style>` : `<link rel="stylesheet" href="${base}vendor/katex.min.css"><link rel="stylesheet" href="${base}kit3.css">`) +155      (await Promise.all(["vendor/katex.min.js", "numerics.js", "kit3.js", "viz.js"].map(async (n) => (existsSync(pj(KIT_DIR, n)) ? (o.inline ? `<script>${(await file(n)).replace(/<\/script/gi, "<\\/script")}</script>` : `<script src="${base}${n}"></script>`) : "")))).join("");156    sprite3 = rt.symbols ? `<svg xmlns="http://www.w3.org/2000/svg" id="sk-project-symbols">${symbolsOnly(rt.symbols)}</svg>` : "";157  }158  const body = rt ? await transpileScene(sceneFragment(o.html)) : sceneFragment(o.html);159  return `<!doctype html><html lang="fr" class="r-${z.kind}"><head><meta charset="utf-8">${css}<style>${vars}</style><script>window.__SCENE=${scene}</script>${js}${extra}</head>` +160    `<body><div id="sk-sprite" aria-hidden="true">${sprite}${sprite3}</div><div id="stage" class="sk-stage">${body}</div></body></html>`;161}162163/** Aperçu autonome (kit en ligne, polices par `file://`) : s'ouvre dans un vrai navigateur et joue en temps réel. Pour le débogage. */164export const standaloneDocument = (o: { html: string; width: number; height: number; seconds: number; scene?: SceneRuntime | null }) =>165  sceneDocument({ ...o, inline: true, kitBase: `file://${FONT_DIR.replace(/fonts\/?$/, "")}` });166167/** Source de l'horloge virtuelle, pour l'aperçu interactif du studio (même moteur que le rendu, piloté par messages). */168export const virtualClockSource = (seed = 0x5eed1e) => `globalThis.__name = globalThis.__name || ((f) => f);globalThis.__clipSettle = 0;(${virtualClock.toString()})(${seed});`;169170// ── horloge virtuelle (injectée avant tout script de la page) ────────────────171function virtualClock(seed: number): void {172  const w = window as unknown as Record<string, unknown>;173  const EPOCH = 1767225600000;174  let now = 0, frame = -1, nextId = 1, started = false;175  const errors: string[] = [];176  const report = (e: unknown) => { if (errors.length < 30) errors.push(e instanceof Error ? `${e.name}: ${e.message}` : String(e)); };177  const RealDate = Date, realRaf = window.requestAnimationFrame.bind(window);178  class VirtualDate extends RealDate {179    constructor(...a: unknown[]) { if (a.length === 0) super(EPOCH + now); else super(...(a as [number])); }180    static now() { return EPOCH + now; }181  }182  w.Date = VirtualDate;183  performance.now = () => now;184  let s = seed >>> 0;185  const rand = () => { s = (s + 0x6d2b79f5) | 0; let t = Math.imul(s ^ (s >>> 15), 1 | s); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };186  Math.random = rand;187  crypto.getRandomValues = ((a: ArrayBufferView) => { const b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength); for (let i = 0; i < b.length; i++) b[i] = Math.floor(rand() * 256); return a; }) as typeof crypto.getRandomValues;188  crypto.randomUUID = (() => { const h = Array.from({ length: 32 }, () => Math.floor(rand() * 16).toString(16)).join(""); return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-a${h.slice(17, 20)}-${h.slice(20, 32)}`; }) as typeof crypto.randomUUID;189190  interface Timer { at: number; fn: (...a: unknown[]) => void; args: unknown[]; every: number; seq: number }191  const timers = new Map<number, Timer>();192  let rafs = new Map<number, (t: number) => void>();193  const add = (fn: unknown, delay: unknown, args: unknown[], repeat: boolean) => {194    const d = Math.max(repeat ? 1 : 0, Number(delay) || 0), id = nextId++;195    if (typeof fn === "function") timers.set(id, { at: now + d, fn: fn as Timer["fn"], args, every: repeat ? d : 0, seq: id });196    return id;197  };198  w.setTimeout = (fn: unknown, d?: unknown, ...a: unknown[]) => add(fn, d, a, false);199  w.setInterval = (fn: unknown, d?: unknown, ...a: unknown[]) => add(fn, d, a, true);200  w.clearTimeout = w.clearInterval = (id: number) => { timers.delete(id); };201  w.requestAnimationFrame = (fn: (t: number) => void) => { const id = nextId++; rafs.set(id, fn); return id; };202  w.cancelAnimationFrame = (id: number) => { rafs.delete(id); };203204  const birth = new WeakMap<Animation, number>();205  const nativeAnimate = Element.prototype.animate;206  Element.prototype.animate = function (this: Element, ...a: Parameters<Element["animate"]>) { const an = nativeAnimate.apply(this, a); birth.set(an, now); return an; };207  /** Adopte les animations apparues depuis le dernier passage (naissance = temps virtuel courant) et positionne toutes les autres. */208  const sync = () => {209    for (const an of document.getAnimations()) {210      let b = birth.get(an);211      if (b === undefined) { b = now; birth.set(an, b); }212      try { if (an.playState !== "paused") an.pause(); an.currentTime = now - b; } catch (e) { report(e); }213    }214    for (const svg of document.querySelectorAll("svg")) {215      try { if (!svg.animationsPaused()) svg.pauseAnimations(); svg.setCurrentTime(now / 1000); } catch { /* svg imbriqué sans horloge */ }216    }217  };218  const MAX_CALLBACKS = 20000;219  const runTimers = (until: number) => {220    for (let n = 0; ; n++) {221      let next: Timer | null = null, nextKey = 0;222      for (const [k, t] of timers) if (t.at <= until && (!next || t.at < next.at || (t.at === next.at && t.seq < next.seq))) { next = t; nextKey = k; }223      if (!next) return;224      if (n > MAX_CALLBACKS) { timers.clear(); report(new Error("trop de minuteries dans une même trame (boucle setTimeout/setInterval ?)")); return; }225      if (next.every) next.at += next.every; else timers.delete(nextKey);226      now = Math.max(now, Math.min(until, next.every ? next.at - next.every : next.at));227      try { next.fn(...next.args); } catch (e) { report(e); }228      sync();229    }230  };231  const tick = (t: number) => {232    runTimers(t);233    now = t;234    const cbs = rafs; rafs = new Map();235    for (const fn of cbs.values()) { try { fn(now); } catch (e) { report(e); } }236    sync();237  };238  w.__clip = {239    /** Avance jusqu'à la trame `target` (incluse) à `fps` trames par seconde, sans en sauter une seule. */240    seek(target: number, fps: number) {241      if (!started) { started = true; frame = 0; tick(0); }242      while (frame < target) { frame++; tick((frame * 1000) / fps); }243      // Attend que le navigateur ait réellement produit une image avec cet état (deux rafraîchissements réels) avant la capture.244      // Avant la capture, on laisse le navigateur produire une vraie image avec cet état : sans cela, la rastérisation des calques245      // animés dépend des images précédentes (≈ 30 px d'anticrénelage différents selon le découpage en pages). Coût mesuré : le rendu246      // 1080p passe de ≈ 0,9× à ≈ 1,4× le temps réel. CLIP_HTMLSCENE_SETTLE=0 retire cette attente (plus rapide, non strictement déterministe).247      const settle = (window as unknown as { __clipSettle?: number }).__clipSettle ?? 1;248      if (settle === 0) return now;249      return new Promise<number>((res) => { if (settle === 1) realRaf(() => res(now)); else realRaf(() => realRaf(() => res(now))); });250    },251    errors: () => errors.splice(0),252    now: () => now,253  };254  window.addEventListener("error", (e) => report(e.error ?? e.message));255  window.addEventListener("unhandledrejection", (e) => report(e.reason));256}257258// ── navigateur partagé ───────────────────────────────────────────────────────259/**260 * Réserve de navigateurs : un processus Chromium plafonne vers 20 captures 1080p par seconde quel que soit le nombre de pages261 * (un seul compositeur) ; plusieurs processus se cumulent presque linéairement. Les pages sont réparties à tour de rôle.262 */263const BROWSERS = Math.max(1, Math.min(8, Number(process.env.CLIP_HTMLSCENE_BROWSERS) || Math.min(3, Math.max(1, Math.floor(os.availableParallelism() / 4)))));264/** Deux parcs : `cpu` (SwiftShader, reproductible partout — toute la 2D) et `gpu` (ANGLE Metal, réservé aux scènes WebGL : ≈ 15× plus rapide en 3D). */265type Pool = "cpu" | "gpu";266const pools: Record<Pool, (Promise<Browser> | null)[]> = { cpu: new Array(BROWSERS).fill(null), gpu: new Array(BROWSERS).fill(null) };267const nextBrowser: Record<Pool, number> = { cpu: 0, gpu: 0 };268/** `CLIP_CHROMIUM_GPU` : `auto` (défaut : Metal pour les scènes WebGL sur macOS), `metal` (toujours), `off` (jamais : SwiftShader partout). */269const GPU_MODE = (process.env.CLIP_CHROMIUM_GPU ?? "auto") as "auto" | "metal" | "off";270export const usesWebgl = (html: string) => /SK\.three\s*\(|getContext\(\s*["'](?:webgl|experimental-webgl)/.test(html);271const poolFor = (html: string): Pool => (GPU_MODE === "metal" || (GPU_MODE === "auto" && process.platform === "darwin" && usesWebgl(html)) ? "gpu" : "cpu");272const LAUNCH_ARGS = ["--force-color-profile=srgb", "--font-render-hinting=none", "--disable-lcd-text", "--hide-scrollbars", "--mute-audio",273  "--disable-background-networking", "--disable-background-timer-throttling", "--disable-renderer-backgrounding", "--disable-backgrounding-occluded-windows",274  "--disable-extensions", "--disable-sync", "--no-first-run", "--disable-features=Translate,MediaRouter,PaintHolding",275  // Rastérisation indépendante de l'historique des images précédentes (sinon l'anticrénelage dépend des zones repeintes).276  "--disable-partial-raster", "--disable-threaded-animation", "--disable-threaded-scrolling", "--disable-checker-imaging", "--disable-image-animation-resync",277  "--run-all-compositor-stages-before-draw", "--disable-new-content-rendering-timeout",278  ...(process.env.CLIP_CHROMIUM_ARGS?.split(" ").filter(Boolean) ?? [])];279280function browser(pool: Pool = "cpu"): Promise<Browser> {281  const browserPool = pools[pool], slot = nextBrowser[pool]++ % BROWSERS;282  let p = browserPool[slot];283  if (!p) {284    p = chromium.launch({ headless: true, executablePath: process.env.CLIP_CHROMIUM_PATH || undefined, args: [...LAUNCH_ARGS, ...(pool === "gpu" ? ["--use-angle=metal", "--enable-gpu", "--ignore-gpu-blocklist"] : ["--enable-unsafe-swiftshader"])] })285      .then((b) => { b.on("disconnected", () => { if (browserPool[slot] === p) browserPool[slot] = null; }); return b; })286      .catch((e: Error) => { if (browserPool[slot] === p) browserPool[slot] = null; throw new HtmlSceneError(`Chromium indisponible (${e.message.split("\n")[0]}). Installer : pnpm exec playwright-core install chromium-headless-shell`, "browser"); });287    browserPool[slot] = p;288  }289  return p;290}291/** Capacités de rendu réellement mesurées dans le navigateur de ce nœud (WebGL, moteur de rendu, taille de texture). */292export async function renderCapabilities(): Promise<{ chromium: string; webgl2: boolean; renderer: string; maxTexture: number; gpu: "metal" | "swiftshader"; browsers: number; pages: number }> {293  const gpu: Pool = GPU_MODE !== "off" && process.platform === "darwin" ? "gpu" : "cpu";294  const b = await browser(gpu), ctx = await b.newContext();295  try {296    const page = await ctx.newPage();297    const r = await page.evaluate(() => {298      const gl = document.createElement("canvas").getContext("webgl2");299      if (!gl) return { webgl2: false, renderer: "", maxTexture: 0 };300      const ext = gl.getExtension("WEBGL_debug_renderer_info");301      return { webgl2: true, renderer: String(ext ? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL) : "?"), maxTexture: Number(gl.getParameter(gl.MAX_TEXTURE_SIZE)) };302    });303    return { chromium: b.version(), ...r, gpu: /Metal/i.test(r.renderer) ? "metal" : "swiftshader", browsers: BROWSERS, pages: MAX_PAGES };304  } finally { await ctx.close().catch(() => undefined); }305}306/** Ferme les navigateurs partagés (fin de worker, fin de test). Sans effet s'ils ne sont pas lancés. */307export async function closeBrowser(): Promise<void> {308  const all = [...pools.cpu, ...pools.gpu];309  pools.cpu.fill(null); pools.gpu.fill(null);310  await Promise.all(all.map(async (p) => { if (p) { try { await (await p).close(); } catch { /* déjà fermé */ } } }));311}312313/** Nombre de pages de rendu simultanées, tous appels confondus. */314const MAX_PAGES = Math.max(1, Number(process.env.CLIP_HTMLSCENE_PAGES) || Math.min(12, Math.max(2, os.availableParallelism() - 2)));315/** Pages entrelacées par rendu, par défaut : deux par navigateur. */316const DEFAULT_PAGES = Math.min(MAX_PAGES, BROWSERS * 2);317let pagesInUse = 0;318const waiters: (() => void)[] = [];319async function acquirePage(): Promise<void> { if (pagesInUse < MAX_PAGES) { pagesInUse++; return; } await new Promise<void>((r) => waiters.push(r)); }320function releasePage(): void { const next = waiters.shift(); if (next) next(); else pagesInUse--; }321322const OP_TIMEOUT = Number(process.env.CLIP_HTMLSCENE_OP_TIMEOUT_MS) || 20_000;323function withTimeout<T>(p: Promise<T>, ms: number, what: string): Promise<T> {324  let timer: NodeJS.Timeout;325  return Promise.race([p, new Promise<never>((_, rej) => { timer = setTimeout(() => rej(new HtmlSceneError(`Délai dépassé (${ms} ms) : ${what}`, "timeout")), ms); })]).finally(() => clearTimeout(timer));326}327328const MIME: Record<string, string> = { ".css": "text/css; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".svg": "image/svg+xml", ".ttf": "font/ttf", ".otf": "font/otf", ".woff2": "font/woff2" };329330interface Session { page: Page; cdp: CDPSession; diag: SceneDiagnostics; seek(frame: number): Promise<void>; shot(quality: number): Promise<Buffer>; close(): Promise<void> }331332export interface SceneInput {333  html: string; width: number; height: number; seconds: number; /** Délai par opération (chargement, positionnement, capture) ; défaut 20 s. */ timeoutMs?: number;334  /** Scène v3 : données d'exécution (voix alignée, repères, thème, symboles, données). Absent = scène v2, rendue comme avant. */335  scene?: SceneRuntime | null;336  /** Facteur de définition : la scène est composée en `width × height` et rastérisée à `scale` fois cette taille (2 = 4K pour une scène 1920×1080). Défaut 1. */337  scale?: number;338}339function validate(o: SceneInput, fps: number): void {340  if (typeof o.html !== "string" || !o.html.trim()) throw new HtmlSceneError("Scène vide", "bad_input");341  const bytes = Buffer.byteLength(o.html, "utf8");342  if (bytes > MAX_HTML_BYTES) throw new HtmlSceneError(`HTML de scène trop volumineux : ${bytes} octets (maximum ${MAX_HTML_BYTES})`, "too_large");343  const ok = (n: number, lo: number, hi: number) => Number.isFinite(n) && n >= lo && n <= hi;344  if (!ok(o.width, 16, 4096) || !ok(o.height, 16, 4096) || !Number.isInteger(o.width) || !Number.isInteger(o.height)) throw new HtmlSceneError(`Dimensions invalides : ${o.width}×${o.height}`, "bad_input");345  if (!ok(o.seconds, 0.03, 600)) throw new HtmlSceneError(`Durée invalide : ${o.seconds} s`, "bad_input");346  if (!ok(fps, 1, 480)) throw new HtmlSceneError(`Cadence invalide : ${fps}`, "bad_input");347  const sc = o.scale ?? 1;348  if (!ok(sc, 0.25, 4) || o.width * sc > 4096 || o.height * sc > 4096) throw new HtmlSceneError(`Facteur de définition invalide : ${sc} (${o.width * sc}×${o.height * sc})`, "bad_input");349}350351/** Ouvre la scène dans une page isolée, prête à être positionnée (polices chargées, horloge à zéro). */352async function openSession(o: SceneInput, fps: number, doc: string): Promise<Session> {353  const OP = o.timeoutMs ?? OP_TIMEOUT;354  await acquirePage();355  let context: BrowserContext | null = null;356  const diag: SceneDiagnostics = { errors: [], console: [], blocked: [] };357  const push = (list: string[], s: string) => { if (list.length < 40 && !list.includes(s)) list.push(s.slice(0, 400)); };358  try {359    const b = await browser(poolFor(o.html));360    context = await withTimeout(b.newContext({ viewport: { width: o.width, height: o.height }, deviceScaleFactor: o.scale ?? 1, serviceWorkers: "block", acceptDownloads: false, bypassCSP: false, javaScriptEnabled: true, locale: "fr-CA", timezoneId: "UTC", colorScheme: "dark", reducedMotion: "no-preference" }), OP, "ouverture du contexte");361    const ctx = context;362    await ctx.route("**/*", async (route) => {363      const url = route.request().url();364      try {365        if (url === SCENE_URL) return await route.fulfill({ status: 200, contentType: "text/html; charset=utf-8", headers: { "Content-Security-Policy": CSP, "Referrer-Policy": "no-referrer" }, body: doc });366        if (url.startsWith(`${SCENE_ORIGIN}/kit/`)) {367          const rel = decodeURIComponent(new URL(url).pathname.slice("/kit/".length));368          const ext = path.extname(rel);369          if (/^(fonts\/|vendor\/|vendor\/fonts\/)?[A-Za-z0-9._-]+$/.test(rel) && MIME[ext]) {370            const file = rel.startsWith("fonts/") ? pj(FONT_DIR, rel.slice(6)) : pj(KIT_DIR, rel);371            if (existsSync(file)) return await route.fulfill({ status: 200, contentType: MIME[ext], body: rel.startsWith("fonts/") || rel.startsWith("vendor/fonts/") ? await readFile(file) : await kitFile(rel) });372          }373        }374        if (!/^(data|blob|about):/.test(url)) push(diag.blocked, url);375        await route.abort("blockedbyclient");376      } catch { /* page fermée pendant la requête */ }377    });378    await ctx.routeWebSocket("**/*", (ws) => { push(diag.blocked, ws.url()); void ws.close(); });379    // tsx/esbuild enveloppe les fonctions nommées dans `__name(...)` : la page doit connaître ce nom avant tout script sérialisé.380    await ctx.addInitScript("globalThis.__name = globalThis.__name || ((f) => f);");381    await ctx.addInitScript(`globalThis.__clipSettle = ${Number(process.env.CLIP_HTMLSCENE_SETTLE ?? 1)};`);382    await ctx.addInitScript(virtualClock, 0x5eed1e);383    const page = await withTimeout(ctx.newPage(), OP, "ouverture de la page");384    ctx.on("page", (p) => { if (p !== page) { push(diag.blocked, `fenêtre : ${p.url()}`); void p.close().catch(() => undefined); } });385    page.on("pageerror", (e) => push(diag.errors, `${e.name}: ${e.message}`));386    page.on("console", (m) => { if (m.type() === "error" || m.type() === "warning") push(diag.console, `${m.type()}: ${m.text()}`); });387    page.on("dialog", (d) => { void d.dismiss().catch(() => undefined); });388    const res = await withTimeout(page.goto(SCENE_URL, { waitUntil: "load", timeout: OP }), OP + 1000, "chargement de la scène");389    if (!res || !res.ok()) throw new HtmlSceneError("La scène ne s'est pas chargée", "load_failed", diag);390    await withTimeout(page.evaluate(async () => {391      const sk = (window as unknown as { SK?: { ready?: Promise<unknown> } }).SK;392      await Promise.all([sk?.ready, document.fonts.ready]);393    }), OP, "chargement des polices");394    const cdp = await ctx.newCDPSession(page);395    const pull = async () => { for (const e of await page.evaluate(() => (window as unknown as { __clip: { errors(): string[] } }).__clip.errors())) push(diag.errors, e); };396    return {397      page, cdp, diag,398      async seek(frame) {399        if (page.url() !== SCENE_URL) throw new HtmlSceneError(`La scène a quitté son document (${page.url().slice(0, 120)})`, "load_failed", diag);400        await withTimeout(page.evaluate(([f, r]) => (window as unknown as { __clip: { seek(f: number, r: number): Promise<number> | number } }).__clip.seek(f, r), [frame, fps]), OP, `positionnement à la trame ${frame} (script de scène trop long ?)`);401      },402      async shot(quality) {403        const r = await withTimeout(cdp.send("Page.captureScreenshot", quality >= 100 ? { format: "png", optimizeForSpeed: true } : { format: "jpeg", quality, optimizeForSpeed: false }), OP, "capture");404        return Buffer.from(r.data, "base64");405      },406      async close() {407        try { await withTimeout(pull(), 3000, "erreurs"); } catch { /* page bloquée */ }408        try { await withTimeout(ctx.close(), 5000, "fermeture"); } catch { await closeBrowser(); }409        releasePage();410      },411    };412  } catch (e) {413    try { if (context) await withTimeout(context.close(), 5000, "fermeture"); } catch { await closeBrowser(); }414    releasePage();415    if (e instanceof HtmlSceneError) { e.diagnostics ??= diag; throw e; }416    throw new HtmlSceneError(`Chargement de la scène impossible : ${(e as Error).message.split("\n")[0]}`, "load_failed", diag);417  }418}419420const frameOf = (t: number, fps: number, total: number) => Math.max(0, Math.min(total - 1, Math.round(t * fps)));421const mergeDiag = (into: SceneDiagnostics, d: SceneDiagnostics) => { for (const k of ["errors", "console", "blocked"] as const) for (const s of d[k]) if (!into[k].includes(s)) into[k].push(s); };422423// ── inspection (relecture par vision + contrôles automatiques) ───────────────424/** Bloc de texte visible à un instant donné, en pixels de la trame. */425export interface TextBox {426  text: string; x: number; y: number; w: number; h: number; fontPx: number; color: string; opacity: number; svg: boolean;427  /** Le bloc contient un compteur animé (kit `data-count`) : `final` est le texte qu'il affichera une fois arrivé. */428  counting?: boolean; final?: string;429  /** Texte produit par un calcul validé (axes, valeurs d'un graphique SKN / Python, équation) : exempté du contrôle « chiffre absent des faits ». */430  computed?: boolean;431  /** Équation KaTeX (le texte est son LaTeX). */432  tex?: boolean;433}434/** Élément lié à un repère de la voix (`data-beat="id"`) : est-il visible à cet instant ? */435export interface BeatSeen { id: string; visible: boolean; x: number; y: number; w: number; h: number }436export interface SceneAudit { at: number; beats?: BeatSeen[]; texts: TextBox[]; /** Part de la ZONE SÛRE couverte par des éléments visibles autres que le décor (0–1). */ elements: number; /** Part de la largeur et de la hauteur de la zone sûre sur laquelle ce dessin s'étend (0–1). */ extent: { w: number; h: number } }437438/** Exécuté dans la page : relève les blocs de texte réellement visibles (opacité cumulée, découpes `overflow`, hors cadre). */439function auditPage(safe: { x: number; y: number; w: number; h: number }): { texts: TextBox[]; elements: number; extent: { w: number; h: number }; beats: BeatSeen[] } {440  const W = window.innerWidth, H = window.innerHeight;441  const opacityOf = (el: Element | null): number => { let o = 1; for (let e = el; e && e !== document.documentElement; e = e.parentElement) { const cs = getComputedStyle(e); if (cs.display === "none" || cs.visibility === "hidden") return 0; o *= Number(cs.opacity); if (o < 0.02) return 0; } return o; };442  const clipOf = (el: Element | null) => {443    let x0 = -1e6, y0 = -1e6, x1 = 1e6, y1 = 1e6;444    for (let e = el; e && e !== document.body; e = e.parentElement) {445      if (e.matches(".scene,.sk-stage")) continue;             // la découpe par le cadre est traitée à part (texte hors cadre)446      const cs = getComputedStyle(e);447      if (cs.overflow !== "visible" || cs.clipPath !== "none") { const r = e.getBoundingClientRect(); x0 = Math.max(x0, r.left); y0 = Math.max(y0, r.top); x1 = Math.min(x1, r.right); y1 = Math.min(y1, r.bottom); }448    }449    return { x0, y0, x1, y1 };450  };451  const blocks = new Map<Element, TextBox & { x1: number; y1: number; final: string }>();452  // Équations KaTeX : leur rendu est masqué aux lecteurs d'écran (aria-hidden), on les relève donc à part, comme un bloc dont le texte est le LaTeX.453  const texBoxes: TextBox[] = [];454  for (const t of document.querySelectorAll(".sk-tex[data-tex]")) {455    const inner = t.querySelector(".katex-html") ?? t, r = inner.getBoundingClientRect();456    if (r.width < 2 || r.height < 2) continue;457    const op = opacityOf(t);458    if (op < 0.3) continue;459    texBoxes.push({ text: `[équation] ${(t.getAttribute("data-tex") ?? "").slice(0, 120)}`, x: Math.round(r.left), y: Math.round(r.top), w: Math.round(r.width), h: Math.round(r.height), fontPx: Math.round(parseFloat(getComputedStyle(t).fontSize) * 10) / 10, color: getComputedStyle(t).color, opacity: Math.round(op * 100) / 100, svg: false, computed: true, tex: true });460  }461  const addBox = (block: Element, styled: Element, r: DOMRect, text: string, fontPx: number, svg: boolean) => {462    if (r.width < 1 || r.height < 1) return;463    const op = opacityOf(styled);464    if (op < 0.3) return;465    const c = clipOf(styled.parentElement);466    const ix = Math.max(0, Math.min(r.right, c.x1) - Math.max(r.left, c.x0)), iy = Math.max(0, Math.min(r.bottom, c.y1) - Math.max(r.top, c.y0));467    if (ix * iy < 0.5 * r.width * r.height) return;468    const cs = getComputedStyle(styled), color = svg ? cs.fill : cs.color;469    const counter = styled.closest("[data-sk-count]"), fin = counter ? counter.getAttribute("data-sk-count") ?? text : text;470    // La boîte d'une ligne de texte dépasse l'encre des glyphes (ascendantes, descendantes, interligne) : on la resserre en hauteur.471    const pad = Math.min(r.height * 0.2, fontPx * 0.16), top = r.top + pad, bottom = r.bottom - pad;472    const b = blocks.get(block);473    if (!b) blocks.set(block, { text, final: fin, counting: !!counter, computed: !!styled.closest("[data-computed]"), x: r.left, y: top, w: 0, h: 0, x1: r.right, y1: bottom, fontPx, color, opacity: op, svg });474    else { b.text += ` ${text}`; b.final += ` ${fin}`; b.counting ||= !!counter; b.x = Math.min(b.x, r.left); b.y = Math.min(b.y, top); b.x1 = Math.max(b.x1, r.right); b.y1 = Math.max(b.y1, bottom); b.fontPx = Math.min(b.fontPx, fontPx); b.opacity = Math.min(b.opacity, op); }475  };476  const stage = document.getElementById("stage") ?? document.body;477  const walker = document.createTreeWalker(stage, NodeFilter.SHOW_TEXT);478  for (let n = walker.nextNode(); n; n = walker.nextNode()) {479    const text = (n.textContent ?? "").replace(/\s+/g, " ").trim(), el = n.parentElement;480    if (!text || !el || el.closest("script,style,defs,title,desc,symbol,[aria-hidden='true']")) continue;481    const svgText = el.closest("text");482    if (svgText) {483      const m = (svgText as SVGTextElement).getScreenCTM();484      const scale = m ? Math.sqrt(Math.abs(m.a * m.d - m.b * m.c)) : 1;485      addBox(svgText, el, el.getBoundingClientRect(), text, parseFloat(getComputedStyle(el).fontSize) * scale, true);486      continue;487    }488    const range = document.createRange(); range.selectNodeContents(n);489    const r = range.getBoundingClientRect();490    let block: HTMLElement = el;491    while (block.parentElement && block !== stage && getComputedStyle(block).display.startsWith("inline")) block = block.parentElement;492    const he = el as HTMLElement, lay = he.offsetHeight, vis = he.getBoundingClientRect().height;493    addBox(block, el, r, text, parseFloat(getComputedStyle(el).fontSize) * (lay > 0 && vis > 0 ? vis / lay : 1), false);494  }495  const texts = [...blocks.values()].map((b) => ({ text: b.text.slice(0, 160), x: Math.round(b.x), y: Math.round(b.y), w: Math.round(b.x1 - b.x), h: Math.round(b.y1 - b.y), fontPx: Math.round(b.fontPx * 10) / 10, color: b.color, opacity: Math.round(b.opacity * 100) / 100, svg: b.svg, ...(b.counting ? { counting: true, final: b.final.slice(0, 160) } : {}), ...(b.computed ? { computed: true } : {}) } as TextBox)).concat(texBoxes);496  const beats: BeatSeen[] = [];497  for (const e of document.querySelectorAll("[data-beat]")) {498    const r = e.getBoundingClientRect(), op = opacityOf(e), cs = getComputedStyle(e);499    const clipped = cs.clipPath !== "none" && /inset\((?:-?[\d.]+% )?(?:1\d\d|9\d)%|circle\(0/.test(cs.clipPath);500    beats.push({ id: e.getAttribute("data-beat") ?? "", visible: op > 0.45 && !clipped && r.width > 2 && r.height > 2 && r.right > 0 && r.bottom > 0 && r.left < W && r.top < H, x: Math.round(r.left), y: Math.round(r.top), w: Math.round(r.width), h: Math.round(r.height) });501  }502  // Occupation : grille grossière de points, compte ceux qui touchent un élément dessiné autre que la scène elle-même.503  let hit = 0, total = 0;504  const cols = new Set<number>(), rows = new Set<number>();505  for (let gy = 0.5; gy < 14; gy++) for (let gx = 0.5; gx < 22; gx++) {506    total++;507    const stack = document.elementsFromPoint(Math.min(W - 1, safe.x + (gx / 22) * safe.w), Math.min(H - 1, safe.y + (gy / 14) * safe.h));508    if (stack.some((e) => e !== stage && !e.matches("html,body,svg,#sk-sprite,.sk-stage,.scene,.sk-safe,.sk-layer,.sk-row,.sk-col,.sk-split,svg.sk-decor *,:not(.scene)[data-decor],:not(.scene)[data-decor] *") && opacityOf(e) > 0.25)) { hit++; cols.add(gx); rows.add(gy); }509  }510  return { texts, elements: hit / total, extent: { w: cols.size / 22, h: rows.size / 14 }, beats };511}512513/**514 * Rend des images clés aux instants `at` (secondes ; une valeur ≥ `seconds` donne la dernière trame) et relève, pour chacune, les blocs515 * de texte visibles. Renvoie aussi les erreurs de la scène. Sert à la relecture par vision et aux contrôles automatiques.516 */517/** Ce que la scène v3 déclare d'elle-même (`SK.meta`) : clés de caméra, pistes, techniques utilisées, équations, provenance, avertissements. */518export interface SceneMeta { camera: { keys: { at: number; x: number; y: number; zoom: number; rot: number; ease: string }[]; layers: number[]; path: string } | null; tracks: { name: string; keys: { at: number; v: unknown; ease: string }[] }[]; tex: string[]; uses: Record<string, boolean>; beatsUsed: Record<string, boolean>; provenance: string | null; warnings: string[] }519520export async function inspectHtmlScene(o: SceneInput & { at: number[]; fps?: number; quality?: number }): Promise<{ frames: Buffer[]; audits: SceneAudit[]; diagnostics: SceneDiagnostics; meta: SceneMeta | null }> {521  const fps = o.fps ?? 30;522  validate(o, fps);523  const total = Math.max(1, Math.round(o.seconds * fps));524  const order = o.at.map((t, i) => ({ i, f: frameOf(t, fps, total) })).sort((a, b) => a.f - b.f);525  const s = await openSession(o, fps, await sceneDocument(o));526  const frames: Buffer[] = new Array(o.at.length), audits: SceneAudit[] = new Array(o.at.length), zone = safeZones(o.width, o.height, !!o.scene).safe;527  let meta: SceneMeta | null = null;528  try {529    for (const { i, f } of order) {530      await s.seek(f);531      frames[i] = await s.shot(o.quality ?? 88);532      audits[i] = { at: f / fps, ...(await withTimeout(s.page.evaluate(auditPage, zone), o.timeoutMs ?? OP_TIMEOUT, "relevé de mise en page")) };533    }534    if (o.scene) meta = await withTimeout(s.page.evaluate(() => { const m = (window as unknown as { SK?: { meta?: unknown } }).SK?.meta; return m ? JSON.parse(JSON.stringify(m)) : null; }), o.timeoutMs ?? OP_TIMEOUT, "relevé des métadonnées") as SceneMeta | null;535  } catch (e) {536    await s.close();537    if (e instanceof HtmlSceneError) { e.diagnostics = s.diag; throw e; }538    throw new HtmlSceneError(`Inspection impossible : ${(e as Error).message.split("\n")[0]}`, "load_failed", s.diag);539  }540  await s.close();541  return { frames, audits, diagnostics: s.diag, meta };542}543544/** Images JPEG de la scène aux instants `at` (secondes). */545export async function captureFrames(o: SceneInput & { at: number[]; fps?: number; quality?: number }): Promise<Buffer[]> {546  return (await inspectHtmlScene(o)).frames;547}548549// ── rendu vidéo ──────────────────────────────────────────────────────────────550export interface RenderResult {551  renderSeconds: number; frames: number; pages: number; diagnostics: SceneDiagnostics;552  /** Temps cumulé (toutes pages) passé à positionner la scène et à capturer, en secondes : sert à mesurer et régler le moteur. */553  timing: { openSeconds: number; seekSeconds: number; captureSeconds: number };554}555556/**557 * Rend la scène en vidéo : `frames = round(seconds × fps)` images exactement, codec intermédiaire du pipeline (`intermediateArgs`),558 * piste audio silencieuse 48 kHz stéréo. `pages` = nombre de pages Chromium entrelacées (défaut : deux par navigateur de la réserve, borné par le plafond global).559 */560export async function renderHtmlScene(o: SceneInput & { fps: number; output: string; pages?: number; quality?: number; onFrame?: (index: number, jpeg: Buffer) => void;561  /** Flou de mouvement : nombre de sous-images rendues puis fondues par image (1 = aucun ; 3 ou 4 = flou cinéma). Multiplie d'autant le temps de rendu. */562  motionBlur?: number }): Promise<RenderResult> {563  validate(o, o.fps);564  const t0 = performance.now();565  const sub = Math.max(1, Math.min(8, Math.round(o.motionBlur ?? 1))), outFps = o.fps, outFrames = Math.max(1, Math.round(o.seconds * outFps));566  // Avec flou de mouvement, la scène est jouée à fps × sub ; FFmpeg fond chaque groupe de `sub` sous-images en une image (obturateur ouvert sur toute l'image).567  if (sub > 1) o = { ...o, fps: outFps * sub };568  const total = sub > 1 ? outFrames * sub : outFrames;569  const n = Math.max(1, Math.min(o.pages ?? DEFAULT_PAGES, MAX_PAGES, Math.ceil(total / 8)));570  const quality = o.quality ?? 94;571  const doc = await sceneDocument({ ...o, scene: o.scene ? { ...o.scene, fps: outFps } : o.scene });572  const diag: SceneDiagnostics = { errors: [], console: [], blocked: [] };573  const scale = o.scale ?? 1, outW = Math.round(o.width * scale), outH = Math.round(o.height * scale);574  const blend = sub > 1 ? `tmix=frames=${sub}:weights='${Array(sub).fill(1).join(" ")}',select='eq(mod(n\\,${sub})\\,${sub - 1})',setpts=N/(${outFps}*TB),` : "";575576  const png = quality >= 100;577  const child = spawn("ffmpeg", ["-hide_banner", "-y", "-f", "image2pipe", "-framerate", String(o.fps), "-c:v", png ? "png" : "mjpeg", "-i", "pipe:0",578    "-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo", "-map", "0:v:0", "-map", "1:a:0", "-frames:v", String(outFrames), "-t", (outFrames / outFps).toFixed(6),579    "-vf", `${blend}scale=${outW}:${outH}:in_range=full:out_range=tv:flags=bicubic,format=yuv420p`, ...intermediateArgs(outFps, o.output)],580  { env: { ...process.env, PATH: BIN_PATH }, stdio: ["pipe", "ignore", "pipe"] });581  let stderr = "", pipeError: Error | null = null;582  child.stderr.on("data", (c: Buffer) => { stderr = (stderr + c.toString()).slice(-4000); });583  child.stdin.on("error", (e) => { pipeError = e; notify(); });584  const encoded = new Promise<void>((resolve, reject) => {585    child.on("error", reject);586    child.on("close", (code) => (code === 0 ? resolve() : reject(new HtmlSceneError(`ffmpeg a échoué (${code}) : ${stderr.split("\n").filter(Boolean).slice(-3).join(" | ")}`, "encode_failed"))));587  });588  encoded.catch(() => undefined);589590  // File ordonnée : la page k produit les trames k, k+n, k+2n… ; l'écrivain les envoie dans l'ordre et freine les pages en avance.591  const ready = new Map<number, Buffer>();592  let written = 0, failure: unknown = null, wake: (() => void) | null = null;593  const notify = () => { const w = wake; wake = null; w?.(); };594  const pause = () => new Promise<void>((r) => { const prev = wake; wake = () => { prev?.(); r(); }; });595  const writer = (async () => {596    while (written < total && !failure && !pipeError) {597      const buf = ready.get(written);598      if (!buf) { await pause(); continue; }599      ready.delete(written);600      o.onFrame?.(written, buf);601      written++;602      notify();603      if (!child.stdin.write(buf)) await new Promise<void>((r) => { const on = () => { child.stdin.off("drain", on); child.off("close", on); r(); }; child.stdin.once("drain", on); child.once("close", on); });604    }605  })();606  const timing = { openSeconds: 0, seekSeconds: 0, captureSeconds: 0 };607  const worker = async (k: number) => {608    const tOpen = performance.now();609    const s = await openSession(o, o.fps, doc);610    timing.openSeconds += (performance.now() - tOpen) / 1000;611    try {612      for (let f = k; f < total && !failure && !pipeError; f += n) {613        while (f - written > n * 6 && !failure) await pause();614        const t1 = performance.now();615        await s.seek(f);616        const t2 = performance.now();617        ready.set(f, await s.shot(quality));618        timing.seekSeconds += (t2 - t1) / 1000; timing.captureSeconds += (performance.now() - t2) / 1000;619        notify();620      }621    } finally { await s.close(); mergeDiag(diag, s.diag); }622  };623  try {624    await Promise.all([...Array.from({ length: n }, (_, k) => worker(k).catch((e) => { failure ??= e; notify(); throw e; })), writer]);625    if (pipeError) throw new HtmlSceneError(`ffmpeg a fermé son entrée : ${stderr.split("\n").filter(Boolean).slice(-2).join(" | ")}`, "encode_failed");626    child.stdin.end();627    await encoded;628  } catch (e) {629    child.kill("SIGKILL");630    const err = failure ?? e;631    if (err instanceof HtmlSceneError) { err.diagnostics ??= diag; throw err; }632    throw new HtmlSceneError(`Rendu impossible : ${(err as Error).message.split("\n")[0]}`, "load_failed", diag);633  }634  return { renderSeconds: (performance.now() - t0) / 1000, frames: outFrames, pages: n, diagnostics: diag, timing };635}636
Files main
Menu

Theme