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 text behind subject effect using MediaPipe segmentation

Augustus Otua771fb497f45
diff --git a/apps/web/src/components/editor/InspectorPanel.tsx b/apps/web/src/components/editor/InspectorPanel.tsx
index 1ea5f1d5..2171a930 100644
--- a/apps/web/src/components/editor/InspectorPanel.tsx
+++ b/apps/web/src/components/editor/InspectorPanel.tsx
@@ -45,6 +45,7 @@ import {
ParticleEffectsSection,
AudioTextSyncPanel,
AlignmentSection,
+ BehindSubjectSection,
} from "./inspector";
import { OPENREEL_TTS_URL } from "../../config/api-endpoints";
import {
@@ -1174,6 +1175,16 @@ export const InspectorPanel: React.FC = () => {
</Section>
)}
+ {showTextSection && (
+ <Section
+ title="Text Behind Subject"
+ sectionId="text-behind-subject"
+ defaultOpen={false}
+ >
+ <BehindSubjectSection clipId={clipId} />
+ </Section>
+ )}
+
{showShapeSection && (
<Section title="Shape Properties" sectionId="shape-properties">
<ShapeSection clipId={clipId} />
diff --git a/apps/web/src/components/editor/Preview.tsx b/apps/web/src/components/editor/Preview.tsx
index 3e2af4dd..304e7d87 100644
--- a/apps/web/src/components/editor/Preview.tsx
+++ b/apps/web/src/components/editor/Preview.tsx
@@ -67,6 +67,7 @@ import {
ParticleRenderer,
} from "./preview/index";
import { ProcessingOverlay } from "./ProcessingOverlay";
+import { getPersonSegmentationEngine } from "@openreel/core";
import type { MotionPathConfig, GSAPMotionPathPoint } from "@openreel/core";
const getAdaptivePoolSize = (width: number, height: number): number => {
@@ -179,6 +180,82 @@ const renderAllLayersWithGPU = async (
}
};
+const hasBehindSubjectText = (textClips: TextClip[]): boolean =>
+ textClips.some((textClip) => textClip.behindSubject);
+
+const captureSubjectFrame = async (
+ ctx: CanvasRenderingContext2D,
+ width: number,
+ height: number,
+): Promise<ImageBitmap | null> => {
+ try {
+ return await createImageBitmap(
+ ctx.canvas as HTMLCanvasElement | OffscreenCanvas,
+ 0,
+ 0,
+ width,
+ height,
+ );
+ } catch {
+ return null;
+ }
+};
+
+const drawMaskedSubjectFromFrame = async (
+ ctx: CanvasRenderingContext2D,
+ subjectFrame: ImageBitmap | null,
+ canvasWidth: number,
+ canvasHeight: number,
+): Promise<void> => {
+ if (!subjectFrame) return;
+
+ const segEngine = getPersonSegmentationEngine();
+ if (!segEngine.isInitialized()) return;
+
+ try {
+ const maskResult = await segEngine.getPersonMask(subjectFrame);
+ if (!maskResult) return;
+
+ const personCanvas = new OffscreenCanvas(canvasWidth, canvasHeight);
+ const personCtx = personCanvas.getContext("2d");
+ if (!personCtx) return;
+
+ personCtx.drawImage(subjectFrame, 0, 0, canvasWidth, canvasHeight);
+
+ const maskCanvas = new OffscreenCanvas(maskResult.width, maskResult.height);
+ const maskCtx = maskCanvas.getContext("2d");
+ if (!maskCtx) return;
+
+ maskCtx.putImageData(maskResult.mask, 0, 0);
+ personCtx.globalCompositeOperation = "destination-in";
+ personCtx.drawImage(maskCanvas, 0, 0, canvasWidth, canvasHeight);
+
+ ctx.drawImage(personCanvas, 0, 0);
+ } catch {
+ // If segmentation fails for a frame, keep the normal text overlay visible.
+ }
+};
+
+const renderTextClipWithSubjectMask = async (
+ ctx: CanvasRenderingContext2D,
+ textClip: TextClip,
+ canvasWidth: number,
+ canvasHeight: number,
+ time: number,
+ subjectFrame: ImageBitmap | null,
+): Promise<void> => {
+ renderTextClipToCanvas(ctx, textClip, canvasWidth, canvasHeight, time);
+
+ if (textClip.behindSubject) {
+ await drawMaskedSubjectFromFrame(
+ ctx,
+ subjectFrame,
+ canvasWidth,
+ canvasHeight,
+ );
+ }
+};
+
interface ClipWithPlaceholder {
isPlaceholder?: boolean;
}
@@ -748,7 +825,7 @@ export const Preview: React.FC = () => {
* "all" renders all overlays (legacy behavior for when no video is present)
*/
const renderOverlayClipsInTrackOrder = useCallback(
- (
+ async (
ctx: CanvasRenderingContext2D,
tracks: Track[],
shapeClips: (ShapeClip | SVGClip | StickerClip)[],
@@ -757,6 +834,7 @@ export const Preview: React.FC = () => {
canvasWidth: number,
canvasHeight: number,
mode: "below-video" | "above-video" | "all" = "all",
+ subjectFrame: ImageBitmap | null = null,
) => {
const videoImageTrackIndices = tracks
.map((t, idx) => ({ track: t, originalIndex: idx }))
@@ -815,12 +893,13 @@ export const Preview: React.FC = () => {
(tc) => tc.trackId === track.id,
);
for (const textClip of trackTextClips) {
- renderTextClipToCanvas(
+ await renderTextClipWithSubjectMask(
ctx,
textClip,
canvasWidth,
canvasHeight,
time,
+ subjectFrame,
);
}
}
@@ -1300,7 +1379,7 @@ export const Preview: React.FC = () => {
ctx.fillRect(0, 0, canvas.width, canvas.height);
shouldClearCanvas = false;
}
- renderOverlayClipsInTrackOrder(
+ await renderOverlayClipsInTrackOrder(
ctx,
timelineTracks,
activeShapeClips,
@@ -1311,7 +1390,7 @@ export const Preview: React.FC = () => {
"below-video",
);
ctx.drawImage(blendedFrame, 0, 0);
- renderOverlayClipsInTrackOrder(
+ await renderOverlayClipsInTrackOrder(
ctx,
timelineTracks,
activeShapeClips,
@@ -1320,6 +1399,7 @@ export const Preview: React.FC = () => {
canvas.width,
canvas.height,
"above-video",
+ hasBehindSubjectText(activeTextClips) ? blendedFrame : null,
);
hasRenderedFrame = true;
}
@@ -1337,7 +1417,7 @@ export const Preview: React.FC = () => {
ctx.fillRect(0, 0, canvas.width, canvas.height);
shouldClearCanvas = false;
}
- renderOverlayClipsInTrackOrder(
+ await renderOverlayClipsInTrackOrder(
ctx,
timelineTracks,
activeShapeClips,
@@ -1348,7 +1428,7 @@ export const Preview: React.FC = () => {
"below-video",
);
ctx.drawImage(validFrame, 0, 0);
- renderOverlayClipsInTrackOrder(
+ await renderOverlayClipsInTrackOrder(
ctx,
timelineTracks,
activeShapeClips,
@@ -1357,6 +1437,7 @@ export const Preview: React.FC = () => {
canvas.width,
canvas.height,
"above-video",
+ hasBehindSubjectText(activeTextClips) ? validFrame : null,
);
hasRenderedFrame = true;
} else if (incomingFrame) {
@@ -1373,7 +1454,7 @@ export const Preview: React.FC = () => {
ctx.fillRect(0, 0, canvas.width, canvas.height);
shouldClearCanvas = false;
}
- renderOverlayClipsInTrackOrder(
+ await renderOverlayClipsInTrackOrder(
ctx,
timelineTracks,
activeShapeClips,
@@ -1384,7 +1465,7 @@ export const Preview: React.FC = () => {
"below-video",
);
ctx.drawImage(validFrame, 0, 0);
- renderOverlayClipsInTrackOrder(
+ await renderOverlayClipsInTrackOrder(
ctx,
timelineTracks,
activeShapeClips,
@@ -1393,6 +1474,7 @@ export const Preview: React.FC = () => {
canvas.width,
canvas.height,
"above-video",
+ hasBehindSubjectText(activeTextClips) ? validFrame : null,
);
hasRenderedFrame = true;
}
@@ -1438,6 +1520,9 @@ export const Preview: React.FC = () => {
)
.sort((a, b) => b.originalIndex - a.originalIndex);
+ let subjectFrame: ImageBitmap | null = null;
+ const shouldCompositeSubject = hasBehindSubjectText(activeTextClips);
+
for (const { track } of allRenderableTracks) {
if (track.type === "video" || track.type === "image") {
for (const clip of track.clips) {
@@ -1529,6 +1614,15 @@ export const Preview: React.FC = () => {
);
hasRenderedFrame = true;
}
+
+ if (shouldCompositeSubject) {
+ subjectFrame?.close();
+ subjectFrame = await captureSubjectFrame(
+ ctx,
+ canvas.width,
+ canvas.height,
+ );
+ }
}
}
}
@@ -1551,17 +1645,20 @@ export const Preview: React.FC = () => {
(tc) => tc.trackId === track.id,
);
for (const textClip of trackTextClips) {
- renderTextClipToCanvas(
+ await renderTextClipWithSubjectMask(
ctx,
textClip,
canvas.width,
canvas.height,
time,
+ subjectFrame,
);
+
hasRenderedFrame = true;
}
}
}
+ subjectFrame?.close();
}
const activeSubtitles = getActiveSubtitles(allSubtitles, time);
@@ -2096,7 +2193,7 @@ export const Preview: React.FC = () => {
);
if (activeShapeClipsNoVideo.length > 0 || activeTextClipsNoVideo.length > 0) {
- renderOverlayClipsInTrackOrder(
+ await renderOverlayClipsInTrackOrder(
ctx,
timelineTracksRef.current,
activeShapeClipsNoVideo,
@@ -2243,11 +2340,14 @@ export const Preview: React.FC = () => {
);
drawFrameWithTransform(ctx, video, transform, canvas.width, canvas.height);
+ const subjectFrame = hasBehindSubjectText(activeTextClips)
+ ? await captureSubjectFrame(ctx, canvas.width, canvas.height)
+ : null;
// Use CPU canvas2D for all overlays - more reliable than GPU compositing
// Render all text/graphics overlays (they're above the video since backgrounds are separate)
if (activeShapeClips.length > 0 || activeTextClips.length > 0) {
- renderOverlayClipsInTrackOrder(
+ await renderOverlayClipsInTrackOrder(
ctx,
timelineTracksRef.current,
activeShapeClips,
@@ -2256,8 +2356,10 @@ export const Preview: React.FC = () => {
canvas.width,
canvas.height,
"all",
+ subjectFrame,
);
}
+ subjectFrame?.close();
const activeSubtitles = getActiveSubtitles(
allSubtitles,
@@ -2317,6 +2419,7 @@ export const Preview: React.FC = () => {
getMediaItem,
isMuted,
preDecodeAllAudioBuffers,
+ renderOverlayClipsInTrackOrder,
setPlayheadPosition,
timelineTracks,
],
@@ -3245,8 +3348,11 @@ export const Preview: React.FC = () => {
)
.sort((a, b) => b.originalIndex - a.originalIndex);
+ const activeTextNeedsSubject = hasBehindSubjectText(activeTextClips);
const useGPU =
- rendererRef.current && rendererRef.current.type === "webgpu";
+ rendererRef.current &&
+ rendererRef.current.type === "webgpu" &&
+ !activeTextNeedsSubject;
if (useGPU) {
const gpuLayers: GPULayer[] = [];
@@ -3353,6 +3459,7 @@ export const Preview: React.FC = () => {
bitmap.close();
}
} else {
+ let subjectFrame: ImageBitmap | null = null;
for (const { track, originalIndex } of allRenderableTracks) {
if (track.type === "video" || track.type === "image") {
const trackFrames = validFrames.filter(
@@ -3366,6 +3473,14 @@ export const Preview: React.FC = () => {
canvas.width,
canvas.height,
);
+ if (activeTextNeedsSubject) {
+ subjectFrame?.close();
+ subjectFrame = await captureSubjectFrame(
+ ctx,
+ canvas.width,
+ canvas.height,
+ );
+ }
}
} else if (track.type === "graphics") {
const trackShapeClips = activeShapeClips.filter(
@@ -3385,16 +3500,18 @@ export const Preview: React.FC = () => {
(tc) => tc.trackId === track.id,
);
for (const textClip of trackTextClips) {
- renderTextClipToCanvas(
+ await renderTextClipWithSubjectMask(
ctx,
textClip,
canvas.width,
canvas.height,
currentPlayhead,
+ subjectFrame,
);
}
}
}
+ subjectFrame?.close();
}
const activeSubtitles = getActiveSubtitles(
diff --git a/apps/web/src/components/editor/inspector/BehindSubjectSection.tsx b/apps/web/src/components/editor/inspector/BehindSubjectSection.tsx
new file mode 100644
index 00000000..ea73e48a
--- /dev/null
+++ b/apps/web/src/components/editor/inspector/BehindSubjectSection.tsx
@@ -0,0 +1,86 @@
+import React, { useCallback, useState, useEffect } from "react";
+import { Switch } from "@openreel/ui";
+import { Loader2 } from "lucide-react";
+import { useEngineStore } from "../../../stores/engine-store";
+import { useProjectStore } from "../../../stores/project-store";
+import { getPersonSegmentationEngine } from "@openreel/core";
+
+interface BehindSubjectSectionProps {
+ clipId: string;
+}
+
+export const BehindSubjectSection: React.FC<BehindSubjectSectionProps> = ({
+ clipId,
+}) => {
+ const getTitleEngine = useEngineStore((state) => state.getTitleEngine);
+ const updateTextBehindSubject = useProjectStore(
+ (state) => state.updateTextBehindSubject,
+ );
+ const modifiedAt = useProjectStore((state) => state.project.modifiedAt);
+ const [isLoading, setIsLoading] = useState(false);
+ const [enabled, setEnabled] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ const engine = getTitleEngine();
+ const textClip = engine?.getTextClip(clipId);
+ setEnabled(textClip?.behindSubject ?? false);
+ }, [clipId, getTitleEngine, modifiedAt]);
+
+ const handleToggle = useCallback(
+ async (checked: boolean) => {
+ const engine = getTitleEngine();
+ if (!engine) return;
+
+ setError(null);
+ setEnabled(checked);
+
+ if (!checked) {
+ updateTextBehindSubject(clipId, false);
+ return;
+ }
+
+ const segEngine = getPersonSegmentationEngine();
+ if (!segEngine.isInitialized()) {
+ setIsLoading(true);
+ try {
+ await segEngine.initialize();
+ } catch {
+ setError("Failed to load AI model. Check your connection.");
+ updateTextBehindSubject(clipId, false);
+ setEnabled(false);
+ setIsLoading(false);
+ return;
+ }
+ setIsLoading(false);
+ }
+
+ updateTextBehindSubject(clipId, true);
+ },
+ [clipId, getTitleEngine, updateTextBehindSubject],
+ );
+
+ return (
+ <div className="space-y-3">
+ <div className="flex items-center justify-between">
+ <div className="flex-1">
+ <p className="text-[11px] text-text-primary">Place Behind Subject</p>
+ <p className="text-[9px] text-text-muted">
+ Text appears behind people in the video
+ </p>
+ </div>
+ {isLoading ? (
+ <Loader2 size={14} className="animate-spin text-primary" />
+ ) : (
+ <Switch checked={enabled} onCheckedChange={handleToggle} />
+ )}
+ </div>
+ {isLoading && (
+ <p className="text-[9px] text-text-muted">Loading AI model...</p>
+ )}
+ {error && (
+ <p className="text-[9px] text-red-400">{error}</p>
+ )}
+ </div>
+ );
+};
diff --git a/apps/web/src/components/editor/inspector/index.ts b/apps/web/src/components/editor/inspector/index.ts
index ca23c1b1..c85a40c4 100644
--- a/apps/web/src/components/editor/inspector/index.ts
+++ b/apps/web/src/components/editor/inspector/index.ts
@@ -90,3 +90,7 @@ export { SceneNavigatorPanel } from "./SceneNavigatorPanel";
// Particle Effects
export { ParticleEffectsSection } from "./ParticleEffectsSection";
+
+// Text Behind Subject
+export { BehindSubjectSection } from "./BehindSubjectSection";
+
diff --git a/apps/web/src/stores/project-store.ts b/apps/web/src/stores/project-store.ts
index 594e30b8..9b4d125c 100644
--- a/apps/web/src/stores/project-store.ts
+++ b/apps/web/src/stores/project-store.ts
@@ -219,6 +219,10 @@ export interface ProjectState {
clipId: string,
transform: Partial<Transform>,
) => TextClip | null;
+ updateTextBehindSubject: (
+ clipId: string,
+ behindSubject: boolean,
+ ) => TextClip | null;
getTextClip: (clipId: string) => TextClip | undefined;
getAllTextClips: () => TextClip[];
updateTextClipKeyframes: (
@@ -2821,6 +2825,25 @@ export const useProjectStore = create<ProjectState>()(
return updatedClip || null;
},
+ /**
+ * Toggle text behind subject compositing.
+ */
+ updateTextBehindSubject: (clipId: string, behindSubject: boolean) => {
+ const titleEngine = useEngineStore.getState().getTitleEngine();
+ if (!titleEngine) {
+ console.error("TitleEngine not initialized");
+ return null;
+ }
+
+ const updatedClip = titleEngine.updateTextClip(clipId, {
+ behindSubject,
+ });
+ if (updatedClip) {
+ set({ project: { ...get().project, modifiedAt: Date.now() } });
+ }
+ return updatedClip || null;
+ },
+
/**
* Get a text clip by ID
*/
diff --git a/apps/web/src/stores/project/types.ts b/apps/web/src/stores/project/types.ts
index 0047826a..55d3f957 100644
--- a/apps/web/src/stores/project/types.ts
+++ b/apps/web/src/stores/project/types.ts
@@ -142,6 +142,10 @@ export interface ProjectState {
clipId: string,
transform: Partial<Transform>,
) => TextClip | null;
+ updateTextBehindSubject: (
+ clipId: string,
+ behindSubject: boolean,
+ ) => TextClip | null;
getTextClip: (clipId: string) => TextClip | undefined;
getAllTextClips: () => TextClip[];
updateTextClipKeyframes: (
diff --git a/packages/core/package.json b/packages/core/package.json
index 494b75f7..d1be3763 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -35,6 +35,7 @@
"dependencies": {
"@ffmpeg/ffmpeg": "^0.12.15",
"@ffmpeg/util": "^0.12.2",
+ "@mediapipe/tasks-vision": "^0.10.35",
"gsap": "^3.14.2",
"idb-keyval": "^6.2.2",
"immer": "^11.0.1",
diff --git a/packages/core/src/ai/index.ts b/packages/core/src/ai/index.ts
index c3bc8152..89058a06 100644
--- a/packages/core/src/ai/index.ts
+++ b/packages/core/src/ai/index.ts
@@ -1,2 +1,3 @@
export * from "./background-removal-engine";
export * from "./auto-reframe-engine";
+export * from "./person-segmentation-engine";
diff --git a/packages/core/src/ai/person-segmentation-engine.ts b/packages/core/src/ai/person-segmentation-engine.ts
new file mode 100644
index 00000000..ddc5af8d
--- /dev/null
+++ b/packages/core/src/ai/person-segmentation-engine.ts
@@ -0,0 +1,133 @@
+import {
+ ImageSegmenter,
+ FilesetResolver,
+} from "@mediapipe/tasks-vision";
+
+export interface SegmentationResult {
+ mask: ImageData;
+ width: number;
+ height: number;
+}
+
+const MODEL_URL =
+ "https://storage.googleapis.com/mediapipe-models/image_segmenter/selfie_segmenter/float16/latest/selfie_segmenter.tflite";
+
+export class PersonSegmentationEngine {
+ private segmenter: ImageSegmenter | null = null;
+ private initialized = false;
+ private initializing: Promise<void> | null = null;
+
+ async initialize(): Promise<void> {
+ if (this.initialized) return;
+ if (this.initializing) return this.initializing;
+
+ this.initializing = this.doInitialize();
+ try {
+ await this.initializing;
+ } catch (error) {
+ this.initializing = null;
+ throw error;
+ }
+ }
+
+ private async doInitialize(): Promise<void> {
+ const vision = await FilesetResolver.forVisionTasks(
+ "https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm",
+ );
+
+ this.segmenter = await ImageSegmenter.createFromOptions(vision, {
+ baseOptions: {
+ modelAssetPath: MODEL_URL,
+ delegate: "GPU",
+ },
+ runningMode: "IMAGE",
+ outputCategoryMask: false,
+ outputConfidenceMasks: true,
+ });
+
+ this.initialized = true;
+ this.initializing = null;
+ }
+
+ isInitialized(): boolean {
+ return this.initialized;
+ }
+
+ async getPersonMask(frame: ImageBitmap): Promise<SegmentationResult | null> {
+ if (!this.segmenter) return null;
+
+ const width = frame.width;
+ const height = frame.height;
+
+ const canvas = document.createElement("canvas");
+ canvas.width = width;
+ canvas.height = height;
+ const ctx = canvas.getContext("2d")!;
+ ctx.drawImage(frame, 0, 0);
+
+ let maskData: ImageData | null = null;
+
+ this.segmenter.segment(canvas, (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),
+ );
+ const foregroundMaskIndex =
+ personLabelIndex >= 0 && personLabelIndex < result.confidenceMasks.length
+ ? personLabelIndex
+ : result.confidenceMasks.length > 1
+ ? result.confidenceMasks.length - 1
+ : 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;
+ }
+
+ for (const confidenceMask of result.confidenceMasks) {
+ confidenceMask.close();
+ }
+ }
+ });
+
+ if (!maskData) return null;
+
+ return { mask: maskData, width, height };
+ }
+
+ dispose(): void {
+ if (this.segmenter) {
+ this.segmenter.close();
+ this.segmenter = null;
+ }
+ this.initialized = false;
+ this.initializing = null;
+ }
+}
+
+let instance: PersonSegmentationEngine | null = null;
+
+export function getPersonSegmentationEngine(): PersonSegmentationEngine {
+ if (!instance) {
+ instance = new PersonSegmentationEngine();
+ }
+ return instance;
+}
+
+export function disposePersonSegmentationEngine(): void {
+ if (instance) {
+ instance.dispose();
+ instance = null;
+ }
+}
diff --git a/packages/core/src/text/title-engine.ts b/packages/core/src/text/title-engine.ts
index 39b82fdb..0f4c7c1e 100644
--- a/packages/core/src/text/title-engine.ts
+++ b/packages/core/src/text/title-engine.ts
@@ -32,6 +32,7 @@ export interface UpdateTextClipOptions {
blendMode?: import("../video/types").BlendMode;
blendOpacity?: number;
emphasisAnimation?: import("../graphics/types").EmphasisAnimation;
+ behindSubject?: boolean;
}
export class TitleEngine {
@@ -124,6 +125,8 @@ export class TitleEngine {
blendOpacity: updates.blendOpacity ?? existing.blendOpacity,
emphasisAnimation:
updates.emphasisAnimation ?? existing.emphasisAnimation,
+ behindSubject:
+ updates.behindSubject ?? existing.behindSubject,
};
this.textClips.set(id, updatedClip);
diff --git a/packages/core/src/text/types.ts b/packages/core/src/text/types.ts
index 0a910e28..4c5654fc 100644
--- a/packages/core/src/text/types.ts
+++ b/packages/core/src/text/types.ts
@@ -14,6 +14,7 @@ export interface TextClip {
readonly blendMode?: import("../video/types").BlendMode;
readonly blendOpacity?: number;
readonly emphasisAnimation?: EmphasisAnimation;
+ readonly behindSubject?: boolean;
}
export interface TextStyle {
diff --git a/packages/core/src/video/video-engine.ts b/packages/core/src/video/video-engine.ts
index 2ecf8450..08fa989b 100644
--- a/packages/core/src/video/video-engine.ts
+++ b/packages/core/src/video/video-engine.ts
@@ -44,6 +44,7 @@ import {
isAnimatedGif,
} from "../media/gif-decoder";
import { getParticleEngine } from "../effects/particle-engine";
+import { getPersonSegmentationEngine } from "../ai/person-segmentation-engine";
const DEFAULT_CACHE_CONFIG: FrameCacheConfig = {
maxFrames: 100,
@@ -446,6 +447,11 @@ export class VideoEngine {
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, width, height);
+ let subjectFrame: ImageBitmap | null = null;
+ const activeTextNeedsSubject = activeTextClips.some(
+ (clip) => clip.behindSubject,
+ );
+
for (const { track } of allRenderableTracks) {
if (track.type === "video" || track.type === "image") {
const clips = this.getClipsAtTime(track, time);
@@ -605,6 +611,11 @@ export class VideoEngine {
height,
);
+ if (activeTextNeedsSubject) {
+ subjectFrame?.close();
+ subjectFrame = await this.captureSubjectFrame(ctx, width, height);
+ }
+
if (processedBitmap !== bitmap) {
processedBitmap.close();
}
@@ -657,10 +668,18 @@ export class VideoEngine {
(tc) => tc.trackId === track.id,
);
for (const textClip of trackTextClips) {
- this.renderTextClipToCanvasCtx(ctx, textClip, time, width, height);
+ await this.renderTextClipWithSubjectMask(
+ ctx,
+ textClip,
+ time,
+ width,
+ height,
+ subjectFrame,
+ );
}
}
}
+ subjectFrame?.close();
this.renderParticlesToContext(ctx, time, width, height);
@@ -742,6 +761,73 @@ export class VideoEngine {
ctx.restore();
}
+ private async captureSubjectFrame(
+ ctx: OffscreenCanvasRenderingContext2D,
+ width: number,
+ height: number,
+ ): Promise<ImageBitmap | null> {
+ try {
+ return await createImageBitmap(ctx.canvas, 0, 0, width, height);
+ } catch {
+ return null;
+ }
+ }
+
+ private async drawMaskedSubjectFromFrame(
+ ctx: OffscreenCanvasRenderingContext2D,
+ subjectFrame: ImageBitmap | null,
+ width: number,
+ height: number,
+ ): Promise<void> {
+ if (!subjectFrame) return;
+
+ try {
+ const segEngine = getPersonSegmentationEngine();
+ if (!segEngine.isInitialized()) {
+ await segEngine.initialize();
+ }
+
+ const maskResult = await segEngine.getPersonMask(subjectFrame);
+ if (!maskResult) return;
+
+ const personCanvas = new OffscreenCanvas(width, height);
+ const personCtx = personCanvas.getContext("2d");
+ if (!personCtx) return;
+
+ personCtx.drawImage(subjectFrame, 0, 0, width, height);
+
+ const maskCanvas = new OffscreenCanvas(
+ maskResult.width,
+ maskResult.height,
+ );
+ const maskCtx = maskCanvas.getContext("2d");
+ if (!maskCtx) return;
+
+ maskCtx.putImageData(maskResult.mask, 0, 0);
+ personCtx.globalCompositeOperation = "destination-in";
+ personCtx.drawImage(maskCanvas, 0, 0, width, height);
+
+ ctx.drawImage(personCanvas, 0, 0);
+ } catch {
+ // Keep the normal text render if segmentation is unavailable.
+ }
+ }
+
+ private async renderTextClipWithSubjectMask(
+ ctx: OffscreenCanvasRenderingContext2D,
+ textClip: TextClip,
+ time: number,
+ width: number,
+ height: number,
+ subjectFrame: ImageBitmap | null,
+ ): Promise<void> {
+ this.renderTextClipToCanvasCtx(ctx, textClip, time, width, height);
+
+ if (textClip.behindSubject) {
+ await this.drawMaskedSubjectFromFrame(ctx, subjectFrame, width, height);
+ }
+ }
+
private getActiveTextClips(timeline: Timeline, time: number): TextClip[] {
const allTextClips = titleEngine.getAllTextClips();
const textTracks = timeline.tracks.filter(
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 17496f52..72b9d538 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -320,6 +320,9 @@ importers:
'@ffmpeg/util':
specifier: ^0.12.2
version: 0.12.2
+ '@mediapipe/tasks-vision':
+ specifier: ^0.10.35
+ version: 0.10.35
gsap:
specifier: ^3.14.2
version: 3.14.2
@@ -1145,6 +1148,9 @@ packages:
'@jridgewell/[email protected]':
resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==}
+ '@mediapipe/[email protected]':
+ resolution: {integrity: sha512-HOvadwVRE6JC+45nyYhmnywnr5h/J8KZvOeUNVOG9q/0875pZgItznFB9bRTvLc264YSJqiZ1NsIpCStJw/egg==}
+
'@nodelib/[email protected]':
resolution: {integrity: sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==}
engines: {node: '>= 8'}
@@ -4272,6 +4278,8 @@ snapshots:
'@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.5.5
+ '@mediapipe/[email protected]': {}
+
'@nodelib/[email protected]':
dependencies:
'@nodelib/fs.stat': 2.0.5