Skip to content

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

feat: enhance video export functionality with audio mixing and improved canvas handling

CristianOlivera1f1b0688e7c50
diff --git a/app/[locale]/(editor)/editor/page.tsx b/app/[locale]/(editor)/editor/page.tsx
index c15d4c9..b58c5a1 100644
--- a/app/[locale]/(editor)/editor/page.tsx
+++ b/app/[locale]/(editor)/editor/page.tsx
@@ -2878,9 +2878,14 @@ export default function Editor() {
setIsPlaying(false);
justEndedRef.current = true;
const endTime = trimRange.end > 0 ? trimRange.end : videoDuration;
+ syncAudioPlayback(endTime, false);
setCurrentTime(endTime);
- setTimeout(() => { justEndedRef.current = false; }, 300);
- }, [trimRange.end, videoDuration]);
+ setTimeout(() => {
+ justEndedRef.current = false;
+ }, 300);
+ }, [trimRange.end, videoDuration, syncAudioPlayback]);
+
+
const layersPanelToolbar = useMemo(() => (
<EditorTopBar
diff --git a/app/components/ui/editor/VideoCanvas.tsx b/app/components/ui/editor/VideoCanvas.tsx
index 2561393..f7063e5 100644
--- a/app/components/ui/editor/VideoCanvas.tsx
+++ b/app/components/ui/editor/VideoCanvas.tsx
@@ -258,6 +258,9 @@ function VideoCanvasInner({
const maskCompositeCanvasRef = useRef<HTMLCanvasElement | null>(null);
const wallpaperImageRef = useRef<HTMLImageElement | null>(null);
const customImageRef = useRef<HTMLImageElement | null>(null);
+ const videoMaskContentCanvasRef = useRef<HTMLCanvasElement | null>(null);
+ const videoMaskAlphaCacheRef = useRef<{ key: string; canvas: HTMLCanvasElement } | null>(null);
+ const shadowCacheRef = useRef<{ key: string; canvas: HTMLCanvasElement; offsetX: number; offsetY: number } | null>(null);
const exportDimensions = useMemo(() => {
if ((aspectRatio === "auto" || aspectRatio === "custom") && customAspectRatio) {
@@ -1515,13 +1518,27 @@ function VideoCanvasInner({
// Shadow
if (shadows > 0 && !SELF_SHADOWING_MOCKUPS.includes(mockupId)) {
+ const shadowKey = `${containerWidth.toFixed(1)}x${containerHeight.toFixed(1)}|${scaledRadius.toFixed(1)}|${scaledShadowBlur.toFixed(1)}`;
+ let cached = shadowCacheRef.current;
+ if (!cached || cached.key !== shadowKey) {
+ const margin = Math.ceil(scaledShadowBlur * 3 + scaledShadowBlur * 0.3 + 8);
+ const buf = document.createElement('canvas');
+ buf.width = Math.ceil(containerWidth) + margin * 2;
+ buf.height = Math.ceil(containerHeight) + margin * 2;
+ const bctx = buf.getContext('2d');
+ if (bctx) {
+ bctx.shadowColor = 'rgba(0, 0, 0, 1)';
+ bctx.shadowBlur = scaledShadowBlur;
+ bctx.shadowOffsetY = scaledShadowBlur * 0.3;
+ bctx.fillStyle = 'black';
+ drawRoundedRect(bctx, margin, margin, containerWidth, containerHeight, scaledRadius);
+ bctx.fill();
+ }
+ cached = { key: shadowKey, canvas: buf, offsetX: margin, offsetY: margin };
+ shadowCacheRef.current = cached;
+ }
c.save();
- c.shadowColor = 'rgba(0, 0, 0, 1)';
- c.shadowBlur = scaledShadowBlur;
- c.shadowOffsetY = scaledShadowBlur * 0.3;
- c.fillStyle = 'black';
- drawRoundedRect(c, containerX, containerY, containerWidth, containerHeight, scaledRadius);
- c.fill();
+ c.drawImage(cached.canvas, containerX - cached.offsetX, containerY - cached.offsetY);
c.restore();
}
@@ -1749,70 +1766,103 @@ function VideoCanvasInner({
));
if (hasVideoMask) {
- const videoLayer = document.createElement('canvas');
- videoLayer.width = canvasWidth;
- videoLayer.height = canvasHeight;
+ let videoLayer = videoMaskContentCanvasRef.current;
+ if (!videoLayer) {
+ videoLayer = document.createElement('canvas');
+ videoMaskContentCanvasRef.current = videoLayer;
+ }
+ if (videoLayer.width !== canvasWidth || videoLayer.height !== canvasHeight) {
+ videoLayer.width = canvasWidth;
+ videoLayer.height = canvasHeight;
+ }
const vlCtx = videoLayer.getContext('2d', canvasCtxOptions);
if (vlCtx) {
+ vlCtx.setTransform(1, 0, 0, 1, 0, 0);
+ vlCtx.clearRect(0, 0, canvasWidth, canvasHeight);
+ vlCtx.globalCompositeOperation = 'source-over';
vlCtx.imageSmoothingEnabled = true;
vlCtx.imageSmoothingQuality = 'high';
if (!imagePhoneActive) {
drawMockupAndMedia(vlCtx, containerX, containerY, containerWidth, containerHeight, video!, false, false);
}
- vlCtx.globalCompositeOperation = 'destination-in';
const vm = videoMaskConfig!;
const [cX, cY, cW, cH] = [containerX, containerY, containerWidth, containerHeight];
-
- if (vm.top) {
- const g = vlCtx.createLinearGradient(cX, cY, cX, cY + cH);
- g.addColorStop(0, 'transparent');
- g.addColorStop(vm.top.from / 100, 'transparent');
- g.addColorStop((vm.top.to ?? 100) / 100, 'black');
- vlCtx.fillStyle = g;
- vlCtx.fillRect(0, 0, canvasWidth, canvasHeight);
- }
- if (vm.bottom) {
- const g = vlCtx.createLinearGradient(cX, cY + cH, cX, cY);
- g.addColorStop(0, 'transparent');
- g.addColorStop(vm.bottom.from / 100, 'transparent');
- g.addColorStop((vm.bottom.to ?? 100) / 100, 'black');
- vlCtx.fillStyle = g;
- vlCtx.fillRect(0, 0, canvasWidth, canvasHeight);
- }
- if (vm.left) {
- const g = vlCtx.createLinearGradient(cX, cY, cX + cW, cY);
- g.addColorStop(0, 'transparent');
- g.addColorStop(vm.left.from / 100, 'transparent');
- g.addColorStop((vm.left.to ?? 100) / 100, 'black');
- vlCtx.fillStyle = g;
- vlCtx.fillRect(0, 0, canvasWidth, canvasHeight);
- }
- if (vm.right) {
- const g = vlCtx.createLinearGradient(cX + cW, cY, cX, cY);
- g.addColorStop(0, 'transparent');
- g.addColorStop(vm.right.from / 100, 'transparent');
- g.addColorStop((vm.right.to ?? 100) / 100, 'black');
- vlCtx.fillStyle = g;
- vlCtx.fillRect(0, 0, canvasWidth, canvasHeight);
- }
- if (vm.angle !== undefined) {
- const angleRad = (vm.angle * Math.PI) / 180;
- const cx2 = cX + cW / 2;
- const cy2 = cY + cH / 2;
- const diag = Math.sqrt(cW * cW + cH * cH) / 2;
- const g = vlCtx.createLinearGradient(
- cx2 - Math.cos(angleRad) * diag, cy2 - Math.sin(angleRad) * diag,
- cx2 + Math.cos(angleRad) * diag, cy2 + Math.sin(angleRad) * diag
- );
- g.addColorStop(0, 'transparent');
- g.addColorStop((vm.angleFrom ?? 0) / 100, 'transparent');
- g.addColorStop((vm.angleTo ?? 100) / 100, 'black');
- vlCtx.fillStyle = g;
- vlCtx.fillRect(0, 0, canvasWidth, canvasHeight);
+ const maskKey = [
+ canvasWidth, canvasHeight, cX.toFixed(1), cY.toFixed(1), cW.toFixed(1), cH.toFixed(1),
+ vm.top ? `t${vm.top.from}-${vm.top.to ?? 100}` : '',
+ vm.bottom ? `b${vm.bottom.from}-${vm.bottom.to ?? 100}` : '',
+ vm.left ? `l${vm.left.from}-${vm.left.to ?? 100}` : '',
+ vm.right ? `r${vm.right.from}-${vm.right.to ?? 100}` : '',
+ vm.angle !== undefined ? `a${vm.angle}-${vm.angleFrom ?? 0}-${vm.angleTo ?? 100}` : '',
+ ].join('|');
+
+ let alphaCache = videoMaskAlphaCacheRef.current;
+ if (!alphaCache || alphaCache.key !== maskKey) {
+ const alphaCanvas = document.createElement('canvas');
+ alphaCanvas.width = canvasWidth;
+ alphaCanvas.height = canvasHeight;
+ const aCtx = alphaCanvas.getContext('2d');
+ if (aCtx) {
+ aCtx.fillStyle = 'black';
+ aCtx.fillRect(0, 0, canvasWidth, canvasHeight);
+ aCtx.globalCompositeOperation = 'destination-in';
+ if (vm.top) {
+ const g = aCtx.createLinearGradient(cX, cY, cX, cY + cH);
+ g.addColorStop(0, 'transparent');
+ g.addColorStop(vm.top.from / 100, 'transparent');
+ g.addColorStop((vm.top.to ?? 100) / 100, 'black');
+ aCtx.fillStyle = g;
+ aCtx.fillRect(0, 0, canvasWidth, canvasHeight);
+ }
+ if (vm.bottom) {
+ const g = aCtx.createLinearGradient(cX, cY + cH, cX, cY);
+ g.addColorStop(0, 'transparent');
+ g.addColorStop(vm.bottom.from / 100, 'transparent');
+ g.addColorStop((vm.bottom.to ?? 100) / 100, 'black');
+ aCtx.fillStyle = g;
+ aCtx.fillRect(0, 0, canvasWidth, canvasHeight);
+ }
+ if (vm.left) {
+ const g = aCtx.createLinearGradient(cX, cY, cX + cW, cY);
+ g.addColorStop(0, 'transparent');
+ g.addColorStop(vm.left.from / 100, 'transparent');
+ g.addColorStop((vm.left.to ?? 100) / 100, 'black');
+ aCtx.fillStyle = g;
+ aCtx.fillRect(0, 0, canvasWidth, canvasHeight);
+ }
+ if (vm.right) {
+ const g = aCtx.createLinearGradient(cX + cW, cY, cX, cY);
+ g.addColorStop(0, 'transparent');
+ g.addColorStop(vm.right.from / 100, 'transparent');
+ g.addColorStop((vm.right.to ?? 100) / 100, 'black');
+ aCtx.fillStyle = g;
+ aCtx.fillRect(0, 0, canvasWidth, canvasHeight);
+ }
+ if (vm.angle !== undefined) {
+ const angleRad = (vm.angle * Math.PI) / 180;
+ const cx2 = cX + cW / 2;
+ const cy2 = cY + cH / 2;
+ const diag = Math.sqrt(cW * cW + cH * cH) / 2;
+ const g = aCtx.createLinearGradient(
+ cx2 - Math.cos(angleRad) * diag, cy2 - Math.sin(angleRad) * diag,
+ cx2 + Math.cos(angleRad) * diag, cy2 + Math.sin(angleRad) * diag
+ );
+ g.addColorStop(0, 'transparent');
+ g.addColorStop((vm.angleFrom ?? 0) / 100, 'transparent');
+ g.addColorStop((vm.angleTo ?? 100) / 100, 'black');
+ aCtx.fillStyle = g;
+ aCtx.fillRect(0, 0, canvasWidth, canvasHeight);
+ }
+ }
+ alphaCache = { key: maskKey, canvas: alphaCanvas };
+ videoMaskAlphaCacheRef.current = alphaCache;
}
- // Composite masked layer to main canvas with zoom applied
+ vlCtx.globalCompositeOperation = 'destination-in';
+ vlCtx.drawImage(alphaCache.canvas, 0, 0);
+ vlCtx.globalCompositeOperation = 'source-over';
+
ctx.save();
applyVideoZoom(ctx);
ctx.drawImage(videoLayer, 0, 0);
@@ -1919,7 +1969,7 @@ function VideoCanvasInner({
c.shadowOffsetX = 0;
c.shadowOffsetY = 18 * imagePhoneShadow * pxScale;
}
-
+
drawMaskedImage(c, phoneGL, baseCx - baseW / 2, baseCy - baseH / 2, baseW, baseH, effectivePhoneMaskConfig);
if (imagePhoneShadow > 0.01) {
diff --git a/hooks/useScreenRecording.ts b/hooks/useScreenRecording.ts
index adca0e2..e720cff 100644
--- a/hooks/useScreenRecording.ts
+++ b/hooks/useScreenRecording.ts
@@ -1,17 +1,13 @@
"use client";
-
import { useState, useCallback, useRef, useEffect } from "react";
import { useRouter, usePathname } from "@/navigation";
-import type { RecordingState, RecordingResult, VideoData } from "@/types";
+import type { RecordingState, RecordingResult, VideoData, RecordingContextType } from "@/types";
import type { CameraConfig, RecordingSetupConfig } from "@/types/camera.types";
-import {
- DEFAULT_RECORDING_SETUP,
- requestCameraStream,
- requestMicrophoneStream,
-} from "@/types/camera.types";
+import { DEFAULT_RECORDING_SETUP, requestCameraStream, requestMicrophoneStream } from "@/types/camera.types";
import { clearAllThumbnailCache } from "@/lib/thumbnail-cache";
+import { Input, Output, Mp4OutputFormat, BufferTarget, Conversion, ALL_FORMATS, BufferSource } from "mediabunny";
-export type { RecordingState, RecordingResult, VideoData };
+export type { RecordingState, RecordingResult, VideoData, RecordingContextType };
function generateVideoId(): string {
return `vid_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
@@ -33,7 +29,9 @@ async function cleanupOldRecording(db: IDBDatabase): Promise<void> {
};
transaction.oncomplete = () => resolve();
transaction.onerror = () => resolve();
- } catch { resolve(); }
+ } catch {
+ resolve();
+ }
});
}
@@ -42,7 +40,6 @@ async function getDB(): Promise<IDBDatabase> {
const dbName = "openvidDB";
const storeName = "videos";
const version = 2;
-
const request = indexedDB.open(dbName, version);
request.onupgradeneeded = (event) => {
@@ -64,15 +61,16 @@ async function getDB(): Promise<IDBDatabase> {
}
};
retryRequest.onsuccess = () => {
- cleanupOldRecording(retryRequest.result).catch(() => {});
+ cleanupOldRecording(retryRequest.result).catch(() => { });
resolve(retryRequest.result);
};
retryRequest.onerror = () => reject(retryRequest.error);
} else {
- cleanupOldRecording(db).catch(() => {});
+ cleanupOldRecording(db).catch(() => { });
resolve(db);
}
};
+
request.onerror = () => reject(request.error);
});
}
@@ -80,10 +78,7 @@ async function getDB(): Promise<IDBDatabase> {
async function saveVideoToIndexedDB(
blob: Blob,
duration: number,
- extras: {
- cameraBlob?: Blob | null;
- cameraConfig?: CameraConfig | null;
- } = {}
+ extras: { cameraBlob?: Blob | null; cameraConfig?: CameraConfig | null } = {}
): Promise<string> {
try {
await clearAllThumbnailCache();
@@ -98,7 +93,6 @@ async function saveVideoToIndexedDB(
const storeName = "videos";
const transaction = db.transaction([storeName], "readwrite");
const store = transaction.objectStore(storeName);
-
const videoData = {
blob,
duration,
@@ -110,12 +104,10 @@ async function saveVideoToIndexedDB(
};
const putRequest = store.put(videoData, "currentVideo");
-
putRequest.onsuccess = () => {
db.close();
resolve(videoId);
};
-
putRequest.onerror = () => {
db.close();
reject(putRequest.error);
@@ -151,13 +143,13 @@ export async function loadVideoFromIndexedDB(): Promise<{
getRequest.onsuccess = () => {
db.close();
const data = getRequest.result;
-
if (data) {
const url = URL.createObjectURL(data.blob);
const videoId = data.videoId || `vid_${data.timestamp || Date.now()}`;
const timestamp = data.timestamp || Date.now();
const cameraBlob: Blob | null = data.cameraBlob ?? null;
const cameraUrl = cameraBlob ? URL.createObjectURL(cameraBlob) : null;
+
resolve({
blob: data.blob,
duration: data.duration,
@@ -226,7 +218,6 @@ function pickSupportedMimeType(preferred: string[]): string | undefined {
try {
if (MediaRecorder.isTypeSupported(mimeType)) return mimeType;
} catch {
- // continue
}
}
return undefined;
@@ -239,7 +230,6 @@ export function useScreenRecording() {
const [recordingTime, setRecordingTime] = useState<number>(0);
const [cameraStream, setCameraStream] = useState<MediaStream | null>(null);
const [cameraConfig, setCameraConfig] = useState<CameraConfig | null>(null);
-
const router = useRouter();
const pathname = usePathname();
@@ -247,12 +237,10 @@ export function useScreenRecording() {
const cameraRecorderRef = useRef<MediaRecorder | null>(null);
const screenChunksRef = useRef<Blob[]>([]);
const cameraChunksRef = useRef<Blob[]>([]);
-
const screenStreamRef = useRef<MediaStream | null>(null);
const cameraStreamRef = useRef<MediaStream | null>(null);
const micStreamRef = useRef<MediaStream | null>(null);
const audioCtxRef = useRef<AudioContext | null>(null);
-
const startTimeRef = useRef<number>(0);
const originalTitleRef = useRef<string>("");
const stateRef = useRef<RecordingState>("idle");
@@ -328,16 +316,10 @@ export function useScreenRecording() {
}, []);
const stopRecording = useCallback(() => {
- if (
- screenRecorderRef.current &&
- screenRecorderRef.current.state !== "inactive"
- ) {
+ if (screenRecorderRef.current && screenRecorderRef.current.state !== "inactive") {
screenRecorderRef.current.stop();
}
- if (
- cameraRecorderRef.current &&
- cameraRecorderRef.current.state !== "inactive"
- ) {
+ if (cameraRecorderRef.current && cameraRecorderRef.current.state !== "inactive") {
cameraRecorderRef.current.stop();
}
}, []);
@@ -353,14 +335,13 @@ export function useScreenRecording() {
cameraChunksRef.current = [];
startTimeRef.current = Date.now();
- const screenMime =
- pickSupportedMimeType([
- "video/webm;codecs=vp9,opus",
- "video/webm;codecs=vp8,opus",
- "video/webm;codecs=vp9",
- "video/webm;codecs=vp8",
- "video/webm",
- ]) || undefined;
+ const screenMime = pickSupportedMimeType([
+ "video/webm;codecs=vp9,opus",
+ "video/webm;codecs=vp8,opus",
+ "video/webm;codecs=vp9",
+ "video/webm;codecs=vp8",
+ "video/webm",
+ ]) || undefined;
const screenRecorder = new MediaRecorder(
screenStream,
@@ -373,6 +354,7 @@ export function useScreenRecording() {
screenChunksRef.current.push(event.data);
}
};
+
screenRecorder.onerror = (event) => {
console.error("Error del MediaRecorder (pantalla):", event);
setError("Error durante la grabación");
@@ -383,12 +365,11 @@ export function useScreenRecording() {
let cameraRecorder: MediaRecorder | null = null;
if (camStream) {
- const camMime =
- pickSupportedMimeType([
- "video/webm;codecs=vp9",
- "video/webm;codecs=vp8",
- "video/webm",
- ]) || undefined;
+ const camMime = pickSupportedMimeType([
+ "video/webm;codecs=vp9",
+ "video/webm;codecs=vp8",
+ "video/webm",
+ ]) || undefined;
cameraRecorder = new MediaRecorder(
camStream,
@@ -416,11 +397,55 @@ export function useScreenRecording() {
cleanupStreams();
try {
- await saveVideoToIndexedDB(
- screenBlob || new Blob([], { type: "video/webm" }),
- duration,
- { cameraBlob, cameraConfig: cameraConfigRef.current }
- );
+ const rawScreenBlob = screenBlob || new Blob([], { type: screenMime || "video/webm" });
+
+ const arrayBuffer = await rawScreenBlob.arrayBuffer();
+ const uint8Array = new Uint8Array(arrayBuffer);
+
+ const source = new BufferSource(uint8Array);
+
+ const input = new Input({
+ source: source,
+ formats: ALL_FORMATS
+ });
+
+ const outputTarget = new BufferTarget();
+ const output = new Output({
+ format: new Mp4OutputFormat(),
+ target: outputTarget,
+ });
+
+ const conversion = await Conversion.init({
+ input,
+ output,
+ video: {
+ hardwareAcceleration: 'prefer-hardware',
+ keyFrameInterval: 2,
+ },
+ audio: {
+ codec: 'aac',
+ sampleRate: 48000,
+ numberOfChannels: 2,
+ }
+ });
+
+ if (!conversion.isValid) {
+ console.error("Pistas descartadas:", conversion.discardedTracks);
+ throw new Error("No se pudo iniciar la conversión del video.");
+ }
+
+ await conversion.execute();
+
+ if (!outputTarget.buffer) {
+ throw new Error("El buffer de salida es nulo. La conversión falló.");
+ }
+
+ const finalMp4Blob = new Blob([outputTarget.buffer], { type: 'video/mp4' });
+
+ await saveVideoToIndexedDB(finalMp4Blob, duration, {
+ cameraBlob,
+ cameraConfig: cameraConfigRef.current,
+ });
if (pathname === "/editor") {
window.location.reload();
@@ -428,15 +453,14 @@ export function useScreenRecording() {
router.push("/editor");
}
} catch (err) {
- console.error("Error al guardar video:", err);
+ console.error("Error al procesar el video con Mediabunny:", err);
setError("Error al procesar el video");
setState("idle");
restoreOriginals();
}
};
-
screenRecorder.onstop = () => {
- screenBlob = new Blob(screenChunksRef.current, { type: "video/webm" });
+ screenBlob = new Blob(screenChunksRef.current, { type: screenMime || "video/webm" });
pendingCount -= 1;
if (pendingCount <= 0) finalize();
else if (cameraRecorder && cameraRecorder.state !== "inactive") {
@@ -446,15 +470,10 @@ export function useScreenRecording() {
if (cameraRecorder) {
cameraRecorder.onstop = () => {
- cameraBlob = new Blob(cameraChunksRef.current, {
- type: "video/webm",
- });
+ cameraBlob = new Blob(cameraChunksRef.current, { type: "video/webm" });
pendingCount -= 1;
if (pendingCount <= 0) finalize();
- else if (
- screenRecorderRef.current &&
- screenRecorderRef.current.state !== "inactive"
- ) {
+ else if (screenRecorderRef.current && screenRecorderRef.current.state !== "inactive") {
screenRecorderRef.current.stop();
}
};
@@ -462,8 +481,6 @@ export function useScreenRecording() {
setState("recording");
- // Retrasar el inicio de la grabadora para que no aparesca el overlay de la cuenta regresiva
-
setTimeout(() => {
startTimeRef.current = Date.now();
screenRecorder.start(1000);
@@ -471,9 +488,7 @@ export function useScreenRecording() {
}, 300);
} catch (err) {
console.error("Error al iniciar grabación:", err);
- setError(
- err instanceof Error ? err.message : "No se pudo iniciar la grabación"
- );
+ setError(err instanceof Error ? err.message : "No se pudo iniciar la grabación");
setState("idle");
cleanupStreams();
restoreOriginals();
@@ -492,9 +507,7 @@ export function useScreenRecording() {
const screenStream = await navigator.mediaDevices.getDisplayMedia({
video: { displaySurface: "browser" },
- audio: setup.systemAudio
- ? { echoCancellation: true, noiseSuppression: true }
- : false,
+ audio: setup.systemAudio ? { echoCancellation: true, noiseSuppression: true } : false,
});
screenStreamRef.current = screenStream;
@@ -513,13 +526,10 @@ export function useScreenRecording() {
let micStream: MediaStream | null = null;
if (setup.microphone.enabled) {
try {
- micStream = await requestMicrophoneStream(
- setup.microphone.deviceId,
- {
- noiseSuppression: setup.microphone.noiseSuppression,
- echoCancellation: setup.microphone.echoCancellation,
- }
- );
+ micStream = await requestMicrophoneStream(setup.microphone.deviceId, {
+ noiseSuppression: setup.microphone.noiseSuppression,
+ echoCancellation: setup.microphone.echoCancellation,
+ });
micStreamRef.current = micStream;
} catch (err) {
console.warn("Micrófono denegado, continuando sin micrófono:", err);
@@ -529,30 +539,22 @@ export function useScreenRecording() {
const screenAudioTracks = screenStream.getAudioTracks();
const micAudioTracks = micStream ? micStream.getAudioTracks() : [];
const needsMixing = micAudioTracks.length > 0;
-
let finalScreenStream: MediaStream = screenStream;
+
if (needsMixing) {
try {
- const AudioCtx =
- window.AudioContext ||
- (window as unknown as { webkitAudioContext: typeof AudioContext })
- .webkitAudioContext;
+ const AudioCtx = window.AudioContext || (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;
const audioCtx = new AudioCtx();
audioCtxRef.current = audioCtx;
-
const destination = audioCtx.createMediaStreamDestination();
if (screenAudioTracks.length > 0) {
- const screenSource = audioCtx.createMediaStreamSource(
- new MediaStream(screenAudioTracks)
- );
+ const screenSource = audioCtx.createMediaStreamSource(new MediaStream(screenAudioTracks));
screenSource.connect(destination);
}
if (micAudioTracks.length > 0) {
- const micSource = audioCtx.createMediaStreamSource(
- new MediaStream(micAudioTracks)
- );
+ const micSource = audioCtx.createMediaStreamSource(new MediaStream(micAudioTracks));
const micGain = audioCtx.createGain();
micGain.gain.value = setup.microphone.volume;
micSource.connect(micGain);
@@ -564,10 +566,7 @@ export function useScreenRecording() {
...destination.stream.getAudioTracks(),
]);
} catch (err) {
- console.warn(
- "Error al mezclar audio, usando solo audio de pantalla:",
- err
- );
+ console.warn("Error al mezclar audio, usando solo audio de pantalla:", err);
finalScreenStream = screenStream;
}
}
@@ -584,7 +583,6 @@ export function useScreenRecording() {
setState("countdown");
setCountdown(4);
-
let count = 4;
const countdownInterval = setInterval(() => {
count -= 1;
@@ -606,16 +604,10 @@ export function useScreenRecording() {
);
const cancelRecording = useCallback(() => {
- if (
- screenRecorderRef.current &&
- screenRecorderRef.current.state !== "inactive"
- ) {
+ if (screenRecorderRef.current && screenRecorderRef.current.state !== "inactive") {
screenRecorderRef.current.stop();
}
- if (
- cameraRecorderRef.current &&
- cameraRecorderRef.current.state !== "inactive"
- ) {
+ if (cameraRecorderRef.current && cameraRecorderRef.current.state !== "inactive") {
cameraRecorderRef.current.stop();
}
cleanupStreams();
@@ -649,4 +641,4 @@ export function useScreenRecording() {
cameraConfig,
updateCameraConfig,
};
-}
+}
\ No newline at end of file
diff --git a/hooks/useVideoExport.ts b/hooks/useVideoExport.ts
index 930707a..5d19506 100644
--- a/hooks/useVideoExport.ts
+++ b/hooks/useVideoExport.ts
@@ -818,16 +818,20 @@ async function exportWithMediabunnyAndAudio(
}
const totalAudioInputs = audioInputs.length;
-
if (totalAudioInputs === 0) {
downloadBlob(videoBlob, `openvid-${width}x${height}.mp4`);
setProgress({ status: "complete", progress: 100, message: "¡Exportación completada!" });
return;
} else if (audioInputs.length > 0) {
- filterComplex += `${audioInputs.join("")}amix=inputs=${audioInputs.length}:duration=longest:dropout_transition=0:normalize=0[aout]`;
+ filterComplex += `${audioInputs.join("")}amix=inputs=${audioInputs.length}:duration=longest:dropout_transition=0:normalize=0,atrim=0:${outputDuration.toFixed(3)},asetpts=PTS-STARTPTS[aout]`;
ffmpegArgs.push("-filter_complex", filterComplex);
ffmpegArgs.push("-map", "0:v", "-map", "[aout]");
- ffmpegArgs.push("-c:v", "copy", "-c:a", "aac", "-b:a", "192k", "output.mp4");
+ ffmpegArgs.push(
+ "-c:v", "copy",
+ "-c:a", "aac", "-b:a", "192k",
+ "-t", outputDuration.toFixed(3),
+ "output.mp4"
+ );
} else {
ffmpegArgs.push("-c:v", "copy", "-an", "output.mp4");
}
diff --git a/public/images/showcase/poster/demo2.avif b/public/images/showcase/poster/demo2.avif
index d84fb6f..bd0ccf3 100644
Binary files a/public/images/showcase/poster/demo2.avif and b/public/images/showcase/poster/demo2.avif differ
diff --git a/public/images/showcase/poster/demo6.avif b/public/images/showcase/poster/demo6.avif
new file mode 100644
index 0000000..d84fb6f
Binary files /dev/null and b/public/images/showcase/poster/demo6.avif differ
diff --git a/public/videos/showcase/demo2.mp4 b/public/videos/showcase/demo2.mp4
index a4ff37b..d7ae8bd 100644
Binary files a/public/videos/showcase/demo2.mp4 and b/public/videos/showcase/demo2.mp4 differ
diff --git a/public/videos/showcase/demo6.mp4 b/public/videos/showcase/demo6.mp4
new file mode 100644
index 0000000..a4ff37b
Binary files /dev/null and b/public/videos/showcase/demo6.mp4 differ
diff --git a/types/editor.types.ts b/types/editor.types.ts
index 39d7d4f..243009d 100644
--- a/types/editor.types.ts
+++ b/types/editor.types.ts
@@ -42,10 +42,12 @@ export interface EditorState {
export interface VideoCanvasHandle {
getExportCanvas: () => HTMLCanvasElement | null;
- drawFrame: (highQuality?: boolean, time?: number) => Promise<void>;
+ drawFrame: (highQuality?: boolean, explicitTimelineTime?: number, frameOverride?: VideoFrame) => Promise<void>;
+
getPreviewContainer: () => HTMLDivElement | null;
clearAllSelection: () => { multiIds: string[]; videoSelected: boolean };
restoreSelectionState: (state: { multiIds: string[]; videoSelected: boolean }) => void;
+
}
export interface VideoThumbnail {