Skip to content

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

feat: update UI components and enhance media handling with new features and optimizations

CristianOlivera1db222de73d55
diff --git a/app/[locale]/(home)/page.tsx b/app/[locale]/(home)/page.tsx
index 84d272a..4825ed3 100644
--- a/app/[locale]/(home)/page.tsx
+++ b/app/[locale]/(home)/page.tsx
@@ -41,7 +41,7 @@ export default function Home() {
<div className="w-full sm:max-w-6xl mx-auto sm:px-6 mb-14">
<EditorPreview />
</div>
- {/* <BentoDemos /> */}
+ <BentoDemos />
</section>
</div>
</div>
diff --git a/app/components/common/Header.tsx b/app/components/common/Header.tsx
index fcf3382..42cee76 100644
--- a/app/components/common/Header.tsx
+++ b/app/components/common/Header.tsx
@@ -10,13 +10,14 @@ import { useTranslations } from "next-intl";
import { Icon } from "@iconify/react";
import { Button } from "@/components/ui/button";
import { useRecording } from "@/hooks/RecordingContext";
-import RecordingSetupDialog from "../ui/RecordingSetupDialog";
+import RecordingSetupDialog from "../ui/RecordingSetupDialog";
import { Alert, AlertTitle, AlertDescription } from "@/components/ui/alert";
+import GitHubStars from "@/components/ui/GitHubStars";
export default function Header() {
const t = useTranslations('header');
const tRecording = useTranslations('recording.steps');
-
+
const [isScrolled, setIsScrolled] = useState(false);
const [isMounted, setIsMounted] = useState(false);
@@ -45,9 +46,9 @@ export default function Header() {
return;
}
- const isMobile = typeof window !== "undefined" &&
+ const isMobile = typeof window !== "undefined" &&
(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || window.innerWidth < 768);
-
+
if (isMobile) {
setShowMobileAlert(true);
setTimeout(() => setShowMobileAlert(false), 5000);
@@ -81,13 +82,12 @@ export default function Header() {
<div className="hidden md:flex items-center gap-8 text-md font-medium text-neutral-400">
<a href="#docs" className="hover:text-white transition-colors">{t('docs')}</a>
- <a href="https://github.com/CristianOlivera1/openvid" target="_blank" rel="noopener noreferrer" className="hover:text-white transition-colors">{t('github')}</a>
<Link href="/donate" target="_blank" className="hover:text-white transition-colors">{t('donate')}</Link>
</div>
<div className="flex items-center gap-3 sm:gap-6">
- <Button
- variant="outline"
+ <Button
+ variant="outline"
onClick={handleHeaderAction}
disabled={isCountdown || isProcessing}
className={cn(
@@ -112,6 +112,7 @@ export default function Header() {
) : (
<LanguageSwitcher />
)}
+
<div className="block">
{!isMounted ? (
<div className="flex items-center gap-2 px-2 py-1">
@@ -129,6 +130,7 @@ export default function Header() {
<MobileMenu />
)}
</div>
+
</div>
</div>
@@ -143,10 +145,10 @@ export default function Header() {
)}
</header>
- <RecordingSetupDialog
- open={setupDialogOpen}
- onClose={() => setSetupDialogOpen(false)}
- onStart={(config) => startCountdown(config)}
+ <RecordingSetupDialog
+ open={setupDialogOpen}
+ onClose={() => setSetupDialogOpen(false)}
+ onStart={(config) => startCountdown(config)}
/>
</>
);
diff --git a/app/components/common/LanguageSwitcher.tsx b/app/components/common/LanguageSwitcher.tsx
index d3c1126..bf753b7 100644
--- a/app/components/common/LanguageSwitcher.tsx
+++ b/app/components/common/LanguageSwitcher.tsx
@@ -34,7 +34,7 @@ export function LanguageSwitcher() {
return (
<DropdownMenu.Root open={isOpen} onOpenChange={setIsOpen}>
<DropdownMenu.Trigger asChild>
- <Button variant="outline"
+ <Button variant="outline" className='text-xs'
disabled={isPending}
>
<Icon icon={currentLanguage.icon} width="18" height="18" />
diff --git a/app/components/ui/BentoDemos.tsx b/app/components/ui/BentoDemos.tsx
index d97f6cf..1909c09 100644
--- a/app/components/ui/BentoDemos.tsx
+++ b/app/components/ui/BentoDemos.tsx
@@ -4,35 +4,14 @@ import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
gsap.registerPlugin(ScrollTrigger);
-const bentoVideos = [
- {
- id: 1,
- src: "https://domare.hernandack.com/uploads/19bf07ca35f55af46ea6396865198c5c.mp4",
- className: "",
- },
- {
- id: 2,
- src: "https://www.w3schools.com/html/mov_bbb.mp4",
- className: "min-[690px]:col-[2/3] min-[690px]:row-span-2",
- },
- {
- id: 3,
- src: "https://domare.hernandack.com/uploads/19bf07ca35f55af46ea6396865198c5c.mp4",
- className:
- "min-[690px]:col-span-2 max-[690px]:col-[2/4] max-[690px]:row-[1/2] max-[470px]:col-auto max-[470px]:row-auto",
- },
- {
- id: 4,
- src: "https://www.w3schools.com/html/mov_bbb.mp4",
- className: "",
- },
- {
- id: 5,
- src: "/images/pages/demo.mp4",
- className: "min-[690px]:col-[3/5] min-[690px]:row-[2/3] max-[470px]:col-span-2",
- },
-];
+const bentoItems = [
+ { id: 1, src: "/images/pages/lovable.avif", className: "" },
+ { id: 2, src: "/images/pages/vegetative.avif", className: "min-[690px]:col-[2/3] min-[690px]:row-span-2" },
+ { id: 3, src: "/images/pages/demo2.mp4", className: "min-[690px]:col-span-2 max-[690px]:col-[2/4] max-[690px]:row-[1/2] max-[470px]:col-auto max-[470px]:row-auto" },
+ { id: 4, src: "/images/pages/crafter.avif", className: "" },
+ { id: 5, src: "/images/pages/demo.mp4", className: "min-[690px]:col-[3/5] min-[690px]:row-[2/3] max-[470px]:col-span-2" },
+];
export function BentoDemos() {
const containerRef = useRef<HTMLDivElement>(null);
@@ -56,45 +35,51 @@ export function BentoDemos() {
rotateX: 0,
filter: "blur(0px)",
duration: 1.4,
- stagger: {
- amount: 0.5,
- from: "start",
- },
+ stagger: { amount: 0.5, from: "start" },
ease: "expo.out",
scrollTrigger: {
trigger: containerRef.current,
start: "top 80%",
- toggleActions: "play none none none",
+ toggleActions: "play none none none",
},
}
);
}, containerRef);
-
return () => ctx.revert();
}, []);
+ // Función auxiliar para detectar si es un video
+ const isVideo = (src: string) => src.endsWith(".mp4") || src.endsWith(".webm");
+
return (
<section
ref={containerRef}
- className="grid place-content-center gap-[15px] p-[max(2vh,1.5rem)] w-full h-[80vh] min-h-[460px] grid-cols-[25%_30%_15%_25%] grid-rows-2 max-[690px]:h-[65vh] max-[470px]:grid-cols-2 max-[470px]:grid-rows-3 perspective-[1200px]"
+ className="grid place-content-center gap-4 p-[max(2vh,1.5rem)] w-full h-[80vh] min-h-115 grid-cols-[25%_30%_15%_25%] grid-rows-2 max-[690px]:h-[65vh] max-[470px]:grid-cols-2 max-[470px]:grid-rows-3 perspective-[1200px]"
>
- {bentoVideos.map((item) => (
+ {bentoItems.map((item) => (
<div
key={item.id}
className={`bento-card group relative rounded-[25px] overflow-hidden bg-zinc-900 border border-white/10 shadow-lg transition-all duration-500 ease-out hover:-translate-y-2 hover:shadow-[0_20px_40px_rgba(0,0,0,0.5)] hover:border-white/30 z-0 hover:z-10 ${item.className}`}
>
<div className="absolute inset-0 bg-black/20 z-10 transition-opacity duration-700 group-hover:opacity-0 pointer-events-none" />
-
- <video
- autoPlay
- loop
- muted
- playsInline
- className="w-full h-full object-cover transition-transform duration-700 ease-out group-hover:scale-110"
- >
- <source src={item.src} type="video/mp4" />
- Tu navegador no soporta el tag de video.
- </video>
+
+ {isVideo(item.src) ? (
+ <video
+ autoPlay
+ loop
+ muted
+ playsInline
+ className="w-full h-full object-cover transition-transform duration-700 ease-out group-hover:scale-110"
+ >
+ <source src={item.src} type="video/mp4" />
+ </video>
+ ) : (
+ <img
+ src={item.src}
+ alt={`Bento item ${item.id}`}
+ className="w-full h-full object-cover transition-transform duration-700 ease-out group-hover:scale-110"
+ />
+ )}
</div>
))}
</section>
diff --git a/app/components/ui/Hero.tsx b/app/components/ui/Hero.tsx
index 6bba424..e55b294 100644
--- a/app/components/ui/Hero.tsx
+++ b/app/components/ui/Hero.tsx
@@ -6,6 +6,7 @@ import { saveUploadedVideo } from "@/lib/video-upload-cache";
import { saveUploadedImage } from "@/lib/image-upload-cache";
import { useLocale, useTranslations } from "next-intl";
import Link from "next/link";
+import GitHubBadge from "@/components/ui/GitHubStars";
interface HeroProps {
onVideoUpload?: (file: File) => void;
@@ -116,11 +117,20 @@ export default function Hero({ onVideoUpload, onPhotoUpload }: HeroProps) {
return (
<>
<h1 className="animate-reveal text-5xl md:text-7xl font-semibold text-white tracking-tight mb-6 leading-[1.1] drop-shadow-[1.2px_1.2px_100.2px_rgba(183,203,248,1)]">
+ <div
+ className={`absolute h-auto shadow-2xl transition-all ${locale === "es"
+ ? "-top-16 sm:-top-4 lg:top-0 xl:top-3 left-14 -rotate-14"
+ : "left-16 -top-16 sm:top-0 xl:top-3 sm:-left-6 -rotate-14"
+ }`}
+ >
+ <GitHubBadge />
+ </div>
+
<img
src="/svg/version.svg"
alt="Version"
aria-hidden="true"
- className={`absolute h-auto shadow-2xl transition-all ${locale === 'es' ? "-top-8 sm:-top-4 lg:top-0 xl:top-4 left-0 -rotate-10 sm:left-26" : "-top-8 sm:top-0 xl:top-4 sm:left-10 -rotate-10" } w-16 sm:w-18`}
+ className={`absolute h-auto shadow-2xl transition-all ${locale === 'es' ? "-top-8 sm:-top-4 lg:top-0 xl:top-2 left-0 -rotate-10 sm:left-30" : "-top-8 sm:top-0 xl:top-2 sm:left-10 -rotate-10"} w-16 sm:w-18`}
/>
{t.rich("title", {
screen: (chunks) => (
diff --git a/app/components/ui/HeroScrollMask.tsx b/app/components/ui/HeroScrollMask.tsx
index 7ec26c0..b565541 100644
--- a/app/components/ui/HeroScrollMask.tsx
+++ b/app/components/ui/HeroScrollMask.tsx
@@ -29,8 +29,8 @@ export function HeroScrollMask() {
const t = useTranslations('demo');
const pinContainerRef = useRef<HTMLDivElement>(null);
const brandRef = useRef<HTMLSpanElement>(null);
- const videoRef = useRef<HTMLVideoElement>(null);
-
+ const videoRef = useRef<HTMLVideoElement>(null); // <- Vuelve a ser HTMLVideoElement
+ const containerRef = useRef<HTMLDivElement>(null);
const textContainerRef = useRef<HTMLDivElement>(null);
const [featureIndex, setFeatureIndex] = useState(0);
@@ -52,7 +52,15 @@ export function HeroScrollMask() {
const conditions = context.conditions as { isMobile: boolean; isDesktop: boolean } | undefined;
const isMobile = !!conditions?.isMobile;
const timeline = gsap.timeline({ defaults: { ease: "none" } });
+ timeline.set(containerRef.current, { visibility: "visible" }, 2.5);
+ // 2. Animamos la opacidad del video (como lo tenías originalmente)
+ timeline.fromTo(
+ videoRef.current,
+ { opacity: 0, scale: 1.1 },
+ { opacity: 1, duration: 0.2, scale: 1.1, ease: "power3.inOut" },
+ 2.5
+ );
timeline.to(
".floating-image",
{
@@ -157,7 +165,7 @@ export function HeroScrollMask() {
<div
ref={textContainerRef}
- className="absolute top-2 right-2 sm:top-6 sm:right-6 md:top-22 md:right-8 z-40 pointer-events-none select-none opacity-0"
+ className="absolute top-2 right-2 sm:top-2 sm:right-6 md:top-14 md:right-8 z-40 pointer-events-none select-none opacity-0"
>
<div className="bg-black/40 backdrop-blur-xl border border-white/20 rounded-xl md:rounded-2xl px-1 py-1 md:px-6 md:py-4 shadow-[0_20px_50px_rgba(0,0,0,0.5)] flex flex-col items-end min-w-45 sm:min-w-65 md:min-w-[320px]">
<div className="h-2 md:h-6 w-full flex items-center justify-end overflow-hidden px-1">
@@ -200,18 +208,22 @@ export function HeroScrollMask() {
<path d="M503.501 20.1523C500.655 10.8349 505.164 2.46105 513.757 0.411426C522.202 -1.60279 528.731 3.9868 528.028 12.6294C527.577 18.1794 523.214 23.1626 517.215 24.9798C511.545 26.6973 507.717 25.4373 503.501 20.1523Z" />
</svg>
</span>
- <div className="absolute inset-0 w-full h-full z-10 overflow-hidden flex flex-col justify-center">
- <div className="absolute inset-0 z-20 bg-linear-to-b from-transparent from-90% to-[#0C0C0D] pointer-events-none" />
+ <div
+ ref={containerRef}
+ className="absolute inset-0 w-full h-full z-10 overflow-hidden flex flex-col justify-center items-center bg-black invisible"
+ >
<video
ref={videoRef}
autoPlay
loop
muted
playsInline
- className="w-full h-auto max-h-full object-contain"
+ className="w-full max-w-370 h-auto max-h-full object-contain"
>
- <source src="/images/pages/demo.mp4" type="video/mp4" />
+ <source src="/images/pages/demo-scroll.mp4" type="video/mp4" />
</video>
+
+ <div className="absolute bottom-0 left-0 right-0 h-40 z-20 bg-linear-to-t from-[#0B0B0B] via-[#0B0B0B]/80 to-transparent pointer-events-none" />
</div>
</h2>
diff --git a/components/ui/GitHubStars.tsx b/components/ui/GitHubStars.tsx
new file mode 100644
index 0000000..568d011
--- /dev/null
+++ b/components/ui/GitHubStars.tsx
@@ -0,0 +1,32 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { Icon } from "@iconify/react";
+
+export default function GitHubBadge() {
+ const [stars, setStars] = useState<number | null>(null);
+
+ useEffect(() => {
+ fetch("https://api.github.com/repos/CristianOlivera1/openvid")
+ .then((res) => res.json())
+ .then((data) => setStars(data.stargazers_count))
+ .catch(() => setStars(null));
+ }, []);
+
+ return (
+ <a
+ href="https://github.com/CristianOlivera1/openvid"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="flex flex-col items-center gap-1 p-2 text-white/70 hover:text-white transition-colors"
+ aria-label="GitHub Repository"
+ >
+ <Icon icon="mdi:github" width="28" height="28" />
+
+ <div className="flex items-center gap-1 px-2 py-1 mt-1 text-xs rounded-md bg-gradient-to-r from-yellow-400 to-yellow-600 text-black font-semibold shadow-md">
+ <Icon icon="mdi:star" width="12" height="12" />
+ <span>{stars ?? "—"}</span>
+ </div>
+ </a>
+ );
+}
diff --git a/hooks/useVideoExport.ts b/hooks/useVideoExport.ts
index 045e6b8..9624004 100644
--- a/hooks/useVideoExport.ts
+++ b/hooks/useVideoExport.ts
@@ -12,46 +12,10 @@ 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;
}
-// Helper: find which clip is active at a given timeline time
function getActiveClipAtTime(clips: VideoTrackClip[], timelineTime: number): { clip: VideoTrackClip; clipTime: number } | null {
for (const clip of clips) {
const clipDuration = clip.trimEnd - clip.trimStart;
@@ -88,11 +52,13 @@ 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;
@@ -109,6 +75,7 @@ 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",
@@ -140,6 +107,7 @@ export function useVideoExport(
message: "Preparando video...",
});
+ // Asegurar que el video esté completamente listo
await ensureVideoReady(video);
if (cancellationRef.current.cancelled) {
@@ -152,37 +120,46 @@ 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;
@@ -233,16 +210,19 @@ 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",
@@ -258,12 +238,15 @@ 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",
@@ -291,15 +274,19 @@ 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);
- const ffmpegReady = !_ffmpegSingleton?.loaded;
- if (ffmpegReady) {
- setProgress({ status: "preparing", progress: 3, message: "Cargando motor WebM..." });
- }
- const ffmpeg = await preloadFFmpeg();
+ 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"),
+ });
video.pause();
video.currentTime = trimStart;
@@ -308,15 +295,21 @@ 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);
}
- const pamData = canvasToRawPam(canvas);
- await ffmpeg.writeFile(`frame${String(i).padStart(5, "0")}.pam`, pamData);
+ // 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);
if (i % 10 === 0 || i === totalFrames - 1) {
setProgress({
@@ -326,29 +319,31 @@ async function exportWithFFmpegWebM(
});
}
+ // Await next frame — partially decoded by now
if (nextI < totalFrames) {
await waitForVideoFrame(video);
}
}
- setProgress({ status: "finalizing", progress: 70, message: "[Paso 2/2] Iniciando codificación VP8..." });
-
- const onProgress = ({ progress }: { progress: number }) => {
+ // Actualizar progreso durante la codificación VP8
+ ffmpeg.on("progress", ({ progress }) => {
if (progress > 0) {
+ const encodingProgress = 70 + Math.round(progress * 20);
setProgress({
status: "finalizing",
- progress: Math.min(70 + Math.round(progress * 20), 90),
+ progress: Math.min(encodingProgress, 90),
message: `[Paso 2/2] Codificando VP8 con transparencia...`,
});
}
- };
- ffmpeg.on("progress", onProgress);
+ });
+
+ setProgress({ status: "finalizing", progress: 70, message: "[Paso 2/2] Iniciando codificación VP8..." });
try {
await ffmpeg.exec([
"-f", "image2",
"-framerate", String(fps),
- "-i", "frame%05d.pam",
+ "-i", "frame%05d.png",
"-c:v", "libvpx",
"-auto-alt-ref", "0",
"-b:v", "1M",
@@ -356,10 +351,10 @@ async function exportWithFFmpegWebM(
"output.webm",
]);
} finally {
- ffmpeg.off("progress", onProgress);
+ // Limpiar frames independientemente del resultado
try {
for (let i = 0; i < totalFrames; i++) {
- await ffmpeg.deleteFile(`frame${String(i).padStart(5, "0")}.pam`);
+ await ffmpeg.deleteFile(`frame${String(i).padStart(5, "0")}.png`);
}
} catch { /* ignorar errores de limpieza */ }
}
@@ -389,6 +384,7 @@ async function exportWithMediabunny(
setProgress: (p: ExportProgress) => void,
cancellation: CancellationToken
): Promise<void> {
+ // Verificar cancelación
if (cancellation.cancelled) {
throw new Error("Exportación cancelada");
}
@@ -420,10 +416,12 @@ 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");
@@ -431,9 +429,11 @@ 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);
@@ -448,11 +448,13 @@ 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");
}
@@ -465,6 +467,7 @@ async function exportWithMediabunny(
await output.finalize();
+ // Verificar una última vez antes de descargar
if (cancellation.cancelled) {
throw new Error("Exportación cancelada");
}
@@ -507,14 +510,18 @@ 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,
@@ -522,8 +529,7 @@ async function exportWithMediabunnyAndAudio(
);
}
- const ffmpegPreload = needsAudioMixing ? preloadFFmpeg().catch(() => null) : null;
-
+ // Verificar cancelación
if (cancellation.cancelled) {
throw new Error("Exportación cancelada");
}
@@ -537,6 +543,7 @@ 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",
@@ -557,9 +564,12 @@ 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) {
@@ -589,12 +599,14 @@ 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) {
@@ -609,14 +621,17 @@ 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) {
@@ -635,6 +650,7 @@ 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) {
@@ -662,38 +678,47 @@ 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: "Mezclando audio...",
+ 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"),
+ });
+
+ // 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) {
@@ -701,6 +726,8 @@ 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",
@@ -709,6 +736,7 @@ async function exportWithMediabunnyAndAudio(
]);
hasSourceAudio = true;
} catch {
+ // No tiene stream de audio
hasSourceAudio = false;
await ffmpeg.deleteFile("original.mp4").catch(() => { });
}
@@ -721,8 +749,10 @@ 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;
@@ -749,20 +779,25 @@ 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}];`;
@@ -770,6 +805,7 @@ async function exportWithMediabunnyAndAudio(
inputIndex++;
}
+ // Add audio tracks to mix
for (const audioTrackFile of audioTracks) {
const { track } = audioTrackFile;
const trackVolume = track.volume * (settings.masterVolume ?? 1);
@@ -782,9 +818,11 @@ 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;
@@ -797,7 +835,8 @@ async function exportWithMediabunnyAndAudio(
ffmpegArgs.push("-c:v", "copy", "-an", "output.mp4");
}
- const onAudioProgress = ({ progress }: { progress: number }) => {
+ // Track FFmpeg progress
+ ffmpeg.on("progress", ({ progress }) => {
if (progress > 0) {
const mixProgress = 70 + Math.round(progress * 25);
setProgress({
@@ -806,13 +845,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",
@@ -820,8 +859,6 @@ async function exportWithMediabunnyAndAudio(
message: "¡Exportación completada (sin mezcla de audio)!",
});
return;
- } finally {
- ffmpeg.off("progress", onAudioProgress);
}
setProgress({
@@ -833,6 +870,7 @@ 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");
@@ -850,6 +888,7 @@ 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({
@@ -890,17 +929,22 @@ async function exportWithFFmpegGif(
setProgress: (p: ExportProgress) => void,
cancellation: CancellationToken
): Promise<void> {
+ const ffmpeg = new FFmpeg();
const totalFrames = Math.ceil(duration * fps);
- const ffmpegReady = !_ffmpegSingleton?.loaded;
- if (ffmpegReady) {
- setProgress({ status: "preparing", progress: 3, message: "Cargando motor de exportación GIF..." });
- }
- const ffmpeg = await preloadFFmpeg();
-
try {
if (cancellation.cancelled) throw new Error("Exportación cancelada");
+ setProgress({ status: "preparing", progress: 3, message: "Cargando motor de exportación GIF..." });
+
+ 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
+ });
+
setProgress({ status: "encoding", progress: 8, message: `Capturando ${totalFrames} frames...` });
video.pause();
@@ -910,13 +954,16 @@ 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);
@@ -930,6 +977,7 @@ async function exportWithFFmpegGif(
});
}
+ // Await next frame — partially decoded by now
if (nextI < totalFrames) {
await waitForVideoFrame(video);
}