summaryrefslogtreecommitdiff
path: root/apps/web/src/hooks/use-frame-cache.ts
blob: 8dc999660564d766a9f127f37671137b4e91c8bc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import { useRef, useCallback } from "react";
import {
  TimelineTrack,
  TimelineElement,
  MediaElement,
  TextElement,
} from "@/types/timeline";
import { MediaFile } from "@/types/media";
import { TProject } from "@/types/project";

interface CachedFrame {
  imageData: ImageData;
  timelineHash: string;
  timestamp: number;
}

interface FrameCacheOptions {
  maxCacheSize?: number; // Maximum number of cached frames
  cacheResolution?: number; // Frames per second to cache at
}

// Shared singleton cache across hook instances (HMR-safe)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const __frameCacheGlobal: any = globalThis as any;
const __sharedFrameCache: Map<number, CachedFrame> =
  __frameCacheGlobal.__sharedFrameCache ?? new Map<number, CachedFrame>();
__frameCacheGlobal.__sharedFrameCache = __sharedFrameCache;

export function useFrameCache(options: FrameCacheOptions = {}) {
  const { maxCacheSize = 300, cacheResolution = 30 } = options; // 10 seconds at 30fps

  const frameCacheRef = useRef(__sharedFrameCache);

  // Generate a hash of the timeline state that affects rendering
  const getTimelineHash = useCallback(
    (
      time: number,
      tracks: TimelineTrack[],
      mediaFiles: MediaFile[],
      activeProject: TProject | null
    ): string => {
      // Get elements that are active at this time
      const activeElements: Array<{
        id: string;
        type: string;
        startTime: number;
        duration: number;
        trimStart: number;
        trimEnd: number;
        mediaId?: string;
        // Text-specific properties
        content?: string;
        fontSize?: number;
        fontFamily?: string;
        color?: string;
        backgroundColor?: string;
        x?: number;
        y?: number;
        rotation?: number;
        opacity?: number;
      }> = [];

      for (const track of tracks) {
        if (track.muted) continue;

        for (const element of track.elements) {
          // Check if element has hidden property (some elements might not have it)
          const isHidden = "hidden" in element ? element.hidden : false;
          if (isHidden) continue;

          const elementStart = element.startTime;
          const elementEnd =
            element.startTime +
            (element.duration - element.trimStart - element.trimEnd);

          if (time >= elementStart && time < elementEnd) {
            if (element.type === "media") {
              const mediaElement = element as MediaElement;
              activeElements.push({
                id: element.id,
                type: element.type,
                startTime: element.startTime,
                duration: element.duration,
                trimStart: element.trimStart,
                trimEnd: element.trimEnd,
                mediaId: mediaElement.mediaId,
              });
            } else if (element.type === "text") {
              const textElement = element as TextElement;
              activeElements.push({
                id: element.id,
                type: element.type,
                startTime: element.startTime,
                duration: element.duration,
                trimStart: element.trimStart,
                trimEnd: element.trimEnd,
                content: textElement.content,
                fontSize: textElement.fontSize,
                fontFamily: textElement.fontFamily,
                color: textElement.color,
                backgroundColor: textElement.backgroundColor,
                x: textElement.x,
                y: textElement.y,
                rotation: textElement.rotation,
                opacity: textElement.opacity,
              });
            }
          }
        }
      }

      // Include project settings that affect rendering
      const projectState = {
        backgroundColor: activeProject?.backgroundColor,
        backgroundType: activeProject?.backgroundType,
        blurIntensity: activeProject?.blurIntensity,
        canvasSize: activeProject?.canvasSize,
      };

      return JSON.stringify({
        activeElements,
        projectState,
        time: Math.floor(time * cacheResolution) / cacheResolution, // Quantize time
      });
    },
    [cacheResolution]
  );

  // Check if a frame is cached and valid
  const isFrameCached = useCallback(
    (
      time: number,
      tracks: TimelineTrack[],
      mediaFiles: MediaFile[],
      activeProject: TProject | null
    ): boolean => {
      const frameKey = Math.floor(time * cacheResolution);
      const cached = frameCacheRef.current.get(frameKey);

      if (!cached) return false;

      const currentHash = getTimelineHash(
        time,
        tracks,
        mediaFiles,
        activeProject
      );
      return cached.timelineHash === currentHash;
    },
    [getTimelineHash, cacheResolution]
  );

  // Get cached frame if available and valid
  const getCachedFrame = useCallback(
    (
      time: number,
      tracks: TimelineTrack[],
      mediaFiles: MediaFile[],
      activeProject: TProject | null
    ): ImageData | null => {
      const frameKey = Math.floor(time * cacheResolution);
      const cached = frameCacheRef.current.get(frameKey);

      if (!cached) return null;

      const currentHash = getTimelineHash(
        time,
        tracks,
        mediaFiles,
        activeProject
      );
      if (cached.timelineHash !== currentHash) {
        // Cache is stale, remove it
        frameCacheRef.current.delete(frameKey);
        return null;
      }

      return cached.imageData;
    },
    [getTimelineHash, cacheResolution]
  );

  // Cache a rendered frame
  const cacheFrame = useCallback(
    (
      time: number,
      imageData: ImageData,
      tracks: TimelineTrack[],
      mediaFiles: MediaFile[],
      activeProject: TProject | null
    ): void => {
      const frameKey = Math.floor(time * cacheResolution);
      const timelineHash = getTimelineHash(
        time,
        tracks,
        mediaFiles,
        activeProject
      );

      // Enforce cache size limit (LRU eviction)
      if (frameCacheRef.current.size >= maxCacheSize) {
        // Remove oldest entries
        const entries = Array.from(frameCacheRef.current.entries());
        entries.sort((a, b) => a[1].timestamp - b[1].timestamp);

        // Remove oldest 20% of entries
        const toRemove = Math.floor(entries.length * 0.2);
        for (let i = 0; i < toRemove; i++) {
          frameCacheRef.current.delete(entries[i][0]);
        }
      }

      frameCacheRef.current.set(frameKey, {
        imageData,
        timelineHash,
        timestamp: Date.now(),
      });
    },
    [getTimelineHash, cacheResolution, maxCacheSize]
  );

  // Clear cache when timeline changes significantly
  const invalidateCache = useCallback(() => {
    frameCacheRef.current.clear();
  }, []);

  // Get render status for timeline indicator
  const getRenderStatus = useCallback(
    (
      time: number,
      tracks: TimelineTrack[],
      mediaFiles: MediaFile[],
      activeProject: TProject | null
    ): "cached" | "not-cached" => {
      return isFrameCached(time, tracks, mediaFiles, activeProject)
        ? "cached"
        : "not-cached";
    },
    [isFrameCached]
  );

  // Pre-render frames around current time
  const preRenderNearbyFrames = useCallback(
    async (
      currentTime: number,
      tracks: TimelineTrack[],
      mediaFiles: MediaFile[],
      activeProject: TProject | null,
      renderFunction: (time: number) => Promise<ImageData>,
      range: number = 3 // seconds
    ) => {
      const framesToPreRender: number[] = [];

      // Calculate frames to pre-render (around current time)
      for (
        let offset = -range;
        offset <= range;
        offset += 1 / cacheResolution
      ) {
        const time = currentTime + offset;
        if (time < 0) continue;

        if (!isFrameCached(time, tracks, mediaFiles, activeProject)) {
          framesToPreRender.push(time);
        }
      }

      // Expand to full 1-second buckets to avoid fragmented tiny cache regions
      const secondsToPreRender = new Set<number>();
      for (const t of framesToPreRender) {
        secondsToPreRender.add(Math.floor(t));
      }

      const expandedTimes: number[] = [];
      for (const s of secondsToPreRender) {
        for (let k = 0; k < cacheResolution; k++) {
          const t = s + k / cacheResolution;
          if (t < 0) continue;
          if (!isFrameCached(t, tracks, mediaFiles, activeProject)) {
            expandedTimes.push(t);
          }
        }
      }

      // Sort forward-first near currentTime to improve perceived responsiveness
      expandedTimes.sort((a, b) => {
        const da = a >= currentTime ? a - currentTime : currentTime - a + 1e6;
        const db = b >= currentTime ? b - currentTime : currentTime - b + 1e6;
        return da - db;
      });

      // Cap total scheduled renders to avoid jank (e.g., up to 90 frames)
      const CAP = Math.max(30, Math.min(90, cacheResolution * 3));
      const toSchedule = expandedTimes.slice(0, CAP);

      // Pre-render during idle time
      for (const time of toSchedule) {
        requestIdleCallback(async () => {
          try {
            const imageData = await renderFunction(time);
            cacheFrame(time, imageData, tracks, mediaFiles, activeProject);
          } catch (error) {
            console.warn(`Pre-render failed for time ${time}:`, error);
          }
        });
      }
    },
    [isFrameCached, cacheFrame, cacheResolution]
  );

  return {
    isFrameCached,
    getCachedFrame,
    cacheFrame,
    invalidateCache,
    getRenderStatus,
    preRenderNearbyFrames,
    cacheSize: frameCacheRef.current.size,
  };
}