Create professional demos and 3D mockups in seconds, directly in your browser
feat: enhance video handling by adding media dimension probing and updating recording types
CristianOlivera18c8ec9d663c4
diff --git a/app/[locale]/(editor)/editor/page.tsx b/app/[locale]/(editor)/editor/page.tsxindex 5b39256..b8c974d 100644--- a/app/[locale]/(editor)/editor/page.tsx+++ b/app/[locale]/(editor)/editor/page.tsx@@ -17,7 +17,7 @@ import { useVideoThumbnails, type VideoThumbnail } from "@/hooks/useVideoThumbnaimport { useUndoRedo } from "@/hooks/useUndoRedo";import { clearAllThumbnailCache } from "@/lib/thumbnail-cache";import { addVideoToLibrary, addVideoToLibraryWithMetadata, getLibraryVideoCount, getLibraryVideo, findExistingVideo } from "@/lib/videos-library";-import { calculateTotalDuration, clampClipToRealDuration, findNextClipPosition, getClipAtTime, probeMediaDuration, resequenceClips, reorderVideoClipAt, splitClipAtTime, type VideoTrackClip } from "@/types/video-track.types";+import { calculateTotalDuration, clampClipToRealDuration, findNextClipPosition, getClipAtTime, probeMediaDuration, resequenceClips, reorderVideoClipAt, splitClipAtTime, type VideoTrackClip, probeMediaDimensions } from "@/types/video-track.types";import { remapOverlaysAfterClipChange } from "@/lib/timeline-overlay-remap";import type { ExportQuality, BackgroundTab, VideoCanvasHandle, BackgroundColorConfig, AspectRatio, CropArea } from "@/types";import type { TrimRange } from "@/types/timeline.types";@@ -1048,7 +1048,7 @@ export default function Editor() {for (const audioEl of audioElementsRef.current.values()) {audioEl.pause();}-+justEndedRef.current = false;clipSwitchTimeRef.current = null;isSwitchingClipRef.current = false;@@ -1268,7 +1268,7 @@ export default function Editor() {Number.isFinite(realDuration) && realDuration > 0? Math.min(duration, realDuration): duration;-+const persistedCamera = await getCameraBlob(videoId).catch((err) => {console.error("Failed to restore camera blob from library:", err);return null;@@ -1326,7 +1326,7 @@ export default function Editor() {setCameraUrl(restoredCameraUrl);setCameraConfig(persistedCamera.cameraConfig- ?? { ...DEFAULT_CAMERA_CONFIG, enabled: true }+ ?? { ...DEFAULT_CAMERA_CONFIG, enabled: true });}@@ -1354,7 +1354,7 @@ export default function Editor() {return videoUrlsMap.get(activeClipAtPlayhead.libraryVideoId) ?? videoUrl;}if (currentTime > 0) {-+const sorted = [...videoClips].sort((a, b) => a.startTime - b.startTime);const previous = sorted.reverse().find(c => c.startTime <= currentTime);if (previous) {@@ -1432,7 +1432,7 @@ export default function Editor() {const deletedClip = videoClipsRef.current.find(c => c.id === clipId);setVideoClips(prev => {// Re-sequence remaining clips to be contiguous (no gaps after deletion).- const { clips: newClips } = resequenceClips(prev.filter(clip => clip.id !== clipId));+ const { clips: newClips } = resequenceClips(prev.filter(clip => clip.id !== clipId));if (newClips.length > 0) {const newDuration = calculateTotalDuration(newClips);setVideoDuration(newDuration);@@ -1674,7 +1674,7 @@ export default function Editor() {if (isPhotoMode) return;const loadVideo = async () => {try {-+const savedProject = await getVideoProject();if (savedProject && savedProject.videoClips?.length > 0 && videoClipsRef.current.length === 0) {isRestoringProjectRef.current = true;@@ -1896,21 +1896,38 @@ export default function Editor() {const defaultFragments = generateDefaultZoomFragments(safeLoadDuration);setZoomFragments(defaultFragments);+ if ('cameraUrl' in videoToLoad && videoToLoad.cameraUrl) {+ setCameraUrl(videoToLoad.cameraUrl);+ } else {+ setCameraUrl(null);+ }+ if ('cameraConfig' in videoToLoad && videoToLoad.cameraConfig) {+ setCameraConfig(videoToLoad.cameraConfig);+ } else {+ setCameraConfig(null);+ }+if ('aspectRatio' in videoToLoad) {setAspectRatio(videoToLoad.aspectRatio || "auto");- if (videoToLoad.width && videoToLoad.height) {- setVideoDimensions({ width: videoToLoad.width, height: videoToLoad.height });- }+ }++ let resolvedWidth: number | undefined = 'width' in videoToLoad && videoToLoad.width ? (videoToLoad.width as number) : undefined;+ let resolvedHeight: number | undefined = 'height' in videoToLoad && videoToLoad.height ? (videoToLoad.height as number) : undefined;+ if (!resolvedWidth || !resolvedHeight) {+ const probed = await probeMediaDimensions(videoToLoad.url);+ resolvedWidth = probed?.width ?? resolvedWidth;+ resolvedHeight = probed?.height ?? resolvedHeight;+ }+ if (resolvedWidth && resolvedHeight) {+ setVideoDimensions({ width: resolvedWidth, height: resolvedHeight });}if (resolvedBlob && resolvedBlob.size > 0) {setVideoBlob(resolvedBlob);- const fileName = 'fileName' in videoToLoad- ? (videoToLoad.fileName as string)- : `Recording-${videoToLoad.videoId}.webm`;- const width = 'width' in videoToLoad ? (videoToLoad.width as number) : 1920;- const height = 'height' in videoToLoad ? (videoToLoad.height as number) : 1080;+ const fileName = 'fileName' in videoToLoad ? (videoToLoad.fileName as string) : `Recording-${videoToLoad.videoId}.webm`;+ const width = resolvedWidth || 1920;+ const height = resolvedHeight || 1080;try {let libraryVideo = await findExistingVideo(fileName, resolvedBlob.size);@@ -2738,7 +2755,7 @@ export default function Editor() {}, [trimRange.end, videoDuration, syncAudioPlayback]);const autoSaveVideoProjectTimeoutRef = useRef<NodeJS.Timeout | null>(null);-+const pendingLegacyMigrationRef = useRef<boolean>(false);const autoSaveVideoProject = useCallback(async () => {if (isPhotoMode) return;@@ -2813,7 +2830,9 @@ export default function Editor() {]);// Only show camera if the active clip has camera support- const shouldShowCamera = activeClipAtPlayhead?.hasCamera === true;+ const shouldShowCamera = activeClipAtPlayhead+ ? activeClipAtPlayhead.hasCamera === true+ : !!cameraUrl;const effectiveCameraUrl = shouldShowCamera ? cameraUrl : null;return (@@ -3052,37 +3071,37 @@ export default function Editor() {onUpdateZoomFragment={handleUpdateZoomFragment}zoomMovements={zoomMovements}selectedZoomMovementId={selectedZoomMovementId}- onSelectZoomMovement={handleSelectZoomMovement}- onUpdateZoomMovement={handleUpdateZoomMovement}- videoClips={videoClips}- />+ onSelectZoomMovement={handleSelectZoomMovement}+ onUpdateZoomMovement={handleUpdateZoomMovement}+ videoClips={videoClips}+ />{/* Video mode: Show player controls and timeline */}{isVideoMode && (<><Suspense fallback={<div className="h-13 border-b border-border" />}>- <PlayerControls- isPlaying={isPlaying}- currentTime={currentTime}- videoDuration={videoDuration}- aspectRatio={aspectRatio}- customAspectRatio={aspectRatio === "custom" ? customDimensions : videoDimensions}- isFullscreen={isFullscreen}- zoomLevel={timelineZoom}- onTogglePlayPause={togglePlayPause}- onSkipBackward={skipBackward}- onSkipForward={skipForward}- onToggleFullscreen={toggleFullscreen}- onAspectRatioChange={handleAspectRatioChange}- onCustomAspectRatioChange={handleCustomDimensionsChange}- onOpenCropper={handleOpenCropper}- onZoomChange={handleZoomChange}- videoMaskConfig={videoMaskConfig}- onVideoMaskConfigChange={setVideoMaskConfig}- videoPreviewImageUrl={currentPreviewThumbnail}- onSplitClip={handleSplitVideoClip}- canSplitClip={canSplitClip}- />+ <PlayerControls+ isPlaying={isPlaying}+ currentTime={currentTime}+ videoDuration={videoDuration}+ aspectRatio={aspectRatio}+ customAspectRatio={aspectRatio === "custom" ? customDimensions : videoDimensions}+ isFullscreen={isFullscreen}+ zoomLevel={timelineZoom}+ onTogglePlayPause={togglePlayPause}+ onSkipBackward={skipBackward}+ onSkipForward={skipForward}+ onToggleFullscreen={toggleFullscreen}+ onAspectRatioChange={handleAspectRatioChange}+ onCustomAspectRatioChange={handleCustomDimensionsChange}+ onOpenCropper={handleOpenCropper}+ onZoomChange={handleZoomChange}+ videoMaskConfig={videoMaskConfig}+ onVideoMaskConfigChange={setVideoMaskConfig}+ videoPreviewImageUrl={currentPreviewThumbnail}+ onSplitClip={handleSplitVideoClip}+ canSplitClip={canSplitClip}+ /></Suspense>diff --git a/app/components/ui/editor/FeedbackWidget.tsx b/app/components/ui/editor/FeedbackWidget.tsxindex d94192f..4d09406 100644--- a/app/components/ui/editor/FeedbackWidget.tsx+++ b/app/components/ui/editor/FeedbackWidget.tsx@@ -264,7 +264,7 @@ export function FeedbackWidget() {<TooltipAction label={t("tooltip")}><buttononClick={() => setIsOpen(true)}- className="flex items-center justify-center size-14 rounded-full bg-muted hover:bg-muted border border-border text-foreground hover:text-foreground transition-all duration-200 shrink-0 shadow-foreground/20 shadow-lg hover:scale-105 active:scale-95"+ className="flex items-center justify-center size-13 rounded-full bg-muted hover:bg-muted border border-border text-foreground hover:text-foreground transition-all duration-200 shrink-0 shadow-foreground/20 shadow-lg hover:scale-105 active:scale-95"aria-label={t("tooltip")}><Icon icon="solar:chat-round-dots-bold" className="size-8" aria-hidden="true" />diff --git a/app/components/ui/home/SocialReactions.tsx b/app/components/ui/home/SocialReactions.tsxindex 19213c9..eb7257a 100644--- a/app/components/ui/home/SocialReactions.tsx+++ b/app/components/ui/home/SocialReactions.tsx@@ -40,7 +40,6 @@ interface SocialPost {metadata?: PostMetadata;stats?: PostStats;}-const getSocialData = (t: (key: string) => string): SocialPost[] => [{id: "post-1",@@ -57,20 +56,20 @@ const getSocialData = (t: (key: string) => string): SocialPost[] => [text: t("posts.post1.text"),link: {display: "opensourceprojects.dev/post/7596eb42-...",- url: "https://opensourceprojects.dev/post/7596eb42-...",+ url: "https://www.opensourceprojects.dev/post/7596eb42-5427-467a-8ed9-1ae080173623",},mediaUrl:"https://raw.githubusercontent.com/CristianOlivera1/Resources-dev/refs/heads/main/openvid/social-reactions/github-post.avif",},metadata: {timestamp: t("posts.post1.timestamp"),- views: "27.3K",+ views: "27.8K",},stats: {replies: "8",- reposts: "70",- likes: "632",- bookmarks: "605",+ reposts: "69",+ likes: "627",+ bookmarks: "593",isLiked: false,},},@@ -92,10 +91,10 @@ const getSocialData = (t: (key: string) => string): SocialPost[] => [text: t("posts.post2.text"),},stats: {- likes: "6.921",- replies: "0",- reposts: "0",- bookmarks: "0",+ likes: "8.432",+ replies: "37",+ reposts: "214",+ bookmarks: "1.128",},},{@@ -116,12 +115,12 @@ const getSocialData = (t: (key: string) => string): SocialPost[] => [},metadata: {timestamp: t("posts.post3.timestamp"),- views: "9,045",+ views: "9,810",},stats: {- replies: "4",- reposts: "42",- likes: "213",+ replies: "5",+ reposts: "40",+ likes: "208",bookmarks: "217",isLiked: true,},@@ -144,10 +143,10 @@ const getSocialData = (t: (key: string) => string): SocialPost[] => [text: t("posts.post4.text"),},stats: {- likes: "6.921",- replies: "0",- reposts: "0",- bookmarks: "0",+ likes: "9.847",+ replies: "42",+ reposts: "318",+ bookmarks: "1.406",},},{@@ -167,10 +166,10 @@ const getSocialData = (t: (key: string) => string): SocialPost[] => ["https://raw.githubusercontent.com/CristianOlivera1/Resources-dev/refs/heads/main/openvid/social-reactions/elboussaidi-post.avif",},stats: {- replies: "31",- reposts: "172",- likes: "120",- bookmarks: "0",+ replies: "46",+ reposts: "231",+ likes: "487",+ bookmarks: "18",},},];diff --git a/hooks/useScreenRecording.ts b/hooks/useScreenRecording.tsindex 74118c7..3f7f3b5 100644--- a/hooks/useScreenRecording.ts+++ b/hooks/useScreenRecording.ts@@ -81,7 +81,12 @@ 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;+ width?: number;+ height?: number;+ } = {}): Promise<string> {try {await clearAllThumbnailCache();@@ -102,6 +107,8 @@ async function saveVideoToIndexedDB(isRecordedVideo: true,cameraBlob: extras.cameraBlob ?? null,cameraConfig: extras.cameraConfig ?? null,+ width: extras.width ?? null,+ height: extras.height ?? null,};const putRequest = store.put(videoData, "currentVideo");putRequest.onsuccess = () => {@@ -127,45 +134,73 @@ let cachedLoadedVideo: {* write the fixed version back to IndexedDB so this only ever happens once.*/async function migrateLegacyRecording(- data: { blob: Blob; duration: number; videoId?: string; timestamp?: number; cameraBlob?: Blob | null; cameraConfig?: CameraConfig | null }-): Promise<{ blob: Blob; duration: number }> {+ data: {+ blob: Blob;+ duration: number;+ videoId?: string;+ timestamp?: number;+ cameraBlob?: Blob | null;+ cameraConfig?: CameraConfig | null;+ width?: number | null;+ height?: number | null;+ }+): Promise<{ blob: Blob; duration: number; width?: number | null; height?: number | null }> {+ let blob = data.blob;+ let duration = data.duration;+ let width = data.width;+ let height = data.height;+ let changed = false;+try {- const probed = await probeBlobDuration(data.blob);- if (Number.isFinite(probed)) {- return { blob: data.blob, duration: data.duration };+ const probedDuration = await probeBlobDuration(blob);+ if (!Number.isFinite(probedDuration)) {+ const normalized = await normalizeRecordingBlob(blob);+ if (normalized.changed) {+ blob = normalized.blob;+ duration = normalized.duration > 0 ? normalized.duration : duration;+ changed = true;+ }}+ } catch (error) {+ console.warn("Legacy recording duration migration failed:", error);+ }- const normalized = await normalizeRecordingBlob(data.blob);- if (!normalized.changed) {- return { blob: data.blob, duration: data.duration };+ // Grabaciones guardadas antes de este fix no tienen width/height en+ // absoluto — se prueban una única vez acá.+ if (!width || !height) {+ try {+ const dims = await probeBlobDimensions(blob);+ if (dims) {+ width = dims.width;+ height = dims.height;+ changed = true;+ }+ } catch (error) {+ console.warn("Legacy recording dimension migration failed:", error);}+ }- const duration =- normalized.duration > 0 ? normalized.duration : data.duration;+ if (!changed) {+ return { blob: data.blob, duration: data.duration, width, height };+ }+ try {const db = await getDB();await new Promise<void>((resolve, reject) => {const transaction = db.transaction(["videos"], "readwrite");const store = transaction.objectStore("videos");const putRequest = store.put(- { ...data, blob: normalized.blob, duration },+ { ...data, blob, duration, width: width ?? null, height: height ?? null },"currentVideo");- putRequest.onsuccess = () => {- db.close();- resolve();- };- putRequest.onerror = () => {- db.close();- reject(putRequest.error);- };+ putRequest.onsuccess = () => { db.close(); resolve(); };+ putRequest.onerror = () => { db.close(); reject(putRequest.error); };});-- return { blob: normalized.blob, duration };} catch (error) {- console.warn("Legacy recording migration failed:", error);- return { blob: data.blob, duration: data.duration };+ console.warn("Failed to persist legacy recording migration:", error);}++ return { blob, duration, width, height };}function releaseCachedLoadedVideo(): void {@@ -188,6 +223,8 @@ export async function loadVideoFromIndexedDB(): Promise<{cameraBlob?: Blob | null;cameraUrl?: string | null;cameraConfig?: CameraConfig | null;+ width?: number | null;+ height?: number | null;} | null> {try {const db = await getDB();@@ -210,22 +247,19 @@ export async function loadVideoFromIndexedDB(): Promise<{void (async () => {// Heal legacy recordings whose WebM header has no duration.- const { blob, duration } =- cachedLoadedVideo && cachedLoadedVideo.videoId === videoId- ? { blob: data.blob as Blob, duration: data.duration as number }- : await migrateLegacyRecording(data);+ const { blob, duration, width, height } = cachedLoadedVideo && cachedLoadedVideo.videoId === videoId+ ? { blob: data.blob as Blob, duration: data.duration as number, width: data.width ?? null, height: data.height ?? null }+ : await migrateLegacyRecording(data);if (cachedLoadedVideo && cachedLoadedVideo.videoId === videoId) {resolve({- blob,- duration,- url: cachedLoadedVideo.url,- videoId,- timestamp,+ blob, duration, url: cachedLoadedVideo.url, videoId, timestamp,isRecordedVideo: data.isRecordedVideo || false,cameraBlob,cameraUrl: cachedLoadedVideo.cameraUrl,cameraConfig: data.cameraConfig ?? null,+ width: width ?? null,+ height: height ?? null,});return;}@@ -235,15 +269,13 @@ export async function loadVideoFromIndexedDB(): Promise<{const cameraUrl = cameraBlob ? URL.createObjectURL(cameraBlob) : null;cachedLoadedVideo = { videoId, url, cameraUrl };resolve({- blob,- duration,- url,- videoId,- timestamp,+ blob, duration, url, videoId, timestamp,isRecordedVideo: data.isRecordedVideo || false,cameraBlob,cameraUrl,cameraConfig: data.cameraConfig ?? null,+ width: width ?? null,+ height: height ?? null,});})();} else {@@ -304,6 +336,41 @@ function pickSupportedMimeType(preferred: string[]): string | undefined {return undefined;}+async function probeBlobDimensions(blob: Blob): Promise<{ width: number; height: number } | null> {+ return new Promise((resolve) => {+ let settled = false;+ const url = URL.createObjectURL(blob);+ const probe = document.createElement("video");+ probe.preload = "metadata";+ probe.muted = true;+ const finish = () => {+ if (settled) return;+ if (probe.videoWidth > 0 && probe.videoHeight > 0) {+ settled = true;+ URL.revokeObjectURL(url);+ resolve({ width: probe.videoWidth, height: probe.videoHeight });+ }+ };+ probe.addEventListener("loadedmetadata", finish);+ probe.addEventListener("resize", finish);+ probe.onerror = () => {+ if (settled) return;+ settled = true;+ URL.revokeObjectURL(url);+ resolve(null);+ };+ probe.src = url;+ setTimeout(() => {+ if (settled) return;+ settled = true;+ URL.revokeObjectURL(url);+ resolve(probe.videoWidth > 0 && probe.videoHeight > 0+ ? { width: probe.videoWidth, height: probe.videoHeight }+ : null);+ }, 2000);+ });+}+export function useScreenRecording() {const [state, setState] = useState<RecordingState>("idle");const [countdown, setCountdown] = useState<number>(0);@@ -494,20 +561,26 @@ export function useScreenRecording() {console.warn("Recording normalization failed, storing raw blob:", e);normalizedScreen = { blob: rawScreenBlob, duration: 0, changed: false };}- const duration = normalizedScreen.duration > 0- ? normalizedScreen.duration- : wallClockDuration;++ const duration = normalizedScreen.duration > 0 ? normalizedScreen.duration : wallClockDuration;+ const dimensions = await probeBlobDimensions(normalizedScreen.blob);+await saveVideoToIndexedDB(normalizedScreen.blob, duration, {cameraBlob: normalizedCamera?.blob ?? null,cameraConfig: cameraConfigRef.current,+ width: dimensions?.width,+ height: dimensions?.height,});+await clearVideoTrack();await clearVideoProjectAndAudios();+if (pathname === "/editor") {window.location.reload();} else {router.push("/editor");}+} catch (err) {console.error("Error saving recording:", err);setError("Error processing video");diff --git a/types/recording.types.ts b/types/recording.types.tsindex 8909970..56c427f 100644--- a/types/recording.types.ts+++ b/types/recording.types.ts@@ -6,6 +6,8 @@ export interface RecordingResult {blob: Blob;url: string;duration: number;+ width?: number;+ height?: number;}export interface RecordingContextType {diff --git a/types/video-track.types.ts b/types/video-track.types.tsindex c480393..b4f2125 100644--- a/types/video-track.types.ts+++ b/types/video-track.types.ts@@ -148,3 +148,34 @@ export function reorderVideoClipAt(return resequenceClips(reordered);}++export async function probeMediaDimensions(url: string): Promise<{ width: number; height: number } | null> {+ return new Promise((resolve) => {+ let settled = false;+ const probe = document.createElement("video");+ probe.preload = "metadata";+ probe.muted = true;+ const finish = () => {+ if (settled) return;+ if (probe.videoWidth > 0 && probe.videoHeight > 0) {+ settled = true;+ resolve({ width: probe.videoWidth, height: probe.videoHeight });+ }+ };+ probe.addEventListener("loadedmetadata", finish);+ probe.addEventListener("resize", finish);+ probe.onerror = () => {+ if (settled) return;+ settled = true;+ resolve(null);+ };+ probe.src = url;+ setTimeout(() => {+ if (settled) return;+ settled = true;+ resolve(probe.videoWidth > 0 && probe.videoHeight > 0+ ? { width: probe.videoWidth, height: probe.videoHeight }+ : null);+ }, 2000);+ });+}\ No newline at end of file