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(export): eliminate memory leaks causing browser crashes during export

Augustus Otu77e99f33194e
diff --git a/apps/web/src/components/editor/Toolbar.tsx b/apps/web/src/components/editor/Toolbar.tsx
index 4dec4941..46e3c672 100644
--- a/apps/web/src/components/editor/Toolbar.tsx
+++ b/apps/web/src/components/editor/Toolbar.tsx
@@ -28,7 +28,6 @@ import { useThemeStore } from "../../stores/theme-store";
import { useRouter } from "../../hooks/use-router";
import {
getExportEngine,
- downloadBlob,
getDeviceProfile,
estimateExportTime,
type VideoExportSettings,
@@ -172,22 +171,82 @@ export const Toolbar: React.FC = () => {
openModal("search");
}, [openModal]);
+ const runExport = useCallback(
+ async (videoSettings: Partial<VideoExportSettings>, _ext: string, writableStream: FileSystemWritableFileStream) => {
+ const engine = getExportEngine();
+ await engine.initialize();
+
+ const generator = engine.exportVideo(project, videoSettings, writableStream);
+ let finalResult: ExportResult | undefined;
+
+ while (true) {
+ const { value, done } = await generator.next();
+ if (done) {
+ finalResult = value;
+ break;
+ }
+ setExportState((prev) => ({
+ ...prev,
+ progress: value.progress * 100,
+ phase: value.phase === "complete" ? "Complete!" : `${value.phase}...`,
+ }));
+ }
+
+ if (finalResult?.success) {
+ setExportState((prev) => ({ ...prev, complete: true, phase: "Saved!" }));
+ track(AnalyticsEvents.PROJECT_EXPORTED, {
+ format: videoSettings.format ?? "mp4",
+ codec: videoSettings.codec ?? "h264",
+ width: videoSettings.width ?? project.settings.width,
+ height: videoSettings.height ?? project.settings.height,
+ frameRate: videoSettings.frameRate ?? project.settings.frameRate,
+ duration: project.timeline?.duration ?? 0,
+ });
+ } else {
+ throw new Error(finalResult?.error?.message || "Export failed");
+ }
+ },
+ [project, track],
+ );
+
+ const showSavePicker = useCallback(async (filename: string, ext: string): Promise<FileSystemWritableFileStream> => {
+ const mimeMap: Record<string, string> = {
+ mp4: "video/mp4",
+ webm: "video/webm",
+ mov: "video/quicktime",
+ wav: "audio/wav",
+ };
+ const handle = await (window as unknown as {
+ showSaveFilePicker: (opts: unknown) => Promise<FileSystemFileHandle>;
+ }).showSaveFilePicker({
+ suggestedName: filename,
+ types: [{
+ description: "Media file",
+ accept: { [mimeMap[ext] || "application/octet-stream"]: [`.${ext}`] },
+ }],
+ });
+ return handle.createWritable();
+ }, []);
+
const handleExport = useCallback(
async (type: ExportType) => {
setIsExportOpen(false);
- setExportState({
- isExporting: true,
- progress: 0,
- phase: "Initializing...",
- error: null,
- complete: false,
- });
try {
- const engine = getExportEngine();
- await engine.initialize();
-
if (type === "wav") {
+ const writable = await showSavePicker(`${project.name || "export"}.wav`, "wav");
+
+ setExportState({
+ isExporting: true,
+ progress: 0,
+ phase: "Initializing...",
+ error: null,
+ complete: false,
+ });
+
+ const engine = getExportEngine();
+ await engine.initialize();
+
const audioSettings: Partial<AudioExportSettings> = {
format: "wav",
sampleRate: 48000,
@@ -207,257 +266,62 @@ export const Toolbar: React.FC = () => {
setExportState((prev) => ({
...prev,
progress: value.progress * 100,
- phase:
- value.phase === "complete" ? "Complete!" : `${value.phase}...`,
+ phase: value.phase === "complete" ? "Complete!" : `${value.phase}...`,
}));
}
if (finalResult?.success && finalResult.blob) {
- downloadBlob(finalResult.blob, `${project.name || "export"}.wav`);
- setExportState((prev) => ({
- ...prev,
- complete: true,
- phase: "Downloaded!",
- }));
+ await finalResult.blob.stream().pipeTo(writable as unknown as WritableStream<Uint8Array>);
+ setExportState((prev) => ({ ...prev, complete: true, phase: "Saved!" }));
track(AnalyticsEvents.PROJECT_EXPORTED, {
format: "wav",
duration: project.timeline?.duration ?? 0,
});
} else {
+ try { await writable.abort(); } catch {}
throw new Error(finalResult?.error?.message || "Export failed");
}
} else {
- const getExportSettings = (): Partial<VideoExportSettings> => {
- const base = {
- width: project.settings.width,
- height: project.settings.height,
- frameRate: project.settings.frameRate,
- };
-
- switch (type) {
- case "project":
- return {
- ...base,
- format: "mov",
- codec: "prores",
- bitrate: 220000,
- quality: 100,
- };
- case "4k-60-master":
- return {
- ...base,
- width: 3840,
- height: 2160,
- frameRate: 60,
- format: "mov",
- codec: "h265",
- bitrate: 100000,
- quality: 95,
- };
- case "4k-master":
- return {
- ...base,
- width: 3840,
- height: 2160,
- frameRate: 30,
- format: "mov",
- codec: "h265",
- bitrate: 80000,
- quality: 95,
- };
- case "4k-prores":
- return {
- ...base,
- width: 3840,
- height: 2160,
- frameRate: 30,
- format: "mov",
- codec: "prores",
- bitrate: 880000,
- quality: 100,
- };
- case "4k":
- return {
- ...base,
- width: 3840,
- height: 2160,
- frameRate: 30,
- format: "mp4",
- codec: "h264",
- bitrate: 50000,
- quality: 90,
- };
- case "1080p-60":
- return {
- ...base,
- width: 1920,
- height: 1080,
- frameRate: 60,
- format: "mp4",
- codec: "h264",
- bitrate: 25000,
- quality: 95,
- };
- case "1080p-high":
- return {
- ...base,
- width: 1920,
- height: 1080,
- frameRate: 30,
- format: "mp4",
- codec: "h264",
- bitrate: 20000,
- quality: 95,
- };
- case "prores":
- return {
- ...base,
- format: "mov",
- codec: "prores",
- bitrate: 220000,
- quality: 100,
- };
- case "gif":
- return {
- ...base,
- format: "webm",
- codec: "vp9",
- bitrate: 8000,
- };
- case "mp4":
- default:
- return {
- ...base,
- format: "mp4",
- codec: "h264",
- bitrate: 12000,
- quality: 85,
- };
- }
- };
-
- const videoSettings = getExportSettings();
-
- const getExtension = () => {
- switch (type) {
- case "4k-60-master":
- case "4k-master":
- case "4k-prores":
- case "prores":
- case "project":
- return "mov";
- case "gif":
- return "webm";
- default:
- return "mp4";
- }
+ const base = {
+ width: project.settings.width,
+ height: project.settings.height,
+ frameRate: project.settings.frameRate,
};
- const getMimeType = () => {
- const ext = getExtension();
- switch (ext) {
- case "mov":
- return "video/quicktime";
- case "webm":
- return "video/webm";
- default:
- return "video/mp4";
- }
+ const presets: Record<string, { settings: Partial<VideoExportSettings>; ext: string }> = {
+ mp4: { settings: { ...base, format: "mp4", codec: "h264", bitrate: 12000, quality: 85 }, ext: "mp4" },
+ gif: { settings: { ...base, format: "webm", codec: "vp9", bitrate: 8000 }, ext: "webm" },
+ project: { settings: { ...base, format: "mp4", codec: "h264", bitrate: 12000, quality: 85 }, ext: "mp4" },
+ "4k-60-master": { settings: { ...base, width: 3840, height: 2160, frameRate: 60, format: "mov", codec: "h265", bitrate: 100000, quality: 95 }, ext: "mov" },
+ "4k-master": { settings: { ...base, width: 3840, height: 2160, frameRate: 30, format: "mov", codec: "h265", bitrate: 80000, quality: 95 }, ext: "mov" },
+ "4k-prores": { settings: { ...base, width: 3840, height: 2160, frameRate: 30, format: "mov", codec: "prores", bitrate: 880000, quality: 100 }, ext: "mov" },
+ "4k": { settings: { ...base, width: 3840, height: 2160, frameRate: 30, format: "mp4", codec: "h264", bitrate: 50000, quality: 90 }, ext: "mp4" },
+ "1080p-60": { settings: { ...base, width: 1920, height: 1080, frameRate: 60, format: "mp4", codec: "h264", bitrate: 25000, quality: 95 }, ext: "mp4" },
+ "1080p-high": { settings: { ...base, width: 1920, height: 1080, frameRate: 30, format: "mp4", codec: "h264", bitrate: 20000, quality: 95 }, ext: "mp4" },
+ prores: { settings: { ...base, format: "mov", codec: "prores", bitrate: 220000, quality: 100 }, ext: "mov" },
};
- let writableStream: FileSystemWritableFileStream | undefined;
- let useStreaming = false;
-
- if ("showSaveFilePicker" in window && typeof (window as Window & { showSaveFilePicker?: unknown }).showSaveFilePicker === "function") {
- try {
- const showSaveFilePicker = (window as Window & { showSaveFilePicker: (options: { suggestedName: string; types: Array<{ description: string; accept: Record<string, string[]> }> }) => Promise<FileSystemFileHandle> }).showSaveFilePicker;
- const fileHandle = await showSaveFilePicker({
- suggestedName: `${project.name || "export"}.${getExtension()}`,
- types: [
- {
- description: "Video file",
- accept: { [getMimeType()]: [`.${getExtension()}`] },
- },
- ],
- });
- writableStream = await fileHandle.createWritable();
- useStreaming = true;
- } catch (e) {
- if ((e as Error).name === "AbortError") {
- setExportState({
- isExporting: false,
- progress: 0,
- phase: "",
- error: null,
- complete: false,
- });
- return;
- }
- useStreaming = false;
- }
- }
-
- const generator = engine.exportVideoWithFFmpeg(project, videoSettings, writableStream);
- let finalResult: ExportResult | undefined;
-
- while (true) {
- const { value, done } = await generator.next();
- if (done) {
- finalResult = value;
- break;
- }
- setExportState((prev) => ({
- ...prev,
- progress: value.progress * 100,
- phase:
- value.phase === "complete" ? "Complete!" : `${value.phase}...`,
- }));
- }
+ const preset = presets[type] ?? presets.mp4;
+ const writable = await showSavePicker(`${project.name || "export"}.${preset.ext}`, preset.ext);
- if (finalResult?.success) {
- track(AnalyticsEvents.PROJECT_EXPORTED, {
- format: videoSettings.format ?? "mp4",
- codec: videoSettings.codec ?? "h264",
- width: videoSettings.width ?? project.settings.width,
- height: videoSettings.height ?? project.settings.height,
- frameRate: videoSettings.frameRate ?? project.settings.frameRate,
- duration: project.timeline?.duration ?? 0,
- exportType: type,
- });
- if (useStreaming) {
- setExportState((prev) => ({
- ...prev,
- complete: true,
- phase: "Saved!",
- }));
- } else if (finalResult.blob) {
- downloadBlob(
- finalResult.blob,
- `${project.name || "export"}.${getExtension()}`,
- );
- setExportState((prev) => ({
- ...prev,
- complete: true,
- phase: "Downloaded!",
- }));
- } else {
- throw new Error("Export completed but no output generated");
- }
- } else {
- throw new Error(finalResult?.error?.message || "Export failed");
- }
- }
-
- setTimeout(() => {
setExportState({
- isExporting: false,
+ isExporting: true,
progress: 0,
- phase: "",
+ phase: "Initializing...",
error: null,
complete: false,
});
+
+ await runExport(preset.settings, preset.ext, writable);
+ }
+
+ setTimeout(() => {
+ setExportState({ isExporting: false, progress: 0, phase: "", error: null, complete: false });
}, 2000);
} catch (error) {
+ if (error instanceof Error && error.name === "AbortError") {
+ return;
+ }
setExportState((prev) => ({
...prev,
isExporting: false,
@@ -465,7 +329,7 @@ export const Toolbar: React.FC = () => {
}));
}
},
- [project, track],
+ [project, track, runExport, showSavePicker],
);
const handleCancelExport = useCallback(() => {
@@ -483,17 +347,18 @@ export const Toolbar: React.FC = () => {
const handleCustomExport = useCallback(
async (settings: VideoExportSettings) => {
setIsExportDialogOpen(false);
- setExportState({
- isExporting: true,
- progress: 0,
- phase: "Initializing...",
- error: null,
- complete: false,
- });
try {
- const engine = getExportEngine();
- await engine.initialize();
+ const ext = settings.format === "mov" ? "mov" : settings.format === "webm" ? "webm" : "mp4";
+ const writable = await showSavePicker(`${project.name || "export"}.${ext}`, ext);
+
+ setExportState({
+ isExporting: true,
+ progress: 0,
+ phase: "Initializing...",
+ error: null,
+ complete: false,
+ });
const needsUpscaling =
settings.width > project.settings.width ||
@@ -507,114 +372,26 @@ export const Toolbar: React.FC = () => {
: undefined,
};
- const ext =
- settings.format === "mov"
- ? "mov"
- : settings.format === "webm"
- ? "webm"
- : "mp4";
-
- const getMimeType = () => {
- switch (ext) {
- case "mov":
- return "video/quicktime";
- case "webm":
- return "video/webm";
- default:
- return "video/mp4";
- }
- };
-
- let writableStream: FileSystemWritableFileStream | undefined;
- let useStreaming = false;
-
- if ("showSaveFilePicker" in window && typeof (window as Window & { showSaveFilePicker?: unknown }).showSaveFilePicker === "function") {
- try {
- const showSaveFilePicker = (window as Window & { showSaveFilePicker: (options: { suggestedName: string; types: Array<{ description: string; accept: Record<string, string[]> }> }) => Promise<FileSystemFileHandle> }).showSaveFilePicker;
- const fileHandle = await showSaveFilePicker({
- suggestedName: `${project.name || "export"}.${ext}`,
- types: [
- {
- description: "Video file",
- accept: { [getMimeType()]: [`.${ext}`] },
- },
- ],
- });
- writableStream = await fileHandle.createWritable();
- useStreaming = true;
- } catch (e) {
- if ((e as Error).name === "AbortError") {
- setExportState({
- isExporting: false,
- progress: 0,
- phase: "",
- error: null,
- complete: false,
- });
- return;
- }
- useStreaming = false;
- }
- }
-
- const generator = engine.exportVideoWithFFmpeg(project, exportSettings, writableStream);
- let finalResult: ExportResult | undefined;
-
- while (true) {
- const { value, done } = await generator.next();
- if (done) {
- finalResult = value;
- break;
- }
- setExportState((prev) => ({
- ...prev,
- progress: value.progress * 100,
- phase:
- value.phase === "complete" ? "Complete!" : `${value.phase}...`,
- }));
- }
-
- if (finalResult?.success) {
- track(AnalyticsEvents.PROJECT_EXPORTED, {
- format: settings.format,
- codec: settings.codec,
- width: settings.width,
- height: settings.height,
- frameRate: settings.frameRate,
- duration: project.timeline?.duration ?? 0,
- exportType: "custom",
- upscaling: settings.upscaling?.enabled ?? false,
- });
- if (useStreaming) {
- setExportState((prev) => ({
- ...prev,
- complete: true,
- phase: "Saved!",
- }));
- } else if (finalResult.blob) {
- downloadBlob(finalResult.blob, `${project.name || "export"}.${ext}`);
- setExportState((prev) => ({
- ...prev,
- complete: true,
- phase: "Downloaded!",
- }));
- } else {
- throw new Error("Export completed but no output generated");
- }
- } else {
- throw new Error(finalResult?.error?.message || "Export failed");
- }
+ await runExport(exportSettings, ext, writable);
+
+ track(AnalyticsEvents.PROJECT_EXPORTED, {
+ format: settings.format,
+ codec: settings.codec,
+ width: settings.width,
+ height: settings.height,
+ frameRate: settings.frameRate,
+ duration: project.timeline?.duration ?? 0,
+ exportType: "custom",
+ upscaling: settings.upscaling?.enabled ?? false,
+ });
setTimeout(() => {
- setExportState({
- isExporting: false,
- progress: 0,
- phase: "",
- error: null,
- complete: false,
- });
+ setExportState({ isExporting: false, progress: 0, phase: "", error: null, complete: false });
}, 2000);
} catch (error) {
+ if (error instanceof Error && error.name === "AbortError") {
+ return;
+ }
setExportState((prev) => ({
...prev,
isExporting: false,
@@ -622,7 +399,7 @@ export const Toolbar: React.FC = () => {
}));
}
},
- [project, track],
+ [project, track, runExport, showSavePicker],
);
@@ -686,13 +463,6 @@ export const Toolbar: React.FC = () => {
const projectRes = `${project.settings.width}×${project.settings.height}`;
const aspectRatio = project.settings.width / project.settings.height;
const isVertical = aspectRatio < 0.9;
- const isSquare = aspectRatio >= 0.9 && aspectRatio <= 1.1;
-
- const getRecommendedLabel = () => {
- if (isVertical) return "TikTok / Reels / Shorts";
- if (isSquare) return "Instagram Feed";
- return "YouTube / Social";
- };
const exportOptions: Array<{
label: string;
@@ -703,18 +473,12 @@ export const Toolbar: React.FC = () => {
separator?: boolean;
}> = [
{
- label: getRecommendedLabel(),
+ label: "MP4 Standard",
icon: Zap,
- desc: `${projectRes} H.264 - Best for your video`,
+ desc: `${projectRes} H.264 - Web & social`,
type: "mp4",
recommended: true,
},
- {
- label: "Project Resolution",
- icon: Film,
- desc: `${projectRes} H.264 - High quality`,
- type: "project",
- },
{
label: "",
icon: Film,
@@ -744,12 +508,6 @@ export const Toolbar: React.FC = () => {
desc: "1920×1080 - Smooth playback",
type: "1080p-60",
},
- {
- label: "MP4 Standard",
- icon: FileVideo,
- desc: `${projectRes} - Web & social`,
- type: "mp4",
- },
{
label: "Audio Only (WAV)",
icon: Music,
diff --git a/packages/core/src/export/export-engine.ts b/packages/core/src/export/export-engine.ts
index 69cb027a..b5cc8410 100644
--- a/packages/core/src/export/export-engine.ts
+++ b/packages/core/src/export/export-engine.ts
@@ -22,7 +22,6 @@ import { titleEngine } from "../text/title-engine";
import { graphicsEngine } from "../graphics/graphics-engine";
import { UpscalingEngine, getUpscalingEngine } from "../video/upscaling";
import { getMediaEngine } from "../media/mediabunny-engine";
-import { getFFmpegFallback } from "../media/ffmpeg-fallback";
import { getWavEncoder } from "../wasm/wav";
export class ExportEngine {
@@ -213,6 +212,7 @@ export class ExportEngine {
async *exportVideo(
project: Project,
settings: Partial<VideoExportSettings> = {},
+ writableStream?: FileSystemWritableFileStream,
): AsyncGenerator<ExportProgress, ExportResult> {
this.ensureInitialized();
@@ -236,36 +236,34 @@ export class ExportEngine {
};
if (fullSettings.codec === "prores") {
- console.warn(
- `[ExportEngine] ProRes encoding is not supported in browsers. Switching to H.264 high quality.`,
- );
fullSettings.codec = "h264";
fullSettings.format = "mp4";
fullSettings.bitrate = 25000;
fullSettings.quality = 95;
}
- const pixelCount = fullSettings.width * fullSettings.height;
+ const { timeline } = project;
+ const timelineDuration = this.calculateTimelineDuration(timeline);
+
const isMemoryIntensiveCodec =
fullSettings.codec === "vp9" ||
fullSettings.codec === "av1" ||
fullSettings.codec === "h265";
- const maxSafePixels = isMemoryIntensiveCodec ? 1920 * 1080 : 3840 * 2160;
+ const isLongVideo = timelineDuration > 120;
- if (pixelCount > maxSafePixels && isMemoryIntensiveCodec) {
- console.warn(
- `[ExportEngine] ${fullSettings.codec.toUpperCase()} at ${fullSettings.width}x${fullSettings.height} may cause browser instability. Reducing to 1080p for stability.`,
- );
- const aspectRatio = fullSettings.width / fullSettings.height;
- if (aspectRatio > 1) {
- fullSettings.width = 1920;
- fullSettings.height = Math.round(1920 / aspectRatio);
- } else {
- fullSettings.height = 1920;
- fullSettings.width = Math.round(1920 * aspectRatio);
- }
- fullSettings.width = Math.round(fullSettings.width / 2) * 2;
- fullSettings.height = Math.round(fullSettings.height / 2) * 2;
+ let maxW = isMemoryIntensiveCodec ? 1920 : 3840;
+ let maxH = isMemoryIntensiveCodec ? 1080 : 2160;
+ if (isLongVideo) {
+ maxW = Math.min(maxW, 1920);
+ maxH = Math.min(maxH, 1080);
+ }
+ if (fullSettings.width > maxW || fullSettings.height > maxH) {
+ const scale = Math.min(maxW / fullSettings.width, maxH / fullSettings.height, 1);
+ fullSettings.width = Math.round(fullSettings.width * scale / 2) * 2;
+ fullSettings.height = Math.round(fullSettings.height * scale / 2) * 2;
+ }
+ if (isLongVideo && fullSettings.frameRate > 30) {
+ fullSettings.frameRate = 30;
}
this.abortController = new AbortController();
@@ -278,9 +276,6 @@ export class ExportEngine {
this.videoEngine?.resetExportState();
- const { timeline } = project;
- const timelineDuration = this.calculateTimelineDuration(timeline);
-
if (timelineDuration <= 0) {
return {
success: false,
@@ -292,6 +287,17 @@ export class ExportEngine {
};
}
+ if (!writableStream) {
+ return {
+ success: false,
+ error: this.createError(
+ "MUXER_ERROR",
+ "No writable stream provided. Export requires a file destination.",
+ "preparing",
+ ),
+ };
+ }
+
const totalFrames = Math.ceil(timelineDuration * fullSettings.frameRate);
let bytesWritten = 0;
@@ -300,7 +306,7 @@ export class ExportEngine {
const {
Output,
- BufferTarget,
+ StreamTarget,
Mp4OutputFormat,
WebMOutputFormat,
MovOutputFormat,
@@ -312,6 +318,20 @@ export class ExportEngine {
getFirstEncodableAudioCodec,
QUALITY_MEDIUM,
} = this.mediabunny!;
+
+ const diskWriter = writableStream;
+ const chunkWriter = new WritableStream<{ data: Uint8Array; position: number }>({
+ async write(chunk) {
+ const buf = chunk.data.buffer.slice(
+ chunk.data.byteOffset,
+ chunk.data.byteOffset + chunk.data.byteLength,
+ ) as ArrayBuffer;
+ await diskWriter.seek(chunk.position);
+ await diskWriter.write(buf);
+ bytesWritten += chunk.data.byteLength;
+ },
+ });
+
let outputFormat;
switch (fullSettings.format) {
case "webm":
@@ -322,12 +342,16 @@ export class ExportEngine {
break;
case "mp4":
default:
- outputFormat = new Mp4OutputFormat({ fastStart: "in-memory" });
+ outputFormat = new Mp4OutputFormat({ fastStart: false });
break;
}
- const target = new BufferTarget();
+ const target = new StreamTarget(chunkWriter, {
+ chunked: true,
+ chunkSize: 4 * 1024 * 1024,
+ });
const output = new Output({ format: outputFormat, target });
+
const videoCodec = await getFirstEncodableVideoCodec(
outputFormat.getSupportedVideoCodecs(),
{ width: fullSettings.width, height: fullSettings.height },
@@ -349,10 +373,10 @@ export class ExportEngine {
const videoSource = new VideoSampleSource({
codec: videoCodec,
- bitrate: QUALITY_MEDIUM,
+ bitrate: fullSettings.bitrate ? fullSettings.bitrate * 1000 : QUALITY_MEDIUM,
keyFrameInterval:
fullSettings.keyframeInterval / fullSettings.frameRate,
- hardwareAcceleration: "prefer-hardware",
+ hardwareAcceleration: "prefer-software",
});
const audioSource = new AudioSampleSource({
codec: audioCodecResult.codec as "aac" | "opus" | "mp3",
@@ -367,13 +391,36 @@ export class ExportEngine {
await output.start();
- const isIntensiveCodec =
- fullSettings.codec === "vp9" ||
- fullSettings.codec === "av1" ||
- fullSettings.codec === "h265";
- const microFlushInterval = isIntensiveCodec ? 10 : 20;
- const majorFlushInterval = 60;
- const cacheCleanInterval = 180;
+ const audioBuffer = await this.renderTimelineAudio(project, fullSettings);
+ if (audioBuffer) {
+ const audioSamples = AudioSample.fromAudioBuffer(audioBuffer, 0);
+ for (const sample of audioSamples) {
+ await audioSource.add(sample);
+ sample.close();
+ }
+ }
+ audioSource.close();
+
+ const mediaEngine = getMediaEngine();
+ const videoMediaIds: string[] = [];
+ for (const track of project.timeline.tracks) {
+ if (track.type !== "video") continue;
+ for (const clip of track.clips) {
+ const mediaItem = project.mediaLibrary.items.find(
+ (m) => m.id === clip.mediaId,
+ );
+ if (mediaItem?.blob && !videoMediaIds.includes(mediaItem.id)) {
+ videoMediaIds.push(mediaItem.id);
+ try {
+ await mediaEngine.createExportDecoder(
+ mediaItem.id,
+ mediaItem.blob,
+ fullSettings.width,
+ );
+ } catch {}
+ }
+ }
+ }
for (let frame = 0; frame < totalFrames; frame++) {
if (this.abortController.signal.aborted) {
@@ -416,23 +463,13 @@ export class ExportEngine {
this.currentExport!.framesRendered = frame + 1;
- if ((frame + 1) % microFlushInterval === 0) {
- await new Promise((resolve) => setTimeout(resolve, 0));
- }
-
- if ((frame + 1) % majorFlushInterval === 0) {
- await new Promise((resolve) => setTimeout(resolve, 10));
- }
-
- if ((frame + 1) % cacheCleanInterval === 0) {
+ if ((frame + 1) % 5 === 0) {
this.videoEngine?.clearVideoElementCache();
+ this.videoEngine?.clearCache();
try {
- const mediaEngine = getMediaEngine();
mediaEngine.clearFrameCache();
- } catch {
- // MediaEngine may not be initialized
- }
- await new Promise((resolve) => setTimeout(resolve, 10));
+ } catch {}
+ await new Promise((resolve) => setTimeout(resolve, 2));
}
yield this.createProgress(
@@ -443,24 +480,12 @@ export class ExportEngine {
bytesWritten,
);
}
- yield this.createProgress(
- "encoding",
- 0.95,
- totalFrames,
- totalFrames,
- bytesWritten,
- );
- const audioBuffer = await this.renderTimelineAudio(project, fullSettings);
- if (audioBuffer) {
- const audioSamples = AudioSample.fromAudioBuffer(audioBuffer, 0);
- for (const sample of audioSamples) {
- await audioSource.add(sample);
- sample.close();
- }
- }
videoSource.close();
- audioSource.close();
+ mediaEngine.disposeAllExportDecoders();
+ mediaEngine.clearFrameCache();
+ this.videoEngine?.clearVideoElementCache();
+ this.videoEngine?.clearCache();
yield this.createProgress(
"muxing",
@@ -471,19 +496,7 @@ export class ExportEngine {
);
await output.finalize();
- const buffer = target.buffer;
- if (!buffer) {
- throw this.createError(
- "MUXER_ERROR",
- "Output buffer is empty",
- "muxing",
- );
- }
-
- const blob = new Blob([buffer], {
- type: this.getMimeType(fullSettings.format),
- });
- bytesWritten = blob.size;
+ await writableStream.close();
yield this.createProgress(
"complete",
@@ -495,10 +508,10 @@ export class ExportEngine {
return {
success: true,
- blob,
stats: this.calculateStats(totalFrames, bytesWritten),
};
} catch (error) {
+ try { await writableStream.abort(); } catch {}
if (error && typeof error === "object" && "code" in error) {
return { success: false, error: error as ExportError };
}
@@ -514,711 +527,11 @@ export class ExportEngine {
this.abortController = null;
this.currentExport = null;
this.videoEngine?.clearVideoElementCache();
- }
- }
-
- async *exportVideoWithWorker(
- project: Project,
- settings: Partial<VideoExportSettings> = {},
- writableStream?: FileSystemWritableFileStream,
- ): AsyncGenerator<ExportProgress, ExportResult> {
- this.ensureInitialized();
-
- const fullSettings: VideoExportSettings = {
- ...DEFAULT_VIDEO_SETTINGS,
- ...settings,
- audioSettings: {
- ...DEFAULT_VIDEO_SETTINGS.audioSettings,
- ...settings.audioSettings,
- },
- };
-
- if (fullSettings.codec === "prores") {
- console.warn(
- `[ExportEngine] ProRes encoding is not supported in browsers. Switching to H.264 high quality.`,
- );
- fullSettings.codec = "h264";
- fullSettings.format = "mp4";
- fullSettings.bitrate = 25000;
- fullSettings.quality = 95;
- }
-
- const pixelCount = fullSettings.width * fullSettings.height;
- const isMemoryIntensiveCodec =
- fullSettings.codec === "vp9" ||
- fullSettings.codec === "av1" ||
- fullSettings.codec === "h265";
- const maxSafePixels = isMemoryIntensiveCodec ? 1920 * 1080 : 3840 * 2160;
-
- if (pixelCount > maxSafePixels && isMemoryIntensiveCodec) {
- console.warn(
- `[ExportEngine] ${fullSettings.codec.toUpperCase()} at ${fullSettings.width}x${fullSettings.height} may cause browser instability. Reducing to 1080p for stability.`,
- );
- const aspectRatio = fullSettings.width / fullSettings.height;
- if (aspectRatio > 1) {
- fullSettings.width = 1920;
- fullSettings.height = Math.round(1920 / aspectRatio);
- } else {
- fullSettings.height = 1920;
- fullSettings.width = Math.round(1920 * aspectRatio);
- }
- fullSettings.width = Math.round(fullSettings.width / 2) * 2;
- fullSettings.height = Math.round(fullSettings.height / 2) * 2;
- }
-
- this.abortController = new AbortController();
- this.currentExport = { startTime: Date.now(), framesRendered: 0 };
-
- const gpuEnabled = await this.initializeGPUForExport(
- fullSettings.width,
- fullSettings.height,
- );
- if (!gpuEnabled) {
- console.warn("[ExportEngine] GPU acceleration not available for export");
- }
-
- this.videoEngine?.resetExportState();
-
- const { timeline } = project;
- const timelineDuration = this.calculateTimelineDuration(timeline);
-
- if (timelineDuration <= 0) {
- return {
- success: false,
- error: this.createError(
- "MUXER_ERROR",
- "Timeline is empty. Add clips before exporting.",
- "preparing",
- ),
- };
- }
-
- const totalFrames = Math.ceil(timelineDuration * fullSettings.frameRate);
-
- try {
- yield this.createProgress("preparing", 0, totalFrames, 0, 0);
-
- const workerResult = await this.runWorkerExport(
- project,
- fullSettings,
- totalFrames,
- writableStream,
- );
-
- for await (const progress of workerResult.progressGenerator) {
- if (this.abortController?.signal.aborted) {
- this.exportWorker?.postMessage({ type: "cancel" });
- throw this.createError(
- "CANCELLED",
- "Export cancelled by user",
- "rendering",
- );
- }
- yield progress;
- }
-
- const result = await workerResult.resultPromise;
- return result;
- } catch (error) {
- if (error && typeof error === "object" && "code" in error) {
- return { success: false, error: error as ExportError };
- }
- return {
- success: false,
- error: this.createError(
- "FRAME_ENCODE_FAILED",
- error instanceof Error ? error.message : "Unknown error",
- "rendering",
- ),
- };
- } finally {
- this.terminateWorker();
- this.abortController = null;
- this.currentExport = null;
- this.videoEngine?.clearVideoElementCache();
- }
- }
-
- private async runWorkerExport(
- project: Project,
- settings: VideoExportSettings,
- totalFrames: number,
- writableStream?: FileSystemWritableFileStream,
- ): Promise<{
- progressGenerator: AsyncGenerator<ExportProgress>;
- resultPromise: Promise<ExportResult>;
- }> {
- let workerReadyResolve: (() => void) | null = null;
- let resultResolve: ((result: ExportResult) => void) | null = null;
- let resultReject: ((error: Error) => void) | null = null;
-
- const workerReadyPromise = new Promise<void>((resolve) => {
- workerReadyResolve = resolve;
- });
-
- const resultPromise = new Promise<ExportResult>((resolve, reject) => {
- resultResolve = resolve;
- resultReject = reject;
- });
-
- let framesInFlight = 0;
- const MAX_FRAMES_IN_FLIGHT = writableStream ? 4 : 8;
- let frameProcessedResolve: (() => void) | null = null;
-
- this.exportWorker = new Worker(
- new URL("./export-worker.ts", import.meta.url),
- { type: "module" },
- );
-
- this.exportWorker.onmessage = async (event) => {
- const { type, blob, error, chunk } = event.data;
-
- if (type === "ready") {
- workerReadyResolve?.();
- return;
- }
-
- if (type === "chunk" && writableStream && chunk) {
- try {
- await writableStream.write({
- type: "write",
- position: chunk.position,
- data: chunk.data,
- });
- } catch (e) {
- console.error("[ExportEngine] Failed to write chunk:", e);
- }
- return;
- }
-
- if (type === "frameProcessed") {
- framesInFlight = Math.max(0, framesInFlight - 1);
- if (frameProcessedResolve) {
- frameProcessedResolve();
- frameProcessedResolve = null;
- }
- return;
- }
-
- if (type === "complete") {
- if (writableStream) {
- try {
- await writableStream.close();
- } catch (e) {
- console.error("[ExportEngine] Failed to close stream:", e);
- }
- }
- const stats = this.calculateStats(totalFrames, blob?.size || 0);
- resultResolve?.({ success: true, blob, stats });
- return;
- }
-
- if (type === "error") {
- if (writableStream) {
- try {
- await writableStream.abort();
- } catch {}
- }
- resultReject?.(new Error(error || "Worker encoding failed"));
- return;
- }
- };
-
- this.exportWorker.onerror = (error) => {
- resultReject?.(new Error(error.message || "Worker error"));
- };
-
- this.exportWorker.postMessage({
- type: "init",
- settings,
- projectName: project.name,
- useStreamTarget: !!writableStream,
- });
-
- await workerReadyPromise;
-
- const self = this;
-
- async function waitForCapacity(): Promise<void> {
- if (framesInFlight < MAX_FRAMES_IN_FLIGHT) {
- return;
- }
- await new Promise<void>((resolve) => {
- frameProcessedResolve = resolve;
- });
- }
-
- async function* generateProgress(): AsyncGenerator<ExportProgress> {
- for (let frame = 0; frame < totalFrames; frame++) {
- if (self.abortController?.signal.aborted) {
- return;
- }
-
- await waitForCapacity();
-
- const time = frame / settings.frameRate;
- const rendered = await self.videoEngine!.renderFrame(
- project,
- time,
- settings.width,
- settings.height,
- );
-
- const shouldUpscale = self.shouldApplyUpscaling(project, settings);
- let frameImage = rendered.image;
-
- if (shouldUpscale && self.upscalingEngine?.isInitialized()) {
- const upscaled = await self.upscalingEngine.upscaleImageBitmap(
- frameImage,
- settings.width,
- settings.height,
- settings.upscaling!,
- );
- frameImage.close();
- frameImage = upscaled;
- }
-
- framesInFlight++;
-
- self.exportWorker?.postMessage(
- {
- type: "addFrame",
- frame: frameImage,
- frameIndex: frame,
- timestamp: time,
- totalFrames,
- settings,
- },
- [frameImage],
- );
-
- self.currentExport!.framesRendered = frame + 1;
-
- yield self.createProgress(
- "rendering",
- (frame + 1) / totalFrames,
- totalFrames,
- frame + 1,
- 0,
- );
-
- const cleanupInterval = writableStream ? 10 : 30;
- if ((frame + 1) % cleanupInterval === 0) {
- self.videoEngine?.clearVideoElementCache();
- try {
- const mediaEngine = getMediaEngine();
- mediaEngine.clearFrameCache();
- } catch {
- // MediaEngine may not be initialized
- }
- if (writableStream) {
- await new Promise((resolve) => setTimeout(resolve, 50));
- }
- }
- }
-
- while (framesInFlight > 0) {
- await new Promise<void>((resolve) => {
- if (framesInFlight === 0) {
- resolve();
- } else {
- frameProcessedResolve = resolve;
- }
- });
- }
-
- yield self.createProgress("encoding", 0.95, totalFrames, totalFrames, 0);
-
- const audioBuffer = await self.renderTimelineAudioPublic(project);
- if (audioBuffer) {
- const channels: Float32Array[] = [];
- for (let i = 0; i < audioBuffer.numberOfChannels; i++) {
- channels.push(audioBuffer.getChannelData(i).slice());
- }
- self.exportWorker?.postMessage({
- type: "addAudio",
- audioBuffer: {
- channels,
- sampleRate: audioBuffer.sampleRate,
- length: audioBuffer.length,
- },
- });
- }
-
- yield self.createProgress("muxing", 0.98, totalFrames, totalFrames, 0);
-
- self.exportWorker?.postMessage({ type: "finalize" });
- }
-
- return {
- progressGenerator: generateProgress(),
- resultPromise,
- };
- }
-
- private async renderTimelineAudioPublic(
- project: Project,
- ): Promise<AudioBuffer | null> {
- return this.renderTimelineAudio(project);
- }
-
- private isSimpleProject(project: Project): { simple: boolean; singleClip?: { mediaId: string; startTime: number; endTime: number; speed: number } } {
- const { timeline } = project;
-
- const allTracks = timeline.tracks.filter(t => !t.hidden);
- const videoTracks = allTracks.filter(t => t.type === "video" || t.type === "image");
- const textTracks = allTracks.filter(t => t.type === "text");
- const graphicsTracks = allTracks.filter(t => t.type === "graphics");
- const audioTracks = allTracks.filter(t => t.type === "audio");
-
- if (textTracks.length > 0) {
- return { simple: false };
- }
-
- if (graphicsTracks.length > 0) {
- return { simple: false };
- }
-
- if (audioTracks.length > 0 && audioTracks.some(t => t.clips.length > 0)) {
- return { simple: false };
- }
-
- let totalVideoClips = 0;
- let singleClip: { mediaId: string; startTime: number; endTime: number; speed: number } | undefined;
- let clipWithEffects = false;
-
- for (const track of videoTracks) {
- for (const clip of track.clips) {
- totalVideoClips++;
-
- if (clip.effects && clip.effects.length > 0) {
- clipWithEffects = true;
- }
-
- if (clip.keyframes && clip.keyframes.length > 0) {
- clipWithEffects = true;
- }
-
- if (clip.transform) {
- const t = clip.transform;
- if (t.scale.x !== 1 || t.scale.y !== 1 || t.rotation !== 0 ||
- t.position.x !== 0 || t.position.y !== 0 || t.opacity !== 1) {
- clipWithEffects = true;
- }
- }
-
- if (totalVideoClips === 1 && !clipWithEffects) {
- const mediaItem = project.mediaLibrary.items.find(m => m.id === clip.mediaId);
- if (mediaItem?.type === "video") {
- singleClip = {
- mediaId: clip.mediaId,
- startTime: clip.inPoint,
- endTime: clip.outPoint,
- speed: clip.speed || 1,
- };
- }
- }
- }
- }
-
- if (clipWithEffects) {
- return { simple: false };
- }
-
- if (totalVideoClips === 1 && singleClip) {
- return { simple: true, singleClip };
- }
-
- return { simple: false };
- }
-
- async *exportVideoWithFFmpeg(
- project: Project,
- settings: Partial<VideoExportSettings> = {},
- writableStream?: FileSystemWritableFileStream,
- ): AsyncGenerator<ExportProgress, ExportResult> {
-
- if (!this.initialized) {
- await this.initialize();
- }
-
- const fullSettings: VideoExportSettings = {
- ...DEFAULT_VIDEO_SETTINGS,
- ...settings,
- audioSettings: {
- ...DEFAULT_VIDEO_SETTINGS.audioSettings,
- ...settings.audioSettings,
- },
- };
-
- if (fullSettings.codec === "prores") {
- fullSettings.codec = "h264";
- fullSettings.format = "mp4";
- fullSettings.bitrate = 25000;
- fullSettings.quality = 95;
- }
-
- this.abortController = new AbortController();
- this.currentExport = { startTime: Date.now(), framesRendered: 0 };
-
- const { timeline } = project;
- const timelineDuration = this.calculateTimelineDuration(timeline);
-
- if (timelineDuration <= 0) {
- return {
- success: false,
- error: this.createError(
- "MUXER_ERROR",
- "Timeline is empty. Add clips before exporting.",
- "preparing",
- ),
- };
- }
-
- const totalFrames = Math.ceil(timelineDuration * fullSettings.frameRate);
- const simpleCheck = this.isSimpleProject(project);
-
- this.videoEngine?.resetExportState();
-
- yield this.createProgress("preparing", 0, totalFrames, 0, 0);
-
- const mediaEngine = getMediaEngine();
-
- if (!mediaEngine.isAvailable()) {
- await mediaEngine.initialize();
- }
- mediaEngine.clearFrameCache();
- mediaEngine.disposeAllExportDecoders();
- this.videoEngine?.clearVideoElementCache();
-
- try {
- const ffmpeg = getFFmpegFallback();
- await ffmpeg.load();
-
- if (simpleCheck.simple && simpleCheck.singleClip) {
- const mediaItem = project.mediaLibrary.items.find(m => m.id === simpleCheck.singleClip!.mediaId);
- if (mediaItem?.blob) {
- const inputWidth = mediaItem.metadata.width;
- const inputHeight = mediaItem.metadata.height;
-
- const clip = project.timeline.tracks
- .flatMap(t => t.clips)
- .find(c => c.mediaId === simpleCheck.singleClip!.mediaId);
-
- const hasClipEffects = clip && (
- (clip.effects && clip.effects.length > 0) ||
- (clip.transform && (
- clip.transform.scale.x !== 1 ||
- clip.transform.scale.y !== 1 ||
- clip.transform.rotation !== 0 ||
- clip.transform.position.x !== 0 ||
- clip.transform.position.y !== 0 ||
- clip.transform.opacity !== 1
- )) ||
- (clip.keyframes && clip.keyframes.length > 0)
- );
-
- const allTracks = project.timeline.tracks.filter(t => !t.hidden);
- const hasMultipleTracks = allTracks.length > 1;
- const hasAnyTextOrGraphics = allTracks.some(t =>
- (t.type === "text" || t.type === "graphics") && t.clips.length > 0
- );
-
- const canUseStreamCopy =
- simpleCheck.singleClip.speed === 1 &&
- inputWidth === fullSettings.width &&
- inputHeight === fullSettings.height &&
- simpleCheck.singleClip.startTime === 0 &&
- !hasClipEffects &&
- !hasMultipleTracks &&
- !hasAnyTextOrGraphics;
-
-
- let lastProgress: ExportProgress | null = null;
- const onProgress = (progress: ExportProgress) => {
- lastProgress = progress;
- };
-
- const resultPromise = ffmpeg.exportVideoDirectly(
- mediaItem.blob,
- {
- startTime: simpleCheck.singleClip.startTime,
- endTime: simpleCheck.singleClip.endTime,
- width: fullSettings.width,
- height: fullSettings.height,
- frameRate: fullSettings.frameRate,
- format: fullSettings.format === "webm" ? "webm" : "mp4",
- videoBitrate: `${fullSettings.bitrate}k`,
- audioBitrate: `${fullSettings.audioSettings.bitrate}k`,
- speed: simpleCheck.singleClip.speed,
- writableStream,
- useStreamCopy: canUseStreamCopy,
- },
- onProgress,
- );
-
- while (true) {
- await new Promise((resolve) => setTimeout(resolve, 100));
-
- if (lastProgress !== null) {
- const progressToYield = lastProgress as ExportProgress;
- yield progressToYield;
- if (progressToYield.phase === "complete") {
- break;
- }
- }
-
- const isResolved = await Promise.race([
- resultPromise.then(() => true),
- new Promise<false>((resolve) => setTimeout(() => resolve(false), 10)),
- ]);
-
- if (isResolved) {
- break;
- }
- }
-
- const blob = await resultPromise;
-
- return {
- success: true,
- blob: blob || undefined,
- stats: this.calculateStats(totalFrames, blob?.size || 0),
- };
- }
- }
-
- await this.initializeGPUForExport(
- fullSettings.width,
- fullSettings.height,
- );
-
- const usedMediaIds = new Set<string>();
- for (const track of project.timeline.tracks) {
- for (const clip of track.clips) {
- if (clip.mediaId) {
- usedMediaIds.add(clip.mediaId);
- }
- }
- }
-
- for (const mediaId of usedMediaIds) {
- const mediaItem = project.mediaLibrary.items.find(m => m.id === mediaId);
- if (mediaItem?.blob && mediaItem.type === "video") {
- await mediaEngine.createExportDecoder(mediaId, mediaItem.blob, fullSettings.width);
- }
- }
-
- const self = this;
-
- async function* generateFrames(): AsyncIterable<{ image: ImageBitmap; frameIndex: number }> {
- for (let frame = 0; frame < totalFrames; frame++) {
- if (self.abortController?.signal.aborted) {
- return;
- }
-
- const time = frame / fullSettings.frameRate;
- const rendered = await self.videoEngine!.renderFrame(
- project,
- time,
- fullSettings.width,
- fullSettings.height,
- );
-
- const shouldUpscale = self.shouldApplyUpscaling(project, fullSettings);
- let frameImage = rendered.image;
-
- if (shouldUpscale && self.upscalingEngine?.isInitialized()) {
- const upscaled = await self.upscalingEngine.upscaleImageBitmap(
- frameImage,
- fullSettings.width,
- fullSettings.height,
- fullSettings.upscaling!,
- );
- frameImage.close();
- frameImage = upscaled;
- }
-
- self.currentExport!.framesRendered = frame + 1;
-
- if ((frame + 1) % 60 === 0) {
- self.videoEngine?.clearVideoElementCache();
- mediaEngine.clearFrameCache();
- }
-
- yield { image: frameImage, frameIndex: frame };
- }
- }
-
- let lastProgress: ExportProgress | null = null;
- const onProgress = (progress: ExportProgress) => {
- lastProgress = progress;
- };
-
- const audioBuffer = await this.renderTimelineAudio(project, fullSettings);
-
- const resultPromise = ffmpeg.encodeFrameSequence(
- generateFrames(),
- {
- width: fullSettings.width,
- height: fullSettings.height,
- frameRate: fullSettings.frameRate,
- totalFrames,
- format: fullSettings.format === "webm" ? "webm" : "mp4",
- videoBitrate: `${fullSettings.bitrate}k`,
- audioBitrate: `${fullSettings.audioSettings.bitrate}k`,
- audioBuffer: audioBuffer || undefined,
- writableStream,
- },
- onProgress,
- );
-
- while (true) {
- await new Promise((resolve) => setTimeout(resolve, 100));
-
- if (lastProgress !== null) {
- const progressToYield = lastProgress as ExportProgress;
- yield progressToYield;
- if (progressToYield.phase === "complete") {
- break;
- }
- }
-
- const isResolved = await Promise.race([
- resultPromise.then(() => true),
- new Promise<false>((resolve) => setTimeout(() => resolve(false), 10)),
- ]);
-
- if (isResolved) {
- break;
- }
- }
-
- const blob = await resultPromise;
-
- return {
- success: true,
- blob: blob || undefined,
- stats: this.calculateStats(totalFrames, blob?.size || 0),
- };
- } catch (error) {
- if (error && typeof error === "object" && "code" in error) {
- return { success: false, error: error as ExportError };
- }
- return {
- success: false,
- error: this.createError(
- "FRAME_ENCODE_FAILED",
- error instanceof Error ? error.message : "Unknown error",
- "rendering",
- ),
- };
- } finally {
- this.abortController = null;
- this.currentExport = null;
- this.videoEngine?.clearVideoElementCache();
- mediaEngine.disposeAllExportDecoders();
- mediaEngine.clearFrameCache();
+ this.videoEngine?.clearCache();
+ try {
+ getMediaEngine().disposeAllExportDecoders();
+ getMediaEngine().clearFrameCache();
+ } catch {}
}
}
@@ -1898,18 +1211,6 @@ export class ExportEngine {
}
}
- private getMimeType(format: VideoExportSettings["format"]): string {
- switch (format) {
- case "webm":
- return "video/webm";
- case "mov":
- return "video/quicktime";
- case "mp4":
- default:
- return "video/mp4";
- }
- }
-
private getAudioMimeType(format: AudioExportSettings["format"]): string {
switch (format) {
case "mp3":
@@ -2094,5 +1395,5 @@ export function downloadBlob(blob: Blob, filename: string): void {
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
- URL.revokeObjectURL(url);
+ setTimeout(() => URL.revokeObjectURL(url), 60000);
}
diff --git a/packages/core/src/export/export-worker.ts b/packages/core/src/export/export-worker.ts
index 46653a28..5df52281 100644
--- a/packages/core/src/export/export-worker.ts
+++ b/packages/core/src/export/export-worker.ts
@@ -139,7 +139,7 @@ async function initialize(
videoSource = new VideoSampleSource({
codec: videoCodec,
- bitrate: QUALITY_MEDIUM,
+ bitrate: settings.bitrate ? settings.bitrate * 1000 : QUALITY_MEDIUM,
keyFrameInterval: settings.keyframeInterval / settings.frameRate,
hardwareAcceleration: "prefer-hardware",
});
@@ -268,7 +268,7 @@ async function addAudio(audioData: {
async function finalize() {
while (frameQueue.length > 0 || isProcessing) {
- await new Promise((resolve) => setTimeout(resolve, 50));
+ await new Promise((resolve) => setTimeout(resolve, 5));
}
if (cancelled || !output || !videoSource || !audioSource || !target) {
diff --git a/packages/core/src/media/ffmpeg-fallback.ts b/packages/core/src/media/ffmpeg-fallback.ts
index 1ce4c213..e7e53a87 100644
--- a/packages/core/src/media/ffmpeg-fallback.ts
+++ b/packages/core/src/media/ffmpeg-fallback.ts
@@ -1042,6 +1042,49 @@ export class FFmpegFallback {
}
}
+ async concatenateSegments(
+ segments: Blob[],
+ format: string = "mp4",
+ ): Promise<Blob> {
+ this.ensureLoaded();
+
+ const filenames: string[] = [];
+ const ext = format === "webm" ? "webm" : "mp4";
+
+ for (let i = 0; i < segments.length; i++) {
+ const name = `seg_${String(i).padStart(4, "0")}.${ext}`;
+ const data = new Uint8Array(await segments[i].arrayBuffer());
+ await this.ffmpeg!.writeFile(name, data);
+ filenames.push(name);
+ }
+
+ let concatList = "";
+ for (const name of filenames) {
+ concatList += `file '${name}'\n`;
+ }
+ await this.ffmpeg!.writeFile("concat_list.txt", concatList);
+
+ const outputName = `output.${ext}`;
+ await this.ffmpeg!.exec([
+ "-f", "concat", "-safe", "0",
+ "-i", "concat_list.txt",
+ "-c", "copy",
+ outputName,
+ ]);
+
+ const outputData = await this.ffmpeg!.readFile(outputName);
+ const mimeType = format === "webm" ? "video/webm" : "video/mp4";
+ const blob = new Blob([outputData.buffer as ArrayBuffer], { type: mimeType });
+
+ await this.cleanupFiles([
+ ...filenames,
+ "concat_list.txt",
+ outputName,
+ ]);
+
+ return blob;
+ }
+
terminate(): void {
if (this.ffmpeg) {
this.removeProgressTracking();
diff --git a/packages/core/src/media/mediabunny-engine.ts b/packages/core/src/media/mediabunny-engine.ts
index 7dbf6305..85bfebf9 100644
--- a/packages/core/src/media/mediabunny-engine.ts
+++ b/packages/core/src/media/mediabunny-engine.ts
@@ -72,6 +72,8 @@ export class ExportFrameDecoder {
private file: File | Blob;
private width?: number;
private initialized = false;
+ private reusableCanvas: OffscreenCanvas | null = null;
+ private reusableCtx: OffscreenCanvasRenderingContext2D | null = null;
constructor(mediabunny: typeof import("mediabunny"), file: File | Blob, width?: number) {
this.mediabunny = mediabunny;
@@ -120,12 +122,17 @@ export class ExportFrameDecoder {
const result = await this.sink.getCanvas(timestamp);
if (!result) return null;
- const clone = new OffscreenCanvas(result.canvas.width, result.canvas.height);
- const ctx = clone.getContext("2d");
- if (ctx) {
- ctx.drawImage(result.canvas, 0, 0);
+ const w = result.canvas.width;
+ const h = result.canvas.height;
+
+ if (!this.reusableCanvas || this.reusableCanvas.width !== w || this.reusableCanvas.height !== h) {
+ this.reusableCanvas = new OffscreenCanvas(w, h);
+ this.reusableCtx = this.reusableCanvas.getContext("2d") as OffscreenCanvasRenderingContext2D;
}
- return clone;
+
+ this.reusableCtx!.clearRect(0, 0, w, h);
+ this.reusableCtx!.drawImage(result.canvas, 0, 0);
+ return this.reusableCanvas;
}
dispose(): void {
@@ -134,6 +141,8 @@ export class ExportFrameDecoder {
this.input = null;
}
this.sink = null;
+ this.reusableCanvas = null;
+ this.reusableCtx = null;
this.initialized = false;
}
}
@@ -142,7 +151,7 @@ export class MediaBunnyEngine {
private initialized = false;
private mediabunny: typeof import("mediabunny") | null = null;
private frameCache: Map<string, FrameCacheEntry> = new Map();
- private readonly MAX_CACHE_SIZE = 50;
+ private readonly MAX_CACHE_SIZE = 5;
private exportDecoders: Map<string, ExportFrameDecoder> = new Map();
async initialize(): Promise<void> {
@@ -163,6 +172,12 @@ export class MediaBunnyEngine {
}
clearFrameCache(): void {
+ for (const entry of this.frameCache.values()) {
+ if (entry.image instanceof OffscreenCanvas) {
+ entry.image.width = 0;
+ entry.image.height = 0;
+ }
+ }
this.frameCache.clear();
}
diff --git a/packages/core/src/video/video-engine.ts b/packages/core/src/video/video-engine.ts
index 98f33294..2ecf8450 100644
--- a/packages/core/src/video/video-engine.ts
+++ b/packages/core/src/video/video-engine.ts
@@ -73,12 +73,15 @@ export class VideoEngine {
private initialized = false;
private frameCache: Map<string, CachedFrame> = new Map();
private gifFrameCache: Map<string, GifFrameCache> = new Map();
+ private staticImageCache: Map<string, ImageBitmap> = new Map();
private cacheConfig: FrameCacheConfig;
private cacheStats = { hits: 0, misses: 0 };
private preloadQueue: PreloadRequest[] = [];
private isPreloading = false;
private compositeCanvas: OffscreenCanvas | null = null;
private compositeCtx: OffscreenCanvasRenderingContext2D | null = null;
+ private decodeCanvas: OffscreenCanvas | null = null;
+ private decodeCtx: OffscreenCanvasRenderingContext2D | null = null;
private parallelDecoder: ParallelFrameDecoder | null = null;
private compositeBuffer: CompositeFrameBuffer | null = null;
@@ -326,9 +329,15 @@ export class VideoEngine {
}, 3000);
});
- const canvas = new OffscreenCanvas(width, height);
- const ctx = canvas.getContext("2d");
- if (!ctx) return null;
+ if (
+ !this.decodeCanvas ||
+ this.decodeCanvas.width !== width ||
+ this.decodeCanvas.height !== height
+ ) {
+ this.decodeCanvas = new OffscreenCanvas(width, height);
+ this.decodeCtx = this.decodeCanvas.getContext("2d") as OffscreenCanvasRenderingContext2D;
+ }
+ const ctx = this.decodeCtx!;
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = "high";
@@ -353,7 +362,7 @@ export class VideoEngine {
ctx.fillRect(0, 0, width, height);
ctx.drawImage(video, drawX, drawY, drawWidth, drawHeight);
- return createImageBitmap(canvas);
+ return createImageBitmap(this.decodeCanvas);
}
/**
@@ -361,7 +370,9 @@ export class VideoEngine {
*/
clearVideoElementCache(): void {
for (const [, cached] of this.videoElementCache) {
- cached.video.src = "";
+ cached.video.pause();
+ cached.video.removeAttribute("src");
+ cached.video.load();
URL.revokeObjectURL(cached.url);
}
this.videoElementCache.clear();
@@ -420,8 +431,16 @@ export class VideoEngine {
)
.sort((a, b) => b.originalIndex - a.originalIndex);
- const canvas = new OffscreenCanvas(width, height);
- const ctx = canvas.getContext("2d") as OffscreenCanvasRenderingContext2D;
+ if (
+ !this.compositeCanvas ||
+ this.compositeCanvas.width !== width ||
+ this.compositeCanvas.height !== height
+ ) {
+ this.compositeCanvas = new OffscreenCanvas(width, height);
+ this.compositeCtx = this.compositeCanvas.getContext("2d") as OffscreenCanvasRenderingContext2D;
+ }
+ const canvas = this.compositeCanvas;
+ const ctx = this.compositeCtx!;
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = "high";
ctx.fillStyle = "#000000";
@@ -438,6 +457,7 @@ export class VideoEngine {
if (!mediaItem?.blob) continue;
let bitmap: ImageBitmap | null = null;
+ let bitmapFromCache = false;
if (mediaItem.type === "image") {
try {
@@ -457,11 +477,20 @@ export class VideoEngine {
clipLocalTime * 1000,
);
bitmap = gifCache.frames[frameIndex];
+ bitmapFromCache = true;
} else {
bitmap = await createImageBitmap(mediaItem.blob);
}
} else {
- bitmap = await createImageBitmap(mediaItem.blob);
+ const cached = this.staticImageCache.get(mediaItem.id);
+ if (cached) {
+ bitmap = cached;
+ bitmapFromCache = true;
+ } else {
+ bitmap = await createImageBitmap(mediaItem.blob);
+ this.staticImageCache.set(mediaItem.id, bitmap);
+ bitmapFromCache = true;
+ }
}
} catch (error) {
console.warn(
@@ -579,7 +608,9 @@ export class VideoEngine {
if (processedBitmap !== bitmap) {
processedBitmap.close();
}
- bitmap.close();
+ if (!bitmapFromCache) {
+ bitmap.close();
+ }
}
}
} else if (track.type === "graphics") {
@@ -639,15 +670,6 @@ export class VideoEngine {
const imageBitmap = await createImageBitmap(canvas);
- if (this.compositeBuffer) {
- const frameNumber = Math.floor(time * 30);
- this.compositeBuffer.writeCompositedFrame(
- await createImageBitmap(imageBitmap),
- time,
- frameNumber,
- );
- }
-
return {
image: imageBitmap,
timestamp: time,
@@ -1942,6 +1964,13 @@ export class VideoEngine {
}
this.frameCache.clear();
this.cacheStats = { hits: 0, misses: 0 };
+
+ for (const gifCache of this.gifFrameCache.values()) {
+ for (const frame of gifCache.frames) {
+ try { frame.close(); } catch {}
+ }
+ }
+ this.gifFrameCache.clear();
}
/**
@@ -2263,8 +2292,14 @@ export class VideoEngine {
dispose(): void {
this.clearCache();
this.clearVideoElementCache();
+ for (const bitmap of this.staticImageCache.values()) {
+ try { bitmap.close(); } catch {}
+ }
+ this.staticImageCache.clear();
this.compositeCanvas = null;
this.compositeCtx = null;
+ this.decodeCanvas = null;
+ this.decodeCtx = null;
this.preloadQueue = [];
this.initialized = false;
this.mediabunny = null;