SPB Git

Repository Public

brand.ts 12.1 KB 234 lines typescript

1import { BRAND_TEXT, FRAME_SIZES, type Lang, type Ratio } from "../lib/contracts";2import { rm } from "node:fs/promises";3import { renderSting } from "./audio";4import { clamp01, displayFont, easeInOutCubic, easeOutCubic, easeOutExpo, fitText, font, newCanvas, PALETTE, prog, renderCanvasVideo, roundRect, type Ctx } from "./canvas";5import { drawHalo, GOLD, goldFill, INK, makeBackdrop, rgba } from "./design";67/**8 * RÈGLE DE MARQUE : chaque vidéo exportée porte le texte exact `clip.spboucher.ai` sur toute sa durée.9 *10 * Dessin du filigrane : texte Inter SemiBold clair (#f2f3f5, opacité 0,92) sur une fine plaque sombre arrondie (#0b0c0f, opacité 0,55).11 * La plaque garantit un contraste texte/fond mesurable quel que soit le plan (très clair, très sombre, chargé) : c'est ce contraste12 * que `verifyWatermark` (qc.ts) mesure par corrélation normalisée contre le gabarit.13 *14 * Zone sûre par ratio (sous-titres = bas centre, jamais recouverts) :15 *  - 16:9 : haut droite, marges 5 % (largeur) / 5,5 % (hauteur) ;16 *  - 9:16 : haut gauche, à 11 % du haut (sous les onglets des applis sociales), 6 % du bord gauche ; la colonne de boutons à droite17 *           et le tiers bas (légende, barre de progression) sont évités ;18 *  - 1:1  : haut droite, marges 5 %.19 * La géométrie est définie sur la trame de référence (FRAME_SIZES[ratio].final) puis mise à l'échelle : un aperçu 480p ou une variante20 * HLS porte exactement le même filigrane, à l'échelle.21 */22const DESIGN = { fontPx: 30, padX: 16, padY: 9, radius: 8, plateAlpha: 0.55, textAlpha: 0.92, weight: 600 as const };23const ANCHOR: Record<Ratio, { corner: "top-right" | "top-left"; mx: number; my: number }> = {24  "16:9": { corner: "top-right", mx: 0.05, my: 0.055 },25  "9:16": { corner: "top-left", mx: 0.06, my: 0.11 },26  "1:1": { corner: "top-right", mx: 0.05, my: 0.05 },27};2829export interface WatermarkLayout {30  ratio: Ratio; text: string; refWidth: number; refHeight: number; sx: number; sy: number;31  /** Plaque, en pixels de la trame de référence. */32  plate: { x: number; y: number; w: number; h: number };33  baseline: { x: number; y: number };34  /** Plaque, en pixels entiers de la trame demandée. */35  region: { x: number; y: number; w: number; h: number };36}3738export function watermarkLayout(width: number, height: number, ratio: Ratio, text: string = BRAND_TEXT): WatermarkLayout {39  const ref = FRAME_SIZES[ratio].final;40  const { ctx } = newCanvas(8, 8);41  ctx.font = font(DESIGN.weight, DESIGN.fontPx);42  const m = ctx.measureText(text);43  const tw = Math.ceil(m.width);44  const w = tw + 2 * DESIGN.padX;45  const h = Math.round(DESIGN.fontPx * 1.0) + 2 * DESIGN.padY;46  const a = ANCHOR[ratio];47  const x = a.corner === "top-right" ? Math.round(ref.width * (1 - a.mx)) - w : Math.round(ref.width * a.mx);48  const y = Math.round(ref.height * a.my);49  const sx = width / ref.width, sy = height / ref.height;50  const rx = Math.floor(x * sx), ry = Math.floor(y * sy);51  return {52    ratio, text, refWidth: ref.width, refHeight: ref.height, sx, sy,53    plate: { x, y, w, h },54    baseline: { x: x + DESIGN.padX, y: y + DESIGN.padY + Math.round(DESIGN.fontPx * 0.84) },55    region: { x: rx, y: ry, w: Math.ceil((x + w) * sx) - rx, h: Math.ceil((y + h) * sy) - ry },56  };57}5859function drawWatermark(ctx: Ctx, l: WatermarkLayout, layers: { plate: boolean; text: boolean }, solid = false): void {60  ctx.save();61  ctx.scale(l.sx, l.sy);62  if (layers.plate) {63    roundRect(ctx, l.plate.x, l.plate.y, l.plate.w, l.plate.h, DESIGN.radius);64    ctx.fillStyle = solid ? "#ffffff" : `rgba(11,12,15,${DESIGN.plateAlpha})`;65    ctx.fill();66  }67  if (layers.text) {68    ctx.font = font(DESIGN.weight, DESIGN.fontPx);69    ctx.textBaseline = "alphabetic";70    ctx.fillStyle = solid ? "#ffffff" : `rgba(242,243,245,${DESIGN.textAlpha})`;71    ctx.fillText(l.text, l.baseline.x, l.baseline.y);72  }73  ctx.restore();74}7576/** Variante interne (tests, QC) : même dessin avec un texte ou un décalage arbitraires. */77export async function renderWatermarkWith(o: { width: number; height: number; ratio: Ratio; text?: string; offset?: { dx: number; dy: number } }): Promise<{ png: Buffer; region: { x: number; y: number; w: number; h: number }; params: Record<string, unknown> }> {78  const l = watermarkLayout(o.width, o.height, o.ratio, o.text ?? BRAND_TEXT);79  const { canvas, ctx } = newCanvas(o.width, o.height);80  if (o.offset) ctx.translate(o.offset.dx, o.offset.dy);81  drawWatermark(ctx, l, { plate: true, text: true });82  return {83    png: await canvas.encode("png"),84    region: l.region,85    params: {86      text: l.text, ratio: o.ratio, width: o.width, height: o.height, corner: ANCHOR[o.ratio].corner, font: "Inter SemiBold",87      fontPx: +(DESIGN.fontPx * l.sy).toFixed(2), plateOpacity: DESIGN.plateAlpha, textOpacity: DESIGN.textAlpha, textColor: PALETTE.text, plateColor: PALETTE.bg,88      region: l.region, referenceFrame: { width: l.refWidth, height: l.refHeight },89    },90  };91}9293/** PNG pleine trame transparent du filigrane `clip.spboucher.ai`, région exacte de la plaque et paramètres de dessin. */94export async function renderWatermark(o: { width: number; height: number; ratio: Ratio }): Promise<{ png: Buffer; region: { x: number; y: number; w: number; h: number }; params: Record<string, unknown> }> {95  return renderWatermarkWith({ width: o.width, height: o.height, ratio: o.ratio });96}9798/**99 * Gabarit de vérification à la résolution demandée : couverture du texte (0–255) et masque de la plaque (0–255) sur la région de la plaque.100 * Utilisé par `verifyWatermark`.101 */102export function watermarkTemplate(width: number, height: number, ratio: Ratio, text: string = BRAND_TEXT): { region: { x: number; y: number; w: number; h: number }; textCoverage: Uint8Array; plateMask: Uint8Array } {103  const l = watermarkLayout(width, height, ratio, text);104  const grab = (layers: { plate: boolean; text: boolean }) => {105    const { ctx } = newCanvas(width, height);106    drawWatermark(ctx, l, layers, true);107    const d = ctx.getImageData(l.region.x, l.region.y, l.region.w, l.region.h).data;108    const out = new Uint8Array(l.region.w * l.region.h);109    for (let i = 0; i < out.length; i++) out[i] = d[i * 4 + 3];110    return out;111  };112  return { region: l.region, textCoverage: grab({ plate: false, text: true }), plateMask: grab({ plate: true, text: false }) };113}114115const DEFAULT_TAGLINE: Record<Lang, string> = { fr: "Production vidéo agentique", en: "Agentic video production" };116117/**118 * Carton de fin — signature de chaîne : décor de marque animé, anneaux qui se tracent, mot-symbole « SP CLIP » révélé lettre à lettre119 * derrière un masque (SP en or, CLIP en clair), reflet qui traverse, filet or qui s'ouvre depuis le centre, URL clip.spboucher.ai,120 * slogan en Instrument Serif italique. Ouverture en fondu depuis le noir ; le décor et le halo restent en mouvement jusqu'à la fin.121 * Sortie : clip intermédiaire (H.264 CRF 12 + PCM 48 kHz stéréo). Le filigrane est ajouté par-dessus par `finishMaster`.122 * `sting` (facultatif) : remplace le silence par une courte signature sonore originale synthétisée (accord qui s'ouvre, voir audio.ts).123 */124export async function renderEndCard(o: { width: number; height: number; language: Lang; tagline: string; seconds: number; fps: number; output: string; sting?: boolean }): Promise<void> {125  const { width: W, height: H } = o;126  const u = Math.min(W, H) / 1080;127  const tagline = o.tagline.trim() || DEFAULT_TAGLINE[o.language];128  const probeCtx = newCanvas(8, 8).ctx;129  const tag = fitText(probeCtx, tagline, { weight: 400, fontOf: (px) => displayFont(px, true), max: 54 * u, min: 30 * u, maxWidth: W * 0.8, maxLines: 2 });130  const k = Math.min(1, Math.max(0.4, o.seconds / 3.2));131  const cx = W / 2, cy = H * 0.455;132  const wordSize = Math.min(172 * u, (W * 0.8) / 4.6);133  const tracking = wordSize * 0.05;134  probeCtx.font = font(700, wordSize);135  const letters = Array.from("SP CLIP").map((ch) => ({ ch, w: ch === " " ? wordSize * 0.3 : probeCtx.measureText(ch).width + tracking }));136  const wordW = letters.reduce((a, l) => a + l.w, 0) - tracking;137  const baseY = cy + wordSize * 0.2;138  const backdrop = makeBackdrop({ width: W, height: H, seed: 0x5bc11b, variant: "orbits", focus: { x: 0.5, y: 0.42 }, energy: 0.8, intro: 0.9 * k, fps: o.fps });139  const urlSize = 50 * u;140  let sting: string | null = null;141  if (o.sting) {142    sting = `${o.output}.sting.wav`;143    await renderSting({ seconds: Math.round(o.seconds * o.fps) / o.fps, output: sting });144  }145146  const rise = (ctx: Ctx, t: number, start: number, draw: () => void) => {147    const p = prog(t, start * k, 0.9 * k);148    if (p <= 0) return;149    ctx.save();150    ctx.globalAlpha *= easeOutCubic(Math.min(1, p * 1.5));151    ctx.translate(0, (1 - easeOutExpo(p)) * 22 * u);152    draw();153    ctx.restore();154  };155156  try {157    await renderCanvasVideo({158      width: W, height: H, fps: o.fps, seconds: o.seconds, output: o.output,159      ...(sting ? { audioInput: ["-i", sting] } : {}),160      draw: (ctx, t) => {161        backdrop.draw(ctx, t);162        // halo de marque qui respire derrière le mot-symbole163        drawHalo(ctx, cx, cy, Math.min(W, H) * 0.62, GOLD, (0.1 + 0.03 * Math.sin(t * 1.6)) * easeOutCubic(prog(t, 0, 1.2 * k)));164        // anneaux : deux arcs fins qui se tracent en sens opposés, puis tournent lentement165        const ring = (radius: number, start: number, dir: 1 | -1, alpha: number) => {166          const p = easeInOutCubic(prog(t, start * k, 1.6 * k));167          if (p <= 0) return;168          const a0 = -Math.PI / 2 + dir * t * 0.12;169          ctx.strokeStyle = rgba(GOLD, alpha);170          ctx.lineWidth = Math.max(1.2, 2 * u);171          ctx.beginPath();172          ctx.arc(cx, cy, radius, a0, a0 + dir * Math.PI * 2 * p * 0.86, dir < 0);173          ctx.stroke();174        };175        ring(Math.min(W, H) * 0.4, 0.05, 1, 0.5);176        ring(Math.min(W, H) * 0.445, 0.25, -1, 0.2);177178        // mot-symbole : lettres révélées derrière un masque, une à une179        ctx.save();180        ctx.font = font(700, wordSize);181        ctx.textAlign = "left";182        ctx.textBaseline = "alphabetic";183        const sweep = ((t - 1.5 * k) % 3.2) / 1.0;184        const clipGrad = ctx.createLinearGradient(cx - wordW / 2, 0, cx + wordW / 2, 0);185        clipGrad.addColorStop(0, PALETTE.text);186        if (sweep > 0.08 && sweep < 0.92) { clipGrad.addColorStop(sweep - 0.08, PALETTE.text); clipGrad.addColorStop(sweep, "#ffffff"); clipGrad.addColorStop(sweep + 0.08, PALETTE.text); }187        clipGrad.addColorStop(1, PALETTE.text);188        let x = cx - wordW / 2;189        letters.forEach((l, i) => {190          const p = easeOutExpo(prog(t, (0.2 + i * 0.075) * k, 0.95 * k));191          if (p > 0.001 && l.ch !== " ") {192            ctx.save();193            ctx.beginPath();194            ctx.rect(x - tracking, baseY - wordSize * 0.86, l.w + tracking, wordSize * 1.02);195            ctx.clip();196            ctx.globalAlpha *= Math.min(1, p * 1.5);197            ctx.fillStyle = i < 2 ? goldFill(ctx, cx - wordW / 2, cx + wordW / 2, sweep) : clipGrad;198            ctx.fillText(l.ch, x, baseY + (1 - p) * wordSize * 0.9);199            ctx.restore();200          }201          x += l.w;202        });203        ctx.restore();204205        // filet or qui s'ouvre depuis le centre206        const lp = easeOutExpo(prog(t, 0.75 * k, 1 * k));207        if (lp > 0) {208          ctx.fillStyle = PALETTE.accent;209          const lw = wordW * 0.52 * lp;210          ctx.fillRect(cx - lw / 2, baseY + 44 * u, lw, Math.max(2, 3 * u));211        }212        ctx.textAlign = "center";213        rise(ctx, t, 0.9, () => {214          ctx.font = font(600, urlSize);215          ctx.letterSpacing = `${(urlSize * 0.02).toFixed(2)}px`;216          ctx.fillStyle = PALETTE.text;217          ctx.fillText(BRAND_TEXT, cx, baseY + 44 * u + 84 * u);218          ctx.letterSpacing = "0px";219        });220        rise(ctx, t, 1.15, () => {221          ctx.font = displayFont(tag.size, true);222          ctx.fillStyle = INK.soft;223          tag.lines.forEach((line, i) => ctx.fillText(line, cx, baseY + 44 * u + 84 * u + 40 * u + tag.size * 0.86 + i * tag.size * 1.2));224        });225        // fondu d'entrée depuis le noir226        const fade = 1 - clamp01(t / (0.4 * k));227        if (fade > 0) { ctx.fillStyle = `rgba(0,0,0,${fade.toFixed(3)})`; ctx.fillRect(0, 0, W, H); }228      },229    });230  } finally {231    if (sting) await rm(sting, { force: true });232  }233}234
Files main
Menu

Theme