Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

15.3 KB
Raw Blame
/**
 * Time-lapse Frame Compositor & Watermark Engine
 *
 * Shared WYSIWYG renderer used across:
 * 1. In-app preview player (modal + full-screen)
 * 2. MediaRecorder video export (.webm/.mp4)
 * 3. Transparent PNG overlay generation for native FFmpeg `.mp4` export
 */

import { canvasToBlob } from './saveManager';
import { safeLocalStorageGetItem, safeLocalStorageSetItem } from './safeStorage';

export type TimelapseWatermarkMode = 'text' | 'image';
export type TimelapseWatermarkFontStyle = 'sans' | 'bold' | 'mono' | 'serif';
export type TimelapseWatermarkPosition =
  | 'top-left'
  | 'top-center'
  | 'top-right'
  | 'center'
  | 'bottom-left'
  | 'bottom-center'
  | 'bottom-right';

export type TimelapseBackgroundMode = 'white' | 'dark' | 'blur' | 'custom';

export interface TimelapseWatermarkConfig {
  enabled: boolean;
  mode: TimelapseWatermarkMode;
  text: string;
  fontStyle: TimelapseWatermarkFontStyle;
  textColor: string;
  showBackdrop: boolean;
  imageDataUrl: string | null;
  position: TimelapseWatermarkPosition;
  /** Size scale relative to output frame width (5..40, default 14). */
  scale: number;
  /** Opacity (0.1..1, default 0.78). */
  opacity: number;
  /** Edge padding percentage of shorter frame dimension (1..12, default 3). */
  margin: number;
}

export const DEFAULT_TIMELAPSE_WATERMARK: TimelapseWatermarkConfig = {
  enabled: false,
  mode: 'text',
  text: 'Ink Studio',
  fontStyle: 'sans',
  textColor: '#ffffff',
  showBackdrop: true,
  imageDataUrl: null,
  position: 'bottom-right',
  scale: 14,
  opacity: 0.78,
  margin: 3,
};

const WATERMARK_PREFS_LS_KEY = 'inkstudio_timelapse_watermark_v1';

export function sanitizeWatermarkConfig(
  raw: Partial<TimelapseWatermarkConfig> | null | undefined,
  fallbackText?: string
): TimelapseWatermarkConfig {
  const base: TimelapseWatermarkConfig = {
    ...DEFAULT_TIMELAPSE_WATERMARK,
    ...(fallbackText && fallbackText.trim() ? { text: fallbackText.trim() } : {}),
  };
  if (!raw || typeof raw !== 'object') return base;

  const mode: TimelapseWatermarkMode = raw.mode === 'image' ? 'image' : 'text';
  const fontStyle: TimelapseWatermarkFontStyle =
    raw.fontStyle === 'bold' || raw.fontStyle === 'mono' || raw.fontStyle === 'serif'
      ? raw.fontStyle
      : 'sans';
  const validPositions: TimelapseWatermarkPosition[] = [
    'top-left',
    'top-center',
    'top-right',
    'center',
    'bottom-left',
    'bottom-center',
    'bottom-right',
  ];
  const position = validPositions.includes(raw.position as TimelapseWatermarkPosition)
    ? (raw.position as TimelapseWatermarkPosition)
    : base.position;

  const textColor =
    typeof raw.textColor === 'string' && /^#[0-9a-fA-F]{6}$/.test(raw.textColor.trim())
      ? raw.textColor.trim()
      : base.textColor;

  return {
    enabled: Boolean(raw.enabled),
    mode,
    text: typeof raw.text === 'string' ? raw.text.slice(0, 80) : base.text,
    fontStyle,
    textColor,
    showBackdrop: raw.showBackdrop !== false,
    imageDataUrl:
      typeof raw.imageDataUrl === 'string' && raw.imageDataUrl.startsWith('data:image/')
        ? raw.imageDataUrl
        : null,
    position,
    scale: Math.max(5, Math.min(40, Number(raw.scale) || base.scale)),
    opacity: Math.max(0.1, Math.min(1, Number(raw.opacity) || base.opacity)),
    margin: Math.max(0, Math.min(15, Number(raw.margin ?? base.margin))),
  };
}

export function loadSavedWatermarkConfig(fallbackText?: string): TimelapseWatermarkConfig {
  try {
    const raw = safeLocalStorageGetItem(WATERMARK_PREFS_LS_KEY);
    if (!raw) return sanitizeWatermarkConfig(null, fallbackText);
    return sanitizeWatermarkConfig(JSON.parse(raw), fallbackText);
  } catch {
    return sanitizeWatermarkConfig(null, fallbackText);
  }
}

export function saveWatermarkConfig(config: TimelapseWatermarkConfig): void {
  const clean = sanitizeWatermarkConfig(config);
  safeLocalStorageSetItem(WATERMARK_PREFS_LS_KEY, JSON.stringify(clean), 'timelapse watermark');
}

export function computeWatermarkPosition(
  frameW: number,
  frameH: number,
  boxW: number,
  boxH: number,
  position: TimelapseWatermarkPosition,
  marginPct: number
): { x: number; y: number } {
  const pad = Math.round(Math.min(frameW, frameH) * (Math.max(0, Math.min(20, marginPct)) / 100));
  let x = pad;
  let y = pad;

  if (position === 'top-center' || position === 'center' || position === 'bottom-center') {
    x = Math.round((frameW - boxW) * 0.5);
  } else if (position === 'top-right' || position === 'bottom-right') {
    x = Math.round(frameW - boxW - pad);
  }

  if (position === 'center') {
    y = Math.round((frameH - boxH) * 0.5);
  } else if (
    position === 'bottom-left' ||
    position === 'bottom-center' ||
    position === 'bottom-right'
  ) {
    y = Math.round(frameH - boxH - pad);
  }

  return {
    x: Math.max(0, Math.min(Math.max(0, frameW - boxW), x)),
    y: Math.max(0, Math.min(Math.max(0, frameH - boxH), y)),
  };
}

function resolveWatermarkFont(style: TimelapseWatermarkFontStyle, pxSize: number): string {
  const size = Math.max(10, Math.round(pxSize));
  switch (style) {
    case 'bold':
      return `800 ${size}px Inter, "Segoe UI", system-ui, sans-serif`;
    case 'mono':
      return `600 ${size}px "JetBrains Mono", "Cascadia Code", Consolas, monospace`;
    case 'serif':
      return `600 ${size}px Georgia, "Times New Roman", serif`;
    default:
      return `600 ${size}px Inter, "Segoe UI", system-ui, sans-serif`;
  }
}

function drawRoundedRectPath(
  ctx: CanvasRenderingContext2D,
  x: number,
  y: number,
  w: number,
  h: number,
  r: number
): void {
  const radius = Math.max(0, Math.min(r, Math.min(w, h) * 0.5));
  if (typeof ctx.roundRect === 'function') {
    ctx.beginPath();
    ctx.roundRect(x, y, w, h, radius);
    return;
  }
  ctx.beginPath();
  ctx.moveTo(x + radius, y);
  ctx.lineTo(x + w - radius, y);
  ctx.quadraticCurveTo(x + w, y, x + w, y + radius);
  ctx.lineTo(x + w, y + h - radius);
  ctx.quadraticCurveTo(x + w, y + h, x + w - radius, y + h);
  ctx.lineTo(x + radius, y + h);
  ctx.quadraticCurveTo(x, y + h, x, y + h - radius);
  ctx.lineTo(x, y + radius);
  ctx.quadraticCurveTo(x, y, x + radius, y);
  ctx.closePath();
}

export function loadWatermarkImageElement(dataUrl: string | null): Promise<HTMLImageElement | null> {
  if (!dataUrl || typeof Image === 'undefined') return Promise.resolve(null);
  return new Promise((resolve) => {
    const img = new Image();
    img.onload = () => resolve(img);
    img.onerror = () => resolve(null);
    img.src = dataUrl;
  });
}

/**
 * Downscales an uploaded logo/signature image cleanly to <= 512px PNG data URL for persistence.
 */
export async function prepareWatermarkImageDataUrl(file: File): Promise<string> {
  const url = URL.createObjectURL(file);
  try {
    const img = await new Promise<HTMLImageElement>((resolve, reject) => {
      const el = new Image();
      el.onload = () => resolve(el);
      el.onerror = () => reject(new Error('Unsupported watermark image file'));
      el.src = url;
    });
    const maxDim = 512;
    const natW = Math.max(1, img.naturalWidth || img.width);
    const natH = Math.max(1, img.naturalHeight || img.height);
    const scale = Math.min(1, maxDim / Math.max(natW, natH));
    const w = Math.max(1, Math.round(natW * scale));
    const h = Math.max(1, Math.round(natH * scale));
    const c = document.createElement('canvas');
    c.width = w;
    c.height = h;
    const ctx = c.getContext('2d');
    if (!ctx) throw new Error('Failed to process watermark image');
    ctx.drawImage(img, 0, 0, w, h);
    return c.toDataURL('image/png');
  } finally {
    URL.revokeObjectURL(url);
  }
}

/**
 * Draws the configured watermark directly onto `ctx` at coordinates matching `frameW x frameH`.
 */
export function drawWatermarkOnContext(
  ctx: CanvasRenderingContext2D,
  frameW: number,
  frameH: number,
  config: TimelapseWatermarkConfig | null | undefined,
  loadedImage?: HTMLImageElement | null
): { x: number; y: number; width: number; height: number } | null {
  if (!config || !config.enabled || frameW <= 0 || frameH <= 0) return null;

  const opacity = Math.max(0.1, Math.min(1, config.opacity));
  const scaleFraction = Math.max(0.05, Math.min(0.4, config.scale / 100));

  if (config.mode === 'image' && loadedImage) {
    const natW = Math.max(1, loadedImage.naturalWidth || loadedImage.width);
    const natH = Math.max(1, loadedImage.naturalHeight || loadedImage.height);
    const targetW = Math.max(16, Math.round(frameW * scaleFraction));
    const ratio = targetW / natW;
    let drawW = targetW;
    let drawH = Math.max(16, Math.round(natH * ratio));
    const maxH = Math.round(frameH * 0.4);
    if (drawH > maxH) {
      const hScale = maxH / drawH;
      drawH = maxH;
      drawW = Math.max(16, Math.round(drawW * hScale));
    }

    const pos = computeWatermarkPosition(frameW, frameH, drawW, drawH, config.position, config.margin);
    ctx.save();
    ctx.globalAlpha = opacity;
    ctx.imageSmoothingEnabled = true;
    ctx.drawImage(loadedImage, pos.x, pos.y, drawW, drawH);
    ctx.restore();
    return { x: pos.x, y: pos.y, width: drawW, height: drawH };
  }

  const label = (config.text || '').trim();
  if (!label) return null;

  const fontSize = Math.max(12, Math.round(Math.min(frameW, frameH) * scaleFraction * 0.22));
  const font = resolveWatermarkFont(config.fontStyle, fontSize);

  ctx.save();
  ctx.font = font;
  ctx.textBaseline = 'middle';
  ctx.textAlign = 'left';

  const metrics = typeof ctx.measureText === 'function' ? ctx.measureText(label) : { width: label.length * fontSize * 0.6 };
  const textW = Math.ceil(metrics.width || label.length * fontSize * 0.6);
  const padX = config.showBackdrop ? Math.round(fontSize * 0.65) : Math.round(fontSize * 0.2);
  const padY = config.showBackdrop ? Math.round(fontSize * 0.36) : Math.round(fontSize * 0.15);
  const boxW = Math.min(frameW, textW + padX * 2);
  const boxH = Math.min(frameH, Math.round(fontSize * 1.25) + padY * 2);

  const pos = computeWatermarkPosition(frameW, frameH, boxW, boxH, config.position, config.margin);

  ctx.globalAlpha = opacity;
  if (config.showBackdrop) {
    // Pick contrasting subtle translucent pill so watermark remains crisp on both white and dark art
    const isDarkText = isColorDark(config.textColor);
    ctx.fillStyle = isDarkText ? 'rgba(255, 255, 255, 0.72)' : 'rgba(12, 12, 14, 0.58)';
    drawRoundedRectPath(ctx, pos.x, pos.y, boxW, boxH, Math.round(boxH * 0.28));
    ctx.fill();
  } else {
    ctx.shadowColor = isColorDark(config.textColor)
      ? 'rgba(255, 255, 255, 0.75)'
      : 'rgba(0, 0, 0, 0.78)';
    ctx.shadowBlur = Math.max(2, Math.round(fontSize * 0.18));
    ctx.shadowOffsetX = 0;
    ctx.shadowOffsetY = Math.max(1, Math.round(fontSize * 0.06));
  }

  ctx.fillStyle = config.textColor || '#ffffff';
  ctx.fillText(label, pos.x + padX, pos.y + boxH * 0.5 + 0.5, Math.max(1, boxW - padX * 2));
  ctx.restore();

  return { x: pos.x, y: pos.y, width: boxW, height: boxH };
}

function isColorDark(hex: string): boolean {
  const clean = (hex || '').replace('#', '').trim();
  if (clean.length !== 6) return false;
  const r = parseInt(clean.slice(0, 2), 16);
  const g = parseInt(clean.slice(2, 4), 16);
  const b = parseInt(clean.slice(4, 6), 16);
  if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) return false;
  return (0.299 * r + 0.587 * g + 0.114 * b) / 255 < 0.45;
}

/**
 * Generates a compact transparent PNG containing only the rendered watermark, plus its exact `(x, y)`
 * coordinates in the target output video frame, for FFmpeg `-filter_complex overlay=X:Y`.
 */
export async function renderWatermarkOverlayPng(
  frameW: number,
  frameH: number,
  config: TimelapseWatermarkConfig | null | undefined
): Promise<{ bytes: Uint8Array; x: number; y: number } | null> {
  if (!config || !config.enabled || typeof document === 'undefined') return null;

  const loadedImg =
    config.mode === 'image' && config.imageDataUrl
      ? await loadWatermarkImageElement(config.imageDataUrl)
      : null;
  if (config.mode === 'image' && !loadedImg) return null;
  if (config.mode === 'text' && !config.text.trim()) return null;

  const full = document.createElement('canvas');
  full.width = Math.max(2, frameW);
  full.height = Math.max(2, frameH);
  const ctx = full.getContext('2d');
  if (!ctx) return null;

  const rect = drawWatermarkOnContext(ctx, full.width, full.height, config, loadedImg);
  if (!rect) return null;

  // Crop strictly around the watermark bounding box (+ shadow margin) so PNG is tiny (~3-20 KB)
  const pad = config.showBackdrop ? 4 : 14;
  const cx = Math.max(0, Math.floor(rect.x - pad));
  const cy = Math.max(0, Math.floor(rect.y - pad));
  const cw = Math.max(2, Math.min(full.width - cx, Math.ceil(rect.width + pad * 2)));
  const ch = Math.max(2, Math.min(full.height - cy, Math.ceil(rect.height + pad * 2)));

  const cropped = document.createElement('canvas');
  cropped.width = cw;
  cropped.height = ch;
  const cCtx = cropped.getContext('2d');
  if (!cCtx) return null;
  cCtx.drawImage(full, cx, cy, cw, ch, 0, 0, cw, ch);

  const blob = await canvasToBlob(cropped, 'image/png');
  const buf = await blob.arrayBuffer();
  return { bytes: new Uint8Array(buf), x: cx, y: cy };
}

export interface RenderOutputFrameOptions {
  backgroundMode?: TimelapseBackgroundMode;
  backgroundColor?: string;
  watermark?: TimelapseWatermarkConfig | null;
  watermarkImage?: HTMLImageElement | null;
}

/**
 * Renders a single decoded keyframe (`HTMLImageElement` or `ImageBitmap`) onto an output canvas
 * with exact aspect-ratio letterboxing (solid or blurred backdrop) and optional watermark.
 */
export function renderTimelapseOutputFrame(
  ctx: CanvasRenderingContext2D,
  source: HTMLImageElement | ImageBitmap | HTMLCanvasElement | null,
  targetW: number,
  targetH: number,
  options: RenderOutputFrameOptions = {}
): void {
  const bgMode = options.backgroundMode ?? 'white';
  const bgColor =
    options.backgroundColor ||
    (bgMode === 'dark' ? '#141414' : '#ffffff');

  ctx.save();
  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.globalAlpha = 1;
  ctx.globalCompositeOperation = 'source-over';
  ctx.filter = 'none';

  ctx.fillStyle = bgMode === 'blur' ? '#141414' : bgColor;
  ctx.fillRect(0, 0, targetW, targetH);

  if (source) {
    const srcW = Math.max(
      1,
      'naturalWidth' in source ? source.naturalWidth || source.width : source.width
    );
    const srcH = Math.max(
      1,
      'naturalHeight' in source ? source.naturalHeight || source.height : source.height
    );

    const fitScale = Math.min(targetW / srcW, targetH / srcH);
    const drawW = srcW * fitScale;
    const drawH = srcH * fitScale;
    const dx = (targetW - drawW) * 0.5;
    const dy = (targetH - drawH) * 0.5;

    // Optional blurred cover backdrop when aspect ratios differ
    if (bgMode === 'blur' && (Math.abs(drawW - targetW) > 2 || Math.abs(drawH - targetH) > 2)) {
      const coverScale = Math.max(targetW / srcW, targetH / srcH) * 1.08;
      const bw = srcW * coverScale;
      const bh = srcH * coverScale;
      const bx = (targetW - bw) * 0.5;
      const by = (targetH - bh) * 0.5;
      ctx.save();
      ctx.filter = `blur(${Math.max(8, Math.round(Math.min(targetW, targetH) * 0.025))}px) brightness(0.68)`;
      ctx.drawImage(source, bx, by, bw, bh);
      ctx.restore();
    }

    ctx.imageSmoothingEnabled = true;
    ctx.drawImage(source, dx, dy, drawW, drawH);
  }

  if (options.watermark?.enabled) {
    drawWatermarkOnContext(ctx, targetW, targetH, options.watermark, options.watermarkImage);
  }

  ctx.restore();
}