Skip to content

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

feat: Implement image and video caching with IndexedDB

CristianOlivera1e3e9883d19b0
diff --git a/hooks/useEditorMode.ts b/hooks/useEditorMode.ts
new file mode 100644
index 0000000..4ddc0bc
--- /dev/null
+++ b/hooks/useEditorMode.ts
@@ -0,0 +1,41 @@
+"use client";
+
+import { useCallback, useMemo } from "react";
+import { useSearchParams } from "next/navigation";
+import type { EditorMode, EditorModeConfig } from "@/types/editor-mode.types";
+import { getEditorModeConfig } from "@/types/editor-mode.types";
+
+interface UseEditorModeReturn {
+ mode: EditorMode;
+ config: EditorModeConfig;
+ isVideoMode: boolean;
+ isPhotoMode: boolean;
+ setMode: (mode: EditorMode) => void;
+}
+
+export function useEditorMode(): UseEditorModeReturn {
+ const searchParams = useSearchParams();
+ const modeParam = searchParams.get("mode");
+
+ const mode: EditorMode = modeParam === "photo" ? "photo" : "video";
+
+ const config = useMemo(() => getEditorModeConfig(mode), [mode]);
+
+ const isVideoMode = mode === "video";
+ const isPhotoMode = mode === "photo";
+
+ const setMode = useCallback((newMode: EditorMode) => {
+ const url = new URL(window.location.href);
+ url.searchParams.set("mode", newMode);
+ window.history.replaceState({}, "", url.toString());
+ }, []);
+
+ return {
+ mode,
+ config,
+ isVideoMode,
+ isPhotoMode,
+ setMode,
+ };
+}
+
diff --git a/hooks/useImageExport.ts b/hooks/useImageExport.ts
new file mode 100644
index 0000000..0c42e45
--- /dev/null
+++ b/hooks/useImageExport.ts
@@ -0,0 +1,243 @@
+"use client";
+
+import { useState, useCallback, useRef } from "react";
+import type { ImageExportFormat } from "@/types/image-project.types";
+import type { VideoCanvasHandle } from "@/types/editor.types";
+
+export interface ImageExportProgress {
+ status: "idle" | "preparing" | "rendering" | "complete" | "error";
+ progress: number;
+ message: string;
+}
+
+interface UseImageExportOptions {
+ canvasRef: React.RefObject<VideoCanvasHandle | null>;
+}
+
+export function useImageExport({ canvasRef }: UseImageExportOptions) {
+ const [exportProgress, setExportProgress] = useState<ImageExportProgress>({
+ status: "idle",
+ progress: 0,
+ message: "",
+ });
+
+ const abortControllerRef = useRef<AbortController | null>(null);
+
+ const resetProgress = useCallback(() => {
+ setExportProgress({
+ status: "idle",
+ progress: 0,
+ message: "",
+ });
+ }, []);
+
+ const exportImage = useCallback(async (
+ format: ImageExportFormat,
+ quality: number,
+ scale: number = 1
+ ): Promise<void> => {
+ const canvas = canvasRef.current?.getExportCanvas?.();
+ if (!canvas) {
+ setExportProgress({
+ status: "error",
+ progress: 0,
+ message: "Canvas not available",
+ });
+ return;
+ }
+
+ abortControllerRef.current = new AbortController();
+ const signal = abortControllerRef.current.signal;
+
+ try {
+ setExportProgress({
+ status: "preparing",
+ progress: 10,
+ message: "Preparing export...",
+ });
+
+ if (canvasRef.current?.drawFrame) {
+ await canvasRef.current.drawFrame();
+ }
+
+ if (signal.aborted) {
+ resetProgress();
+ return;
+ }
+
+ setExportProgress({
+ status: "rendering",
+ progress: 30,
+ message: "Rendering image...",
+ });
+
+ let exportCanvas = canvas;
+
+ if (scale !== 1) {
+ exportCanvas = document.createElement("canvas");
+ exportCanvas.width = canvas.width * scale;
+ exportCanvas.height = canvas.height * scale;
+
+ const ctx = exportCanvas.getContext("2d", {
+ alpha: format === "png",
+ willReadFrequently: false,
+ });
+
+ if (!ctx) {
+ throw new Error("Failed to create export canvas context");
+ }
+
+ ctx.imageSmoothingEnabled = true;
+ ctx.imageSmoothingQuality = "high";
+ ctx.drawImage(canvas, 0, 0, exportCanvas.width, exportCanvas.height);
+ }
+
+ if (signal.aborted) {
+ resetProgress();
+ return;
+ }
+
+ setExportProgress({
+ status: "rendering",
+ progress: 60,
+ message: "Encoding image...",
+ });
+
+ const mimeType = format === "png"
+ ? "image/png"
+ : format === "jpeg"
+ ? "image/jpeg"
+ : format === "avif"
+ ? "image/avif"
+ : "image/webp";
+
+ if (format === "avif") {
+ const avifSupported = await new Promise<boolean>(resolve => {
+ const testCanvas = document.createElement("canvas");
+ testCanvas.width = testCanvas.height = 1;
+ testCanvas.toBlob(
+ b => resolve(b !== null && b.type === "image/avif"),
+ "image/avif"
+ );
+ });
+ if (!avifSupported) {
+ throw new Error("AVIF encoding is not supported in this browser. Please use WebP or PNG instead.");
+ }
+ }
+
+ const blob = await new Promise<Blob>((resolve, reject) => {
+ exportCanvas.toBlob(
+ (b) => {
+ if (b) {
+ resolve(b);
+ } else {
+ reject(new Error(`Failed to encode as ${format.toUpperCase()}. Try a different format.`));
+ }
+ },
+ mimeType,
+ format === "png" ? undefined : quality
+ );
+ });
+
+ if (signal.aborted) {
+ resetProgress();
+ return;
+ }
+
+ setExportProgress({
+ status: "rendering",
+ progress: 90,
+ message: "Downloading...",
+ });
+
+ const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
+ const scaleLabel = scale > 1 ? `@${scale}x` : "";
+ const qualityLabel = format !== "png" ? `-q${Math.round(quality * 100)}` : "";
+ const filename = `openvid-export-${timestamp}${scaleLabel}${qualityLabel}.${format}`;
+
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = filename;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+
+ const sizeDisplay = blob.size > 1024 * 1024
+ ? `${(blob.size / 1024 / 1024).toFixed(2)} MB`
+ : `${Math.round(blob.size / 1024)} KB`;
+
+ setExportProgress({
+ status: "complete",
+ progress: 100,
+ message: `Export complete! ${sizeDisplay}`,
+ });
+
+ setTimeout(() => {
+ resetProgress();
+ }, 2000);
+
+ } catch (error) {
+ if (signal.aborted) {
+ resetProgress();
+ return;
+ }
+
+ console.error("Image export error:", error);
+ setExportProgress({
+ status: "error",
+ progress: 0,
+ message: error instanceof Error ? error.message : "Export failed",
+ });
+ } finally {
+ abortControllerRef.current = null;
+ }
+ }, [canvasRef, resetProgress]);
+
+ const cancelExport = useCallback(() => {
+ if (abortControllerRef.current) {
+ abortControllerRef.current.abort();
+ abortControllerRef.current = null;
+ }
+ resetProgress();
+ }, [resetProgress]);
+
+ const copyToClipboard = useCallback(async (): Promise<boolean> => {
+ const canvas = canvasRef.current?.getExportCanvas?.();
+ if (!canvas) return false;
+
+ try {
+ if (canvasRef.current?.drawFrame) {
+ await canvasRef.current.drawFrame();
+ }
+
+ const blob = await new Promise<Blob>((resolve, reject) => {
+ canvas.toBlob(
+ (b) => {
+ if (b) resolve(b);
+ else reject(new Error("Failed to create blob"));
+ },
+ "image/png"
+ );
+ });
+
+ await navigator.clipboard.write([
+ new ClipboardItem({ "image/png": blob })
+ ]);
+
+ return true;
+ } catch (error) {
+ console.error("Failed to copy to clipboard:", error);
+ return false;
+ }
+ }, [canvasRef]);
+
+ return {
+ exportImage,
+ cancelExport,
+ copyToClipboard,
+ exportProgress,
+ resetProgress,
+ };
+}
diff --git a/hooks/useImageProjects.ts b/hooks/useImageProjects.ts
new file mode 100644
index 0000000..44b0a66
--- /dev/null
+++ b/hooks/useImageProjects.ts
@@ -0,0 +1,222 @@
+"use client";
+
+import { useState, useCallback, useEffect } from "react";
+import type { ImageProject, ImageProjectPreview } from "@/types/image-project.types";
+import {
+ saveImageProject,
+ updateImageProject,
+ getImageProject,
+ getAllImageProjects,
+ deleteImageProject,
+ setCurrentProjectId,
+ getCurrentProjectId,
+} from "@/lib/image-projects-cache";
+import type { BackgroundTab, BackgroundColorConfig, AspectRatio, CropArea } from "@/types";
+import type { CanvasElement } from "@/types/canvas-elements.types";
+import type { MockupConfig } from "@/types/mockup.types";
+import type { Preview3DConfig, ImageMaskConfig } from "@/types/photo.types";
+import { DEFAULT_MOCKUP_CONFIG } from "@/types/mockup.types";
+import { DEFAULT_MASK_CONFIG, PREVIEW_CONFIGS } from "@/types/photo.types";
+
+interface ImageProjectState {
+ backgroundTab: BackgroundTab;
+ selectedWallpaper: number;
+ backgroundBlur: number;
+ selectedImageUrl: string;
+ backgroundColorConfig: BackgroundColorConfig | null;
+ padding: number;
+ roundedCorners: number;
+ shadows: number;
+ aspectRatio: AspectRatio;
+ customDimensions: { width: number; height: number } | null;
+ cropArea: CropArea | undefined;
+ mockupId: string;
+ mockupConfig: MockupConfig;
+ canvasElements: CanvasElement[];
+ imageTransform: {
+ rotation: number;
+ translateX: number;
+ translateY: number;
+ };
+ imagePreview3D: Preview3DConfig;
+ apply3DToBackground: boolean;
+ imageMaskConfig: ImageMaskConfig;
+}
+
+const DEFAULT_PROJECT_STATE: ImageProjectState = {
+ backgroundTab: "wallpaper",
+ selectedWallpaper: 0,
+ backgroundBlur: 0,
+ selectedImageUrl: "",
+ backgroundColorConfig: null,
+ padding: 10,
+ roundedCorners: 10,
+ shadows: 10,
+ aspectRatio: "auto",
+ customDimensions: null,
+ cropArea: undefined,
+ mockupId: "none",
+ mockupConfig: DEFAULT_MOCKUP_CONFIG,
+ canvasElements: [],
+ imageTransform: {
+ rotation: 0,
+ translateX: 0,
+ translateY: 0,
+ },
+ imagePreview3D: PREVIEW_CONFIGS[0],
+ apply3DToBackground: false,
+ imageMaskConfig: DEFAULT_MASK_CONFIG,
+};
+
+export function useImageProjects() {
+ const [projects, setProjects] = useState<ImageProjectPreview[]>([]);
+ const [currentProject, setCurrentProject] = useState<ImageProject | null>(null);
+ const [isLoading, setIsLoading] = useState(false);
+ const [isSaving, setIsSaving] = useState(false);
+
+ useEffect(() => {
+ loadProjects();
+ }, []);
+
+ useEffect(() => {
+ const currentId = getCurrentProjectId();
+ if (currentId && !currentProject) {
+ loadProject(currentId);
+ }
+ }, []);
+
+ const loadProjects = useCallback(async (showLoading = true) => {
+ if (showLoading) {
+ setIsLoading(true);
+ }
+ try {
+ const allProjects = await getAllImageProjects();
+ setProjects(allProjects);
+ } catch (error) {
+ console.error("Error loading projects:", error);
+ } finally {
+ if (showLoading) {
+ setIsLoading(false);
+ }
+ }
+ }, []);
+
+ const loadProject = useCallback(async (id: string): Promise<ImageProject | null> => {
+ setIsLoading(true);
+ try {
+ const project = await getImageProject(id);
+ if (project) {
+ setCurrentProject(project);
+ setCurrentProjectId(id);
+ }
+ return project;
+ } catch (error) {
+ console.error("Error loading project:", error);
+ return null;
+ } finally {
+ setIsLoading(false);
+ }
+ }, []);
+
+ const createProject = useCallback(async (
+ imageBlob: Blob,
+ imageName: string,
+ imageWidth: number,
+ imageHeight: number,
+ state: Partial<ImageProjectState> = {}
+ ): Promise<ImageProject | null> => {
+ setIsSaving(true);
+ try {
+ const fullState = { ...DEFAULT_PROJECT_STATE, ...state };
+ const project = await saveImageProject({
+ imageBlob,
+ imageName,
+ imageWidth,
+ imageHeight,
+ ...fullState,
+ });
+
+ setCurrentProject(project);
+ setCurrentProjectId(project.id);
+ await loadProjects(false);
+ return project;
+ } catch (error) {
+ console.error("Error creating project:", error);
+ return null;
+ } finally {
+ setIsSaving(false);
+ }
+ }, [loadProjects]);
+
+ const saveCurrentProject = useCallback(async (
+ updates: Partial<Omit<ImageProject, "id" | "createdAt">>
+ ): Promise<ImageProject | null> => {
+ if (!currentProject) {
+ console.warn("No current project to save");
+ return null;
+ }
+
+ setIsSaving(true);
+ try {
+ const existing = await getImageProject(currentProject.id);
+ if (!existing) {
+ console.warn(`Project ${currentProject.id} no longer exists, skipping save`);
+ setCurrentProject(null);
+ return null;
+ }
+
+ const updated = await updateImageProject(currentProject.id, updates);
+ setCurrentProject(updated);
+ await loadProjects(false);
+ return updated;
+ } catch (error) {
+ console.error("Error saving project:", error);
+ return null;
+ } finally {
+ setIsSaving(false);
+ }
+ }, [currentProject, loadProjects]);
+
+ const switchToProject = useCallback(async (id: string): Promise<ImageProject | null> => {
+
+ const project = await loadProject(id);
+ return project;
+ }, [loadProject]);
+
+ const removeProject = useCallback(async (id: string): Promise<void> => {
+ try {
+ await deleteImageProject(id);
+
+ if (currentProject?.id === id) {
+ setCurrentProject(null);
+ setCurrentProjectId(null);
+ }
+
+ await loadProjects(false);
+ } catch (error) {
+ console.error("Error deleting project:", error);
+ }
+ }, [currentProject, loadProjects]);
+
+ const clearCurrentProject = useCallback(() => {
+ setCurrentProject(null);
+ setCurrentProjectId(null);
+ }, []);
+
+ return {
+ projects,
+ currentProject,
+ isLoading,
+ isSaving,
+
+ loadProjects,
+ loadProject,
+ createProject,
+ saveCurrentProject,
+ switchToProject,
+ removeProject,
+ clearCurrentProject,
+ };
+}
+
+export type UseImageProjectsReturn = ReturnType<typeof useImageProjects>;
diff --git a/hooks/useScreenCapture.ts b/hooks/useScreenCapture.ts
new file mode 100644
index 0000000..3a75ec2
--- /dev/null
+++ b/hooks/useScreenCapture.ts
@@ -0,0 +1,135 @@
+"use client";
+
+import { useState, useCallback, useRef } from "react";
+
+interface ScreenCaptureState {
+ status: "idle" | "selecting" | "capturing" | "complete" | "error";
+ error: string | null;
+}
+
+interface UseScreenCaptureReturn {
+ captureScreen: () => Promise<Blob | null>;
+ state: ScreenCaptureState;
+ isCapturing: boolean;
+}
+
+export function useScreenCapture(): UseScreenCaptureReturn {
+ const [state, setState] = useState<ScreenCaptureState>({
+ status: "idle",
+ error: null,
+ });
+
+ const streamRef = useRef<MediaStream | null>(null);
+
+ const cleanupStream = useCallback(() => {
+ if (streamRef.current) {
+ streamRef.current.getTracks().forEach(track => track.stop());
+ streamRef.current = null;
+ }
+ }, []);
+
+ const captureScreen = useCallback(async (): Promise<Blob | null> => {
+ // Check browser support
+ if (!navigator.mediaDevices?.getDisplayMedia) {
+ setState({
+ status: "error",
+ error: "Screen capture is not supported in this browser",
+ });
+ return null;
+ }
+
+ try {
+ setState({ status: "selecting", error: null });
+
+ const stream = await navigator.mediaDevices.getDisplayMedia({
+ video: {
+ displaySurface: "monitor",
+ },
+ audio: false,
+ // @ts-expect-error - preferCurrentTab is a newer API
+ preferCurrentTab: false,
+ });
+
+ streamRef.current = stream;
+ setState({ status: "capturing", error: null });
+
+ const videoTrack = stream.getVideoTracks()[0];
+ if (!videoTrack) {
+ throw new Error("No video track available");
+ }
+
+ const settings = videoTrack.getSettings();
+ const width = settings.width || 1920;
+ const height = settings.height || 1080;
+
+ const video = document.createElement("video");
+ video.srcObject = stream;
+ video.muted = true;
+ video.playsInline = true;
+
+ await new Promise<void>((resolve, reject) => {
+ video.onloadedmetadata = () => {
+ video.play()
+ .then(() => resolve())
+ .catch(reject);
+ };
+ video.onerror = () => reject(new Error("Failed to load video stream"));
+ });
+
+ await new Promise(resolve => setTimeout(resolve, 100));
+
+ const canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+
+ const ctx = canvas.getContext("2d", { alpha: false });
+ if (!ctx) {
+ throw new Error("Failed to create canvas context");
+ }
+
+ ctx.drawImage(video, 0, 0, width, height);
+
+ cleanupStream();
+
+ const blob = await new Promise<Blob>((resolve, reject) => {
+ canvas.toBlob(
+ (b) => {
+ if (b) resolve(b);
+ else reject(new Error("Failed to create image blob"));
+ },
+ "image/png",
+ 1
+ );
+ });
+
+ setState({ status: "complete", error: null });
+
+ setTimeout(() => {
+ setState({ status: "idle", error: null });
+ }, 1000);
+
+ return blob;
+
+ } catch (error) {
+ cleanupStream();
+
+ if (error instanceof Error && error.name === "NotAllowedError") {
+ setState({ status: "idle", error: null });
+ return null;
+ }
+
+ console.error("Screen capture error:", error);
+ setState({
+ status: "error",
+ error: error instanceof Error ? error.message : "Failed to capture screen",
+ });
+ return null;
+ }
+ }, [cleanupStream]);
+
+ return {
+ captureScreen,
+ state,
+ isCapturing: state.status === "selecting" || state.status === "capturing",
+ };
+}
diff --git a/hooks/useVideoExport.ts b/hooks/useVideoExport.ts
index a8df109..045e6b8 100644
--- a/hooks/useVideoExport.ts
+++ b/hooks/useVideoExport.ts
@@ -12,6 +12,41 @@ import { toBlobURL } from "@ffmpeg/util";
export type { ExportQuality, ExportSettings, ExportProgress };
+let _ffmpegSingleton: FFmpeg | null = null;
+let _ffmpegLoadPromise: Promise<FFmpeg> | null = null;
+
+function preloadFFmpeg(): Promise<FFmpeg> {
+ if (_ffmpegSingleton?.loaded) return Promise.resolve(_ffmpegSingleton);
+ if (_ffmpegLoadPromise) return _ffmpegLoadPromise;
+
+ _ffmpegLoadPromise = (async () => {
+ const instance = new FFmpeg();
+ const baseURL = `${window.location.origin}/ffmpeg`;
+ await instance.load({
+ coreURL: await toBlobURL(`${baseURL}/ffmpeg-core.js`, "text/javascript"),
+ wasmURL: await toBlobURL(`${baseURL}/ffmpeg-core.wasm`, "application/wasm"),
+ });
+ _ffmpegSingleton = instance;
+ return instance;
+ })().catch((err) => {
+ _ffmpegLoadPromise = null;
+ throw err;
+ });
+
+ return _ffmpegLoadPromise;
+}
+
+function canvasToRawPam(canvas: HTMLCanvasElement): Uint8Array {
+ const ctx = canvas.getContext("2d")!;
+ const { data } = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ const header = `P7\nWIDTH ${canvas.width}\nHEIGHT ${canvas.height}\nDEPTH 4\nMAXVAL 255\nTUPLTYPE RGB_ALPHA\nENDHDR\n`;
+ const headerBytes = new TextEncoder().encode(header);
+ const out = new Uint8Array(headerBytes.length + data.length);
+ out.set(headerBytes, 0);
+ out.set(data, headerBytes.length);
+ return out;
+}
+
interface CancellationToken {
cancelled: boolean;
}
@@ -53,13 +88,11 @@ export function useVideoExport(
}, []);
const exportVideo = useCallback(async (settings: ExportSettings): Promise<void> => {
- // Prevenir múltiples exportaciones simultáneas
if (isExportingRef.current) {
console.log("Export already in progress");
return;
}
- // Reset completo del estado antes de empezar
cancellationRef.current = { cancelled: false };
isExportingRef.current = true;
@@ -76,7 +109,6 @@ export function useVideoExport(
return;
}
- // Verificar que el video tenga duración válida
if (!video.duration || video.duration === Infinity || isNaN(video.duration)) {
setExportProgress({
status: "error",
@@ -108,7 +140,6 @@ export function useVideoExport(
message: "Preparando video...",
});
- // Asegurar que el video esté completamente listo
await ensureVideoReady(video);
if (cancellationRef.current.cancelled) {
@@ -121,46 +152,37 @@ export function useVideoExport(
message: "Configurando exportación...",
});
- // Ajustar tamaño del canvas según calidad manteniendo aspect ratio
const originalWidth = exportCanvas.width;
const originalHeight = exportCanvas.height;
const originalAspectRatio = originalWidth / originalHeight;
const qualityAspectRatio = qualitySettings.width / qualitySettings.height;
- // Escalar para mantener el aspect ratio del canvas original
let targetWidth: number;
let targetHeight: number;
if (Math.abs(originalAspectRatio - qualityAspectRatio) < 0.01) {
- // Si los aspect ratios son similares, usar dimensiones directas
targetWidth = qualitySettings.width;
targetHeight = qualitySettings.height;
} else if (originalAspectRatio > qualityAspectRatio) {
- // Canvas más ancho, escalar por ancho
targetWidth = qualitySettings.width;
targetHeight = Math.round(qualitySettings.width / originalAspectRatio);
} else {
- // Canvas más alto, escalar por altura
targetHeight = qualitySettings.height;
targetWidth = Math.round(qualitySettings.height * originalAspectRatio);
}
- // Ensure dimensions are even numbers (required by AVC codec)
targetWidth = Math.round(targetWidth / 2) * 2;
targetHeight = Math.round(targetHeight / 2) * 2;
exportCanvas.width = targetWidth;
exportCanvas.height = targetHeight;
- // Guardar posición actual del video y estado de audio
const originalTime = video.currentTime;
const wasPlaying = !video.paused;
const originalMuted = video.muted;
- // Mutear el video durante la exportación para evitar audio entrecortado
video.muted = true;
- // Determine trim range (use full video if no trim specified)
const trimStart = settings.trim?.start ?? 0;
const trimEnd = settings.trim?.end ?? video.duration;
const exportDuration = trimEnd - trimStart;
@@ -211,19 +233,16 @@ export function useVideoExport(
);
}
- // Restaurar canvas y video
exportCanvas.width = originalWidth;
exportCanvas.height = originalHeight;
video.currentTime = originalTime;
video.muted = originalMuted;
- // Restaurar estado de reproducción
if (wasPlaying) {
await video.play().catch(() => { });
}
} catch (error) {
- // Si fue cancelado, no mostrar error
if (cancellationRef.current.cancelled) {
setExportProgress({
status: "idle",
@@ -239,15 +258,12 @@ export function useVideoExport(
});
}
} finally {
- // Siempre resetear el flag de exportación
isExportingRef.current = false;
}
}, [videoRef, canvasRef]);
const cancelExport = useCallback(() => {
- // Marcar como cancelado
cancellationRef.current.cancelled = true;
- // Resetear el flag de exportación inmediatamente
isExportingRef.current = false;
setExportProgress({
status: "idle",
@@ -275,19 +291,15 @@ async function exportWithFFmpegWebM(
height: number,
setProgress: (p: ExportProgress) => void,
cancellation: CancellationToken,
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
_settings?: ExportSettings // Reserved for future audio support in WebM
): Promise<void> {
- const ffmpeg = new FFmpeg();
const totalFrames = Math.ceil(duration * fps);
- setProgress({ status: "preparing", progress: 3, message: "Cargando motor WebM..." });
-
- const ffmpegBase = `${window.location.origin}/ffmpeg`;
- await ffmpeg.load({
- coreURL: await toBlobURL(`${ffmpegBase}/ffmpeg-core.js`, "text/javascript"),
- wasmURL: await toBlobURL(`${ffmpegBase}/ffmpeg-core.wasm`, "application/wasm"),
- });
+ const ffmpegReady = !_ffmpegSingleton?.loaded;
+ if (ffmpegReady) {
+ setProgress({ status: "preparing", progress: 3, message: "Cargando motor WebM..." });
+ }
+ const ffmpeg = await preloadFFmpeg();
video.pause();
video.currentTime = trimStart;
@@ -296,21 +308,15 @@ async function exportWithFFmpegWebM(
for (let i = 0; i < totalFrames; i++) {
if (cancellation.cancelled) throw new Error("Exportación cancelada");
- // Video is already at the correct position (pre-seek or end of prev iteration)
await canvasHandle.drawFrame();
- // Trigger next seek immediately after canvas capture to overlap with encode
const nextI = i + 1;
if (nextI < totalFrames) {
video.currentTime = Math.min(trimStart + nextI / fps, trimStart + duration - 0.001);
}
- // Encode current frame while next seek is in flight
- const blob = await new Promise<Blob>((resolve, reject) =>
- canvas.toBlob(b => b ? resolve(b) : reject(), "image/png")
- );
- const data = new Uint8Array(await blob.arrayBuffer());
- await ffmpeg.writeFile(`frame${String(i).padStart(5, "0")}.png`, data);
+ const pamData = canvasToRawPam(canvas);
+ await ffmpeg.writeFile(`frame${String(i).padStart(5, "0")}.pam`, pamData);
if (i % 10 === 0 || i === totalFrames - 1) {
setProgress({
@@ -320,31 +326,29 @@ async function exportWithFFmpegWebM(
});
}
- // Await next frame — partially decoded by now
if (nextI < totalFrames) {
await waitForVideoFrame(video);
}
}
- // Actualizar progreso durante la codificación VP8
- ffmpeg.on("progress", ({ progress }) => {
+ setProgress({ status: "finalizing", progress: 70, message: "[Paso 2/2] Iniciando codificación VP8..." });
+
+ const onProgress = ({ progress }: { progress: number }) => {
if (progress > 0) {
- const encodingProgress = 70 + Math.round(progress * 20);
setProgress({
status: "finalizing",
- progress: Math.min(encodingProgress, 90),
+ progress: Math.min(70 + Math.round(progress * 20), 90),
message: `[Paso 2/2] Codificando VP8 con transparencia...`,
});
}
- });
-
- setProgress({ status: "finalizing", progress: 70, message: "[Paso 2/2] Iniciando codificación VP8..." });
+ };
+ ffmpeg.on("progress", onProgress);
try {
await ffmpeg.exec([
"-f", "image2",
"-framerate", String(fps),
- "-i", "frame%05d.png",
+ "-i", "frame%05d.pam",
"-c:v", "libvpx",
"-auto-alt-ref", "0",
"-b:v", "1M",
@@ -352,10 +356,10 @@ async function exportWithFFmpegWebM(
"output.webm",
]);
} finally {
- // Limpiar frames independientemente del resultado
+ ffmpeg.off("progress", onProgress);
try {
for (let i = 0; i < totalFrames; i++) {
- await ffmpeg.deleteFile(`frame${String(i).padStart(5, "0")}.png`);
+ await ffmpeg.deleteFile(`frame${String(i).padStart(5, "0")}.pam`);
}
} catch { /* ignorar errores de limpieza */ }
}
@@ -385,7 +389,6 @@ async function exportWithMediabunny(
setProgress: (p: ExportProgress) => void,
cancellation: CancellationToken
): Promise<void> {
- // Verificar cancelación
if (cancellation.cancelled) {
throw new Error("Exportación cancelada");
}
@@ -417,12 +420,10 @@ async function exportWithMediabunny(
await output.start();
- // Pausar el video y moverlo al inicio del trim
video.pause();
video.currentTime = trimStart;
await waitForVideoFrame(video);
- // Procesar frames con seek pipelinizado (seek N+1 overlaps encode N)
for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {
if (cancellation.cancelled) {
throw new Error("Exportación cancelada");
@@ -430,11 +431,9 @@ async function exportWithMediabunny(
const outputTime = frameIndex / fps;
- // Video is already at the correct position (pre-seek or end of prev iteration)
await canvasHandle.drawFrame();
await videoSource.add(outputTime, frameDuration);
- // Trigger next seek immediately (overlaps JS overhead)
const nextIndex = frameIndex + 1;
if (nextIndex < totalFrames) {
video.currentTime = Math.min(trimStart + nextIndex / fps, trimStart + duration - 0.001);
@@ -449,13 +448,11 @@ async function exportWithMediabunny(
});
}
- // Await next frame — partially decoded by now
if (nextIndex < totalFrames) {
await waitForVideoFrame(video);
}
}
- // Verificar cancelación antes de finalizar
if (cancellation.cancelled) {
throw new Error("Exportación cancelada");
}
@@ -468,7 +465,6 @@ async function exportWithMediabunny(
await output.finalize();
- // Verificar una última vez antes de descargar
if (cancellation.cancelled) {
throw new Error("Exportación cancelada");
}
@@ -511,18 +507,14 @@ async function exportWithMediabunnyAndAudio(
settings: ExportSettings
): Promise<void> {
const hasAudioTracks = settings.audioTracks && settings.audioTracks.length > 0;
- // Only consider original audio if: (1) not explicitly muted AND (2) the source video actually has an audio stream.
- // videoHasAudioTrack defaults to true (safe fallback) if not provided.
const sourceHasAudioStream = settings.videoHasAudioTrack !== false;
const hasOriginalAudio = !settings.muteOriginalAudio && sourceHasAudioStream;
const needsAudioMixing = hasAudioTracks || hasOriginalAudio;
- // Check if multi-clip export
const hasMultipleClips = settings.videoClips && settings.videoClips.length > 1 && settings.videoClipBlobs;
const clips = settings.videoClips || [];
const clipBlobs = settings.videoClipBlobs;
- // If no audio mixing needed, use simple export (single video only)
if (!needsAudioMixing && !hasMultipleClips) {
return exportWithMediabunny(
video, canvasHandle, canvas, duration, trimStart, fps,
@@ -530,7 +522,8 @@ async function exportWithMediabunnyAndAudio(
);
}
- // Verificar cancelación
+ const ffmpegPreload = needsAudioMixing ? preloadFFmpeg().catch(() => null) : null;
+
if (cancellation.cancelled) {
throw new Error("Exportación cancelada");
}
@@ -544,7 +537,6 @@ async function exportWithMediabunnyAndAudio(
const totalFrames = Math.ceil(duration * fps);
const frameDuration = 1 / fps;
- // Step 1: Encode video with MediaBunny
const output = new Output({
format: new Mp4OutputFormat({
fastStart: "in-memory",
@@ -565,12 +557,9 @@ async function exportWithMediabunnyAndAudio(
video.pause();
- // For multi-clip export, track the current active clip ID
let currentClipId: string | null = null;
- // Initial setup based on whether we have multiple clips
if (hasMultipleClips && clips.length > 0) {
- // Sort clips by start time
const sortedClips = [...clips].sort((a, b) => a.startTime - b.startTime);
const firstClip = sortedClips[0];
if (firstClip && clipBlobs) {
@@ -600,14 +589,12 @@ async function exportWithMediabunnyAndAudio(
const outputTime = frameIndex / fps;
const timelineTime = trimStart + outputTime;
- // Multi-clip: determine which clip we're in and seek to correct position
if (hasMultipleClips && clipBlobs) {
const activeClipInfo = getActiveClipAtTime(clips, timelineTime);
if (activeClipInfo) {
const { clip, clipTime } = activeClipInfo;
- // Check if we need to switch video source
if (clip.id !== currentClipId) {
const newBlob = clipBlobs.get(clip.libraryVideoId);
if (newBlob) {
@@ -622,17 +609,14 @@ async function exportWithMediabunnyAndAudio(
}
}
- // Seek to correct position within the clip's video
video.currentTime = clipTime;
await waitForVideoFrame(video);
}
}
- // Video is already at the correct position (pre-seek or end of prev iteration)
await canvasHandle.drawFrame();
await videoSource.add(outputTime, frameDuration);
- // For single-clip, trigger next seek immediately (overlaps JS overhead)
if (!hasMultipleClips) {
const nextFrame = frameIndex + 1;
if (nextFrame < totalFrames) {
@@ -651,7 +635,6 @@ async function exportWithMediabunnyAndAudio(
});
}
- // Await next frame — for single clip only (multi-clip handled at start of loop)
if (!hasMultipleClips) {
const nextFrame = frameIndex + 1;
if (nextFrame < totalFrames) {
@@ -679,47 +662,38 @@ async function exportWithMediabunnyAndAudio(
const videoBlob = new Blob([buffer], { type: "video/mp4" });
- // If no audio mixing needed, download directly
if (!needsAudioMixing) {
downloadBlob(videoBlob, `video-export-${width}x${height}.mp4`);
setProgress({ status: "complete", progress: 100, message: "¡Exportación completada!" });
return;
}
- // Pre-check: even if needsAudioMixing is true, verify we actually have usable audio sources
- // before loading FFmpeg (which can fail with FS errors if WASM files are missing/corrupt)
const sourceBlob = hasOriginalAudio ? settings.videoBlob : undefined;
const hasUsableSourceBlob = !!(sourceBlob && sourceBlob.size > 0);
const hasUsableAudioTracks = !!(settings.audioTracks && settings.audioTracks.some(t => t.audioUrl));
if (!hasUsableSourceBlob && !hasUsableAudioTracks) {
- // No actual audio data to mix — download video directly without loading FFmpeg
downloadBlob(videoBlob, `video-export-${width}x${height}.mp4`);
setProgress({ status: "complete", progress: 100, message: "¡Exportación completada!" });
return;
}
- // Step 2: Use FFmpeg to add audio — wrapped in try-catch to fall back on any FS/WASM error
try {
+ if (ffmpegPreload !== null) {
+ const preloaded = await ffmpegPreload;
+ if (!preloaded) throw new Error("FFmpeg preload failed");
+ }
+ const ffmpeg = await preloadFFmpeg();
+
setProgress({
status: "finalizing",
progress: 60,
- message: "Cargando motor de audio...",
- });
-
- const ffmpeg = new FFmpeg();
- const baseURL = `${window.location.origin}/ffmpeg`;
-
- await ffmpeg.load({
- coreURL: await toBlobURL(`${baseURL}/ffmpeg-core.js`, "text/javascript"),
- wasmURL: await toBlobURL(`${baseURL}/ffmpeg-core.wasm`, "application/wasm"),
+ message: "Mezclando audio...",
});
- // Write video file to FFmpeg
const videoData = new Uint8Array(await videoBlob.arrayBuffer());
await ffmpeg.writeFile("video.mp4", videoData);
- // Write original video for audio extraction if needed
let hasSourceAudio = false;
if (hasOriginalAudio) {
if (hasUsableSourceBlob) {
@@ -727,8 +701,6 @@ async function exportWithMediabunnyAndAudio(
const originalVideoData = new Uint8Array(await sourceBlob!.arrayBuffer());
await ffmpeg.writeFile("original.mp4", originalVideoData);
- // Verificar si el video tiene stream de audio
- // Probamos extrayendo audio — si falla, no tiene audio
try {
await ffmpeg.exec([
"-i", "original.mp4",
@@ -737,7 +709,6 @@ async function exportWithMediabunnyAndAudio(
]);
hasSourceAudio = true;
} catch {
- // No tiene stream de audio
hasSourceAudio = false;
await ffmpeg.deleteFile("original.mp4").catch(() => { });
}
@@ -750,10 +721,8 @@ async function exportWithMediabunnyAndAudio(
}
}
- // Write audio track files
const audioTracks: { index: number; filename: string; track: NonNullable<typeof settings.audioTracks>[0] }[] = [];
if (settings.audioTracks && settings.audioTracks.length > 0) {
- // Fetch all audio tracks in parallel, then write to FFmpeg WASM memory sequentially
const fetchResults = await Promise.all(
settings.audioTracks.map(async (track, i) => {
if (!track.audioUrl) return null;
@@ -780,25 +749,20 @@ async function exportWithMediabunnyAndAudio(
message: "Mezclando audio...",
});
- // Build FFmpeg command for audio mixing
const ffmpegArgs: string[] = ["-i", "video.mp4"];
- // Add original audio input if available
if (hasSourceAudio) {
ffmpegArgs.push("-ss", String(trimStart), "-t", String(duration), "-i", "original.mp4");
}
- // Add audio track inputs
for (const audioTrackFile of audioTracks) {
ffmpegArgs.push("-i", audioTrackFile.filename);
}
- // Build filter complex for audio mixing
const audioInputs: string[] = [];
let filterComplex = "";
let inputIndex = 1; // Start at 1 because 0 is the video
- // Add original audio to mix
if (hasSourceAudio) {
const volume = settings.masterVolume ?? 1;
filterComplex += `[${inputIndex}:a]volume=${volume}[a${inputIndex}];`;
@@ -806,7 +770,6 @@ async function exportWithMediabunnyAndAudio(
inputIndex++;
}
- // Add audio tracks to mix
for (const audioTrackFile of audioTracks) {
const { track } = audioTrackFile;
const trackVolume = track.volume * (settings.masterVolume ?? 1);
@@ -819,11 +782,9 @@ async function exportWithMediabunnyAndAudio(
inputIndex++;
}
- // Mix all audio streams
const totalAudioInputs = (hasSourceAudio ? 1 : 0) + audioTracks.length;
if (totalAudioInputs === 0) {
- // No usable audio after processing — download video directly
downloadBlob(videoBlob, `video-export-${width}x${height}.mp4`);
setProgress({ status: "complete", progress: 100, message: "¡Exportación completada!" });
return;
@@ -836,8 +797,7 @@ async function exportWithMediabunnyAndAudio(
ffmpegArgs.push("-c:v", "copy", "-an", "output.mp4");
}
- // Track FFmpeg progress
- ffmpeg.on("progress", ({ progress }) => {
+ const onAudioProgress = ({ progress }: { progress: number }) => {
if (progress > 0) {
const mixProgress = 70 + Math.round(progress * 25);
setProgress({
@@ -846,13 +806,13 @@ async function exportWithMediabunnyAndAudio(
message: `Procesando audio... ${Math.round(progress * 100)}%`,
});
}
- });
+ };
+ ffmpeg.on("progress", onAudioProgress);
try {
await ffmpeg.exec(ffmpegArgs);
} catch (e) {
console.error("FFmpeg audio mixing failed:", e);
- // Fallback: export video without audio mixing
downloadBlob(videoBlob, `video-export-${width}x${height}.mp4`);
setProgress({
status: "complete",
@@ -860,6 +820,8 @@ async function exportWithMediabunnyAndAudio(
message: "¡Exportación completada (sin mezcla de audio)!",
});
return;
+ } finally {
+ ffmpeg.off("progress", onAudioProgress);
}
setProgress({
@@ -871,7 +833,6 @@ async function exportWithMediabunnyAndAudio(
const outputData = (await ffmpeg.readFile("output.mp4")) as Uint8Array;
const outputBlob = new Blob([new Uint8Array(outputData)], { type: "video/mp4" });
- // Cleanup
try {
await ffmpeg.deleteFile("video.mp4");
await ffmpeg.deleteFile("output.mp4");
@@ -889,7 +850,6 @@ async function exportWithMediabunnyAndAudio(
message: "¡Exportación con audio completada!",
});
} catch (ffmpegError) {
- // Catch-all for any FFmpeg/WASM/FS error — fall back to video-only download
console.warn("FFmpeg audio processing failed, exporting video only:", ffmpegError);
downloadBlob(videoBlob, `video-export-${width}x${height}.mp4`);
setProgress({
@@ -930,21 +890,16 @@ async function exportWithFFmpegGif(
setProgress: (p: ExportProgress) => void,
cancellation: CancellationToken
): Promise<void> {
- const ffmpeg = new FFmpeg();
const totalFrames = Math.ceil(duration * fps);
- try {
- if (cancellation.cancelled) throw new Error("Exportación cancelada");
-
+ const ffmpegReady = !_ffmpegSingleton?.loaded;
+ if (ffmpegReady) {
setProgress({ status: "preparing", progress: 3, message: "Cargando motor de exportación GIF..." });
+ }
+ const ffmpeg = await preloadFFmpeg();
- const baseURL = `${window.location.origin}/ffmpeg`;
-
- await ffmpeg.load({
- coreURL: await toBlobURL(`${baseURL}/ffmpeg-core.js`, "text/javascript"),
- wasmURL: await toBlobURL(`${baseURL}/ffmpeg-core.wasm`, "application/wasm"),
- // sin workerURL — @ffmpeg/core es single-thread
- });
+ try {
+ if (cancellation.cancelled) throw new Error("Exportación cancelada");
setProgress({ status: "encoding", progress: 8, message: `Capturando ${totalFrames} frames...` });
@@ -955,16 +910,13 @@ async function exportWithFFmpegGif(
for (let i = 0; i < totalFrames; i++) {
if (cancellation.cancelled) throw new Error("Exportación cancelada");
- // Video is already at the correct position (pre-seek or end of prev iteration)
await canvasHandle.drawFrame();
- // Trigger next seek immediately after canvas capture to overlap with encode
const nextI = i + 1;
if (nextI < totalFrames) {
video.currentTime = Math.min(trimStart + nextI / fps, trimStart + duration - 0.001);
}
- // Encode current frame while next seek is in flight
const blob = await canvasToBlobFast(canvas);
const data = await blobToUint8Array(blob);
await ffmpeg.writeFile(`frame${String(i).padStart(5, "0")}.jpg`, data);
@@ -978,7 +930,6 @@ async function exportWithFFmpegGif(
});
}
- // Await next frame — partially decoded by now
if (nextI < totalFrames) {
await waitForVideoFrame(video);
}
diff --git a/hooks/useVideoUpload.ts b/hooks/useVideoUpload.ts
index 44719b5..ade6d3d 100644
--- a/hooks/useVideoUpload.ts
+++ b/hooks/useVideoUpload.ts
@@ -10,7 +10,7 @@ interface UploadedVideoData {
fileName: string;
width: number;
height: number;
- timestamp: number; // uploadedAt timestamp for comparison
+ timestamp: number;
}
interface UseVideoUploadReturn {
diff --git a/lib/image-projects-cache.ts b/lib/image-projects-cache.ts
new file mode 100644
index 0000000..1c8e5b0
--- /dev/null
+++ b/lib/image-projects-cache.ts
@@ -0,0 +1,262 @@
+import type { ImageProject, ImageProjectPreview } from "@/types/image-project.types";
+
+const DB_NAME = "openvid-image-projects";
+const DB_VERSION = 1;
+const STORE_NAME = "projects";
+const CURRENT_PROJECT_KEY = "current-active-project";
+
+let dbInstance: IDBDatabase | null = null;
+
+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;
+ 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: "id" });
+ store.createIndex("createdAt", "createdAt", { unique: false });
+ }
+ };
+ });
+}
+
+async function generateThumbnail(blob: Blob, maxSize = 200): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const img = new Image();
+ const url = URL.createObjectURL(blob);
+
+ img.onload = () => {
+ const canvas = document.createElement("canvas");
+ const ctx = canvas.getContext("2d");
+ if (!ctx) {
+ URL.revokeObjectURL(url);
+ reject(new Error("Failed to get canvas context"));
+ return;
+ }
+
+ let width = img.width;
+ let height = img.height;
+
+ if (width > height) {
+ if (width > maxSize) {
+ height = (height * maxSize) / width;
+ width = maxSize;
+ }
+ } else {
+ if (height > maxSize) {
+ width = (width * maxSize) / height;
+ height = maxSize;
+ }
+ }
+
+ canvas.width = width;
+ canvas.height = height;
+ ctx.drawImage(img, 0, 0, width, height);
+
+ URL.revokeObjectURL(url);
+ resolve(canvas.toDataURL("image/jpeg", 0.7));
+ };
+
+ img.onerror = () => {
+ URL.revokeObjectURL(url);
+ reject(new Error("Failed to load image"));
+ };
+
+ img.src = url;
+ });
+}
+
+async function blobToDataURL(blob: Blob): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onload = () => resolve(reader.result as string);
+ reader.onerror = () => reject(reader.error);
+ reader.readAsDataURL(blob);
+ });
+}
+
+export async function saveImageProject(project: Omit<ImageProject, "id" | "imageDataUrl" | "thumbnailDataUrl" | "createdAt" | "updatedAt">): Promise<ImageProject> {
+ try {
+ const db = await openDB();
+ const [thumbnail, imageDataUrl] = await Promise.all([
+ generateThumbnail(project.imageBlob),
+ blobToDataURL(project.imageBlob)
+ ]);
+
+ const fullProject: ImageProject = {
+ ...project,
+ id: crypto.randomUUID(),
+ imageDataUrl,
+ thumbnailDataUrl: thumbnail,
+ createdAt: Date.now()
+ };
+
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction([STORE_NAME], "readwrite");
+ const store = transaction.objectStore(STORE_NAME);
+ const request = store.put(fullProject);
+
+ request.onsuccess = () => resolve(fullProject);
+ request.onerror = () => reject(request.error);
+ });
+ } catch (error) {
+ console.error("Error saving image project:", error);
+ throw error;
+ }
+}
+
+export async function updateImageProject(id: string, updates: Partial<Omit<ImageProject, "id" | "createdAt">>): Promise<ImageProject> {
+ try {
+ const db = await openDB();
+ const existing = await getImageProject(id);
+
+ if (!existing) {
+ throw new Error(`Project with id ${id} not found`);
+ }
+
+ let thumbnail = existing.thumbnailDataUrl;
+ let imageDataUrl = existing.imageDataUrl;
+
+ if (updates.imageBlob) {
+ [thumbnail, imageDataUrl] = await Promise.all([
+ generateThumbnail(updates.imageBlob),
+ blobToDataURL(updates.imageBlob)
+ ]);
+ }
+
+ const updated: ImageProject = {
+ ...existing,
+ ...updates,
+ imageDataUrl,
+ thumbnailDataUrl: thumbnail
+ };
+
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction([STORE_NAME], "readwrite");
+ const store = transaction.objectStore(STORE_NAME);
+ const request = store.put(updated);
+
+ request.onsuccess = () => resolve(updated);
+ request.onerror = () => reject(request.error);
+ });
+ } catch (error) {
+ console.error("Error updating image project:", error);
+ throw error;
+ }
+}
+
+export async function getImageProject(id: string): Promise<ImageProject | 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(id);
+
+ request.onsuccess = () => resolve(request.result || null);
+ request.onerror = () => reject(request.error);
+ });
+ } catch (error) {
+ console.error("Error getting image project:", error);
+ return null;
+ }
+}
+
+export async function getAllImageProjects(): Promise<ImageProjectPreview[]> {
+ try {
+ const db = await openDB();
+
+ return new Promise((resolve, reject) => {
+ const transaction = db.transaction([STORE_NAME], "readonly");
+ const store = transaction.objectStore(STORE_NAME);
+ const index = store.index("createdAt");
+ const request = index.openCursor(null, "prev");
+
+ const projects: ImageProjectPreview[] = [];
+
+ request.onsuccess = (event) => {
+ const cursor = (event.target as IDBRequest<IDBCursorWithValue>).result;
+ if (cursor) {
+ const project = cursor.value as ImageProject;
+ projects.push({
+ id: project.id,
+ imageName: project.imageName,
+ thumbnailDataUrl: project.thumbnailDataUrl,
+ createdAt: project.createdAt
+ });
+ cursor.continue();
+ } else {
+ resolve(projects);
+ }
+ };
+
+ request.onerror = () => reject(request.error);
+ });
+ } catch (error) {
+ console.error("Error getting all image projects:", error);
+ return [];
+ }
+}
+
+export async function deleteImageProject(id: string): 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(id);
+
+ request.onsuccess = () => resolve();
+ request.onerror = () => reject(request.error);
+ });
+ } catch (error) {
+ console.error("Error deleting image project:", error);
+ throw error;
+ }
+}
+
+export function setCurrentProjectId(id: string | null): void {
+ if (id) {
+ localStorage.setItem(CURRENT_PROJECT_KEY, id);
+ } else {
+ localStorage.removeItem(CURRENT_PROJECT_KEY);
+ }
+}
+
+export function getCurrentProjectId(): string | null {
+ if (typeof window === "undefined") return null;
+ return localStorage.getItem(CURRENT_PROJECT_KEY);
+}
+
+export function createProjectImageUrl(blob: Blob): string {
+ return URL.createObjectURL(blob);
+}
+
+export async function getProjectCount(): Promise<number> {
+ 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.count();
+
+ request.onsuccess = () => resolve(request.result);
+ request.onerror = () => reject(request.error);
+ });
+ } catch (error) {
+ console.error("Error getting project count:", error);
+ return 0;
+ }
+}
diff --git a/lib/image-upload-cache.ts b/lib/image-upload-cache.ts
new file mode 100644
index 0000000..e002388
--- /dev/null
+++ b/lib/image-upload-cache.ts
@@ -0,0 +1,166 @@
+const DB_NAME = "openvid-uploaded-images";
+const DB_VERSION = 1;
+const STORE_NAME = "images";
+const SINGLE_IMAGE_KEY = "current-uploaded-image";
+
+export interface CachedUploadedImage {
+ key: string;
+ blob: Blob;
+ fileName: string;
+ fileSize: number;
+ width: number;
+ height: number;
+ aspectRatio: string;
+ uploadedAt: number;
+}
+
+let dbInstance: IDBDatabase | null = null;
+
+/**
+ * Open IndexedDB connection for images
+ */
+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;
+ 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 });
+ }
+ };
+ });
+}
+
+/**
+ * Get image metadata from file
+ */
+async function getImageMetadata(file: File): Promise<{
+ width: number;
+ height: number;
+ aspectRatio: string;
+}> {
+ return new Promise((resolve, reject) => {
+ const img = new Image();
+
+ img.onload = () => {
+ const metadata = {
+ width: img.naturalWidth,
+ height: img.naturalHeight,
+ aspectRatio: "auto",
+ };
+ URL.revokeObjectURL(img.src);
+ resolve(metadata);
+ };
+
+ img.onerror = () => {
+ URL.revokeObjectURL(img.src);
+ reject(new Error("Failed to load image metadata"));
+ };
+
+ img.src = URL.createObjectURL(file);
+ });
+}
+
+/**
+ * Save uploaded image (replaces any existing image)
+ */
+export async function saveUploadedImage(file: File): Promise<CachedUploadedImage> {
+ try {
+ const db = await openDB();
+ const metadata = await getImageMetadata(file);
+
+ const data: CachedUploadedImage = {
+ key: SINGLE_IMAGE_KEY,
+ blob: file,
+ fileName: file.name,
+ fileSize: file.size,
+ 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);
+
+ // Delete existing image first
+ store.delete(SINGLE_IMAGE_KEY);
+
+ // Save new image
+ const request = store.put(data);
+ request.onsuccess = () => resolve(data);
+ request.onerror = () => reject(request.error);
+ });
+ } catch (error) {
+ console.error("Error saving uploaded image:", error);
+ throw error;
+ }
+}
+
+/**
+ * Get uploaded image from cache
+ */
+export async function getUploadedImage(): Promise<CachedUploadedImage | 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_IMAGE_KEY);
+
+ request.onsuccess = () => resolve(request.result || null);
+ request.onerror = () => reject(request.error);
+ });
+ } catch (error) {
+ console.error("Error getting uploaded image:", error);
+ return null;
+ }
+}
+
+/**
+ * Delete uploaded image from cache
+ */
+export async function deleteUploadedImage(): 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_IMAGE_KEY);
+
+ request.onsuccess = () => resolve();
+ request.onerror = () => reject(request.error);
+ });
+ } catch (error) {
+ console.error("Error deleting uploaded image:", error);
+ throw error;
+ }
+}
+
+/**
+ * Check if there's an uploaded image
+ */
+export async function hasUploadedImage(): Promise<boolean> {
+ const image = await getUploadedImage();
+ return image !== null;
+}
+
+/**
+ * Create object URL for cached image
+ */
+export function createImageUrl(cachedImage: CachedUploadedImage): string {
+ return URL.createObjectURL(cachedImage.blob);
+}
diff --git a/lib/perspective3d.ts b/lib/perspective3d.ts
new file mode 100644
index 0000000..d447cee
--- /dev/null
+++ b/lib/perspective3d.ts
@@ -0,0 +1,141 @@
+import * as THREE from "three";
+
+let _renderer: THREE.WebGLRenderer | null = null;
+let _scene: THREE.Scene | null = null;
+let _camera: THREE.PerspectiveCamera | null = null;
+let _plane: THREE.Mesh | null = null;
+let _material: THREE.MeshBasicMaterial | null = null;
+let _texture: THREE.CanvasTexture | null = null;
+let _offscreen: HTMLCanvasElement | null = null;
+let _lastAspect = 0;
+
+function buildRenderer(): THREE.WebGLRenderer {
+ const r = new THREE.WebGLRenderer({
+ alpha: true,
+ antialias: true,
+ preserveDrawingBuffer: true,
+ premultipliedAlpha: false,
+ });
+ r.outputColorSpace = THREE.SRGBColorSpace;
+ r.toneMapping = THREE.NoToneMapping;
+ r.setClearColor(0x000000, 0);
+ return r;
+}
+
+function ensureScene(aspect: number): { scene: THREE.Scene; plane: THREE.Mesh } {
+ if (!_scene) {
+ _scene = new THREE.Scene();
+ }
+
+ if (!_texture || !_offscreen) {
+ _offscreen = document.createElement("canvas");
+ _texture = new THREE.CanvasTexture(_offscreen);
+ _texture.colorSpace = THREE.SRGBColorSpace;
+ _texture.minFilter = THREE.LinearFilter;
+ _texture.magFilter = THREE.LinearFilter;
+ _texture.generateMipmaps = false;
+ }
+
+ if (!_material) {
+ _material = new THREE.MeshBasicMaterial({
+ map: _texture,
+ transparent: true,
+ side: THREE.FrontSide,
+ depthTest: false,
+ depthWrite: false,
+ });
+ }
+
+ if (!_plane || Math.abs(_lastAspect - aspect) > 0.0001) {
+ if (_plane) {
+ _plane.geometry.dispose();
+ _scene.remove(_plane);
+ }
+ const geo = new THREE.PlaneGeometry(2 * aspect, 2);
+ _plane = new THREE.Mesh(geo, _material);
+ _scene.add(_plane);
+ _lastAspect = aspect;
+ }
+
+ return { scene: _scene, plane: _plane };
+}
+
+export function applyPerspective3D(
+ canvas: HTMLCanvasElement,
+ rotateXDeg: number,
+ rotateYDeg: number,
+ perspectivePx: number
+): void {
+ if (rotateXDeg === 0 && rotateYDeg === 0) return;
+ if (typeof window === "undefined") return;
+
+ const w = canvas.width;
+ const h = canvas.height;
+ if (w === 0 || h === 0) return;
+
+ const aspect = w / h;
+
+ if (!_renderer) {
+ _renderer = buildRenderer();
+ }
+ if (_renderer.domElement.width !== w || _renderer.domElement.height !== h) {
+ _renderer.setSize(w, h, false);
+ }
+
+ const { scene, plane } = ensureScene(aspect);
+
+ const off = _offscreen!;
+ if (off.width !== w || off.height !== h) {
+ off.width = w;
+ off.height = h;
+ }
+ const offCtx = off.getContext("2d", { alpha: true, willReadFrequently: false })!;
+ offCtx.clearRect(0, 0, w, h);
+ offCtx.drawImage(canvas, 0, 0);
+
+ _texture!.image = off;
+ _texture!.needsUpdate = true;
+
+ const PERSPECTIVE_REFERENCE_HEIGHT = 1080;
+ const cameraZ = (2 * perspectivePx) / PERSPECTIVE_REFERENCE_HEIGHT;
+ const fovDeg = (2 * Math.atan(1 / cameraZ) * 180) / Math.PI;
+
+ if (!_camera) {
+ _camera = new THREE.PerspectiveCamera(fovDeg, aspect, 0.001, cameraZ * 20);
+ _camera.position.set(0, 0, cameraZ);
+ } else {
+ _camera.fov = fovDeg;
+ _camera.aspect = aspect;
+ _camera.near = 0.001;
+ _camera.far = cameraZ * 20;
+ _camera.position.set(0, 0, cameraZ);
+ }
+ _camera.lookAt(0, 0, 0);
+ _camera.updateProjectionMatrix();
+ plane.rotation.x = -(rotateXDeg * Math.PI) / 180;
+ plane.rotation.y = (rotateYDeg * Math.PI) / 180;
+ plane.rotation.z = 0;
+
+ _renderer.render(scene, _camera);
+
+ const ctx2d = canvas.getContext("2d", { alpha: true, willReadFrequently: false })!;
+ ctx2d.clearRect(0, 0, w, h);
+ ctx2d.drawImage(_renderer.domElement, 0, 0);
+}
+
+export function disposePerspective3D(): void {
+ _texture?.dispose();
+ _material?.dispose();
+ if (_plane) {
+ _plane.geometry.dispose();
+ }
+ _renderer?.dispose();
+ _renderer = null;
+ _scene = null;
+ _camera = null;
+ _plane = null;
+ _material = null;
+ _texture = null;
+ _offscreen = null;
+ _lastAspect = 0;
+}
diff --git a/lib/video-cache-utils.ts b/lib/video-cache-utils.ts
index 44a7985..48def90 100644
--- a/lib/video-cache-utils.ts
+++ b/lib/video-cache-utils.ts
@@ -1,12 +1,5 @@
-/**
- * Utility functions to check for any cached video (recorded or uploaded)
- */
-
import { getUploadedVideo } from "./video-upload-cache";
-/**
- * Check if a recorded video exists in IndexedDB
- */
async function hasRecordedVideo(): Promise<boolean> {
try {
const dbName = "openvidDB";
@@ -49,16 +42,11 @@ async function hasRecordedVideo(): Promise<boolean> {
}
}
-/**
- * Check if any video exists (recorded OR uploaded)
- */
export async function hasAnyVideo(): Promise<boolean> {
try {
- // Check uploaded videos first (faster)
const uploadedVideo = await getUploadedVideo();
if (uploadedVideo) return true;
- // If no uploaded video, check recorded video
return await hasRecordedVideo();
} catch (error) {
console.error("Error checking for any video:", error);
diff --git a/lib/video-upload-cache.ts b/lib/video-upload-cache.ts
index 9aa8b1f..bec5b8c 100644
--- a/lib/video-upload-cache.ts
+++ b/lib/video-upload-cache.ts
@@ -17,9 +17,6 @@ export interface CachedUploadedVideo {
let dbInstance: IDBDatabase | null = null;
-/**
- * Open IndexedDB connection
- */
async function openDB(): Promise<IDBDatabase> {
if (dbInstance) return dbInstance;
@@ -42,18 +39,11 @@ async function openDB(): Promise<IDBDatabase> {
});
}
-/**
- * Calculate aspect ratio from dimensions
- * Always returns "auto" to use the actual video dimensions
- */
+
function calculateAspectRatio(_width: number, _height: number): string {
- // Always return "auto" so videos use their actual dimensions
return "auto";
}
-/**
- * Get video metadata from file
- */
async function getVideoMetadata(file: File): Promise<{
duration: number;
width: number;
@@ -72,7 +62,6 @@ async function getVideoMetadata(file: File): Promise<{
aspectRatio: calculateAspectRatio(video.videoWidth, video.videoHeight),
};
- // Cleanup
URL.revokeObjectURL(video.src);
resolve(metadata);
};
@@ -86,14 +75,10 @@ async function getVideoMetadata(file: File): Promise<{
});
}
-/**
- * Save uploaded video (replaces any existing video)
- */
export async function saveUploadedVideo(file: File): Promise<CachedUploadedVideo> {
try {
const db = await openDB();
- // Get video metadata
const metadata = await getVideoMetadata(file);
const data: CachedUploadedVideo = {
@@ -112,7 +97,6 @@ export async function saveUploadedVideo(file: File): Promise<CachedUploadedVideo
const transaction = db.transaction(STORE_NAME, "readwrite");
const store = transaction.objectStore(STORE_NAME);
- // Put will replace any existing video with the same key
const request = store.put(data);
request.onerror = () => reject(request.error);
@@ -124,9 +108,6 @@ export async function saveUploadedVideo(file: File): Promise<CachedUploadedVideo
}
}
-/**
- * Get the current uploaded video
- */
export async function getUploadedVideo(): Promise<CachedUploadedVideo | null> {
try {
const db = await openDB();
@@ -148,9 +129,6 @@ export async function getUploadedVideo(): Promise<CachedUploadedVideo | null> {
}
}
-/**
- * Delete the uploaded video
- */
export async function deleteUploadedVideo(): Promise<void> {
try {
const db = await openDB();
@@ -168,17 +146,11 @@ export async function deleteUploadedVideo(): Promise<void> {
}
}
-/**
- * Check if an uploaded video exists
- */
export async function hasUploadedVideo(): Promise<boolean> {
const video = await getUploadedVideo();
return video !== null;
}
-/**
- * Get uploaded video info without loading the blob
- */
export async function getUploadedVideoInfo(): Promise<{
fileName: string;
fileSize: number;
diff --git a/lib/video.utils.ts b/lib/video.utils.ts
index c24c0b8..75860c4 100644
--- a/lib/video.utils.ts
+++ b/lib/video.utils.ts
@@ -1,9 +1,5 @@
import { TIMELINE_ZOOM_SCALE } from './constants';
-/**
- * Espera a que un frame de video esté realmente disponible para captura
- * Usa requestVideoFrameCallback si está disponible (Chrome/Edge)
- */
export function waitForVideoFrame(video: HTMLVideoElement): Promise<void> {
return new Promise((resolve) => {
let resolved = false;
@@ -48,7 +44,7 @@ export async function ensureVideoReady(video: HTMLVideoElement): Promise<void> {
resolve();
};
video.addEventListener('canplay', onReady, { once: true });
- setTimeout(resolve, 3000); // Timeout máximo
+ setTimeout(resolve, 3000);
});
}
@@ -60,11 +56,7 @@ export async function ensureVideoReady(video: HTMLVideoElement): Promise<void> {
await new Promise<void>(resolve => setTimeout(resolve, 100));
}
-/**
- * Formatea segundos a MM:SS
- */
export function formatTime(time: number): string {
- // Validar que el tiempo sea un número válido
if (isNaN(time) || !isFinite(time) || time < 0) {
return '00:00';
}
@@ -73,9 +65,6 @@ export function formatTime(time: number): string {
return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}
-/**
- * Descarga un Blob como archivo
- */
export function downloadBlob(blob: Blob, filename: string): void {
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
@@ -87,11 +76,6 @@ export function downloadBlob(blob: Blob, filename: string): void {
URL.revokeObjectURL(url);
}
-/**
- * Calcula el multiplicador de zoom para el timeline
- * @param zoom - Nivel de zoom (1-10)
- * @returns Multiplicador de ancho del timeline
- */
export function getZoomMultiplier(zoom: number): number {
const rounded = Math.round(Math.max(1, Math.min(10, zoom)));
return TIMELINE_ZOOM_SCALE[rounded] ?? 1;
diff --git a/types/video.types.ts b/types/video.types.ts
index 69ab13b..e9338c8 100644
--- a/types/video.types.ts
+++ b/types/video.types.ts
@@ -14,8 +14,6 @@ export interface ExportSettings {
trim?: TrimSettings;
transparentBackground?: boolean;
muteOriginalAudio?: boolean;
- /** Whether the source video file actually contains an audio stream.
- * When false, FFmpeg audio mixing is skipped entirely even if muteOriginalAudio is false. */
videoHasAudioTrack?: boolean;
audioTracks?: Array<{
audioUrl: string;