Skip to content

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

Merge branch 'main' into prueba-camilo

CristianOlivera1e89aa5b745f5
diff --cc hooks/useScreenRecording.ts
index fc2b25e,862db13..93e7b35
--- a/hooks/useScreenRecording.ts
+++ b/hooks/useScreenRecording.ts
@@@ -318,291 -295,261 +318,291 @@@ export function useScreenRecording()
}
}, []);
- const startRecording = useCallback((stream: MediaStream) => {
- try {
- chunksRef.current = [];
- // cursorKeyframesRef.current = []; // Reset cursor keyframes
- startTimeRef.current = Date.now();
-
- // Get video dimensions from the stream
- const videoTrack = stream.getVideoTracks()[0];
- const settings = videoTrack.getSettings();
- videoDimensionsRef.current = {
- width: settings.width || 1920,
- height: settings.height || 1080,
- };
+ const updateCameraConfig = useCallback((partial: Partial<CameraConfig>) => {
+ setCameraConfig((prev) => (prev ? { ...prev, ...partial } : prev));
+ }, []);
- const codecOptions = [
- { mimeType: "video/webm;codecs=vp9,opus" },
- { mimeType: "video/webm;codecs=vp8,opus" },
- { mimeType: "video/webm;codecs=vp9" },
- { mimeType: "video/webm;codecs=vp8" },
- { mimeType: "video/webm" },
- ];
-
- let mediaRecorder: MediaRecorder | null = null;
-
- for (const options of codecOptions) {
- try {
- if (MediaRecorder.isTypeSupported(options.mimeType)) {
- mediaRecorder = new MediaRecorder(stream, options);
- break;
+ const startRecording = useCallback(
+ (screenStream: MediaStream, camStream: MediaStream | null) => {
+ try {
+ screenChunksRef.current = [];
+ 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 screenRecorder = new MediaRecorder(
+ screenStream,
+ screenMime ? { mimeType: screenMime } : undefined
+ );
+ screenRecorderRef.current = screenRecorder;
+
+ screenRecorder.ondataavailable = (event) => {
+ if (event.data.size > 0) {
+ screenChunksRef.current.push(event.data);
}
- } catch (e) {
- console.warn(`Failed to create MediaRecorder with ${options.mimeType}:`, e);
- }
- }
+ };
+ screenRecorder.onerror = (event) => {
+ console.error("Error del MediaRecorder (pantalla):", event);
+ setError("Error durante la grabación");
+ setState("idle");
+ cleanupStreams();
+ restoreOriginals();
+ };
- if (!mediaRecorder) {
- try {
- mediaRecorder = new MediaRecorder(stream);
- console.log("Using default MediaRecorder settings");
- } catch {
- throw new Error("No se pudo crear MediaRecorder con ninguna configuración");
+ let cameraRecorder: MediaRecorder | null = null;
+ if (camStream) {
+ const camMime =
+ pickSupportedMimeType([
+ "video/webm;codecs=vp9",
+ "video/webm;codecs=vp8",
+ "video/webm",
+ ]) || undefined;
+
+ cameraRecorder = new MediaRecorder(
+ camStream,
+ camMime ? { mimeType: camMime } : undefined
+ );
+ cameraRecorderRef.current = cameraRecorder;
+
+ cameraRecorder.ondataavailable = (event) => {
+ if (event.data.size > 0) {
+ cameraChunksRef.current.push(event.data);
+ }
+ };
+ cameraRecorder.onerror = (event) => {
+ console.error("Error del MediaRecorder (cámara):", event);
+ // Camera failure should not crash the whole recording.
+ };
}
- }
- mediaRecorderRef.current = mediaRecorder;
+ let pendingCount = cameraRecorder ? 2 : 1;
+ let screenBlob: Blob | null = null;
+ let cameraBlob: Blob | null = null;
+
+ const finalize = async () => {
+ setState("processing");
+ const duration = (Date.now() - startTimeRef.current) / 1000;
+ cleanupStreams();
+
+ try {
+ await saveVideoToIndexedDB(
+ screenBlob || new Blob([], { type: "video/webm" }),
+ duration,
+ {
+ cameraBlob,
+ cameraConfig: cameraConfigRef.current,
+ }
+ );
+
+ if (pathname === "/editor") {
+ window.location.reload();
+ } else {
+ router.push("/editor");
+ }
+ } catch (err) {
+ console.error("Error al guardar video:", err);
+ setError("Error al procesar el video");
+ setState("idle");
+ restoreOriginals();
+ }
+ };
+
+ screenRecorder.onstop = () => {
+ screenBlob = new Blob(screenChunksRef.current, { type: "video/webm" });
+ pendingCount -= 1;
+ if (pendingCount <= 0) finalize();
+ else if (cameraRecorder && cameraRecorder.state !== "inactive") {
+ cameraRecorder.stop();
+ }
+ };
- mediaRecorder.ondataavailable = (event) => {
- if (event.data.size > 0) {
- chunksRef.current.push(event.data);
+ if (cameraRecorder) {
+ cameraRecorder.onstop = () => {
+ cameraBlob = new Blob(cameraChunksRef.current, {
+ type: "video/webm",
+ });
+ pendingCount -= 1;
+ if (pendingCount <= 0) finalize();
+ else if (
+ screenRecorderRef.current &&
+ screenRecorderRef.current.state !== "inactive"
+ ) {
+ screenRecorderRef.current.stop();
+ }
+ };
}
- };
- mediaRecorder.onerror = (event) => {
- console.error("MediaRecorder error:", event);
- setError("Error durante la grabación");
+ screenRecorder.start(1000);
+ cameraRecorder?.start(1000);
+ setState("recording");
+ } catch (err) {
+ console.error("Error al iniciar grabación:", err);
+ setError(
+ err instanceof Error ? err.message : "No se pudo iniciar la grabación"
+ );
setState("idle");
+ cleanupStreams();
restoreOriginals();
- };
+ }
+ },
+ [router, pathname, restoreOriginals, cleanupStreams]
+ );
- mediaRecorder.onstop = async () => {
- setState("processing");
+ const startCountdown = useCallback(
+ async (setupArg?: RecordingSetupConfig) => {
+ const setup: RecordingSetupConfig = setupArg ?? DEFAULT_RECORDING_SETUP;
- if (streamRef.current) {
- streamRef.current.getTracks().forEach((track) => track.stop());
- streamRef.current = null;
- }
+ try {
+ setError(null);
+ setRecordingTime(0);
- // Clean up capture controller
- /* if (captureControllerRef.current) {
- captureControllerRef.current.oncapturedmousechange = null;
- captureControllerRef.current = null;
- }*/
-
- const blob = new Blob(chunksRef.current, { type: "video/webm" });
- const duration = (Date.now() - startTimeRef.current) / 1000;
-
- // Build cursor recording data
- /* const cursorData: CursorRecordingData = {
- keyframes: cursorKeyframesRef.current,
- videoDimensions: videoDimensionsRef.current,
- frameRate: 60,
- hasCursorData: cursorKeyframesRef.current.length > 0,
- };*/
-
- try {
- await saveVideoToIndexedDB(blob, duration, /* cursorData */);
-
- if (pathname === "/editor") {
- window.location.reload();
- } else {
- router.push("/editor");
+ const screenStream = await navigator.mediaDevices.getDisplayMedia({
+ video: { displaySurface: "browser" },
+ audio: setup.systemAudio
+ ? { echoCancellation: true, noiseSuppression: true }
+ : false,
+ });
+ screenStreamRef.current = screenStream;
+
+ let camStream: MediaStream | null = null;
+ if (setup.camera.enabled) {
+ try {
+ camStream = await requestCameraStream(setup.camera.deviceId);
+ cameraStreamRef.current = camStream;
+ setCameraStream(camStream);
+ setCameraConfig(setup.camera);
+ } catch (err) {
+ console.warn("Cámara denegada, continuando sin cámara:", err);
}
- } catch (error) {
- console.error("Error al guardar video:", error);
- setError("Error al procesar el video");
- setState("idle");
- restoreOriginals();
}
- };
-
- try {
- mediaRecorder.start(1000);
- setState("recording");
- } catch (e) {
- console.error("Error starting MediaRecorder:", e);
- throw new Error("No se pudo iniciar la grabación");
- }
-
- } catch (err) {
- console.error("Error al iniciar grabación:", err);
- setError(err instanceof Error ? err.message : "No se pudo iniciar la grabación");
- setState("idle");
- restoreOriginals();
- }
- }, [router, pathname, restoreOriginals]);
-
- const startCountdown = useCallback(async () => {
- try {
- setError(null);
-
- // Check if CaptureController is supported (2026 API for cursor tracking)
- // const hasCaptureController = supportsCursorCapture();
- // let controller: CaptureController | null = null;
-
- /* if (hasCaptureController && typeof CaptureController !== "undefined") {
- try {
- controller = new CaptureController();
- captureControllerRef.current = controller;
-
- // Listen for cursor position changes
- controller.oncapturedmousechange = (event: CapturedMouseEvent) => {
- console.log(`[RAW EVENT] X: ${event.surfaceX}, Y: ${event.surfaceY} | Estado actual: ${stateRef.current}`);
- if (stateRef.current !== "recording") return;
- console.log(`Cursor detectado en X: ${event.surfaceX}, Y: ${event.surfaceY}`);
-
- const time = (Date.now() - startTimeRef.current) / 1000;
- const { width, height } = videoDimensionsRef.current;
-
- // Convert pixel coordinates to percentages
- const x = (event.surfaceX / width) * 100;
- const y = (event.surfaceY / height) * 100;
-
- // Only add keyframe if position changed significantly (optimization)
- const lastKeyframe = cursorKeyframesRef.current[cursorKeyframesRef.current.length - 1];
- if (!lastKeyframe ||
- Math.abs(lastKeyframe.x - x) > 0.1 ||
- Math.abs(lastKeyframe.y - y) > 0.1 ||
- lastKeyframe.clicking !== isClickingRef.current) {
-
- cursorKeyframesRef.current.push({
- time,
- x,
- y,
- state: lastCursorStateRef.current,
- clicking: isClickingRef.current,
- });
- }
- };
- console.log("CaptureController initialized for cursor tracking");
- } catch (e) {
- console.warn("Failed to initialize CaptureController:", e);
- controller = null;
- captureControllerRef.current = null;
+ let micStream: MediaStream | null = null;
+ if (setup.microphone.enabled) {
+ try {
+ 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);
+ }
}
- }*/
-
- // Build display media options
- const displayMediaOptions: DisplayMediaStreamOptions /*ExtendedDisplayMediaOptions*/ = {
- video: {
- displaySurface: "browser",
- // Hide native cursor when CaptureController is available
- // so we can draw our custom cursor instead
- /* ...(controller ? { cursor: "never" as const } : {}),*/
- },
- audio: {
- echoCancellation: true,
- noiseSuppression: true,
- },
- // Attach controller if available
- /*...(controller ? { controller } : {}),*/
- };
-
- const stream = await navigator.mediaDevices.getDisplayMedia(displayMediaOptions as DisplayMediaStreamOptions);
-
- streamRef.current = stream;
- // Set up click tracking for the captured surface
- /* if (controller) {
- // Track mouse clicks globally during recording
- const handleMouseDown = () => { isClickingRef.current = true; };
- const handleMouseUp = () => { isClickingRef.current = false; };
-
- document.addEventListener("mousedown", handleMouseDown);
- document.addEventListener("mouseup", handleMouseUp);
+ 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 = new AudioCtx();
+ audioCtxRef.current = audioCtx;
+
+ const destination = audioCtx.createMediaStreamDestination();
+
+ if (screenAudioTracks.length > 0) {
+ const screenSource = audioCtx.createMediaStreamSource(
+ new MediaStream(screenAudioTracks)
+ );
+ screenSource.connect(destination);
+ }
- // Clean up click listeners when stream ends
- stream.getVideoTracks()[0].addEventListener("ended", () => {
- document.removeEventListener("mousedown", handleMouseDown);
- document.removeEventListener("mouseup", handleMouseUp);
- });
- }*/
+ if (micAudioTracks.length > 0) {
+ const micSource = audioCtx.createMediaStreamSource(
+ new MediaStream(micAudioTracks)
+ );
+ const micGain = audioCtx.createGain();
+ micGain.gain.value = setup.microphone.volume;
+ micSource.connect(micGain);
+ micGain.connect(destination);
+ }
- stream.getVideoTracks()[0].onended = () => {
- if (stateRef.current === "recording") {
- stopRecording();
- } else {
- setState("idle");
- restoreOriginals();
+ finalScreenStream = new MediaStream([
+ ...screenStream.getVideoTracks(),
+ ...destination.stream.getAudioTracks(),
+ ]);
+ } catch (err) {
+ console.warn(
+ "Error al mezclar audio, usando solo audio de pantalla:",
+ err
+ );
+ finalScreenStream = screenStream;
+ }
}
- };
- setState("countdown");
- setCountdown(4);
-
- let count = 4;
- const countdownInterval = setInterval(() => {
- count--;
- setCountdown(count);
+ screenStream.getVideoTracks()[0].onended = () => {
+ if (stateRef.current === "recording") {
+ stopRecording();
+ } else {
+ setState("idle");
+ cleanupStreams();
+ restoreOriginals();
+ }
+ };
- if (count <= 0) {
- clearInterval(countdownInterval);
- startRecording(stream);
- }
- }, 1000);
+ setState("countdown");
+ setCountdown(4);
- } catch (err) {
- console.error("Error al iniciar captura:", err);
- setError("No se pudo iniciar la captura de pantalla");
- setState("idle");
- restoreOriginals();
- }
- }, [restoreOriginals, stopRecording, startRecording]);
+ let count = 4;
+ const countdownInterval = setInterval(() => {
+ count -= 1;
+ setCountdown(count);
+ if (count <= 0) {
+ clearInterval(countdownInterval);
+ startRecording(finalScreenStream, camStream);
+ }
+ }, 1000);
+ } catch (err) {
+ console.error("Error al iniciar captura:", err);
+ setError("No se pudo iniciar la captura de pantalla");
+ setState("idle");
+ cleanupStreams();
+ restoreOriginals();
+ }
+ },
+ [restoreOriginals, stopRecording, startRecording, cleanupStreams]
+ );
const cancelRecording = useCallback(() => {
- if (streamRef.current) {
- streamRef.current.getTracks().forEach((track) => track.stop());
- streamRef.current = null;
+ if (
+ screenRecorderRef.current &&
+ screenRecorderRef.current.state !== "inactive"
+ ) {
+ screenRecorderRef.current.stop();
}
- if (mediaRecorderRef.current && mediaRecorderRef.current.state !== "inactive") {
- mediaRecorderRef.current.stop();
+ if (
+ cameraRecorderRef.current &&
+ cameraRecorderRef.current.state !== "inactive"
+ ) {
+ cameraRecorderRef.current.stop();
}
- // Clean up capture controller
- /* if (captureControllerRef.current) {
- captureControllerRef.current.oncapturedmousechange = null;
- captureControllerRef.current = null;
- }*/
- chunksRef.current = [];
- // cursorKeyframesRef.current = [];
+ cleanupStreams();
+ screenChunksRef.current = [];
+ cameraChunksRef.current = [];
+ setRecordingTime(0);
setState("idle");
+ setCameraConfig(null);
restoreOriginals();
- }, [restoreOriginals]);
+ }, [cleanupStreams, restoreOriginals]);
useEffect(() => {
- if (recordingTime >= 60 && state === "recording") {
+ if (recordingTime >= 120 && state === "recording") {
stopRecording();
}
}, [recordingTime, state, stopRecording]);