Create professional demos and 3D mockups in seconds, directly in your browser
feat: implement playback time context and legacy recording migration, enhance video duration handling
CristianOlivera18c3952536574
diff --git a/app/contexts/PlaybackTimeContext.tsx b/app/contexts/PlaybackTimeContext.tsxnew file mode 100644index 0000000..aefba9f--- /dev/null+++ b/app/contexts/PlaybackTimeContext.tsx@@ -0,0 +1,38 @@+"use client";++import { createContext, useContext, useMemo, type ReactNode } from "react";++interface PlaybackTimeContextValue {+ currentTime: number;+}++const PlaybackTimeContext = createContext<PlaybackTimeContextValue>({+ currentTime: 0,+});++/**+ * Provides `currentTime` to descendants without forcing parent components+ * (like ControlPanel) to re-render on every playback tick (~30fps).+ *+ * Only components that actually need the current playback time should call+ * `usePlaybackTime()`. This isolates the 30fps re-renders to those leaves+ * instead of re-rendering the entire editor subtree.+ */+export function PlaybackTimeProvider({+ children,+ currentTime,+}: {+ children: ReactNode;+ currentTime: number;+}) {+ const value = useMemo(() => ({ currentTime }), [currentTime]);+ return (+ <PlaybackTimeContext.Provider value={value}>+ {children}+ </PlaybackTimeContext.Provider>+ );+}++export function usePlaybackTime(): PlaybackTimeContextValue {+ return useContext(PlaybackTimeContext);+}diff --git a/hooks/useScreenRecording.ts b/hooks/useScreenRecording.tsindex fa8c43c..74118c7 100644--- a/hooks/useScreenRecording.ts+++ b/hooks/useScreenRecording.ts@@ -8,6 +8,7 @@ import { DEFAULT_RECORDING_SETUP, requestCameraStream, requestMicrophoneStream }import { clearAllThumbnailCache } from "@/lib/thumbnail-cache";import { clearVideoTrack } from "@/lib/video-upload-cache";import { clearVideoProjectAndAudios } from "@/lib/video-project-cache";+import { normalizeRecordingBlob, probeBlobDuration, type NormalizedRecording } from "@/lib/webm-duration.utils";export type { RecordingState, RecordingResult, VideoData, RecordingContextType };@@ -120,6 +121,53 @@ let cachedLoadedVideo: {cameraUrl: string | null;} | null = null;+/**+ * Self-healing migration: legacy recordings stored by MediaRecorder lack+ * duration metadata. When such a blob is loaded, remux it (packet copy) and+ * 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 }> {+ try {+ const probed = await probeBlobDuration(data.blob);+ if (Number.isFinite(probed)) {+ return { blob: data.blob, duration: data.duration };+ }++ const normalized = await normalizeRecordingBlob(data.blob);+ if (!normalized.changed) {+ return { blob: data.blob, duration: data.duration };+ }++ const duration =+ normalized.duration > 0 ? normalized.duration : data.duration;++ 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 },+ "currentVideo"+ );+ 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 };+ }+}+function releaseCachedLoadedVideo(): void {if (cachedLoadedVideo) {URL.revokeObjectURL(cachedLoadedVideo.url);@@ -160,36 +208,44 @@ export async function loadVideoFromIndexedDB(): Promise<{const timestamp = data.timestamp || Date.now();const cameraBlob: Blob | null = data.cameraBlob ?? null;- if (cachedLoadedVideo && cachedLoadedVideo.videoId === videoId) {+ 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);++ if (cachedLoadedVideo && cachedLoadedVideo.videoId === videoId) {+ resolve({+ blob,+ duration,+ url: cachedLoadedVideo.url,+ videoId,+ timestamp,+ isRecordedVideo: data.isRecordedVideo || false,+ cameraBlob,+ cameraUrl: cachedLoadedVideo.cameraUrl,+ cameraConfig: data.cameraConfig ?? null,+ });+ return;+ }++ releaseCachedLoadedVideo();+ const url = URL.createObjectURL(blob);+ const cameraUrl = cameraBlob ? URL.createObjectURL(cameraBlob) : null;+ cachedLoadedVideo = { videoId, url, cameraUrl };resolve({- blob: data.blob,- duration: data.duration,- url: cachedLoadedVideo.url,+ blob,+ duration,+ url,videoId,timestamp,isRecordedVideo: data.isRecordedVideo || false,cameraBlob,- cameraUrl: cachedLoadedVideo.cameraUrl,+ cameraUrl,cameraConfig: data.cameraConfig ?? null,});- return;- }-- releaseCachedLoadedVideo();- const url = URL.createObjectURL(data.blob);- const cameraUrl = cameraBlob ? URL.createObjectURL(cameraBlob) : null;- cachedLoadedVideo = { videoId, url, cameraUrl };- resolve({- blob: data.blob,- duration: data.duration,- url,- videoId,- timestamp,- isRecordedVideo: data.isRecordedVideo || false,- cameraBlob,- cameraUrl,- cameraConfig: data.cameraConfig ?? null,- });+ })();} else {resolve(null);}@@ -418,13 +474,31 @@ export function useScreenRecording() {return;}setState("processing");- const duration = (Date.now() - startTimeRef.current) / 1000;+ const wallClockDuration = (Date.now() - startTimeRef.current) / 1000;cleanupStreams();try {const rawScreenBlob =screenBlob || new Blob([], { type: screenMime || "video/webm" });- await saveVideoToIndexedDB(rawScreenBlob, duration, {- cameraBlob,+ // MediaRecorder WebMs lack duration metadata; remux (packet copy,+ // no re-encode) so the stored file reports a real duration.+ let normalizedScreen: NormalizedRecording;+ let normalizedCamera: NormalizedRecording | null = null;+ try {+ [normalizedScreen, normalizedCamera] = await Promise.all([+ normalizeRecordingBlob(rawScreenBlob),+ cameraBlob+ ? normalizeRecordingBlob(cameraBlob)+ : Promise.resolve(null as NormalizedRecording | null),+ ]);+ } catch (e) {+ console.warn("Recording normalization failed, storing raw blob:", e);+ normalizedScreen = { blob: rawScreenBlob, duration: 0, changed: false };+ }+ const duration = normalizedScreen.duration > 0+ ? normalizedScreen.duration+ : wallClockDuration;+ await saveVideoToIndexedDB(normalizedScreen.blob, duration, {+ cameraBlob: normalizedCamera?.blob ?? null,cameraConfig: cameraConfigRef.current,});await clearVideoTrack();diff --git a/lib/video.utils.ts b/lib/video.utils.tsindex 3765041..806041b 100644--- a/lib/video.utils.ts+++ b/lib/video.utils.ts@@ -1,4 +1,5 @@import { TIMELINE_ZOOM_SCALE } from './constants';+import { forceResolveVideoDuration } from './webm-duration.utils';export function waitForVideoFrame(video: HTMLVideoElement): Promise<void> {return new Promise((resolve) => {@@ -48,6 +49,12 @@ export async function ensureVideoReady(video: HTMLVideoElement): Promise<void> {});}+ // Headerless WebM (MediaRecorder) reports Infinity; force the browser to+ // scan the stream and resolve the real duration before exporting.+ if (!Number.isFinite(video.duration)) {+ await forceResolveVideoDuration(video);+ }+// Pausar y mover al iniciovideo.pause();video.currentTime = 0;diff --git a/lib/webm-duration.utils.ts b/lib/webm-duration.utils.tsnew file mode 100644index 0000000..e2a8721--- /dev/null+++ b/lib/webm-duration.utils.ts@@ -0,0 +1,176 @@+import {+ Input,+ Output,+ Conversion,+ BufferTarget,+ BlobSource,+ ALL_FORMATS,+ WebMOutputFormat,+} from "mediabunny";++/**+ * MediaRecorder-produced WebM files omit the EBML `Duration` element (and the+ * seek index/Cues), which makes `HTMLVideoElement.duration` report `Infinity`+ * until the element is forced to scan the whole file. That breaks export+ * validation, timeline clamping and multi-clip playback.+ *+ * Strategy (defense in depth):+ * 1. `normalizeRecordingBlob` — remuxes the recording with mediabunny (packet+ * copy, zero re-encoding) so the file carries proper duration metadata.+ * Applied when a recording is saved AND as a self-healing migration when a+ * legacy broken blob is loaded from IndexedDB.+ * 2. `forceResolveVideoDuration` — runtime fallback that forces any given+ * `<video>` element to compute the real duration via an out-of-range seek.+ */++const PROBE_TIMEOUT_MS = 4000;+const REMUX_TIMEOUT_MS = 60_000;++export interface NormalizedRecording {+ /** The original blob if it was already healthy, otherwise the remuxed one. */+ blob: Blob;+ /** Real media duration in seconds; 0 if it could not be determined. */+ duration: number;+ /** True when the input blob was broken and had to be remuxed. */+ changed: boolean;+}++/**+ * Reads the duration of a media blob using a detached <video> element.+ * Returns `Infinity` when the browser cannot determine it (headerless WebM),+ * and `NaN` only if the blob is not decodable at all.+ */+export function probeBlobDuration(blob: Blob): Promise<number> {+ return new Promise((resolve) => {+ const url = URL.createObjectURL(blob);+ const video = document.createElement("video");+ let settled = false;++ const finish = (value: number) => {+ if (settled) return;+ settled = true;+ clearTimeout(timeout);+ video.removeAttribute("src");+ video.load();+ URL.revokeObjectURL(url);+ resolve(value);+ };++ const timeout = setTimeout(() => finish(Infinity), PROBE_TIMEOUT_MS);++ video.preload = "metadata";+ video.muted = true;+ video.onloadedmetadata = () => finish(video.duration);+ video.onerror = () => finish(NaN);+ video.src = url;+ });+}++function isKnownDuration(value: number): value is number {+ return Number.isFinite(value) && value > 0;+}++/**+ * Guarantees a blob whose container metadata includes a real duration.+ *+ * If the blob already reports a finite duration it is returned untouched+ * (zero-cost fast path). Otherwise it is demuxed/remuxed through mediabunny:+ * packets are copied verbatim (no re-encode), but the new WebM header gets a+ * correct `Duration` plus a full Cues index, fixing both duration reporting+ * and seeking accuracy.+ */+export async function normalizeRecordingBlob(blob: Blob): Promise<NormalizedRecording> {+ const probed = await probeBlobDuration(blob);+ if (isKnownDuration(probed)) {+ return { blob, duration: probed, changed: false };+ }++ try {+ const remuxed = await Promise.race([+ remuxWithDurationMetadata(blob),+ new Promise<never>((_, reject) =>+ setTimeout(() => reject(new Error("Remux timed out")), REMUX_TIMEOUT_MS)+ ),+ ]);+ return remuxed;+ } catch (error) {+ console.warn("[webm-duration] Could not normalize recording blob:", error);+ return { blob, duration: isKnownDuration(probed) ? probed : 0, changed: false };+ }+}++async function remuxWithDurationMetadata(blob: Blob): Promise<NormalizedRecording> {+ const input = new Input({+ formats: ALL_FORMATS,+ source: new BlobSource(blob),+ });++ const output = new Output({+ format: new WebMOutputFormat(),+ target: new BufferTarget(),+ });++ const conversion = await Conversion.init({ input, output });+ await conversion.execute();++ const buffer = (output.target as BufferTarget).buffer;+ if (!buffer || buffer.byteLength === 0) {+ throw new Error("Remux produced an empty buffer");+ }++ const fixedBlob = new Blob([buffer], { type: "video/webm" });+ const duration = await probeBlobDuration(fixedBlob);++ if (!isKnownDuration(duration)) {+ throw new Error("Remuxed blob still reports no duration");+ }++ // Guard against pathological outputs smaller than the source data.+ if (fixedBlob.size < blob.size * 0.5) {+ throw new Error("Remuxed blob is suspiciously smaller than the source");+ }++ return { blob: fixedBlob, duration, changed: true };+}++/**+ * Runtime fallback for elements backed by unfixable sources: forces the+ * browser to compute the real duration by seeking far beyond the end of the+ * media. Resolves once `video.duration` becomes a finite number.+ */+export function forceResolveVideoDuration(video: HTMLVideoElement): Promise<number> {+ return new Promise((resolve) => {+ if (isKnownDuration(video.duration)) {+ resolve(video.duration);+ return;+ }++ let settled = false;++ const finish = () => {+ if (settled) return;+ settled = true;+ clearTimeout(fallbackTimer);+ video.removeEventListener("durationchange", onDurationChange);+ resolve(isKnownDuration(video.duration) ? video.duration : 0);+ };++ const onDurationChange = () => {+ if (!Number.isFinite(video.duration)) return;+ // Reset to a sane position; also triggers a fresh frame request.+ video.currentTime = 0;+ finish();+ };++ const fallbackTimer = setTimeout(finish, PROBE_TIMEOUT_MS);++ video.addEventListener("durationchange", onDurationChange);+ // Out-of-range target: Chromium clamps it to the last decodable+ // timestamp, which forces a full stream scan and resolves the duration.+ try {+ video.currentTime = 1e101;+ } catch {+ finish();+ }+ });+}