OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.
TypeScript
feat: add video thumbnail generation and improve transition rendering
Augustus Otu976a1fe11819
diff --git a/apps/web/src/bridges/media-bridge.ts b/apps/web/src/bridges/media-bridge.tsindex bc29f1ae..aebffe93 100644--- a/apps/web/src/bridges/media-bridge.ts+++ b/apps/web/src/bridges/media-bridge.ts@@ -49,6 +49,108 @@ export class MediaBridge {private waveformGenerator: WaveformGenerator | null = null;private initialized = false;+ private async generateVideoElementThumbnails(+ file: File | Blob,+ count = 10,+ width = 160,+ ): Promise<{ timestamp: number; dataUrl: string }[]> {+ if (typeof document === "undefined") {+ return [];+ }++ const url = URL.createObjectURL(file);+ const video = document.createElement("video");+ video.src = url;+ video.muted = true;+ video.playsInline = true;+ video.preload = "metadata";++ const cleanup = () => {+ video.removeAttribute("src");+ video.load();+ URL.revokeObjectURL(url);+ };++ const waitForEvent = (+ eventName: "loadedmetadata" | "seeked",+ timeoutMs = 2500,+ ) =>+ new Promise<void>((resolve, reject) => {+ let timeoutId: number | undefined;+ const finish = (error?: Error) => {+ if (timeoutId !== undefined) {+ window.clearTimeout(timeoutId);+ }+ video.removeEventListener(eventName, onEvent);+ video.removeEventListener("error", onError);+ if (error) reject(error);+ else resolve();+ };+ const onEvent = () => finish();+ const onError = () => finish(new Error("Video thumbnail decode failed"));++ timeoutId = window.setTimeout(+ () => finish(new Error("Video thumbnail decode timed out")),+ timeoutMs,+ );+ video.addEventListener(eventName, onEvent, { once: true });+ video.addEventListener("error", onError, { once: true });+ });++ try {+ await waitForEvent("loadedmetadata");++ const sourceWidth = video.videoWidth || width;+ const sourceHeight = video.videoHeight || Math.round(width * 9 / 16);+ const height = Math.max(+ 1,+ Math.round(width * (sourceHeight / Math.max(1, sourceWidth))),+ );+ const duration = Number.isFinite(video.duration) && video.duration > 0+ ? video.duration+ : 0;+ const maxSeekTime = Math.max(0, duration - 0.05);+ const timestamps =+ duration > 0+ ? Array.from({ length: Math.max(1, count) }, (_, i) => {+ const progress =+ count <= 1 ? 0.1 : (i + 0.5) / Math.max(1, count);+ return Math.min(maxSeekTime, Math.max(0, duration * progress));+ })+ : [0];++ const canvas = document.createElement("canvas");+ canvas.width = width;+ canvas.height = height;+ const ctx = canvas.getContext("2d");+ if (!ctx) {+ return [];+ }++ const thumbnails: { timestamp: number; dataUrl: string }[] = [];+ for (const timestamp of timestamps) {+ if (Math.abs(video.currentTime - timestamp) > 0.01) {+ video.currentTime = timestamp;+ await waitForEvent("seeked");+ }++ ctx.fillStyle = "#000";+ ctx.fillRect(0, 0, width, height);+ ctx.drawImage(video, 0, 0, width, height);+ thumbnails.push({+ timestamp,+ dataUrl: canvas.toDataURL("image/jpeg", 0.72),+ });+ }++ return thumbnails;+ } catch {+ return [];+ } finally {+ cleanup();+ }+ }+/*** Initialize the media bridge* Connects to the MediaImportService and WaveformGenerator@@ -165,11 +267,20 @@ export class MediaBridge {{ count: 10, width: 160 },);- return thumbnails.map((thumb) => ({+ const mapped = thumbnails.map((thumb) => ({timestamp: thumb.timestamp,dataUrl: thumb.dataUrl || "",})).filter((t) => t.dataUrl);++ if (mapped.length > 0 || mediaType !== "video") {+ return mapped;+ }++ return await this.generateVideoElementThumbnails(file, 10, 160);} catch {+ if (mediaType === "video") {+ return await this.generateVideoElementThumbnails(file, 10, 160);+ }return [];}}diff --git a/apps/web/src/bridges/transition-bridge.ts b/apps/web/src/bridges/transition-bridge.tsindex 405af613..47fe4244 100644--- a/apps/web/src/bridges/transition-bridge.ts+++ b/apps/web/src/bridges/transition-bridge.ts@@ -476,8 +476,8 @@ export class TransitionBridge {* @returns The blended frame*/async renderTransition(- outgoingFrame: ImageBitmap,- incomingFrame: ImageBitmap,+ outgoingFrame: CanvasImageSource,+ incomingFrame: CanvasImageSource,transition: Transition,progress: number,): Promise<{ frame: ImageBitmap; processingTime: number } | null> {@@ -502,6 +502,29 @@ export class TransitionBridge {}}+ async renderTransitionToCanvas(+ outgoingFrame: CanvasImageSource,+ incomingFrame: CanvasImageSource,+ transition: Transition,+ progress: number,+ ): Promise<OffscreenCanvas | null> {+ if (!this.initialized || !this.transitionEngine) {+ return null;+ }++ try {+ return await this.transitionEngine.renderTransitionToCanvas(+ outgoingFrame,+ incomingFrame,+ transition,+ progress,+ );+ } catch (error) {+ console.error("[TransitionBridge] Render error:", error);+ return null;+ }+ }+/*** Clear all transitions for a track*diff --git a/apps/web/src/components/editor/EditorInterface.tsx b/apps/web/src/components/editor/EditorInterface.tsxindex c8841a32..17668c13 100644--- a/apps/web/src/components/editor/EditorInterface.tsx+++ b/apps/web/src/components/editor/EditorInterface.tsx@@ -42,6 +42,8 @@ import {const DEFAULT_TIMELINE_VH = 42;const MIN_TIMELINE_VH = 22;const MAX_TIMELINE_VH = 70;+// Compact mode: timeline takes most of the height, leaving a small preview.+const COMPACT_TIMELINE_VH = 80;const DEFAULT_MEDIA_W = 460;const MIN_MEDIA_W = 320;@@ -211,6 +213,7 @@ export const EditorInterface: React.FC = () => {getSelectedClipIds,panels,setPanelVisible,+ timelineMaximized,} = useUIStore();const { project, updateClipKeyframes } = useProjectStore();const tracks = project.timeline.tracks;@@ -378,10 +381,11 @@ export const EditorInterface: React.FC = () => {useEffect(() => {const r = rootRef.current;if (!r) return;+ const tlVh = timelineMaximized ? COMPACT_TIMELINE_VH : timelineVh;r.style.setProperty("--media-w", `${mediaWidth}px`);r.style.setProperty("--inspector-w", `${inspectorWidth}px`);- r.style.setProperty("--tl-height", `${timelineVh}vh`);- }, [mediaWidth, inspectorWidth, timelineVh]);+ r.style.setProperty("--tl-height", `${tlVh}vh`);+ }, [mediaWidth, inspectorWidth, timelineVh, timelineMaximized]);if (initializing || !initialized) {return (@@ -402,9 +406,12 @@ export const EditorInterface: React.FC = () => {// Grid template uses inline CSS for the resizable columns. The CSS// variables `--media-w`, `--inspector-w`, `--tl-height` are kept in// sync via the effect above so other components can use them too.+ const effectiveTimelineVh = timelineMaximized+ ? COMPACT_TIMELINE_VH+ : timelineVh;const gridStyle: React.CSSProperties = {gridTemplateColumns: `${mediaWidth}px ${RESIZE_HANDLE}px 1fr ${RESIZE_HANDLE}px ${inspectorWidth}px`,- gridTemplateRows: `1fr ${RESIZE_HANDLE}px ${timelineVh}vh`,+ gridTemplateRows: `1fr ${RESIZE_HANDLE}px ${effectiveTimelineVh}vh`,gridTemplateAreas:"'media mh stage ih inspector' 'th th th th th' 'timeline timeline timeline timeline timeline'",};diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsxindex b7f84b35..30adadad 100644--- a/apps/web/src/components/editor/Preview.tsx+++ b/apps/web/src/components/editor/Preview.tsx@@ -66,6 +66,7 @@ import {getTransitionAtTime,setImageLoadCallback,renderTransitionFrame,+ renderTransitionCanvas,getAnimatedTransform,applyEmphasisAnimation,CropModeView,@@ -588,6 +589,23 @@ export const Preview: React.FC = () => {const isDark = useThemeStore((state) => state.isDark);+ // The preview canvas background / letterbox bars follow the theme (matching+ // the --stage-bg token) instead of being hardcoded black, so light mode+ // shows a light stage. Kept in a ref so every render path (scrub, playback,+ // transitions) picks up the current value without re-creating callbacks.+ // Export keeps a black backdrop separately (video-engine), so exported video+ // is never letterboxed in the UI theme color.+ const previewBgRef = useRef<string>(isDark ? "#000000" : "#ffffff");+ useEffect(() => {+ const screenBg =+ typeof window !== "undefined"+ ? getComputedStyle(document.documentElement)+ .getPropertyValue("--screen-bg")+ .trim()+ : "";+ previewBgRef.current = screenBg || (isDark ? "#000000" : "#ffffff");+ }, [isDark]);+// Canvas interaction state for resize/moveconst [interactionMode, setInteractionMode] =useState<InteractionMode>("none");@@ -788,8 +806,15 @@ export const Preview: React.FC = () => {}const aspectRatio = settings.width / settings.height;- const availableWidth = Math.min(videoAreaSize.width, 800);- const availableHeight = Math.min(videoAreaSize.height, 450);+ // Fill the available preview area (minus a small margin) while preserving+ // the project aspect ratio, instead of capping at a fixed small size which+ // left the monitor floating in unused space on larger screens.+ const PREVIEW_PADDING = 24;+ const availableWidth = Math.max(1, videoAreaSize.width - PREVIEW_PADDING * 2);+ const availableHeight = Math.max(+ 1,+ videoAreaSize.height - PREVIEW_PADDING * 2,+ );let width = availableWidth;let height = width / aspectRatio;@@ -1739,7 +1764,7 @@ export const Preview: React.FC = () => {offsetX = (canvasWidth - drawWidth) / 2;}- tempCtx.fillStyle = "#000000";+ tempCtx.fillStyle = previewBgRef.current;tempCtx.fillRect(0, 0, canvasWidth, canvasHeight);tempCtx.drawImage(video, offsetX, offsetY, drawWidth, drawHeight);@@ -1861,7 +1886,7 @@ export const Preview: React.FC = () => {blendedFrame.height > 0) {if (shouldClearCanvas) {- ctx.fillStyle = "#000000";+ ctx.fillStyle = previewBgRef.current;ctx.fillRect(0, 0, canvas.width, canvas.height);shouldClearCanvas = false;}@@ -1908,7 +1933,7 @@ export const Preview: React.FC = () => {? processed: outgoingFrame;if (shouldClearCanvas) {- ctx.fillStyle = "#000000";+ ctx.fillStyle = previewBgRef.current;ctx.fillRect(0, 0, canvas.width, canvas.height);shouldClearCanvas = false;}@@ -1949,7 +1974,7 @@ export const Preview: React.FC = () => {? processed: incomingFrame;if (shouldClearCanvas) {- ctx.fillStyle = "#000000";+ ctx.fillStyle = previewBgRef.current;ctx.fillRect(0, 0, canvas.width, canvas.height);shouldClearCanvas = false;}@@ -2483,22 +2508,6 @@ export const Preview: React.FC = () => {return { canUse: false, clips: [] };}- // Native playback uses a single <video> element per active clip and a- // straight drawImage — it can't blend two clips, so any clip-to-clip- // transition in the playback range forces the multi-track path.- const hasUpcomingTransition = videoTracks.some((track) =>- track.transitions.some((t) => {- const clipA = track.clips.find((c) => c.id === t.clipAId);- if (!clipA) return false;- const transitionEnd =- clipA.startTime + clipA.duration + t.duration / 2;- return transitionEnd > startPosition;- }),- );- if (hasUpcomingTransition) {- return { canUse: false, clips: [] };- }-if (allVideoClips.length === 0) return { canUse: false, clips: [] };allVideoClips.sort((a, b) => a.clip.startTime - b.clip.startTime);@@ -2699,6 +2708,37 @@ export const Preview: React.FC = () => {return null;};+ const findNativeClipById = (clipId: string) =>+ clips.find(({ clip }) => clip.id === clipId) ?? null;++ const syncVideoToClipTime = (+ video: HTMLVideoElement,+ clip: (typeof clips)[0]["clip"],+ time: number,+ ) => {+ const speedEngine = getSpeedEngine();+ const localTime = Math.max(+ 0,+ Math.min(clip.duration, time - clip.startTime),+ );+ const adjustedLocalTime = speedEngine.getSourceTimeAtPlaybackTime(+ clip.id,+ localTime,+ );+ const sourceTime = Math.max(+ clip.inPoint,+ Math.min(clip.outPoint, clip.inPoint + adjustedLocalTime),+ );+ const vidstabPlay = getVidstabEngine();+ const videoTime = vidstabPlay.hasStabilized(clip.id)+ ? sourceTime - clip.inPoint+ : sourceTime;++ if (Math.abs(video.currentTime - videoTime) > 0.1) {+ video.currentTime = videoTime;+ }+ };+const drawFrame = async () => {if (!isActive || !nativePlaybackActiveRef.current) return;@@ -2720,10 +2760,114 @@ export const Preview: React.FC = () => {return;}+ const transitionInfo = getTransitionAtTime(+ currentPlayhead,+ timelineTracksRef.current,+ );+ if (transitionInfo) {+ const outgoingClip = findNativeClipById(transitionInfo.clipA.id);+ const incomingClip = findNativeClipById(transitionInfo.clipB.id);++ if (outgoingClip && incomingClip) {+ await Promise.all([+ loadVideoForClip(outgoingClip.clip, outgoingClip.mediaItem),+ loadVideoForClip(incomingClip.clip, incomingClip.mediaItem),+ ]);++ const outgoingCacheId = getVidstabEngine().hasStabilized(+ outgoingClip.clip.id,+ )+ ? `stabilized:${outgoingClip.clip.id}`+ : outgoingClip.clip.mediaId;+ const incomingCacheId = getVidstabEngine().hasStabilized(+ incomingClip.clip.id,+ )+ ? `stabilized:${incomingClip.clip.id}`+ : incomingClip.clip.mediaId;+ const outgoingVideo = videoCache.get(outgoingCacheId)?.video;+ const incomingVideo = videoCache.get(incomingCacheId)?.video;++ if (outgoingVideo && incomingVideo) {+ syncVideoToClipTime(+ outgoingVideo,+ outgoingClip.clip,+ currentPlayhead,+ );+ syncVideoToClipTime(+ incomingVideo,+ incomingClip.clip,+ currentPlayhead,+ );+ if (outgoingVideo.paused) outgoingVideo.play().catch(() => {});+ if (incomingVideo.paused) incomingVideo.play().catch(() => {});++ const blended = await renderTransitionCanvas(+ transitionInfo,+ outgoingVideo,+ incomingVideo,+ );+ ctx.fillStyle = previewBgRef.current;+ ctx.fillRect(0, 0, canvas.width, canvas.height);+ ctx.drawImage(blended, 0, 0, canvas.width, canvas.height);++ const activeShapeClipsTr = getActiveShapeClips(+ allShapeClipsRef.current,+ currentPlayhead,+ );+ const activeTextClipsTr = getActiveTextClips(+ allTextClipsRef.current,+ currentPlayhead,+ );+ if (+ activeShapeClipsTr.length > 0 ||+ activeTextClipsTr.length > 0+ ) {+ await renderOverlayClipsInTrackOrder(+ ctx,+ timelineTracksRef.current,+ activeShapeClipsTr,+ activeTextClipsTr,+ currentPlayhead,+ canvas.width,+ canvas.height,+ "all",+ );+ }++ const activeSubtitlesTr = getActiveSubtitles(+ allSubtitles,+ currentPlayhead,+ );+ for (const subtitle of activeSubtitlesTr) {+ renderSubtitleToCanvas(+ ctx,+ subtitle,+ canvas.width,+ canvas.height,+ currentPlayhead,+ );+ }++ const nowTransition = performance.now();+ if (+ nowTransition - lastPlayheadUpdateRef.current >=+ PLAYHEAD_UPDATE_THROTTLE_MS+ ) {+ lastPlayheadUpdateRef.current = nowTransition;+ setPlayheadPosition(currentPlayhead);+ }+ rafId = requestAnimationFrame(() => {+ drawFrame();+ });+ return;+ }+ }+ }+const activeClip = findClipAtTime(currentPlayhead);if (!activeClip) {- ctx.fillStyle = "#000000";+ ctx.fillStyle = previewBgRef.current;ctx.fillRect(0, 0, canvas.width, canvas.height);const sortedImageClipsNoVideo = [...imageClips].sort(@@ -2881,7 +3025,7 @@ export const Preview: React.FC = () => {};}- ctx.fillStyle = "#000000";+ ctx.fillStyle = previewBgRef.current;ctx.fillRect(0, 0, canvas.width, canvas.height);// Sort by track index descending (higher index = background = render first)@@ -3370,7 +3514,7 @@ export const Preview: React.FC = () => {preparedFrame.frame.height,);- ctx.fillStyle = "#000000";+ ctx.fillStyle = previewBgRef.current;ctx.fillRect(0, 0, canvas.width, canvas.height);if (useGPU && preparedFrame.frame instanceof ImageBitmap) {const gpuResult = await renderFrameWithGPU(@@ -3826,7 +3970,7 @@ export const Preview: React.FC = () => {const decodeClipFrameForTransition = async (clip: (typeof tracks)[0]["clips"][0],- ): Promise<ImageBitmap | null> => {+ ): Promise<HTMLCanvasElement | OffscreenCanvas | null> => {const resources = playbackResourcesRef.current.get(clip.id);if (!resources) return null;const speedEngine = getSpeedEngine();@@ -3849,7 +3993,7 @@ export const Preview: React.FC = () => {}).getCanvas(sourceTime);if (!result?.canvas) return null;- return await createImageBitmap(result.canvas);+ return result.canvas;} catch (error) {console.warn(`[Preview] Transition decode failed for clip ${clip.id}:`,@@ -3866,13 +4010,13 @@ export const Preview: React.FC = () => {if (outgoing && incoming) {try {- const blended = await renderTransitionFrame(+ const blended = await renderTransitionCanvas(transitionInfoMulti,outgoing,incoming,);- ctx.fillStyle = "#000000";+ ctx.fillStyle = previewBgRef.current;ctx.fillRect(0, 0, canvas.width, canvas.height);ctx.drawImage(blended, 0, 0, canvas.width, canvas.height);@@ -3909,9 +4053,6 @@ export const Preview: React.FC = () => {}mainCtx.drawImage(offscreenCanvasRef.current!, 0, 0);- blended.close();- outgoing.close();- incoming.close();frameCount++;masterClock.reportVideoTime(currentPlayhead);@@ -3949,12 +4090,7 @@ export const Preview: React.FC = () => {"[Preview] Transition render failed, falling back to normal compositing:",error,);- outgoing.close();- incoming.close();}- } else {- outgoing?.close();- incoming?.close();}}}@@ -4121,7 +4257,7 @@ export const Preview: React.FC = () => {currentTextClips.length > 0 ||currentShapeClips.length > 0) {- ctx.fillStyle = "#000000";+ ctx.fillStyle = previewBgRef.current;ctx.fillRect(0, 0, canvas.width, canvas.height);const tracks = timelineTracksRef.current;@@ -5916,7 +6052,7 @@ export const Preview: React.FC = () => {{/* Video Area */}<divref={videoAreaRef}- className={`flex-1 min-h-0 min-w-0 relative flex items-center justify-center bg-background-secondary/30 transition-all duration-300 ${+ className={`flex-1 min-h-0 min-w-0 relative flex items-center justify-center bg-stage-bg transition-all duration-300 ${isMaximized || isFullscreen ? "p-0" : "p-4"} ${zoomLevel > 1 ? "overflow-auto" : ""}`}onMouseMove={interactionMode !== "none" ? handleMouseMove : undefined}@@ -5924,10 +6060,12 @@ export const Preview: React.FC = () => {><divref={overlayRef}- className={`relative bg-black overflow-visible transition-all duration-300 ${+ className={`relative bg-[var(--screen-bg)] overflow-visible transition-all duration-300 ${isMaximized || isFullscreen? "rounded-none ring-0 shadow-none"- : "shadow-2xl rounded-xl ring-1 ring-border shadow-[0_0_50px_rgba(0,0,0,0.5)]"+ : isDark+ ? "shadow-2xl rounded-xl ring-1 ring-border shadow-[0_0_50px_rgba(0,0,0,0.5)]"+ : "rounded-xl ring-1 ring-border shadow-[0_10px_40px_rgba(0,0,0,0.1)]"}`}style={isMaximized || isFullscreen@@ -5951,7 +6089,7 @@ export const Preview: React.FC = () => {ref={canvasRef}width={settings.width}height={settings.height}- className="w-full h-full object-contain bg-black"+ className="w-full h-full object-contain bg-[var(--screen-bg)]"style={{cursor: hoveredGraphicClipId && !isPlaying ? "pointer" : "default",}}diff --git a/apps/web/src/components/editor/Timeline.tsx b/apps/web/src/components/editor/Timeline.tsxindex 03ab196d..fc82b3ea 100644--- a/apps/web/src/components/editor/Timeline.tsx+++ b/apps/web/src/components/editor/Timeline.tsx@@ -10,6 +10,7 @@ import {Redo2,Layers,Maximize2,+ Minimize2,Film,Music,Image,@@ -99,8 +100,16 @@ export const Timeline: React.FC = () => {const [showLayersPanel, setShowLayersPanel] = useState(false);- const { select, selectMultiple, clearSelection, getSelectedClipIds, snapSettings, toggleSnap } =- useUIStore();+ const {+ select,+ selectMultiple,+ clearSelection,+ getSelectedClipIds,+ snapSettings,+ toggleSnap,+ timelineMaximized,+ toggleTimelineMaximized,+ } = useUIStore();const selectedClipIds = getSelectedClipIds();const { getTitleEngine, getGraphicsEngine } = useEngineStore();@@ -224,13 +233,20 @@ export const Timeline: React.FC = () => {useEffect(() => {if (playbackState !== "playing") return;+ const el = tracksRef.current;+ if (!el) return;const playheadPixels = playheadPosition * pixelsPerSecond;- const visibleEnd = scrollX + viewportWidth - 150;-- if (playheadPixels > visibleEnd && tracksRef.current) {- const newScrollX = playheadPixels - viewportWidth + 200;- tracksRef.current.scrollLeft = Math.max(0, newScrollX);+ // Keep the playhead in the left portion of the viewport during playback so+ // most of the upcoming timeline stays visible. When it crosses near the+ // right edge (or jumps out of view via a seek/loop), page the view so the+ // playhead lands back near the left with the rest as lookahead — instead of+ // pinning it at the end on a long timeline.+ const leftMargin = Math.min(Math.max(viewportWidth * 0.12, 60), 220);+ const followThreshold = scrollX + viewportWidth - leftMargin;++ if (playheadPixels > followThreshold || playheadPixels < scrollX) {+ el.scrollLeft = Math.max(0, playheadPixels - leftMargin);}}, [playheadPosition, playbackState, pixelsPerSecond, scrollX, viewportWidth]);@@ -926,8 +942,20 @@ export const Timeline: React.FC = () => {</TLTool></div>- <TLTool title="Maximize timeline">- <Maximize2 size={14} />+ <TLTool+ onClick={toggleTimelineMaximized}+ active={timelineMaximized}+ title={+ timelineMaximized+ ? "Restore layout"+ : "Maximize timeline (more room)"+ }+ >+ {timelineMaximized ? (+ <Minimize2 size={14} />+ ) : (+ <Maximize2 size={14} />+ )}</TLTool></div></div>@@ -939,7 +967,7 @@ export const Timeline: React.FC = () => {><div className="flex shrink-0"><div className="w-32 h-[26px] bg-bg-1 border-b border-r border-border shrink-0" />- <div className="flex-1 overflow-hidden relative">+ <div className="flex-1 overflow-hidden relative bg-bg-1 border-b border-border"><divstyle={{width: `${timelineDuration * pixelsPerSecond}px`,diff --git a/apps/web/src/components/editor/preview/canvas-renderers.ts b/apps/web/src/components/editor/preview/canvas-renderers.tsindex ce54804d..37e89a69 100644--- a/apps/web/src/components/editor/preview/canvas-renderers.ts+++ b/apps/web/src/components/editor/preview/canvas-renderers.ts@@ -2129,3 +2129,38 @@ export const renderTransitionFrame = async (return transitionInfo.progress < 0.5 ? outgoingFrame : incomingFrame;}};++export const renderTransitionCanvas = async (+ transitionInfo: TransitionRenderInfo,+ outgoingFrame: CanvasImageSource,+ incomingFrame: CanvasImageSource,+): Promise<CanvasImageSource> => {+ try {+ const transitionBridge = getTransitionBridge();+ if (!transitionBridge.isInitialized()) {+ return transitionInfo.progress < 0.5 ? outgoingFrame : incomingFrame;+ }++ const transition = transitionBridge.getTransition(+ transitionInfo.transitionId,+ );+ if (!transition) {+ return transitionInfo.progress < 0.5 ? outgoingFrame : incomingFrame;+ }++ const canvas = await transitionBridge.renderTransitionToCanvas(+ outgoingFrame,+ incomingFrame,+ transition,+ transitionInfo.progress,+ );++ if (canvas && canvas.width > 0 && canvas.height > 0) {+ return canvas;+ }++ return transitionInfo.progress < 0.5 ? outgoingFrame : incomingFrame;+ } catch {+ return transitionInfo.progress < 0.5 ? outgoingFrame : incomingFrame;+ }+};diff --git a/apps/web/src/index.css b/apps/web/src/index.cssindex 81778bb3..bc2666b3 100644--- a/apps/web/src/index.css+++ b/apps/web/src/index.css@@ -58,7 +58,11 @@--track-bg: oklch(0.95 0.005 240);--tl-bg: oklch(0.93 0.005 240);--waveform: oklch(0.72 0.16 162 / 0.55);- --stage-bg: oklch(0.18 0.005 240);+ /* preview stage: white in light mode so the area around the monitor+ matches the other white surfaces instead of a grey cinema stage */+ --stage-bg: oklch(1 0 0);+ /* the preview "screen" itself (canvas + letterbox): white in light */+ --screen-bg: oklch(1 0 0);/* accent (emerald) */--accent: oklch(0.72 0.16 162);@@ -97,6 +101,8 @@--tl-bg: oklch(0.1 0.005 240);--waveform: oklch(0.78 0.16 162 / 0.85);--stage-bg: oklch(0.08 0.004 240);+ /* the preview "screen" itself (canvas + letterbox): black in dark */+ --screen-bg: oklch(0 0 0);--accent: oklch(0.72 0.16 162);--accent-strong: oklch(0.66 0.18 162);diff --git a/apps/web/src/stores/project-store.ts b/apps/web/src/stores/project-store.tsindex 6e2a2929..0d03dc15 100644--- a/apps/web/src/stores/project-store.ts+++ b/apps/web/src/stores/project-store.ts@@ -1720,6 +1720,26 @@ export const useProjectStore = create<ProjectState>()(mediaType = "image";}+ if (mediaType === "video" && !thumbnailUrl) {+ try {+ const thumbs = await mediaBridge.generateThumbnailsForMedia(+ processedMedia.blob ?? file,+ mediaType,+ );+ if (thumbs.length > 0) {+ thumbnailUrl = thumbs[0].dataUrl;+ filmstripThumbnails.push(+ ...thumbs.map((thumb) => ({+ timestamp: thumb.timestamp,+ url: thumb.dataUrl,+ })),+ );+ }+ } catch {+ // Background retry below is best-effort.+ }+ }+const newMediaItem: MediaItem = {id: uuidv4(),name: file.name,@@ -1766,11 +1786,11 @@ export const useProjectStore = create<ProjectState>()(console.error("[ProjectStore] Failed to persist media blob:", err);}- if (isLargeFile && !thumbnailUrl) {+ if (mediaType === "video" && !thumbnailUrl) {setTimeout(async () => {try {const thumbs = await mediaBridge.generateThumbnailsForMedia(- file,+ newMediaItem.blob ?? file,mediaType,);if (thumbs.length > 0) {@@ -1795,6 +1815,7 @@ export const useProjectStore = create<ProjectState>()(...currentProject.mediaLibrary,items: updatedItems,},+ modifiedAt: Date.now(),},});}@@ -1903,14 +1924,36 @@ export const useProjectStore = create<ProjectState>()(}}+ const mediaType = processedMedia.metadata.hasVideo+ ? "video"+ : processedMedia.metadata.hasAudio+ ? "audio"+ : "image";++ if (mediaType === "video" && !thumbnailUrl) {+ try {+ const thumbs = await mediaBridge.generateThumbnailsForMedia(+ processedMedia.blob ?? file,+ mediaType,+ );+ if (thumbs.length > 0) {+ thumbnailUrl = thumbs[0].dataUrl;+ filmstripThumbnails.push(+ ...thumbs.map((thumb) => ({+ timestamp: thumb.timestamp,+ url: thumb.dataUrl,+ })),+ );+ }+ } catch {+ // Background retry below is best-effort.+ }+ }+const updatedItem: MediaItem = {id: mediaId,name: file.name,- type: processedMedia.metadata.hasVideo- ? "video"- : processedMedia.metadata.hasAudio- ? "audio"- : "image",+ type: mediaType,fileHandle: null,blob: file,metadata: {@@ -1945,6 +1988,42 @@ export const useProjectStore = create<ProjectState>()(},});+ if (updatedItem.type === "video" && !updatedItem.thumbnailUrl) {+ setTimeout(async () => {+ try {+ const thumbs = await mediaBridge.generateThumbnailsForMedia(+ updatedItem.blob ?? file,+ updatedItem.type,+ );+ if (thumbs.length > 0) {+ const currentProject = get().project;+ const updatedItemsWithThumbs =+ currentProject.mediaLibrary.items.map((item) =>+ item.id === mediaId+ ? {+ ...item,+ thumbnailUrl: thumbs[0].dataUrl,+ filmstripThumbnails: thumbs.map((thumb) => ({+ timestamp: thumb.timestamp,+ url: thumb.dataUrl,+ })),+ }+ : item,+ );+ set({+ project: {+ ...currentProject,+ mediaLibrary: { items: updatedItemsWithThumbs },+ modifiedAt: Date.now(),+ },+ });+ }+ } catch {+ // Background thumbnail generation is best-effort+ }+ }, 100);+ }+return {success: true,actionId: uuidv4(),diff --git a/apps/web/src/stores/ui-store.ts b/apps/web/src/stores/ui-store.tsindex b35c04a9..5497832d 100644--- a/apps/web/src/stores/ui-store.ts+++ b/apps/web/src/stores/ui-store.ts@@ -70,6 +70,7 @@ export interface UIState {showThumbnails: boolean;showKeyframes: boolean;autoScroll: boolean;+ timelineMaximized: boolean;activeModal: string | null;modalData: Record<string, unknown> | null;contextMenu: {@@ -115,6 +116,8 @@ export interface UIState {setShowThumbnails: (show: boolean) => void;setShowKeyframes: (show: boolean) => void;setAutoScroll: (enabled: boolean) => void;+ setTimelineMaximized: (maximized: boolean) => void;+ toggleTimelineMaximized: () => void;openModal: (modalId: string, data?: Record<string, unknown>) => void;closeModal: () => void;showContextMenu: (x: number, y: number, items: ContextMenuItem[]) => void;@@ -210,6 +213,7 @@ export const useUIStore = create<UIState>()(showThumbnails: true,showKeyframes: true,autoScroll: true,+ timelineMaximized: false,activeModal: null,modalData: null,@@ -475,6 +479,14 @@ export const useUIStore = create<UIState>()(set({ autoScroll: enabled });},+ setTimelineMaximized: (maximized: boolean) => {+ set({ timelineMaximized: maximized });+ },++ toggleTimelineMaximized: () => {+ set((state) => ({ timelineMaximized: !state.timelineMaximized }));+ },+openModal: (modalId: string, data?: Record<string, unknown>) => {set({activeModal: modalId,@@ -577,6 +589,7 @@ export const useUIStore = create<UIState>()(showThumbnails: state.showThumbnails,showKeyframes: state.showKeyframes,autoScroll: state.autoScroll,+ timelineMaximized: state.timelineMaximized,skipWelcomeScreen: state.skipWelcomeScreen,inspectorActiveTab: state.inspectorActiveTab,}),diff --git a/packages/core/src/video/transition-engine.ts b/packages/core/src/video/transition-engine.tsindex e489a689..b58021ec 100644--- a/packages/core/src/video/transition-engine.ts+++ b/packages/core/src/video/transition-engine.ts@@ -28,8 +28,13 @@ export class TransitionEngine {private width: number;private height: number;private initialized = false;- private scratch: OffscreenCanvas | null = null;- private scratchCtx: OffscreenCanvasRenderingContext2D | null = null;+ // Two reusable letterbox scratch canvases (outgoing + incoming are both live+ // during a blend, so they cannot share one). Kept as canvases — not+ // ImageBitmaps — so fitting costs zero createImageBitmap per frame.+ private scratchA: OffscreenCanvas | null = null;+ private scratchACtx: OffscreenCanvasRenderingContext2D | null = null;+ private scratchB: OffscreenCanvas | null = null;+ private scratchBCtx: OffscreenCanvasRenderingContext2D | null = null;constructor(config: TransitionEngineConfig) {this.width = config.width;@@ -62,34 +67,55 @@ export class TransitionEngine {return this.ctx;}- // Letterbox (contain) a source frame into an engine-sized frame so the- // per-transition geometry — which assumes inputs already fill the canvas —- // preserves the source aspect ratio instead of stretching it. Returns the- // original frame untouched when it is already engine-sized (e.g. the- // scrub path pre-letterboxes), so callers must only close the result when- // it differs from the input.- private async fitToCanvas(source: ImageBitmap): Promise<ImageBitmap> {- if (source.width === this.width && source.height === this.height) {+ private sourceDimensions(source: CanvasImageSource): {+ width: number;+ height: number;+ } {+ if (+ typeof HTMLVideoElement !== "undefined" &&+ source instanceof HTMLVideoElement+ ) {+ return { width: source.videoWidth, height: source.videoHeight };+ }+ const dims = source as { width?: number; height?: number };+ return { width: dims.width ?? 0, height: dims.height ?? 0 };+ }++ // Letterbox (contain) a source frame into an engine-sized scratch canvas so+ // the per-transition geometry — which assumes inputs already fill the canvas+ // — preserves the source aspect ratio instead of stretching it. Returns the+ // original frame untouched when it is already engine-sized (e.g. the scrub+ // path pre-letterboxes). Uses a reusable scratch canvas (no createImageBitmap)+ // so it is cheap to run every frame during playback/export.+ private fitToCanvas(+ source: CanvasImageSource,+ slot: "A" | "B",+ ): CanvasImageSource {+ const { width: sourceWidth, height: sourceHeight } =+ this.sourceDimensions(source);+ if (sourceWidth === this.width && sourceHeight === this.height) {return source;}if (typeof OffscreenCanvas === "undefined") {return source;}- const sourceWidth = source.width;- const sourceHeight = source.height;if (sourceWidth <= 0 || sourceHeight <= 0) {return source;}- if (- !this.scratch ||- this.scratch.width !== this.width ||- this.scratch.height !== this.height- ) {- this.scratch = new OffscreenCanvas(this.width, this.height);- this.scratchCtx = this.scratch.getContext("2d");+ let scratch = slot === "A" ? this.scratchA : this.scratchB;+ let scratchCtx = slot === "A" ? this.scratchACtx : this.scratchBCtx;+ if (!scratch || scratch.width !== this.width || scratch.height !== this.height) {+ scratch = new OffscreenCanvas(this.width, this.height);+ scratchCtx = scratch.getContext("2d");+ if (slot === "A") {+ this.scratchA = scratch;+ this.scratchACtx = scratchCtx;+ } else {+ this.scratchB = scratch;+ this.scratchBCtx = scratchCtx;+ }}- const scratchCtx = this.scratchCtx;if (!scratchCtx) {return source;}@@ -110,16 +136,37 @@ export class TransitionEngine {scratchCtx.clearRect(0, 0, this.width, this.height);scratchCtx.drawImage(source, drawX, drawY, drawWidth, drawHeight);- return await createImageBitmap(this.scratch);+ return scratch;}async renderTransition(- outgoingFrame: ImageBitmap,- incomingFrame: ImageBitmap,+ outgoingFrame: CanvasImageSource,+ incomingFrame: CanvasImageSource,transition: Transition,progress: number,): Promise<TransitionRenderResult> {const startTime = performance.now();+ const canvas = await this.renderTransitionToCanvas(+ outgoingFrame,+ incomingFrame,+ transition,+ progress,+ );+ const frame = await createImageBitmap(canvas);++ return {+ frame,+ processingTime: performance.now() - startTime,+ gpuAccelerated: false, // Canvas 2D is not GPU accelerated+ };+ }++ async renderTransitionToCanvas(+ outgoingFrame: CanvasImageSource,+ incomingFrame: CanvasImageSource,+ transition: Transition,+ progress: number,+ ): Promise<OffscreenCanvas> {if (!this.canvas || !this.ctx) {throw new Error("Canvas not available. Rendering requires a browser environment.",@@ -136,8 +183,8 @@ export class TransitionEngine {// keeps its orientation through the transition instead of being stretched// to fill. The scrub path already passes engine-sized frames, so this is a// no-op there; the multitrack-preview and export paths pass native frames.- const outgoing = await this.fitToCanvas(outgoingFrame);- const incoming = await this.fitToCanvas(incomingFrame);+ const outgoing = this.fitToCanvas(outgoingFrame, "A");+ const incoming = this.fitToCanvas(incomingFrame, "B");this.ctx.clearRect(0, 0, this.width, this.height);switch (transition.type) {@@ -204,23 +251,12 @@ export class TransitionEngine {await this.renderCrossfade(outgoing, incoming, easedProgress);}- const frame = await createImageBitmap(this.canvas);-- // fitToCanvas returns the original when it is already engine-sized, so- // only close the letterboxed copies we actually allocated.- if (outgoing !== outgoingFrame) outgoing.close();- if (incoming !== incomingFrame) incoming.close();-- return {- frame,- processingTime: performance.now() - startTime,- gpuAccelerated: false, // Canvas 2D is not GPU accelerated- };+ return this.canvas;}private async renderCrossfade(- outgoing: ImageBitmap,- incoming: ImageBitmap,+ outgoing: CanvasImageSource,+ incoming: CanvasImageSource,progress: number,): Promise<void> {const ctx = this.getContext();@@ -235,8 +271,8 @@ export class TransitionEngine {}private async renderDipToColor(- outgoing: ImageBitmap,- incoming: ImageBitmap,+ outgoing: CanvasImageSource,+ incoming: CanvasImageSource,progress: number,color: "black" | "white",holdDuration: number,@@ -271,112 +307,54 @@ export class TransitionEngine {}private async renderWipe(- outgoing: ImageBitmap,- incoming: ImageBitmap,+ outgoing: CanvasImageSource,+ incoming: CanvasImageSource,progress: number,direction: string,- softness: number,+ _softness: number,): Promise<void> {const ctx = this.getContext();- // Draw outgoing frame as base- ctx.drawImage(outgoing, 0, 0, this.width, this.height);+ const w = this.width;+ const h = this.height;++ // Outgoing is the base; the incoming frame is revealed inside a region+ // that grows from nothing (progress 0 → outgoing fully visible) to the+ // whole canvas (progress 1 → incoming fully visible). Each direction is the+ // edge the incoming frame wipes in from.+ ctx.drawImage(outgoing, 0, 0, w, h);ctx.save();-- const softPixels = softness * Math.max(this.width, this.height) * 0.1;-+ ctx.beginPath();switch (direction) {- case "left":- this.createWipeClip(- ctx,- progress * this.width,- 0,- this.width,- this.height,- );- break;case "right":- this.createWipeClip(- ctx,- 0,- 0,- this.width * (1 - progress),- this.height,- true,- );+ ctx.rect(w * (1 - progress), 0, w * progress, h);break;case "up":- this.createWipeClip(- ctx,- 0,- progress * this.height,- this.width,- this.height,- );+ ctx.rect(0, 0, w, h * progress);break;case "down":- this.createWipeClip(- ctx,- 0,- 0,- this.width,- this.height * (1 - progress),- true,- );+ ctx.rect(0, h * (1 - progress), w, h * progress);break;- case "diagonal":- this.createDiagonalWipeClip(ctx, progress);+ case "diagonal": {+ const offset = (w + h) * progress;+ ctx.moveTo(0, 0);+ ctx.lineTo(offset, 0);+ ctx.lineTo(0, offset);+ ctx.closePath();break;+ }+ case "left":default:- this.createWipeClip(- ctx,- progress * this.width,- 0,- this.width,- this.height,- );- }- if (softness > 0 && softPixels > 0) {- ctx.globalAlpha = 0.8; // Slight softening effect- }-- ctx.drawImage(incoming, 0, 0, this.width, this.height);- ctx.restore();- }-- private createWipeClip(- ctx: OffscreenCanvasRenderingContext2D,- x: number,- y: number,- width: number,- height: number,- invert: boolean = false,- ): void {- ctx.beginPath();- if (invert) {- ctx.rect(width, y, this.width - width, height);- } else {- ctx.rect(x, y, width - x, height - y);+ ctx.rect(0, 0, w * progress, h);+ break;}ctx.clip();- }-- private createDiagonalWipeClip(- ctx: OffscreenCanvasRenderingContext2D,- progress: number,- ): void {- const offset = (this.width + this.height) * progress;- ctx.beginPath();- ctx.moveTo(offset, 0);- ctx.lineTo(offset - this.height, this.height);- ctx.lineTo(this.width, this.height);- ctx.lineTo(this.width, 0);- ctx.closePath();- ctx.clip();+ ctx.drawImage(incoming, 0, 0, w, h);+ ctx.restore();}private async renderSlide(- outgoing: ImageBitmap,- incoming: ImageBitmap,+ outgoing: CanvasImageSource,+ incoming: CanvasImageSource,progress: number,direction: string,pushOut: boolean,@@ -416,8 +394,8 @@ export class TransitionEngine {}private async renderZoom(- outgoing: ImageBitmap,- incoming: ImageBitmap,+ outgoing: CanvasImageSource,+ incoming: CanvasImageSource,progress: number,scale: number,center: { x: number; y: number },@@ -453,8 +431,8 @@ export class TransitionEngine {}private async renderPush(- outgoing: ImageBitmap,- incoming: ImageBitmap,+ outgoing: CanvasImageSource,+ incoming: CanvasImageSource,progress: number,direction: string,): Promise<void> {