Create professional demos and 3D mockups in seconds, directly in your browser
feat: enhance video export functionality and improve camera overlay dimensions
CristianOlivera1ded2adae4847
diff --git a/hooks/useVideoExport.ts b/hooks/useVideoExport.tsindex 12ea448..1b96c75 100644--- a/hooks/useVideoExport.ts+++ b/hooks/useVideoExport.ts@@ -8,7 +8,8 @@ import { QUALITY_SETTINGS, DEFAULT_EXPORT_FPS } from "@/lib/constants";import { ensureVideoReady, waitForVideoFrame, downloadBlob } from "@/lib/video.utils";import { FFmpeg } from "@ffmpeg/ffmpeg";import { toBlobURL } from "@ffmpeg/util";-import { blobToUint8Array, buildAtempoChain, canvasToBlobFast, getActiveClipAtTime } from "@/lib/ffmpeg.utils";+import { blobToUint8Array, buildAtempoChain, canvasToBlobFast, getActiveClipAtTime, resolveClipTrimStart } from "@/lib/ffmpeg.utils";+import type { VideoTrackClip } from "@/types/video-track.types";export type { ExportQuality, ExportSettings, ExportProgress };@@ -143,33 +144,21 @@ export function useVideoExport(try {if (settings.quality === "gif") {+ if (settings.videoClips && settings.videoClips.length > 1) {+ throw new Error("La exportación a GIF con varios clips en el timeline aún no está soportada. Exporta como MP4 o une los clips primero.");+ }await exportWithFFmpegGif(- video,- canvasHandle,- exportCanvas,- exportDuration,- trimStart,- fps,- targetWidth,- targetHeight,- setExportProgress,- cancellationRef.current,- speed+ video, canvasHandle, exportCanvas, exportDuration, trimStart, fps,+ targetWidth, targetHeight, setExportProgress, cancellationRef.current, speed,+ settings.videoClips);} else if (settings.quality === "webm-alpha" || settings.transparentBackground) {+ if (settings.videoClips && settings.videoClips.length > 1) {+ throw new Error("La exportación a WebM transparente con varios clips en el timeline aún no está soportada. Exporta como MP4 o une los clips primero.");+ }await exportWithFFmpegWebM(- video,- canvasHandle,- exportCanvas,- exportDuration,- trimStart,- fps,- targetWidth,- targetHeight,- setExportProgress,- cancellationRef.current,- speed,- settings+ video, canvasHandle, exportCanvas, exportDuration, trimStart, fps,+ targetWidth, targetHeight, setExportProgress, cancellationRef.current, speed, settings);} else {await exportWithMediabunnyAndAudio(@@ -262,6 +251,7 @@ async function exportWithMediabunny(setProgress: (p: ExportProgress) => void,cancellation: CancellationToken,speed: number = 1,+ sourceTrimStart: number = trimStart,): Promise<void> {if (cancellation.cancelled) {throw new Error("Export cancelled");@@ -313,30 +303,21 @@ async function exportWithMediabunny(await passOutput.start();video.pause();- video.currentTime = trimStart;+ video.currentTime = sourceTrimStart;await waitForVideoFrame(video);-- setProgress({- status: "encoding",- progress: 10,- message: `Starting encoding ${fps} fps...`,- });+ setProgress({ status: "encoding", progress: 10, message: `Starting encoding ${fps} fps...` });for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) {- if (cancellation.cancelled) {- await passOutput.cancel();- throw new Error("Export cancelled");- }+ if (cancellation.cancelled) { await passOutput.cancel(); throw new Error("Export cancelled"); }const outputTime = frameIndex / fps;const contentOffset = Math.min(outputTime * speed, duration - 0.001);const timelineTime = trimStart + contentOffset;await canvasHandle.drawFrame(true, timelineTime);-const nextIndex = frameIndex + 1;let nextFrameReady: Promise<void> | null = null;if (nextIndex < totalFrames) {const nextContentOffset = Math.min((nextIndex / fps) * speed, duration - 0.001);- video.currentTime = trimStart + nextContentOffset;+ video.currentTime = sourceTrimStart + nextContentOffset;nextFrameReady = waitForVideoFrame(video);}@@ -430,6 +411,7 @@ async function exportWithMediabunnyAndAudio(const clips = settings.videoClips || [];const clipBlobs = settings.videoClipBlobs;const clipAudioStates = settings.clipAudioStates;+ const sourceTrimStart = resolveClipTrimStart(clips, trimStart);let hasPerClipAudio = true;if (clipAudioStates) {@@ -446,7 +428,7 @@ async function exportWithMediabunnyAndAudio(if (!needsAudioMixing && !hasMultipleClips) {return exportWithMediabunny(video, canvasHandle, canvas, duration, trimStart, fps, bitrate, width, height,- setProgress, cancellation, speed+ setProgress, cancellation, speed, sourceTrimStart);}@@ -527,7 +509,7 @@ async function exportWithMediabunnyAndAudio(}video.currentTime = clips[0]?.trimStart || 0;} else {- video.currentTime = trimStart;+ video.currentTime = sourceTrimStart;}await waitForVideoFrame(video);@@ -568,7 +550,7 @@ async function exportWithMediabunnyAndAudio(const nextFrame = frameIndex + 1;if (nextFrame < totalFrames) {const nextContentOffset = Math.min((nextFrame / fps) * speed, duration - 0.001);- video.currentTime = trimStart + nextContentOffset;+ video.currentTime = sourceTrimStart + nextContentOffset;nextFrameReady = waitForVideoFrame(video);}}@@ -735,7 +717,7 @@ async function exportWithMediabunnyAndAudio(ffmpegArgs.push("-ss", String(clip.trimStart), "-t", String(clipTrimmedDuration), "-i", filename);}} else {- ffmpegArgs.push("-ss", String(trimStart), "-t", String(duration), "-i", "original.mp4");+ ffmpegArgs.push("-ss", String(sourceTrimStart), "-t", String(duration), "-i", "original.mp4");}}@@ -868,11 +850,12 @@ async function exportWithFFmpegGif(setProgress: (p: ExportProgress) => void,cancellation: CancellationToken,speed: number = 1,+ videoClips?: VideoTrackClip[],): Promise<void> {const ffmpeg = new FFmpeg();const outputDuration = duration / speed;const totalFrames = Math.ceil(outputDuration * fps);-+ const sourceTrimStart = resolveClipTrimStart(videoClips, trimStart);try {if (cancellation.cancelled) throw new Error("Export cancelled");@@ -888,21 +871,18 @@ async function exportWithFFmpegGif(setProgress({ status: "encoding", progress: 8, message: `Capturing ${totalFrames} frames...` });video.pause();- video.currentTime = trimStart;+ video.currentTime = sourceTrimStart;await waitForVideoFrame(video);-for (let i = 0; i < totalFrames; i++) {if (cancellation.cancelled) throw new Error("Export cancelled");-const outputTime = i / fps;const contentOffset = Math.min(outputTime * speed, duration - 0.001);const timelineTime = trimStart + contentOffset;await canvasHandle.drawFrame(true, timelineTime);-const nextI = i + 1;if (nextI < totalFrames) {const nextContentOffset = Math.min((nextI / fps) * speed, duration - 0.001);- video.currentTime = trimStart + nextContentOffset;+ video.currentTime = sourceTrimStart + nextContentOffset;}const blob = await canvasToBlobFast(canvas);@@ -981,35 +961,31 @@ async function exportWithFFmpegWebM(setProgress: (p: ExportProgress) => void,cancellation: CancellationToken,speed: number = 1,- _settings?: ExportSettings,+ settings?: ExportSettings,): Promise<void> {const ffmpeg = new FFmpeg();const outputDuration = duration / speed;const totalFrames = Math.ceil(outputDuration * fps);-+ const sourceTrimStart = resolveClipTrimStart(settings?.videoClips, trimStart);setProgress({ status: "preparing", progress: 3, message: "Loading WebM engine..." });-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"),});-video.pause();- video.currentTime = trimStart;+ video.currentTime = sourceTrimStart;await waitForVideoFrame(video);for (let i = 0; i < totalFrames; i++) {if (cancellation.cancelled) throw new Error("Export cancelled");-const outputTime = i / fps;const contentOffset = Math.min(outputTime * speed, duration - 0.001);const timelineTime = trimStart + contentOffset;await canvasHandle.drawFrame(true, timelineTime);-const nextI = i + 1;if (nextI < totalFrames) {const nextContentOffset = Math.min((nextI / fps) * speed, duration - 0.001);- video.currentTime = trimStart + nextContentOffset;+ video.currentTime = sourceTrimStart + nextContentOffset;}const blob = await new Promise<Blob>((resolve, reject) =>diff --git a/lib/camera-overlay.utils.ts b/lib/camera-overlay.utils.tsindex b6fb8d2..eb9e47b 100644--- a/lib/camera-overlay.utils.ts+++ b/lib/camera-overlay.utils.ts@@ -72,7 +72,7 @@ export async function drawCameraOverlayToCtx(ctx.clip();} else {const radius = cameraConfig.shape === "squircle"- ? Math.round(85 * sizeMultiplier)+ ? Math.round(65 * sizeMultiplier): Math.round(6 * sizeMultiplier);drawRoundedRect(ctx, drawX, drawY, size, size, radius);ctx.fill();diff --git a/lib/canvas.utils.ts b/lib/canvas.utils.tsindex 99d7802..d01f717 100644--- a/lib/canvas.utils.ts+++ b/lib/canvas.utils.ts@@ -145,7 +145,6 @@ export function applyCanvasBackground(}if (cssBackground.includes('conic-gradient')) {- // Parsear: conic-gradient(from {angle}deg at {x}% {y}%, {stops})const angleMatch = cssBackground.match(/from\s+(\d+)deg/);const positionMatch = cssBackground.match(/at\s+(\d+)%\s+(\d+)%/);@@ -220,28 +219,24 @@ export function calculateSmoothZoom(const isAdvancedZoom = (f: ZoomFragment) => f.enable3D || f.movementEnabled;const movementsFor = (fragmentId: string) => zoomMovements.filter(m => m.zoomFragmentId === fragmentId);- // Compute scale for a fragment at a given time, covering all 3 phases- // (entry, hold, exit) entirely WITHIN [startTime, endTime].const computeFragmentScale = (fragment: ZoomFragment, time: number): number => {const totalDuration = fragment.endTime - fragment.startTime;const transitionSec = Math.min(speedToTransitionMs(fragment.speed) / 1000, totalDuration / 2);const targetScale = zoomLevelToFactor(fragment.zoomLevel);const timeIntoFragment = time - fragment.startTime;- // Entry ramp [start, start+T]if (transitionSec > 0 && timeIntoFragment < transitionSec) {const progress = Math.min(1, Math.max(0, timeIntoFragment / transitionSec));return 1 + (targetScale - 1) * easeOutQuart(progress);}- // Exit ramp [end-T, end]const timeBeforeEnd = fragment.endTime - time;if (transitionSec > 0 && timeBeforeEnd < transitionSec) {- const progress = Math.min(1, Math.max(0, timeBeforeEnd / transitionSec));- return 1 + (targetScale - 1) * easeOutQuart(progress);+ const timeIntoExit = transitionSec - timeBeforeEnd;+ const progress = Math.min(1, Math.max(0, timeIntoExit / transitionSec));+ return targetScale - (targetScale - 1) * easeOutQuart(progress);}- // Holdreturn targetScale;};diff --git a/lib/ffmpeg.utils.ts b/lib/ffmpeg.utils.tsindex 8c72405..796474a 100644--- a/lib/ffmpeg.utils.ts+++ b/lib/ffmpeg.utils.ts@@ -22,6 +22,13 @@ export function getActiveClipAtTime(clips: VideoTrackClip[], timelineTime: numbereturn null;}+export function resolveClipTrimStart(clips: VideoTrackClip[] | undefined, fallbackTimelineStart: number): number {+ if (clips && clips.length === 1) {+ return clips[0].trimStart;+ }+ return fallbackTimelineStart;+}+export async function blobToUint8Array(blob: Blob): Promise<Uint8Array> {const buffer = await blob.arrayBuffer();return new Uint8Array(buffer);diff --git a/lib/iphone-duo/screen-material.ts b/lib/iphone-duo/screen-material.tsindex 6def937..d892243 100644--- a/lib/iphone-duo/screen-material.ts+++ b/lib/iphone-duo/screen-material.ts@@ -1,4 +1,3 @@-// Adapted from iphone-duo by Justin Levine (MIT). See ./LICENSE.import { Matrix3, Matrix4, ShaderMaterial, Vector2 } from 'three'export function createScreenMaterial(cover: boolean) {diff --git a/types/camera.types.ts b/types/camera.types.tsindex 192e0f9..e8ff675 100644--- a/types/camera.types.ts+++ b/types/camera.types.ts@@ -51,8 +51,8 @@ export const DEFAULT_CAMERA_CONFIG: CameraConfig = {enabled: false,deviceId: null,shape: "squircle",- size: 0.18,- position: { x: 0.88, y: 0.88 },+ size: 0.30,+ position: { x: 0.88, y: 0.8 },corner: "bottom-right",mirror: true,};diff --git a/types/control-panel.types.ts b/types/control-panel.types.tsindex 6bc4af1..8559787 100644--- a/types/control-panel.types.ts+++ b/types/control-panel.types.ts@@ -17,6 +17,7 @@ export interface ControlPanelProps {roundedCorners: number;shadows: number;selectedImageUrl: string;+ unsplashBgUrl?: string;backgroundColorConfig: BackgroundColorConfig | null;backgroundColorCss?: string;onBackgroundTabChange: (tab: BackgroundTab) => void;diff --git a/types/editor.types.ts b/types/editor.types.tsindex 7b4ece6..6968c1b 100644--- a/types/editor.types.ts+++ b/types/editor.types.ts@@ -97,10 +97,9 @@ export interface VideoCanvasProps {onElementSelect?: (id: string | null) => void;onElementDelete?: (id: string | string[]) => void;cameraUrl?: string | null;-+ cameraSourceUrl?: string | null;cameraConfig?: CameraConfig | null;onCameraConfigChange?: (partial: Partial<CameraConfig>) => void;-onCameraClick?: () => void;layersPanelToolbar?: React.ReactNode;textToolActive?: boolean;diff --git a/types/zoom.types.ts b/types/zoom.types.tsindex a336ef6..8a12979 100644--- a/types/zoom.types.ts+++ b/types/zoom.types.ts@@ -48,7 +48,6 @@ export function easeInOutQuart(t: number): number {return t < 0.5 ? 8 * t * t * t * t : 1 - Math.pow(-2 * t + 2, 4) / 2;}-export interface ZoomPhaseState {phase: 'entry' | 'hold' | 'exit';scale: number;