Skip to content

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

57.3 KB
Raw Blame
/**
 * Time-lapse Recording, Persistent Storage, Preview & Export Engine
 *
 * - Persists keyframes in external local storage (Tauri `%LOCALAPPDATA%/inkstudio_timelapse` or
 *   browser IndexedDB) rather than bloating `.ink` project files — `.ink` only stores a tiny
 *   `recordingId` reference so recordings survive restarts and resume seamlessly.
 * - Supports three optimized capture areas (`artwork`, `canvas-view`, `app-window`) up to 4K with
 *   idle/trailing coalescing, active-stroke deferral, frustum culling, and change deduplication.
 * - Shares WYSIWYG composition, duration/FPS timeline sampling, and watermark rendering across
 *   the in-app preview player, full-screen viewer, MediaRecorder, and native FFmpeg exports.
 */

import {
  CanvasDimensions,
  InkTimelapseFrameData,
  InkTimelapseFrameMetadata,
  InkTimelapseMetadata,
  LayerItem,
  TimelapseCaptureArea,
  TimelapseCaptureResolution,
  TimelapseExportAspectRatio,
  TimelapseExportResolution,
  TimelapseQualityPreset,
} from '../types/editor';
import { canvasToBlob, TimelapsePersistenceProvider } from './saveManager';
import {
  captureNativeTimelapseFrame,
  isNativeCanvasActive,
} from './nativeEngineBridge';
import {
  captureNativeAppWindowToCanvas,
  computeCanvasViewDimensions,
  renderNativeCanvasViewToCanvas,
  TimelapseLiveCaptureContext,
} from './timelapseCanvasView';
import {
  deletePersistedRecording,
  generateRecordingId,
  invokeTauri,
  invokeTauriRaw,
  isIndexedDbAvailable,
  isTauriRuntime,
  listPersistedRecordings,
  loadPersistedSession,
  lookupLinkedRecordingId,
  PersistentFrameRecord,
  PersistentTimelapseMeta,
  persistSessionMeta,
  persistSingleFrame,
  readPersistedFrame,
  saveDocumentRecordingLink,
  StoredRecordingSummary,
  toArrayBuffer,
} from './timelapseStorage';
import {
  loadWatermarkImageElement,
  renderTimelapseOutputFrame,
  renderWatermarkOverlayPng,
  TimelapseBackgroundMode,
  TimelapseWatermarkConfig,
} from './timelapseWatermark';

export type {
  TimelapseCaptureArea,
  TimelapseCaptureResolution,
  TimelapseQualityPreset,
  TimelapseLiveCaptureContext,
  StoredRecordingSummary,
  TimelapseBackgroundMode,
  TimelapseWatermarkConfig,
};

export type TimelapseDurationPreset = '15s' | '30s' | '60s' | '120s' | 'full' | 'custom';
export type TimelapseAspectRatio = TimelapseExportAspectRatio;
export type TimelapseResolution = TimelapseExportResolution;
export type TimelapseFps = 24 | 30 | 60;

export interface TimelapseFrameEntry {
  id: string;
  index: number;
  timestamp: number;
  width: number;
  height: number;
  mimeType: 'image/webp' | 'image/jpeg' | 'image/png';
  bytes: number;
  offloadedToDisk: boolean;
  captureArea?: TimelapseCaptureArea;
  blob?: Blob;
}

export interface TimelapseSessionStats {
  documentId: string;
  recordingId: string | null;
  enabled: boolean;
  frameCount: number;
  memoryBytes: number;
  diskFrames: number;
  storageBytes: number;
  captureArea: TimelapseCaptureArea;
  captureResolution: TimelapseCaptureResolution;
  storageBackend: 'disk' | 'indexeddb' | 'memory';
}

export interface TimelapseExportOptions {
  duration: TimelapseDurationPreset;
  customDurationSec?: number;
  aspectRatio: TimelapseAspectRatio;
  resolution: TimelapseResolution;
  fps?: number;
  quality?: TimelapseQualityPreset;
  backgroundMode?: TimelapseBackgroundMode;
  backgroundColor?: string;
  watermark?: TimelapseWatermarkConfig | null;
  preferFfmpeg?: boolean;
}

export interface TimelapseExportResult {
  blob: Blob;
  mimeType: string;
  extension: string;
  frameCount: number;
  durationSec: number;
}

export interface AttachOrRestoreOptions {
  documentName?: string;
  metadata?: InkTimelapseMetadata | null;
  legacyFrames?: InkTimelapseFrameData[] | null;
  linkedDocId?: string | null;
  sourcePath?: string | null;
  fallbackRecordingId?: string | null;
  fallbackDims?: CanvasDimensions;
  onProgress?: (done: number, total: number) => void;
}

const DEFAULT_MIN_INTERVAL_MS = 350;
const DEFAULT_MAX_RAM_BYTES = 48 * 1024 * 1024; // 48 MB RAM cap only when no persistent storage exists
const TAURI_BATCH_MAX_FRAMES = 128;
const TAURI_BATCH_MAX_BYTES = 16 * 1024 * 1024; // 16 MB per IPC batch

export function captureResolutionToMaxDim(res: TimelapseCaptureResolution): number {
  switch (res) {
    case '720p':
      return 1280;
    case '2k':
      return 2560;
    case '4k':
      return 3840;
    default:
      return 1920; // '1080p'
  }
}

export function formatTimelapseBytes(bytes: number): string {
  const safe = Math.max(0, Number(bytes) || 0);
  if (safe < 1024) return `${safe} B`;
  if (safe < 1024 * 1024) return `${(safe / 1024).toFixed(1)} KB`;
  if (safe < 1024 * 1024 * 1024) return `${(safe / (1024 * 1024)).toFixed(1)} MB`;
  return `${(safe / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}

function packFrameIndices(indices: number[]): Uint8Array {
  const out = new Uint8Array(indices.length * 4);
  const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
  for (let i = 0; i < indices.length; i++) {
    view.setUint32(i * 4, indices[i] >>> 0, true);
  }
  return out;
}

/**
 * Packs a batch of timelapse frames into the binary format expected by Rust `timelapse_write_frames_batch`:
 * `[count: u32 LE] ([frameIndex: u32 LE][extCode: u8 (0=webp, 1=jpg, 2=png)][dataLen: u32 LE][data])*`
 */
export function packTimelapseFrameBatch(
  entries: Array<{ index: number; ext: 'webp' | 'jpg' | 'png'; bytes: Uint8Array }>
): Uint8Array {
  let total = 4;
  for (const e of entries) {
    total += 9 + e.bytes.byteLength;
  }
  const out = new Uint8Array(total);
  const view = new DataView(out.buffer, out.byteOffset, out.byteLength);
  view.setUint32(0, entries.length >>> 0, true);
  let offset = 4;
  for (const e of entries) {
    view.setUint32(offset, e.index >>> 0, true);
    out[offset + 4] = e.ext === 'png' ? 2 : e.ext === 'jpg' ? 1 : 0;
    view.setUint32(offset + 5, e.bytes.byteLength >>> 0, true);
    offset += 9;
    out.set(e.bytes, offset);
    offset += e.bytes.byteLength;
  }
  return out;
}

async function blobToUint8Array(blob: Blob): Promise<Uint8Array> {
  const buf = await blob.arrayBuffer();
  return new Uint8Array(buf);
}

/**
 * Computes even-dimension output video size for the chosen aspect ratio & resolution preset.
 */
export function computeTimelapseDimensions(
  srcWidth: number,
  srcHeight: number,
  aspectRatio: TimelapseAspectRatio,
  resolution: TimelapseResolution
): { width: number; height: number } {
  const targetShort =
    resolution === '4k'
      ? 2160
      : resolution === '2k'
        ? 1440
        : resolution === '1080p'
          ? 1080
          : 720;
  const toEven = (n: number) => Math.max(2, Math.round(n / 2) * 2);

  if (aspectRatio === '16:9') {
    const h = targetShort;
    const w = toEven((h * 16) / 9);
    return { width: w, height: toEven(h) };
  }
  if (aspectRatio === '9:16') {
    const w = targetShort;
    const h = toEven((w * 16) / 9);
    return { width: toEven(w), height: h };
  }
  if (aspectRatio === '1:1') {
    const s = toEven(targetShort);
    return { width: s, height: s };
  }
  if (aspectRatio === '4:5') {
    const w = toEven(targetShort);
    const h = toEven((w * 5) / 4);
    return { width: w, height: h };
  }

  // Original aspect ratio fitted cleanly within longest-edge budget
  const safeW = Math.max(1, srcWidth);
  const safeH = Math.max(1, srcHeight);
  const maxDim =
    resolution === '4k'
      ? 3840
      : resolution === '2k'
        ? 2560
        : resolution === '1080p'
          ? 1920
          : 1280;
  const scale = Math.min(1, maxDim / Math.max(safeW, safeH));
  return {
    width: toEven(safeW * scale),
    height: toEven(safeH * scale),
  };
}

/**
 * Computes target output video duration in seconds for a duration preset.
 */
export function resolveTimelapseTargetSeconds(
  totalCapturedFrames: number,
  duration: TimelapseDurationPreset,
  fps = 30,
  customDurationSec = 30
): number {
  if (totalCapturedFrames <= 0) return 0;
  const safeFps = Math.max(1, Math.min(60, fps));
  if (duration === 'full') {
    const repeat = totalCapturedFrames < safeFps * 5 ? 2 : 1;
    return (totalCapturedFrames * repeat) / safeFps;
  }
  if (duration === 'custom') {
    return Math.max(2, Math.min(600, Number(customDurationSec) || 30));
  }
  if (duration === '15s') return 15;
  if (duration === '30s') return 30;
  if (duration === '60s') return 60;
  if (duration === '120s') return 120;
  return 30;
}

/**
 * Maps captured frames onto output timeline frame indices for the selected duration preset and FPS.
 */
export function sampleTimelapseFrameIndices(
  totalCapturedFrames: number,
  duration: TimelapseDurationPreset,
  fps = 30,
  customDurationSec = 30
): number[] {
  if (totalCapturedFrames <= 0) return [];
  if (totalCapturedFrames === 1) return [0];

  const safeFps = Math.max(1, Math.min(60, fps));
  if (duration === 'full') {
    const out: number[] = [];
    const repeat = totalCapturedFrames < safeFps * 5 ? 2 : 1;
    for (let i = 0; i < totalCapturedFrames; i++) {
      for (let r = 0; r < repeat; r++) out.push(i);
    }
    return out;
  }

  const seconds = resolveTimelapseTargetSeconds(
    totalCapturedFrames,
    duration,
    safeFps,
    customDurationSec
  );
  const targetOutFrames = Math.max(1, Math.round(seconds * safeFps));
  const indices: number[] = [];
  for (let i = 0; i < targetOutFrames; i++) {
    const ratio = targetOutFrames === 1 ? 1 : i / (targetOutFrames - 1);
    const srcIdx = Math.min(
      totalCapturedFrames - 1,
      Math.floor(ratio * totalCapturedFrames)
    );
    indices.push(srcIdx);
  }
  return indices;
}

/**
 * Computes recommended MediaRecorder video bitrate from resolution, FPS, and quality preset.
 */
export function computeMediaRecorderBitrate(
  resolution: TimelapseResolution,
  fps: number,
  quality: TimelapseQualityPreset = 'high'
): number {
  const baseByRes =
    resolution === '4k'
      ? 18_000_000
      : resolution === '2k'
        ? 10_000_000
        : resolution === '1080p'
          ? 6_000_000
          : 3_500_000;
  const fpsFactor = fps >= 50 ? 1.45 : fps <= 24 ? 0.85 : 1.0;
  const qualityFactor =
    quality === 'standard'
      ? 0.6
      : quality === 'ultra'
        ? 1.65
        : quality === 'lossless'
          ? 2.4
          : 1.0;
  return Math.round(baseByRes * fpsFactor * qualityFactor);
}

function scheduleIdleYield(timeoutMs = 180): Promise<void> {
  return new Promise<void>((resolve) => {
    const g = globalThis as unknown as {
      requestIdleCallback?: (cb: () => void, opts?: { timeout: number }) => number;
    };
    if (typeof g.requestIdleCallback === 'function') {
      g.requestIdleCallback(() => resolve(), { timeout: timeoutMs });
    } else {
      setTimeout(resolve, 0);
    }
  });
}

interface TrailingCaptureArgs {
  layers: LayerItem[];
  dimensions: CanvasDimensions;
  liveCtx?: TimelapseLiveCaptureContext;
}

interface InternalSession {
  documentId: string;
  recordingId: string;
  documentName: string;
  enabled: boolean;
  captureArea: TimelapseCaptureArea;
  captureResolution: TimelapseCaptureResolution;
  frames: TimelapseFrameEntry[];
  nextIndex: number;
  lastCaptureAt: number;
  lastCaptureSig: string | null;
  pendingCapture: boolean;
  pendingCapturePromise: Promise<boolean> | null;
  trailingTimer: ReturnType<typeof setTimeout> | null;
  pendingTrailingArgs: TrailingCaptureArgs | null;
  writeQueue: Promise<void>;
  memoryBytes: number;
  storageBytes: number;
  createdAt: number;
  updatedAt: number;
  generation: number;
}

export class TimelapseRecorderManager {
  private sessions = new Map<string, InternalSession>();
  private captureCanvas: HTMLCanvasElement | null = null;
  private listeners = new Set<() => void>();
  private minIntervalMs: number;
  private defaultCaptureResolution: TimelapseCaptureResolution;
  private maxRamBytes: number;

  constructor(options?: {
    minIntervalMs?: number;
    maxCaptureDim?: number;
    captureResolution?: TimelapseCaptureResolution;
    maxRamBytes?: number;
  }) {
    this.minIntervalMs = options?.minIntervalMs ?? DEFAULT_MIN_INTERVAL_MS;
    this.maxRamBytes = options?.maxRamBytes ?? DEFAULT_MAX_RAM_BYTES;
    if (options?.captureResolution) {
      this.defaultCaptureResolution = options.captureResolution;
    } else if (options?.maxCaptureDim) {
      this.defaultCaptureResolution =
        options.maxCaptureDim >= 3200
          ? '4k'
          : options.maxCaptureDim >= 2200
            ? '2k'
            : options.maxCaptureDim <= 1280
              ? '720p'
              : '1080p';
    } else {
      this.defaultCaptureResolution = '1080p';
    }
  }

  private getOrCreate(documentId: string, recordingIdOverride?: string): InternalSession {
    let sess = this.sessions.get(documentId);
    if (!sess) {
      const now = Date.now();
      sess = {
        documentId,
        recordingId: recordingIdOverride || generateRecordingId(),
        documentName: 'Untitled',
        enabled: false,
        captureArea: 'artwork',
        captureResolution: this.defaultCaptureResolution,
        frames: [],
        nextIndex: 0,
        lastCaptureAt: 0,
        lastCaptureSig: null,
        pendingCapture: false,
        pendingCapturePromise: null,
        trailingTimer: null,
        pendingTrailingArgs: null,
        writeQueue: Promise.resolve(),
        memoryBytes: 0,
        storageBytes: 0,
        createdAt: now,
        updatedAt: now,
        generation: 0,
      };
      this.sessions.set(documentId, sess);
    }
    return sess;
  }

  private buildPersistentMeta(sess: InternalSession): PersistentTimelapseMeta {
    return {
      recordingId: sess.recordingId,
      documentName: sess.documentName || 'Untitled',
      enabled: sess.enabled,
      captureArea: sess.captureArea,
      captureResolution: sess.captureResolution,
      nextIndex: sess.nextIndex,
      createdAt: sess.createdAt,
      updatedAt: sess.updatedAt,
    };
  }

  private enqueueMetaPersist(sess: InternalSession): void {
    if (!sess.enabled && sess.frames.length === 0) return;
    const meta = this.buildPersistentMeta(sess);
    sess.writeQueue = sess.writeQueue
      .then(() => persistSessionMeta(meta))
      .then(() => {})
      .catch(() => {});
  }

  public subscribe(listener: () => void): () => void {
    this.listeners.add(listener);
    return () => this.listeners.delete(listener);
  }

  private notify(): void {
    for (const l of this.listeners) l();
  }

  public isRecording(documentId: string | null): boolean {
    if (!documentId) return false;
    return this.sessions.get(documentId)?.enabled ?? false;
  }

  public getRecordingId(documentId: string | null): string | null {
    if (!documentId) return null;
    const sess = this.sessions.get(documentId);
    if (!sess || (!sess.enabled && sess.frames.length === 0)) return null;
    return sess.recordingId;
  }

  public setDocumentName(documentId: string, name: string): void {
    const sess = this.sessions.get(documentId);
    if (!sess) return;
    const clean = (name || 'Untitled').replace(/\*+$/, '').trim() || 'Untitled';
    if (sess.documentName === clean) return;
    sess.documentName = clean;
    sess.updatedAt = Date.now();
    this.enqueueMetaPersist(sess);
  }

  public linkDocumentSave(
    documentId: string | null,
    opts: { documentName?: string; sourcePath?: string | null }
  ): void {
    if (!documentId) return;
    const sess = this.sessions.get(documentId);
    if (!sess || (!sess.enabled && sess.frames.length === 0)) return;
    if (opts.documentName) {
      sess.documentName = opts.documentName.replace(/\*+$/, '').trim() || sess.documentName;
      sess.updatedAt = Date.now();
      this.enqueueMetaPersist(sess);
    }
    saveDocumentRecordingLink({
      recordingId: sess.recordingId,
      docId: documentId,
      sourcePath: opts.sourcePath,
    });
  }

  public setRecording(documentId: string, enabled: boolean, documentName?: string): void {
    const sess = this.getOrCreate(documentId);
    if (documentName) {
      sess.documentName = documentName.replace(/\*+$/, '').trim() || sess.documentName;
    }
    if (sess.enabled === enabled) return;
    sess.enabled = enabled;
    sess.updatedAt = Date.now();
    if (!enabled && sess.trailingTimer !== null) {
      clearTimeout(sess.trailingTimer);
      sess.trailingTimer = null;
      sess.pendingTrailingArgs = null;
    }
    if (enabled || sess.frames.length > 0) {
      saveDocumentRecordingLink({ recordingId: sess.recordingId, docId: documentId });
      this.enqueueMetaPersist(sess);
    }
    this.notify();
  }

  public toggleRecording(documentId: string, documentName?: string): boolean {
    const sess = this.getOrCreate(documentId);
    const next = !sess.enabled;
    this.setRecording(documentId, next, documentName);
    return next;
  }

  public setCaptureArea(documentId: string, captureArea: TimelapseCaptureArea): void {
    const sess = this.getOrCreate(documentId);
    if (sess.captureArea === captureArea) return;
    sess.captureArea = captureArea;
    sess.lastCaptureSig = null;
    sess.updatedAt = Date.now();
    this.enqueueMetaPersist(sess);
    this.notify();
  }

  public setCaptureResolution(
    documentId: string,
    captureResolution: TimelapseCaptureResolution
  ): void {
    const sess = this.getOrCreate(documentId);
    if (sess.captureResolution === captureResolution) return;
    sess.captureResolution = captureResolution;
    sess.lastCaptureSig = null;
    sess.updatedAt = Date.now();
    this.enqueueMetaPersist(sess);
    this.notify();
  }

  public getStats(documentId: string | null): TimelapseSessionStats {
    const backend: 'disk' | 'indexeddb' | 'memory' = isTauriRuntime()
      ? 'disk'
      : isIndexedDbAvailable()
        ? 'indexeddb'
        : 'memory';

    if (!documentId) {
      return {
        documentId: '',
        recordingId: null,
        enabled: false,
        frameCount: 0,
        memoryBytes: 0,
        diskFrames: 0,
        storageBytes: 0,
        captureArea: 'artwork',
        captureResolution: this.defaultCaptureResolution,
        storageBackend: backend,
      };
    }
    const sess = this.sessions.get(documentId);
    if (!sess) {
      return {
        documentId,
        recordingId: null,
        enabled: false,
        frameCount: 0,
        memoryBytes: 0,
        diskFrames: 0,
        storageBytes: 0,
        captureArea: 'artwork',
        captureResolution: this.defaultCaptureResolution,
        storageBackend: backend,
      };
    }
    const diskFrames = sess.frames.filter((f) => f.offloadedToDisk).length;
    return {
      documentId,
      recordingId: sess.enabled || sess.frames.length > 0 ? sess.recordingId : null,
      enabled: sess.enabled,
      frameCount: sess.frames.length,
      memoryBytes: sess.memoryBytes,
      diskFrames,
      storageBytes: sess.storageBytes,
      captureArea: sess.captureArea,
      captureResolution: sess.captureResolution,
      storageBackend: backend,
    };
  }

  public getFrames(documentId: string): TimelapseFrameEntry[] {
    return this.sessions.get(documentId)?.frames ?? [];
  }

  public async waitForPendingCapture(documentId: string): Promise<void> {
    const sess = this.sessions.get(documentId);
    if (!sess) return;
    if (sess.trailingTimer !== null) {
      clearTimeout(sess.trailingTimer);
      sess.trailingTimer = null;
      sess.pendingTrailingArgs = null;
    }
    if (sess.pendingCapturePromise) {
      await sess.pendingCapturePromise.catch(() => {});
    }
    await sess.writeQueue.catch(() => {});
  }

  /**
   * Explicitly deletes all recorded frames for this document from memory AND persistent storage.
   */
  public async clearSession(documentId: string): Promise<void> {
    const sess = this.sessions.get(documentId);
    const recordingId = sess?.recordingId;
    if (sess) {
      sess.generation++;
      if (sess.trailingTimer !== null) {
        clearTimeout(sess.trailingTimer);
        sess.trailingTimer = null;
        sess.pendingTrailingArgs = null;
      }
      const inFlight = sess.pendingCapturePromise;
      if (inFlight) {
        await inFlight.catch(() => {});
      }
      await sess.writeQueue.catch(() => {});
      sess.frames = [];
      sess.nextIndex = 0;
      sess.memoryBytes = 0;
      sess.storageBytes = 0;
      sess.lastCaptureAt = 0;
      sess.lastCaptureSig = null;
      sess.updatedAt = Date.now();
    }
    if (recordingId) {
      await deletePersistedRecording(recordingId);
    }
    if (sess && sess.enabled) {
      // Keep fresh metadata if recording remains armed
      this.enqueueMetaPersist(sess);
    }
    this.notify();
  }

  /**
   * Detaches a document's time-lapse session from RAM on tab close or app exit while
   * PRESERVING all recorded keyframes and metadata in external persistent storage so
   * recording seamlessly continues after app restart or document reopen.
   */
  public async detachSession(documentId: string): Promise<void> {
    const sess = this.sessions.get(documentId);
    if (!sess) return;
    if (sess.trailingTimer !== null) {
      clearTimeout(sess.trailingTimer);
      sess.trailingTimer = null;
      sess.pendingTrailingArgs = null;
    }
    const inFlight = sess.pendingCapturePromise;
    if (inFlight) {
      await inFlight.catch(() => {});
    }
    if (sess.enabled || sess.frames.length > 0) {
      this.enqueueMetaPersist(sess);
      await sess.writeQueue.catch(() => {});
    }
    sess.generation++;
    this.sessions.delete(documentId);
    this.notify();
  }

  /**
   * Permanently removes a session from memory AND deletes its persistent recording from storage
   * (used when explicitly discarding a crashed unsaved session or wiping data).
   */
  public async removeSession(documentId: string): Promise<void> {
    const sess = this.sessions.get(documentId);
    const recordingId = sess?.recordingId ?? documentId;
    if (sess) {
      sess.generation++;
      if (sess.trailingTimer !== null) {
        clearTimeout(sess.trailingTimer);
        sess.trailingTimer = null;
        sess.pendingTrailingArgs = null;
      }
      const inFlight = sess.pendingCapturePromise;
      this.sessions.delete(documentId);
      if (inFlight) {
        await inFlight.catch(() => {});
      }
      await sess.writeQueue.catch(() => {});
    }
    await deletePersistedRecording(recordingId);
    this.notify();
  }

  /**
   * Lists all time-lapse recordings stored persistently in local app storage / IndexedDB.
   */
  public async listStoredRecordings(): Promise<StoredRecordingSummary[]> {
    return listPersistedRecordings();
  }

  /**
   * Deletes an arbitrary stored recording by `recordingId` (detaching if currently active).
   */
  public async deleteStoredRecording(recordingId: string): Promise<void> {
    for (const [docId, sess] of this.sessions.entries()) {
      if (sess.recordingId === recordingId) {
        await this.clearSession(docId);
        return;
      }
    }
    await deletePersistedRecording(recordingId);
    this.notify();
  }

  /**
   * Attaches an existing persisted local recording (e.g. from the Local Recordings drawer)
   * onto `documentId` so the artist can preview, export, or continue recording on it.
   */
  public async attachExistingRecording(
    documentId: string,
    recordingId: string,
    documentName?: string
  ): Promise<{ enabled: boolean; frameCount: number }> {
    return this.attachOrRestoreSession(documentId, {
      documentName,
      fallbackRecordingId: recordingId,
    });
  }

  /**
   * Restores or reconnects a document's time-lapse session from external persistent storage
   * (by `.ink` `recordingId`, saved path/recent-doc link, or crash-recovery ID), migrating
   * any legacy embedded `.ink` frames automatically into external storage.
   */
  public async attachOrRestoreSession(
    documentId: string,
    options: AttachOrRestoreOptions
  ): Promise<{ enabled: boolean; frameCount: number }> {
    const existing = this.sessions.get(documentId);
    const nextGen = (existing?.generation ?? 0) + 1;
    if (existing) {
      existing.generation = nextGen;
      if (existing.trailingTimer !== null) {
        clearTimeout(existing.trailingTimer);
        existing.trailingTimer = null;
        existing.pendingTrailingArgs = null;
      }
      if (existing.pendingCapturePromise) {
        await existing.pendingCapturePromise.catch(() => {});
      }
      await existing.writeQueue.catch(() => {});
    }

    const meta = options.metadata ?? null;
    const validLegacyFrames = Array.isArray(options.legacyFrames)
      ? options.legacyFrames
          .filter((f) => f && f.bytes && f.bytes.byteLength > 0)
          .slice()
          .sort((a, b) => a.index - b.index)
      : [];

    const linkedId = lookupLinkedRecordingId({
      docId: options.linkedDocId ?? documentId,
      sourcePath: options.sourcePath,
    });

    const candidateRecordingId =
      meta?.recordingId ||
      options.fallbackRecordingId ||
      linkedId ||
      null;

    // 1. Try loading from external persistent storage (Tauri disk / Browser IndexedDB)
    let persisted = candidateRecordingId
      ? await loadPersistedSession(candidateRecordingId)
      : null;

    // Also try fallbackRecordingId if different from meta.recordingId and primary was empty
    if (
      (!persisted || (!persisted.meta && persisted.frames.length === 0)) &&
      options.fallbackRecordingId &&
      options.fallbackRecordingId !== candidateRecordingId
    ) {
      const alt = await loadPersistedSession(options.fallbackRecordingId);
      if (alt && (alt.meta || alt.frames.length > 0)) {
        persisted = alt;
      }
    }

    const hasPersisted = Boolean(persisted && (persisted.meta || persisted.frames.length > 0));
    const hasLegacy = validLegacyFrames.length > 0;
    const desiredEnabled = Boolean(meta?.enabled ?? persisted?.meta?.enabled ?? false);

    if (!hasPersisted && !hasLegacy && !desiredEnabled) {
      this.sessions.delete(documentId);
      this.notify();
      return { enabled: false, frameCount: 0 };
    }

    const resolvedRecordingId =
      persisted?.meta?.recordingId ||
      candidateRecordingId ||
      generateRecordingId();

    const now = Date.now();
    const cleanDocName =
      (options.documentName || persisted?.meta?.documentName || 'Untitled')
        .replace(/\*+$/, '')
        .trim() || 'Untitled';

    const captureArea: TimelapseCaptureArea =
      meta?.captureArea ?? persisted?.meta?.captureArea ?? 'artwork';
    const captureResolution: TimelapseCaptureResolution =
      meta?.captureResolution ?? persisted?.meta?.captureResolution ?? this.defaultCaptureResolution;

    const sess: InternalSession = {
      documentId,
      recordingId: resolvedRecordingId,
      documentName: cleanDocName,
      enabled: desiredEnabled,
      captureArea,
      captureResolution,
      frames: [],
      nextIndex: 0,
      lastCaptureAt: 0,
      lastCaptureSig: null,
      pendingCapture: false,
      pendingCapturePromise: null,
      trailingTimer: null,
      pendingTrailingArgs: null,
      writeQueue: Promise.resolve(),
      memoryBytes: 0,
      storageBytes: 0,
      createdAt: persisted?.meta?.createdAt || now,
      updatedAt: now,
      generation: nextGen,
    };
    this.sessions.set(documentId, sess);

    const fallbackW = Math.max(2, Math.round(options.fallbackDims?.width || 1080));
    const fallbackH = Math.max(2, Math.round(options.fallbackDims?.height || 1080));

    // 2. Populate frame index from external persistent storage (0 RAM used for image bytes!)
    if (persisted && persisted.frames.length > 0) {
      const metaFramesByIndex = new Map<number, InkTimelapseFrameMetadata>();
      if (Array.isArray(meta?.frames)) {
        for (const fm of meta.frames) {
          if (fm && Number.isSafeInteger(fm.index) && fm.index >= 0) {
            metaFramesByIndex.set(fm.index, fm);
          }
        }
      }
      let maxIdx = -1;
      let totalBytes = 0;
      for (const pf of persisted.frames) {
        const fallbackFm = metaFramesByIndex.get(pf.index);
        const bytes = pf.bytes || fallbackFm?.bytes || 0;
        totalBytes += bytes;
        sess.frames.push({
          id: `tl-${resolvedRecordingId}-${pf.index}`,
          index: pf.index,
          timestamp: pf.timestamp || fallbackFm?.timestamp || 0,
          width: pf.width || fallbackFm?.width || fallbackW,
          height: pf.height || fallbackFm?.height || fallbackH,
          mimeType:
            pf.mimeType === 'image/png'
              ? 'image/png'
              : pf.mimeType === 'image/jpeg'
                ? 'image/jpeg'
                : 'image/webp',
          bytes,
          offloadedToDisk: true,
          captureArea: pf.captureArea,
        });
        if (pf.index > maxIdx) maxIdx = pf.index;
      }
      sess.storageBytes = persisted.totalBytes || totalBytes;
      sess.nextIndex = Math.max(
        maxIdx + 1,
        persisted.meta?.nextIndex ?? 0,
        meta?.nextIndex ?? 0
      );
      options.onProgress?.(sess.frames.length, sess.frames.length);
    } else if (hasLegacy) {
      // 3. Migrate legacy embedded `.ink` frames into external persistent storage seamlessly
      await this.migrateFramesIntoPersistentStorage(
        sess,
        nextGen,
        validLegacyFrames,
        options.onProgress
      );
      if (this.sessions.get(documentId) !== sess || sess.generation !== nextGen) {
        return { enabled: false, frameCount: 0 };
      }
    } else {
      sess.nextIndex = Math.max(persisted?.meta?.nextIndex ?? 0, meta?.nextIndex ?? 0);
    }

    saveDocumentRecordingLink({
      recordingId: resolvedRecordingId,
      docId: documentId,
      sourcePath: options.sourcePath,
    });
    if (options.linkedDocId && options.linkedDocId !== documentId) {
      saveDocumentRecordingLink({
        recordingId: resolvedRecordingId,
        docId: options.linkedDocId,
      });
    }
    this.enqueueMetaPersist(sess);

    this.notify();
    return { enabled: sess.enabled, frameCount: sess.frames.length };
  }

  private async migrateFramesIntoPersistentStorage(
    sess: InternalSession,
    expectedGen: number,
    validFrames: InkTimelapseFrameData[],
    onProgress?: (done: number, total: number) => void
  ): Promise<void> {
    const total = validFrames.length;
    const normalized = validFrames.map((f, seqIdx) => {
      const mimeType: 'image/webp' | 'image/jpeg' | 'image/png' =
        f.mimeType === 'image/png'
          ? 'image/png'
          : f.mimeType === 'image/jpeg'
            ? 'image/jpeg'
            : 'image/webp';
      const ext: 'webp' | 'jpg' | 'png' =
        mimeType === 'image/png' ? 'png' : mimeType === 'image/jpeg' ? 'jpg' : 'webp';
      return {
        index: seqIdx,
        timestamp: Number.isFinite(f.timestamp) ? f.timestamp : 0,
        width: Math.max(2, Math.round(f.width) || 2),
        height: Math.max(2, Math.round(f.height) || 2),
        mimeType,
        ext,
        bytes: f.bytes,
        captureArea: f.captureArea,
      };
    });

    if (isTauriRuntime()) {
      let cursor = 0;
      while (cursor < total) {
        if (this.sessions.get(sess.documentId) !== sess || sess.generation !== expectedGen) {
          return;
        }
        const batch: typeof normalized = [];
        let batchBytes = 0;
        while (
          cursor < total &&
          batch.length < TAURI_BATCH_MAX_FRAMES &&
          (batch.length === 0 ||
            batchBytes + normalized[cursor].bytes.byteLength <= TAURI_BATCH_MAX_BYTES)
        ) {
          batch.push(normalized[cursor]);
          batchBytes += normalized[cursor].bytes.byteLength;
          cursor++;
        }

        let batchOffloaded = false;
        try {
          const packed = packTimelapseFrameBatch(
            batch.map((b) => ({ index: b.index, ext: b.ext, bytes: b.bytes }))
          );
          await invokeTauriRaw<number>('timelapse_write_frames_batch', packed, {
            'x-session-id': encodeURIComponent(sess.recordingId),
          });
          batchOffloaded = true;
        } catch {
          batchOffloaded = false;
        }

        if (this.sessions.get(sess.documentId) !== sess || sess.generation !== expectedGen) {
          return;
        }

        for (const item of batch) {
          let offloaded = batchOffloaded;
          if (!offloaded) {
            offloaded = await persistSingleFrame(
              sess.recordingId,
              {
                index: item.index,
                timestamp: item.timestamp,
                width: item.width,
                height: item.height,
                mimeType: item.mimeType,
                bytes: item.bytes.byteLength,
                captureArea: item.captureArea,
              },
              item.bytes,
              this.buildPersistentMeta(sess)
            );
          }
          const blob = offloaded
            ? undefined
            : new Blob([item.bytes as BlobPart], { type: item.mimeType });
          if (blob) sess.memoryBytes += blob.size;
          sess.storageBytes += item.bytes.byteLength;
          sess.frames.push({
            id: `tl-${sess.recordingId}-${item.index}`,
            index: item.index,
            timestamp: item.timestamp,
            width: item.width,
            height: item.height,
            mimeType: item.mimeType,
            bytes: item.bytes.byteLength,
            offloadedToDisk: offloaded,
            captureArea: item.captureArea,
            blob,
          });
        }
        onProgress?.(cursor, total);
      }
    } else {
      for (let i = 0; i < total; i++) {
        if (this.sessions.get(sess.documentId) !== sess || sess.generation !== expectedGen) {
          return;
        }
        const item = normalized[i];
        const record: PersistentFrameRecord = {
          index: item.index,
          timestamp: item.timestamp,
          width: item.width,
          height: item.height,
          mimeType: item.mimeType,
          bytes: item.bytes.byteLength,
          captureArea: item.captureArea,
        };
        const persisted = await persistSingleFrame(
          sess.recordingId,
          record,
          item.bytes,
          this.buildPersistentMeta(sess)
        );
        const blob = persisted
          ? undefined
          : new Blob([item.bytes as BlobPart], { type: item.mimeType });
        if (blob) sess.memoryBytes += blob.size;
        sess.storageBytes += item.bytes.byteLength;
        sess.frames.push({
          id: `tl-${sess.recordingId}-${item.index}`,
          index: item.index,
          timestamp: item.timestamp,
          width: item.width,
          height: item.height,
          mimeType: item.mimeType,
          bytes: item.bytes.byteLength,
          offloadedToDisk: persisted,
          captureArea: item.captureArea,
          blob,
        });
        onProgress?.(i + 1, total);
      }
    }

    sess.nextIndex = sess.frames.length;
  }

  /**
   * Backward-compatible restore alias that delegates to `attachOrRestoreSession`.
   */
  public async restoreSession(
    documentId: string,
    metadata: InkTimelapseMetadata | null | undefined,
    frames?: InkTimelapseFrameData[] | null,
    onProgress?: (done: number, total: number) => void
  ): Promise<{ enabled: boolean; frameCount: number }> {
    return this.attachOrRestoreSession(documentId, {
      metadata,
      legacyFrames: frames,
      onProgress,
    });
  }

  /**
   * Restores a time-lapse session after an unexpected crash using the WAL recovery manifest
   * and persisted keyframes in local storage.
   */
  public async restoreFromScratchDisk(
    documentId: string,
    metadata: InkTimelapseMetadata | null | undefined,
    fallbackDims?: CanvasDimensions
  ): Promise<{ enabled: boolean; frameCount: number }> {
    if (!metadata) {
      return { enabled: false, frameCount: 0 };
    }
    return this.attachOrRestoreSession(documentId, {
      metadata,
      fallbackRecordingId: metadata.recordingId || documentId,
      fallbackDims,
    });
  }

  /**
   * Returns lightweight JSON metadata for `.ink` manifests and crash-recovery WAL manifests
   * (zero binary frame payloads).
   */
  public getRecoveryMetadata(documentId: string | null): InkTimelapseMetadata | null {
    if (!documentId) return null;
    const sess = this.sessions.get(documentId);
    if (!sess || (!sess.enabled && sess.frames.length === 0)) return null;
    return {
      recordingId: sess.recordingId,
      storageMode: 'external',
      enabled: sess.enabled,
      frameCount: sess.frames.length,
      nextIndex: sess.nextIndex,
      captureArea: sess.captureArea,
      captureResolution: sess.captureResolution,
    };
  }

  /**
   * Builds a lightweight persistence provider used by `serializeInkProject` so `.ink` saves
   * record the external `recordingId` reference without embedding frame binaries.
   */
  public createPersistenceProvider(documentId: string | null): TimelapsePersistenceProvider | null {
    if (!documentId) return null;
    const frameLookup = new Map<number, TimelapseFrameEntry>();

    return {
      waitForPendingCapture: () => this.waitForPendingCapture(documentId),
      getSessionSnapshot: () => {
        frameLookup.clear();
        const sess = this.sessions.get(documentId);
        if (!sess || (!sess.enabled && sess.frames.length === 0)) {
          return null;
        }
        const frames = sess.frames.map((f) => {
          frameLookup.set(f.index, f);
          return {
            index: f.index,
            timestamp: f.timestamp,
            width: f.width,
            height: f.height,
            mimeType: f.mimeType,
            bytes: f.bytes,
          };
        });
        return {
          recordingId: sess.recordingId,
          enabled: sess.enabled,
          nextIndex: sess.nextIndex,
          captureArea: sess.captureArea,
          captureResolution: sess.captureResolution,
          frames,
        };
      },
      readFrameBytes: async (frameIndex: number) => {
        const entry =
          frameLookup.get(frameIndex) ??
          this.sessions.get(documentId)?.frames.find((f) => f.index === frameIndex);
        if (!entry) return null;
        return this.loadFrameBytes(documentId, entry);
      },
    };
  }

  private scheduleTrailingCapture(
    documentId: string,
    sess: InternalSession,
    args: TrailingCaptureArgs,
    delayMs: number
  ): void {
    sess.pendingTrailingArgs = args;
    if (sess.trailingTimer !== null) return;
    sess.trailingTimer = setTimeout(() => {
      sess.trailingTimer = null;
      const latest = sess.pendingTrailingArgs;
      sess.pendingTrailingArgs = null;
      if (!latest || this.sessions.get(documentId) !== sess || !sess.enabled) return;
      void this.captureKeyframe(
        documentId,
        latest.layers,
        latest.dimensions,
        false,
        latest.liveCtx
      );
    }, Math.max(24, delayMs));
  }

  /**
   * Captures a throttled, off-frame keyframe according to the selected capture area
   * (`artwork`, `canvas-view`, `app-window`) and capture resolution (`720p`..`4k`),
   * offloading immediately to external persistent storage via Rust `ink-engine`.
   */
  public async captureKeyframe(
    documentId: string,
    layers: LayerItem[],
    dimensions: CanvasDimensions,
    force = false,
    liveCtx?: TimelapseLiveCaptureContext
  ): Promise<boolean> {
    const sess = this.sessions.get(documentId);
    if (!sess || !sess.enabled) return false;
    if (typeof document === 'undefined' || dimensions.width <= 0 || dimensions.height <= 0) {
      return false;
    }

    if (liveCtx?.documentName) {
      const cleanName = liveCtx.documentName.replace(/\*+$/, '').trim();
      if (cleanName) sess.documentName = cleanName;
    }

    if (!force && liveCtx?.isDrawingActive?.()) {
      this.scheduleTrailingCapture(
        documentId,
        sess,
        { layers, dimensions, liveCtx },
        Math.max(120, this.minIntervalMs)
      );
      return false;
    }

    const now = Date.now();
    const elapsed = now - sess.lastCaptureAt;
    if (!force && (sess.pendingCapture || elapsed < this.minIntervalMs)) {
      const waitMs = sess.pendingCapture
        ? Math.max(120, this.minIntervalMs)
        : Math.max(32, this.minIntervalMs - elapsed + 16);
      this.scheduleTrailingCapture(
        documentId,
        sess,
        { layers, dimensions, liveCtx },
        waitMs
      );
      return false;
    }

    const gen = sess.generation;
    sess.pendingCapture = true;
    sess.lastCaptureAt = now;

    let run: Promise<boolean> | null = null;
    run = (async (): Promise<boolean> => {
      try {
        if (!force) {
          await scheduleIdleYield(160);
          if (this.sessions.get(documentId) !== sess || sess.generation !== gen || !sess.enabled) {
            return false;
          }
          if (liveCtx?.isDrawingActive?.()) {
            this.scheduleTrailingCapture(
              documentId,
              sess,
              { layers, dimensions, liveCtx },
              Math.max(140, this.minIntervalMs)
            );
            return false;
          }
        }

        const maxCaptureDim = captureResolutionToMaxDim(sess.captureResolution);
        const area = sess.captureArea;

        // Native Rust Artwork Timelapse Capture: renders downscaled PNG straight from
        // crates/ink-engine tiles directly into src-tauri/src/timelapse.rs (ZERO JS pixel IPC!)
        if (isNativeCanvasActive() && area === 'artwork') {
          const idx = sess.nextIndex;
          const nativeRes = await captureNativeTimelapseFrame({
            docId: documentId,
            sessionId: sess.recordingId,
            frameIndex: idx,
            maxDim: maxCaptureDim,
            captureArea: 'artwork',
          });
          if (this.sessions.get(documentId) !== sess || sess.generation !== gen) {
            return false;
          }
          if (nativeRes) {
            sess.nextIndex = idx + 1;
            sess.updatedAt = now;
            const entry: TimelapseFrameEntry = {
              id: `tl-${sess.recordingId}-${idx}`,
              index: idx,
              timestamp: now,
              width: nativeRes.width,
              height: nativeRes.height,
              mimeType: 'image/png',
              bytes: nativeRes.bytes,
              offloadedToDisk: true,
              captureArea: 'artwork',
            };
            sess.storageBytes += entry.bytes;
            sess.frames.push(entry);
            if (sess.frames.length === 1 || sess.frames.length % 10 === 0) {
              this.enqueueMetaPersist(sess);
            }
            this.notify();
            return true;
          }
          return false;
        }

        if (!this.captureCanvas) {
          this.captureCanvas = document.createElement('canvas');
        }

        let outW = 0;
        let outH = 0;
        let capturedAreaUsed: TimelapseCaptureArea = area;

        if (area === 'app-window') {
          const nativeRes = await captureNativeAppWindowToCanvas(
            this.captureCanvas,
            maxCaptureDim
          );
          if (this.sessions.get(documentId) !== sess || sess.generation !== gen) {
            return false;
          }
          if (nativeRes) {
            outW = nativeRes.width;
            outH = nativeRes.height;
            capturedAreaUsed = 'app-window';
          }
        }

        if (outW === 0 && (area === 'canvas-view' || area === 'app-window')) {
          const vp = liveCtx?.viewportElement;
          const cam = liveCtx?.camera;
          const vpW = vp?.clientWidth ?? 0;
          const vpH = vp?.clientHeight ?? 0;
          if (vpW >= 32 && vpH >= 32 && cam) {
            const cvDims = computeCanvasViewDimensions(vpW, vpH, maxCaptureDim);
            this.captureCanvas.width = cvDims.width;
            this.captureCanvas.height = cvDims.height;
            const rendered = await renderNativeCanvasViewToCanvas(
              this.captureCanvas,
              documentId,
              dimensions,
              vpW,
              vpH,
              cam,
              maxCaptureDim,
              {
                showCheckerboard: liveCtx?.showCheckerboard,
                valueCheckEnabled: liveCtx?.valueCheckEnabled,
                matteColor: liveCtx?.matteColor,
              }
            );
            if (this.sessions.get(documentId) !== sess || sess.generation !== gen) {
              return false;
            }
            if (rendered) {
              outW = cvDims.width;
              outH = cvDims.height;
              capturedAreaUsed = 'canvas-view';
            }
          }
        }

        if (outW === 0) {
          return false;
        }

        const encodeQuality = maxCaptureDim >= 2560 ? 0.80 : 0.82;
        let mimeType: 'image/webp' | 'image/jpeg' = 'image/webp';
        let blob: Blob;
        try {
          blob = await canvasToBlob(this.captureCanvas, 'image/webp', encodeQuality);
          if (blob.type !== 'image/webp') {
            mimeType = 'image/jpeg';
          }
        } catch {
          mimeType = 'image/jpeg';
          blob = await canvasToBlob(this.captureCanvas, 'image/jpeg', encodeQuality);
        }

        if (this.sessions.get(documentId) !== sess || sess.generation !== gen) {
          return false;
        }

        const idx = sess.nextIndex++;
        sess.updatedAt = now;

        const entry: TimelapseFrameEntry = {
          id: `tl-${sess.recordingId}-${idx}`,
          index: idx,
          timestamp: now,
          width: outW,
          height: outH,
          mimeType,
          bytes: blob.size,
          offloadedToDisk: false,
          captureArea: capturedAreaUsed,
          blob,
        };

        const metaSnapshot = this.buildPersistentMeta(sess);
        const frameRecord: PersistentFrameRecord = {
          index: idx,
          timestamp: now,
          width: outW,
          height: outH,
          mimeType,
          bytes: blob.size,
          captureArea: capturedAreaUsed,
        };

        const frameBytes = await blobToUint8Array(blob);
        if (this.sessions.get(documentId) !== sess || sess.generation !== gen) {
          return false;
        }

        // Persist immediately to external storage (Tauri persistent disk or Browser IndexedDB)
        const persisted = await persistSingleFrame(
          sess.recordingId,
          frameRecord,
          frameBytes,
          metaSnapshot
        );
        if (this.sessions.get(documentId) !== sess || sess.generation !== gen) {
          return false;
        }

        if (persisted) {
          entry.offloadedToDisk = true;
          entry.blob = undefined; // Keep JS heap RAM usage at 0
        } else {
          sess.memoryBytes += entry.bytes;
        }

        sess.storageBytes += entry.bytes;
        sess.frames.push(entry);

        // Save persistent metadata on first frame or periodically so meta.json stays fresh
        if (sess.frames.length === 1 || sess.frames.length % 10 === 0) {
          this.enqueueMetaPersist(sess);
        }

        // Bounded RAM thinning ONLY when running without any persistent backend (e.g. headless fallback)
        if (!persisted && sess.memoryBytes > this.maxRamBytes && sess.frames.length > 8) {
          const thinned: TimelapseFrameEntry[] = [];
          let memBytes = 0;
          let totalBytes = 0;
          for (let i = 0; i < sess.frames.length; i++) {
            const f = sess.frames[i];
            const keep = i === 0 || i === sess.frames.length - 1 || i % 2 === 0;
            if (keep) {
              thinned.push(f);
              totalBytes += f.bytes;
              memBytes += f.offloadedToDisk ? 0 : f.bytes;
            }
          }
          sess.frames = thinned;
          sess.memoryBytes = memBytes;
          sess.storageBytes = totalBytes;
        }

        this.notify();
        return true;
      } finally {
        sess.pendingCapture = false;
        if (sess.pendingCapturePromise === run) {
          sess.pendingCapturePromise = null;
        }
      }
    })();

    sess.pendingCapturePromise = run;
    return run;
  }

  /**
   * Resolves a frame entry into raw binary bytes (reading back from external persistent storage if offloaded).
   */
  public async loadFrameBytes(
    documentId: string,
    frame: TimelapseFrameEntry
  ): Promise<Uint8Array | null> {
    if (frame.blob) {
      try {
        return await blobToUint8Array(frame.blob);
      } catch {
        return null;
      }
    }
    const sess = this.sessions.get(documentId);
    const recordingId = sess?.recordingId ?? documentId;
    if (frame.offloadedToDisk) {
      return readPersistedFrame(recordingId, frame.index, frame.mimeType);
    }
    return null;
  }

  /**
   * Resolves a frame entry into a Blob (reading back from external persistent storage if offloaded).
   */
  public async loadFrameBlob(
    documentId: string,
    frame: TimelapseFrameEntry
  ): Promise<Blob | null> {
    if (frame.blob) return frame.blob;
    const bytes = await this.loadFrameBytes(documentId, frame);
    if (!bytes) return null;
    return new Blob([bytes as BlobPart], { type: frame.mimeType });
  }

  public async checkFfmpegAvailable(): Promise<boolean> {
    if (!isTauriRuntime()) return false;
    try {
      return await invokeTauri<boolean>('timelapse_check_ffmpeg', {});
    } catch {
      return false;
    }
  }

  /**
   * Renders captured keyframes into a downloadable WebM or MP4 video with full FPS, quality,
   * duration, resolution, aspect ratio, background mode, and watermark fidelity.
   */
  public async exportVideo(
    documentId: string,
    options: TimelapseExportOptions,
    onProgress?: (progress: number) => void
  ): Promise<TimelapseExportResult> {
    await this.waitForPendingCapture(documentId);
    const sess = this.sessions.get(documentId);
    if (!sess || sess.frames.length === 0) {
      throw new Error('No time-lapse frames recorded for this document.');
    }

    const fps = Math.max(1, Math.min(60, Math.round(options.fps ?? 30)));
    const quality: TimelapseQualityPreset = options.quality ?? 'high';
    const bgMode: TimelapseBackgroundMode = options.backgroundMode ?? (options.backgroundColor === '#141414' ? 'dark' : 'white');
    const bgColor =
      options.backgroundColor || (bgMode === 'dark' ? '#141414' : '#ffffff');

    // Use the latest frame dimensions for 'original' aspect ratio so recent capture-area choices define aspect cleanly
    const refFrame = sess.frames[sess.frames.length - 1] ?? sess.frames[0];
    const targetDims = computeTimelapseDimensions(
      refFrame.width,
      refFrame.height,
      options.aspectRatio,
      options.resolution
    );
    const sampledIndices = sampleTimelapseFrameIndices(
      sess.frames.length,
      options.duration,
      fps,
      options.customDurationSec
    );

    // 1. Native FFmpeg hardware-friendly MP4 export in Tauri when frames are persisted on disk
    if (
      options.preferFfmpeg &&
      isTauriRuntime() &&
      sess.frames.every((f) => f.offloadedToDisk)
    ) {
      const hasFfmpeg = await this.checkFfmpegAvailable();
      if (hasFfmpeg) {
        onProgress?.(0.15);
        const packedIndices = packFrameIndices(
          sampledIndices.map((idx) => sess.frames[idx].index)
        );

        let wmOverlay: { bytes: Uint8Array; x: number; y: number } | null = null;
        if (options.watermark?.enabled) {
          wmOverlay = await renderWatermarkOverlayPng(
            targetDims.width,
            targetDims.height,
            options.watermark
          ).catch(() => null);
        }

        let body: Uint8Array;
        const headers: Record<string, string> = {
          'x-session-id': encodeURIComponent(sess.recordingId),
          'x-ext':
            refFrame.mimeType === 'image/png'
              ? 'png'
              : refFrame.mimeType === 'image/webp'
                ? 'webp'
                : 'jpg',
          'x-fps': String(fps),
          'x-width': String(targetDims.width),
          'x-height': String(targetDims.height),
          'x-bg-color': encodeURIComponent(bgColor),
          'x-bg-blur': bgMode === 'blur' ? '1' : '0',
          'x-quality': quality,
        };

        if (wmOverlay && wmOverlay.bytes.byteLength > 0) {
          body = new Uint8Array(packedIndices.byteLength + wmOverlay.bytes.byteLength);
          body.set(packedIndices, 0);
          body.set(wmOverlay.bytes, packedIndices.byteLength);
          headers['x-watermark-bytes'] = String(wmOverlay.bytes.byteLength);
          headers['x-watermark-x'] = String(wmOverlay.x);
          headers['x-watermark-y'] = String(wmOverlay.y);
        } else {
          body = packedIndices;
        }

        onProgress?.(0.3);
        const mp4Raw = await invokeTauriRaw<ArrayBuffer | Uint8Array | number[]>(
          'timelapse_export_ffmpeg',
          body,
          headers
        );
        onProgress?.(1);
        return {
          blob: new Blob([toArrayBuffer(mp4Raw)], { type: 'video/mp4' }),
          mimeType: 'video/mp4',
          extension: '.mp4',
          frameCount: sampledIndices.length,
          durationSec: sampledIndices.length / fps,
        };
      }
    }

    // 2. Browser / WebView MediaRecorder video pipeline
    if (typeof document === 'undefined' || typeof MediaRecorder === 'undefined') {
      throw new Error('Video recording is not supported in this environment.');
    }

    const canvas = document.createElement('canvas');
    canvas.width = targetDims.width;
    canvas.height = targetDims.height;
    const ctx = canvas.getContext('2d');
    if (!ctx) throw new Error('Failed to create 2D context for time-lapse export.');

    const candidateMimes = [
      'video/webm;codecs=vp9',
      'video/webm;codecs=vp8',
      'video/webm',
      'video/mp4',
    ];
    const mimeType =
      candidateMimes.find((m) => MediaRecorder.isTypeSupported(m)) || 'video/webm';
    const extension = mimeType.includes('mp4') ? '.mp4' : '.webm';

    const wmImg =
      options.watermark?.enabled &&
      options.watermark.mode === 'image' &&
      options.watermark.imageDataUrl
        ? await loadWatermarkImageElement(options.watermark.imageDataUrl)
        : null;

    const stream = canvas.captureStream(fps);
    const recorder = new MediaRecorder(stream, {
      mimeType,
      videoBitsPerSecond: computeMediaRecorderBitrate(options.resolution, fps, quality),
    });

    const chunks: BlobPart[] = [];
    recorder.ondataavailable = (ev) => {
      if (ev.data && ev.data.size > 0) chunks.push(ev.data);
    };

    const stoppedPromise = new Promise<Blob>((resolve, reject) => {
      recorder.onstop = () => resolve(new Blob(chunks, { type: mimeType }));
      recorder.onerror = () => reject(new Error('MediaRecorder encoding failed.'));
    });

    // Bounded LRU cache of decoded frames (prefers off-main-thread ImageBitmap)
    const decodedCache = new Map<number, ImageBitmap | HTMLImageElement>();
    const canUseBitmap = typeof createImageBitmap === 'function';

    const decodeSource = async (
      srcIdx: number
    ): Promise<ImageBitmap | HTMLImageElement | null> => {
      const cached = decodedCache.get(srcIdx);
      if (cached) return cached;
      const frame = sess.frames[srcIdx];
      if (!frame) return null;
      const blob = await this.loadFrameBlob(documentId, frame);
      if (!blob) return null;

      let decoded: ImageBitmap | HTMLImageElement | null = null;
      if (canUseBitmap) {
        try {
          decoded = await createImageBitmap(blob);
        } catch {
          decoded = null;
        }
      }
      if (!decoded) {
        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 (decodedCache.size >= 14) {
          const oldestKey = decodedCache.keys().next().value;
          if (oldestKey !== undefined) {
            const oldest = decodedCache.get(oldestKey);
            if (oldest && 'close' in oldest && typeof oldest.close === 'function') {
              oldest.close();
            }
            decodedCache.delete(oldestKey);
          }
        }
        decodedCache.set(srcIdx, decoded);
      }
      return decoded;
    };

    recorder.start();
    const frameIntervalMs = Math.max(16, Math.round(1000 / fps));
    let lastDrawnSrcIdx = -1;
    let blob: Blob;

    try {
      for (let i = 0; i < sampledIndices.length; i++) {
        const srcIdx = sampledIndices[i];
        // Optimization: skip redundant canvas redraw when consecutive timeline frames share the same keyframe
        if (srcIdx !== lastDrawnSrcIdx) {
          const img = await decodeSource(srcIdx);
          renderTimelapseOutputFrame(ctx, img, targetDims.width, targetDims.height, {
            backgroundMode: bgMode,
            backgroundColor: bgColor,
            watermark: options.watermark,
            watermarkImage: wmImg,
          });
          lastDrawnSrcIdx = srcIdx;
        }
        onProgress?.((i + 1) / sampledIndices.length);
        await new Promise((r) => setTimeout(r, frameIntervalMs));
      }
      if (recorder.state !== 'inactive') {
        recorder.stop();
      }
      blob = await stoppedPromise;
    } catch (err) {
      try {
        if (recorder.state !== 'inactive') {
          recorder.stop();
        }
      } catch {
        // Ignore stop errors during failure unwind
      }
      void stoppedPromise.catch(() => {});
      throw err;
    } finally {
      for (const item of decodedCache.values()) {
        if ('close' in item && typeof item.close === 'function') {
          item.close();
        }
      }
      decodedCache.clear();
      stream.getTracks().forEach((t) => {
        try {
          t.stop();
        } catch {
          // Ignore track stop errors
        }
      });
    }

    return {
      blob,
      mimeType,
      extension,
      frameCount: sampledIndices.length,
      durationSec: sampledIndices.length / fps,
    };
  }
}

export const globalTimelapseManager = new TimelapseRecorderManager();