summaryrefslogtreecommitdiff
path: root/apps/web/src/lib/timeline-renderer.ts
blob: 4d00129c4f4f3ed149ecb65aa2ffb521124fba70 (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
import type { TimelineTrack } from "@/types/timeline";
import type { MediaFile } from "@/types/media";
import type { BlurIntensity } from "@/types/project";
import { videoCache } from "./video-cache";
import { drawCssBackground } from "./canvas-gradients";

export interface RenderContext {
  ctx: CanvasRenderingContext2D;
  time: number;
  canvasWidth: number;
  canvasHeight: number;
  tracks: TimelineTrack[];
  mediaFiles: MediaFile[];
  backgroundColor?: string;
  backgroundType?: "color" | "blur";
  blurIntensity?: BlurIntensity;
  projectCanvasSize?: { width: number; height: number };
}

const imageElementCache = new Map<string, HTMLImageElement>();

async function getImageElement(
  mediaItem: MediaFile
): Promise<HTMLImageElement> {
  const cacheKey = mediaItem.id;
  const cached = imageElementCache.get(cacheKey);
  if (cached) return cached;
  const img = new Image();
  await new Promise<void>((resolve, reject) => {
    img.onload = () => resolve();
    img.onerror = () => reject(new Error("Image load failed"));
    img.src = mediaItem.url || URL.createObjectURL(mediaItem.file);
  });
  imageElementCache.set(cacheKey, img);
  return img;
}

export async function renderTimelineFrame({
  ctx,
  time,
  canvasWidth,
  canvasHeight,
  tracks,
  mediaFiles,
  backgroundColor,
  backgroundType,
  blurIntensity,
  projectCanvasSize,
}: RenderContext): Promise<void> {
  // Background
  ctx.clearRect(0, 0, canvasWidth, canvasHeight);
  if (
    backgroundColor &&
    backgroundColor !== "transparent" &&
    !backgroundColor.includes("gradient")
  ) {
    ctx.fillStyle = backgroundColor;
    ctx.fillRect(0, 0, canvasWidth, canvasHeight);
  }

  // If backgroundColor is a CSS gradient string, draw it using JS (no foreignObject) to avoid CORS tainting
  if (backgroundColor && backgroundColor.includes("gradient")) {
    try {
      drawCssBackground(ctx, canvasWidth, canvasHeight, backgroundColor);
    } catch {
      // best-effort; ignore failures
    }
  }

  const scaleX = projectCanvasSize ? canvasWidth / projectCanvasSize.width : 1;
  const scaleY = projectCanvasSize
    ? canvasHeight / projectCanvasSize.height
    : 1;
  const idToMedia = new Map(mediaFiles.map((m) => [m.id, m] as const));
  const active: Array<{
    track: TimelineTrack;
    element: TimelineTrack["elements"][number];
    mediaItem: MediaFile | null;
  }> = [];

  for (let t = tracks.length - 1; t >= 0; t -= 1) {
    const track = tracks[t];
    for (const element of track.elements) {
      if (element.hidden) continue;
      const elementStart = element.startTime;
      const elementEnd =
        element.startTime +
        (element.duration - element.trimStart - element.trimEnd);
      if (time >= elementStart && time < elementEnd) {
        let mediaItem: MediaFile | null = null;
        if (element.type === "media") {
          mediaItem =
            element.mediaId === "test"
              ? null
              : idToMedia.get(element.mediaId) || null;
        }
        active.push({ track, element, mediaItem });
      }
    }
  }

  // If background is set to blur, draw the active media as a blurred cover layer first
  if (backgroundType === "blur") {
    const blurPx = Math.max(0, blurIntensity ?? 8);
    // Find a suitable media element (video/image) among active elements
    const bgCandidate = active.find(({ element, mediaItem }) => {
      return (
        element.type === "media" &&
        mediaItem !== null &&
        (mediaItem.type === "video" || mediaItem.type === "image")
      );
    });
    if (bgCandidate && bgCandidate.mediaItem) {
      const { element, mediaItem } = bgCandidate;
      try {
        if (mediaItem.type === "video") {
          const localTime = time - element.startTime + element.trimStart;
          const frame = await videoCache.getFrameAt(
            mediaItem.id,
            mediaItem.file,
            Math.max(0, localTime)
          );
          if (frame) {
            const mediaW = Math.max(1, mediaItem.width || canvasWidth);
            const mediaH = Math.max(1, mediaItem.height || canvasHeight);
            const coverScale = Math.max(
              canvasWidth / mediaW,
              canvasHeight / mediaH
            );
            const drawW = mediaW * coverScale;
            const drawH = mediaH * coverScale;
            const drawX = (canvasWidth - drawW) / 2;
            const drawY = (canvasHeight - drawH) / 2;
            ctx.save();
            ctx.filter = `blur(${blurPx}px)`;
            ctx.drawImage(frame.canvas, drawX, drawY, drawW, drawH);
            ctx.restore();
          }
        } else if (mediaItem.type === "image") {
          const img = await getImageElement(mediaItem);
          const mediaW = Math.max(
            1,
            mediaItem.width || img.naturalWidth || canvasWidth
          );
          const mediaH = Math.max(
            1,
            mediaItem.height || img.naturalHeight || canvasHeight
          );
          const coverScale = Math.max(
            canvasWidth / mediaW,
            canvasHeight / mediaH
          );
          const drawW = mediaW * coverScale;
          const drawH = mediaH * coverScale;
          const drawX = (canvasWidth - drawW) / 2;
          const drawY = (canvasHeight - drawH) / 2;
          ctx.save();
          ctx.filter = `blur(${blurPx}px)`;
          ctx.drawImage(img, drawX, drawY, drawW, drawH);
          ctx.restore();
        }
      } catch {
        // Ignore background blur failures; foreground will still render
      }
    }
  }

  for (const { element, mediaItem } of active) {
    if (element.type === "media" && mediaItem) {
      if (mediaItem.type === "video") {
        try {
          const localTime = time - element.startTime + element.trimStart;

          const frame = await videoCache.getFrameAt(
            mediaItem.id,
            mediaItem.file,
            localTime
          );
          if (!frame) continue;

          const mediaW = Math.max(1, mediaItem.width || canvasWidth);
          const mediaH = Math.max(1, mediaItem.height || canvasHeight);
          const containScale = Math.min(
            canvasWidth / mediaW,
            canvasHeight / mediaH
          );
          const drawW = mediaW * containScale;
          const drawH = mediaH * containScale;
          const drawX = (canvasWidth - drawW) / 2;
          const drawY = (canvasHeight - drawH) / 2;

          ctx.drawImage(frame.canvas, drawX, drawY, drawW, drawH);
        } catch (error) {
          console.warn(
            `Failed to render video frame for ${mediaItem.name}:`,
            error
          );
        }
      }
      if (mediaItem.type === "image") {
        const img = new Image();
        await new Promise<void>((resolve, reject) => {
          img.onload = () => resolve();
          img.onerror = () => reject(new Error("Image load failed"));
          img.src = mediaItem.url || URL.createObjectURL(mediaItem.file);
        });
        const mediaW = Math.max(
          1,
          mediaItem.width || img.naturalWidth || canvasWidth
        );
        const mediaH = Math.max(
          1,
          mediaItem.height || img.naturalHeight || canvasHeight
        );
        const containScale = Math.min(
          canvasWidth / mediaW,
          canvasHeight / mediaH
        );
        const drawW = mediaW * containScale;
        const drawH = mediaH * containScale;
        const drawX = (canvasWidth - drawW) / 2;
        const drawY = (canvasHeight - drawH) / 2;
        ctx.drawImage(img, drawX, drawY, drawW, drawH);
      }
    }
    if (element.type === "text") {
      const text = element;
      const posX = canvasWidth / 2 + text.x * scaleX;
      const posY = canvasHeight / 2 + text.y * scaleY;
      ctx.save();
      ctx.translate(posX, posY);
      ctx.rotate((text.rotation * Math.PI) / 180);
      ctx.globalAlpha = Math.max(0, Math.min(1, text.opacity));
      const px = text.fontSize * scaleX;
      const weight = text.fontWeight === "bold" ? "bold " : "";
      const style = text.fontStyle === "italic" ? "italic " : "";
      ctx.font = `${style}${weight}${px}px ${text.fontFamily}`;
      ctx.fillStyle = text.color;
      ctx.textAlign = text.textAlign as CanvasTextAlign;
      ctx.textBaseline = "middle";
      const metrics = ctx.measureText(text.content);
      const hasBoxMetrics =
        "actualBoundingBoxAscent" in metrics &&
        "actualBoundingBoxDescent" in metrics;
      const ascent = hasBoxMetrics
        ? (
            metrics as TextMetrics & {
              actualBoundingBoxAscent: number;
              actualBoundingBoxDescent: number;
            }
          ).actualBoundingBoxAscent
        : px * 0.8;
      const descent = hasBoxMetrics
        ? (
            metrics as TextMetrics & {
              actualBoundingBoxAscent: number;
              actualBoundingBoxDescent: number;
            }
          ).actualBoundingBoxDescent
        : px * 0.2;
      const textW = metrics.width;
      const textH = ascent + descent;
      const padX = 8 * scaleX;
      const padY = 4 * scaleX;
      if (text.backgroundColor) {
        ctx.save();
        ctx.fillStyle = text.backgroundColor;
        let bgLeft = -textW / 2;
        if (ctx.textAlign === "left") bgLeft = 0;
        if (ctx.textAlign === "right") bgLeft = -textW;
        ctx.fillRect(
          bgLeft - padX,
          -textH / 2 - padY,
          textW + padX * 2,
          textH + padY * 2
        );
        ctx.restore();
      }
      ctx.fillText(text.content, 0, 0);
      ctx.restore();
    }
  }
}