-
Notifications
You must be signed in to change notification settings - Fork 5.2k
feat(effects): add @opencut/effects package with 24 effects and presets #750
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
doananh234
wants to merge
10
commits into
OpenCut-app:main
Choose a base branch
from
doananh234:feat/effects-package
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
81adac6
feat(effects): add @opencut/effects package with 24 effects and presets
7e40be9
test(effects): add unit tests for chromatic aberration, glitch, sharp…
doananh234 6cbc8d9
test(effects): add unit tests for chromatic aberration, glitch, sharp…
doananh234 22a42d5
fix: review coderabbit
doananh234 39de9fd
Merge branch 'feat/effects-package' of github.com:doananh234/OpenCut …
doananh234 464245c
Update apps/web/src/services/face-mesh/face-mesh-provider.ts
doananh234 04c3eed
fix: improve handle error in face-mesh
doananh234 4f74ec9
chore: add util for get effectParams
doananh234 14ea50a
Merge branch 'feat/effects-package' of github.com:doananh234/OpenCut …
doananh234 46d741a
chore: handle validate hex color
doananh234 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,13 +1,2 @@ | ||
| import { hasEffect, registerEffect } from "../registry"; | ||
| import { blurEffectDefinition } from "./blur"; | ||
|
|
||
| const defaultEffects = [blurEffectDefinition]; | ||
|
|
||
| export function registerDefaultEffects(): void { | ||
| for (const definition of defaultEffects) { | ||
| if (hasEffect({ effectType: definition.type })) { | ||
| continue; | ||
| } | ||
| registerEffect({ definition }); | ||
| } | ||
| } | ||
| /** Re-export from @opencut/effects package */ | ||
| export { registerAllEffects as registerDefaultEffects } from "@opencut/effects"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,31 +1,8 @@ | ||
| import type { EffectDefinition } from "@/types/effects"; | ||
|
|
||
| const effectDefinitions = new Map<string, EffectDefinition>(); | ||
|
|
||
| export function registerEffect({ | ||
| definition, | ||
| }: { | ||
| definition: EffectDefinition; | ||
| }): void { | ||
| effectDefinitions.set(definition.type, definition); | ||
| } | ||
|
|
||
| export function hasEffect({ effectType }: { effectType: string }): boolean { | ||
| return effectDefinitions.has(effectType); | ||
| } | ||
|
|
||
| export function getEffect({ | ||
| effectType, | ||
| }: { | ||
| effectType: string; | ||
| }): EffectDefinition { | ||
| const definition = effectDefinitions.get(effectType); | ||
| if (!definition) { | ||
| throw new Error(`Unknown effect type: ${effectType}`); | ||
| } | ||
| return definition; | ||
| } | ||
|
|
||
| export function getAllEffects(): EffectDefinition[] { | ||
| return Array.from(effectDefinitions.values()); | ||
| } | ||
| /** Re-export registry functions from @opencut/effects package */ | ||
| export { | ||
| registerEffect, | ||
| hasEffect, | ||
| getEffect, | ||
| getAllEffects, | ||
| clearEffects, | ||
| } from "@opencut/effects"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,244 @@ | ||
| import type { EffectContext } from "@opencut/effects"; | ||
|
|
||
| /** | ||
| * Face mesh detection provider using MediaPipe Face Mesh. | ||
| * Lazy-loads the WASM module only when first needed. | ||
| * Runs detection per frame and caches results. | ||
| */ | ||
|
|
||
| import type { FaceMesh as FaceMeshType, Results } from "@mediapipe/face_mesh"; | ||
|
|
||
| let faceMeshInstance: FaceMeshType | null = null; | ||
| let isLoading = false; | ||
| /** Shared in-flight promise for pending detections — avoids race conditions */ | ||
| let pendingDetection: Promise<Results> | null = null; | ||
| let pendingResolve: ((results: Results) => void) | null = null; | ||
| let pendingReject: ((error: Error) => void) | null = null; | ||
| let pendingTimeoutId: ReturnType<typeof setTimeout> | null = null; | ||
|
|
||
| /** Detection timeout in milliseconds */ | ||
| const DETECTION_TIMEOUT_MS = 5000; | ||
|
|
||
| /** MediaPipe Face Mesh version — must match package.json dependency */ | ||
| const MEDIAPIPE_VERSION = "0.4.1657299874"; | ||
|
|
||
| /** Types that MediaPipe FaceMesh accepts */ | ||
| type MediaPipeImageSource = | ||
| | HTMLImageElement | ||
| | HTMLCanvasElement | ||
| | HTMLVideoElement; | ||
|
|
||
| /** Clear the pending timeout if it exists */ | ||
| function clearPendingTimeout(): void { | ||
| if (pendingTimeoutId !== null) { | ||
| clearTimeout(pendingTimeoutId); | ||
| pendingTimeoutId = null; | ||
| } | ||
| } | ||
|
|
||
| /** Check if source is a valid MediaPipe image source */ | ||
| function isMediaPipeImageSource( | ||
| source: CanvasImageSource, | ||
| ): source is MediaPipeImageSource { | ||
| return ( | ||
| source instanceof HTMLImageElement || | ||
| source instanceof HTMLCanvasElement || | ||
| source instanceof HTMLVideoElement | ||
| ); | ||
| } | ||
|
|
||
| /** Convert OffscreenCanvas to HTMLCanvasElement for MediaPipe compatibility */ | ||
| function toHTMLCanvas(source: OffscreenCanvas): HTMLCanvasElement { | ||
| const canvas = document.createElement("canvas"); | ||
| canvas.width = source.width; | ||
| canvas.height = source.height; | ||
| const ctx = canvas.getContext("2d"); | ||
| if (ctx) { | ||
| ctx.drawImage(source, 0, 0); | ||
| } | ||
| return canvas; | ||
| } | ||
|
|
||
| /** Prepare source for MediaPipe — converts OffscreenCanvas if needed */ | ||
| function prepareSourceForMediaPipe( | ||
| source: CanvasImageSource, | ||
| ): MediaPipeImageSource | null { | ||
| if (isMediaPipeImageSource(source)) { | ||
| return source; | ||
| } | ||
| if (source instanceof OffscreenCanvas) { | ||
| return toHTMLCanvas(source); | ||
| } | ||
| // ImageBitmap, SVGImageElement, VideoFrame are not supported | ||
| return null; | ||
| } | ||
|
|
||
| /** Lazy-load MediaPipe Face Mesh WASM module */ | ||
| async function loadFaceMesh(): Promise<FaceMeshType | null> { | ||
| if (faceMeshInstance) return faceMeshInstance; | ||
| if (isLoading) return null; | ||
|
|
||
| isLoading = true; | ||
| try { | ||
| const { FaceMesh } = await import("@mediapipe/face_mesh"); | ||
| const fm = new FaceMesh({ | ||
| locateFile: (file: string) => | ||
| `https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh@${MEDIAPIPE_VERSION}/${file}`, | ||
| }); | ||
| fm.setOptions({ | ||
| maxNumFaces: 1, | ||
| refineLandmarks: true, | ||
| minDetectionConfidence: 0.5, | ||
| minTrackingConfidence: 0.5, | ||
| }); | ||
| fm.onResults((results: Results) => { | ||
| if (pendingResolve) { | ||
| clearPendingTimeout(); | ||
| pendingResolve(results); | ||
| pendingResolve = null; | ||
| pendingReject = null; | ||
| } | ||
| }); | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| faceMeshInstance = fm; | ||
| return fm; | ||
| } catch (err) { | ||
| return null; | ||
|
doananh234 marked this conversation as resolved.
|
||
| } finally { | ||
| isLoading = false; | ||
| } | ||
| } | ||
|
|
||
| /** MediaPipe face landmark indices for key regions */ | ||
| const LANDMARK_INDICES = { | ||
| leftCheek: 234, | ||
| rightCheek: 454, | ||
| jawBottom: 152, | ||
| jawLeft: 132, | ||
| jawRight: 361, | ||
| leftEyeCenter: 159, | ||
| rightEyeCenter: 386, | ||
| mouthCenter: 13, | ||
| }; | ||
|
|
||
| /** Convert MediaPipe face landmarks to EffectContext */ | ||
| function landmarksToContext( | ||
| landmarks: Array<{ x: number; y: number; z: number }>, | ||
| ): EffectContext { | ||
| const lc = landmarks[LANDMARK_INDICES.leftCheek]; | ||
| const rc = landmarks[LANDMARK_INDICES.rightCheek]; | ||
| const jaw = landmarks[LANDMARK_INDICES.jawBottom]; | ||
| const jawL = landmarks[LANDMARK_INDICES.jawLeft]; | ||
| const jawR = landmarks[LANDMARK_INDICES.jawRight]; | ||
|
|
||
| // Estimate cheek radius from face width | ||
| const faceWidth = Math.abs(rc.x - lc.x); | ||
| const cheekRadius = faceWidth * 0.15; | ||
|
|
||
| return { | ||
| faceDetected: true, | ||
| cheekLeft: [lc.x, lc.y], | ||
| cheekRight: [rc.x, rc.y], | ||
| cheekRadius, | ||
| jawPoints: [jaw.x, jaw.y, jawL.x, jawL.y, jawR.x, jawR.y], | ||
| }; | ||
| } | ||
|
|
||
| /** Detect face in the given image source and return EffectContext */ | ||
| export async function detectFace( | ||
| source: CanvasImageSource, | ||
| ): Promise<EffectContext> { | ||
| const fm = await loadFaceMesh(); | ||
| if (!fm) { | ||
| return { faceDetected: false }; | ||
| } | ||
|
|
||
| // Convert source to MediaPipe-compatible format | ||
| const mediaPipeSource = prepareSourceForMediaPipe(source); | ||
| if (!mediaPipeSource) { | ||
| // Source type not supported by MediaPipe | ||
| return { faceDetected: false }; | ||
| } | ||
|
|
||
| // Reuse existing in-flight detection if one exists | ||
| if (pendingDetection) { | ||
| const results = await pendingDetection; | ||
| if ( | ||
| !results?.multiFaceLandmarks || | ||
| results.multiFaceLandmarks.length === 0 | ||
| ) { | ||
| return { faceDetected: false }; | ||
| } | ||
| return landmarksToContext(results.multiFaceLandmarks[0]); | ||
| } | ||
|
|
||
| // Create new detection promise with timeout | ||
| pendingDetection = new Promise<Results>((resolve, reject) => { | ||
| pendingResolve = resolve; | ||
| pendingReject = reject; | ||
|
|
||
| // Set up timeout for detection | ||
| pendingTimeoutId = setTimeout(() => { | ||
| if (pendingReject) { | ||
| pendingReject(new Error("Face detection timeout")); | ||
| pendingResolve = null; | ||
| pendingReject = null; | ||
| pendingDetection = null; | ||
| pendingTimeoutId = null; | ||
| } | ||
| }, DETECTION_TIMEOUT_MS); | ||
|
|
||
| // Send image for detection, catching sync errors | ||
| try { | ||
| fm.send({ image: mediaPipeSource }); | ||
| } catch (error) { | ||
| clearPendingTimeout(); | ||
| reject(error instanceof Error ? error : new Error(String(error))); | ||
| } | ||
| }); | ||
|
|
||
| let results: Results; | ||
| try { | ||
| results = await pendingDetection; | ||
| } catch (error) { | ||
| // Detection failed (timeout or error) — return no face detected | ||
| pendingDetection = null; | ||
| pendingResolve = null; | ||
| pendingReject = null; | ||
| return { faceDetected: false }; | ||
| } | ||
|
|
||
| clearPendingTimeout(); | ||
| pendingDetection = null; | ||
| pendingResolve = null; | ||
| pendingReject = null; | ||
|
|
||
| if ( | ||
| !results?.multiFaceLandmarks || | ||
| results.multiFaceLandmarks.length === 0 | ||
| ) { | ||
| return { faceDetected: false }; | ||
| } | ||
|
|
||
| return landmarksToContext(results.multiFaceLandmarks[0]); | ||
| } | ||
|
|
||
| /** Check if MediaPipe is loaded (for conditional rendering) */ | ||
| export function isFaceMeshReady(): boolean { | ||
| return faceMeshInstance !== null; | ||
| } | ||
|
|
||
| /** Clean up MediaPipe resources */ | ||
| export function disposeFaceMesh(): void { | ||
| // Clear timeout and settle any pending detection before disposing | ||
| clearPendingTimeout(); | ||
| if (pendingReject) { | ||
| pendingReject(new Error("Face mesh disposed")); | ||
| pendingReject = null; | ||
| pendingResolve = null; | ||
| pendingDetection = null; | ||
| } | ||
| if (faceMeshInstance) { | ||
| faceMeshInstance.close(); | ||
| faceMeshInstance = null; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| export { detectFace, isFaceMeshReady, disposeFaceMesh } from "./face-mesh-provider"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.