Repository Public
1import { rm, writeFile } from "node:fs/promises";2import path from "node:path";3import { afterAll, beforeAll, describe, expect, it } from "vitest";4import { BRAND_TEXT, FPS, FRAME_SIZES, type QcCheck, type Ratio } from "../src/lib/contracts";5import { renderEndCard, renderWatermark, renderWatermarkWith } from "../src/media/brand";6import { finishMaster } from "../src/media/compose";7import { ff, probe } from "../src/media/ffmpeg";8import { packageHls } from "../src/media/hls";9import { verifyWatermark, WATERMARK_THRESHOLDS, type WatermarkFrameMeasure } from "../src/media/qc";10import { BACKGROUNDS, makeVideo, tmpDir } from "./fixtures/media";1112/**13 * Règle de marque : le filigrane `clip.spboucher.ai` doit être mesuré sur toute la durée de chaque fichier livré.14 * Positifs : masters réels (finishMaster) en 16:9, 9:16 et 1:1 sur fond clair, sombre et chargé, puis après passage HLS.15 * Négatifs : même vidéo sans filigrane, avec un autre texte, avec le filigrane déplacé.16 * Les mesures de calibration (70 positifs, 96 négatifs) sont documentées dans src/media/qc.ts (WATERMARK_THRESHOLDS).17 */18const T = 240_000;19const RATIOS: Ratio[] = ["16:9", "9:16", "1:1"];20const CARD = 2;21let dir = "";22const f = (name: string) => path.join(dir, name);23const tag = (ratio: Ratio, bg: string) => `${ratio.replace(":", "x")}-${bg}`;24const frames = (c: QcCheck) => c.measured.frames as WatermarkFrameMeasure[];25const report: string[] = [];26const note = (name: string, c: QcCheck) => report.push(`${name.padEnd(44)} ${c.status.padEnd(4)} ncc min ${String(c.measured.minNcc).padEnd(6)} contraste min ${c.measured.minContrast}`);2728beforeAll(async () => {29 dir = await tmpDir("watermark");30 for (const ratio of RATIOS) for (const [bg, source] of Object.entries(BACKGROUNDS)) {31 await makeVideo(f(`prog-${tag(ratio, bg)}.mkv`), { source, ...FRAME_SIZES[ratio].final, seconds: 4, audio: "sine" });32 }33}, T);34afterAll(async () => {35 console.log(`Mesures du filigrane (seuils ncc ≥ ${WATERMARK_THRESHOLDS.minNcc}, contraste ≥ ${WATERMARK_THRESHOLDS.minContrast})\n${report.join("\n")}`);36 if (dir) await rm(dir, { recursive: true, force: true });37});3839describe("renderWatermark", () => {40 it.each(RATIOS)("%s : PNG pleine trame transparent, région dans la zone sûre, loin des sous-titres", async (ratio) => {41 const { width, height } = FRAME_SIZES[ratio].final;42 const wm = await renderWatermark({ width, height, ratio });43 await writeFile(f(`wm-${ratio.replace(":", "x")}.png`), wm.png);44 expect(await probe(f(`wm-${ratio.replace(":", "x")}.png`))).toMatchObject({ width, height, pixFmt: "rgba" });45 expect(wm.params).toMatchObject({ text: BRAND_TEXT, ratio });46 const r = wm.region;47 expect(r.x).toBeGreaterThanOrEqual(width * 0.04);48 expect(r.x + r.w).toBeLessThanOrEqual(width * 0.96);49 expect(r.y).toBeGreaterThanOrEqual(height * 0.04);50 expect(r.y + r.h).toBeLessThan(height * 0.2); // en haut : jamais dans la zone des sous-titres (bas centre)51 if (ratio === "9:16") {52 expect(r.y).toBeGreaterThanOrEqual(height * 0.1); // sous les onglets des applis sociales53 expect(r.x + r.w).toBeLessThan(width * 0.8); // hors de la colonne de boutons à droite54 }55 // même géométrie relative à l'échelle de l'aperçu56 const p = FRAME_SIZES[ratio].preview;57 const small = await renderWatermark({ ...p, ratio });58 expect(small.region.x / p.width).toBeCloseTo(r.x / width, 2);59 expect(small.region.w / p.width).toBeCloseTo(r.w / width, 1);60 }, T);6162 it("renderEndCard : clip à la bonne taille avec piste silencieuse 48 kHz stéréo", async () => {63 await renderEndCard({ width: 480, height: 854, language: "en", tagline: "Agentic video production", seconds: 2, fps: FPS, output: f("card.mkv") });64 const p = await probe(f("card.mkv"));65 expect(p).toMatchObject({ width: 480, height: 854, fps: FPS, hasAudio: true, sampleRate: 48000, channels: 2 });66 expect(p.duration).toBeCloseTo(2, 2);67 }, T);68});6970describe("verifyWatermark — positifs", () => {71 for (const ratio of RATIOS) for (const bg of Object.keys(BACKGROUNDS)) {72 it(`master ${ratio} sur fond ${bg}`, async () => {73 const out = f(`master-${tag(ratio, bg)}.mp4`);74 await finishMaster({ program: f(`prog-${tag(ratio, bg)}.mkv`), output: out, ...FRAME_SIZES[ratio].final, fps: FPS, ratio, language: "fr", endCard: { seconds: CARD, tagline: "" }, metadata: {}, workDir: f(`w-${tag(ratio, bg)}`) });75 const c = await verifyWatermark({ file: out, ratio, endCardSeconds: CARD });76 note(`+ master ${ratio} ${bg}`, c);77 expect(c).toMatchObject({ key: "watermark", status: "pass", blocking: true });78 expect(frames(c).length).toBeGreaterThanOrEqual(8);79 expect(frames(c).every((x) => x.ok && x.ncc >= WATERMARK_THRESHOLDS.minNcc + 0.1)).toBe(true);80 // début, juste avant le carton, pendant le carton, dernière trame81 const where = frames(c).map((x) => x.where);82 for (const w of ["première trame", "milieu", "juste avant le carton", "pendant le carton", "dernière trame"]) expect(where).toContain(w);83 expect(frames(c)[0].t).toBe(0);84 expect(frames(c).at(-1)!.t).toBeCloseTo(4 + CARD, 1);85 // sans indication du carton : même verdict, 12 trames demandées86 const d = await verifyWatermark({ file: out, ratio, samples: 12 });87 expect(d.status).toBe("pass");88 expect(frames(d)).toHaveLength(12);89 }, T);90 }9192 it.each(RATIOS)("aperçu %s (480p, encodage léger)", async (ratio) => {93 const out = f(`preview-${tag(ratio, "charge")}.mp4`);94 await finishMaster({ program: f(`prog-${tag(ratio, "charge")}.mkv`), output: out, ...FRAME_SIZES[ratio].preview, fps: FPS, ratio, language: "fr", endCard: { seconds: CARD, tagline: "" }, preview: true, metadata: {}, workDir: f(`wp-${tag(ratio, "charge")}`) });95 const c = await verifyWatermark({ file: out, ratio });96 note(`+ aperçu ${ratio} chargé`, c);97 expect(c.status).toBe("pass");98 }, T);99100 it.each(RATIOS)("après passage HLS %s (fonds clair et chargé, toutes les variantes + playlist maîtresse)", async (ratio) => {101 for (const bg of ["clair", "charge"]) {102 const hls = await packageHls({ input: f(`master-${tag(ratio, bg)}.mp4`), outDir: f(`hls-${tag(ratio, bg)}`), sourceHeight: FRAME_SIZES[ratio].final.height, language: "fr" });103 expect(hls.renditions).toHaveLength(4);104 for (const r of hls.renditions) {105 const c = await verifyWatermark({ file: path.join(f(`hls-${tag(ratio, bg)}`), r.uri!), ratio, endCardSeconds: CARD });106 note(`+ HLS ${r.width}x${r.height} ${ratio} ${bg}`, c);107 expect(c.status, `${r.width}x${r.height} ${bg} : ${c.detail}`).toBe("pass");108 }109 expect((await verifyWatermark({ file: hls.master, ratio })).status).toBe("pass");110 }111 }, T);112});113114describe("verifyWatermark — négatifs", () => {115 /** Même programme + carton, encodé comme un master, avec un filigrane arbitraire (ou aucun). */116 async function forge(ratio: Ratio, bg: string, name: string, png: Buffer | null, size = FRAME_SIZES[ratio].final): Promise<string> {117 const out = f(`neg-${name}-${tag(ratio, bg)}.mp4`);118 const scale = `scale=${size.width}:${size.height},format=yuv420p`;119 if (png) {120 await writeFile(f("neg.png"), png);121 await ff(["-i", f(`prog-${tag(ratio, bg)}.mkv`), "-i", f("neg.png"), "-filter_complex", `[0:v]${scale}[s];[s][1:v]overlay=0:0,format=yuv420p`, "-c:v", "libx264", "-preset", "veryfast", "-crf", "18", "-c:a", "aac", out]);122 } else await ff(["-i", f(`prog-${tag(ratio, bg)}.mkv`), "-vf", scale, "-c:v", "libx264", "-preset", "veryfast", "-crf", "18", "-c:a", "aac", out]);123 return out;124 }125 const cases: [Ratio, string][] = [["16:9", "charge"], ["16:9", "sombre"], ["9:16", "clair"], ["1:1", "charge"]];126127 it.each(cases)("%s fond %s : sans filigrane", async (ratio, bg) => {128 const c = await verifyWatermark({ file: await forge(ratio, bg, "none", null), ratio });129 note(`- sans filigrane ${ratio} ${bg}`, c);130 expect(c).toMatchObject({ status: "fail", blocking: true });131 expect(c.measured.failedFrames).toBe(10);132 expect(c.measured.minNcc as number).toBeLessThan(0.2);133 }, T);134135 it.each(cases)("%s fond %s : autre texte", async (ratio, bg) => {136 const size = FRAME_SIZES[ratio].final;137 for (const text of ["clip.example.com", "www.exemple.org", "CLIP.SPBOUCHER.AI"]) {138 const c = await verifyWatermark({ file: await forge(ratio, bg, "text", (await renderWatermarkWith({ ...size, ratio, text })).png), ratio });139 note(`- texte « ${text} » ${ratio} ${bg}`, c);140 expect(c.status, text).toBe("fail");141 expect(frames(c).every((x) => !x.ok), text).toBe(true);142 }143 // aussi à la taille d'aperçu, où le texte est plus petit144 const p = FRAME_SIZES[ratio].preview;145 const c = await verifyWatermark({ file: await forge(ratio, bg, "text-small", (await renderWatermarkWith({ ...p, ratio, text: "clip.example.com" })).png, p), ratio });146 note(`- texte « clip.example.com » 480p ${ratio} ${bg}`, c);147 expect(c.status).toBe("fail");148 }, T);149150 it.each(cases)("%s fond %s : filigrane déplacé", async (ratio, bg) => {151 const size = FRAME_SIZES[ratio].final;152 for (const offset of [{ dx: 12, dy: 0 }, { dx: 0, dy: 10 }, { dx: ratio === "9:16" ? 400 : -400, dy: 500 }]) {153 const c = await verifyWatermark({ file: await forge(ratio, bg, "moved", (await renderWatermarkWith({ ...size, ratio, offset })).png), ratio });154 note(`- décalé (${offset.dx}, ${offset.dy}) ${ratio} ${bg}`, c);155 expect(c.status, JSON.stringify(offset)).toBe("fail");156 expect(frames(c).every((x) => !x.ok)).toBe(true);157 }158 }, T);159160 it("filigrane présent seulement sur une partie de la durée → échec (une trame non conforme suffit)", async () => {161 const size = FRAME_SIZES["16:9"].final;162 await writeFile(f("wm.png"), (await renderWatermark({ ...size, ratio: "16:9" })).png);163 await ff(["-i", f("prog-16x9-charge.mkv"), "-i", f("wm.png"), "-filter_complex", "[0:v][1:v]overlay=0:0:enable='lt(t,2.6)',format=yuv420p", "-c:v", "libx264", "-preset", "veryfast", "-crf", "18", "-c:a", "aac", f("partial.mp4")]);164 const c = await verifyWatermark({ file: f("partial.mp4"), ratio: "16:9" });165 expect(c.status).toBe("fail");166 const bad = frames(c).filter((x) => !x.ok);167 expect(bad.length).toBeGreaterThan(0);168 expect(bad.length).toBeLessThan(frames(c).length);169 expect(bad.every((x) => x.t >= 2.6)).toBe(true);170 expect(frames(c).filter((x) => x.ok).every((x) => x.t < 2.6)).toBe(true);171 }, T);172173 it("mauvais ratio annoncé ou fichier illisible → échec bloquant explicite", async () => {174 const c = await verifyWatermark({ file: f("master-16x9-charge.mp4"), ratio: "9:16" });175 expect(c).toMatchObject({ status: "fail", blocking: true });176 await writeFile(f("junk.mp4"), "junk");177 expect(await verifyWatermark({ file: f("junk.mp4"), ratio: "16:9" })).toMatchObject({ status: "fail", blocking: true });178 }, T);179});180