Skip to content

Create professional demos and 3D mockups in seconds, directly in your browser

feat: add Phone 3D composite drawing utility and enhance video upload cache

CristianOlivera12fc94b02efb4
diff --git a/hooks/useVideoThumbnails.ts b/hooks/useVideoThumbnails.ts
index ac934dd..f4c1007 100644
--- a/hooks/useVideoThumbnails.ts
+++ b/hooks/useVideoThumbnails.ts
@@ -28,7 +28,7 @@ const QUALITY_PRESETS: Record<ThumbnailQuality, number | null> = {
native: null,
};
-// Low quality preset for fast initial loading
+// Low quality preset for fastinitial loading
const LOW_QUALITY_WIDTH = 480;
export interface UseVideoThumbnailsReturn {
@@ -39,13 +39,6 @@ export interface UseVideoThumbnailsReturn {
regenerate: () => void;
}
-/**
- * Hook to generate high-quality video thumbnails for smooth scrubbing preview
- * Features:
- * - IndexedDB caching (doesn't regenerate if cached)
- * - Progressive loading (low quality first, then high quality)
- * - Background processing using requestIdleCallback
- */
export function useVideoThumbnails(
videoUrl: string | null,
duration: number,
@@ -312,13 +305,22 @@ export function useVideoThumbnails(
};
}, [videoUrl, duration, videoId, generateThumbnails]);
+ const lowQualityThumbnailsRef = useRef<VideoThumbnail[]>([]);
+ const highQualityThumbnailsRef = useRef<VideoThumbnail[]>([]);
+
+ useEffect(() => {
+ lowQualityThumbnailsRef.current = lowQualityThumbnails;
+ }, [lowQualityThumbnails]);
+
+ useEffect(() => {
+ highQualityThumbnailsRef.current = highQualityThumbnails;
+ }, [highQualityThumbnails]);
+
const getThumbnailForTime = useCallback((time: number): VideoThumbnail | null => {
const findNearest = (thumbs: VideoThumbnail[]): VideoThumbnail | null => {
if (thumbs.length === 0) return null;
-
let left = 0;
let right = thumbs.length - 1;
-
while (left < right) {
const mid = Math.floor((left + right) / 2);
if (thumbs[mid].time < time) {
@@ -327,7 +329,6 @@ export function useVideoThumbnails(
right = mid;
}
}
-
if (left > 0) {
const prevDiff = Math.abs(thumbs[left - 1].time - time);
const currDiff = Math.abs(thumbs[left].time - time);
@@ -335,11 +336,13 @@ export function useVideoThumbnails(
return thumbs[left - 1];
}
}
-
return thumbs[left];
};
- const highThumb = findNearest(highQualityThumbnails);
+ const highThumbs = highQualityThumbnailsRef.current;
+ const lowThumbs = lowQualityThumbnailsRef.current;
+
+ const highThumb = findNearest(highThumbs);
if (highThumb) {
const timeDiff = Math.abs(highThumb.time - time);
if (timeDiff <= interval * 1.5) {
@@ -347,16 +350,14 @@ export function useVideoThumbnails(
}
}
- const lowThumb = findNearest(lowQualityThumbnails);
-
+ const lowThumb = findNearest(lowThumbs);
if (highThumb && lowThumb) {
const highDiff = Math.abs(highThumb.time - time);
const lowDiff = Math.abs(lowThumb.time - time);
return highDiff <= lowDiff ? highThumb : lowThumb;
}
-
return highThumb || lowThumb;
- }, [lowQualityThumbnails, highQualityThumbnails, interval]);
+ }, [interval]);
const regenerate = useCallback(() => {
generateThumbnails(true);
diff --git a/lib/canvas-elements-render.utils.ts b/lib/canvas-elements-render.utils.ts
new file mode 100644
index 0000000..feef561
--- /dev/null
+++ b/lib/canvas-elements-render.utils.ts
@@ -0,0 +1,115 @@
+import type { SvgElement, CanvasElement } from "@/types/canvas-elements.types";
+import { getSvgDataUrl } from "@/components/canvas-svg";
+import { VIDEO_Z_INDEX } from "@/lib/constants";
+
+export async function renderCanvasElements(
+ ctx: CanvasRenderingContext2D,
+ elements: CanvasElement[],
+ canvasWidth: number,
+ canvasHeight: number,
+ behindVideo: boolean,
+ svgImageCache: Map<string, HTMLImageElement>,
+ elementImageCache: Map<string, HTMLImageElement>,
+): Promise<void> {
+ const filteredElements = elements.filter(el =>
+ behindVideo ? el.zIndex < VIDEO_Z_INDEX : el.zIndex >= VIDEO_Z_INDEX
+ );
+ const sortedElements = [...filteredElements].sort((a, b) => a.zIndex - b.zIndex);
+ const referenceSize = Math.min(canvasWidth, canvasHeight);
+
+ for (const element of sortedElements) {
+ if (element.type === "svg") {
+ const svgElement = element as SvgElement;
+ const svgDataUrl = getSvgDataUrl(svgElement.svgId, svgElement.color || "#FFFFFF");
+ if (!svgDataUrl) continue;
+
+ const cacheKey = `${svgElement.svgId}-${svgElement.color || "#FFFFFF"}`;
+ let svgImage = svgImageCache.get(cacheKey);
+
+ if (!svgImage || svgImage.src !== svgDataUrl) {
+ svgImage = new Image();
+ svgImageCache.set(cacheKey, svgImage);
+ svgImage.src = svgDataUrl;
+ await new Promise<void>((resolve) => {
+ if (svgImage!.complete) resolve();
+ else {
+ svgImage!.onload = () => resolve();
+ svgImage!.onerror = () => resolve();
+ }
+ });
+ } else if (!svgImage.complete) {
+ await new Promise<void>((resolve) => {
+ svgImage!.onload = () => resolve();
+ svgImage!.onerror = () => resolve();
+ setTimeout(resolve, 500);
+ });
+ }
+
+ ctx.save();
+ const elemX = (svgElement.x / 100) * canvasWidth;
+ const elemY = (svgElement.y / 100) * canvasHeight;
+ const elemWidth = (svgElement.width / 100) * referenceSize;
+ const elemHeight = (svgElement.height / 100) * referenceSize;
+
+ ctx.translate(elemX, elemY);
+ ctx.rotate((svgElement.rotation * Math.PI) / 180);
+ ctx.globalAlpha = svgElement.opacity;
+ ctx.drawImage(
+ svgImage,
+ -elemWidth / 2,
+ -elemHeight / 2,
+ elemWidth,
+ elemHeight
+ );
+ ctx.restore();
+ } else if (element.type === "image") {
+ const img = elementImageCache.get(element.imagePath);
+ if (!img) continue;
+
+ ctx.save();
+ const elemX = (element.x / 100) * canvasWidth;
+ const elemY = (element.y / 100) * canvasHeight;
+
+ const elemWidth = (element.width / 100) * referenceSize;
+ const elemHeight = (element.height / 100) * referenceSize;
+
+ const imgAspectRatio = img.naturalWidth / img.naturalHeight;
+ let finalWidth = elemWidth;
+ let finalHeight = elemHeight;
+
+ const elementAspectRatio = elemWidth / elemHeight;
+ if (imgAspectRatio > elementAspectRatio) {
+ finalHeight = elemWidth / imgAspectRatio;
+ } else {
+ finalWidth = elemHeight * imgAspectRatio;
+ }
+
+ ctx.translate(elemX, elemY);
+ ctx.rotate((element.rotation * Math.PI) / 180);
+ ctx.globalAlpha = element.opacity;
+ ctx.drawImage(
+ img,
+ -finalWidth / 2,
+ -finalHeight / 2,
+ finalWidth,
+ finalHeight
+ );
+ ctx.restore();
+ } else if (element.type === "text") {
+ ctx.save();
+ const elemX = (element.x / 100) * canvasWidth;
+ const elemY = (element.y / 100) * canvasHeight;
+ ctx.translate(elemX, elemY);
+ ctx.rotate((element.rotation * Math.PI) / 180);
+ ctx.globalAlpha = element.opacity;
+ const scaledFontSize = element.fontSize * (referenceSize / 1080);
+ const fontWeight = element.fontWeight === 'normal' ? '400' : element.fontWeight === 'medium' ? '500' : '700';
+ ctx.font = `${fontWeight} ${scaledFontSize}px ${element.fontFamily}`;
+ ctx.fillStyle = element.color;
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+ ctx.fillText(element.content, 0, 0);
+ ctx.restore();
+ }
+ }
+}
\ No newline at end of file
diff --git a/lib/masked-image-draw.utils.ts b/lib/masked-image-draw.utils.ts
new file mode 100644
index 0000000..53e9481
--- /dev/null
+++ b/lib/masked-image-draw.utils.ts
@@ -0,0 +1,41 @@
+import type { MutableRefObject } from "react";
+import { applyGradientMaskToRegion } from "@/lib/media-mask.utils";
+import type { ImageMaskConfigLike } from "@/lib/phone3d.utils";
+
+export function drawMaskedImage(
+ destCtx: CanvasRenderingContext2D,
+ img: CanvasImageSource,
+ x: number,
+ y: number,
+ w: number,
+ h: number,
+ maskConfig: ImageMaskConfigLike | null | undefined,
+ maskCompositeCanvasRef: MutableRefObject<HTMLCanvasElement | null>,
+): void {
+ if (!maskConfig?.enabled) {
+ destCtx.drawImage(img, x, y, w, h);
+ return;
+ }
+
+ const safeW = Math.max(1, Math.round(w));
+ const safeH = Math.max(1, Math.round(h));
+ let off = maskCompositeCanvasRef.current;
+ if (!off) {
+ off = document.createElement('canvas');
+ maskCompositeCanvasRef.current = off;
+ }
+ if (off.width !== safeW || off.height !== safeH) {
+ off.width = safeW;
+ off.height = safeH;
+ }
+ const offCtx = off.getContext('2d');
+ if (!offCtx) {
+ destCtx.drawImage(img, x, y, w, h);
+ return;
+ }
+ offCtx.setTransform(1, 0, 0, 1, 0, 0);
+ offCtx.clearRect(0, 0, safeW, safeH);
+ offCtx.drawImage(img, 0, 0, safeW, safeH);
+ applyGradientMaskToRegion(offCtx, 0, 0, safeW, safeH, maskConfig);
+ destCtx.drawImage(off, x, y, w, h);
+}
\ No newline at end of file
diff --git a/lib/mockup-media-draw.utils.ts b/lib/mockup-media-draw.utils.ts
new file mode 100644
index 0000000..3e5a034
--- /dev/null
+++ b/lib/mockup-media-draw.utils.ts
@@ -0,0 +1,177 @@
+import type { MutableRefObject } from "react";
+import type { VideoCanvasProps } from "@/types";
+import {
+ drawRoundedRect,
+ drawRoundedRectBottomOnly,
+} from "@/lib/canvas.utils";
+import { drawMockupToCanvas } from "@/lib/mockup-canvas.utils";
+import { DEFAULT_MOCKUP_CONFIG } from "@/types/mockup.types";
+import { BOTTOM_ONLY_RADIUS_MOCKUPS, SELF_SHADOWING_MOCKUPS } from "@/lib/constants";
+import { MockupMotionTransform } from "./mockup-motion";
+
+const DEG_TO_RAD = Math.PI / 180;
+
+export type ShadowCache = {
+ key: string;
+ canvas: HTMLCanvasElement;
+ offsetX: number;
+ offsetY: number;
+};
+
+export interface MockupDrawContext {
+ videoTransform: NonNullable<VideoCanvasProps["videoTransform"]>;
+ imageTransform: VideoCanvasProps["imageTransform"];
+ apply3DToBackground: boolean;
+ imageZoomScale: number;
+ shadows: VideoCanvasProps["shadows"];
+ mockupId: NonNullable<VideoCanvasProps["mockupId"]>;
+ mockupConfig: VideoCanvasProps["mockupConfig"];
+ mediaType: NonNullable<VideoCanvasProps["mediaType"]>;
+ cropArea: VideoCanvasProps["cropArea"];
+ sourceWidth: number;
+ sourceHeight: number;
+ canvasWidth: number;
+ canvasHeight: number;
+ scaledRadius: number;
+ scaledShadowBlur: number;
+ shadowCacheRef: MutableRefObject<ShadowCache | null>;
+ mockupMotion?: MockupMotionTransform;
+}
+
+function applyPseudo3DTilt(c: CanvasRenderingContext2D, rotateXDeg: number, rotateYDeg: number) {
+ if (rotateXDeg === 0 && rotateYDeg === 0) return;
+ const rotXR = rotateXDeg * DEG_TO_RAD;
+ const rotYR = rotateYDeg * DEG_TO_RAD;
+ const tanY = Math.tan(rotYR);
+ const tanX = Math.tan(rotXR);
+ const sX = 1 / Math.sqrt(1 + tanY * tanY);
+ const sY = 1 / Math.sqrt(1 + tanX * tanX);
+ c.transform(sX, tanX * sY, tanY * sX, sY, 0, 0);
+}
+
+export function drawMockupAndMedia(
+ c: CanvasRenderingContext2D,
+ containerX: number,
+ containerY: number,
+ containerWidth: number,
+ containerHeight: number,
+ source: HTMLVideoElement | HTMLImageElement,
+ applyImageXform: boolean,
+ is3DActive: boolean,
+ ctx2: MockupDrawContext,
+): void {
+ const {
+ videoTransform, imageTransform, apply3DToBackground, imageZoomScale,
+ shadows, mockupId, mockupConfig, mediaType, cropArea,
+ sourceWidth, sourceHeight, canvasWidth, canvasHeight,
+ scaledRadius, scaledShadowBlur, shadowCacheRef, mockupMotion
+ } = ctx2;
+
+ const vCX = containerX + containerWidth / 2;
+ const vCY = containerY + containerHeight / 2;
+ const txPx = (videoTransform.translateX / 100) * containerWidth;
+ const tyPx = (videoTransform.translateY / 100) * containerHeight;
+
+ c.save();
+ c.translate(vCX + txPx, vCY + tyPx);
+ c.rotate(videoTransform.rotation * DEG_TO_RAD);
+
+ if (mockupMotion) {
+ const mTxPx = (mockupMotion.translateXPct / 100) * containerWidth;
+ const mTyPx = (mockupMotion.translateYPct / 100) * containerHeight;
+ c.translate(mTxPx, mTyPx);
+ c.scale(mockupMotion.scale, mockupMotion.scale);
+ c.rotate(mockupMotion.rotateZ * DEG_TO_RAD);
+ if (!is3DActive) applyPseudo3DTilt(c, mockupMotion.rotateX, mockupMotion.rotateY);
+ }
+
+ if (applyImageXform && imageTransform && !apply3DToBackground) {
+ if (imageTransform.perspective && imageTransform.perspective > 0 && (imageTransform.rotateX !== 0 || imageTransform.rotateY !== 0)) {
+ const rotXR = imageTransform.rotateX * DEG_TO_RAD;
+ const rotYR = imageTransform.rotateY * DEG_TO_RAD;
+ const tanY2 = Math.tan(rotYR);
+ const tanX2 = Math.tan(rotXR);
+ const sX2 = 1 / Math.sqrt(1 + tanY2 * tanY2);
+ const sY2 = 1 / Math.sqrt(1 + tanX2 * tanX2);
+ c.transform(sX2, tanX2 * sY2, tanY2 * sX2, sY2, 0, 0);
+ }
+ c.rotate(imageTransform.rotateZ * DEG_TO_RAD);
+ c.scale(imageTransform.scale * imageZoomScale, imageTransform.scale * imageZoomScale);
+ const iTY = (imageTransform.translateY / 100) * containerHeight;
+ c.translate(0, iTY / (imageTransform.scale * imageZoomScale));
+ }
+ c.translate(-vCX, -vCY);
+ if (mockupMotion) c.globalAlpha *= mockupMotion.opacity; // ← nuevo
+
+ if (shadows > 0 && !SELF_SHADOWING_MOCKUPS.includes(mockupId)) {
+ const shadowKey = `${containerWidth.toFixed(1)}x${containerHeight.toFixed(1)}|${scaledRadius.toFixed(1)}|${scaledShadowBlur.toFixed(1)}`;
+ let cached = shadowCacheRef.current;
+ if (!cached || cached.key !== shadowKey) {
+ const margin = Math.ceil(scaledShadowBlur * 3 + scaledShadowBlur * 0.3 + 8);
+ const buf = document.createElement('canvas');
+ buf.width = Math.ceil(containerWidth) + margin * 2;
+ buf.height = Math.ceil(containerHeight) + margin * 2;
+ const bctx = buf.getContext('2d');
+ if (bctx) {
+ bctx.shadowColor = 'rgba(0, 0, 0, 1)';
+ bctx.shadowBlur = scaledShadowBlur;
+ bctx.shadowOffsetY = scaledShadowBlur * 0.3;
+ bctx.fillStyle = 'black';
+ drawRoundedRect(bctx, margin, margin, containerWidth, containerHeight, scaledRadius);
+ bctx.fill();
+ }
+ cached = { key: shadowKey, canvas: buf, offsetX: margin, offsetY: margin };
+ shadowCacheRef.current = cached;
+ }
+ c.save();
+ c.drawImage(cached.canvas, containerX - cached.offsetX, containerY - cached.offsetY);
+ c.restore();
+ }
+
+ const hasMockupLocal = mockupId && mockupId !== "none";
+ const mockupCfg = mockupConfig || DEFAULT_MOCKUP_CONFIG;
+ let vX = containerX, vY = containerY, vW = containerWidth, vH = containerHeight, vR = scaledRadius;
+
+ if (hasMockupLocal) {
+ const mBlur = SELF_SHADOWING_MOCKUPS.includes(mockupId) ? scaledShadowBlur : 0;
+ const mr = drawMockupToCanvas(c, mockupId, mockupCfg, containerX, containerY, containerWidth, containerHeight, scaledRadius, mBlur, canvasWidth, canvasHeight);
+ vX = mr.contentX; vY = mr.contentY; vW = mr.contentWidth; vH = mr.contentHeight;
+ vR = mockupId === "outline" ? scaledRadius * 1.6 : (mockupId === "iphone-slim" || mockupId === "glass-curve" || mockupId === "glass-full") ? scaledRadius * 2.5 : scaledRadius;
+ }
+
+ c.save();
+ const bottomOnly = hasMockupLocal && BOTTOM_ONLY_RADIUS_MOCKUPS.includes(mockupId);
+ if (vR > 0) {
+ if (bottomOnly) {
+ drawRoundedRectBottomOnly(c, vX, vY, vW, vH, vR);
+ } else {
+ drawRoundedRect(c, vX, vY, vW, vH, vR);
+ }
+ c.clip();
+ } else {
+ c.beginPath();
+ c.rect(vX, vY, vW, vH);
+ c.clip();
+ }
+
+ if (mediaType === "video") {
+ const baseFilter = is3DActive
+ ? 'saturate(125%) contrast(110%) brightness(105%)'
+ : 'saturate(130%) contrast(104%) brightness(103%)';
+ const motionBlur = mockupMotion && mockupMotion.blurPx > 0.4 ? ` blur(${mockupMotion.blurPx}px)` : '';
+ c.filter = baseFilter + motionBlur;
+ }
+
+ if (cropArea && (cropArea.width < 100 || cropArea.height < 100 || cropArea.x > 0 || cropArea.y > 0)) {
+ const sX = (cropArea.x / 100) * sourceWidth;
+ const sY = (cropArea.y / 100) * sourceHeight;
+ const cW2 = (cropArea.width / 100) * sourceWidth;
+ const cH2 = (cropArea.height / 100) * sourceHeight;
+ c.drawImage(source, sX, sY, cW2, cH2, vX, vY, vW, vH);
+ } else {
+ c.drawImage(source, vX, vY, vW, vH);
+ }
+
+ c.restore();
+ c.restore();
+}
\ No newline at end of file
diff --git a/lib/mockup-motion.ts b/lib/mockup-motion.ts
new file mode 100644
index 0000000..cf55dea
--- /dev/null
+++ b/lib/mockup-motion.ts
@@ -0,0 +1,865 @@
+export type MockupMotionPresetId =
+ | "none"
+ | "rise-settle"
+ | "flip-reveal"
+ | "focus-in"
+ | "cinematic-showcase"
+ | "isometric-lift"
+ | "panoramic-sweep"
+ | "macro-track"
+ | "depth-emerge"
+ | "dolly-vertigo"
+ | "rim-light-reveal"
+ | "surface-orbit"
+ | "low-dolly-reveal"
+ | "exit-fade-down"
+ | "exit-scale-blur"
+ | "z-spin-reveal";
+
+export const MOCKUP_MOTION_PRESETS: {
+ id: MockupMotionPresetId;
+ category: "Entrance" | "Continue" | "Exit";
+}[] = [
+ { id: "focus-in", category: "Entrance" },
+ { id: "rise-settle", category: "Entrance" },
+ { id: "flip-reveal", category: "Entrance" },
+ { id: "depth-emerge", category: "Entrance" },
+ { id: "z-spin-reveal", category: "Entrance" },
+ { id: "isometric-lift", category: "Entrance" },
+ { id: "cinematic-showcase", category: "Continue" },
+ { id: "panoramic-sweep", category: "Continue" },
+ { id: "macro-track", category: "Continue" },
+ { id: "rim-light-reveal", category: "Continue" },
+ { id: "surface-orbit", category: "Continue" },
+ { id: "low-dolly-reveal", category: "Continue" },
+ { id: "exit-fade-down", category: "Exit" },
+ { id: "exit-scale-blur", category: "Exit" },
+ ];
+
+export interface MockupMotionConfig {
+ presetId: MockupMotionPresetId;
+ intensity: number;
+ speed: number;
+}
+
+export const DEFAULT_MOCKUP_MOTION_CONFIG: MockupMotionConfig = {
+ presetId: "none",
+ intensity: 50,
+ speed: 50,
+};
+
+export interface MockupMotionTransform {
+ scale: number;
+ translateXPct: number;
+ translateYPct: number;
+ rotateX: number;
+ rotateY: number;
+ rotateZ: number;
+ opacity: number;
+ blurPx: number;
+ perspectivePx: number;
+}
+
+export const REST_MOCKUP_MOTION: MockupMotionTransform = {
+ scale: 1,
+ translateXPct: 0,
+ translateYPct: 0,
+ rotateX: 0,
+ rotateY: 0,
+ rotateZ: 0,
+ opacity: 1,
+ blurPx: 0,
+ perspectivePx: 0,
+};
+
+const clamp01 = (n: number) => Math.max(0, Math.min(1, n));
+const lerp = (a: number, b: number, t: number) => a + (b - a) * t;
+
+function easeOutCubic(t: number) {
+ return 1 - (1 - t) ** 3;
+}
+function easeOutBack(t: number) {
+ const c1 = 1.70158;
+ const c3 = c1 + 1;
+ return 1 + c3 * (t - 1) ** 3 + c1 * (t - 1) ** 2;
+}
+
+function easeInOutCubic(t: number) {
+ return t < 0.5 ? 4 * t ** 3 : 1 - (-2 * t + 2) ** 3 / 2;
+}
+
+function easeOutQuint(t: number) {
+ return 1 - (1 - t) ** 5;
+}
+
+function speedToDurationSec(speed: number): number {
+ return lerp(1.4, 0.35, clamp01(speed / 100));
+}
+
+export function sampleMockupMotion(
+ config: MockupMotionConfig,
+ currentTime: number,
+ clipDurationSec: number
+): MockupMotionTransform {
+ const { presetId, intensity, speed } = config;
+ const i = clamp01(intensity / 100);
+ if (presetId === "none" || clipDurationSec <= 0) return REST_MOCKUP_MOTION;
+
+ switch (presetId) {
+ case "rise-settle": {
+ const dur = Math.min(speedToDurationSec(speed), clipDurationSec);
+ const t = clamp01(currentTime / dur);
+ const eased = easeOutBack(t);
+ const riseDistance = lerp(8, 28, i);
+ return {
+ ...REST_MOCKUP_MOTION,
+ translateYPct: lerp(riseDistance, 0, eased),
+ opacity: lerp(0, 1, easeOutCubic(clamp01(t * 1.6))),
+ };
+ }
+ case "flip-reveal": {
+ const dur = Math.min(speedToDurationSec(speed) * 1.2, clipDurationSec);
+ const t = clamp01(currentTime / dur);
+ const eased = easeOutCubic(t);
+ const startAngle = lerp(35, 65, i);
+ return {
+ ...REST_MOCKUP_MOTION,
+ rotateY: lerp(-startAngle, 0, eased),
+ opacity: lerp(0.2, 1, easeOutCubic(clamp01(t * 1.8))),
+ perspectivePx: 900,
+ };
+ }
+ case "focus-in": {
+ const dur = Math.min(speedToDurationSec(speed), clipDurationSec);
+ const t = clamp01(currentTime / dur);
+ const eased = easeOutCubic(t);
+ const startBlur = lerp(6, 22, i);
+ return {
+ ...REST_MOCKUP_MOTION,
+ scale: lerp(1.06, 1, eased),
+ blurPx: lerp(startBlur, 0, eased),
+ opacity: lerp(0.3, 1, easeOutCubic(clamp01(t * 2))),
+ };
+ }
+
+ case "z-spin-reveal": {
+ const speedT = clamp01(speed / 100);
+ const animationEnd = lerp(0.95, 0.85, speedT);
+ const p = clamp01(currentTime / clipDurationSec);
+
+ const xRot0 = lerp(45, 60, i);
+ const yRot0 = lerp(10, 20, i);
+ const zRot0 = lerp(-85, -95, i);
+ const zoomStart = lerp(0.7, 0.8, i);
+
+ let scale = 1, tiltX = 0, tiltY = 0, tiltZ = 0;
+
+ if (p <= animationEnd) {
+ const lp = easeInOutCubic(clamp01(p / animationEnd));
+
+ scale = lerp(zoomStart, 1, lp);
+ tiltX = lerp(xRot0, 0, lp);
+ tiltY = lerp(yRot0, 0, lp);
+ tiltZ = lerp(zRot0, 0, lp);
+ } else {
+ scale = 1;
+ tiltX = 0;
+ tiltY = 0;
+ tiltZ = 0;
+ }
+
+ const tiltRatio = clamp01(Math.abs(tiltX) / (xRot0 || 1));
+ const perspective = lerp(2000, 1000, tiltRatio);
+
+ return {
+ ...REST_MOCKUP_MOTION,
+ scale,
+ translateXPct: 0,
+ translateYPct: 0,
+ rotateX: tiltX,
+ rotateY: tiltY,
+ rotateZ: tiltZ,
+ perspectivePx: perspective,
+ };
+ }
+ case "cinematic-showcase": {
+ const speedT = clamp01(speed / 100);
+ const impactEnd = lerp(0.12, 0.05, speedT);
+ const panEnd = lerp(0.68, 0.55, speedT);
+ const p = clamp01(currentTime / clipDurationSec);
+ const zoomStart = lerp(1.5, 2.4, i);
+ const zoomPan = lerp(1.15, 1.35, i);
+ const tiltX0 = lerp(2, 6, i);
+ const tiltY0 = lerp(4, 10, i);
+ const anchorX0 = lerp(0.25, 0.4, i);
+ const anchorY0 = lerp(0.20, 0.35, i);
+ const anchorX1 = lerp(0.05, 0.15, i);
+ const anchorY1 = lerp(0.04, 0.12, i);
+ let scale: number, anchorX: number, anchorY: number, tiltX: number, tiltY: number;
+ let blur = 0;
+
+ if (p <= impactEnd) {
+ const lp = easeOutCubic(clamp01(p / Math.max(impactEnd, 0.0001)));
+ scale = lerp(zoomStart * 1.04, zoomStart, lp);
+ anchorX = anchorX0;
+ anchorY = anchorY0;
+ tiltX = lerp(tiltX0 * 1.1, tiltX0, lp);
+ tiltY = lerp(tiltY0 * 1.1, tiltY0, lp);
+
+
+ } else if (p <= panEnd) {
+ const lp = easeInOutCubic(clamp01((p - impactEnd) / (panEnd - impactEnd)));
+ scale = lerp(zoomStart, zoomPan, lp);
+ anchorX = lerp(anchorX0, anchorX1, lp);
+ anchorY = lerp(anchorY0, anchorY1, lp);
+ tiltX = lerp(tiltX0, tiltX0 * 0.4, lp);
+ tiltY = lerp(tiltY0, tiltY0 * 0.4, lp);
+
+ blur = Math.sin(Math.PI * lp) * lerp(1.5, 4, i);
+
+ } else {
+ const lp = easeOutQuint(clamp01((p - panEnd) / (1 - panEnd)));
+ scale = lerp(zoomPan, 1, lp);
+ anchorX = lerp(anchorX1, 0, lp);
+ anchorY = lerp(anchorY1, 0, lp);
+ tiltX = lerp(tiltX0 * 0.4, 0, lp);
+ tiltY = lerp(tiltY0 * 0.4, 0, lp);
+
+ blur = 0;
+ }
+
+ const translateXPct = scale * anchorX * 100;
+ const translateYPct = scale * anchorY * 100;
+
+ const tiltRatio = clamp01((Math.abs(tiltX) + Math.abs(tiltY)) / (tiltX0 + tiltY0 || 1));
+ const perspective = lerp(2500, 1500, tiltRatio);
+
+ return {
+ ...REST_MOCKUP_MOTION,
+ scale,
+ translateXPct,
+ translateYPct,
+ rotateX: tiltX,
+ rotateY: tiltY,
+ blurPx: blur,
+ perspectivePx: perspective,
+ };
+ }
+
+ case "depth-emerge": {
+ const dur = Math.min(speedToDurationSec(speed) * 1.3, clipDurationSec);
+ const t = clamp01(currentTime / dur);
+ const emergeEnd = 0.45;
+ const blurFadeEnd = 0.55;
+
+ const startScale = lerp(0.35, 0.15, i);
+ const startBlur = lerp(12, 28, i);
+ const startRotateX = lerp(25, 55, i);
+ const startRotateY = lerp(-20, -45, i);
+ const startOpacity = 0;
+
+ let scale: number, blur: number, rotX: number, rotY: number, opacity: number;
+
+ if (t <= emergeEnd) {
+ const lp = easeOutCubic(clamp01(t / emergeEnd));
+ scale = lerp(startScale, 1.08, lp);
+ blur = lerp(startBlur, 0, easeOutCubic(clamp01(t / blurFadeEnd)));
+ rotX = lerp(startRotateX, 8, lp);
+ rotY = lerp(startRotateY, -8, lp);
+ opacity = lerp(startOpacity, 1, easeOutCubic(clamp01(t * 2.2)));
+ } else {
+ const lp = easeOutBack(clamp01((t - emergeEnd) / (1 - emergeEnd)));
+ scale = lerp(1.08, 1, lp);
+ blur = 0;
+ rotX = lerp(8, 0, lp);
+ rotY = lerp(-8, 0, lp);
+ opacity = 1;
+ }
+
+ const tiltRatio = clamp01((Math.abs(rotX) + Math.abs(rotY)) / (startRotateX + Math.abs(startRotateY) || 1));
+ const perspective = lerp(1800, 900, tiltRatio);
+
+ return {
+ ...REST_MOCKUP_MOTION,
+ scale,
+ rotateX: rotX,
+ rotateY: rotY,
+ blurPx: blur,
+ opacity,
+ perspectivePx: perspective,
+ };
+ }
+
+ case "dolly-vertigo": {
+ const speedT = clamp01(speed / 100);
+ const dollyEnd = lerp(0.72, 0.58, speedT);
+ const p = clamp01(currentTime / clipDurationSec);
+ const zoomStart = lerp(2.8, 4.0, i);
+ const zoomDolly = lerp(0.85, 0.65, i);
+ const zPush = lerp(120, 220, i);
+ const tiltX0 = lerp(4, 10, i);
+ const tiltY0 = lerp(-8, -18, i);
+ const rollZ0 = lerp(-3, -8, i);
+ const anchorX0 = lerp(0.2, 0.35, i);
+ const anchorY0 = lerp(0.15, 0.3, i);
+ let scale: number, anchorX: number, anchorY: number;
+ let tiltX: number, tiltY: number, tiltZ: number;
+ let blur = 0;
+
+ if (p <= dollyEnd) {
+ const lp = easeInOutCubic(clamp01(p / dollyEnd));
+
+ scale = lerp(zoomStart, zoomDolly, lp);
+ anchorX = lerp(anchorX0, 0, lp);
+ anchorY = lerp(anchorY0, 0, lp);
+ tiltX = lerp(tiltX0, tiltX0 * 0.3, lp);
+ tiltY = lerp(tiltY0, tiltY0 * 0.2, lp);
+ tiltZ = lerp(rollZ0, rollZ0 * 0.3, lp);
+
+ const motionPeak = Math.sin(Math.PI * lp);
+ blur = motionPeak * lerp(1.5, 4, i);
+ } else {
+ const lp = easeOutQuint(clamp01((p - dollyEnd) / (1 - dollyEnd)));
+ scale = lerp(zoomDolly, 1, lp);
+ anchorX = 0;
+ anchorY = 0;
+ tiltX = lerp(tiltX0 * 0.3, 0, lp);
+ tiltY = lerp(tiltY0 * 0.2, 0, lp);
+ tiltZ = lerp(rollZ0 * 0.3, 0, lp);
+ blur = 0;
+ }
+
+ const translateYPct = lerp(zPush * 0.05, 0, easeOutCubic(p));
+ const translateXPct = scale * anchorX * 100;
+ const finalTranslateYPct = scale * anchorY * 100 + translateYPct;
+ const tiltRatio = clamp01((Math.abs(tiltX) + Math.abs(tiltY)) / (tiltX0 + Math.abs(tiltY0) || 1));
+ const perspective = lerp(3000, 1400, tiltRatio);
+
+ return {
+ ...REST_MOCKUP_MOTION,
+ scale,
+ translateXPct,
+ translateYPct: finalTranslateYPct,
+ rotateX: tiltX,
+ rotateY: tiltY,
+ rotateZ: tiltZ,
+ blurPx: blur,
+ perspectivePx: perspective,
+ };
+ }
+
+ case "rim-light-reveal": {
+ const speedT = clamp01(speed / 100);
+ const darknessEnd = lerp(0.22, 0.15, speedT);
+ const flashEnd = lerp(0.55, 0.42, speedT);
+ const p = clamp01(currentTime / clipDurationSec);
+ const zoomDark = lerp(3.5, 5.0, i);
+ const xRotDark = lerp(60, 85, i);
+ const yRotDark = lerp(40, 65, i);
+ const zRotDark = lerp(-15, -30, i);
+ const anchorXDark = lerp(0.2, 0.35, i);
+ const anchorYDark = lerp(0.15, 0.3, i);
+ const zoomFlash = lerp(1.4, 1.8, i);
+ const xRotFlash = lerp(15, 25, i);
+ const yRotFlash = lerp(10, 18, i);
+ const zRotFlash = lerp(-4, -8, i);
+
+ let scale: number, anchorX: number, anchorY: number;
+ let tiltX: number, tiltY: number, tiltZ: number;
+ let blur = 0;
+ let opacity = 1;
+
+ if (p <= darknessEnd) {
+
+ const lp = easeOutCubic(clamp01(p / Math.max(darknessEnd, 0.0001)));
+ scale = lerp(zoomDark * 1.05, zoomDark, lp);
+ anchorX = anchorXDark;
+ anchorY = anchorYDark;
+ tiltX = xRotDark;
+ tiltY = yRotDark;
+ tiltZ = zRotDark;
+ blur = lerp(10, 18, i);
+ opacity = lerp(0.15, 0.35, lp);
+ } else if (p <= flashEnd) {
+
+ const segment = flashEnd - darknessEnd;
+ const lp = clamp01((p - darknessEnd) / Math.max(segment, 0.0001));
+ const motionLinearProgress = easeOutQuint(lp);
+ scale = lerp(zoomDark, zoomFlash, motionLinearProgress);
+ anchorX = lerp(anchorXDark, 0, motionLinearProgress);
+ anchorY = lerp(anchorYDark, 0, motionLinearProgress);
+ tiltX = lerp(xRotDark, xRotFlash, motionLinearProgress);
+ tiltY = lerp(yRotDark, yRotFlash, motionLinearProgress);
+ tiltZ = lerp(zRotDark, zRotFlash, motionLinearProgress);
+ blur = lerp(lerp(10, 18, i), 0, motionLinearProgress);
+
+ opacity = lp < 0.2
+ ? lerp(0.35, 1.08, easeOutCubic(lp / 0.2))
+ : lerp(1.08, 1, easeOutCubic(clamp01((lp - 0.2) / 0.8)));
+ } else {
+
+ const lp = easeOutQuint(clamp01((p - flashEnd) / (1 - flashEnd)));
+ scale = lerp(zoomFlash, 1, lp);
+ anchorX = 0;
+ anchorY = 0;
+ tiltX = lerp(xRotFlash, 0, lp);
+ tiltY = lerp(yRotFlash, 0, lp);
+ tiltZ = lerp(zRotFlash, 0, lp);
+ blur = 0;
+ opacity = 1;
+ }
+
+ const translateXPct = scale * anchorX * 100;
+ const translateYPct = scale * anchorY * 100;
+ const tiltRatio = clamp01((Math.abs(tiltX) + Math.abs(tiltY)) / (xRotDark + yRotDark || 1));
+ const perspective = lerp(3200, 2000, tiltRatio);
+
+ return {
+ ...REST_MOCKUP_MOTION,
+ scale,
+ translateXPct,
+ translateYPct,
+ rotateX: tiltX,
+ rotateY: tiltY,
+ rotateZ: tiltZ,
+ blurPx: blur,
+ opacity,
+ perspectivePx: perspective,
+ };
+ }
+ case "isometric-lift": {
+ const speedT = clamp01(speed / 100);
+ const liftEnd = lerp(0.75, 0.6, speedT);
+ const p = clamp01(currentTime / clipDurationSec);
+ const xRot0 = lerp(35, 60, i);
+ const zRot0 = lerp(-15, -40, i);
+ const yRot0 = lerp(10, 25, i);
+ const zoomStart = lerp(1.1, 1.45, i);
+ let scale = 1, tiltX = 0, tiltY = 0, tiltZ = 0, translateYPct = 0;
+
+ if (p <= liftEnd) {
+ const lp = easeInOutCubic(clamp01(p / liftEnd));
+
+ scale = lerp(zoomStart, 1.05, lp);
+ tiltX = lerp(xRot0, xRot0 * 0.15, lp);
+ tiltY = lerp(yRot0, yRot0 * 0.15, lp);
+ tiltZ = lerp(zRot0, 0, lp);
+
+ translateYPct = lerp(lerp(0, 0, i), 0, lp);
+ } else {
+ const lp = easeOutQuint(clamp01((p - liftEnd) / (1 - liftEnd)));
+
+ scale = lerp(1.05, 1, lp);
+ tiltX = lerp(xRot0 * 0.15, 0, lp);
+ tiltY = lerp(yRot0 * 0.15, 0, lp);
+ tiltZ = 0;
+ translateYPct = 0;
+ }
+
+ const tiltRatio = clamp01(Math.abs(tiltX) / (xRot0 || 1));
+ const perspective = lerp(2000, 1100, tiltRatio);
+
+ return {
+ ...REST_MOCKUP_MOTION,
+ scale,
+ translateXPct: 0,
+ translateYPct,
+ rotateX: tiltX,
+ rotateY: tiltY,
+ rotateZ: tiltZ,
+ perspectivePx: perspective,
+ };
+ }
+
+ case "panoramic-sweep": {
+ const speedT = clamp01(speed / 100);
+ const sweepEnd = lerp(0.7, 0.55, speedT);
+ const p = clamp01(currentTime / clipDurationSec);
+ const zoomSweep = lerp(1.2, 1.6, i);
+ const tiltYStart = lerp(-35, -55, i);
+ const tiltYEnd = lerp(15, 25, i);
+ const tiltZRoll = lerp(-4, -12, i);
+ const anchorXStart = lerp(-0.35, -0.5, i);
+ const anchorXEnd = lerp(0.15, 0.25, i);
+ let scale = 1, anchorX = 0, tiltX = 0, tiltY = 0, tiltZ = 0, blur = 0;
+
+ if (p <= sweepEnd) {
+ const lp = easeInOutCubic(clamp01(p / sweepEnd));
+
+ const arc = Math.sin(Math.PI * lp);
+ scale = lerp(zoomSweep, zoomSweep * 0.92, arc);
+ anchorX = lerp(anchorXStart, anchorXEnd, lp);
+ tiltY = lerp(tiltYStart, tiltYEnd, lp);
+ tiltZ = lerp(tiltZRoll, -tiltZRoll * 0.4, lp);
+ tiltX = lerp(lerp(5, 12, i), lerp(2, 6, i), lp);
+ blur = arc * lerp(2, 6, i);
+
+ } else {
+ const lp = easeOutQuint(clamp01((p - sweepEnd) / (1 - sweepEnd)));
+
+ scale = lerp(zoomSweep * (1 - 0.08 * Math.sin(Math.PI)), 1, lp);
+ anchorX = lerp(anchorXEnd, 0, lp);
+ tiltY = lerp(tiltYEnd, 0, lp);
+ tiltZ = lerp(-tiltZRoll * 0.4, 0, lp);
+ tiltX = lerp(lerp(2, 6, i), 0, lp);
+ blur = 0;
+ }
+
+ const perspective = 2200;
+
+ return {
+ ...REST_MOCKUP_MOTION,
+ scale,
+ translateXPct: scale * anchorX * 100,
+ translateYPct: 0,
+ rotateX: tiltX,
+ rotateY: tiltY,
+ rotateZ: tiltZ,
+ blurPx: blur,
+ perspectivePx: perspective,
+ };
+ }
+
+ case "macro-track": {
+ const speedT = clamp01(speed / 100);
+ const trackEnd = lerp(0.75, 0.6, speedT);
+ const p = clamp01(currentTime / clipDurationSec);
+ const zoom0 = lerp(2.2, 3.2, i);
+ const xRot0 = lerp(45, 65, i);
+ const zRot0 = lerp(8, 22, i);
+ const anchorX0 = lerp(0.3, 0.45, i);
+ const anchorY0 = lerp(0.35, 0.48, i);
+ const anchorX1 = lerp(-0.05, -0.1, i);
+ const anchorY1 = lerp(-0.05, -0.1, i);
+ let scale = 1, anchorX = 0, anchorY = 0, tiltX = 0, tiltZ = 0;
+
+ if (p <= trackEnd) {
+ const lp = easeInOutCubic(clamp01(p / trackEnd));
+
+ scale = lerp(zoom0, zoom0 * 0.6, lp);
+ anchorX = lerp(anchorX0, anchorX1, lp);
+ anchorY = lerp(anchorY0, anchorY1, lp);
+ tiltX = lerp(xRot0, xRot0 * 0.3, lp);
+ tiltZ = lerp(zRot0, zRot0 * 0.2, lp);
+ } else {
+ const lp = easeOutQuint(clamp01((p - trackEnd) / (1 - trackEnd)));
+
+ scale = lerp(zoom0 * 0.6, 1, lp);
+ anchorX = lerp(anchorX1, 0, lp);
+ anchorY = lerp(anchorY1, 0, lp);
+ tiltX = lerp(xRot0 * 0.3, 0, lp);
+ tiltZ = lerp(zRot0 * 0.2, 0, lp);
+ }
+
+ const perspective = 2500;
+
+ return {
+ ...REST_MOCKUP_MOTION,
+ scale,
+ translateXPct: scale * anchorX * 100,
+ translateYPct: scale * anchorY * 100,
+ rotateX: tiltX,
+ rotateY: 0,
+ rotateZ: tiltZ,
+ blurPx: 0,
+ perspectivePx: perspective,
+ };
+ }
+
+ case "surface-orbit": {
+ const speedT = clamp01(speed / 100);
+ const orbitEnd = lerp(0.8, 0.65, speedT);
+ const p = clamp01(currentTime / clipDurationSec);
+ const xRot0 = lerp(50, 70, i);
+ const yRot0 = 0;
+ const zRot0 = 0;
+ const zoom0 = lerp(1.3, 1.65, i);
+ const anchorX0 = 0;
+ const anchorY0 = lerp(0.08, 0.18, i);
+ const xRotMid = lerp(20, 30, i);
+ const yRotMid = 0;
+ const zRotMid = 0;
+ const zoomMid = lerp(1.12, 1.38, i);
+ const anchorXMid = 0;
+ const anchorYMid = lerp(0.02, 0.05, i);
+
+ let scale: number, tiltX: number, tiltY: number, tiltZ: number;
+ let anchorX: number, anchorY: number;
+
+ if (p <= orbitEnd) {
+ const lp = easeInOutCubic(clamp01(p / orbitEnd));
+ const orbitT = easeInOutCubic(lp);
+
+ scale = lerp(zoom0, zoomMid, orbitT);
+ anchorX = lerp(anchorX0, anchorXMid, orbitT);
+ anchorY = lerp(anchorY0, anchorYMid, orbitT);
+ tiltX = lerp(xRot0, xRotMid, orbitT);
+ tiltY = lerp(yRot0, yRotMid, orbitT);
+ tiltZ = lerp(zRot0, zRotMid, orbitT);
+ } else {
+ const lp = easeOutQuint(clamp01((p - orbitEnd) / (1 - orbitEnd)));
+
+ scale = lerp(zoomMid, 1, lp);
+ anchorX = lerp(anchorXMid, 0, lp);
+ anchorY = lerp(anchorYMid, 0, lp);
+ tiltX = lerp(xRotMid, 0, lp);
+ tiltY = lerp(yRotMid, 0, lp);
+ tiltZ = lerp(zRotMid, 0, lp);
+ }
+
+ const translateXPct = scale * anchorX * 100;
+ const translateYPct = scale * anchorY * 100;
+ const tiltRatio = clamp01((Math.abs(tiltX) + Math.abs(tiltY)) / (xRot0 + yRot0 || 1));
+ const perspective = lerp(3000, 1800, tiltRatio);
+
+ return {
+ ...REST_MOCKUP_MOTION,
+ scale,
+ translateXPct,
+ translateYPct,
+ rotateX: tiltX,
+ rotateY: tiltY,
+ rotateZ: tiltZ,
+ blurPx: 0,
+ perspectivePx: perspective,
+ };
+ }
+
+ case "low-dolly-reveal": {
+ const speedT = clamp01(speed / 100);
+ const dollyEnd = lerp(0.76, 0.62, speedT);
+ const p = clamp01(currentTime / clipDurationSec);
+ const xRot0 = lerp(35, 48, i);
+ const yRot0 = lerp(-6, -12, i);
+ const zRot0 = lerp(2, 6, i);
+ const zoom0 = lerp(1.4, 1.8, i);
+ const anchorX0 = lerp(0.04, 0.1, i);
+ const anchorY0 = lerp(-0.1, -0.2, i);
+ const xRotMid = lerp(12, 18, i);
+ const yRotMid = lerp(-2, -5, i);
+ const zRotMid = lerp(1, 2, i);
+ const zoomMid = lerp(1.08, 1.2, i);
+ const anchorXMid = lerp(0.01, 0.03, i);
+ const anchorYMid = lerp(-0.02, -0.04, i);
+
+ let scale: number, tiltX: number, tiltY: number, tiltZ: number;
+ let anchorX: number, anchorY: number;
+
+ if (p <= dollyEnd) {
+ const lp = clamp01(p / dollyEnd);
+ const dollyT = easeInOutCubic(lp);
+ scale = lerp(zoom0, zoomMid, dollyT);
+ anchorX = lerp(anchorX0, anchorXMid, dollyT);
+ anchorY = lerp(anchorY0, anchorYMid, dollyT);
+ tiltX = lerp(xRot0, xRotMid, dollyT);
+ tiltY = lerp(yRot0, yRotMid, dollyT);
+ tiltZ = lerp(zRot0, zRotMid, dollyT);
+ } else {
+ const lp = easeOutQuint(clamp01((p - dollyEnd) / (1 - dollyEnd)));
+
+ scale = lerp(zoomMid, 1, lp);
+ anchorX = lerp(anchorXMid, 0, lp);
+ anchorY = lerp(anchorYMid, 0, lp);
+ tiltX = lerp(xRotMid, 0, lp);
+ tiltY = lerp(yRotMid, 0, lp);
+ tiltZ = lerp(zRotMid, 0, lp);
+ }
+
+ const translateXPct = scale * anchorX * 100;
+ const translateYPct = scale * anchorY * 100;
+ const tiltRatio = clamp01((Math.abs(tiltX) + Math.abs(tiltY)) / (xRot0 + Math.abs(yRot0) || 1));
+ const perspective = lerp(2800, 1800, tiltRatio);
+
+ return {
+ ...REST_MOCKUP_MOTION,
+ scale,
+ translateXPct,
+ translateYPct,
+ rotateX: tiltX,
+ rotateY: tiltY,
+ rotateZ: tiltZ,
+ blurPx: 0,
+ perspectivePx: perspective,
+ };
+ }
+
+ case "exit-fade-down": {
+ const dur = Math.min(speedToDurationSec(speed), clipDurationSec);
+ const startAt = Math.max(0, clipDurationSec - dur);
+ const t = clamp01((currentTime - startAt) / dur);
+ const eased = easeOutCubic(t);
+ const distance = lerp(6, 24, i);
+ return {
+ ...REST_MOCKUP_MOTION,
+ translateYPct: lerp(0, distance, eased),
+ opacity: lerp(1, 0, eased),
+ };
+ }
+ case "exit-scale-blur": {
+ const dur = Math.min(speedToDurationSec(speed), clipDurationSec);
+ const startAt = Math.max(0, clipDurationSec - dur);
+ const t = clamp01((currentTime - startAt) / dur);
+ const eased = easeOutCubic(t);
+ return {
+ ...REST_MOCKUP_MOTION,
+ scale: lerp(1, lerp(1.02, 1.25, i), eased),
+ blurPx: lerp(0, lerp(4, 16, i), eased),
+ opacity: lerp(1, 0, eased),
+ };
+ }
+ default:
+ return REST_MOCKUP_MOTION;
+ }
+}
+
+const ENTRANCE_EXIT_PADDING = 1.4;
+const DEFAULT_CONTINUOUS_DURATION = 3;
+
+export function getDefaultFragmentDuration(
+ presetId: MockupMotionPresetId,
+ speed: number
+): number {
+
+ if (
+ presetId === "cinematic-showcase" ||
+ presetId === "isometric-lift" ||
+ presetId === "panoramic-sweep" ||
+ presetId === "macro-track" ||
+ presetId === "dolly-vertigo" ||
+ presetId === "rim-light-reveal" ||
+ presetId === "surface-orbit" ||
+ presetId === "low-dolly-reveal" ||
+ presetId === "z-spin-reveal"
+
+ ) {
+ return lerp(7, 4.5, clamp01(speed / 100));
+ }
+
+ const category = getMotionPresetCategory(presetId);
+ if (category === "Entrance" || category === "Exit") {
+ return speedToDurationSec(speed) * ENTRANCE_EXIT_PADDING;
+ }
+ return DEFAULT_CONTINUOUS_DURATION;
+}
+
+export function buildMockupMotionCss(m: MockupMotionTransform): string {
+ return [
+ `translate(${m.translateXPct}%, ${m.translateYPct}%)`,
+ `scale(${m.scale})`,
+ m.rotateX !== 0 ? `rotateX(${m.rotateX}deg)` : "",
+ m.rotateY !== 0 ? `rotateY(${m.rotateY}deg)` : "",
+ m.rotateZ !== 0 ? `rotateZ(${m.rotateZ}deg)` : "",
+ ]
+ .filter(Boolean)
+ .join(" ");
+}
+
+export interface MockupMotionFragment extends MockupMotionConfig {
+ id: string;
+ startTime: number;
+ endTime: number;
+}
+
+export function getMotionPresetCategory(
+ id: MockupMotionPresetId
+): (typeof MOCKUP_MOTION_PRESETS)[number]["category"] {
+ return MOCKUP_MOTION_PRESETS.find((p) => p.id === id)?.category ?? "Continue";
+}
+
+export function sampleFragmentMotion(
+ fragment: MockupMotionFragment,
+ currentTime: number
+): MockupMotionTransform {
+ if (currentTime < fragment.startTime || currentTime > fragment.endTime) {
+ return REST_MOCKUP_MOTION;
+ }
+ const localTime = currentTime - fragment.startTime;
+ const localDuration = fragment.endTime - fragment.startTime;
+ return sampleMockupMotion(
+ { presetId: fragment.presetId, intensity: fragment.intensity, speed: fragment.speed },
+ localTime,
+ localDuration
+ );
+}
+
+export function sampleCombinedMockupMotion(
+ fragments: MockupMotionFragment[],
+ currentTime: number
+): MockupMotionTransform {
+ const active = fragments.filter(
+ (f) => currentTime >= f.startTime && currentTime <= f.endTime
+ );
+ if (active.length === 0) return REST_MOCKUP_MOTION;
+
+ return active.reduce<MockupMotionTransform>(
+ (acc, fragment) => {
+ const t = sampleFragmentMotion(fragment, currentTime);
+ return {
+ scale: acc.scale * t.scale,
+ translateXPct: acc.translateXPct + t.translateXPct,
+ translateYPct: acc.translateYPct + t.translateYPct,
+ rotateX: acc.rotateX + t.rotateX,
+ rotateY: acc.rotateY + t.rotateY,
+ rotateZ: acc.rotateZ + t.rotateZ,
+ opacity: acc.opacity * t.opacity,
+ blurPx: Math.max(acc.blurPx, t.blurPx),
+ perspectivePx: Math.max(acc.perspectivePx, t.perspectivePx),
+ };
+ },
+ { ...REST_MOCKUP_MOTION }
+ );
+}
+
+export function findValidMotionPlacement(
+ presetId: MockupMotionPresetId,
+ speed: number,
+ hintTime: number,
+ existingFragments: MockupMotionFragment[],
+ clipDurationSec: number
+): { startTime: number; endTime: number } | null {
+ const duration = Math.min(getDefaultFragmentDuration(presetId, speed), clipDurationSec);
+ if (duration <= 0 || clipDurationSec <= 0) return null;
+
+ const category = getMotionPresetCategory(presetId);
+ const sorted = [...existingFragments].sort((a, b) => a.startTime - b.startTime);
+
+ const overlaps = (start: number, end: number) =>
+ sorted.some((f) => start < f.endTime && end > f.startTime);
+
+ const tryPlace = (start: number) => {
+ const end = start + duration;
+ if (start < 0 || end > clipDurationSec) return null;
+ return overlaps(start, end) ? null : { startTime: start, endTime: end };
+ };
+
+ const preferredStart =
+ category === "Entrance"
+ ? 0
+ : category === "Exit"
+ ? Math.max(0, clipDurationSec - duration)
+ : Math.max(0, Math.min(hintTime - duration / 2, clipDurationSec - duration));
+
+ const direct = tryPlace(preferredStart);
+ if (direct) return direct;
+
+ const gaps: { start: number; end: number }[] = [];
+ let cursor = 0;
+ for (const f of sorted) {
+ if (f.startTime > cursor) gaps.push({ start: cursor, end: f.startTime });
+ cursor = Math.max(cursor, f.endTime);
+ }
+ if (cursor < clipDurationSec) gaps.push({ start: cursor, end: clipDurationSec });
+
+ const fitting = gaps.filter((g) => g.end - g.start >= duration);
+ if (fitting.length === 0) return null;
+
+ fitting.sort((a, b) => {
+ const da = Math.min(Math.abs(a.start - preferredStart), Math.abs(a.end - duration - preferredStart));
+ const db = Math.min(Math.abs(b.start - preferredStart), Math.abs(b.end - duration - preferredStart));
+ return da - db;
+ });
+
+ const gap = fitting[0];
+ const start = Math.max(gap.start, Math.min(preferredStart, gap.end - duration));
+ return { startTime: start, endTime: start + duration };
+}
\ No newline at end of file
diff --git a/lib/phone3d-composite-draw.utils.ts b/lib/phone3d-composite-draw.utils.ts
new file mode 100644
index 0000000..7685f51
--- /dev/null
+++ b/lib/phone3d-composite-draw.utils.ts
@@ -0,0 +1,109 @@
+import type { MutableRefObject } from "react";
+import { drawMaskedImage } from "@/lib/masked-image-draw.utils";
+import { PHONE_H, PHONE_W, DEVICE_3D_DIMENSIONS, type ImageMaskConfigLike } from "@/lib/phone3d.utils";
+
+export interface Phone3DApi {
+ renderAt: (w: number, h: number) => void;
+ restorePreview: () => void;
+ hasBuiltInShadow?: boolean;
+ getVisualSize?: () => { width: number; height: number; offsetY?: number } | null;
+}
+
+export interface Phone3DCompositeContext {
+ imagePhoneCanvasRef: MutableRefObject<HTMLCanvasElement | null>;
+ imagePhoneApiRef: MutableRefObject<Phone3DApi | null>;
+ canvasDimensions: { width: number; height: number } | null;
+ imagePhoneDevice: string;
+ imagePhoneScale: number;
+ imagePhoneX: number;
+ imagePhoneY: number;
+ imagePhoneShadow: number;
+ imagePhoneShadowColor: string;
+ effectivePhoneMaskConfig: ImageMaskConfigLike | null | undefined;
+ maskCompositeCanvasRef: MutableRefObject<HTMLCanvasElement | null>;
+}
+
+export function drawPhone3DCompositeWithZoom(
+ c: CanvasRenderingContext2D,
+ canvasWidth: number,
+ canvasHeight: number,
+ _frameTime: number,
+ zs: { scale: number; focusX: number; focusY: number },
+ highQuality: boolean,
+ pivotX: number,
+ pivotY: number,
+ ctx2: Phone3DCompositeContext,
+): void {
+ const {
+ imagePhoneCanvasRef, imagePhoneApiRef, canvasDimensions, imagePhoneDevice,
+ imagePhoneScale, imagePhoneX, imagePhoneY, imagePhoneShadow, imagePhoneShadowColor,
+ effectivePhoneMaskConfig, maskCompositeCanvasRef,
+ } = ctx2;
+
+ const phoneGL = imagePhoneCanvasRef.current!;
+ const domW = canvasDimensions?.width ?? canvasWidth;
+ const pxScale = canvasWidth / domW;
+ const zScale = zs.scale;
+ const centerX = canvasWidth / 2;
+ const centerY = canvasHeight / 2;
+ const measuredDims = imagePhoneApiRef.current?.getVisualSize?.();
+ const deviceDims = measuredDims ?? DEVICE_3D_DIMENSIONS[imagePhoneDevice] ?? { width: PHONE_W, height: PHONE_H };
+ const visualOffsetY = (measuredDims?.offsetY ?? 0) * imagePhoneScale * pxScale;
+ const baseCx = centerX + imagePhoneX * pxScale;
+ const baseCy = centerY + imagePhoneY * pxScale + visualOffsetY;
+ const baseW = deviceDims.width * imagePhoneScale * pxScale;
+ const baseH = deviceDims.height * imagePhoneScale * pxScale;
+
+ if (highQuality) {
+ imagePhoneApiRef.current?.renderAt(baseW, baseH);
+ }
+
+ c.save();
+ if (zScale !== 1) {
+ c.translate(pivotX, pivotY);
+ c.scale(zScale, zScale);
+ c.translate(-pivotX, -pivotY);
+ }
+
+ const hasBuiltInShadow = imagePhoneApiRef.current?.hasBuiltInShadow ?? false;
+ if (imagePhoneShadow > 0.01 && !hasBuiltInShadow) {
+ const sT = imagePhoneShadow * imagePhoneShadow;
+ const sBlur = sT * 60;
+ const sOpacity = sT * 0.7;
+ c.save();
+ c.globalAlpha = sOpacity;
+ c.filter = `blur(${Math.max(2, sBlur * 0.6) * pxScale}px)`;
+ c.beginPath();
+ c.ellipse(
+ baseCx,
+ baseCy + baseH / 2 + sBlur * 0.2 * pxScale,
+ baseW * (0.6 - sT * 0.1) / 2,
+ Math.max(4, sBlur * 0.55) * pxScale / 2,
+ 0, 0, Math.PI * 2
+ );
+ c.fillStyle = imagePhoneShadowColor;
+ c.fill();
+ c.restore();
+ }
+
+ if (imagePhoneShadow > 0.01) {
+ c.shadowColor = imagePhoneShadowColor;
+ c.shadowBlur = 28 * imagePhoneShadow * pxScale;
+ c.shadowOffsetX = 0;
+ c.shadowOffsetY = 18 * imagePhoneShadow * pxScale;
+ }
+
+ drawMaskedImage(c, phoneGL, baseCx - baseW / 2, baseCy - baseH / 2, baseW, baseH, effectivePhoneMaskConfig, maskCompositeCanvasRef);
+
+ if (imagePhoneShadow > 0.01) {
+ c.shadowColor = "transparent";
+ c.shadowBlur = 0;
+ c.shadowOffsetY = 0;
+ }
+
+ c.restore();
+
+ if (highQuality) {
+ imagePhoneApiRef.current?.restorePreview();
+ }
+}
\ No newline at end of file
diff --git a/lib/video-cache-utils.ts b/lib/video-cache-utils.ts
index 48def90..649f67e 100644
--- a/lib/video-cache-utils.ts
+++ b/lib/video-cache-utils.ts
@@ -1,4 +1,5 @@
-import { getUploadedVideo } from "./video-upload-cache";
+import { getUploadedVideo, getVideoTrack } from "./video-upload-cache";
+import { getLibraryVideoCount } from "./videos-library";
async function hasRecordedVideo(): Promise<boolean> {
try {
@@ -43,13 +44,19 @@ async function hasRecordedVideo(): Promise<boolean> {
}
export async function hasAnyVideo(): Promise<boolean> {
- try {
- const uploadedVideo = await getUploadedVideo();
- if (uploadedVideo) return true;
+ try {
+ const track = await getVideoTrack();
+ if (track && track.length > 0) return true;
- return await hasRecordedVideo();
- } catch (error) {
- console.error("Error checking for any video:", error);
- return false;
- }
+ const uploadedVideo = await getUploadedVideo();
+ if (uploadedVideo) return true;
+
+ const libraryCount = await getLibraryVideoCount();
+ if (libraryCount > 0) return true;
+
+ return await hasRecordedVideo();
+ } catch (error) {
+ console.error("Error checking for any video:", error);
+ return false;
+ }
}
diff --git a/lib/video-upload-cache.ts b/lib/video-upload-cache.ts
index 4835dbb..bd39a4f 100644
--- a/lib/video-upload-cache.ts
+++ b/lib/video-upload-cache.ts
@@ -1,205 +1,251 @@
import { normalizeVideoFile } from "./video-conversion";
+import type { VideoTrackClip } from "@/types/video-track.types";
const DB_NAME = "openvid-uploaded-videos";
-const DB_VERSION = 1;
+const DB_VERSION = 2;
const STORE_NAME = "videos";
const SINGLE_VIDEO_KEY = "current-uploaded-video";
+const TRACK_STORE_NAME = "video-track";
+const TRACK_KEY = "current-video-track";
+
export interface CachedUploadedVideo {
- key: string;
- blob: Blob;
- fileName: string;
- fileSize: number;
- duration: number;
- width: number;
- height: number;
- aspectRatio: string;
- uploadedAt: number;
+ key: string;
+ blob: Blob;
+ fileName: string;
+ fileSize: number;
+ duration: number;
+ width: number;
+ height: number;
+ aspectRatio: string;
+ uploadedAt: number;
+}
+
+interface CachedVideoTrack {
+ key: string;
+ clips: VideoTrackClip[];
+ savedAt: number;
}
let dbInstance: IDBDatabase | null = null;
async function cleanupOldUploadCache(db: IDBDatabase): Promise<void> {
- const SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1000;
- const cutoff = Date.now() - SEVEN_DAYS_MS;
- return new Promise((resolve) => {
- try {
- const transaction = db.transaction(STORE_NAME, "readwrite");
- const store = transaction.objectStore(STORE_NAME);
- const getReq = store.get(SINGLE_VIDEO_KEY);
- getReq.onsuccess = () => {
- const record = getReq.result as CachedUploadedVideo | undefined;
- if (record && record.uploadedAt < cutoff) {
- store.delete(SINGLE_VIDEO_KEY);
- }
- };
- transaction.oncomplete = () => resolve();
- transaction.onerror = () => resolve();
- } catch { resolve(); }
- });
+ const SEVEN_DAYS_MS = 7 * 24 * 60 * 60 * 1000;
+ const cutoff = Date.now() - SEVEN_DAYS_MS;
+ return new Promise((resolve) => {
+ try {
+ const transaction = db.transaction(STORE_NAME, "readwrite");
+ const store = transaction.objectStore(STORE_NAME);
+ const getReq = store.get(SINGLE_VIDEO_KEY);
+ getReq.onsuccess = () => {
+ const record = getReq.result as CachedUploadedVideo | undefined;
+ if (record && record.uploadedAt < cutoff) {
+ store.delete(SINGLE_VIDEO_KEY);
+ }
+ };
+ transaction.oncomplete = () => resolve();
+ transaction.onerror = () => resolve();
+ } catch {
+ resolve();
+ }
+ });
}
async function openDB(): Promise<IDBDatabase> {
- if (dbInstance) return dbInstance;
-
- return new Promise((resolve, reject) => {
- const request = indexedDB.open(DB_NAME, DB_VERSION);
-
- request.onerror = () => reject(request.error);
- request.onsuccess = () => {
- dbInstance = request.result;
- cleanupOldUploadCache(dbInstance).catch(() => { });
- resolve(request.result);
- };
-
- request.onupgradeneeded = (event) => {
- const db = (event.target as IDBOpenDBRequest).result;
- if (!db.objectStoreNames.contains(STORE_NAME)) {
- const store = db.createObjectStore(STORE_NAME, { keyPath: "key" });
- store.createIndex("uploadedAt", "uploadedAt", { unique: false });
- }
- };
- });
+ if (dbInstance) return dbInstance;
+ return new Promise((resolve, reject) => {
+ const request = indexedDB.open(DB_NAME, DB_VERSION);
+ request.onerror = () => reject(request.error);
+ request.onsuccess = () => {
+ dbInstance = request.result;
+ cleanupOldUploadCache(dbInstance).catch(() => { });
+ resolve(request.result);
+ };
+ request.onupgradeneeded = (event) => {
+ const db = (event.target as IDBOpenDBRequest).result;
+ if (!db.objectStoreNames.contains(STORE_NAME)) {
+ const store = db.createObjectStore(STORE_NAME, { keyPath: "key" });
+ store.createIndex("uploadedAt", "uploadedAt", { unique: false });
+ }
+ if (!db.objectStoreNames.contains(TRACK_STORE_NAME)) {
+ db.createObjectStore(TRACK_STORE_NAME, { keyPath: "key" });
+ }
+ };
+ });
}
function calculateAspectRatio(width: number, height: number): string {
- if (!width || !height) return "auto";
- const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));
- const divisor = gcd(width, height);
- return `${width / divisor}/${height / divisor}`;
+ if (!width || !height) return "auto";
+ const gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));
+ const divisor = gcd(width, height);
+ return `${width / divisor}/${height / divisor}`;
}
async function getVideoMetadata(source: Blob): Promise<{
- duration: number;
- width: number;
- height: number;
- aspectRatio: string;
+ duration: number;
+ width: number;
+ height: number;
+ aspectRatio: string;
}> {
- return new Promise((resolve, reject) => {
- const video = document.createElement("video");
- video.preload = "metadata";
- const url = URL.createObjectURL(source);
-
- const cleanup = () => {
- video.removeAttribute("src");
- video.load();
- URL.revokeObjectURL(url);
- };
-
- video.onloadedmetadata = () => {
- const metadata = {
- duration: video.duration,
- width: video.videoWidth,
- height: video.videoHeight,
- aspectRatio: calculateAspectRatio(video.videoWidth, video.videoHeight),
- };
- cleanup();
- resolve(metadata);
- };
- video.onerror = () => {
- cleanup();
- reject(new Error("Failed to load video metadata"));
- };
- video.src = url;
- });
+ return new Promise((resolve, reject) => {
+ const video = document.createElement("video");
+ video.preload = "metadata";
+ const url = URL.createObjectURL(source);
+ const cleanup = () => {
+ video.removeAttribute("src");
+ video.load();
+ URL.revokeObjectURL(url);
+ };
+ video.onloadedmetadata = () => {
+ const metadata = {
+ duration: video.duration,
+ width: video.videoWidth,
+ height: video.videoHeight,
+ aspectRatio: calculateAspectRatio(video.videoWidth, video.videoHeight),
+ };
+ cleanup();
+ resolve(metadata);
+ };
+ video.onerror = () => {
+ cleanup();
+ reject(new Error("Failed to load video metadata"));
+ };
+ video.src = url;
+ });
}
export async function saveUploadedVideo(file: File): Promise<CachedUploadedVideo> {
- try {
- const db = await openDB();
-
- const { blob: normalizedBlob, wasConverted } = await normalizeVideoFile(file);
-
- const metadata = await getVideoMetadata(normalizedBlob);
-
- const fileName = wasConverted
- ? `${file.name.replace(/\.[^/.]+$/, "")}.mp4`
- : file.name;
-
- const data: CachedUploadedVideo = {
- key: SINGLE_VIDEO_KEY,
- blob: normalizedBlob,
- fileName,
- fileSize: normalizedBlob.size,
- duration: metadata.duration,
- width: metadata.width,
- height: metadata.height,
- aspectRatio: metadata.aspectRatio,
- uploadedAt: Date.now(),
- };
-
- return new Promise((resolve, reject) => {
- const transaction = db.transaction(STORE_NAME, "readwrite");
- const store = transaction.objectStore(STORE_NAME);
- const request = store.put(data);
- request.onerror = () => {
- reject(request.error);
- };
- request.onsuccess = () => resolve(data);
- });
- } catch (error) {
- throw error;
- }
+ try {
+ const db = await openDB();
+ const { blob: normalizedBlob, wasConverted } = await normalizeVideoFile(file);
+ const metadata = await getVideoMetadata(normalizedBlob);
+ const fileName = wasConverted ? `${file.name.replace(/\.[^/.]+$/, "")}.mp4` : file.name;
+ const data: CachedUploadedVideo = {
+ key: SINGLE_VIDEO_KEY,
+ blob: normalizedBlob,
+ fileName,
+ fileSize: normalizedBlob.size,
+ duration: metadata.duration,
+ width: metadata.width,
+ height: metadata.height,
+ aspectRatio: metadata.aspectRatio,
+ uploadedAt: Date.now(),
+ };
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction(STORE_NAME, "readwrite");
+ const store = transaction.objectStore(STORE_NAME);
+ const request = store.put(data);
+ request.onerror = () => { reject(request.error); };
+ request.onsuccess = () => resolve(data);
+ });
+ } catch (error) {
+ throw error;
+ }
}
export async function getUploadedVideo(): Promise<CachedUploadedVideo | null> {
- try {
- const db = await openDB();
-
- return new Promise((resolve, reject) => {
- const transaction = db.transaction(STORE_NAME, "readonly");
- const store = transaction.objectStore(STORE_NAME);
- const request = store.get(SINGLE_VIDEO_KEY);
-
- request.onerror = () => reject(request.error);
- request.onsuccess = () => {
- const result = request.result;
- resolve(result || null);
- };
- });
- } catch (error) {
- console.warn("Failed to get uploaded video:", error);
- return null;
- }
+ try {
+ const db = await openDB();
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction(STORE_NAME, "readonly");
+ const store = transaction.objectStore(STORE_NAME);
+ const request = store.get(SINGLE_VIDEO_KEY);
+ request.onerror = () => reject(request.error);
+ request.onsuccess = () => {
+ const result = request.result;
+ resolve(result || null);
+ };
+ });
+ } catch (error) {
+ console.warn("Failed to get uploaded video:", error);
+ return null;
+ }
}
export async function deleteUploadedVideo(): Promise<void> {
- try {
- const db = await openDB();
-
- return new Promise((resolve, reject) => {
- const transaction = db.transaction(STORE_NAME, "readwrite");
- const store = transaction.objectStore(STORE_NAME);
- const request = store.delete(SINGLE_VIDEO_KEY);
-
- request.onerror = () => reject(request.error);
- request.onsuccess = () => resolve();
- });
- } catch (error) {
- console.warn("Failed to delete uploaded video:", error);
- }
+ try {
+ const db = await openDB();
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction(STORE_NAME, "readwrite");
+ const store = transaction.objectStore(STORE_NAME);
+ const request = store.delete(SINGLE_VIDEO_KEY);
+ request.onerror = () => reject(request.error);
+ request.onsuccess = () => resolve();
+ });
+ } catch (error) {
+ console.warn("Failed to delete uploaded video:", error);
+ }
}
export async function hasUploadedVideo(): Promise<boolean> {
- const video = await getUploadedVideo();
- return video !== null;
+ const video = await getUploadedVideo();
+ return video !== null;
}
export async function getUploadedVideoInfo(): Promise<{
- fileName: string;
- fileSize: number;
- duration: number;
- aspectRatio: string;
- uploadedAt: number;
+ fileName: string;
+ fileSize: number;
+ duration: number;
+ aspectRatio: string;
+ uploadedAt: number;
} | null> {
- const video = await getUploadedVideo();
- if (!video) return null;
+ const video = await getUploadedVideo();
+ if (!video) return null;
+ return {
+ fileName: video.fileName,
+ fileSize: video.fileSize,
+ duration: video.duration,
+ aspectRatio: video.aspectRatio,
+ uploadedAt: video.uploadedAt,
+ };
+}
- return {
- fileName: video.fileName,
- fileSize: video.fileSize,
- duration: video.duration,
- aspectRatio: video.aspectRatio,
- uploadedAt: video.uploadedAt,
- };
+export async function saveVideoTrack(clips: VideoTrackClip[]): Promise<void> {
+ try {
+ const db = await openDB();
+ const data: CachedVideoTrack = { key: TRACK_KEY, clips, savedAt: Date.now() };
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction(TRACK_STORE_NAME, "readwrite");
+ const store = transaction.objectStore(TRACK_STORE_NAME);
+ const request = store.put(data);
+ request.onerror = () => reject(request.error);
+ request.onsuccess = () => resolve();
+ });
+ } catch (error) {
+ console.warn("Failed to save video track:", error);
+ }
+}
+
+export async function getVideoTrack(): Promise<VideoTrackClip[] | null> {
+ try {
+ const db = await openDB();
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction(TRACK_STORE_NAME, "readonly");
+ const store = transaction.objectStore(TRACK_STORE_NAME);
+ const request = store.get(TRACK_KEY);
+ request.onerror = () => reject(request.error);
+ request.onsuccess = () => {
+ const result = request.result as CachedVideoTrack | undefined;
+ resolve(result ? result.clips : null);
+ };
+ });
+ } catch (error) {
+ console.warn("Failed to get video track:", error);
+ return null;
+ }
}
+
+export async function clearVideoTrack(): Promise<void> {
+ try {
+ const db = await openDB();
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction(TRACK_STORE_NAME, "readwrite");
+ const store = transaction.objectStore(TRACK_STORE_NAME);
+ const request = store.delete(TRACK_KEY);
+ request.onerror = () => reject(request.error);
+ request.onsuccess = () => resolve();
+ });
+ } catch (error) {
+ console.warn("Failed to clear video track:", error);
+ }
+}
\ No newline at end of file