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 clip effects and add adjacent transitions

Augustus Otu0eb122248192
diff --git a/apps/web/src/bridges/transition-bridge.ts b/apps/web/src/bridges/transition-bridge.ts
index 78534693..405af613 100644
--- a/apps/web/src/bridges/transition-bridge.ts
+++ b/apps/web/src/bridges/transition-bridge.ts
@@ -264,6 +264,16 @@ export class TransitionBridge {
return this.trackTransitions.get(trackId) || [];
}
+ setTransitionsForTrack(trackId: string, transitions: Transition[]): void {
+ this.trackTransitions.set(
+ trackId,
+ transitions.map((transition) => ({
+ ...transition,
+ params: { ...transition.params },
+ })),
+ );
+ }
+
/**
* Get transition between two specific clips
*
diff --git a/apps/web/src/components/editor/InspectorPanel.tsx b/apps/web/src/components/editor/InspectorPanel.tsx
index 2cd04466..9a80d078 100644
--- a/apps/web/src/components/editor/InspectorPanel.tsx
+++ b/apps/web/src/components/editor/InspectorPanel.tsx
@@ -1013,7 +1013,7 @@ export const InspectorPanel: React.FC = () => {
clipType === "svg" ||
clipType === "sticker") && (
<Section
- title="Entry/Exit Transitions"
+ title="Transitions"
sectionId="transitions"
defaultOpen={false}
>
diff --git a/apps/web/src/components/editor/inspector/ClipTransitionSection.tsx b/apps/web/src/components/editor/inspector/ClipTransitionSection.tsx
index 19bd786e..99a3fa34 100644
--- a/apps/web/src/components/editor/inspector/ClipTransitionSection.tsx
+++ b/apps/web/src/components/editor/inspector/ClipTransitionSection.tsx
@@ -15,14 +15,17 @@ import {
Droplets,
} from "lucide-react";
import type {
+ Clip as TimelineClip,
Keyframe,
EasingType,
Transform,
GraphicClip,
+ Transition,
} from "@openreel/core";
import { useProjectStore } from "../../../stores/project-store";
import { useEngineStore } from "../../../stores/engine-store";
import { toast } from "../../../stores/notification-store";
+import { TransitionInspector } from "./TransitionInspector";
import {
Select,
SelectTrigger,
@@ -103,6 +106,15 @@ interface CanvasDimensions {
height: number;
}
+interface AdjacentTransitionConfig {
+ key: "incoming" | "outgoing";
+ title: string;
+ description: string;
+ clipA: TimelineClip;
+ clipB: TimelineClip;
+ transition?: Transition;
+}
+
function calculateSlideOffsets(
baseTransform: Transform,
_canvas: CanvasDimensions,
@@ -901,15 +913,60 @@ export const ClipTransitionSection: React.FC<ClipTransitionSectionProps> = ({
getShapeClip,
getSVGClip,
getStickerClip,
+ addClipTransition,
+ updateClipTransition,
+ removeClipTransition,
} = useProjectStore();
const getTitleEngine = useEngineStore((state) => state.getTitleEngine);
const getGraphicsEngine = useEngineStore((state) => state.getGraphicsEngine);
const { settings } = project;
+ const timelineClipContext = useMemo(() => {
+ for (const track of project.timeline.tracks) {
+ const sortedClips = [...track.clips].sort((clipA, clipB) => {
+ if (clipA.startTime !== clipB.startTime) {
+ return clipA.startTime - clipB.startTime;
+ }
+
+ return clipA.id.localeCompare(clipB.id);
+ });
+ const clipIndex = sortedClips.findIndex((candidate) => candidate.id === clipId);
+
+ if (clipIndex === -1) {
+ continue;
+ }
+
+ const currentClip = sortedClips[clipIndex];
+ const previousClip = clipIndex > 0 ? sortedClips[clipIndex - 1] : undefined;
+ const nextClip =
+ clipIndex < sortedClips.length - 1 ? sortedClips[clipIndex + 1] : undefined;
+
+ return {
+ currentClip,
+ previousClip,
+ nextClip,
+ incomingTransition: previousClip
+ ? track.transitions.find(
+ (transition) =>
+ transition.clipAId === previousClip.id &&
+ transition.clipBId === currentClip.id,
+ )
+ : undefined,
+ outgoingTransition: nextClip
+ ? track.transitions.find(
+ (transition) =>
+ transition.clipAId === currentClip.id &&
+ transition.clipBId === nextClip.id,
+ )
+ : undefined,
+ };
+ }
+
+ return null;
+ }, [project.timeline.tracks, clipId]);
+
const clip = useMemo(() => {
- const regularClip = project.timeline.tracks
- .flatMap((t) => t.clips)
- .find((c) => c.id === clipId);
+ const regularClip = timelineClipContext?.currentClip;
if (regularClip)
return { type: "regular" as const, data: regularClip as ClipLike };
@@ -929,7 +986,7 @@ export const ClipTransitionSection: React.FC<ClipTransitionSectionProps> = ({
return null;
}, [
- project.timeline.tracks,
+ timelineClipContext,
clipId,
getTextClip,
getShapeClip,
@@ -939,6 +996,59 @@ export const ClipTransitionSection: React.FC<ClipTransitionSectionProps> = ({
project.modifiedAt,
]);
+ const adjacentTransitions = useMemo<AdjacentTransitionConfig[]>(() => {
+ if (!timelineClipContext) {
+ return [];
+ }
+
+ const transitions: AdjacentTransitionConfig[] = [];
+
+ if (timelineClipContext.previousClip) {
+ transitions.push({
+ key: "incoming",
+ title: "Incoming Transition",
+ description: "From the previous clip into this clip",
+ clipA: timelineClipContext.previousClip,
+ clipB: timelineClipContext.currentClip,
+ transition: timelineClipContext.incomingTransition,
+ });
+ }
+
+ if (timelineClipContext.nextClip) {
+ transitions.push({
+ key: "outgoing",
+ title: "Outgoing Transition",
+ description: "From this clip into the next clip",
+ clipA: timelineClipContext.currentClip,
+ clipB: timelineClipContext.nextClip,
+ transition: timelineClipContext.outgoingTransition,
+ });
+ }
+
+ return transitions;
+ }, [timelineClipContext]);
+
+ const handleTransitionCreate = useCallback(
+ (transition: Transition) => {
+ addClipTransition(transition);
+ },
+ [addClipTransition],
+ );
+
+ const handleTransitionUpdate = useCallback(
+ (transitionId: string, updates: Partial<Transition>) => {
+ updateClipTransition(transitionId, updates);
+ },
+ [updateClipTransition],
+ );
+
+ const handleTransitionRemove = useCallback(
+ (transitionId: string) => {
+ removeClipTransition(transitionId);
+ },
+ [removeClipTransition],
+ );
+
const detected = clip
? detectCurrentTransitions(clip.data)
: {
@@ -1166,8 +1276,51 @@ export const ClipTransitionSection: React.FC<ClipTransitionSectionProps> = ({
onClick={applyTransitions}
className="w-full py-2 bg-primary hover:bg-primary-hover text-white font-medium rounded-lg text-[11px] transition-all"
>
- Apply Transitions
+ Apply Entry/Exit Animations
</button>
+
+ <div className="space-y-3 border-t border-border pt-3">
+ <span className="text-[10px] font-medium text-text-secondary uppercase tracking-wider">
+ Clip-to-Clip Transitions
+ </span>
+
+ {timelineClipContext ? (
+ adjacentTransitions.length > 0 ? (
+ adjacentTransitions.map((adjacentTransition) => (
+ <div
+ key={adjacentTransition.key}
+ className="space-y-2 rounded-lg border border-border bg-background-secondary p-3"
+ >
+ <div className="space-y-1">
+ <p className="text-[10px] font-medium text-text-primary">
+ {adjacentTransition.title}
+ </p>
+ <p className="text-[9px] text-text-muted">
+ {adjacentTransition.description}
+ </p>
+ </div>
+
+ <TransitionInspector
+ clipA={adjacentTransition.clipA}
+ clipB={adjacentTransition.clipB}
+ transition={adjacentTransition.transition}
+ onTransitionCreate={handleTransitionCreate}
+ onTransitionUpdate={handleTransitionUpdate}
+ onTransitionRemove={handleTransitionRemove}
+ />
+ </div>
+ ))
+ ) : (
+ <p className="text-[10px] text-text-muted">
+ No adjacent clips are available on this track.
+ </p>
+ )
+ ) : (
+ <p className="text-[10px] text-text-muted">
+ Clip-to-clip transitions are available for timeline media clips.
+ </p>
+ )}
+ </div>
</div>
);
};
diff --git a/apps/web/src/components/editor/inspector/TransitionInspector.tsx b/apps/web/src/components/editor/inspector/TransitionInspector.tsx
index 5d5d426c..73863629 100644
--- a/apps/web/src/components/editor/inspector/TransitionInspector.tsx
+++ b/apps/web/src/components/editor/inspector/TransitionInspector.tsx
@@ -1,4 +1,4 @@
-import React, { useCallback, useMemo, useState } from "react";
+import React, { useCallback, useEffect, useMemo, useState } from "react";
import {
ArrowRight,
ArrowLeft,
@@ -259,6 +259,13 @@ export const TransitionInspector: React.FC<TransitionInspectorProps> = ({
transition?.params || bridge.getDefaultParams(selectedType),
);
+ useEffect(() => {
+ const nextType = transition?.type || "crossfade";
+ setSelectedType(nextType);
+ setDuration(transition?.duration || 1.0);
+ setParams(transition?.params || bridge.getDefaultParams(nextType));
+ }, [bridge, clipA.id, clipB.id, transition]);
+
// Validate transition
const validation = useMemo(() => {
if (!bridge.isInitialized()) {
diff --git a/apps/web/src/stores/project-store.test.ts b/apps/web/src/stores/project-store.test.ts
index 4972b02e..2de8428e 100644
--- a/apps/web/src/stores/project-store.test.ts
+++ b/apps/web/src/stores/project-store.test.ts
@@ -1,6 +1,108 @@
import { describe, it, expect, beforeEach, vi } from "vitest";
import { useProjectStore } from "./project-store";
-import type { Project, Clip, MediaItem } from "@openreel/core";
+import type { Project, Clip, MediaItem, Transition } from "@openreel/core";
+
+const {
+ mockEffectsBridge,
+ mockEffectsBridgeState,
+ mockTransitionBridge,
+ mockTransitionBridgeState,
+} = vi.hoisted(() => {
+ const clipEffects = new Map<string, Array<{
+ id: string;
+ type: string;
+ enabled: boolean;
+ params: Record<string, unknown>;
+ order: number;
+ }>>();
+
+ const getDefaultParams = (effectType: string): Record<string, unknown> => {
+ switch (effectType) {
+ case "brightness":
+ return { value: 0 };
+ case "contrast":
+ return { value: 1 };
+ case "saturation":
+ return { value: 1 };
+ case "blur":
+ return { radius: 0, type: "gaussian" };
+ default:
+ return {};
+ }
+ };
+
+ const effectsBridge = {
+ isInitialized: vi.fn(() => true),
+ applyVideoEffect: vi.fn(
+ (clipId: string, effectType: string, params: Record<string, unknown> = {}) => {
+ const effects = clipEffects.get(clipId) || [];
+ const effect = {
+ id: `effect-${effects.length + 1}`,
+ type: effectType,
+ enabled: true,
+ params: { ...getDefaultParams(effectType), ...params },
+ order: effects.length,
+ };
+ clipEffects.set(clipId, [...effects, effect]);
+ return { success: true, effectId: effect.id };
+ },
+ ),
+ getEffects: vi.fn((clipId: string) => [...(clipEffects.get(clipId) || [])]),
+ getEffect: vi.fn((clipId: string, effectId: string) =>
+ (clipEffects.get(clipId) || []).find((effect) => effect.id === effectId),
+ ),
+ deserializeEffects: vi.fn(
+ (
+ clipId: string,
+ data: {
+ effects: Array<{
+ id: string;
+ type: string;
+ enabled: boolean;
+ params: Record<string, unknown>;
+ order: number;
+ }>;
+ },
+ ) => {
+ clipEffects.set(
+ clipId,
+ data.effects.map((effect) => ({ ...effect })),
+ );
+ return { success: true };
+ },
+ ),
+ clearEffects: vi.fn((clipId: string) => {
+ clipEffects.delete(clipId);
+ }),
+ getColorGrading: vi.fn(() => ({})),
+ };
+
+ const trackTransitions = new Map<string, Transition[]>();
+ const transitionBridge = {
+ isInitialized: vi.fn(() => true),
+ setTransitionsForTrack: vi.fn(
+ (trackId: string, transitions: Transition[]) => {
+ trackTransitions.set(
+ trackId,
+ transitions.map((transition) => ({
+ ...transition,
+ params: { ...transition.params },
+ })),
+ );
+ },
+ ),
+ clearTransitionsForTrack: vi.fn((trackId: string) => {
+ trackTransitions.delete(trackId);
+ }),
+ };
+
+ return {
+ mockEffectsBridge: effectsBridge,
+ mockEffectsBridgeState: { clipEffects },
+ mockTransitionBridge: transitionBridge,
+ mockTransitionBridgeState: { trackTransitions },
+ };
+});
vi.mock("../services/auto-save", () => ({
autoSaveManager: {
@@ -33,8 +135,18 @@ vi.mock("../bridges/media-bridge", () => ({
initializeMediaBridge: vi.fn().mockResolvedValue(undefined),
}));
+vi.mock("../bridges/effects-bridge", () => ({
+ getEffectsBridge: vi.fn(() => mockEffectsBridge),
+}));
+
+vi.mock("../bridges/transition-bridge", () => ({
+ getTransitionBridge: vi.fn(() => mockTransitionBridge),
+}));
+
describe("ProjectStore", () => {
beforeEach(() => {
+ mockEffectsBridgeState.clipEffects.clear();
+ mockTransitionBridgeState.trackTransitions.clear();
useProjectStore.getState().createNewProject();
});
@@ -496,6 +608,256 @@ describe("ProjectStore", () => {
});
});
+ describe("video effects", () => {
+ const createProjectWithVideoClip = (): Project => ({
+ id: "effects-project",
+ name: "Effects Project",
+ createdAt: Date.now(),
+ modifiedAt: Date.now(),
+ settings: {
+ width: 1920,
+ height: 1080,
+ frameRate: 30,
+ sampleRate: 48000,
+ channels: 2,
+ },
+ mediaLibrary: { items: [] },
+ timeline: {
+ tracks: [
+ {
+ id: "video-track-1",
+ type: "video",
+ name: "Video",
+ clips: [
+ {
+ id: "video-clip-1",
+ mediaId: "video-media-1",
+ trackId: "video-track-1",
+ startTime: 0,
+ duration: 8,
+ inPoint: 0,
+ outPoint: 8,
+ effects: [],
+ audioEffects: [],
+ transform: {
+ position: { x: 0.5, y: 0.5 },
+ scale: { x: 1, y: 1 },
+ rotation: 0,
+ anchor: { x: 0.5, y: 0.5 },
+ opacity: 1,
+ },
+ volume: 1,
+ keyframes: [],
+ },
+ ],
+ transitions: [],
+ locked: false,
+ hidden: false,
+ muted: false,
+ solo: false,
+ },
+ ],
+ subtitles: [],
+ duration: 8,
+ markers: [],
+ },
+ });
+
+ it("should persist video effects to the clip timeline state", () => {
+ useProjectStore.getState().loadProject(createProjectWithVideoClip());
+
+ const addedEffect = useProjectStore
+ .getState()
+ .addVideoEffect("video-clip-1", "brightness", { value: 15 });
+
+ expect(addedEffect).not.toBeNull();
+ expect(useProjectStore.getState().getClip("video-clip-1")?.effects).toEqual([
+ {
+ id: addedEffect!.id,
+ type: "brightness",
+ enabled: true,
+ params: { value: 15 },
+ },
+ ]);
+ expect(useProjectStore.getState().getVideoEffects("video-clip-1")).toHaveLength(1);
+ });
+
+ it("should keep clip effects synchronized across update, toggle, reorder, and remove", () => {
+ useProjectStore.getState().loadProject(createProjectWithVideoClip());
+
+ const brightness = useProjectStore
+ .getState()
+ .addVideoEffect("video-clip-1", "brightness", { value: 10 });
+ const contrast = useProjectStore
+ .getState()
+ .addVideoEffect("video-clip-1", "contrast", { value: 1.2 });
+
+ expect(brightness).not.toBeNull();
+ expect(contrast).not.toBeNull();
+
+ const updated = useProjectStore
+ .getState()
+ .updateVideoEffect("video-clip-1", brightness!.id, { value: 20 });
+ const toggled = useProjectStore
+ .getState()
+ .toggleVideoEffect("video-clip-1", brightness!.id, false);
+ const reordered = useProjectStore
+ .getState()
+ .reorderVideoEffects("video-clip-1", [contrast!.id, brightness!.id]);
+ const removed = useProjectStore
+ .getState()
+ .removeVideoEffect("video-clip-1", contrast!.id);
+
+ expect(updated?.params).toEqual({ value: 20 });
+ expect(toggled?.enabled).toBe(false);
+ expect(reordered).toBe(true);
+ expect(removed).toBe(true);
+ expect(useProjectStore.getState().getClip("video-clip-1")?.effects).toEqual([
+ {
+ id: brightness!.id,
+ type: "brightness",
+ enabled: false,
+ params: { value: 20 },
+ },
+ ]);
+ });
+ });
+
+ describe("clip transitions", () => {
+ const createProjectWithAdjacentClips = (): Project => ({
+ id: "transition-project",
+ name: "Transition Project",
+ createdAt: Date.now(),
+ modifiedAt: Date.now(),
+ settings: {
+ width: 1920,
+ height: 1080,
+ frameRate: 30,
+ sampleRate: 48000,
+ channels: 2,
+ },
+ mediaLibrary: { items: [] },
+ timeline: {
+ tracks: [
+ {
+ id: "video-track-1",
+ type: "video",
+ name: "Video",
+ clips: [
+ {
+ id: "clip-a",
+ mediaId: "video-a",
+ trackId: "video-track-1",
+ startTime: 0,
+ duration: 4,
+ inPoint: 0,
+ outPoint: 4,
+ effects: [],
+ audioEffects: [],
+ transform: {
+ position: { x: 0.5, y: 0.5 },
+ scale: { x: 1, y: 1 },
+ rotation: 0,
+ anchor: { x: 0.5, y: 0.5 },
+ opacity: 1,
+ },
+ volume: 1,
+ keyframes: [],
+ },
+ {
+ id: "clip-b",
+ mediaId: "video-b",
+ trackId: "video-track-1",
+ startTime: 4,
+ duration: 4,
+ inPoint: 0,
+ outPoint: 4,
+ effects: [],
+ audioEffects: [],
+ transform: {
+ position: { x: 0.5, y: 0.5 },
+ scale: { x: 1, y: 1 },
+ rotation: 0,
+ anchor: { x: 0.5, y: 0.5 },
+ opacity: 1,
+ },
+ volume: 1,
+ keyframes: [],
+ },
+ ],
+ transitions: [],
+ locked: false,
+ hidden: false,
+ muted: false,
+ solo: false,
+ },
+ ],
+ subtitles: [],
+ duration: 8,
+ markers: [],
+ },
+ });
+
+ it("should persist adjacent clip transitions and mirror them into the transition bridge", () => {
+ useProjectStore.getState().loadProject(createProjectWithAdjacentClips());
+
+ const transition: Transition = {
+ id: "transition-1",
+ clipAId: "clip-a",
+ clipBId: "clip-b",
+ type: "crossfade",
+ duration: 0.5,
+ params: { curve: "ease" },
+ };
+
+ const addedTransition = useProjectStore
+ .getState()
+ .addClipTransition(transition);
+ const updatedTransition = useProjectStore
+ .getState()
+ .updateClipTransition("transition-1", {
+ duration: 0.75,
+ params: { curve: "linear" },
+ });
+
+ expect(addedTransition).toEqual(transition);
+ expect(useProjectStore.getState().getClipTransitionBetweenClips("clip-a", "clip-b")).toEqual({
+ id: "transition-1",
+ clipAId: "clip-a",
+ clipBId: "clip-b",
+ type: "crossfade",
+ duration: 0.75,
+ params: { curve: "linear" },
+ });
+ expect(updatedTransition).toEqual({
+ id: "transition-1",
+ clipAId: "clip-a",
+ clipBId: "clip-b",
+ type: "crossfade",
+ duration: 0.75,
+ params: { curve: "linear" },
+ });
+ expect(mockTransitionBridgeState.trackTransitions.get("video-track-1")).toEqual([
+ {
+ id: "transition-1",
+ clipAId: "clip-a",
+ clipBId: "clip-b",
+ type: "crossfade",
+ duration: 0.75,
+ params: { curve: "linear" },
+ },
+ ]);
+
+ const removedTransition = useProjectStore
+ .getState()
+ .removeClipTransition("transition-1");
+
+ expect(removedTransition).toBe(true);
+ expect(useProjectStore.getState().getClipTransition("transition-1")).toBeUndefined();
+ expect(mockTransitionBridgeState.trackTransitions.get("video-track-1")).toEqual([]);
+ });
+ });
+
describe("marker operations", () => {
it("should add a marker", () => {
useProjectStore.getState().addMarker(5, "Scene 1", "#ff0000");
diff --git a/apps/web/src/stores/project-store.ts b/apps/web/src/stores/project-store.ts
index 9b4d125c..6a3c1121 100644
--- a/apps/web/src/stores/project-store.ts
+++ b/apps/web/src/stores/project-store.ts
@@ -6,6 +6,7 @@ import type {
MediaItem,
Track,
Clip,
+ Transition,
Action,
ActionResult,
TextClip,
@@ -37,6 +38,7 @@ import type {
ColorGradingSettings,
} from "../bridges/effects-bridge";
import { getEffectsBridge } from "../bridges/effects-bridge";
+import { getTransitionBridge } from "../bridges/transition-bridge";
import {
autoSaveManager,
initializeAutoSave,
@@ -165,6 +167,17 @@ export interface ProjectState {
trimStart: boolean,
) => Promise<ActionResult>;
getClip: (clipId: string) => Clip | undefined;
+ addClipTransition: (transition: Transition) => Transition | null;
+ updateClipTransition: (
+ transitionId: string,
+ updates: Partial<Pick<Transition, "type" | "duration" | "params">>,
+ ) => Transition | null;
+ removeClipTransition: (transitionId: string) => boolean;
+ getClipTransition: (transitionId: string) => Transition | undefined;
+ getClipTransitionBetweenClips: (
+ clipAId: string,
+ clipBId: string,
+ ) => Transition | undefined;
separateAudio: (clipId: string) => Promise<ActionResult>;
updateClipTransform: (
clipId: string,
@@ -421,6 +434,177 @@ export const useProjectStore = create<ProjectState>()(
const actionHistory = new ActionHistory();
const actionExecutor = new ActionExecutor(actionHistory);
+ const getProjectClipIds = (project: Project): string[] =>
+ project.timeline.tracks.flatMap((track) =>
+ track.clips.map((clip) => clip.id),
+ );
+
+ const mapClipEffectsToVideoEffects = (effects: Effect[]): VideoEffect[] =>
+ effects.map((effect, order) => ({
+ id: effect.id,
+ type: effect.type as VideoEffectType,
+ enabled: effect.enabled,
+ params: effect.params,
+ order,
+ }));
+
+ const updateProjectClip = (
+ project: Project,
+ clipId: string,
+ updater: (clip: Clip) => Clip,
+ ): Project | null => {
+ let hasUpdatedClip = false;
+
+ const updatedTracks = project.timeline.tracks.map((track) => {
+ let trackUpdated = false;
+
+ const updatedClips = track.clips.map((clip) => {
+ if (clip.id !== clipId) {
+ return clip;
+ }
+
+ hasUpdatedClip = true;
+ trackUpdated = true;
+ return updater(clip);
+ });
+
+ return trackUpdated ? { ...track, clips: updatedClips } : track;
+ });
+
+ if (!hasUpdatedClip) {
+ return null;
+ }
+
+ return {
+ ...project,
+ timeline: { ...project.timeline, tracks: updatedTracks },
+ modifiedAt: Date.now(),
+ };
+ };
+
+ const buildSerializedColorGrading = (clipId: string) => {
+ const effectsBridge = getEffectsBridge();
+ if (!effectsBridge.isInitialized()) {
+ return {};
+ }
+
+ const colorGrading = effectsBridge.getColorGrading(clipId);
+
+ return {
+ ...(colorGrading.colorWheels
+ ? { colorWheels: colorGrading.colorWheels }
+ : {}),
+ ...(colorGrading.curves ? { curves: colorGrading.curves } : {}),
+ ...(colorGrading.lut
+ ? {
+ lut: {
+ data: Array.from(colorGrading.lut.data),
+ size: colorGrading.lut.size,
+ intensity: colorGrading.lut.intensity,
+ },
+ }
+ : {}),
+ ...(colorGrading.hsl ? { hsl: colorGrading.hsl } : {}),
+ };
+ };
+
+ const syncClipEffectsBridge = (project: Project, clipId: string): void => {
+ const effectsBridge = getEffectsBridge();
+ if (!effectsBridge.isInitialized()) {
+ return;
+ }
+
+ const clip = project.timeline.tracks
+ .flatMap((track) => track.clips)
+ .find((candidate) => candidate.id === clipId);
+
+ if (!clip) {
+ effectsBridge.clearEffects(clipId);
+ return;
+ }
+
+ const effects = mapClipEffectsToVideoEffects(clip.effects);
+ effectsBridge.deserializeEffects(clipId, {
+ effects: effects.map((effect) => ({
+ id: effect.id,
+ type: effect.type,
+ enabled: effect.enabled,
+ params: effect.params,
+ order: effect.order,
+ })),
+ colorGrading: buildSerializedColorGrading(clipId),
+ });
+ };
+
+ const syncProjectEffectsBridge = (
+ nextProject: Project,
+ previousProject?: Project,
+ ): void => {
+ const effectsBridge = getEffectsBridge();
+ if (!effectsBridge.isInitialized()) {
+ return;
+ }
+
+ const nextClipIds = new Set(getProjectClipIds(nextProject));
+
+ for (const clipId of previousProject ? getProjectClipIds(previousProject) : []) {
+ if (!nextClipIds.has(clipId)) {
+ effectsBridge.clearEffects(clipId);
+ }
+ }
+
+ for (const clipId of nextClipIds) {
+ syncClipEffectsBridge(nextProject, clipId);
+ }
+ };
+
+ const syncTrackTransitionsBridge = (
+ project: Project,
+ trackId: string,
+ ): void => {
+ const transitionBridge = getTransitionBridge();
+ if (!transitionBridge.isInitialized()) {
+ return;
+ }
+
+ const track = project.timeline.tracks.find(
+ (candidate) => candidate.id === trackId,
+ );
+
+ if (!track) {
+ transitionBridge.clearTransitionsForTrack(trackId);
+ return;
+ }
+
+ transitionBridge.setTransitionsForTrack(trackId, track.transitions);
+ };
+
+ const syncProjectTransitionsBridge = (
+ nextProject: Project,
+ previousProject?: Project,
+ ): void => {
+ const transitionBridge = getTransitionBridge();
+ if (!transitionBridge.isInitialized()) {
+ return;
+ }
+
+ const nextTrackIds = new Set(
+ nextProject.timeline.tracks.map((track) => track.id),
+ );
+
+ for (const trackId of previousProject
+ ? previousProject.timeline.tracks.map((track) => track.id)
+ : []) {
+ if (!nextTrackIds.has(trackId)) {
+ transitionBridge.clearTransitionsForTrack(trackId);
+ }
+ }
+
+ for (const track of nextProject.timeline.tracks) {
+ syncTrackTransitionsBridge(nextProject, track.id);
+ }
+ };
+
return {
// Initial state - create empty project (Requirement 1.1)
project: createEmptyProject(),
@@ -440,8 +624,14 @@ export const useProjectStore = create<ProjectState>()(
) => {
const newHistory = new ActionHistory();
const newExecutor = new ActionExecutor(newHistory);
+ const previousProject = get().project;
+ const nextProject = createEmptyProject(name, settings);
+
+ syncProjectEffectsBridge(nextProject, previousProject);
+ syncProjectTransitionsBridge(nextProject, previousProject);
+
set({
- project: createEmptyProject(name, settings),
+ project: nextProject,
actionHistory: newHistory,
actionExecutor: newExecutor,
clipUndoStack: [],
@@ -451,6 +641,7 @@ export const useProjectStore = create<ProjectState>()(
},
loadProject: (project: Project) => {
+ const previousProject = get().project;
const titleEngine = useEngineStore.getState().getTitleEngine();
const graphicsEngine = useEngineStore.getState().getGraphicsEngine();
@@ -479,6 +670,9 @@ export const useProjectStore = create<ProjectState>()(
? { ...project, timeline: { ...project.timeline, duration: computedDuration } }
: project;
+ syncProjectEffectsBridge(fixedProject, previousProject);
+ syncProjectTransitionsBridge(fixedProject, previousProject);
+
set({
project: fixedProject,
actionHistory: newHistory,
@@ -1613,6 +1807,170 @@ export const useProjectStore = create<ProjectState>()(
return undefined;
},
+ addClipTransition: (transition: Transition) => {
+ const { project } = get();
+ const clip = project.timeline.tracks
+ .flatMap((track) => track.clips)
+ .find((candidate) => candidate.id === transition.clipAId);
+
+ if (!clip) {
+ return null;
+ }
+
+ const track = project.timeline.tracks.find(
+ (candidate) => candidate.id === clip.trackId,
+ );
+ if (!track) {
+ return null;
+ }
+
+ const updatedTrack = {
+ ...track,
+ transitions: [
+ ...track.transitions.filter(
+ (candidate) =>
+ candidate.id !== transition.id &&
+ !(
+ candidate.clipAId === transition.clipAId &&
+ candidate.clipBId === transition.clipBId
+ ),
+ ),
+ transition,
+ ],
+ };
+
+ const updatedProject = {
+ ...project,
+ timeline: {
+ ...project.timeline,
+ tracks: project.timeline.tracks.map((candidate) =>
+ candidate.id === track.id ? updatedTrack : candidate,
+ ),
+ },
+ modifiedAt: Date.now(),
+ };
+
+ syncTrackTransitionsBridge(updatedProject, track.id);
+ set({ project: updatedProject });
+
+ return transition;
+ },
+
+ updateClipTransition: (
+ transitionId: string,
+ updates: Partial<Pick<Transition, "type" | "duration" | "params">>,
+ ) => {
+ const { project } = get();
+ let updatedTrackId: string | null = null;
+ let updatedTransition: Transition | null = null;
+
+ const updatedTracks = project.timeline.tracks.map((track) => {
+ let trackUpdated = false;
+
+ const updatedTransitions = track.transitions.map((transition) => {
+ if (transition.id !== transitionId) {
+ return transition;
+ }
+
+ trackUpdated = true;
+ updatedTrackId = track.id;
+ updatedTransition = {
+ ...transition,
+ ...(updates.type !== undefined ? { type: updates.type } : {}),
+ ...(updates.duration !== undefined
+ ? { duration: updates.duration }
+ : {}),
+ ...(updates.params !== undefined
+ ? { params: { ...transition.params, ...updates.params } }
+ : {}),
+ };
+ return updatedTransition;
+ });
+
+ return trackUpdated
+ ? { ...track, transitions: updatedTransitions }
+ : track;
+ });
+
+ if (!updatedTransition || !updatedTrackId) {
+ return null;
+ }
+
+ const updatedProject = {
+ ...project,
+ timeline: { ...project.timeline, tracks: updatedTracks },
+ modifiedAt: Date.now(),
+ };
+
+ syncTrackTransitionsBridge(updatedProject, updatedTrackId);
+ set({ project: updatedProject });
+
+ return updatedTransition;
+ },
+
+ removeClipTransition: (transitionId: string) => {
+ const { project } = get();
+ let updatedTrackId: string | null = null;
+ let hasRemovedTransition = false;
+
+ const updatedTracks = project.timeline.tracks.map((track) => {
+ const updatedTransitions = track.transitions.filter((transition) => {
+ const shouldKeep = transition.id !== transitionId;
+ if (!shouldKeep) {
+ updatedTrackId = track.id;
+ hasRemovedTransition = true;
+ }
+ return shouldKeep;
+ });
+
+ return updatedTransitions.length !== track.transitions.length
+ ? { ...track, transitions: updatedTransitions }
+ : track;
+ });
+
+ if (!hasRemovedTransition || !updatedTrackId) {
+ return false;
+ }
+
+ const updatedProject = {
+ ...project,
+ timeline: { ...project.timeline, tracks: updatedTracks },
+ modifiedAt: Date.now(),
+ };
+
+ syncTrackTransitionsBridge(updatedProject, updatedTrackId);
+ set({ project: updatedProject });
+
+ return true;
+ },
+
+ getClipTransition: (transitionId: string) => {
+ const { project } = get();
+ for (const track of project.timeline.tracks) {
+ const transition = track.transitions.find(
+ (candidate) => candidate.id === transitionId,
+ );
+ if (transition) {
+ return transition;
+ }
+ }
+ return undefined;
+ },
+
+ getClipTransitionBetweenClips: (clipAId: string, clipBId: string) => {
+ const { project } = get();
+ for (const track of project.timeline.tracks) {
+ const transition = track.transitions.find(
+ (candidate) =>
+ candidate.clipAId === clipAId && candidate.clipBId === clipBId,
+ );
+ if (transition) {
+ return transition;
+ }
+ }
+ return undefined;
+ },
+
copyClips: (clipIds: string[]) => {
const { getClip } = get();
const clips = clipIds
@@ -3792,6 +4150,7 @@ export const useProjectStore = create<ProjectState>()(
effectType: VideoEffectType,
params?: Record<string, unknown>,
) => {
+ const { project } = get();
const effectsBridge = getEffectsBridge();
if (!effectsBridge.isInitialized()) {
console.error("EffectsBridge not initialized");
@@ -3810,8 +4169,27 @@ export const useProjectStore = create<ProjectState>()(
const effect = effectsBridge.getEffect(clipId, result.effectId);
if (effect) {
- // Trigger re-render by updating project state
- set({ project: { ...get().project, modifiedAt: Date.now() } });
+ const updatedProject = updateProjectClip(project, clipId, (clip) => ({
+ ...clip,
+ effects: [
+ ...clip.effects,
+ {
+ id: effect.id,
+ type: effect.type,
+ enabled: effect.enabled,
+ params: effect.params,
+ },
+ ],
+ }));
+
+ if (!updatedProject) {
+ console.error("Failed to persist video effect: clip not found");
+ effectsBridge.removeVideoEffect(clipId, effect.id);
+ return null;
+ }
+
+ syncClipEffectsBridge(updatedProject, clipId);
+ set({ project: updatedProject });
}
return effect || null;
},
@@ -3825,49 +4203,33 @@ export const useProjectStore = create<ProjectState>()(
effectId: string,
params: Record<string, unknown>,
) => {
- const effectsBridge = getEffectsBridge();
- if (!effectsBridge.isInitialized()) {
- console.error("EffectsBridge not initialized");
- return null;
- }
+ const { project } = get();
+ let hasUpdatedEffect = false;
- const result = effectsBridge.updateVideoEffect(
- clipId,
- effectId,
- params,
- );
- if (!result.success) {
- console.error("Failed to update video effect:", result.error);
+ const updatedProject = updateProjectClip(project, clipId, (clip) => ({
+ ...clip,
+ effects: clip.effects.map((effect) => {
+ if (effect.id !== effectId) {
+ return effect;
+ }
+
+ hasUpdatedEffect = true;
+ return {
+ ...effect,
+ params: { ...effect.params, ...params },
+ };
+ }),
+ }));
+
+ if (!updatedProject || !hasUpdatedEffect) {
+ console.error("Failed to update video effect: effect not found");
return null;
}
- const effect = effectsBridge.getEffect(clipId, effectId);
- if (effect) {
- const { project } = get();
- const updatedTracks = project.timeline.tracks.map((track) => ({
- ...track,
- clips: track.clips.map((clip) => {
- if (clip.id === clipId) {
- const updatedEffects = clip.effects.map((e) =>
- e.id === effectId
- ? { ...e, params: { ...e.params, ...params } }
- : e,
- );
- return { ...clip, effects: updatedEffects };
- }
- return clip;
- }),
- }));
+ syncClipEffectsBridge(updatedProject, clipId);
+ set({ project: updatedProject });
- set({
- project: {
- ...project,
- timeline: { ...project.timeline, tracks: updatedTracks },
- modifiedAt: Date.now(),
- },
- });
- }
- return effect || null;
+ return getEffectsBridge().getEffect(clipId, effectId) || null;
},
/**
@@ -3875,20 +4237,27 @@ export const useProjectStore = create<ProjectState>()(
* Restore clip to previous state when effect removed
*/
removeVideoEffect: (clipId: string, effectId: string) => {
- const effectsBridge = getEffectsBridge();
- if (!effectsBridge.isInitialized()) {
- console.error("EffectsBridge not initialized");
- return false;
- }
+ const { project } = get();
+ let hasRemovedEffect = false;
+
+ const updatedProject = updateProjectClip(project, clipId, (clip) => ({
+ ...clip,
+ effects: clip.effects.filter((effect) => {
+ const shouldKeep = effect.id !== effectId;
+ if (!shouldKeep) {
+ hasRemovedEffect = true;
+ }
+ return shouldKeep;
+ }),
+ }));
- const result = effectsBridge.removeVideoEffect(clipId, effectId);
- if (!result.success) {
- console.error("Failed to remove video effect:", result.error);
+ if (!updatedProject || !hasRemovedEffect) {
+ console.error("Failed to remove video effect: effect not found");
return false;
}
- // Trigger re-render by updating project state
- set({ project: { ...get().project, modifiedAt: Date.now() } });
+ syncClipEffectsBridge(updatedProject, clipId);
+ set({ project: updatedProject });
return true;
},
@@ -3897,20 +4266,36 @@ export const useProjectStore = create<ProjectState>()(
* Update effect order in clip's effect list
*/
reorderVideoEffects: (clipId: string, effectIds: string[]) => {
- const effectsBridge = getEffectsBridge();
- if (!effectsBridge.isInitialized()) {
- console.error("EffectsBridge not initialized");
+ const { project, getClip } = get();
+ const clip = getClip(clipId);
+ if (!clip) {
+ console.error("Failed to reorder video effects: clip not found");
return false;
}
- const result = effectsBridge.reorderEffects(clipId, effectIds);
- if (!result.success) {
- console.error("Failed to reorder video effects:", result.error);
+ const effectMap = new Map(clip.effects.map((effect) => [effect.id, effect]));
+ const reorderedIds = new Set(effectIds);
+ if (
+ effectIds.length !== clip.effects.length ||
+ reorderedIds.size !== clip.effects.length ||
+ effectIds.some((effectId) => !effectMap.has(effectId))
+ ) {
+ console.error("Failed to reorder video effects: invalid effect order");
return false;
}
- // Trigger re-render by updating project state
- set({ project: { ...get().project, modifiedAt: Date.now() } });
+ const updatedProject = updateProjectClip(project, clipId, (currentClip) => ({
+ ...currentClip,
+ effects: effectIds.map((effectId) => effectMap.get(effectId)!),
+ }));
+
+ if (!updatedProject) {
+ console.error("Failed to reorder video effects: clip not found");
+ return false;
+ }
+
+ syncClipEffectsBridge(updatedProject, clipId);
+ set({ project: updatedProject });
return true;
},
@@ -3923,46 +4308,65 @@ export const useProjectStore = create<ProjectState>()(
effectId: string,
enabled: boolean,
) => {
- const effectsBridge = getEffectsBridge();
- if (!effectsBridge.isInitialized()) {
- console.error("EffectsBridge not initialized");
- return null;
- }
+ const { project } = get();
+ let hasToggledEffect = false;
- const result = effectsBridge.toggleEffect(clipId, effectId, enabled);
- if (!result.success) {
- console.error("Failed to toggle video effect:", result.error);
+ const updatedProject = updateProjectClip(project, clipId, (clip) => ({
+ ...clip,
+ effects: clip.effects.map((effect) => {
+ if (effect.id !== effectId) {
+ return effect;
+ }
+
+ hasToggledEffect = true;
+ return { ...effect, enabled };
+ }),
+ }));
+
+ if (!updatedProject || !hasToggledEffect) {
+ console.error("Failed to toggle video effect: effect not found");
return null;
}
- const effect = effectsBridge.getEffect(clipId, effectId);
- if (effect) {
- // Trigger re-render by updating project state
- set({ project: { ...get().project, modifiedAt: Date.now() } });
- }
- return effect || null;
+ syncClipEffectsBridge(updatedProject, clipId);
+ set({ project: updatedProject });
+
+ return getEffectsBridge().getEffect(clipId, effectId) || null;
},
/**
* Get all video effects for a clip
*/
getVideoEffects: (clipId: string) => {
+ const { project } = get();
+ const clip = project.timeline.tracks
+ .flatMap((track) => track.clips)
+ .find((candidate) => candidate.id === clipId);
+ const timelineEffects = clip
+ ? mapClipEffectsToVideoEffects(clip.effects)
+ : [];
+
const effectsBridge = getEffectsBridge();
if (!effectsBridge.isInitialized()) {
- return [];
+ return timelineEffects;
+ }
+
+ const bridgeEffects = effectsBridge.getEffects(clipId);
+ if (bridgeEffects.length === 0 && timelineEffects.length > 0) {
+ syncClipEffectsBridge(project, clipId);
+ return effectsBridge.getEffects(clipId);
}
- return effectsBridge.getEffects(clipId);
+
+ return bridgeEffects.length > 0 ? bridgeEffects : timelineEffects;
},
/**
* Get a specific video effect by ID
*/
getVideoEffect: (clipId: string, effectId: string) => {
- const effectsBridge = getEffectsBridge();
- if (!effectsBridge.isInitialized()) {
- return undefined;
- }
- return effectsBridge.getEffect(clipId, effectId);
+ return get()
+ .getVideoEffects(clipId)
+ .find((effect) => effect.id === effectId);
},
// Color grading actions
diff --git a/apps/web/src/stores/project/types.ts b/apps/web/src/stores/project/types.ts
index 55d3f957..42deb61a 100644
--- a/apps/web/src/stores/project/types.ts
+++ b/apps/web/src/stores/project/types.ts
@@ -4,6 +4,7 @@ import type {
MediaItem,
Track,
Clip,
+ Transition,
Action,
ActionResult,
TextClip,
@@ -111,6 +112,17 @@ export interface ProjectState {
trimStart: boolean,
) => Promise<ActionResult>;
getClip: (clipId: string) => Clip | undefined;
+ addClipTransition: (transition: Transition) => Transition | null;
+ updateClipTransition: (
+ transitionId: string,
+ updates: Partial<Pick<Transition, "type" | "duration" | "params">>,
+ ) => Transition | null;
+ removeClipTransition: (transitionId: string) => boolean;
+ getClipTransition: (transitionId: string) => Transition | undefined;
+ getClipTransitionBetweenClips: (
+ clipAId: string,
+ clipBId: string,
+ ) => Transition | undefined;
updateClipTransform: (
clipId: string,
transform: Partial<Transform>,
diff --git a/packages/core/src/video/video-effects-engine.test.ts b/packages/core/src/video/video-effects-engine.test.ts
new file mode 100644
index 00000000..ae7f919a
--- /dev/null
+++ b/packages/core/src/video/video-effects-engine.test.ts
@@ -0,0 +1,142 @@
+import { describe, expect, it } from "vitest";
+import type { Effect } from "../types/timeline";
+import { VideoEffectsEngine } from "./video-effects-engine";
+
+const createMockContext = (
+ width: number,
+ height: number,
+ pixels: number[],
+) => {
+ let imageData = new Uint8ClampedArray(pixels);
+
+ return {
+ ctx: {
+ getImageData: () => ({
+ data: new Uint8ClampedArray(imageData),
+ width,
+ height,
+ }),
+ putImageData: (next: { data: Uint8ClampedArray }) => {
+ imageData = new Uint8ClampedArray(next.data);
+ },
+ },
+ getPixels: () => Array.from(imageData),
+ };
+};
+
+describe("VideoEffectsEngine", () => {
+ it("supports the advanced editor filters in the shared engine", () => {
+ const engine = new VideoEffectsEngine({ width: 8, height: 8, useGPU: false }) as any;
+
+ expect(engine.isFilterSupported("shadow")).toBe(true);
+ expect(engine.isFilterSupported("glow")).toBe(true);
+ expect(engine.isFilterSupported("motion-blur")).toBe(true);
+ expect(engine.isFilterSupported("radial-blur")).toBe(true);
+ expect(engine.isFilterSupported("chromatic-aberration")).toBe(true);
+ expect(
+ engine.buildCSSFilter({
+ id: "shadow-1",
+ type: "shadow",
+ enabled: true,
+ params: {
+ offsetX: 4,
+ offsetY: 6,
+ blur: 10,
+ opacity: 0.5,
+ color: "#112233",
+ },
+ } satisfies Effect),
+ ).toContain("drop-shadow(4px 6px 10px rgba(17, 34, 51, 0.5))");
+ expect(
+ engine.buildCSSFilter({
+ id: "glow-1",
+ type: "glow",
+ enabled: true,
+ params: {
+ radius: 12,
+ intensity: 1.4,
+ color: "#ffffff",
+ },
+ } satisfies Effect),
+ ).toContain("drop-shadow");
+ });
+
+ it("applies motion blur at pixel level", async () => {
+ const engine = new VideoEffectsEngine({ width: 5, height: 1, useGPU: false }) as any;
+ const { ctx, getPixels } = createMockContext(5, 1, [
+ 0, 0, 0, 255,
+ 0, 0, 0, 255,
+ 255, 0, 0, 255,
+ 0, 0, 0, 255,
+ 0, 0, 0, 255,
+ ]);
+
+ await engine.applyEffectPixelLevel(
+ ctx,
+ {
+ id: "motion-blur-1",
+ type: "motion-blur",
+ enabled: true,
+ params: { distance: 4, angle: 0 },
+ } satisfies Effect,
+ 5,
+ 1,
+ );
+
+ const pixels = getPixels();
+ expect(pixels[0]).toBeGreaterThan(0);
+ expect(pixels[8]).toBeLessThan(255);
+ });
+
+ it("applies radial blur at pixel level", async () => {
+ const engine = new VideoEffectsEngine({ width: 5, height: 1, useGPU: false }) as any;
+ const { ctx, getPixels } = createMockContext(5, 1, [
+ 255, 0, 0, 255,
+ 0, 0, 0, 255,
+ 0, 0, 0, 255,
+ 0, 0, 0, 255,
+ 0, 0, 0, 255,
+ ]);
+
+ await engine.applyEffectPixelLevel(
+ ctx,
+ {
+ id: "radial-blur-1",
+ type: "radial-blur",
+ enabled: true,
+ params: { amount: 80, centerX: 50, centerY: 50 },
+ } satisfies Effect,
+ 5,
+ 1,
+ );
+
+ const pixels = getPixels();
+ expect(pixels[0]).toBeLessThan(255);
+ expect(pixels[4]).toBeGreaterThan(0);
+ });
+
+ it("applies chromatic aberration at pixel level", async () => {
+ const engine = new VideoEffectsEngine({ width: 3, height: 1, useGPU: false }) as any;
+ const { ctx, getPixels } = createMockContext(3, 1, [
+ 10, 20, 30, 255,
+ 40, 50, 60, 255,
+ 70, 80, 90, 255,
+ ]);
+
+ await engine.applyEffectPixelLevel(
+ ctx,
+ {
+ id: "chromatic-1",
+ type: "chromatic-aberration",
+ enabled: true,
+ params: { amount: 2 },
+ } satisfies Effect,
+ 3,
+ 1,
+ );
+
+ const pixels = getPixels();
+ expect(pixels[4]).toBe(70);
+ expect(pixels[6]).toBe(30);
+ });
+});
\ No newline at end of file
diff --git a/packages/core/src/video/video-effects-engine.ts b/packages/core/src/video/video-effects-engine.ts
index bbc108b1..7b90e063 100644
--- a/packages/core/src/video/video-effects-engine.ts
+++ b/packages/core/src/video/video-effects-engine.ts
@@ -349,7 +349,12 @@ export type FilterType =
| "chromaKey"
| "temperature"
| "tint"
- | "tonal";
+ | "tonal"
+ | "shadow"
+ | "glow"
+ | "motion-blur"
+ | "radial-blur"
+ | "chromatic-aberration";
export class VideoEffectsEngine {
private canvas: OffscreenCanvas | null = null;
@@ -1066,6 +1071,24 @@ export class VideoEffectsEngine {
this.applyTonal(data, shadows, midtones, highlights);
break;
}
+ case "motion-blur": {
+ const distance = (params.distance as number) || 0;
+ const angle = (params.angle as number) || 0;
+ this.applyMotionBlur(data, width, height, distance, angle);
+ break;
+ }
+ case "radial-blur": {
+ const amount = (params.amount as number) || 0;
+ const centerX = (params.centerX as number) || 50;
+ const centerY = (params.centerY as number) || 50;
+ this.applyRadialBlur(data, width, height, amount, centerX, centerY);
+ break;
+ }
+ case "chromatic-aberration": {
+ const amount = (params.amount as number) || 0;
+ this.applyChromaticAberration(data, width, height, amount);
+ break;
+ }
}
ctx.putImageData(imageData, 0, 0);
@@ -1254,12 +1277,204 @@ export class VideoEffectsEngine {
}
}
+ private applyMotionBlur(
+ data: Uint8ClampedArray,
+ width: number,
+ height: number,
+ distance: number,
+ angle: number,
+ ): void {
+ const blurDistance = Math.max(0, distance);
+ if (blurDistance <= 0) {
+ return;
+ }
+
+ const copy = new Uint8ClampedArray(data);
+ const sampleCount = Math.max(2, Math.min(16, Math.ceil(blurDistance / 4) + 1));
+ const radians = (angle * Math.PI) / 180;
+ const dirX = Math.cos(radians);
+ const dirY = Math.sin(radians);
+ const maxOffset = blurDistance / 2;
+
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ let red = 0;
+ let green = 0;
+ let blue = 0;
+ let alpha = 0;
+ let samples = 0;
+
+ for (let sampleIndex = 0; sampleIndex < sampleCount; sampleIndex++) {
+ const t = sampleCount === 1 ? 0 : sampleIndex / (sampleCount - 1);
+ const offset = (t - 0.5) * 2 * maxOffset;
+ const sampleX = Math.round(x + dirX * offset);
+ const sampleY = Math.round(y + dirY * offset);
+
+ if (
+ sampleX < 0 ||
+ sampleX >= width ||
+ sampleY < 0 ||
+ sampleY >= height
+ ) {
+ continue;
+ }
+
+ const sampleOffset = (sampleY * width + sampleX) * 4;
+ red += copy[sampleOffset];
+ green += copy[sampleOffset + 1];
+ blue += copy[sampleOffset + 2];
+ alpha += copy[sampleOffset + 3];
+ samples += 1;
+ }
+
+ if (samples === 0) {
+ continue;
+ }
+
+ const pixelOffset = (y * width + x) * 4;
+ data[pixelOffset] = Math.round(red / samples);
+ data[pixelOffset + 1] = Math.round(green / samples);
+ data[pixelOffset + 2] = Math.round(blue / samples);
+ data[pixelOffset + 3] = Math.round(alpha / samples);
+ }
+ }
+ }
+
+ private applyRadialBlur(
+ data: Uint8ClampedArray,
+ width: number,
+ height: number,
+ amount: number,
+ centerX: number,
+ centerY: number,
+ ): void {
+ const blurAmount = Math.max(0, amount);
+ if (blurAmount <= 0) {
+ return;
+ }
+
+ const copy = new Uint8ClampedArray(data);
+ const sampleCount = Math.max(2, Math.min(12, Math.ceil(blurAmount / 8) + 2));
+ const strength = Math.max(0, Math.min(1, blurAmount / 100));
+ const centerPixelX = (centerX / 100) * Math.max(0, width - 1);
+ const centerPixelY = (centerY / 100) * Math.max(0, height - 1);
+
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const deltaX = x - centerPixelX;
+ const deltaY = y - centerPixelY;
+ let red = 0;
+ let green = 0;
+ let blue = 0;
+ let alpha = 0;
+ let samples = 0;
+
+ for (let sampleIndex = 0; sampleIndex < sampleCount; sampleIndex++) {
+ const t = sampleCount === 1 ? 0 : sampleIndex / (sampleCount - 1);
+ const scale = 1 + (t - 0.5) * strength * 1.5;
+ const sampleX = Math.round(centerPixelX + deltaX * scale);
+ const sampleY = Math.round(centerPixelY + deltaY * scale);
+
+ if (
+ sampleX < 0 ||
+ sampleX >= width ||
+ sampleY < 0 ||
+ sampleY >= height
+ ) {
+ continue;
+ }
+
+ const sampleOffset = (sampleY * width + sampleX) * 4;
+ red += copy[sampleOffset];
+ green += copy[sampleOffset + 1];
+ blue += copy[sampleOffset + 2];
+ alpha += copy[sampleOffset + 3];
+ samples += 1;
+ }
+
+ if (samples === 0) {
+ continue;
+ }
+
+ const pixelOffset = (y * width + x) * 4;
+ data[pixelOffset] = Math.round(red / samples);
+ data[pixelOffset + 1] = Math.round(green / samples);
+ data[pixelOffset + 2] = Math.round(blue / samples);
+ data[pixelOffset + 3] = Math.round(alpha / samples);
+ }
+ }
+ }
+
+ private applyChromaticAberration(
+ data: Uint8ClampedArray,
+ width: number,
+ height: number,
+ amount: number,
+ ): void {
+ const offset = Math.max(0, Math.round(amount / 2));
+ if (offset <= 0) {
+ return;
+ }
+
+ const copy = new Uint8ClampedArray(data);
+
+ for (let y = 0; y < height; y++) {
+ for (let x = 0; x < width; x++) {
+ const pixelOffset = (y * width + x) * 4;
+ const redX = Math.min(width - 1, x + offset);
+ const blueX = Math.max(0, x - offset);
+ const redOffset = (y * width + redX) * 4;
+ const blueOffset = (y * width + blueX) * 4;
+
+ data[pixelOffset] = copy[redOffset];
+ data[pixelOffset + 1] = copy[pixelOffset + 1];
+ data[pixelOffset + 2] = copy[blueOffset + 2];
+ data[pixelOffset + 3] = copy[pixelOffset + 3];
+ }
+ }
+ }
+
+ private toFilterColor(color: string | undefined, opacity: number): string {
+ const alpha = Math.max(0, Math.min(1, opacity));
+ if (!color) {
+ return `rgba(0, 0, 0, ${alpha})`;
+ }
+
+ if (color.startsWith("rgb(" ) || color.startsWith("rgba(")) {
+ return color;
+ }
+
+ const normalized = color.replace(/^#/, "");
+ const hex =
+ normalized.length === 3
+ ? normalized
+ .split("")
+ .map((char) => `${char}${char}`)
+ .join("")
+ : normalized;
+
+ if (hex.length !== 6) {
+ return `rgba(0, 0, 0, ${alpha})`;
+ }
+
+ const red = Number.parseInt(hex.slice(0, 2), 16);
+ const green = Number.parseInt(hex.slice(2, 4), 16);
+ const blue = Number.parseInt(hex.slice(4, 6), 16);
+
+ if (Number.isNaN(red) || Number.isNaN(green) || Number.isNaN(blue)) {
+ return `rgba(0, 0, 0, ${alpha})`;
+ }
+
+ return `rgba(${red}, ${green}, ${blue}, ${alpha})`;
+ }
+
private buildCSSFilter(effect: Effect): string {
- const params = effect.params as Record<string, number>;
+ const params = effect.params as Record<string, number | string>;
+ const value = typeof params.value === "number" ? params.value : 0;
switch (effect.type) {
case "brightness":
- return `brightness(${1 + (params.value || 0) / 100})`;
+ return `brightness(${1 + value / 100})`;
case "contrast":
return `contrast(${params.value || 1})`;
case "saturation":
@@ -1268,6 +1483,29 @@ export class VideoEffectsEngine {
return `hue-rotate(${params.rotation || 0}deg)`;
case "blur":
return `blur(${params.radius || 0}px)`;
+ case "shadow": {
+ const color = this.toFilterColor(
+ typeof params.color === "string" ? params.color : undefined,
+ typeof params.opacity === "number" ? params.opacity : 0.8,
+ );
+ return `drop-shadow(${params.offsetX || 0}px ${params.offsetY || 0}px ${params.blur || 0}px ${color})`;
+ }
+ case "glow": {
+ const radius = Number(params.radius || 0);
+ const intensity =
+ typeof params.intensity === "number"
+ ? Math.max(0, Math.min(3, params.intensity))
+ : 1;
+ const primaryColor = this.toFilterColor(
+ typeof params.color === "string" ? params.color : undefined,
+ Math.min(1, 0.35 * intensity),
+ );
+ const secondaryColor = this.toFilterColor(
+ typeof params.color === "string" ? params.color : undefined,
+ Math.min(1, 0.2 * intensity),
+ );
+ return `drop-shadow(0 0 ${radius}px ${primaryColor}) drop-shadow(0 0 ${Math.max(1, radius / 2)}px ${secondaryColor})`;
+ }
default:
return "";
}
@@ -1348,6 +1586,11 @@ export class VideoEffectsEngine {
"temperature",
"tint",
"tonal",
+ "shadow",
+ "glow",
+ "motion-blur",
+ "radial-blur",
+ "chromatic-aberration",
];
}
diff --git a/packages/core/src/video/video-engine.ts b/packages/core/src/video/video-engine.ts
index 7ece3644..7661c96e 100644
--- a/packages/core/src/video/video-engine.ts
+++ b/packages/core/src/video/video-engine.ts
@@ -754,7 +754,7 @@ export class VideoEngine {
}
}
- if (clip.effects && clip.effects.length > 0) {
+ if (clipInfo.effects && clipInfo.effects.length > 0) {
try {
if (!this.effectsEngine) {
this.effectsEngine = new VideoEffectsEngine({
@@ -771,7 +771,7 @@ export class VideoEngine {
}
const effectsResult = await this.effectsEngine.applyEffects(
processedBitmap,
- clip.effects,
+ clipInfo.effects,
);
if (processedBitmap !== bitmap) {
processedBitmap.close();