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

feat: add CapCut-inspired features and fix background removal

Augustus Otu39b518d98bc3
diff --git a/apps/web/src/components/editor/AssetsPanel.tsx b/apps/web/src/components/editor/AssetsPanel.tsx
index f5218dc0..e6161561 100644
--- a/apps/web/src/components/editor/AssetsPanel.tsx
+++ b/apps/web/src/components/editor/AssetsPanel.tsx
@@ -35,6 +35,7 @@ import { useUIStore } from "../../stores/ui-store";
import type { MediaItem } from "@openreel/core";
import { AspectRatioMatchDialog } from "./dialogs/AspectRatioMatchDialog";
import { AIGenTab } from "./AIGenTab";
+import { TemplatesTab } from "./panels/TemplatesTab";
import { useTtsAudioStore } from "../../stores/tts-store";
import { toast } from "../../stores/notification-store";
import { saveFileHandle, saveDirectoryHandle } from "../../services/media-storage";
@@ -522,11 +523,11 @@ export const AssetsPanel: React.FC = () => {
const fileInputRef = useRef<HTMLInputElement>(null);
const [searchQuery, setSearchQuery] = useState("");
const [activeTab, setActiveTabRaw] = useState<
- "media" | "text" | "graphics" | "ai"
+ "media" | "text" | "graphics" | "ai" | "templates"
>("media");
const ttsHasUnsaved = useTtsAudioStore((s) => s.generatedAudio !== null && !s.isAudioSaved);
- const setActiveTab = useCallback((tab: "media" | "text" | "graphics" | "ai") => {
+ const setActiveTab = useCallback((tab: "media" | "text" | "graphics" | "ai" | "templates") => {
if (activeTab === "ai" && tab !== "ai" && ttsHasUnsaved) {
toast.warning("Unsaved audio discarded", "Save to media or download next time to keep it.");
}
@@ -967,6 +968,19 @@ export const AssetsPanel: React.FC = () => {
<div className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary rounded-t-full shadow-[0_-2px_8px_rgba(34,197,94,0.5)]" />
)}
</button>
+ <button
+ onClick={() => setActiveTab("templates")}
+ className={`pb-3 transition-all relative ${
+ activeTab === "templates"
+ ? "text-text-primary"
+ : "hover:text-text-secondary"
+ }`}
+ >
+ Templates
+ {activeTab === "templates" && (
+ <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-primary rounded-t-full shadow-[0_-2px_8px_rgba(34,197,94,0.5)]" />
+ )}
+ </button>
</div>
{/* Search & view toggle - only show for media tab */}
@@ -1447,6 +1461,9 @@ export const AssetsPanel: React.FC = () => {
{/* AI Tab Content */}
{activeTab === "ai" && <AIGenTab />}
+ {/* Templates Tab Content */}
+ {activeTab === "templates" && <TemplatesTab />}
+
{aspectRatioDialogData && (
<AspectRatioMatchDialog
isOpen={showAspectRatioDialog}
diff --git a/apps/web/src/components/editor/InspectorPanel.tsx b/apps/web/src/components/editor/InspectorPanel.tsx
index 2171a930..1916bb10 100644
--- a/apps/web/src/components/editor/InspectorPanel.tsx
+++ b/apps/web/src/components/editor/InspectorPanel.tsx
@@ -39,6 +39,7 @@ import {
AutoCutSilenceSection,
CropSection,
SpeedSection,
+ SpeedRampSection,
MotionPresetsPanel,
EmphasisAnimationSection,
MotionPathSection,
@@ -48,6 +49,7 @@ import {
BehindSubjectSection,
} from "./inspector";
import { OPENREEL_TTS_URL } from "../../config/api-endpoints";
+import { AutoEditPanel } from "./panels/AutoEditPanel";
import {
getAudioBridgeEffects,
initializeAudioBridgeEffects,
@@ -753,6 +755,13 @@ export const InspectorPanel: React.FC = () => {
</Section>
)}
+ {/* Auto-Edit - Cut video clips to audio beats */}
+ {showAudioEffects && (
+ <Section title="Beat-Synced Auto-Edit" sectionId="auto-edit" defaultOpen={false}>
+ <AutoEditPanel onClose={() => {}} />
+ </Section>
+ )}
+
{/* Transform */}
{showTransformControls && (
<Section title="Transform" sectionId="transform">
@@ -902,6 +911,22 @@ export const InspectorPanel: React.FC = () => {
</Section>
)}
+ {/* Speed Curves */}
+ {showVideoControls &&
+ selectedClip &&
+ !selectedClip.mediaId.startsWith("text-") &&
+ !selectedClip.mediaId.startsWith("shape-") &&
+ !selectedClip.mediaId.startsWith("svg-") &&
+ !selectedClip.mediaId.startsWith("sticker-") && (
+ <Section
+ title="Speed Curves"
+ sectionId="speed-curves"
+ defaultOpen={false}
+ >
+ <SpeedRampSection clip={selectedClip as Clip} />
+ </Section>
+ )}
+
{/* Alignment - Position element on canvas */}
{(clipType === "video" ||
clipType === "image" ||
diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsx
index 304e7d87..fd7c035c 100644
--- a/apps/web/src/components/editor/Preview.tsx
+++ b/apps/web/src/components/editor/Preview.tsx
@@ -67,7 +67,7 @@ import {
ParticleRenderer,
} from "./preview/index";
import { ProcessingOverlay } from "./ProcessingOverlay";
-import { getPersonSegmentationEngine } from "@openreel/core";
+import { getPersonSegmentationEngine, getBackgroundRemovalEngine } from "@openreel/core";
import type { MotionPathConfig, GSAPMotionPathPoint } from "@openreel/core";
const getAdaptivePoolSize = (width: number, height: number): number => {
@@ -2339,7 +2339,27 @@ export const Preview: React.FC = () => {
currentPlayhead,
);
- drawFrameWithTransform(ctx, video, transform, canvas.width, canvas.height);
+ const bgEngine = getBackgroundRemovalEngine();
+ const hasBgRemoval = bgEngine?.isInitialized() && bgEngine.getSettings(clip.id).enabled;
+
+ let videoFrame: HTMLVideoElement | ImageBitmap = video;
+ if (hasBgRemoval) {
+ try {
+ const rawBitmap = await createImageBitmap(video);
+ const processed = await applyEffectsToFrame(clip.id, rawBitmap);
+ if (processed !== rawBitmap) {
+ rawBitmap.close();
+ }
+ videoFrame = processed;
+ } catch {
+ videoFrame = video;
+ }
+ }
+
+ drawFrameWithTransform(ctx, videoFrame, transform, canvas.width, canvas.height);
+ if (videoFrame !== video && videoFrame instanceof ImageBitmap) {
+ videoFrame.close();
+ }
const subjectFrame = hasBehindSubjectText(activeTextClips)
? await captureSubjectFrame(ctx, canvas.width, canvas.height)
: null;
@@ -3775,6 +3795,20 @@ export const Preview: React.FC = () => {
isDark,
]);
+ const [previewInvalidateCounter, setPreviewInvalidateCounter] = useState(0);
+ useEffect(() => {
+ const handler = () => setPreviewInvalidateCounter((c) => c + 1);
+ window.addEventListener("openreel:preview-invalidate", handler);
+ return () => window.removeEventListener("openreel:preview-invalidate", handler);
+ }, []);
+
+ useEffect(() => {
+ if (isPlaying || previewInvalidateCounter === 0) return;
+ const canvas = canvasRef.current;
+ if (!canvas) return;
+ renderFrameDirectly(playheadPosition);
+ }, [previewInvalidateCounter, isPlaying, renderFrameDirectly, playheadPosition]);
+
const selectedClipId = useMemo(() => {
const clipSelection = selectedItems.find((item) => item.type === "clip");
return clipSelection?.id || null;
diff --git a/apps/web/src/components/editor/inspector/BackgroundRemovalSection.tsx b/apps/web/src/components/editor/inspector/BackgroundRemovalSection.tsx
index baeebbd1..e7b7ffc0 100644
--- a/apps/web/src/components/editor/inspector/BackgroundRemovalSection.tsx
+++ b/apps/web/src/components/editor/inspector/BackgroundRemovalSection.tsx
@@ -89,6 +89,7 @@ export const BackgroundRemovalSection: React.FC<
}
onSettingsChange?.(newSettings);
+ window.dispatchEvent(new CustomEvent("openreel:preview-invalidate"));
},
[settings, clipId, onSettingsChange],
);
diff --git a/apps/web/src/components/editor/inspector/SpeedRampSection.tsx b/apps/web/src/components/editor/inspector/SpeedRampSection.tsx
index b960eb56..61bf5898 100644
--- a/apps/web/src/components/editor/inspector/SpeedRampSection.tsx
+++ b/apps/web/src/components/editor/inspector/SpeedRampSection.tsx
@@ -23,6 +23,7 @@ import {
type SpeedKeyframe,
SPEED_MIN,
SPEED_MAX,
+ SPEED_CURVE_PRESETS,
} from "@openreel/core";
interface ClipLike {
@@ -328,6 +329,26 @@ export const SpeedRampSection: React.FC<SpeedRampSectionProps> = ({ clip }) => {
[clip.id, speedEngine],
);
+ const handleApplyCurvePreset = useCallback(
+ (presetId: string) => {
+ const preset = SPEED_CURVE_PRESETS.find((p) => p.id === presetId);
+ if (!preset) return;
+
+ keyframes.forEach((kf) => speedEngine.removeSpeedKeyframe(clip.id, kf.id));
+
+ for (const kf of preset.keyframes) {
+ const absoluteTime = kf.time * clip.duration;
+ speedEngine.addSpeedKeyframe(clip.id, absoluteTime, kf.speed, kf.easing);
+ }
+
+ setShowCurve(true);
+ useProjectStore.setState((state) => ({
+ project: { ...state.project, modifiedAt: Date.now() },
+ }));
+ },
+ [clip.id, clip.duration, keyframes, speedEngine],
+ );
+
const handleReset = useCallback(() => {
speedEngine.setClipSpeed(clip.id, 1, clip.duration);
speedEngine.setReverse(clip.id, false, clip.duration);
@@ -419,6 +440,24 @@ export const SpeedRampSection: React.FC<SpeedRampSectionProps> = ({ clip }) => {
</button>
</div>
+ <div className="space-y-1.5">
+ <span className="text-[10px] font-medium text-text-secondary">
+ Speed Curve Presets
+ </span>
+ <div className="grid grid-cols-2 gap-1">
+ {SPEED_CURVE_PRESETS.map((preset) => (
+ <button
+ key={preset.id}
+ onClick={() => handleApplyCurvePreset(preset.id)}
+ className="py-1.5 px-2 text-[9px] rounded-lg border bg-background-tertiary border-border text-text-secondary hover:border-primary/50 hover:text-primary transition-colors text-left"
+ title={preset.description}
+ >
+ {preset.name}
+ </button>
+ ))}
+ </div>
+ </div>
+
<button
onClick={() => setShowCurve(!showCurve)}
className="w-full flex items-center gap-2 py-2 text-[10px] text-text-secondary hover:text-text-primary transition-colors"
diff --git a/apps/web/src/components/editor/panels/AutoEditPanel.tsx b/apps/web/src/components/editor/panels/AutoEditPanel.tsx
new file mode 100644
index 00000000..186362b1
--- /dev/null
+++ b/apps/web/src/components/editor/panels/AutoEditPanel.tsx
@@ -0,0 +1,309 @@
+import React, { useState, useCallback, useMemo } from "react";
+import { Music, Zap, Loader2 } from "lucide-react";
+import { Slider } from "@openreel/ui";
+import { useProjectStore } from "../../../stores/project-store";
+import {
+ getBeatDetectionEngine,
+ getAutoEditService,
+ type AutoEditOptions,
+ type AutoEditResult,
+ type CutMode,
+ type BeatAnalysisResult,
+ type Clip,
+} from "@openreel/core";
+
+interface AutoEditPanelProps {
+ onClose: () => void;
+}
+
+export const AutoEditPanel: React.FC<AutoEditPanelProps> = ({ onClose }) => {
+ const project = useProjectStore((s) => s.project);
+ const [cutMode, setCutMode] = useState<CutMode>("beats");
+ const [sensitivity, setSensitivity] = useState(0.5);
+ const [minClipDuration, setMinClipDuration] = useState(0.5);
+ const [analyzing, setAnalyzing] = useState(false);
+ const [preview, setPreview] = useState<AutoEditResult | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ const audioClips = useMemo(() => {
+ const clips: Clip[] = [];
+ for (const track of project.timeline.tracks) {
+ if (track.type === "audio") {
+ clips.push(...track.clips);
+ }
+ }
+ return clips;
+ }, [project.timeline.tracks]);
+
+ const videoClips = useMemo(() => {
+ const clips: Clip[] = [];
+ for (const track of project.timeline.tracks) {
+ if (track.type === "video") {
+ clips.push(...track.clips);
+ }
+ }
+ return clips;
+ }, [project.timeline.tracks]);
+
+ const [selectedAudioClipId, setSelectedAudioClipId] = useState<string>(
+ audioClips[0]?.id ?? "",
+ );
+
+ const handleAnalyze = useCallback(async () => {
+ const audioClip = audioClips.find((c) => c.id === selectedAudioClipId);
+ if (!audioClip || videoClips.length === 0) return;
+
+ setAnalyzing(true);
+ setError(null);
+ setPreview(null);
+
+ try {
+ const beatEngine = getBeatDetectionEngine();
+
+ let beatAnalysis: BeatAnalysisResult;
+ const existing = project.timeline.beatAnalysis;
+ if (existing && existing.sourceClipId === selectedAudioClipId) {
+ beatAnalysis = {
+ bpm: existing.bpm,
+ confidence: existing.confidence,
+ beats: project.timeline.beatMarkers?.map((m, i) => ({
+ time: m.time,
+ strength: m.strength,
+ index: i,
+ })) ?? [],
+ duration: project.timeline.duration,
+ downbeats: project.timeline.beatMarkers
+ ?.filter((m) => m.isDownbeat)
+ .map((m) => m.time) ?? [],
+ };
+ } else {
+ const mediaItem = useProjectStore
+ .getState()
+ .project.mediaLibrary.items.find(
+ (m) => m.id === audioClip.mediaId,
+ );
+ if (!mediaItem?.blob) {
+ setError("Audio file not loaded");
+ setAnalyzing(false);
+ return;
+ }
+ beatAnalysis = await beatEngine.analyzeFromBlob(mediaItem.blob);
+ }
+
+ const options: AutoEditOptions = {
+ cutMode,
+ minClipDuration,
+ maxClipDuration: 10,
+ sensitivity,
+ };
+
+ const autoEditService = getAutoEditService();
+ const result = autoEditService.generateCuts(
+ beatAnalysis,
+ videoClips,
+ options,
+ );
+ setPreview(result);
+ } catch (err) {
+ setError(
+ err instanceof Error ? err.message : "Failed to analyze audio",
+ );
+ } finally {
+ setAnalyzing(false);
+ }
+ }, [
+ audioClips,
+ selectedAudioClipId,
+ videoClips,
+ cutMode,
+ sensitivity,
+ minClipDuration,
+ project.timeline,
+ ]);
+
+ const handleApply = useCallback(() => {
+ if (!preview || preview.cuts.length === 0) return;
+
+ const tracks = [...project.timeline.tracks];
+ const videoTrackIndex = tracks.findIndex((t) => t.type === "video");
+ if (videoTrackIndex === -1) return;
+
+ const newClips: Clip[] = preview.cuts.map((cut, index) => {
+ const sourceClip = videoClips.find((c) => c.id === cut.sourceClipId);
+ if (!sourceClip) return null;
+
+ return {
+ ...sourceClip,
+ id: `auto-edit-${Date.now()}-${index}`,
+ startTime: cut.startTime,
+ duration: cut.duration,
+ inPoint: cut.inPoint,
+ outPoint: cut.outPoint,
+ };
+ }).filter((c): c is Clip => c !== null);
+
+ const updatedTrack = {
+ ...tracks[videoTrackIndex],
+ clips: newClips,
+ };
+ tracks[videoTrackIndex] = updatedTrack;
+
+ useProjectStore.setState((state) => ({
+ project: {
+ ...state.project,
+ timeline: {
+ ...state.project.timeline,
+ tracks,
+ duration: preview.totalDuration,
+ },
+ modifiedAt: Date.now(),
+ },
+ }));
+
+ onClose();
+ }, [preview, project.timeline.tracks, videoClips, onClose]);
+
+ return (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Zap size={14} className="text-primary" />
+ <span className="text-[11px] font-medium text-text-primary">
+ Beat-Synced Auto-Edit
+ </span>
+ </div>
+ </div>
+
+ {audioClips.length === 0 ? (
+ <div className="text-center py-6 text-text-muted text-[10px]">
+ <Music size={24} className="mx-auto mb-2 opacity-50" />
+ <p>Add an audio track to use auto-edit</p>
+ </div>
+ ) : (
+ <>
+ <div className="space-y-2">
+ <label className="text-[10px] font-medium text-text-secondary">
+ Audio Source
+ </label>
+ <select
+ value={selectedAudioClipId}
+ onChange={(e) => setSelectedAudioClipId(e.target.value)}
+ className="w-full px-2 py-1.5 text-[10px] bg-background-tertiary border border-border rounded-lg text-text-primary"
+ >
+ {audioClips.map((clip) => (
+ <option key={clip.id} value={clip.id}>
+ {clip.mediaId} ({clip.duration.toFixed(1)}s)
+ </option>
+ ))}
+ </select>
+ </div>
+
+ <div className="space-y-2">
+ <label className="text-[10px] font-medium text-text-secondary">
+ Cut Mode
+ </label>
+ <div className="grid grid-cols-3 gap-1">
+ {(["beats", "downbeats", "segments"] as CutMode[]).map((mode) => (
+ <button
+ key={mode}
+ onClick={() => setCutMode(mode)}
+ className={`py-1.5 text-[9px] rounded-lg border transition-colors capitalize ${
+ cutMode === mode
+ ? "bg-primary/20 border-primary text-primary"
+ : "bg-background-tertiary border-border text-text-secondary hover:border-primary/50"
+ }`}
+ >
+ {mode}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ <div className="space-y-1.5">
+ <div className="flex justify-between">
+ <label className="text-[10px] font-medium text-text-secondary">
+ Sensitivity
+ </label>
+ <span className="text-[9px] text-text-muted">
+ {Math.round(sensitivity * 100)}%
+ </span>
+ </div>
+ <Slider
+ min={0}
+ max={1}
+ step={0.05}
+ value={[sensitivity]}
+ onValueChange={(v) => setSensitivity(v[0])}
+ />
+ </div>
+
+ <div className="space-y-1.5">
+ <div className="flex justify-between">
+ <label className="text-[10px] font-medium text-text-secondary">
+ Min Clip Duration
+ </label>
+ <span className="text-[9px] text-text-muted">
+ {minClipDuration.toFixed(1)}s
+ </span>
+ </div>
+ <Slider
+ min={0.1}
+ max={3}
+ step={0.1}
+ value={[minClipDuration]}
+ onValueChange={(v) => setMinClipDuration(v[0])}
+ />
+ </div>
+
+ <button
+ onClick={handleAnalyze}
+ disabled={analyzing || videoClips.length === 0}
+ className="w-full flex items-center justify-center gap-2 py-2.5 text-[10px] font-medium bg-primary/20 border border-primary/30 text-primary rounded-lg hover:bg-primary/30 transition-colors disabled:opacity-50"
+ >
+ {analyzing ? (
+ <>
+ <Loader2 size={12} className="animate-spin" />
+ Analyzing beats...
+ </>
+ ) : (
+ <>
+ <Zap size={12} />
+ Generate Auto-Edit
+ </>
+ )}
+ </button>
+
+ {error && (
+ <p className="text-[9px] text-red-400">{error}</p>
+ )}
+
+ {preview && (
+ <div className="space-y-2 p-2.5 bg-background-tertiary rounded-lg border border-border">
+ <p className="text-[10px] font-medium text-text-primary">
+ Preview
+ </p>
+ <div className="grid grid-cols-2 gap-2 text-[9px]">
+ <div>
+ <span className="text-text-muted">Cuts: </span>
+ <span className="text-text-primary">{preview.cuts.length}</span>
+ </div>
+ <div>
+ <span className="text-text-muted">Duration: </span>
+ <span className="text-text-primary">
+ {preview.totalDuration.toFixed(1)}s
+ </span>
+ </div>
+ </div>
+ <button
+ onClick={handleApply}
+ className="w-full py-2 text-[10px] font-medium bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors"
+ >
+ Apply Auto-Edit
+ </button>
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ );
+};
diff --git a/apps/web/src/components/editor/panels/TemplatesTab.tsx b/apps/web/src/components/editor/panels/TemplatesTab.tsx
new file mode 100644
index 00000000..d03064e2
--- /dev/null
+++ b/apps/web/src/components/editor/panels/TemplatesTab.tsx
@@ -0,0 +1,181 @@
+import React, { useState, useEffect, useCallback, useMemo } from "react";
+import { Search, Layout, Clock } from "lucide-react";
+import { useEngineStore } from "../../../stores/engine-store";
+import { useProjectStore } from "../../../stores/project-store";
+import type {
+ TemplateSummary,
+ TemplateCategory,
+} from "@openreel/core";
+import { TEMPLATE_CATEGORIES } from "@openreel/core";
+
+export const TemplatesTab: React.FC = () => {
+ const getTemplateEngine = useEngineStore((s) => s.getTemplateEngine);
+ const [templates, setTemplates] = useState<TemplateSummary[]>([]);
+ const [searchQuery, setSearchQuery] = useState("");
+ const [selectedCategory, setSelectedCategory] = useState<
+ "all" | TemplateCategory
+ >("all");
+ const [loading, setLoading] = useState(true);
+ const [applying, setApplying] = useState<string | null>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ const load = async () => {
+ const engine = await getTemplateEngine();
+ await engine.initialize();
+ const list = await engine.listTemplates();
+ if (!cancelled) {
+ setTemplates(list);
+ setLoading(false);
+ }
+ };
+ load();
+ return () => {
+ cancelled = true;
+ };
+ }, [getTemplateEngine]);
+
+ const filteredTemplates = useMemo(() => {
+ let result = templates;
+ if (selectedCategory !== "all") {
+ result = result.filter((t) => t.category === selectedCategory);
+ }
+ if (searchQuery.trim()) {
+ const q = searchQuery.toLowerCase();
+ result = result.filter((t) => t.name.toLowerCase().includes(q));
+ }
+ return result;
+ }, [templates, selectedCategory, searchQuery]);
+
+ const handleApplyTemplate = useCallback(
+ async (templateId: string) => {
+ const hasClips =
+ useProjectStore.getState().project.timeline.tracks.length > 0;
+ if (hasClips) {
+ const confirmed = window.confirm(
+ "Applying a template will replace your current project. Continue?",
+ );
+ if (!confirmed) return;
+ }
+
+ setApplying(templateId);
+ try {
+ const engine = await getTemplateEngine();
+ const template = await engine.loadTemplate(templateId);
+ if (!template) return;
+
+ const result = engine.applyTemplate(template, {});
+ useProjectStore.setState(() => ({
+ project: { ...result.project, modifiedAt: Date.now() },
+ }));
+ } finally {
+ setApplying(null);
+ }
+ },
+ [getTemplateEngine],
+ );
+
+ const formatDuration = (seconds: number): string => {
+ const mins = Math.floor(seconds / 60);
+ const secs = Math.round(seconds % 60);
+ return mins > 0 ? `${mins}:${secs.toString().padStart(2, "0")}` : `${secs}s`;
+ };
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center py-12 text-text-muted text-xs">
+ Loading templates...
+ </div>
+ );
+ }
+
+ return (
+ <div className="px-5 space-y-3">
+ <div className="relative">
+ <Search
+ size={14}
+ className="absolute left-2.5 top-1/2 -translate-y-1/2 text-text-muted"
+ />
+ <input
+ type="text"
+ placeholder="Search templates..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ className="w-full pl-8 pr-3 py-2 text-xs bg-background-secondary border border-border rounded-lg text-text-primary placeholder:text-text-muted focus:outline-none focus:border-primary/50"
+ />
+ </div>
+
+ <div className="flex gap-1.5 flex-wrap">
+ <button
+ onClick={() => setSelectedCategory("all")}
+ className={`px-2.5 py-1 text-[10px] rounded-full border transition-colors ${
+ selectedCategory === "all"
+ ? "bg-primary/20 border-primary text-primary"
+ : "bg-background-tertiary border-border text-text-muted hover:border-primary/50"
+ }`}
+ >
+ All
+ </button>
+ {TEMPLATE_CATEGORIES.slice(0, 6).map((cat) => (
+ <button
+ key={cat.id}
+ onClick={() => setSelectedCategory(cat.id)}
+ className={`px-2.5 py-1 text-[10px] rounded-full border transition-colors ${
+ selectedCategory === cat.id
+ ? "bg-primary/20 border-primary text-primary"
+ : "bg-background-tertiary border-border text-text-muted hover:border-primary/50"
+ }`}
+ >
+ {cat.name}
+ </button>
+ ))}
+ </div>
+
+ {filteredTemplates.length === 0 ? (
+ <div className="text-center py-8 text-text-muted text-xs">
+ No templates found
+ </div>
+ ) : (
+ <div className="grid grid-cols-2 gap-2">
+ {filteredTemplates.map((template) => (
+ <button
+ key={template.id}
+ onClick={() => handleApplyTemplate(template.id)}
+ disabled={applying !== null}
+ className="group relative flex flex-col p-3 bg-background-tertiary border border-border rounded-lg hover:border-primary/50 transition-all text-left disabled:opacity-50"
+ >
+ <div className="w-full aspect-video bg-background-secondary rounded mb-2 flex items-center justify-center">
+ {template.thumbnailUrl ? (
+ <img
+ src={template.thumbnailUrl}
+ alt={template.name}
+ className="w-full h-full object-cover rounded"
+ />
+ ) : (
+ <Layout size={20} className="text-text-muted" />
+ )}
+ </div>
+ <span className="text-[10px] font-medium text-text-primary truncate w-full">
+ {template.name}
+ </span>
+ <div className="flex items-center gap-2 mt-1">
+ <span className="text-[9px] text-text-muted capitalize">
+ {template.category.replace("-", " ")}
+ </span>
+ <span className="flex items-center gap-0.5 text-[9px] text-text-muted">
+ <Clock size={8} />
+ {formatDuration(template.duration)}
+ </span>
+ </div>
+ {applying === template.id && (
+ <div className="absolute inset-0 bg-background-primary/80 rounded-lg flex items-center justify-center">
+ <span className="text-[10px] text-primary">Applying...</span>
+ </div>
+ )}
+ </button>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+};
diff --git a/apps/web/src/hooks/useProjectRecovery.ts b/apps/web/src/hooks/useProjectRecovery.ts
index db4727c7..a26d6925 100644
--- a/apps/web/src/hooks/useProjectRecovery.ts
+++ b/apps/web/src/hooks/useProjectRecovery.ts
@@ -1,5 +1,6 @@
import { useState, useEffect, useCallback } from "react";
import { autoSaveManager, type AutoSaveMetadata } from "../services/auto-save";
+import { clearAllStorage } from "../services/media-storage";
import { useProjectStore } from "../stores/project-store";
interface RecoveryState {
@@ -66,6 +67,7 @@ export function useProjectRecovery() {
const clearAll = useCallback(async () => {
await autoSaveManager.clearAllSaves();
+ await clearAllStorage();
setState((prev) => ({ ...prev, availableSaves: [], showDialog: false }));
}, []);
diff --git a/apps/web/src/services/media-storage.ts b/apps/web/src/services/media-storage.ts
index c20ead39..ad39739a 100644
--- a/apps/web/src/services/media-storage.ts
+++ b/apps/web/src/services/media-storage.ts
@@ -75,3 +75,20 @@ export async function getStorageStats(): Promise<{
mediaCount: usage.mediaItems,
};
}
+
+export async function clearAllStorage(): Promise<void> {
+ await storage.clearAllData();
+
+ const databasesToDelete = ["openreel-autosave", "openreel-projects", "openreel-templates"];
+ await Promise.allSettled(
+ databasesToDelete.map(
+ (dbName) =>
+ new Promise<void>((resolve, reject) => {
+ const request = indexedDB.deleteDatabase(dbName);
+ request.onsuccess = () => resolve();
+ request.onerror = () => reject(request.error);
+ request.onblocked = () => resolve();
+ }),
+ ),
+ );
+}
diff --git a/packages/core/src/ai/background-removal-engine.ts b/packages/core/src/ai/background-removal-engine.ts
index 406b5237..a61492a6 100644
--- a/packages/core/src/ai/background-removal-engine.ts
+++ b/packages/core/src/ai/background-removal-engine.ts
@@ -1,3 +1,5 @@
+import { getPersonSegmentationEngine } from "./person-segmentation-engine";
+
export type BackgroundMode =
| "blur"
| "color"
@@ -37,6 +39,7 @@ export class BackgroundRemovalEngine {
private backgroundImage: ImageBitmap | null = null;
private settings: Map<string, BackgroundRemovalSettings> = new Map();
private initialized = false;
+ private useAI = false;
async initialize(onProgress?: ProgressCallback): Promise<void> {
if (this.initialized) return;
@@ -52,6 +55,15 @@ export class BackgroundRemovalEngine {
this.outputCanvas = new OffscreenCanvas(1920, 1080);
this.outputCtx = this.outputCanvas.getContext("2d");
+ onProgress?.(50, "Loading AI segmentation model...");
+ const segEngine = getPersonSegmentationEngine();
+ try {
+ await segEngine.initialize();
+ this.useAI = true;
+ } catch {
+ this.useAI = false;
+ }
+
onProgress?.(100, "Background removal ready");
this.initialized = true;
}
@@ -101,9 +113,12 @@ export class BackgroundRemovalEngine {
this.outputCanvas!.height = height;
}
+ if (this.useAI) {
+ return this.processFrameFast(clipId, frame, width, height, settings);
+ }
+
this.ctx.drawImage(frame, 0, 0, width, height);
const imageData = this.ctx.getImageData(0, 0, width, height);
-
const mask = this.generateSimpleMask(imageData, settings.threshold);
if (settings.edgeBlur > 0) {
@@ -111,7 +126,6 @@ export class BackgroundRemovalEngine {
}
this.maskCtx.putImageData(mask, 0, 0);
-
this.outputCtx.clearRect(0, 0, width, height);
switch (settings.mode) {
@@ -146,6 +160,77 @@ export class BackgroundRemovalEngine {
return createImageBitmap(this.outputCanvas!);
}
+ private async processFrameFast(
+ _clipId: string,
+ frame: ImageBitmap,
+ width: number,
+ height: number,
+ settings: BackgroundRemovalSettings,
+ ): Promise<ImageBitmap> {
+ const segEngine = getPersonSegmentationEngine();
+ const segResult = await segEngine.getPersonMask(frame);
+ if (!segResult) return frame;
+
+ if (settings.edgeBlur > 0 || settings.threshold !== 0.7) {
+ const maskData = new ImageData(
+ new Uint8ClampedArray(segResult.mask.data),
+ segResult.mask.width,
+ segResult.mask.height,
+ );
+ const thresholdByte = Math.round(settings.threshold * 255);
+ const alphaData = maskData.data;
+ for (let i = 3; i < alphaData.length; i += 4) {
+ const raw = alphaData[i];
+ alphaData[i] = raw >= thresholdByte ? 255 : Math.round(raw * (raw / thresholdByte));
+ }
+ this.maskCtx!.putImageData(maskData, 0, 0);
+ if (settings.edgeBlur > 0) {
+ this.maskCtx!.filter = `blur(${settings.edgeBlur}px)`;
+ this.maskCtx!.drawImage(this.maskCanvas!, 0, 0);
+ this.maskCtx!.filter = "none";
+ }
+ } else {
+ this.maskCtx!.putImageData(segResult.mask, 0, 0);
+ }
+
+ this.outputCtx!.clearRect(0, 0, width, height);
+
+ switch (settings.mode) {
+ case "blur":
+ this.outputCtx!.filter = `blur(${settings.blurAmount}px)`;
+ this.outputCtx!.drawImage(frame, 0, 0, width, height);
+ this.outputCtx!.filter = "none";
+ break;
+ case "color":
+ this.outputCtx!.fillStyle = settings.backgroundColor;
+ this.outputCtx!.fillRect(0, 0, width, height);
+ break;
+ case "image":
+ if (this.backgroundImage) {
+ this.outputCtx!.drawImage(this.backgroundImage, 0, 0, width, height);
+ } else {
+ this.outputCtx!.fillStyle = "#000000";
+ this.outputCtx!.fillRect(0, 0, width, height);
+ }
+ break;
+ case "transparent":
+ break;
+ default:
+ this.outputCtx!.drawImage(frame, 0, 0, width, height);
+ return createImageBitmap(this.outputCanvas!);
+ }
+
+ this.ctx!.clearRect(0, 0, width, height);
+ this.ctx!.drawImage(frame, 0, 0, width, height);
+ this.ctx!.globalCompositeOperation = "destination-in";
+ this.ctx!.drawImage(this.maskCanvas!, 0, 0, width, height);
+ this.ctx!.globalCompositeOperation = "source-over";
+
+ this.outputCtx!.drawImage(this.canvas!, 0, 0);
+
+ return createImageBitmap(this.outputCanvas!);
+ }
+
private generateSimpleMask(
imageData: ImageData,
_threshold: number,
diff --git a/packages/core/src/ai/person-segmentation-engine.ts b/packages/core/src/ai/person-segmentation-engine.ts
index ddc5af8d..8fbe25d7 100644
--- a/packages/core/src/ai/person-segmentation-engine.ts
+++ b/packages/core/src/ai/person-segmentation-engine.ts
@@ -16,6 +16,15 @@ export class PersonSegmentationEngine {
private segmenter: ImageSegmenter | null = null;
private initialized = false;
private initializing: Promise<void> | null = null;
+ private cachedMask: SegmentationResult | null = null;
+ private lastSegmentTime = 0;
+ private segmentInterval = 66;
+ private segCanvas: HTMLCanvasElement | null = null;
+ private segCtx: CanvasRenderingContext2D | null = null;
+ private upscaleCanvas: HTMLCanvasElement | null = null;
+ private upscaleCtx: CanvasRenderingContext2D | null = null;
+ private readonly SEG_WIDTH = 512;
+ private readonly SEG_HEIGHT = 288;
async initialize(): Promise<void> {
if (this.initialized) return;
@@ -40,11 +49,19 @@ export class PersonSegmentationEngine {
modelAssetPath: MODEL_URL,
delegate: "GPU",
},
- runningMode: "IMAGE",
+ runningMode: "VIDEO",
outputCategoryMask: false,
outputConfidenceMasks: true,
});
+ this.segCanvas = document.createElement("canvas");
+ this.segCanvas.width = this.SEG_WIDTH;
+ this.segCanvas.height = this.SEG_HEIGHT;
+ this.segCtx = this.segCanvas.getContext("2d", { willReadFrequently: true });
+
+ this.upscaleCanvas = document.createElement("canvas");
+ this.upscaleCtx = this.upscaleCanvas.getContext("2d", { willReadFrequently: true });
+
this.initialized = true;
this.initializing = null;
}
@@ -53,24 +70,29 @@ export class PersonSegmentationEngine {
return this.initialized;
}
+ setSegmentInterval(ms: number): void {
+ this.segmentInterval = Math.max(16, ms);
+ }
+
async getPersonMask(frame: ImageBitmap): Promise<SegmentationResult | null> {
if (!this.segmenter) return null;
- const width = frame.width;
- const height = frame.height;
+ const now = performance.now();
+ if (this.cachedMask && now - this.lastSegmentTime < this.segmentInterval) {
+ return this.cachedMask;
+ }
+
+ const outputWidth = frame.width;
+ const outputHeight = frame.height;
+
+ if (!this.segCtx || !this.segCanvas) return null;
- const canvas = document.createElement("canvas");
- canvas.width = width;
- canvas.height = height;
- const ctx = canvas.getContext("2d")!;
- ctx.drawImage(frame, 0, 0);
+ this.segCtx.drawImage(frame, 0, 0, this.SEG_WIDTH, this.SEG_HEIGHT);
- let maskData: ImageData | null = null;
+ let rawMask: Float32Array | null = null;
- this.segmenter.segment(canvas, (result) => {
+ this.segmenter.segmentForVideo(this.segCanvas, Math.round(now), (result) => {
if (result.confidenceMasks && result.confidenceMasks.length > 0) {
- // Selfie segmentation models may return background first and person
- // second. Prefer the foreground/person mask when it is available.
const labels = this.segmenter?.getLabels() ?? [];
const personLabelIndex = labels.findIndex((label) =>
/foreground|human|person|selfie/i.test(label),
@@ -83,17 +105,7 @@ export class PersonSegmentationEngine {
: 0;
const foregroundMask =
result.confidenceMasks[foregroundMaskIndex] ?? result.confidenceMasks[0];
- const mask = foregroundMask.getAsFloat32Array();
- maskData = new ImageData(width, height);
-
- for (let i = 0; i < mask.length; i++) {
- const confidence = mask[i];
- const alpha = Math.round(confidence * 255);
- maskData.data[i * 4] = 255;
- maskData.data[i * 4 + 1] = 255;
- maskData.data[i * 4 + 2] = 255;
- maskData.data[i * 4 + 3] = alpha;
- }
+ rawMask = new Float32Array(foregroundMask.getAsFloat32Array());
for (const confidenceMask of result.confidenceMasks) {
confidenceMask.close();
@@ -101,9 +113,79 @@ export class PersonSegmentationEngine {
}
});
- if (!maskData) return null;
+ if (!rawMask) return this.cachedMask;
+
+ const segMaskData = new ImageData(this.SEG_WIDTH, this.SEG_HEIGHT);
+ for (let i = 0; i < (rawMask as Float32Array).length; i++) {
+ const alpha = Math.round((rawMask as Float32Array)[i] * 255);
+ segMaskData.data[i * 4] = 255;
+ segMaskData.data[i * 4 + 1] = 255;
+ segMaskData.data[i * 4 + 2] = 255;
+ segMaskData.data[i * 4 + 3] = alpha;
+ }
+
+ if (
+ !this.upscaleCanvas || !this.upscaleCtx ||
+ this.upscaleCanvas.width !== outputWidth ||
+ this.upscaleCanvas.height !== outputHeight
+ ) {
+ this.upscaleCanvas!.width = outputWidth;
+ this.upscaleCanvas!.height = outputHeight;
+ }
+
+ const tempCanvas = document.createElement("canvas");
+ tempCanvas.width = this.SEG_WIDTH;
+ tempCanvas.height = this.SEG_HEIGHT;
+ const tempCtx = tempCanvas.getContext("2d")!;
+ tempCtx.putImageData(segMaskData, 0, 0);
+
+ this.upscaleCtx!.imageSmoothingEnabled = true;
+ this.upscaleCtx!.imageSmoothingQuality = "high";
+ this.upscaleCtx!.clearRect(0, 0, outputWidth, outputHeight);
+ this.upscaleCtx!.drawImage(tempCanvas, 0, 0, outputWidth, outputHeight);
- return { mask: maskData, width, height };
+ const maskData = this.upscaleCtx!.getImageData(0, 0, outputWidth, outputHeight);
+
+ this.refineEdges(maskData);
+
+ this.cachedMask = { mask: maskData, width: outputWidth, height: outputHeight };
+ this.lastSegmentTime = now;
+ return this.cachedMask;
+ }
+
+ private refineEdges(mask: ImageData): void {
+ const { data, width, height } = mask;
+ const radius = 2;
+ const temp = new Uint8ClampedArray(width * height);
+
+ for (let i = 0; i < data.length; i += 4) {
+ temp[i >> 2] = data[i + 3];
+ }
+
+ for (let y = radius; y < height - radius; y++) {
+ for (let x = radius; x < width - radius; x++) {
+ const idx = y * width + x;
+ const center = temp[idx];
+
+ if (center === 0 || center === 255) continue;
+
+ let sum = 0;
+ let count = 0;
+ for (let dy = -radius; dy <= radius; dy++) {
+ for (let dx = -radius; dx <= radius; dx++) {
+ sum += temp[(y + dy) * width + (x + dx)];
+ count++;
+ }
+ }
+ const smoothed = sum / count;
+
+ const contrast = smoothed < 128
+ ? smoothed * smoothed / 128
+ : 255 - (255 - smoothed) * (255 - smoothed) / 128;
+
+ data[(idx) * 4 + 3] = Math.round(contrast);
+ }
+ }
}
dispose(): void {
@@ -111,6 +193,11 @@ export class PersonSegmentationEngine {
this.segmenter.close();
this.segmenter = null;
}
+ this.segCanvas = null;
+ this.segCtx = null;
+ this.upscaleCanvas = null;
+ this.upscaleCtx = null;
+ this.cachedMask = null;
this.initialized = false;
this.initializing = null;
}
diff --git a/packages/core/src/storage/storage-engine.ts b/packages/core/src/storage/storage-engine.ts
index a9b7ffec..a4bd9e6f 100644
--- a/packages/core/src/storage/storage-engine.ts
+++ b/packages/core/src/storage/storage-engine.ts
@@ -443,6 +443,33 @@ export class StorageEngine implements IStorageEngine {
});
}
+ async clearAllData(): Promise<void> {
+ const db = await this.getDb();
+ const storeNames = [
+ STORES.PROJECTS,
+ STORES.MEDIA,
+ STORES.CACHE,
+ STORES.WAVEFORMS,
+ STORES.FILE_HANDLES,
+ STORES.DIR_HANDLES,
+ ];
+
+ return new Promise((resolve, reject) => {
+ const tx = db.transaction(storeNames, "readwrite");
+ for (const storeName of storeNames) {
+ tx.objectStore(storeName).clear();
+ }
+ tx.oncomplete = () => resolve();
+ tx.onerror = () =>
+ reject(
+ createStorageError(
+ "DATABASE_ERROR",
+ `Failed to clear all data: ${tx.error?.message}`,
+ ),
+ );
+ });
+ }
+
close(): void {
if (this.db) {
this.db.close();
diff --git a/packages/core/src/storage/types.ts b/packages/core/src/storage/types.ts
index d2ce30bd..da579d9a 100644
--- a/packages/core/src/storage/types.ts
+++ b/packages/core/src/storage/types.ts
@@ -122,5 +122,6 @@ export interface IStorageEngine {
getStorageUsage(): Promise<StorageUsage>;
// Database management
+ clearAllData(): Promise<void>;
close(): void;
}
diff --git a/packages/core/src/timeline/auto-edit-service.ts b/packages/core/src/timeline/auto-edit-service.ts
new file mode 100644
index 00000000..ef3dc216
--- /dev/null
+++ b/packages/core/src/timeline/auto-edit-service.ts
@@ -0,0 +1,145 @@
+import type { Beat, BeatAnalysisResult } from "../audio/beat-detection-engine";
+import type { Clip } from "../types/timeline";
+
+export type CutMode = "beats" | "downbeats" | "segments";
+
+export interface AutoEditOptions {
+ readonly cutMode: CutMode;
+ readonly minClipDuration: number;
+ readonly maxClipDuration: number;
+ readonly sensitivity: number;
+}
+
+export const DEFAULT_AUTO_EDIT_OPTIONS: AutoEditOptions = {
+ cutMode: "beats",
+ minClipDuration: 0.3,
+ maxClipDuration: 10,
+ sensitivity: 0.5,
+};
+
+export interface AutoEditCut {
+ readonly sourceClipId: string;
+ readonly inPoint: number;
+ readonly outPoint: number;
+ readonly startTime: number;
+ readonly duration: number;
+}
+
+export interface AutoEditResult {
+ readonly cuts: AutoEditCut[];
+ readonly totalDuration: number;
+ readonly beatCount: number;
+}
+
+export class AutoEditService {
+ generateCuts(
+ beatAnalysis: BeatAnalysisResult,
+ sourceClips: Clip[],
+ options: AutoEditOptions = DEFAULT_AUTO_EDIT_OPTIONS,
+ ): AutoEditResult {
+ if (sourceClips.length === 0 || beatAnalysis.beats.length === 0) {
+ return { cuts: [], totalDuration: 0, beatCount: 0 };
+ }
+
+ const cutPoints = this.getCutPoints(beatAnalysis, options);
+ const filteredCutPoints = this.filterByMinDuration(
+ cutPoints,
+ options.minClipDuration,
+ );
+
+ const cuts: AutoEditCut[] = [];
+ let currentTime = 0;
+ let sourceIndex = 0;
+
+ for (let i = 0; i < filteredCutPoints.length - 1; i++) {
+ const segmentStart = filteredCutPoints[i];
+ const segmentEnd = filteredCutPoints[i + 1];
+ const segmentDuration = segmentEnd - segmentStart;
+
+ if (segmentDuration > options.maxClipDuration) continue;
+
+ const sourceClip = sourceClips[sourceIndex % sourceClips.length];
+ const availableDuration = sourceClip.outPoint - sourceClip.inPoint;
+ const inPoint =
+ sourceClip.inPoint +
+ ((i * segmentDuration) % Math.max(availableDuration - segmentDuration, segmentDuration));
+
+ cuts.push({
+ sourceClipId: sourceClip.id,
+ inPoint: Math.min(inPoint, sourceClip.outPoint - segmentDuration),
+ outPoint: Math.min(inPoint + segmentDuration, sourceClip.outPoint),
+ startTime: currentTime,
+ duration: segmentDuration,
+ });
+
+ currentTime += segmentDuration;
+ sourceIndex++;
+ }
+
+ return {
+ cuts,
+ totalDuration: currentTime,
+ beatCount: filteredCutPoints.length,
+ };
+ }
+
+ private getCutPoints(
+ beatAnalysis: BeatAnalysisResult,
+ options: AutoEditOptions,
+ ): number[] {
+ switch (options.cutMode) {
+ case "downbeats":
+ return [0, ...beatAnalysis.downbeats].sort((a, b) => a - b);
+
+ case "beats": {
+ const strengthThreshold = 1 - options.sensitivity;
+ const filteredBeats = beatAnalysis.beats.filter(
+ (beat: Beat) => beat.strength >= strengthThreshold,
+ );
+ return [0, ...filteredBeats.map((b: Beat) => b.time)].sort(
+ (a, b) => a - b,
+ );
+ }
+
+ case "segments": {
+ const beatsPerSegment = Math.max(
+ 2,
+ Math.round(4 * (1 - options.sensitivity) + 1),
+ );
+ const points: number[] = [0];
+ for (let i = 0; i < beatAnalysis.beats.length; i += beatsPerSegment) {
+ points.push(beatAnalysis.beats[i].time);
+ }
+ return points;
+ }
+
+ default:
+ return [0, beatAnalysis.duration];
+ }
+ }
+
+ private filterByMinDuration(
+ cutPoints: number[],
+ minDuration: number,
+ ): number[] {
+ if (cutPoints.length <= 1) return cutPoints;
+
+ const filtered: number[] = [cutPoints[0]];
+ for (let i = 1; i < cutPoints.length; i++) {
+ const lastPoint = filtered[filtered.length - 1];
+ if (cutPoints[i] - lastPoint >= minDuration) {
+ filtered.push(cutPoints[i]);
+ }
+ }
+ return filtered;
+ }
+}
+
+let instance: AutoEditService | null = null;
+
+export function getAutoEditService(): AutoEditService {
+ if (!instance) {
+ instance = new AutoEditService();
+ }
+ return instance;
+}
diff --git a/packages/core/src/timeline/index.ts b/packages/core/src/timeline/index.ts
index 6d882de0..0b48f0db 100644
--- a/packages/core/src/timeline/index.ts
+++ b/packages/core/src/timeline/index.ts
@@ -23,6 +23,16 @@ export {
type SnapResult,
} from "./clip-manager";
+export {
+ AutoEditService,
+ getAutoEditService,
+ DEFAULT_AUTO_EDIT_OPTIONS,
+ type AutoEditOptions,
+ type AutoEditCut,
+ type AutoEditResult,
+ type CutMode,
+} from "./auto-edit-service";
+
export {
NestedSequenceEngine,
getNestedSequenceEngine,
diff --git a/packages/core/src/video/index.ts b/packages/core/src/video/index.ts
index eca46be2..d9855c4a 100644
--- a/packages/core/src/video/index.ts
+++ b/packages/core/src/video/index.ts
@@ -8,6 +8,7 @@ export * from "./transform-animator";
export * from "./mask-engine";
export * from "./composite-engine";
export * from "./speed-engine";
+export * from "./speed-presets";
export * from "./keyframe-engine";
export * from "./chroma-key-engine";
export * from "./motion-tracking-engine";
diff --git a/packages/core/src/video/speed-presets.ts b/packages/core/src/video/speed-presets.ts
new file mode 100644
index 00000000..c81fdccf
--- /dev/null
+++ b/packages/core/src/video/speed-presets.ts
@@ -0,0 +1,82 @@
+import type { EasingType } from "../types/timeline";
+
+export interface SpeedCurvePreset {
+ readonly id: string;
+ readonly name: string;
+ readonly description: string;
+ readonly keyframes: ReadonlyArray<{
+ readonly time: number;
+ readonly speed: number;
+ readonly easing: EasingType;
+ }>;
+}
+
+export const SPEED_CURVE_PRESETS: readonly SpeedCurvePreset[] = [
+ {
+ id: "flash",
+ name: "Flash",
+ description: "Quick burst of speed in the middle",
+ keyframes: [
+ { time: 0, speed: 0.5, easing: "easeInQuad" },
+ { time: 0.3, speed: 4, easing: "easeOutQuad" },
+ { time: 0.7, speed: 4, easing: "easeInQuad" },
+ { time: 1, speed: 0.5, easing: "linear" },
+ ],
+ },
+ {
+ id: "smooth-slow-mo",
+ name: "Smooth Slow-Mo",
+ description: "Gradual slow down and speed up",
+ keyframes: [
+ { time: 0, speed: 1, easing: "easeInOutCubic" },
+ { time: 0.3, speed: 0.3, easing: "linear" },
+ { time: 0.7, speed: 0.3, easing: "easeInOutCubic" },
+ { time: 1, speed: 1, easing: "linear" },
+ ],
+ },
+ {
+ id: "jump-cut",
+ name: "Jump Cut",
+ description: "Alternating fast and normal speed",
+ keyframes: [
+ { time: 0, speed: 1, easing: "linear" },
+ { time: 0.2, speed: 3, easing: "linear" },
+ { time: 0.4, speed: 1, easing: "linear" },
+ { time: 0.6, speed: 3, easing: "linear" },
+ { time: 0.8, speed: 1, easing: "linear" },
+ { time: 1, speed: 3, easing: "linear" },
+ ],
+ },
+ {
+ id: "montage",
+ name: "Montage",
+ description: "Gradual acceleration throughout",
+ keyframes: [
+ { time: 0, speed: 1, easing: "easeInQuart" },
+ { time: 0.5, speed: 1.5, easing: "easeInQuart" },
+ { time: 1, speed: 3, easing: "linear" },
+ ],
+ },
+ {
+ id: "hero-moment",
+ name: "Hero Moment",
+ description: "Dramatic slow-down at the peak",
+ keyframes: [
+ { time: 0, speed: 1.5, easing: "easeInCubic" },
+ { time: 0.35, speed: 0.2, easing: "linear" },
+ { time: 0.65, speed: 0.2, easing: "easeOutCubic" },
+ { time: 1, speed: 1.5, easing: "linear" },
+ ],
+ },
+ {
+ id: "bullet-time",
+ name: "Bullet Time",
+ description: "Near freeze in the center",
+ keyframes: [
+ { time: 0, speed: 2, easing: "easeInExpo" },
+ { time: 0.4, speed: 0.1, easing: "linear" },
+ { time: 0.6, speed: 0.1, easing: "easeOutExpo" },
+ { time: 1, speed: 2, easing: "linear" },
+ ],
+ },
+];
diff --git a/packages/core/src/video/video-engine.ts b/packages/core/src/video/video-engine.ts
index 08fa989b..3097b86c 100644
--- a/packages/core/src/video/video-engine.ts
+++ b/packages/core/src/video/video-engine.ts
@@ -37,6 +37,7 @@ import {
import { GPUCompositor, initializeGPUCompositor } from "./gpu-compositor";
import { getRendererFactory, type Renderer } from "./renderer-factory";
import { keyframeEngine } from "./keyframe-engine";
+import { getBackgroundRemovalEngine } from "../ai/background-removal-engine";
import {
type GifFrameCache,
createGifFrameCache,
@@ -573,6 +574,28 @@ export class VideoEngine {
};
let processedBitmap = bitmap;
+
+ const bgEngine = getBackgroundRemovalEngine();
+ if (bgEngine && bgEngine.isInitialized()) {
+ const bgSettings = bgEngine.getSettings(clip.id);
+ if (bgSettings.enabled) {
+ try {
+ const bgResult = await bgEngine.processFrame(
+ clip.id,
+ processedBitmap,
+ processedBitmap.width,
+ processedBitmap.height,
+ );
+ if (bgResult && bgResult !== processedBitmap) {
+ if (processedBitmap !== bitmap) {
+ processedBitmap.close();
+ }
+ processedBitmap = bgResult;
+ }
+ } catch {}
+ }
+ }
+
if (clip.effects && clip.effects.length > 0) {
try {
if (!this.effectsEngine) {
@@ -589,9 +612,12 @@ export class VideoEngine {
await Promise.race([initPromise, timeoutPromise]);
}
const effectsResult = await this.effectsEngine.applyEffects(
- bitmap,
+ processedBitmap,
clip.effects,
);
+ if (processedBitmap !== bitmap) {
+ processedBitmap.close();
+ }
processedBitmap = effectsResult.image;
} catch (error) {
console.warn(