Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript

fix: resolve export crashes, optimize file size, and speed up imports

Augustus Otuf9304f17f3fc
diff --git a/apps/web/src/bridges/media-bridge.test.ts b/apps/web/src/bridges/media-bridge.test.ts
index 60c7aa57..202dc25c 100644
--- a/apps/web/src/bridges/media-bridge.test.ts
+++ b/apps/web/src/bridges/media-bridge.test.ts
@@ -320,3 +320,120 @@ describe("MediaBridge - Error Handling", () => {
expect(result.success).toBe(false);
});
});
+
+describe("MediaBridge - Quick Mode Import", () => {
+ let mediaBridge: MediaBridge;
+
+ beforeEach(() => {
+ mediaBridge = new MediaBridge();
+ mockImportMedia.mockReset();
+ });
+
+ it("should pass quickMode=true to import service when specified", async () => {
+ mockImportMedia.mockResolvedValue({
+ success: true,
+ media: {
+ id: "large-file-id",
+ name: "large-video.mp4",
+ type: "video",
+ metadata: {
+ duration: 600,
+ width: 1920,
+ height: 1080,
+ frameRate: 30,
+ codec: "h264",
+ sampleRate: 48000,
+ channels: 2,
+ fileSize: 100000000,
+ },
+ thumbnails: [],
+ waveformData: null,
+ },
+ });
+
+ await mediaBridge.initialize();
+ const file = new File(["test"], "large-video.mp4", { type: "video/mp4" });
+
+ const result = await mediaBridge.importFile(file, true, true);
+
+ expect(mockImportMedia).toHaveBeenCalledWith(
+ file,
+ expect.objectContaining({
+ quickMode: true,
+ generateThumbnails: false,
+ generateWaveform: false,
+ }),
+ );
+ expect(result.success).toBe(true);
+ });
+
+ it("should not skip thumbnails when quickMode is false", async () => {
+ mockImportMedia.mockResolvedValue({
+ success: true,
+ media: {
+ id: "normal-file-id",
+ name: "video.mp4",
+ type: "video",
+ metadata: {
+ duration: 10,
+ width: 1920,
+ height: 1080,
+ frameRate: 30,
+ codec: "h264",
+ sampleRate: 48000,
+ channels: 2,
+ fileSize: 1000000,
+ },
+ thumbnails: [{ timestamp: 0, dataUrl: "data:image/jpeg;base64,abc" }],
+ waveformData: null,
+ },
+ });
+
+ await mediaBridge.initialize();
+ const file = new File(["test"], "video.mp4", { type: "video/mp4" });
+
+ const result = await mediaBridge.importFile(file, true, false);
+
+ expect(mockImportMedia).toHaveBeenCalledWith(
+ file,
+ expect.objectContaining({
+ quickMode: false,
+ generateThumbnails: true,
+ generateWaveform: true,
+ }),
+ );
+ expect(result.success).toBe(true);
+ });
+
+ it("should return success even without thumbnails in quick mode", async () => {
+ mockImportMedia.mockResolvedValue({
+ success: true,
+ media: {
+ id: "quick-import-id",
+ name: "large-video.mp4",
+ type: "video",
+ metadata: {
+ duration: 300,
+ width: 3840,
+ height: 2160,
+ frameRate: 30,
+ codec: "h264",
+ sampleRate: 48000,
+ channels: 2,
+ fileSize: 500000000,
+ },
+ thumbnails: [],
+ waveformData: null,
+ },
+ });
+
+ await mediaBridge.initialize();
+ const file = new File(["test"], "4k-video.mp4", { type: "video/mp4" });
+
+ const result = await mediaBridge.importFile(file, true, true);
+
+ expect(result.success).toBe(true);
+ expect(result.media?.thumbnails).toEqual([]);
+ expect(result.hasWaveform).toBe(false);
+ });
+});
diff --git a/apps/web/src/bridges/media-bridge.ts b/apps/web/src/bridges/media-bridge.ts
index 803a64c7..bc29f1ae 100644
--- a/apps/web/src/bridges/media-bridge.ts
+++ b/apps/web/src/bridges/media-bridge.ts
@@ -90,6 +90,7 @@ export class MediaBridge {
async importFile(
file: File,
generateWaveform = true,
+ quickMode = false,
): Promise<MediaBridgeImportResult> {
if (!this.initialized || !this.mediaImportService) {
return {
@@ -99,24 +100,20 @@ export class MediaBridge {
};
}
- // Capture current project state for rollback on failure
- // Maintain current state on failed import
const projectStateBefore = this.captureProjectState();
try {
- // Import the media file
- // Generate more thumbnails for filmstrip display (10 thumbnails at different timestamps)
const result = await this.mediaImportService.importMedia(file, {
- generateThumbnails: true,
- thumbnailCount: 10, // More thumbnails for better filmstrip effect
- thumbnailWidth: 160, // Smaller width for filmstrip thumbnails
- generateWaveform,
+ generateThumbnails: !quickMode,
+ thumbnailCount: 10,
+ thumbnailWidth: 160,
+ generateWaveform: generateWaveform && !quickMode,
waveformSamplesPerSecond: 100,
useFallback: true,
+ quickMode,
});
if (!result.success || !result.media) {
- // Display error message and maintain current state
return {
success: false,
error: result.error || "Import failed",
@@ -125,8 +122,6 @@ export class MediaBridge {
};
}
- // Validate metadata extraction
- // Extract metadata (duration, dimensions, codec)
const metadata = result.media.metadata;
if (!this.validateMetadata(metadata)) {
return {
@@ -143,7 +138,6 @@ export class MediaBridge {
hasWaveform: result.media.waveformData !== null,
};
} catch (error) {
- // Maintain current state on failed import
this.restoreProjectState(projectStateBefore);
const errorMessage =
@@ -156,6 +150,30 @@ export class MediaBridge {
}
}
+ async generateThumbnailsForMedia(
+ file: File | Blob,
+ mediaType: "video" | "audio" | "image",
+ ): Promise<{ timestamp: number; dataUrl: string }[]> {
+ if (!this.initialized || !this.mediaImportService) {
+ return [];
+ }
+
+ try {
+ const thumbnails = await this.mediaImportService.generateThumbnailsForMedia(
+ file,
+ mediaType,
+ { count: 10, width: 160 },
+ );
+
+ return thumbnails.map((thumb) => ({
+ timestamp: thumb.timestamp,
+ dataUrl: thumb.dataUrl || "",
+ })).filter((t) => t.dataUrl);
+ } catch {
+ return [];
+ }
+ }
+
/**
* Import multiple media files
*
diff --git a/apps/web/src/stores/project-store.ts b/apps/web/src/stores/project-store.ts
index 879c28d8..ac80ace9 100644
--- a/apps/web/src/stores/project-store.ts
+++ b/apps/web/src/stores/project-store.ts
@@ -480,14 +480,13 @@ export const useProjectStore = create<ProjectState>()(
const { project } = get();
try {
- // Initialize and use MediaBridge for proper media processing
const mediaBridge = getMediaBridge();
if (!mediaBridge.isInitialized()) {
await initializeMediaBridge();
}
- // Import the file with full processing (thumbnails, waveforms, metadata)
- const importResult = await mediaBridge.importFile(file, true);
+ const isLargeFile = file.size > 50 * 1024 * 1024;
+ const importResult = await mediaBridge.importFile(file, true, isLargeFile);
if (!importResult.success || !importResult.media) {
return {
@@ -584,7 +583,6 @@ export const useProjectStore = create<ProjectState>()(
filmstripThumbnails.length > 0 ? filmstripThumbnails : undefined,
};
- // Add to media library
const updatedProject = {
...project,
mediaLibrary: {
@@ -607,6 +605,45 @@ export const useProjectStore = create<ProjectState>()(
console.error("[ProjectStore] Failed to persist media blob:", err);
}
+ if (isLargeFile && !thumbnailUrl) {
+ setTimeout(async () => {
+ try {
+ const thumbs = await mediaBridge.generateThumbnailsForMedia(
+ file,
+ mediaType,
+ );
+ if (thumbs.length > 0) {
+ const currentProject = get().project;
+ const mediaIndex = currentProject.mediaLibrary.items.findIndex(
+ (m) => m.id === newMediaItem.id,
+ );
+ if (mediaIndex !== -1) {
+ const updatedItems = [...currentProject.mediaLibrary.items];
+ updatedItems[mediaIndex] = {
+ ...updatedItems[mediaIndex],
+ thumbnailUrl: thumbs[0].dataUrl,
+ filmstripThumbnails: thumbs.map((t) => ({
+ timestamp: t.timestamp,
+ url: t.dataUrl,
+ })),
+ };
+ set({
+ project: {
+ ...currentProject,
+ mediaLibrary: {
+ ...currentProject.mediaLibrary,
+ items: updatedItems,
+ },
+ },
+ });
+ }
+ }
+ } catch {
+ // Background thumbnail generation is best-effort
+ }
+ }, 100);
+ }
+
return {
success: true,
actionId: newMediaItem.id,
diff --git a/packages/core/src/export/export-engine.ts b/packages/core/src/export/export-engine.ts
index 6a87fa6d..71e36b99 100644
--- a/packages/core/src/export/export-engine.ts
+++ b/packages/core/src/export/export-engine.ts
@@ -270,13 +270,10 @@ export class ExportEngine {
this.abortController = new AbortController();
this.currentExport = { startTime: Date.now(), framesRendered: 0 };
- const gpuEnabled = await this.initializeGPUForExport(
+ await this.initializeGPUForExport(
fullSettings.width,
fullSettings.height,
);
- if (gpuEnabled) {
- } else {
- }
const { timeline } = project;
const timelineDuration = this.calculateTimelineDuration(timeline);
diff --git a/packages/core/src/media/ffmpeg-fallback.ts b/packages/core/src/media/ffmpeg-fallback.ts
index 6be3acf1..1ce4c213 100644
--- a/packages/core/src/media/ffmpeg-fallback.ts
+++ b/packages/core/src/media/ffmpeg-fallback.ts
@@ -90,6 +90,14 @@ export class FFmpegFallback {
| ((data: { progress: number; time?: number }) => void)
| null = null;
+ private calculateBufsize(bitrate: string): string {
+ const match = bitrate.match(/^(\d+(?:\.\d+)?)\s*([KkMmGg]?)$/);
+ if (!match) return bitrate;
+ const value = parseFloat(match[1]);
+ const unit = match[2] || "";
+ return `${Math.round(value * 2)}${unit}`;
+ }
+
async load(): Promise<void> {
if (this.loaded) return;
if (this.loading) return this.loading;
@@ -105,19 +113,35 @@ export class FFmpegFallback {
this.ffmpeg = new FFmpeg() as unknown as FFmpegInstance;
- const baseURL = "https://unpkg.com/@ffmpeg/[email protected]/dist/esm";
-
- const [coreURL, wasmURL, workerURL] = await Promise.all([
- toBlobURL(`${baseURL}/ffmpeg-core.js`, "text/javascript"),
- toBlobURL(`${baseURL}/ffmpeg-core.wasm`, "application/wasm"),
- toBlobURL(`${baseURL}/ffmpeg-core.worker.js`, "text/javascript"),
- ]);
+ const useMultiThread = typeof crossOriginIsolated !== "undefined" && crossOriginIsolated;
+ const baseURL = useMultiThread
+ ? "https://unpkg.com/@ffmpeg/[email protected]/dist/esm"
+ : "https://unpkg.com/@ffmpeg/[email protected]/dist/esm";
+
+ if (useMultiThread) {
+ const [coreURL, wasmURL, workerURL] = await Promise.all([
+ toBlobURL(`${baseURL}/ffmpeg-core.js`, "text/javascript"),
+ toBlobURL(`${baseURL}/ffmpeg-core.wasm`, "application/wasm"),
+ toBlobURL(`${baseURL}/ffmpeg-core.worker.js`, "text/javascript"),
+ ]);
+
+ await this.ffmpeg.load({
+ coreURL,
+ wasmURL,
+ workerURL,
+ });
+ } else {
+ const [coreURL, wasmURL] = await Promise.all([
+ toBlobURL(`${baseURL}/ffmpeg-core.js`, "text/javascript"),
+ toBlobURL(`${baseURL}/ffmpeg-core.wasm`, "application/wasm"),
+ ]);
+
+ await this.ffmpeg.load({
+ coreURL,
+ wasmURL,
+ });
+ }
- await this.ffmpeg.load({
- coreURL,
- wasmURL,
- workerURL,
- });
this.loaded = true;
} catch (error) {
this.loading = null;
@@ -600,17 +624,9 @@ export class FFmpegFallback {
} = options;
const outputFilename = `output.${format}`;
- const tempDir = "frames";
let frameCount = 0;
try {
- try {
- await this.ffmpeg!.listDir(tempDir);
- } catch {
- await this.ffmpeg!.exec(["-f", "lavfi", "-i", "nullsrc=s=1x1:d=0.001", "-frames:v", "0", "-y", "/dev/null"]);
- }
-
- const framePromises: Promise<void>[] = [];
const BATCH_SIZE = 10;
for await (const { image, frameIndex } of frames) {
@@ -649,8 +665,6 @@ export class FFmpegFallback {
}
}
- await Promise.all(framePromises);
-
let hasAudio = false;
if (audioBuffer && audioBuffer.length > 0) {
const wavBlob = this.encodeAudioBufferToWav(audioBuffer);
@@ -687,17 +701,19 @@ export class FFmpegFallback {
if (format === "mp4") {
ffmpegArgs.push(
"-c:v", "libx264",
- "-preset", "ultrafast",
+ "-preset", "fast",
"-crf", "23",
- "-b:v", videoBitrate,
+ "-maxrate", videoBitrate,
+ "-bufsize", this.calculateBufsize(videoBitrate),
"-pix_fmt", "yuv420p",
);
} else {
ffmpegArgs.push(
"-c:v", "libvpx-vp9",
- "-b:v", videoBitrate,
- "-deadline", "realtime",
- "-cpu-used", "8",
+ "-crf", "31",
+ "-b:v", "0",
+ "-deadline", "good",
+ "-cpu-used", "4",
"-row-mt", "1",
);
}
@@ -934,9 +950,10 @@ export class FFmpegFallback {
if (format === "mp4") {
ffmpegArgs.push(
"-c:v", "libx264",
- "-preset", "ultrafast",
+ "-preset", "fast",
"-crf", "23",
- "-b:v", videoBitrate,
+ "-maxrate", videoBitrate,
+ "-bufsize", this.calculateBufsize(videoBitrate),
"-pix_fmt", "yuv420p",
"-c:a", "aac",
"-b:a", audioBitrate,
@@ -944,9 +961,10 @@ export class FFmpegFallback {
} else {
ffmpegArgs.push(
"-c:v", "libvpx-vp9",
- "-b:v", videoBitrate,
- "-deadline", "realtime",
- "-cpu-used", "8",
+ "-crf", "31",
+ "-b:v", "0",
+ "-deadline", "good",
+ "-cpu-used", "4",
"-row-mt", "1",
"-c:a", "libopus",
"-b:a", audioBitrate,
diff --git a/packages/core/src/media/media-import-service.ts b/packages/core/src/media/media-import-service.ts
index 95089326..11f6a5d2 100644
--- a/packages/core/src/media/media-import-service.ts
+++ b/packages/core/src/media/media-import-service.ts
@@ -26,6 +26,7 @@ export interface MediaImportOptions {
generateWaveform?: boolean;
waveformSamplesPerSecond?: number;
useFallback?: boolean;
+ quickMode?: boolean;
}
const DEFAULT_OPTIONS: Required<MediaImportOptions> = {
@@ -35,6 +36,7 @@ const DEFAULT_OPTIONS: Required<MediaImportOptions> = {
generateWaveform: true,
waveformSamplesPerSecond: 100,
useFallback: true,
+ quickMode: false,
};
export class MediaImportService {
@@ -118,7 +120,7 @@ export class MediaImportService {
}
}
let thumbnails: ThumbnailResult[] = [];
- if (opts.generateThumbnails) {
+ if (opts.generateThumbnails && !opts.quickMode) {
if (mediaType === "video" && metadata.hasVideo) {
try {
thumbnails = await this.mediaEngine.generateThumbnails(
@@ -134,7 +136,6 @@ export class MediaImportService {
);
}
} else if (mediaType === "image") {
- // For images, create a single thumbnail from the image itself
try {
const img = new Image();
const objectUrl = URL.createObjectURL(file);
@@ -151,7 +152,6 @@ export class MediaImportService {
img.src = objectUrl;
});
- // Create canvas for thumbnail
const canvas = document.createElement("canvas");
const targetWidth = opts.thumbnailWidth || 320;
const aspectRatio = img.height / img.width;
@@ -182,7 +182,7 @@ export class MediaImportService {
}
}
let waveformData: WaveformData | null = null;
- if (opts.generateWaveform && metadata.hasAudio) {
+ if (opts.generateWaveform && metadata.hasAudio && !opts.quickMode) {
try {
waveformData = await this.mediaEngine.generateWaveform(
file,
@@ -472,6 +472,65 @@ export class MediaImportService {
image: ["JPEG", "PNG", "WebP", "GIF"],
};
}
+
+ async generateThumbnailsForMedia(
+ file: File | Blob,
+ mediaType: "video" | "audio" | "image",
+ options: { count?: number; width?: number } = {},
+ ): Promise<ThumbnailResult[]> {
+ if (!this.initialized) {
+ await this.initialize();
+ }
+
+ const { count = 10, width = 160 } = options;
+
+ if (mediaType === "video") {
+ return this.mediaEngine.generateThumbnails(file, count, width);
+ }
+
+ if (mediaType === "image") {
+ const img = new Image();
+ const objectUrl = URL.createObjectURL(file);
+
+ await new Promise<void>((resolve, reject) => {
+ img.onload = () => {
+ URL.revokeObjectURL(objectUrl);
+ resolve();
+ };
+ img.onerror = () => {
+ URL.revokeObjectURL(objectUrl);
+ reject(new Error("Failed to load image"));
+ };
+ img.src = objectUrl;
+ });
+
+ const canvas = document.createElement("canvas");
+ const aspectRatio = img.height / img.width;
+ const targetHeight = Math.round(width * aspectRatio);
+
+ canvas.width = width;
+ canvas.height = targetHeight;
+
+ const ctx = canvas.getContext("2d");
+ if (ctx) {
+ ctx.drawImage(img, 0, 0, width, targetHeight);
+ const dataUrl = canvas.toDataURL("image/jpeg", 0.8);
+ return [{ timestamp: 0, canvas, dataUrl }];
+ }
+ }
+
+ return [];
+ }
+
+ async generateWaveformForMedia(
+ file: File | Blob,
+ samplesPerSecond = 100,
+ ): Promise<WaveformData | null> {
+ if (!this.initialized) {
+ await this.initialize();
+ }
+ return this.mediaEngine.generateWaveform(file, samplesPerSecond);
+ }
}
let importServiceInstance: MediaImportService | null = null;