SPB Git

Repository Public

qc.ts 19.8 KB 273 lines typescript

1import { BRAND_TEXT, type QcCheck, type Ratio } from "../lib/contracts";2import { watermarkTemplate } from "./brand";3import { grayFrame, grayFramesSinglePass, probe, run, type Probe } from "./ffmpeg";45/**6 * Contrôle qualité technique : uniquement des valeurs MESURÉES par FFmpeg (aucun score inventé).7 */89// ── contrôles techniques ─────────────────────────────────────────────────────10export const QC_LIMITS = {11  /** blackdetect : pixel « noir » sous 3 % de luminance (le fond de marque #0b0c0f, ≈ 4,5 %, n'est PAS noir), image noire à 98 %. */12  blackPixTh: 0.03, blackPicTh: 0.98, blackMinSeconds: 0.5,13  /** Part de la durée en noir au-delà de laquelle le contrôle échoue. */14  blackFailShare: 0.3,15  silenceDb: -50, silenceMinSeconds: 1,16  /** Silence continu hors narration toléré sans avertissement (un carton de fin muet dure moins). */17  silenceWarnSeconds: 5,18  /** Part d'une fenêtre de narration en silence au-delà de laquelle la voix est considérée absente. */19  narrationSilentShare: 0.5,20  truePeakPass: -1.0, truePeakFail: -0.1,21  loudnessTarget: -14, loudnessPass: 1.0, loudnessWarn: 3.0,22} as const;2324interface Interval { start: number; end: number }25const overlap = (a: Interval, b: Interval) => Math.max(0, Math.min(a.end, b.end) - Math.max(a.start, b.start));26const r3 = (n: number) => Math.round(n * 1000) / 1000;2728export async function technicalChecks(o: { file: string; expected: { width: number; height: number; minSeconds: number; maxSeconds: number }; narrationWindows: { start: number; end: number }[] }): Promise<QcCheck[]> {29  const checks: QcCheck[] = [];30  const notMeasured = (key: string, label: string, blocking: boolean, detail: string): QcCheck => ({ key, label, status: "not_measured", blocking, measured: {}, detail });3132  let p: Probe | null = null;33  let probeError = "";34  try { p = await probe(o.file); } catch (e) { probeError = (e as Error).message; }35  if (!p || !p.hasVideo) {36    const why = probeError || "aucune piste vidéo";37    return [38      { key: "decodable", label: "Fichier décodable", status: "fail", blocking: true, measured: { error: why }, detail: `ffprobe ne lit pas le fichier : ${why}` },39      notMeasured("duration", "Durée", true, "non mesurée : fichier illisible"),40      notMeasured("resolution", "Résolution", true, "non mesurée : fichier illisible"),41      notMeasured("black_frames", "Images noires", false, "non mesuré : fichier illisible"),42      notMeasured("silence", "Silences", false, "non mesuré : fichier illisible"),43      notMeasured("clipping", "Crête vraie", false, "non mesuré : fichier illisible"),44      notMeasured("loudness", "Sonie intégrée", false, "non mesuré : fichier illisible"),45    ];46  }4748  // Un seul décodage complet : erreurs de décodage, blackdetect, silencedetect, ebur128 (crête vraie), astats.49  const L = QC_LIMITS;50  const args = ["-hide_banner", "-nostdin", "-xerror", "-i", o.file, "-map", "0:v:0", "-vf", `blackdetect=d=${L.blackMinSeconds}:pix_th=${L.blackPixTh}:pic_th=${L.blackPicTh}`];51  if (p.hasAudio) args.push("-map", "0:a:0", "-af", `silencedetect=n=${L.silenceDb}dB:d=${L.silenceMinSeconds},astats=measure_perchannel=none:measure_overall=Peak_level,ebur128=peak=true`);52  args.push("-f", "null", "-");53  let log = "", decodeError = "";54  try { log = (await run("ffmpeg", args, 3_600_000)).stderr; } catch (e) { decodeError = (e as Error).message; }55  const errorLines = log.split("\n").filter((l) => /\b(error while decoding|corrupt|invalid data|concealing|missing reference|decode_slice)/i.test(l));56  const frames = Number([...log.matchAll(/frame=\s*(\d+)/g)].pop()?.[1] ?? NaN);57  const decoded = !decodeError && errorLines.length === 0;58  checks.push({59    key: "decodable", label: "Fichier décodable", status: decoded ? "pass" : "fail", blocking: true,60    measured: { decodedFrames: Number.isFinite(frames) ? frames : null, decodeErrors: errorLines.length, videoCodec: p.videoCodec ?? null, audioCodec: p.audioCodec ?? null, ...(decodeError ? { error: decodeError } : {}) },61    detail: decoded ? `Décodage complet sans erreur (${Number.isFinite(frames) ? frames : "?"} images).` : `Erreurs de décodage : ${decodeError || errorLines.slice(0, 2).join(" | ")}`,62  });6364  const durOk = p.duration >= o.expected.minSeconds && p.duration <= o.expected.maxSeconds;65  checks.push({ key: "duration", label: "Durée", status: durOk ? "pass" : "fail", blocking: true,66    measured: { seconds: r3(p.duration), minSeconds: o.expected.minSeconds, maxSeconds: o.expected.maxSeconds },67    detail: `${p.duration.toFixed(2)} s mesurées ; attendu entre ${o.expected.minSeconds} et ${o.expected.maxSeconds} s.` });6869  const resOk = p.width === o.expected.width && p.height === o.expected.height;70  checks.push({ key: "resolution", label: "Résolution", status: resOk ? "pass" : "fail", blocking: true,71    measured: { width: p.width, height: p.height, expectedWidth: o.expected.width, expectedHeight: o.expected.height, fps: r3(p.fps) },72    detail: `${p.width}×${p.height} mesuré ; attendu ${o.expected.width}×${o.expected.height}.` });7374  if (decodeError) {75    checks.push(notMeasured("black_frames", "Images noires", false, "non mesuré : décodage interrompu"), notMeasured("silence", "Silences", false, "non mesuré : décodage interrompu"),76      notMeasured("clipping", "Crête vraie", false, "non mesuré : décodage interrompu"), notMeasured("loudness", "Sonie intégrée", false, "non mesuré : décodage interrompu"));77    return checks;78  }7980  // images noires81  const black: Interval[] = [...log.matchAll(/black_start:([\d.]+)\s+black_end:([\d.]+)/g)].map((m) => ({ start: Number(m[1]), end: Number(m[2]) }));82  const blackTotal = black.reduce((a, b) => a + (b.end - b.start), 0);83  const blackShare = p.duration > 0 ? blackTotal / p.duration : 0;84  checks.push({ key: "black_frames", label: "Images noires", status: !black.length ? "pass" : blackShare >= L.blackFailShare ? "fail" : "warn", blocking: false,85    measured: { intervals: black.map((b) => ({ start: r3(b.start), end: r3(b.end) })), totalSeconds: r3(blackTotal), share: r3(blackShare), longestSeconds: r3(Math.max(0, ...black.map((b) => b.end - b.start))), pixTh: L.blackPixTh, minSeconds: L.blackMinSeconds },86    detail: black.length ? `${black.length} passage(s) noir(s), ${blackTotal.toFixed(2)} s au total (${(blackShare * 100).toFixed(1)} % de la durée).` : `Aucun passage noir de ${L.blackMinSeconds} s ou plus.` });8788  if (!p.hasAudio) {89    checks.push({ key: "silence", label: "Silences", status: "fail", blocking: false, measured: { hasAudio: false }, detail: "Le fichier n'a pas de piste audio." },90      notMeasured("clipping", "Crête vraie", false, "non mesuré : pas de piste audio"), notMeasured("loudness", "Sonie intégrée", false, "non mesuré : pas de piste audio"));91    return checks;92  }9394  // silences95  const starts = [...log.matchAll(/silence_start:\s*(-?[\d.]+)/g)].map((m) => Math.max(0, Number(m[1])));96  const ends = [...log.matchAll(/silence_end:\s*([\d.]+)/g)].map((m) => Number(m[1]));97  const silences: Interval[] = starts.map((s, i) => ({ start: s, end: ends[i] ?? p.duration }));98  const windows = o.narrationWindows.filter((w) => w.end > w.start);99  const perWindow = windows.map((w) => ({ start: w.start, end: w.end, silentSeconds: r3(silences.reduce((a, s) => a + overlap(s, w), 0)) }));100  const insideTotal = perWindow.reduce((a, w) => a + w.silentSeconds, 0);101  // parties de silence hors narration102  const outside: Interval[] = [];103  for (const s of silences) {104    let cur = s.start;105    for (const w of [...windows].sort((a, b) => a.start - b.start)) {106      if (w.end <= cur || w.start >= s.end) continue;107      if (w.start > cur) outside.push({ start: cur, end: w.start });108      cur = Math.max(cur, w.end);109    }110    if (cur < s.end) outside.push({ start: cur, end: s.end });111  }112  const longestOutside = Math.max(0, ...outside.map((s) => s.end - s.start));113  const mutedWindows = perWindow.filter((w) => w.end - w.start >= 1 && w.silentSeconds / (w.end - w.start) >= L.narrationSilentShare);114  const silenceStatus = mutedWindows.length ? "fail" : longestOutside >= L.silenceWarnSeconds ? "warn" : "pass";115  checks.push({ key: "silence", label: "Silences", status: silenceStatus, blocking: false,116    measured: { intervals: silences.map((s) => ({ start: r3(s.start), end: r3(s.end) })), totalSeconds: r3(silences.reduce((a, s) => a + s.end - s.start, 0)),117      outsideNarrationSeconds: r3(outside.reduce((a, s) => a + s.end - s.start, 0)), longestOutsideNarrationSeconds: r3(longestOutside), insideNarrationSeconds: r3(insideTotal),118      narrationWindows: perWindow, thresholdDb: L.silenceDb, minSeconds: L.silenceMinSeconds },119    detail: mutedWindows.length ? `Voix absente : ${mutedWindows.length} fenêtre(s) de narration silencieuse(s) à ${L.narrationSilentShare * 100} % ou plus.`120      : longestOutside >= L.silenceWarnSeconds ? `Silence continu de ${longestOutside.toFixed(2)} s hors narration (seuil ${L.silenceWarnSeconds} s).`121      : `Pas de silence anormal (plus long silence hors narration : ${longestOutside.toFixed(2)} s).` });122123  // crête vraie et sonie (ebur128)124  const summary = log.slice(log.lastIndexOf("Summary:"));125  const integrated = Number(summary.match(/I:\s*(-?[\d.]+|-?inf)\s*LUFS/)?.[1]?.replace("inf", "Infinity") ?? NaN);126  const lra = Number(summary.match(/LRA:\s*([\d.]+)\s*LU/)?.[1] ?? NaN);127  const truePeak = Number(summary.match(/Peak:\s*(-?[\d.]+|-?inf)\s*dBFS/)?.[1]?.replace("inf", "Infinity") ?? NaN);128  const samplePeak = Number(log.match(/Peak level dB:\s*(-?[\d.]+|-?inf)/)?.[1]?.replace("inf", "Infinity") ?? NaN);129  const silent = !Number.isFinite(integrated) || integrated <= -69;130  if (Number.isNaN(truePeak)) checks.push(notMeasured("clipping", "Crête vraie", false, "non mesuré : ebur128 n'a pas rendu de crête"));131  else checks.push({ key: "clipping", label: "Crête vraie", status: truePeak > L.truePeakFail ? "fail" : truePeak > L.truePeakPass ? "warn" : "pass", blocking: false,132    measured: { truePeakDbtp: Number.isFinite(truePeak) ? truePeak : null, samplePeakDbfs: Number.isFinite(samplePeak) ? r3(samplePeak) : null, passAtOrBelow: L.truePeakPass, failAbove: L.truePeakFail },133    detail: Number.isFinite(truePeak) ? `Crête vraie ${truePeak.toFixed(1)} dBTP (réussite ≤ ${L.truePeakPass}, échec > ${L.truePeakFail}).` : "Signal nul : aucune crête." });134  if (silent) checks.push({ key: "loudness", label: "Sonie intégrée", status: "warn", blocking: false, measured: { integratedLufs: null, silent: true, target: L.loudnessTarget }, detail: "Piste audio silencieuse : sonie non mesurable." });135  else {136    const delta = Math.abs(integrated - L.loudnessTarget);137    checks.push({ key: "loudness", label: "Sonie intégrée", status: delta <= L.loudnessPass ? "pass" : delta <= L.loudnessWarn ? "warn" : "fail", blocking: false,138      measured: { integratedLufs: integrated, loudnessRangeLu: Number.isFinite(lra) ? lra : null, target: L.loudnessTarget, passWithin: L.loudnessPass, warnWithin: L.loudnessWarn },139      detail: `${integrated.toFixed(1)} LUFS intégrés (cible ${L.loudnessTarget} ± ${L.loudnessPass}).` });140  }141  return checks;142}143144// ── filigrane ────────────────────────────────────────────────────────────────145/**146 * Seuils de `verifyWatermark`.147 *  - `ncc` : corrélation croisée normalisée entre la luminance de la trame dans la plaque et la couverture du texte du gabarit,148 *    maximisée sur un petit décalage (± `search` px, compense l'arrondi de mise à l'échelle) ;149 *  - `contrast` : écart de luminance moyen (0–255) entre les pixels du texte et ceux de la plaque — garantit que le texte est VISIBLE,150 *    pas seulement corrélé.151 * Une trame est conforme si ncc ≥ minNcc ET contrast ≥ minContrast ; la vérification passe si TOUTES les trames sont conformes.152 *153 * Calibration mesurée le 2026-11-19 (Apple M5 Max, FFmpeg 8.1.1 ; 10 trames par fichier, valeur = minimum des trames) :154 *  - POSITIFS, 70 fichiers : masters 1080p, aperçus 480p, variantes HLS 1080/720/480/360 et playlist maîtresse ; ratios 16:9, 9:16, 1:1 ;155 *    fonds blanc, noir, mire testsrc2, bruit, fractale, gris → ncc min. 0,839 (HLS 360p 1:1 sur blanc), contraste min. 84,7 ;156 *    masters 1080p : ncc ≥ 0,96.157 *  - NÉGATIFS : sans filigrane (13) ncc ≤ 0,01, contraste ≤ 1 ; même plaque à l'autre coin ≤ 0,01 ; autre texte « clip.example.com » (13)158 *    ≤ 0,627 ; « www.exemple.org » ≤ 0,495 ; « CLIP.SPBOUCHER.AI » ≤ 0,351 ; « sp-clip.ai » ≤ 0,342 ; filigrane décalé de 8 / 14 / 40 px159 *    ≤ 0,474 / 0,553 / 0,584 ; décalé de 10 px en vertical ≤ 0,382.160 *  → seuil ncc 0,73 (milieu de l'intervalle 0,627–0,839), contraste 50.161 * LIMITE CONNUE : un texte qui ne diffère que d'une lettre (« clip.spbouchar.ai ») corrèle à 0,91–0,98 et n'est PAS distingué ;162 * la vérification atteste la présence du filigrane de marque à l'endroit prévu, ce n'est pas une reconnaissance de caractères.163 */164export const WATERMARK_THRESHOLDS = { minNcc: 0.73, minContrast: 50 } as const;165166export interface WatermarkFrameMeasure { t: number; ncc: number; contrast: number; dx: number; dy: number; ok: boolean; where: string }167168function matchTemplate(frame: Buffer, fw: number, tpl: { w: number; h: number; text: Uint8Array; mask: Uint8Array }, search: number): { ncc: number; contrast: number; dx: number; dy: number } {169  // pixels utiles : intérieur de la plaque170  const idx: number[] = [];171  for (let i = 0; i < tpl.mask.length; i++) if (tpl.mask[i] > 200) idx.push(i);172  const n = idx.length;173  let tMean = 0;174  for (const i of idx) tMean += tpl.text[i];175  tMean /= n;176  let tVar = 0;177  for (const i of idx) tVar += (tpl.text[i] - tMean) ** 2;178  let best = { ncc: -1, contrast: 0, dx: 0, dy: 0 };179  for (let dy = -search; dy <= search; dy++) {180    for (let dx = -search; dx <= search; dx++) {181      let fMean = 0;182      const off = (search + dy) * fw + (search + dx);183      for (const i of idx) fMean += frame[off + Math.floor(i / tpl.w) * fw + (i % tpl.w)];184      fMean /= n;185      let cov = 0, fVar = 0, on = 0, onN = 0, offSum = 0, offN = 0;186      for (const i of idx) {187        const f = frame[off + Math.floor(i / tpl.w) * fw + (i % tpl.w)];188        const t = tpl.text[i];189        cov += (f - fMean) * (t - tMean);190        fVar += (f - fMean) ** 2;191        if (t > 200) { on += f; onN++; } else if (t < 16) { offSum += f; offN++; }192      }193      const ncc = fVar > 1e-6 && tVar > 1e-6 ? cov / Math.sqrt(fVar * tVar) : 0;194      if (ncc > best.ncc) best = { ncc, contrast: onN && offN ? on / onN - offSum / offN : 0, dx, dy };195    }196  }197  return best;198}199200/**201 * Vérifie la présence du filigrane `clip.spboucher.ai` sur toute la durée : au moins 8 trames (10 par défaut) — première, dernière,202 * milieu, fin du programme / carton de fin, et trames réparties — sont comparées au gabarit à la résolution du fichier203 * (MP4 ou playlist HLS). `endCardSeconds`, s'il est fourni, place deux trames exactement de part et d'autre du début du carton.204 * Contrôle BLOQUANT : une seule trame non conforme fait échouer la vérification.205 */206export async function verifyWatermark(o: { file: string; ratio: Ratio; samples?: number; endCardSeconds?: number }): Promise<QcCheck> {207  const label = "Filigrane clip.spboucher.ai";208  const fail = (detail: string, measured: Record<string, unknown> = {}): QcCheck => ({ key: "watermark", label, status: "fail", blocking: true, measured, detail });209  let p: Probe;210  try { p = await probe(o.file); } catch (e) { return fail(`Fichier illisible : ${(e as Error).message}`); }211  if (!p.hasVideo || !(p.duration > 0)) return fail("Aucune piste vidéo mesurable.");212  const aspect = p.width / p.height;213  const expected = o.ratio === "16:9" ? 16 / 9 : o.ratio === "9:16" ? 9 / 16 : 1;214  if (Math.abs(aspect / expected - 1) > 0.03) return fail(`Le fichier (${p.width}×${p.height}) n'est pas au ratio ${o.ratio}.`, { width: p.width, height: p.height });215216  const tplRaw = watermarkTemplate(p.width, p.height, o.ratio, BRAND_TEXT);217  const region = tplRaw.region;218  const tpl = { w: region.w, h: region.h, text: tplRaw.textCoverage, mask: tplRaw.plateMask };219  const search = Math.max(2, Math.round((4 * p.height) / (o.ratio === "9:16" ? 1920 : 1080)));220  const crop = { x: region.x - search, y: region.y - search, w: region.w + 2 * search, h: region.h + 2 * search };221  if (crop.x < 0 || crop.y < 0 || crop.x + crop.w > p.width || crop.y + crop.h > p.height) return fail("Région du filigrane hors de l'image.", { region });222223  const D = p.duration;224  const frameDur = 1 / (p.fps || 30);225  const count = Math.max(8, Math.round(o.samples ?? 10));226  const times: { t: number; where: string }[] = [{ t: 0, where: "première trame" }, { t: -1, where: "dernière trame" }, { t: D / 2, where: "milieu" }];227  if (o.endCardSeconds && o.endCardSeconds > 0 && o.endCardSeconds < D) {228    times.push({ t: Math.max(0, D - o.endCardSeconds - 2 * frameDur), where: "juste avant le carton" }, { t: D - o.endCardSeconds / 2, where: "pendant le carton" });229  } else {230    times.push({ t: Math.max(0, D - Math.min(4.5, D * 0.3)), where: "fin du programme (estimée)" }, { t: Math.max(0, D - Math.min(0.75, D * 0.1)), where: "fin / carton" });231  }232  const rest = count - times.length;233  for (let i = 1; i <= rest; i++) times.push({ t: (D * (i - 0.37)) / rest, where: "réparti" });234  // instants croissants, distincts d'au moins deux trames, bornés avant la fin235  const last = times.find((s) => s.t < 0)!;236  const timed = times.filter((s) => s.t >= 0).sort((a, b) => a.t - b.t);237  const maxT = Math.max(0, D - 3 * frameDur);238  for (const [i, s] of timed.entries()) s.t = Math.min(maxT, i ? Math.max(s.t, timed[i - 1].t + 2 * frameDur) : s.t);239240  // MP4 : recherche directe, exacte à la trame. HLS : un seul décodage (la recherche `-ss` y est imprécise).241  const isHls = /hls|applehttp/.test(p.format ?? "") || /\.m3u8($|\?)/i.test(o.file);242  let grabbed: (Buffer | null)[];243  if (isHls) {244    try { grabbed = await grayFramesSinglePass(o.file, timed.map((s) => s.t), crop); } catch { grabbed = timed.map(() => null); }245  } else {246    grabbed = [];247    for (const s of timed) { try { grabbed.push((await grayFrame(o.file, s.t, crop))?.data ?? null); } catch { grabbed.push(null); } }248  }249  let lastFrame: Buffer | null = null;250  try { lastFrame = (await grayFrame(o.file, -1, crop))?.data ?? null; } catch { lastFrame = null; }251252  const frames: WatermarkFrameMeasure[] = [];253  for (const [i, s] of [...timed, last].entries()) {254    const data = i < timed.length ? grabbed[i] : lastFrame;255    const t = s.t < 0 ? r3(D) : r3(s.t);256    if (!data) { frames.push({ t, ncc: 0, contrast: 0, dx: 0, dy: 0, ok: false, where: `${s.where} (trame non extraite)` }); continue; }257    const m = matchTemplate(data, crop.w, tpl, search);258    frames.push({ t, ncc: r3(m.ncc), contrast: Math.round(m.contrast * 10) / 10, dx: m.dx, dy: m.dy,259      ok: m.ncc >= WATERMARK_THRESHOLDS.minNcc && m.contrast >= WATERMARK_THRESHOLDS.minContrast, where: s.where });260  }261  frames.sort((a, b) => a.t - b.t);262  const bad = frames.filter((f) => !f.ok);263  const minNcc = Math.min(...frames.map((f) => f.ncc)), minContrast = Math.min(...frames.map((f) => f.contrast));264  return {265    key: "watermark", label, status: bad.length ? "fail" : "pass", blocking: true,266    measured: { text: BRAND_TEXT, ratio: o.ratio, width: p.width, height: p.height, durationSeconds: r3(D), region, searchPx: search, samples: frames.length,267      minNcc: r3(minNcc), minContrast, thresholds: WATERMARK_THRESHOLDS, failedFrames: bad.length, frames },268    detail: bad.length269      ? `Filigrane absent ou non conforme sur ${bad.length}/${frames.length} trame(s) (corrélation min. ${minNcc.toFixed(2)}, contraste min. ${minContrast.toFixed(0)} ; seuils ${WATERMARK_THRESHOLDS.minNcc} / ${WATERMARK_THRESHOLDS.minContrast}).`270      : `Filigrane mesuré sur ${frames.length}/${frames.length} trames (corrélation min. ${minNcc.toFixed(2)}, contraste min. ${minContrast.toFixed(0)}).`,271  };272}273
Files main
Menu

Theme