Skip to content

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

13.9 KB
Raw Blame
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import {
  computeTimelapseDimensions,
  globalTimelapseManager,
  resolveTimelapseTargetSeconds,
  sampleTimelapseFrameIndices,
  TimelapseAspectRatio,
  TimelapseBackgroundMode,
  TimelapseDurationPreset,
  TimelapseResolution,
  TimelapseWatermarkConfig,
} from '../../utils/timelapseEngine';
import {
  loadWatermarkImageElement,
  renderTimelapseOutputFrame,
} from '../../utils/timelapseWatermark';

export type TimelapsePlaybackSpeed = 0.5 | 1 | 2;

export interface UseTimelapsePreviewPlayerParams {
  isOpen: boolean;
  documentId: string | null;
  frameCount: number;
  duration: TimelapseDurationPreset;
  customDurationSec: number;
  fps: number;
  aspectRatio: TimelapseAspectRatio;
  resolution: TimelapseResolution;
  backgroundMode: TimelapseBackgroundMode;
  backgroundColor: string;
  watermark: TimelapseWatermarkConfig;
  playbackSpeed: TimelapsePlaybackSpeed;
  loop: boolean;
  isFullscreen: boolean;
}

const MAX_DECODED_CACHE = 36;
const LOOKAHEAD_UNIQUE_FRAMES = 6;

export function formatTimecode(seconds: number): string {
  const safe = Math.max(0, Number.isFinite(seconds) ? seconds : 0);
  const mins = Math.floor(safe / 60);
  const secs = safe - mins * 60;
  const wholeSecs = Math.floor(secs);
  const tenths = Math.floor((secs - wholeSecs) * 10);
  return `${String(mins).padStart(2, '0')}:${String(wholeSecs).padStart(2, '0')}.${tenths}`;
}

export function useTimelapsePreviewPlayer({
  isOpen,
  documentId,
  frameCount,
  duration,
  customDurationSec,
  fps,
  aspectRatio,
  resolution,
  backgroundMode,
  backgroundColor,
  watermark,
  playbackSpeed,
  loop,
  isFullscreen,
}: UseTimelapsePreviewPlayerParams) {
  const [isPlaying, setIsPlaying] = useState(false);
  const [timelineIndex, setTimelineIndex] = useState(0);

  const modalCanvasRef = useRef<HTMLCanvasElement | null>(null);
  const fullscreenCanvasRef = useRef<HTMLCanvasElement | null>(null);
  const decodedCacheRef = useRef<Map<string, ImageBitmap | HTMLImageElement>>(new Map());
  const inFlightLoadsRef = useRef<Map<string, Promise<ImageBitmap | HTMLImageElement | null>>>(
    new Map()
  );
  const watermarkImgRef = useRef<HTMLImageElement | null>(null);
  const [watermarkImgVersion, setWatermarkImgVersion] = useState(0);
  const lastRenderedSourceRef = useRef<ImageBitmap | HTMLImageElement | null>(null);
  const timelineIndexRef = useRef(0);
  timelineIndexRef.current = timelineIndex;

  // Sample exact output timeline matching the export engine
  const sampledIndices = useMemo(
    () => sampleTimelapseFrameIndices(frameCount, duration, fps, customDurationSec),
    [frameCount, duration, fps, customDurationSec]
  );

  const totalTimelineFrames = sampledIndices.length;
  const totalDurationSec = useMemo(
    () => resolveTimelapseTargetSeconds(frameCount, duration, fps, customDurationSec),
    [frameCount, duration, fps, customDurationSec]
  );

  // Compute target export dimensions (and preview canvas resolution)
  const outputDims = useMemo(() => {
    if (!documentId || frameCount <= 0) {
      return computeTimelapseDimensions(1920, 1080, aspectRatio, resolution);
    }
    const frames = globalTimelapseManager.getFrames(documentId);
    const refFrame = frames[frames.length - 1] ?? frames[0];
    return computeTimelapseDimensions(
      refFrame?.width || 1920,
      refFrame?.height || 1080,
      aspectRatio,
      resolution
    );
  }, [documentId, frameCount, aspectRatio, resolution]);

  const previewCanvasDims = useMemo(() => {
    const maxEdge = isFullscreen ? 1920 : 960;
    const scale = Math.min(1, maxEdge / Math.max(outputDims.width, outputDims.height));
    return {
      width: Math.max(2, Math.round((outputDims.width * scale) / 2) * 2),
      height: Math.max(2, Math.round((outputDims.height * scale) / 2) * 2),
    };
  }, [outputDims.width, outputDims.height, isFullscreen]);

  // Preserve proportional playback position whenever duration preset or FPS changes
  const prevTotalRef = useRef(totalTimelineFrames);
  useEffect(() => {
    const prevTotal = prevTotalRef.current;
    prevTotalRef.current = totalTimelineFrames;
    if (totalTimelineFrames <= 0) {
      setTimelineIndex(0);
      setIsPlaying(false);
      return;
    }
    if (prevTotal > 1 && prevTotal !== totalTimelineFrames) {
      const ratio = Math.min(1, Math.max(0, timelineIndexRef.current / (prevTotal - 1)));
      const nextIdx = Math.round(ratio * (totalTimelineFrames - 1));
      setTimelineIndex(nextIdx);
    } else if (timelineIndexRef.current >= totalTimelineFrames) {
      setTimelineIndex(Math.max(0, totalTimelineFrames - 1));
    }
  }, [totalTimelineFrames]);

  const clearDecodedCache = useCallback(() => {
    for (const item of decodedCacheRef.current.values()) {
      if ('close' in item && typeof item.close === 'function') {
        try {
          item.close();
        } catch {
          // ignore
        }
      }
    }
    decodedCacheRef.current.clear();
    inFlightLoadsRef.current.clear();
    lastRenderedSourceRef.current = null;
  }, []);

  // Reset cache when switching documents or closing modal
  useEffect(() => {
    setTimelineIndex(0);
    setIsPlaying(false);
    clearDecodedCache();
  }, [documentId, clearDecodedCache]);

  useEffect(() => {
    if (!isOpen) {
      setIsPlaying(false);
      clearDecodedCache();
    }
  }, [isOpen, clearDecodedCache]);

  useEffect(() => {
    return () => {
      clearDecodedCache();
    };
  }, [clearDecodedCache]);

  // Load watermark logo image when configured
  useEffect(() => {
    let cancelled = false;
    if (watermark.enabled && watermark.mode === 'image' && watermark.imageDataUrl) {
      loadWatermarkImageElement(watermark.imageDataUrl).then((img) => {
        if (cancelled) return;
        watermarkImgRef.current = img;
        setWatermarkImgVersion((v) => v + 1);
      });
    } else {
      watermarkImgRef.current = null;
      setWatermarkImgVersion((v) => v + 1);
    }
    return () => {
      cancelled = true;
    };
  }, [watermark.enabled, watermark.mode, watermark.imageDataUrl]);

  const decodeFrameAtSourceIndex = useCallback(
    async (srcIdx: number): Promise<ImageBitmap | HTMLImageElement | null> => {
      if (!documentId) return null;
      const frames = globalTimelapseManager.getFrames(documentId);
      const entry = frames[srcIdx];
      if (!entry) return null;

      const cacheKey = entry.id;
      const cached = decodedCacheRef.current.get(cacheKey);
      if (cached) {
        // Refresh LRU position
        decodedCacheRef.current.delete(cacheKey);
        decodedCacheRef.current.set(cacheKey, cached);
        return cached;
      }

      const existingPromise = inFlightLoadsRef.current.get(cacheKey);
      if (existingPromise) return existingPromise;

      const promise = (async (): Promise<ImageBitmap | HTMLImageElement | null> => {
        try {
          const blob = await globalTimelapseManager.loadFrameBlob(documentId, entry);
          if (!blob) return null;
          let decoded: ImageBitmap | HTMLImageElement | null = null;
          if (typeof createImageBitmap === 'function') {
            try {
              decoded = await createImageBitmap(blob);
            } catch {
              decoded = null;
            }
          }
          if (!decoded && typeof Image !== 'undefined') {
            const url = URL.createObjectURL(blob);
            decoded = await new Promise<HTMLImageElement | null>((resolve) => {
              const el = new Image();
              el.onload = () => {
                URL.revokeObjectURL(url);
                resolve(el);
              };
              el.onerror = () => {
                URL.revokeObjectURL(url);
                resolve(null);
              };
              el.src = url;
            });
          }
          if (decoded) {
            if (decodedCacheRef.current.size >= MAX_DECODED_CACHE) {
              const oldestKey = decodedCacheRef.current.keys().next().value;
              if (oldestKey !== undefined) {
                const oldest = decodedCacheRef.current.get(oldestKey);
                if (
                  oldest &&
                  oldest !== lastRenderedSourceRef.current &&
                  'close' in oldest &&
                  typeof oldest.close === 'function'
                ) {
                  try {
                    oldest.close();
                  } catch {
                    // ignore
                  }
                }
                decodedCacheRef.current.delete(oldestKey);
              }
            }
            decodedCacheRef.current.set(cacheKey, decoded);
          }
          return decoded;
        } finally {
          inFlightLoadsRef.current.delete(cacheKey);
        }
      })();

      inFlightLoadsRef.current.set(cacheKey, promise);
      return promise;
    },
    [documentId]
  );

  const paintCanvas = useCallback(
    (source: ImageBitmap | HTMLImageElement | null) => {
      const target = isFullscreen ? fullscreenCanvasRef.current : modalCanvasRef.current;
      if (!target) return;
      if (target.width !== previewCanvasDims.width) target.width = previewCanvasDims.width;
      if (target.height !== previewCanvasDims.height) target.height = previewCanvasDims.height;
      const ctx = target.getContext('2d');
      if (!ctx) return;
      renderTimelapseOutputFrame(ctx, source, target.width, target.height, {
        backgroundMode,
        backgroundColor,
        watermark,
        watermarkImage: watermarkImgRef.current,
      });
    },
    [
      isFullscreen,
      previewCanvasDims.width,
      previewCanvasDims.height,
      backgroundMode,
      backgroundColor,
      watermark,
    ]
  );

  // Render active frame & prefetch upcoming unique frames
  useEffect(() => {
    if (!isOpen || !documentId || totalTimelineFrames === 0) return;

    const clamped = Math.max(0, Math.min(totalTimelineFrames - 1, timelineIndex));
    const srcIdx = sampledIndices[clamped] ?? 0;
    const frames = globalTimelapseManager.getFrames(documentId);
    const entry = frames[srcIdx];
    let cancelled = false;

    const cached = entry ? decodedCacheRef.current.get(entry.id) : undefined;
    if (cached) {
      lastRenderedSourceRef.current = cached;
      paintCanvas(cached);
    } else {
      // Keep previous frame visible while async decode finishes (zero flicker!)
      if (lastRenderedSourceRef.current) {
        paintCanvas(lastRenderedSourceRef.current);
      }
      void decodeFrameAtSourceIndex(srcIdx).then((decoded) => {
        if (cancelled || !decoded) return;
        lastRenderedSourceRef.current = decoded;
        paintCanvas(decoded);
      });
    }

    // Lookahead prefetcher: pre-decode the next N unique source frames along the sampled timeline
    const seen = new Set<number>([srcIdx]);
    let prefetched = 0;
    for (
      let offset = 1;
      offset < totalTimelineFrames && prefetched < LOOKAHEAD_UNIQUE_FRAMES;
      offset++
    ) {
      const nextPos = (clamped + offset) % totalTimelineFrames;
      const nextSrc = sampledIndices[nextPos];
      if (nextSrc !== undefined && !seen.has(nextSrc)) {
        seen.add(nextSrc);
        prefetched++;
        void decodeFrameAtSourceIndex(nextSrc);
      }
    }

    return () => {
      cancelled = true;
    };
  }, [
    isOpen,
    documentId,
    totalTimelineFrames,
    timelineIndex,
    sampledIndices,
    paintCanvas,
    decodeFrameAtSourceIndex,
    watermarkImgVersion,
    isFullscreen,
    frameCount,
  ]);

  // Real-time rAF playback loop synchronized strictly to (fps * playbackSpeed)
  useEffect(() => {
    if (!isOpen || !isPlaying || totalTimelineFrames <= 1) return;

    let rafId = 0;
    let lastTs = performance.now();
    let floatPos = timelineIndexRef.current;

    const tick = (now: number) => {
      const dtSec = Math.min(0.15, Math.max(0, (now - lastTs) / 1000));
      lastTs = now;
      floatPos += dtSec * fps * playbackSpeed;

      if (floatPos >= totalTimelineFrames) {
        if (loop) {
          floatPos = floatPos % totalTimelineFrames;
        } else {
          setTimelineIndex(totalTimelineFrames - 1);
          setIsPlaying(false);
          return;
        }
      }

      const nextDiscrete = Math.floor(floatPos);
      if (nextDiscrete !== timelineIndexRef.current) {
        timelineIndexRef.current = nextDiscrete;
        setTimelineIndex(nextDiscrete);
      }
      rafId = requestAnimationFrame(tick);
    };

    rafId = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(rafId);
  }, [isOpen, isPlaying, totalTimelineFrames, fps, playbackSpeed, loop]);

  const togglePlay = useCallback(() => {
    if (totalTimelineFrames <= 1) return;
    setIsPlaying((prev) => {
      if (!prev && timelineIndexRef.current >= totalTimelineFrames - 1) {
        setTimelineIndex(0);
      }
      return !prev;
    });
  }, [totalTimelineFrames]);

  const seekTo = useCallback(
    (idx: number) => {
      const clamped = Math.max(0, Math.min(Math.max(0, totalTimelineFrames - 1), idx));
      setTimelineIndex(clamped);
    },
    [totalTimelineFrames]
  );

  const stepBy = useCallback(
    (delta: number) => {
      setIsPlaying(false);
      if (totalTimelineFrames <= 0) return;
      setTimelineIndex((prev) => {
        const next = prev + delta;
        if (next < 0) return loop ? totalTimelineFrames - 1 : 0;
        if (next >= totalTimelineFrames) return loop ? 0 : totalTimelineFrames - 1;
        return next;
      });
    },
    [totalTimelineFrames, loop]
  );

  const restart = useCallback(() => {
    setTimelineIndex(0);
  }, []);

  const currentSourceFrameIndex =
    totalTimelineFrames > 0
      ? (sampledIndices[Math.min(timelineIndex, totalTimelineFrames - 1)] ?? 0)
      : 0;
  const currentTimeSec = fps > 0 ? timelineIndex / fps : 0;

  return {
    modalCanvasRef,
    fullscreenCanvasRef,
    isPlaying,
    setIsPlaying,
    togglePlay,
    timelineIndex,
    totalTimelineFrames,
    currentSourceFrameIndex,
    currentTimeSec,
    totalDurationSec,
    outputDims,
    previewCanvasDims,
    seekTo,
    stepBy,
    restart,
  };
}