Skip to content

Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.

fix(webcam): address the review findings on the AI background PR

EtienneLescotd1b051afd180
diff --git a/biome.json b/biome.json
index 8690776ed..8954e61bf 100644
--- a/biome.json
+++ b/biome.json
@@ -3,7 +3,7 @@
"vcs": { "enabled": true, "clientKind": "git", "useIgnoreFile": true },
"files": {
"ignoreUnknown": false,
- "includes": ["**", "!**/*.css", "!**/design/**", "!**/.worktrees/**", "!**/public/**"]
+ "includes": ["**", "!**/*.css", "!**/design/**", "!**/.worktrees/**", "!**/public/mediapipe/**"]
},
"formatter": {
"enabled": true,
diff --git a/crates/compositor/src/compositor_windows.rs b/crates/compositor/src/compositor_windows.rs
index 1ae36bc2b..d22567b3e 100644
--- a/crates/compositor/src/compositor_windows.rs
+++ b/crates/compositor/src/compositor_windows.rs
@@ -1538,11 +1538,7 @@ impl Compositor {
scene_preset.as_deref(),
Some("dual-frame") | Some("vertical-stack"),
);
- let is_transparent_cutout = matches!(
- scene_ref.as_ref().and_then(|s| s.webcam_effect.as_ref()),
- Some(e) if e.mode == "transparent" || (e.mode == "presegmented" && e.blur_intensity < -0.5)
- );
- if cfg.shadow && !webcam_is_block && !is_transparent_cutout && shape_fade > 0.0 {
+ if cfg.shadow && !webcam_is_block && shape_fade > 0.0 {
let strength = WEBCAM_SHADOW_OPACITY * shape_fade;
self.draw_shadow(
w_dst,
@@ -1553,39 +1549,25 @@ impl Compositor {
strength,
);
}
- let (effect_mode_val, blur_val, custom_bg_color) = match scene_ref.as_ref().and_then(|s| s.webcam_effect.as_ref()) {
- Some(e) if e.mode == "transparent" => (1.0f32, 0.0f32, [0.0, 0.0, 0.0, 1.0]),
- Some(e) if e.mode == "blur" => (2.0f32, e.blur_intensity, [0.0, 0.0, 0.0, 1.0]),
- Some(e) if e.mode == "custom" => {
- let col = match &e.background {
- Some(SceneBackground::Color { color }) => parse_hex(color).unwrap_or([0.0, 0.0, 0.0, 1.0]),
- _ => [0.0, 0.0, 0.0, 1.0],
- };
- (3.0f32, 0.0f32, col)
- }
- Some(e) if e.mode == "presegmented" => (0.0f32, 0.0f32, [0.0, 0.0, 0.0, 1.0]),
- _ => (0.0f32, 0.0f32, [0.0, 0.0, 0.0, 1.0]),
- };
-
- if effect_mode_val <= 0.5 {
- self.draw_video(
- &LayerCB {
- dst: w_dst,
- src: [u0, sv0, u1, sv1],
- quad_px: w_px,
- radius_px: w_radius,
- mode: 0.0,
- color: custom_bg_color,
- fx: [0.0, 0.0, effect_mode_val, blur_val],
- src_prev: [u0, sv0, u1, sv1], // src fixe (pas de zoom webcam)
- dst_prev: w_dst_prev,
- mb: [mb_taps, 1.0, 1.0, 0.0],
- ..Default::default()
- },
- &wy,
- &wuv,
- );
- }
+ // La segmentation est PRÉ-RENDUE côté app (MediaPipe) et le natif reçoit déjà la
+ // piste détourée/floutée : il n'y a donc aucun effet à appliquer ici, la webcam se
+ // dessine comme n'importe quelle autre piste.
+ self.draw_video(
+ &LayerCB {
+ dst: w_dst,
+ src: [u0, sv0, u1, sv1],
+ quad_px: w_px,
+ radius_px: w_radius,
+ mode: 0.0,
+ color: [0.0, 0.0, 0.0, 1.0],
+ src_prev: [u0, sv0, u1, sv1], // src fixe (pas de zoom webcam)
+ dst_prev: w_dst_prev,
+ mb: [mb_taps, 1.0, 1.0, 0.0],
+ ..Default::default()
+ },
+ &wy,
+ &wuv,
+ );
}
// --- annotations : calque le plus haut, comme dans le DOM de la preview (le calque y est
diff --git a/crates/compositor/src/scene.rs b/crates/compositor/src/scene.rs
index bde9dd519..2d20e233b 100644
--- a/crates/compositor/src/scene.rs
+++ b/crates/compositor/src/scene.rs
@@ -429,20 +429,6 @@ pub struct SceneOutput {
pub fps: Option<f64>,
}
-/// Effet d'arrière-plan de la webcam (détourage IA, flou, fond personnalisé).
-#[derive(Debug, Clone, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct SceneWebcamEffect {
- /// "none" | "transparent" | "blur" | "custom"
- pub mode: String,
- #[serde(default)]
- pub blur_intensity: f32,
- #[serde(default)]
- pub background: Option<SceneBackground>,
- #[serde(default)]
- pub mask_path: Option<String>,
-}
-
/// Tout ce dont le natif a besoin pour composer la scène, sérialisé depuis un document.
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -468,9 +454,6 @@ pub struct Scene {
/// Crop écran par clip, dans le même ordre que `clips` (`cropByClip` côté TS).
#[serde(default)]
pub crop_by_clip: Vec<Option<SceneCrop>>,
- /// Effet d'arrière-plan / détourage IA de la webcam.
- #[serde(default)]
- pub webcam_effect: Option<SceneWebcamEffect>,
/// État de rendu interne, positionné par `for_clip_window` (jamais envoyé par l'app).
#[serde(skip)]
pub(crate) active_clip_index: usize,
@@ -618,36 +601,6 @@ mod tests {
let s = Scene::from_json(json).expect("parse sans webcam_rect");
assert!(s.layout.webcam_rect.is_none());
assert_eq!(s.layout.preset, "picture-in-picture");
- assert!(s.webcam_effect.is_none());
- }
-
- #[test]
- fn parses_webcam_effect_payload() {
- let json = r##"{
- "clips": [],
- "layout": {"preset":"picture-in-picture","webcamSize":0.25,"webcamShape":"circle","webcamMirror":false,"webcamPosition":null,"webcamReactiveZoom":false},
- "effects": {"padding":0,"blur":false,"shadow":0,"roundnessFrac":0,"motionBlur":0},
- "background": {"kind":"color","color":"#000000"},
- "zoomRegions": [],
- "cursor": {"show":false,"size":1,"smoothing":0,"motionBlur":0,"clickBounce":0,"clipToBounds":false,"theme":"default"},
- "cropByClip": [],
- "output": {"width":1920,"height":1080,"fps":null},
- "webcamEffect": {
- "mode": "custom",
- "blurIntensity": 0.75,
- "background": {"kind":"color","color":"#ff0080"},
- "maskPath": "/path/to/mask.mp4"
- }
- }"##;
- let s = Scene::from_json(json).expect("parse avec webcamEffect");
- let effect = s.webcam_effect.expect("webcamEffect présent");
- assert_eq!(effect.mode, "custom");
- assert_eq!(effect.blur_intensity, 0.75);
- assert_eq!(effect.mask_path.as_deref(), Some("/path/to/mask.mp4"));
- match effect.background {
- Some(SceneBackground::Color { color }) => assert_eq!(color, "#ff0080"),
- _ => panic!("expected color background"),
- }
}
}
diff --git a/crates/compositor/src/shaders.hlsl b/crates/compositor/src/shaders.hlsl
index 212c9b66f..b9d438d7d 100644
--- a/crates/compositor/src/shaders.hlsl
+++ b/crates/compositor/src/shaders.hlsl
@@ -154,73 +154,6 @@ float3 quad_inverse_bilinear(float2 P, float2 c00, float2 c10, float2 c11, float
return (r0.z > 0.5) ? r0 : r1;
}
-// Human skin, body prior and subject saliency detection in YCbCr:
-// Y (luminance), Cb (blue difference), Cr (red difference).
-float compute_person_mask(float2 uv, float2 qpx, float threshold, float feather)
-{
- float y = texY.Sample(samp, uv);
- float2 cbcr = texUV.Sample(samp, uv);
-
- // Anatomical portrait prior: Head and shoulders form a vertical rounded shape
- float2 torso_p = (uv - float2(0.5, 0.72)) * float2(1.8, 1.2);
- float torso_d = length(torso_p);
- float2 head_p = (uv - float2(0.5, 0.45)) * float2(2.5, 2.0);
- float head_d = length(head_p);
- float body_prior = saturate(1.0 - min(torso_d, head_d));
-
- // Skin tone probability in normalized YCbCr space:
- // Cb in [0.36, 0.50], Cr in [0.54, 0.70]
- float cb_d = abs(cbcr.x - 0.43);
- float cr_d = abs(cbcr.y - 0.61);
- float is_skin = saturate(1.0 - (cb_d * 7.5 + cr_d * 6.5));
-
- // High contrast/edge energy
- float2 delta = float2(1.5 / max(qpx.x, 1.0), 1.5 / max(qpx.y, 1.0));
- float y_l = texY.Sample(samp, uv - float2(delta.x, 0.0));
- float y_r = texY.Sample(samp, uv + float2(delta.x, 0.0));
- float y_u = texY.Sample(samp, uv - float2(0.0, delta.y));
- float y_d = texY.Sample(samp, uv + float2(0.0, delta.y));
- float edge = abs(y_l - y_r) + abs(y_u - y_d);
-
- // Top room background suppression (ceiling / top room corners are never the speaker)
- float center_dist_x = abs(uv.x - 0.5) * 2.0;
- float center_dist_y = uv.y;
- float corner_dist = saturate((1.0 - center_dist_y) * (center_dist_x * 0.9 + 0.1));
- float subject_envelope = saturate(1.0 - corner_dist * 1.6) * saturate(center_dist_y * 2.2);
-
- // Combined score
- float score = body_prior * 0.55 + is_skin * 0.40 + subject_envelope * 0.35 + edge * 0.20;
-
- // User threshold and feathering
- float center_t = lerp(0.20, 0.75, saturate(threshold));
- float half_f = max(feather * 0.25, 0.02);
-
- float min_t = max(center_t - half_f, 0.0);
- float max_t = min(center_t + half_f, 1.0);
-
- float mask = smoothstep(min_t, max_t, score);
- return saturate(mask);
-}
-
-float3 sample_blur_yuv(float2 uv, float intensity, float2 qpx)
-{
- float radius = max(intensity * 12.0, 4.0);
- float2 step = radius / max(qpx, 1.0);
- float3 sum = 0.0;
- float total = 0.0;
- [unroll] for (int dy = -2; dy <= 2; dy++)
- {
- [unroll] for (int dx = -2; dx <= 2; dx++)
- {
- float2 offset = float2(dx, dy) * step;
- float weight = 1.0 / (1.0 + length(float2(dx, dy)));
- sum += sample_yuv(saturate(uv + offset)) * weight;
- total += weight;
- }
- }
- return sum / max(total, 1e-4);
-}
-
float4 ps_main(VSOut i) : SV_Target
{
// mode 13 : SPRITE DE CURSEUR posé sur l'écran incliné. Même warp que le mode 8, mais
@@ -477,7 +410,6 @@ float4 ps_main(VSOut i) : SV_Target
}
float3 rgb;
- float alpha = color.a;
if (mode < 0.5)
{
// flou de mouvement par vélocité (§8) : pour CE pixel sortie, uv à la frame
@@ -503,31 +435,13 @@ float4 ps_main(VSOut i) : SV_Target
}
rgb = acc / (float) taps;
}
-
- // Effet d'arrière-plan webcam : fx.z (1=cutout, 2=blur, 3=custom)
- float effect_mode = fx.z;
- if (effect_mode > 0.5)
- {
- float person = compute_person_mask(uv_now, quad_px, fx.y, fx.x);
- if (effect_mode > 2.5)
- {
- rgb = lerp(color.rgb, rgb, person);
- }
- else if (effect_mode > 1.5)
- {
- float3 bg_blur = sample_blur_yuv(uv_now, fx.w, quad_px);
- rgb = lerp(bg_blur, rgb, person);
- }
- else
- {
- alpha *= person;
- }
- }
}
else
{
rgb = color.rgb;
}
+
+ float alpha = color.a;
if (radius_px > 0.0)
{
// `quad_px` est en px de SORTIE (le render target porte la géométrie de sortie) et
diff --git a/electron/electron-env.d.ts b/electron/electron-env.d.ts
index e140a4e37..d76fad663 100644
--- a/electron/electron-env.d.ts
+++ b/electron/electron-env.d.ts
@@ -98,6 +98,15 @@ interface Window {
message?: string;
error?: string;
}>;
+ writeDerivedMedia: (
+ data: ArrayBuffer,
+ fileName: string,
+ ) => Promise<{
+ success: boolean;
+ path?: string;
+ message?: string;
+ error?: string;
+ }>;
storeRecordedSession: (
payload: import("../src/lib/recordingSession").StoreRecordedSessionInput,
) => Promise<{
diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.ts
index aa2014670..13812e94c 100644
--- a/electron/ipc/handlers.ts
+++ b/electron/ipc/handlers.ts
@@ -107,6 +107,12 @@ const ALLOWED_IMPORT_VIDEO_EXTENSIONS = new Set([
".ts",
]);
const PREVIEW_AUDIO_DIR = path.join(app.getPath("userData"), "preview-audio");
+// Derived export artifacts (pre-segmented webcam tracks, …). Deliberately NOT
+// RECORDINGS_DIR: these are regenerable byproducts of one export run, not takes,
+// and `get-recorded-video-path` returns the alphabetically last `.webm` in there —
+// a `webcam-segmented-*.webm` would sort after `recording-*` and be handed back as
+// "the latest recording".
+const DERIVED_MEDIA_DIR = path.join(app.getPath("userData"), "derived-media");
const nativeMacCaptureEvents = new EventEmitter();
// Enumeration walks every display and window and grabs a thumbnail of each, so it
@@ -3427,6 +3433,54 @@ export function registerIpcHandlers(
}
});
+ // A derived export artifact, NOT a take: no recording-session state, no
+ // `.session.json` manifest, no media links, no cursor-telemetry flush.
+ // `store-recorded-video` does all of that (it is the session finaliser) and is
+ // the wrong door for a file an export regenerates every run.
+ ipcMain.handle("write-derived-media", async (_, data: ArrayBuffer, fileName: string) => {
+ try {
+ const trimmed = typeof fileName === "string" ? fileName.trim() : "";
+ if (!trimmed) {
+ return { success: false, message: "Invalid derived media file name" };
+ }
+ // `base` differs from the input for `a/b`, `a\b` and absolute paths — but NOT
+ // for "." or "..", which `path.join` would then resolve back out of the
+ // directory. `resolveRecordingOutputPath` rejects those explicitly; so does this.
+ const parsedName = path.parse(trimmed);
+ if (
+ parsedName.base !== trimmed ||
+ path.isAbsolute(trimmed) ||
+ trimmed === "." ||
+ trimmed === ".."
+ ) {
+ return {
+ success: false,
+ message: "Derived media file name must not contain path segments",
+ };
+ }
+
+ await fs.mkdir(DERIVED_MEDIA_DIR, { recursive: true });
+ const outputPath = path.join(DERIVED_MEDIA_DIR, parsedName.base);
+ await fs.writeFile(outputPath, Buffer.from(data));
+ // The file lives outside RECORDINGS_DIR, so the read gate would refuse it.
+ // We just wrote it, so it is approved by construction.
+ approveFilePath(outputPath);
+
+ return {
+ success: true,
+ path: outputPath,
+ message: "Derived media written successfully",
+ };
+ } catch (error) {
+ console.error("Failed to write derived media:", error);
+ return {
+ success: false,
+ message: "Failed to write derived media",
+ error: String(error),
+ };
+ }
+ });
+
ipcMain.handle("get-recorded-video-path", async () => {
try {
if (currentRecordingSession?.screenVideoPath) {
diff --git a/electron/main.ts b/electron/main.ts
index a27e038ef..a85629bf3 100644
--- a/electron/main.ts
+++ b/electron/main.ts
@@ -140,11 +140,6 @@ function createWindow() {
return;
}
- if (process.env.OPENSCREEN_START_EDITOR === "1" || process.env.OPENSCREEN_EDITOR === "1") {
- mainWindow = createEditorWindow();
- return;
- }
-
mainWindow = createHudOverlayWindow();
}
diff --git a/electron/preload.ts b/electron/preload.ts
index 6aff16407..37da9590c 100644
--- a/electron/preload.ts
+++ b/electron/preload.ts
@@ -159,6 +159,11 @@ contextBridge.exposeInMainWorld("electronAPI", {
storeRecordedVideo: (videoData: ArrayBuffer, fileName: string) => {
return ipcRenderer.invoke("store-recorded-video", videoData, fileName);
},
+ /** Derived export artifact (pre-segmented webcam track, …) → userData/derived-media.
+ * Unlike storeRecordedVideo this touches no recording-session state. */
+ writeDerivedMedia: (data: ArrayBuffer, fileName: string) => {
+ return ipcRenderer.invoke("write-derived-media", data, fileName);
+ },
storeRecordedSession: (payload: StoreRecordedSessionInput) => {
return ipcRenderer.invoke("store-recorded-session", payload);
},
diff --git a/src/cli/CliExportRunner.tsx b/src/cli/CliExportRunner.tsx
index 6193175df..9aa47d46d 100644
--- a/src/cli/CliExportRunner.tsx
+++ b/src/cli/CliExportRunner.tsx
@@ -27,7 +27,7 @@ import { assetCameraSource } from "@/lib/ai-edition/timeline/camera";
import { resolveClipSourceEndSec } from "@/lib/ai-edition/timeline/clipDuration";
import { DEFAULT_ZOOM_DEPTH, ZOOM_DEPTH_SCALES } from "@/lib/ai-edition/timeline/zoom-scale";
import { buildAutoZoomSuggestions } from "@/lib/ai-edition/timeline/zoom-suggestions";
-import { prepareSegmentedWebcamTrack } from "@/lib/ai-edition/webcamSegmentation";
+import { applySegmentedWebcamTracks } from "@/lib/ai-edition/webcamSegmentation";
import type { CliDoneResult, CliExportRequest } from "@/lib/cliContracts";
import { GIF_SIZE_PRESETS, type GifSizePreset } from "@/lib/exporter";
import { calculateMp4ExportSettings } from "@/lib/exporter/mp4ExportSettings";
@@ -264,46 +264,29 @@ async function runExport(request: CliExportRequest): Promise<CliDoneResult> {
aspectRatioValue,
});
- let clips = buildNativeClipList(axcutDocument);
- if (clips.length === 0) {
+ const builtClips = buildNativeClipList(axcutDocument);
+ if (builtClips.length === 0) {
throw new Error("The project's timeline has no visible clips to export");
}
const sceneDesc = buildSceneDescription(axcutDocument);
const settings = getEditorSettings(axcutDocument);
- if (settings.webcamBackgroundMode !== "none") {
- const processedMap = new Map<string, string>();
- for (const clip of clips) {
- if (clip.webcamPath && !processedMap.has(clip.webcamPath)) {
- const processedPath = await prepareSegmentedWebcamTrack(
- clip.webcamPath,
- {
- mode: settings.webcamBackgroundMode,
- blurIntensity: settings.webcamBlurIntensity,
- wallpaper: settings.webcamWallpaper,
- },
- (prog) => {
- window.electronAPI.cliProgress({
- percentage: Math.min(100, prog * 100),
- currentFrame: Math.round(prog * 100),
- totalFrames: 100,
- estimatedTimeRemaining: 0,
- });
- },
- );
- processedMap.set(clip.webcamPath, processedPath);
- }
- }
- clips = clips.map((clip) =>
- clip.webcamPath && processedMap.has(clip.webcamPath)
- ? { ...clip, webcamPath: processedMap.get(clip.webcamPath)! }
- : clip,
- );
- sceneDesc.webcamEffect = {
- mode: "presegmented",
- blurIntensity: settings.webcamBackgroundMode === "transparent" ? -1 : 0,
- };
- }
+ const clips = await applySegmentedWebcamTracks(
+ builtClips,
+ {
+ mode: settings.webcamBackgroundMode,
+ blurIntensity: settings.webcamBlurIntensity,
+ wallpaper: settings.webcamWallpaper,
+ },
+ (prog) => {
+ window.electronAPI.cliProgress({
+ percentage: Math.min(100, prog * 100),
+ currentFrame: Math.round(prog * 100),
+ totalFrames: 100,
+ estimatedTimeRemaining: 0,
+ });
+ },
+ );
const sceneJson = JSON.stringify(sceneDesc);
// Progress: native pushes raw encoded-frame counts; totals and pacing are
diff --git a/src/components/ai-edition/ExportDialog.tsx b/src/components/ai-edition/ExportDialog.tsx
index 8f1cf39e6..ad618ad13 100644
--- a/src/components/ai-edition/ExportDialog.tsx
+++ b/src/components/ai-edition/ExportDialog.tsx
@@ -22,7 +22,7 @@ import type { AxcutDocument } from "@/lib/ai-edition/schema";
import { getEditorSettings } from "@/lib/ai-edition/store/editorSettings";
import { assetCameraSource } from "@/lib/ai-edition/timeline/camera";
import { resolveClipSourceEndSec } from "@/lib/ai-edition/timeline/clipDuration";
-import { prepareSegmentedWebcamTrack } from "@/lib/ai-edition/webcamSegmentation";
+import { applySegmentedWebcamTracks } from "@/lib/ai-edition/webcamSegmentation";
import {
type ExportFormat,
type ExportProgress,
@@ -310,43 +310,25 @@ export function ExportDialog({ open, onClose, document }: ExportDialogProps) {
});
});
try {
- let exportClips = clips;
const sceneDesc = buildSceneDescription(document);
const settings = getEditorSettings(document);
- if (settings.webcamBackgroundMode !== "none") {
- const processedMap = new Map<string, string>();
- for (const clip of exportClips) {
- if (clip.webcamPath && !processedMap.has(clip.webcamPath)) {
- const processedPath = await prepareSegmentedWebcamTrack(
- clip.webcamPath,
- {
- mode: settings.webcamBackgroundMode,
- blurIntensity: settings.webcamBlurIntensity,
- wallpaper: settings.webcamWallpaper,
- },
- (prog) => {
- setProgress({
- currentFrame: Math.round(prog * 100),
- totalFrames: 100,
- percentage: Math.round(prog * 100),
- estimatedTimeRemaining: 0,
- });
- },
- );
- processedMap.set(clip.webcamPath, processedPath);
- }
- }
- exportClips = exportClips.map((clip) =>
- clip.webcamPath && processedMap.has(clip.webcamPath)
- ? { ...clip, webcamPath: processedMap.get(clip.webcamPath)! }
- : clip,
- );
- sceneDesc.webcamEffect = {
- mode: "presegmented",
- blurIntensity: settings.webcamBackgroundMode === "transparent" ? -1 : 0,
- };
- }
+ const exportClips = await applySegmentedWebcamTracks(
+ clips,
+ {
+ mode: settings.webcamBackgroundMode,
+ blurIntensity: settings.webcamBlurIntensity,
+ wallpaper: settings.webcamWallpaper,
+ },
+ (prog) => {
+ setProgress({
+ currentFrame: Math.round(prog * 100),
+ totalFrames: 100,
+ percentage: Math.round(prog * 100),
+ estimatedTimeRemaining: 0,
+ });
+ },
+ );
const sceneJson = JSON.stringify(sceneDesc);
const outDims = tierOutputDims(quality);
diff --git a/src/components/ai-edition/NativeCompositorOverlay.tsx b/src/components/ai-edition/NativeCompositorOverlay.tsx
index 710e90c74..75029c1f0 100644
--- a/src/components/ai-edition/NativeCompositorOverlay.tsx
+++ b/src/components/ai-edition/NativeCompositorOverlay.tsx
@@ -81,6 +81,25 @@ export function NativeCompositorOverlay() {
// `null` = document pas encore chargé (on attend) ; `{}` = chargé sans asset (→ fixture) ;
// `{screenPath,…}` = vraies sources de l'asset primaire.
+ const settings = useMemo(() => getEditorSettings(document), [document]);
+
+ // The real camera path, independent of whether NATIVE is the one drawing it: the scene
+ // still needs it to look up the probed webcam size, which shapes the PiP box.
+ const cameraPath = useMemo(() => {
+ if (!document) return undefined;
+ const primary =
+ document.assets.find((a) => a.id === document.project.primaryAssetId) ?? document.assets[0];
+ return primary ? assetCameraSource(primary).path || undefined : undefined;
+ }, [document]);
+
+ // With a background effect on, WebcamOverlay's segmentation canvas paints the camera
+ // (background included) over this slot. Handing the same camera to the native view too
+ // would draw the RAW frame underneath it — invisible behind an opaque blur/custom
+ // result, but plainly visible through the alpha of a transparent cut-out, which made
+ // cut-out mode look like it did nothing. Withholding the source is what makes the app
+ // the sole owner of that layer; `has_webcam` gates only the draw, never the layout.
+ const appOwnsWebcamLayer = settings.webcamBackgroundMode !== "none";
+
const sources = useMemo(() => {
if (!document) {
return null;
@@ -95,13 +114,13 @@ export function NativeCompositorOverlay() {
// the one accessor, so it can never disagree with the scene or the export.
return {
screenPath: primary.originalPath,
- webcamPath: assetCameraSource(primary).path || undefined,
+ webcamPath: appOwnsWebcamLayer ? undefined : assetCameraSource(primary).path || undefined,
// sidecar convention (electron/ipc/handlers.ts readCursorRecordingFile) : la
// télémétrie curseur vit à côté de la vidéo tant qu'elle n'a pas bougé. Absente →
// le natif ignore juste le curseur (CursorTrack::load échoue silencieusement).
cursorPath: `${primary.originalPath}.cursor.json`,
};
- }, [document]);
+ }, [document, appOwnsWebcamLayer]);
const ready = sources !== null;
const { viewId, error } = useNativeCompositorView(canvasRef, {
@@ -132,8 +151,10 @@ export function NativeCompositorOverlay() {
return;
}
try {
- const activeWebcamPath = sources && "webcamPath" in sources ? sources.webcamPath : undefined;
- const webcamSourceSize = activeWebcamPath ? getWebcamNativeSize(activeWebcamPath) : null;
+ // Deliberately `cameraPath`, not `sources.webcamPath`: the latter is withheld
+ // while the app owns the webcam layer, and losing the probed size here would
+ // reshape the PiP box out from under the segmentation canvas that fills it.
+ const webcamSourceSize = cameraPath ? getWebcamNativeSize(cameraPath) : null;
const scene = buildSceneDescription(document, webcamSourceSize);
setNativeScene(JSON.stringify(scene));
} catch (error) {
@@ -164,7 +185,6 @@ export function NativeCompositorOverlay() {
// n'a pas d'importance. Et ca ne peut pas lutter contre un drag de slider :
// `setLive` passe par `setDocument`, donc `document` a deja la NOUVELLE
// valeur a chaque tick -- la meme que celle que le handler vient de pousser.
- const settings = useMemo(() => getEditorSettings(document), [document]);
useEffect(() => {
const push = () => pushAllNativeParams(settings);
push();
diff --git a/src/components/ai-edition/RightPanes.tsx b/src/components/ai-edition/RightPanes.tsx
index 2e5be4276..497f45b62 100644
--- a/src/components/ai-edition/RightPanes.tsx
+++ b/src/components/ai-edition/RightPanes.tsx
@@ -13,7 +13,6 @@ import {
Layout as LayoutIcon,
Loader2,
MousePointerClick,
- Palette,
Sliders,
Trash2,
} from "lucide-react";
@@ -215,60 +214,22 @@ export function isSupportedBackgroundImage(type: string, fileName: string): bool
return IMAGE_EXTENSIONS.some((extension) => name.endsWith(extension));
}
-// Wallpaper picker — image / solid color / gradient tabs.
-//
-// Wallpapers round-trip through the legacyEditor envelope exactly as they did
-// in the v2 editor: gradient strings stay as-is, colors as `#hex`, and image
-// paths are restricted to `/wallpapers/...` or the user's own data: URLs from
-// the upload custom flow.
-function BackgroundSection() {
+/**
+ * The "upload custom wallpaper" concern: a hidden `<input type=file>` plus the reader
+ * that turns the pick into a `data:` URL.
+ *
+ * A hook rather than part of `WallpaperPicker` because WHERE the input may be mounted is
+ * the caller's problem. `BackgroundSection` renders the picker inside a Popover, and
+ * opening the OS file dialog takes focus, which closes the Popover — an input mounted
+ * inside it would unmount mid-pick and drop the file. That caller mounts `input` outside
+ * the Popover; inline callers mount it next to the picker.
+ */
+function useWallpaperFileInput(onPicked: (dataUrl: string) => void): {
+ pick: () => void;
+ input: ReactNode;
+} {
const ts = useScopedT("settings");
- const { settings, set, setLive, commit, hasDocument } = useEditorSettings();
- const [pickerOpen, setPickerOpen] = useState(false);
- // Seeded from what the project is actually using, so the picker opens on the tab the
- // user is already in rather than always on Image.
- const [tab, setTab] = useState<"image" | "color" | "gradient">(
- () => classifyWallpaper(settings.wallpaper).kind,
- );
- const fileInputRef = useRef<HTMLInputElement | null>(null);
- const customUrls = useMemoCustomWallpapers(settings.wallpaper);
-
- // The custom gradient editor emits continuously while the user drags a
- // color point / angle knob / brightness slider, so mirror the SliderCell
- // model: preview live with setLive, then persist once the changes settle.
- const gradientCommitTimer = useRef<number | null>(null);
- const handleGradientChange = useCallback(
- (state: GradientEditorState) => {
- setLive({ wallpaper: buildGradientFromEditor(state) });
- if (gradientCommitTimer.current !== null) {
- window.clearTimeout(gradientCommitTimer.current);
- }
- gradientCommitTimer.current = window.setTimeout(() => {
- gradientCommitTimer.current = null;
- void commit();
- }, 400);
- },
- [setLive, commit],
- );
- useEffect(
- () => () => {
- if (gradientCommitTimer.current !== null) {
- window.clearTimeout(gradientCommitTimer.current);
- }
- },
- [],
- );
-
- const isSelected = (value: string) => settings.wallpaper === value;
-
- const handleTabChange = (next: "image" | "color" | "gradient") => {
- setTab(next);
- };
-
- const handlePickFile = () => {
- if (!hasDocument) return;
- fileInputRef.current?.click();
- };
+ const ref = useRef<HTMLInputElement | null>(null);
const handleFileSelected = (e: ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
@@ -285,12 +246,40 @@ function BackgroundSection() {
toast.error(ts("background.imageReadFailed"));
return;
}
- void set({ wallpaper: dataUrl });
+ onPicked(dataUrl);
};
reader.onerror = () => toast.error(ts("background.imageReadFailed"));
reader.readAsDataURL(file);
};
+ return {
+ pick: () => ref.current?.click(),
+ input: (
+ <input
+ ref={ref}
+ type="file"
+ accept={IMAGE_ACCEPT}
+ style={{ display: "none" }}
+ onChange={handleFileSelected}
+ />
+ ),
+ };
+}
+
+// Wallpaper picker — image / solid color / gradient tabs.
+//
+// Wallpapers round-trip through the legacyEditor envelope exactly as they did
+// in the v2 editor: gradient strings stay as-is, colors as `#hex`, and image
+// paths are restricted to `/wallpapers/...` or the user's own data: URLs from
+// the upload custom flow.
+function BackgroundSection() {
+ const ts = useScopedT("settings");
+ const { settings, set, setLive, commit, hasDocument } = useEditorSettings();
+ const [pickerOpen, setPickerOpen] = useState(false);
+ const { pick: handlePickFile, input: fileInput } = useWallpaperFileInput((dataUrl) =>
+ set({ wallpaper: dataUrl }),
+ );
+
return (
<>
<div className={styles.sectionLabel}>{ts("background.title")}</div>
@@ -329,117 +318,21 @@ function BackgroundSection() {
className="w-auto border-0 bg-transparent p-0 shadow-none"
>
<div className={styles.bgPopover}>
- {/* role="tab" + aria-selected are what make the tablist above mean
- anything: without them a screen reader announces three plain
- buttons and never says which one is current. */}
- <div className={styles.paneTabs} role="tablist">
- <button
- type="button"
- role="tab"
- aria-selected={tab === "image"}
- className={tab === "image" ? styles.isActive : ""}
- onClick={() => handleTabChange("image")}
- >
- {ts("background.image")}
- </button>
- <button
- type="button"
- role="tab"
- aria-selected={tab === "color"}
- className={tab === "color" ? styles.isActive : ""}
- onClick={() => handleTabChange("color")}
- >
- {ts("background.color")}
- </button>
- <button
- type="button"
- role="tab"
- aria-selected={tab === "gradient"}
- className={tab === "gradient" ? styles.isActive : ""}
- onClick={() => handleTabChange("gradient")}
- >
- {ts("background.gradient")}
- </button>
- </div>
- {tab === "image" ? (
- <>
- <button
- type="button"
- className={styles.uploadBtn}
- disabled={!hasDocument}
- onClick={handlePickFile}
- >
- {ts("background.uploadCustom")}
- </button>
- <div className={styles.bgGrid}>
- {customUrls.map((url) => (
- <button
- type="button"
- key={`custom-${url.slice(-32)}`}
- className={`${styles.bgThumb} ${isSelected(url) ? styles.isActive : ""}`}
- style={{ background: `center/cover no-repeat url(${url})` }}
- aria-label={ts("background.customWallpaper")}
- disabled={!hasDocument}
- onClick={() => void set({ wallpaper: url })}
- />
- ))}
- {WALLPAPER_PATHS.map((path, i) => {
- // Grid swatch paints the small pre-generated thumbnail (see
- // WALLPAPER_THUMB_PATHS) — selecting it still stores/applies `path`,
- // the full-res original, unchanged.
- const previewUrl = resolveImageWallpaperUrl(WALLPAPER_THUMB_PATHS[i]);
- return (
- <button
- type="button"
- key={path}
- className={`${styles.bgThumb} ${isSelected(path) ? styles.isActive : ""}`}
- style={{ background: `center/cover no-repeat url(${previewUrl})` }}
- aria-label={ts("background.imageLabel", { index: i + 1 })}
- disabled={!hasDocument}
- onClick={() => void set({ wallpaper: path })}
- />
- );
- })}
- </div>
- </>
- ) : tab === "color" ? (
- <BackgroundColorTab
- value={settings.wallpaper}
- hasDocument={hasDocument}
- isSelected={isSelected}
- onPick={(color) => void set({ wallpaper: color })}
- />
- ) : (
- <>
- <div className={styles.bgGrid}>
- {GRAD_PRESETS.map((bg, i) => (
- <button
- type="button"
- key={bg}
- className={`${styles.bgThumb} ${isSelected(bg) ? styles.isActive : ""}`}
- style={{ background: bg }}
- aria-label={ts("background.gradientLabel", { index: i + 1 })}
- disabled={!hasDocument}
- onClick={() => void set({ wallpaper: bg })}
- />
- ))}
- </div>
- {hasDocument ? <GradientEditor onChange={handleGradientChange} /> : null}
- </>
- )}
+ <WallpaperPicker
+ value={settings.wallpaper}
+ hasDocument={hasDocument}
+ onChange={(url) => void set({ wallpaper: url })}
+ onLiveChange={(url) => setLive({ wallpaper: url })}
+ onCommit={commit}
+ onPickFile={handlePickFile}
+ />
</div>
</PopoverContent>
</Popover>
{/* Stays mounted OUTSIDE the popover: opening the OS file dialog takes focus,
which closes the popover and would unmount the input mid-pick, dropping the
file. It has no layout to cost us here. */}
- <input
- ref={fileInputRef}
- type="file"
- accept={IMAGE_ACCEPT}
- style={{ display: "none" }}
- onChange={handleFileSelected}
- />
+ {fileInput}
{/* Reads in the order it acts: pick a background, then blur it. Lived under
"Effects" while that was a separate facet, which is how a control named
"Blur BG" ended up in the tab that doesn't say background. */}
@@ -613,6 +506,9 @@ export interface WallpaperPickerProps {
onLiveChange?: (val: string) => void;
onCommit?: () => void;
updateNativeBackground?: boolean;
+ /** Opens the OS file dialog. The hidden `<input>` it clicks belongs to the caller
+ * (see `useWallpaperFileInput`): where it may be mounted depends on the caller. */
+ onPickFile: () => void;
}
export function WallpaperPicker({
@@ -622,10 +518,14 @@ export function WallpaperPicker({
onLiveChange,
onCommit,
updateNativeBackground = true,
+ onPickFile,
}: WallpaperPickerProps) {
const ts = useScopedT("settings");
- const [tab, setTab] = useState<"image" | "color" | "gradient">("image");
- const fileInputRef = useRef<HTMLInputElement | null>(null);
+ // Seeded from what is actually in use, so the picker opens on the tab the user is
+ // already in rather than always on Image.
+ const [tab, setTab] = useState<"image" | "color" | "gradient">(
+ () => classifyWallpaper(value).kind,
+ );
const customUrls = useMemoCustomWallpapers(value);
const gradientCommitTimer = useRef<number | null>(null);
@@ -659,37 +559,16 @@ export function WallpaperPicker({
setTab(next);
};
- const handlePickFile = () => {
- if (!hasDocument) return;
- fileInputRef.current?.click();
- };
-
- const handleFileSelected = (e: ChangeEvent<HTMLInputElement>) => {
- const file = e.target.files?.[0];
- e.target.value = "";
- if (!file) return;
- if (!isSupportedBackgroundImage(file.type, file.name)) {
- toast.error(ts("background.unsupportedImage"));
- return;
- }
- const reader = new FileReader();
- reader.onload = () => {
- const dataUrl = typeof reader.result === "string" ? reader.result : "";
- if (!dataUrl) {
- toast.error(ts("background.imageReadFailed"));
- return;
- }
- onChange(dataUrl);
- };
- reader.onerror = () => toast.error(ts("background.imageReadFailed"));
- reader.readAsDataURL(file);
- };
-
return (
<>
+ {/* role="tab" + aria-selected are what make the tablist mean anything: without
+ them a screen reader announces three plain buttons and never says which one
+ is current. */}
<div className={styles.paneTabs} role="tablist">
<button
type="button"
+ role="tab"
+ aria-selected={tab === "image"}
className={tab === "image" ? styles.isActive : ""}
onClick={() => handleTabChange("image")}
>
@@ -697,6 +576,8 @@ export function WallpaperPicker({
</button>
<button
type="button"
+ role="tab"
+ aria-selected={tab === "color"}
className={tab === "color" ? styles.isActive : ""}
onClick={() => handleTabChange("color")}
>
@@ -704,6 +585,8 @@ export function WallpaperPicker({
</button>
<button
type="button"
+ role="tab"
+ aria-selected={tab === "gradient"}
className={tab === "gradient" ? styles.isActive : ""}
onClick={() => handleTabChange("gradient")}
>
@@ -716,17 +599,10 @@ export function WallpaperPicker({
type="button"
className={styles.uploadBtn}
disabled={!hasDocument}
- onClick={handlePickFile}
+ onClick={onPickFile}
>
{ts("background.uploadCustom")}
</button>
- <input
- ref={fileInputRef}
- type="file"
- accept={IMAGE_ACCEPT}
- style={{ display: "none" }}
- onChange={handleFileSelected}
- />
<div className={styles.bgGrid}>
{customUrls.map((url) => (
<button
@@ -785,33 +661,6 @@ export function WallpaperPicker({
);
}
-// Wallpaper picker — image / solid color / gradient tabs.
-//
-// Wallpapers round-trip through the legacyEditor envelope exactly as they did
-// in the v2 editor: gradient strings stay as-is, colors as `#hex`, and image
-// paths are restricted to `/wallpapers/...` or the user's own data: URLs from
-// the upload custom flow.
-export function BackgroundPane() {
- const ts = useScopedT("settings");
- const { settings, set, setLive, commit, hasDocument } = useEditorSettings();
-
- return (
- <Pane
- title={ts("background.title")}
- icon={<Palette size={14} />}
- helpText={ts("background.help")}
- >
- <WallpaperPicker
- value={settings.wallpaper}
- hasDocument={hasDocument}
- onChange={(url) => void set({ wallpaper: url })}
- onLiveChange={(url) => setLive({ wallpaper: url })}
- onCommit={commit}
- />
- </Pane>
- );
-}
-
/** Which clip a transcript cut lands on. The clip id is what makes the cut land on ONE
* block: two clips over the same media share an asset and a source range, so an
* asset-only target had the trim show up on both of them (and on the wrong one in the
@@ -2091,6 +1940,9 @@ const CAMERA_BACKGROUND_MODES: Array<{
export function LayoutPane() {
const ts = useScopedT("settings");
const { settings, set, setLive, commit, hasDocument } = useEditorSettings();
+ const { pick: handlePickWebcamWallpaper, input: webcamWallpaperInput } = useWallpaperFileInput(
+ (dataUrl) => set({ webcamWallpaper: dataUrl }),
+ );
const document = useProjectStore((s) => s.document);
// A project can hold clips with no camera attached at all (plain imports or a
// recording made without a webcam). Keep the saved camera preference for later, but
@@ -2337,27 +2189,16 @@ export function LayoutPane() {
</div>
{settings.webcamBackgroundMode === "blur" ? (
<div className={styles.sliderGrid}>
- <div className={`${styles.sliderCell} ${styles.full}`}>
- <div className={styles.head}>
- <span className={styles.label}>{ts("layout.webcamBlurIntensity")}</span>
- <span className={styles.val}>{Math.round(settings.webcamBlurIntensity * 100)}%</span>
- </div>
- <input
- type="range"
- min={0}
- max={100}
- step={1}
- defaultValue={Math.round(settings.webcamBlurIntensity * 100)}
- disabled={layoutControlsDisabled}
- onChange={(e) => {
- const next = Number(e.target.value) / 100;
- setLive({ webcamBlurIntensity: next });
- }}
- onMouseUp={() => void commit()}
- onTouchEnd={() => void commit()}
- onKeyUp={() => void commit()}
- />
- </div>
+ <SliderCell
+ label={ts("layout.webcamBlurIntensity")}
+ value={Math.round(settings.webcamBlurIntensity * 100)}
+ min={0}
+ max={100}
+ suffix="%"
+ disabled={layoutControlsDisabled}
+ onChange={(next) => setLive({ webcamBlurIntensity: next / 100 })}
+ onCommit={() => void commit()}
+ />
</div>
) : null}
{settings.webcamBackgroundMode === "custom" ? (
@@ -2369,7 +2210,9 @@ export function LayoutPane() {
onLiveChange={(url) => setLive({ webcamWallpaper: url })}
onCommit={commit}
updateNativeBackground={false}
+ onPickFile={handlePickWebcamWallpaper}
/>
+ {webcamWallpaperInput}
</div>
) : null}
<div className={styles.sectionLabel}>{ts("layout.webcamFraming")}</div>
diff --git a/src/components/ai-edition/WebcamOverlay.test.tsx b/src/components/ai-edition/WebcamOverlay.test.tsx
index 15c94be31..a7dd2d98c 100644
--- a/src/components/ai-edition/WebcamOverlay.test.tsx
+++ b/src/components/ai-edition/WebcamOverlay.test.tsx
@@ -90,6 +90,29 @@ function baseProps(currentTimeSec: number) {
};
}
+const baseLegacyEditor = {
+ wallpaper: "#000000",
+ shadowIntensity: 0,
+ borderRadius: 0,
+ padding: 0,
+ showBlur: false,
+ motionBlurAmount: 0,
+ webcamSizePreset: 25,
+ webcamMaskShape: "rectangle",
+ webcamLayoutPreset: "picture-in-picture",
+ webcamMirrored: false,
+ webcamReactiveZoom: false,
+ webcamWallpaper: "#ff0080",
+ webcamBlurIntensity: 0.5,
+ cursorShow: false,
+ cursorSize: 1,
+ cursorSmoothing: 0,
+ cursorMotionBlur: 0,
+ cursorClickBounce: 0,
+ cursorTheme: "default",
+ cursorClipToBounds: false,
+};
+
describe("WebcamOverlay (per-clip camera resolution)", () => {
afterEach(() => {
cleanup();
@@ -155,31 +178,13 @@ describe("WebcamOverlay (per-clip camera resolution)", () => {
expect(container.querySelector("video")).toBeTruthy();
});
- it("renders background container when custom or blur background mode is active", () => {
+ // The background is painted INTO the segmentation canvas (colour, gradient and image
+ // alike), which is also what gets encoded for export — so the canvas being mounted is
+ // what "the effect is on" means. An extra CSS background layer used to sit behind it
+ // and was either invisible or a second, differently-painted copy of the same wallpaper.
+ it("mounts the segmentation canvas when a webcam background mode is active", () => {
const doc = makeDocument();
- doc.legacyEditor = {
- wallpaper: "#000000",
- shadowIntensity: 0,
- borderRadius: 0,
- padding: 0,
- showBlur: false,
- motionBlurAmount: 0,
- webcamSizePreset: 25,
- webcamMaskShape: "rectangle",
- webcamLayoutPreset: "picture-in-picture",
- webcamMirrored: false,
- webcamReactiveZoom: false,
- webcamBackgroundMode: "custom",
- webcamWallpaper: "#ff0080",
- webcamBlurIntensity: 0.5,
- cursorShow: false,
- cursorSize: 1,
- cursorSmoothing: 0,
- cursorMotionBlur: 0,
- cursorClickBounce: 0,
- cursorTheme: "default",
- cursorClipToBounds: false,
- };
+ doc.legacyEditor = { ...baseLegacyEditor, webcamBackgroundMode: "custom" };
useProjectStore.setState({
projectId: "proj_test",
document: doc,
@@ -193,10 +198,28 @@ describe("WebcamOverlay (per-clip camera resolution)", () => {
});
const { container } = render(<WebcamOverlay {...baseProps(2)} />);
- const video = container.querySelector("video");
- expect(video).toBeTruthy();
- const bg = container.querySelector("[aria-hidden='true']");
- expect(bg).toBeTruthy();
- expect((bg as HTMLElement)?.style.backgroundColor).toBe("rgb(255, 0, 128)");
+ // The <video> stays mounted as the decode/clock source even with an effect on.
+ expect(container.querySelector("video")).toBeTruthy();
+ expect(container.querySelector("canvas")).toBeTruthy();
+ });
+
+ it("does not mount the segmentation canvas when the background mode is none", () => {
+ const doc = makeDocument();
+ doc.legacyEditor = { ...baseLegacyEditor, webcamBackgroundMode: "none" };
+ useProjectStore.setState({
+ projectId: "proj_test",
+ document: doc,
+ revision: 1,
+ status: "ready",
+ error: null,
+ sourceDurationSec: 0,
+ currentTimeSec: 2,
+ dirty: false,
+ lastSavedAt: new Date(),
+ });
+
+ const { container } = render(<WebcamOverlay {...baseProps(2)} />);
+ expect(container.querySelector("video")).toBeTruthy();
+ expect(container.querySelector("canvas")).toBeNull();
});
});
diff --git a/src/components/ai-edition/WebcamOverlay.tsx b/src/components/ai-edition/WebcamOverlay.tsx
index 6c7640c64..e15b49db6 100644
--- a/src/components/ai-edition/WebcamOverlay.tsx
+++ b/src/components/ai-edition/WebcamOverlay.tsx
@@ -16,11 +16,7 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { toFileUrl } from "@/components/video-editor/projectPersistence";
-import type {
- WebcamBackgroundMode,
- WebcamLayoutPreset,
- WebcamMaskShape,
-} from "@/components/video-editor/types";
+import type { WebcamLayoutPreset, WebcamMaskShape } from "@/components/video-editor/types";
import type { AxcutClip } from "@/lib/ai-edition/schema";
import { useProjectStore } from "@/lib/ai-edition/store/projectStore";
import { useEditorSettings } from "@/lib/ai-edition/store/useEditorSettings";
@@ -31,8 +27,10 @@ import {
resolveCameraSyncTarget,
} from "@/lib/ai-edition/timeline/playback-clock";
import { locateVirtualPosition } from "@/lib/ai-edition/timeline/virtual-preview";
-import { renderSegmentedWebcam } from "@/lib/ai-edition/webcamSegmentation";
-import { classifyWallpaper, resolveImageWallpaperUrl } from "@/lib/wallpaper";
+import {
+ renderSegmentedWebcam,
+ type SegmentationRenderOptions,
+} from "@/lib/ai-edition/webcamSegmentation";
import { getCssClipPath } from "@/lib/webcamMaskShapes";
import { setWebcamNativeSize } from "@/native/webcamSizeCache";
import styles from "./NewEditorShell.module.css";
@@ -164,6 +162,16 @@ export function WebcamOverlay(props: WebcamOverlayProps) {
const canvasRef = useRef<HTMLCanvasElement | null>(null);
+ // Same idiom as the playback-clock loop above: the rAF tick reads the latest
+ // settings through a ref so the loop is not re-created on every document mutation.
+ const requestRenderRef = useRef<(() => void) | null>(null);
+ const segmentationOptionsRef = useRef<SegmentationRenderOptions>({
+ mode: settings.webcamBackgroundMode,
+ blurIntensity: settings.webcamBlurIntensity,
+ wallpaper: settings.webcamWallpaper,
+ crop: settings.webcamCropRegion,
+ });
+
// Neural segmentation render loop when background effect is active
useEffect(() => {
if (!videoEl || settings.webcamBackgroundMode === "none") return;
@@ -171,79 +179,116 @@ export function WebcamOverlay(props: WebcamOverlayProps) {
if (!canvas) return;
let isDestroyed = false;
- let isProcessing = false;
let raf = 0;
- const processFrame = async () => {
- if (isDestroyed) return;
- if (!isProcessing && videoEl.readyState >= 2 && !videoEl.paused) {
- isProcessing = true;
- try {
- await renderSegmentedWebcam(videoEl, canvas, {
- mode: settings.webcamBackgroundMode,
- blurIntensity: settings.webcamBlurIntensity,
- wallpaper: settings.webcamWallpaper,
- });
- } catch (err) {
- console.error("[WebcamOverlay] Segmentation error:", err);
- } finally {
- isProcessing = false;
- }
+ const render = async () => {
+ if (isDestroyed || videoEl.readyState < 2) return;
+ // Read through the ref, not the closure: the loop must survive a document
+ // mutation (a slider drag writes a new document on every tick) without being
+ // torn down and rebuilt.
+ try {
+ await renderSegmentedWebcam(videoEl, canvas, segmentationOptionsRef.current);
+ } catch (err) {
+ console.error("[WebcamOverlay] Segmentation error:", err);
}
- raf = window.requestAnimationFrame(processFrame);
};
- const renderOnce = () => {
- if (videoEl.readyState >= 2) {
- void renderSegmentedWebcam(videoEl, canvas, {
- mode: settings.webcamBackgroundMode,
- blurIntensity: settings.webcamBlurIntensity,
- wallpaper: settings.webcamWallpaper,
- });
+ // One frame in flight at a time, with a TRAILING re-run: dropping overlapping
+ // requests outright would leave the canvas on the pre-seek frame while scrubbing
+ // (each `seeked` lands while the previous render is still running, and nothing
+ // re-renders once it finishes because the rAF loop only draws while playing).
+ let inFlight: Promise<void> | null = null;
+ let rerunRequested = false;
+ const requestRender = () => {
+ if (inFlight) {
+ rerunRequested = true;
+ return;
}
+ const run = () => {
+ inFlight = render().finally(() => {
+ inFlight = null;
+ if (rerunRequested && !isDestroyed) {
+ rerunRequested = false;
+ run();
+ }
+ });
+ };
+ run();
+ };
+
+ const processFrame = () => {
+ if (isDestroyed) return;
+ if (!videoEl.paused) requestRender();
+ raf = window.requestAnimationFrame(processFrame);
};
- renderOnce();
- videoEl.addEventListener("seeked", renderOnce);
- videoEl.addEventListener("loadeddata", renderOnce);
+ requestRender();
+ // Exposed so the settings effect below can repaint a PAUSED preview: the rAF pump
+ // only draws while playing, so without this, dragging the blur slider or picking a
+ // wallpaper would change nothing on screen until playback resumed.
+ requestRenderRef.current = requestRender;
+ videoEl.addEventListener("seeked", requestRender);
+ videoEl.addEventListener("loadeddata", requestRender);
raf = window.requestAnimationFrame(processFrame);
return () => {
isDestroyed = true;
+ requestRenderRef.current = null;
window.cancelAnimationFrame(raf);
- videoEl.removeEventListener("seeked", renderOnce);
- videoEl.removeEventListener("loadeddata", renderOnce);
+ videoEl.removeEventListener("seeked", requestRender);
+ videoEl.removeEventListener("loadeddata", requestRender);
};
+ }, [videoEl, settings.webcamBackgroundMode]);
+
+ // Publish the latest options to the loop, then repaint. Keyed on the SCALAR crop
+ // values rather than `settings.webcamCropRegion`'s identity, which `getEditorSettings`
+ // rebuilds on every document mutation. The repaint matters because the rAF pump only
+ // draws while playing: without it, dragging the blur slider or picking a wallpaper
+ // would change nothing on screen until playback resumed.
+ const { x: cropX, y: cropY, width: cropW, height: cropH } = settings.webcamCropRegion;
+ useEffect(() => {
+ segmentationOptionsRef.current = {
+ mode: settings.webcamBackgroundMode,
+ blurIntensity: settings.webcamBlurIntensity,
+ wallpaper: settings.webcamWallpaper,
+ // Native crops the webcam with `webcam_crop` before the cover-fit; the canvas
+ // has to do the same or a cropped camera previews uncropped.
+ crop: { x: cropX, y: cropY, width: cropW, height: cropH },
+ };
+ requestRenderRef.current?.();
}, [
- videoEl,
settings.webcamBackgroundMode,
settings.webcamBlurIntensity,
settings.webcamWallpaper,
+ cropX,
+ cropY,
+ cropW,
+ cropH,
]);
if (!cameraTrack?.sourcePath || !cameraTrack.visible) {
return null;
}
- const bgStyle = buildWebcamBackgroundStyle(
- settings.webcamBackgroundMode,
- settings.webcamWallpaper,
- props.borderRadius,
- props.webcamMaskShape,
- );
-
+ // ponytail: the layout computes the final borderRadius (preset fraction for
+ // dual-frame/overlay, 0 for stack, half-circle for circle PiP, etc.). Push it onto
+ // the element that actually carries the pixels so it clips the camera content; the
+ // container stays a transparent, overflow:hidden wrapper.
const videoStyle: React.CSSProperties = {
display: hasError ? "none" : "block",
transform: settings.webcamMirrored ? "scaleX(-1)" : undefined,
clipPath: getCssClipPath(props.webcamMaskShape) ?? undefined,
borderRadius: `${props.borderRadius}px`,
- position: bgStyle ? "relative" : undefined,
- zIndex: bgStyle ? 1 : undefined,
};
+ // With an effect on, the pixels come from the segmentation canvas — background
+ // included, in every mode — so the <video> stays mounted only as the decode/clock
+ // source. There is deliberately no CSS background layer behind it: one existed and
+ // was either invisible (an opaque canvas covers it) or a second, differently-painted
+ // copy of the same wallpaper, which is exactly how preview and export drifted apart.
const isCustomEffect = settings.webcamBackgroundMode !== "none";
- const video = (
+ return (
<>
<video
key={cameraTrack.sourcePath}
@@ -287,58 +332,4 @@ export function WebcamOverlay(props: WebcamOverlayProps) {
) : null}
</>
);
-
- if (!bgStyle) {
- return video;
- }
-
- return (
- <div style={{ position: "relative", width: "100%", height: "100%" }}>
- <div style={bgStyle} aria-hidden="true" />
- {video}
- </div>
- );
-}
-
-function buildWebcamBackgroundStyle(
- mode: WebcamBackgroundMode,
- wallpaper: string,
- borderRadius: number,
- maskShape: WebcamMaskShape,
-): React.CSSProperties | null {
- if (mode === "none") return null;
- const base: React.CSSProperties = {
- position: "absolute",
- inset: 0,
- zIndex: 0,
- borderRadius: `${borderRadius}px`,
- clipPath: getCssClipPath(maskShape) ?? undefined,
- overflow: "hidden",
- };
- if (mode === "transparent") {
- return { ...base, backgroundColor: "transparent" };
- }
- if (mode === "blur") {
- return {
- ...base,
- backdropFilter: "blur(12px)",
- backgroundColor: "rgba(0, 0, 0, 0.2)",
- };
- }
- if (mode === "custom") {
- const w = classifyWallpaper(wallpaper);
- if (w.kind === "color") return { ...base, backgroundColor: w.value };
- if (w.kind === "gradient")
- return { ...base, backgroundImage: w.value, backgroundSize: "cover" };
- const url = resolveImageWallpaperUrl(w.path);
- if (!url) return base;
- return {
- ...base,
- backgroundImage: `url(${url})`,
- backgroundSize: "cover",
- backgroundPosition: "center",
- backgroundRepeat: "no-repeat",
- };
- }
- return null;
}
diff --git a/src/components/video-editor/types.ts b/src/components/video-editor/types.ts
index b00ca5367..243252703 100644
--- a/src/components/video-editor/types.ts
+++ b/src/components/video-editor/types.ts
@@ -23,7 +23,16 @@ export const DEFAULT_WEBCAM_MASK_SHAPE: WebcamMaskShape = "rectangle";
export const DEFAULT_WEBCAM_MIRRORED = false;
/** Background mode for the webcam feed (none, transparent AI cutout, blurred background, custom background). */
-export type WebcamBackgroundMode = "none" | "transparent" | "blur" | "custom";
+export const WEBCAM_BACKGROUND_MODES = ["none", "transparent", "blur", "custom"] as const;
+
+export type WebcamBackgroundMode = (typeof WEBCAM_BACKGROUND_MODES)[number];
+
+/** A `legacyEditor` envelope is user-writable JSON: anything that is not one of the four
+ * known modes has to fall back, or `renderSegmentedWebcam` matches no branch and encodes
+ * a blank webcam track. */
+export function isWebcamBackgroundMode(value: unknown): value is WebcamBackgroundMode {
+ return (WEBCAM_BACKGROUND_MODES as readonly unknown[]).includes(value);
+}
export const DEFAULT_WEBCAM_BACKGROUND_MODE: WebcamBackgroundMode = "none";
diff --git a/src/lib/ai-edition/store/editorSettings.test.ts b/src/lib/ai-edition/store/editorSettings.test.ts
index b43145d93..d7cfdfcf4 100644
--- a/src/lib/ai-edition/store/editorSettings.test.ts
+++ b/src/lib/ai-edition/store/editorSettings.test.ts
@@ -251,4 +251,22 @@ describe("patchEditorSettings", () => {
expect(snap.webcamWallpaper).toBe("#ff0080");
expect(snap.webcamBlurIntensity).toBe(0.8);
});
+
+ // `legacyEditor` is user-writable JSON. An unknown mode used to flow straight through
+ // as a WebcamBackgroundMode, so the export pre-render ran and `renderSegmentedWebcam`
+ // matched no branch — encoding a blank webcam track.
+ it("falls back to the default when the stored webcam background mode is unknown", () => {
+ const doc = {
+ ...baseDoc,
+ legacyEditor: { webcamBackgroundMode: "hologram" },
+ } as typeof baseDoc;
+ expect(getEditorSettings(doc).webcamBackgroundMode).toBe("none");
+ });
+
+ it("clamps a stored webcam blur intensity into 0..1", () => {
+ const tooHigh = { ...baseDoc, legacyEditor: { webcamBlurIntensity: 1000 } } as typeof baseDoc;
+ expect(getEditorSettings(tooHigh).webcamBlurIntensity).toBe(1);
+ const negative = { ...baseDoc, legacyEditor: { webcamBlurIntensity: -3 } } as typeof baseDoc;
+ expect(getEditorSettings(negative).webcamBlurIntensity).toBe(0);
+ });
});
diff --git a/src/lib/ai-edition/store/editorSettings.ts b/src/lib/ai-edition/store/editorSettings.ts
index 455f013ff..4892b577f 100644
--- a/src/lib/ai-edition/store/editorSettings.ts
+++ b/src/lib/ai-edition/store/editorSettings.ts
@@ -25,6 +25,7 @@ import {
DEFAULT_WEBCAM_POSITION,
DEFAULT_WEBCAM_REACTIVE_ZOOM,
DEFAULT_WEBCAM_SIZE_PRESET,
+ isWebcamBackgroundMode,
type WebcamBackgroundMode,
type WebcamLayoutPreset,
type WebcamMaskShape,
@@ -34,6 +35,7 @@ import {
import { DEFAULT_CURSOR_THEME_ID } from "@/lib/cursor/cursorThemes";
import { DEFAULT_WALLPAPER } from "@/lib/wallpaper";
import type { AspectRatio } from "@/utils/aspectRatioUtils";
+import { clamp01 } from "@/utils/math";
import type { AxcutDocument } from "../schema";
// ponytail: avoid dragging in lib/exporter full surface here — we only
@@ -245,12 +247,14 @@ export function getEditorSettings(doc: AxcutDocument | null | undefined): Editor
AUDIO_GAIN_DB_LIMIT,
Math.max(-AUDIO_GAIN_DB_LIMIT, num(legacy?.audioGainDb, 0)),
),
- webcamBackgroundMode:
- legacy?.webcamBackgroundMode ?? DEFAULT_EDITOR_SETTINGS.webcamBackgroundMode,
+ webcamBackgroundMode: isWebcamBackgroundMode(legacy?.webcamBackgroundMode)
+ ? legacy.webcamBackgroundMode
+ : DEFAULT_EDITOR_SETTINGS.webcamBackgroundMode,
webcamWallpaper: str(legacy?.webcamWallpaper, DEFAULT_EDITOR_SETTINGS.webcamWallpaper),
- webcamBlurIntensity: num(
- legacy?.webcamBlurIntensity,
- DEFAULT_EDITOR_SETTINGS.webcamBlurIntensity,
+ // Same 0-1 range the slider offers; unclamped, a stored 1000 reaches
+ // `blur(25000px)` on the preview canvas and wedges the compositing thread.
+ webcamBlurIntensity: clamp01(
+ num(legacy?.webcamBlurIntensity, DEFAULT_EDITOR_SETTINGS.webcamBlurIntensity),
),
cursor,
cursorShow: bool(legacy?.cursorShow, DEFAULT_EDITOR_SETTINGS.cursorShow),
diff --git a/src/lib/ai-edition/webcamSegmentation.test.ts b/src/lib/ai-edition/webcamSegmentation.test.ts
new file mode 100644
index 000000000..c4d49f366
--- /dev/null
+++ b/src/lib/ai-edition/webcamSegmentation.test.ts
@@ -0,0 +1,177 @@
+// @vitest-environment jsdom
+//
+// The MediaPipe result channel is a SINGLE callback slot: `onResults` holds one
+// listener and `send()` gives no way to tell two outstanding results apart. These
+// tests pin the protocol that makes that safe — one listener for the segmenter's
+// lifetime, one send in flight at a time, and every caller's promise settled
+// exactly once — because getting it wrong strands a promise, and a stranded
+// promise silently freezes the preview instead of failing.
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+type Listener = (results: { image: unknown; segmentationMask: unknown }) => void;
+
+/** Deliveries are queued so a test can control WHEN a send produces its result. */
+const pendingSends: Array<() => void> = [];
+let listener: Listener | null = null;
+let sendCount = 0;
+
+vi.mock("@mediapipe/selfie_segmentation", () => {
+ class FakeSelfieSegmentation {
+ setOptions() {
+ // options do not affect the protocol under test
+ }
+ initialize() {
+ return Promise.resolve();
+ }
+ onResults(fn: Listener) {
+ listener = fn;
+ }
+ send() {
+ sendCount += 1;
+ pendingSends.push(() => {
+ listener?.({
+ image: makeSource(640, 360),
+ segmentationMask: makeSource(256, 144),
+ });
+ });
+ return Promise.resolve();
+ }
+ }
+ return { SelfieSegmentation: FakeSelfieSegmentation };
+});
+
+/** Stand-in for a MediaPipe `GpuBuffer` — deliberately a DIFFERENT resolution for
+ * the mask than the image, which is the real behaviour of the landscape model. */
+function makeSource(width: number, height: number) {
+ const el = window.document.createElement("canvas");
+ el.width = width;
+ el.height = height;
+ return el;
+}
+
+function flushOneSend() {
+ const next = pendingSends.shift();
+ next?.();
+}
+
+function makeVideo(width = 640, height = 360): HTMLVideoElement {
+ const video = window.document.createElement("video");
+ Object.defineProperty(video, "videoWidth", { value: width, configurable: true });
+ Object.defineProperty(video, "videoHeight", { value: height, configurable: true });
+ return video;
+}
+
+// jsdom has no 2D backend; a recording stub is enough since these tests assert on
+// the promise protocol and the source rects, not on pixels.
+interface DrawCall {
+ args: unknown[];
+}
+const drawCalls: DrawCall[] = [];
+
+function installCanvasStub() {
+ HTMLCanvasElement.prototype.getContext = vi.fn(function stubGetContext(this: HTMLCanvasElement) {
+ return {
+ canvas: this,
+ filter: "none",
+ fillStyle: "",
+ globalCompositeOperation: "source-over",
+ save: () => undefined,
+ restore: () => undefined,
+ clearRect: () => undefined,
+ fillRect: () => undefined,
+ createLinearGradient: () => ({ addColorStop: () => undefined }),
+ drawImage: (...args: unknown[]) => {
+ drawCalls.push({ args });
+ },
+ };
+ }) as unknown as HTMLCanvasElement["getContext"];
+}
+
+describe("renderSegmentedWebcam (MediaPipe result channel)", () => {
+ beforeEach(() => {
+ // `listener` is deliberately NOT reset: `getSelfieSegmenter` caches the segmenter,
+ // so `onResults` is registered once for the whole file — which is the property
+ // under test. Clearing it here would orphan every later delivery.
+ drawCalls.length = 0;
+ sendCount = 0;
+ installCanvasStub();
+ });
+
+ it("resolves the caller's promise when MediaPipe delivers a result", async () => {
+ const { renderSegmentedWebcam } = await import("./webcamSegmentation");
+ const canvas = window.document.createElement("canvas");
+
+ let settled = false;
+ const done = renderSegmentedWebcam(makeVideo(), canvas, {
+ mode: "blur",
+ blurIntensity: 0.5,
+ }).then(() => {
+ settled = true;
+ });
+
+ // Let the queue reach `send()` before delivering.
+ await vi.waitFor(() => expect(sendCount).toBe(1));
+ expect(settled).toBe(false);
+ flushOneSend();
+ await done;
+ expect(settled).toBe(true);
+ });
+
+ // The regression this file exists for: two overlapping calls used to share one
+ // `onResults` slot, so the first caller's promise was never settled and the
+ // preview's in-flight guard stayed stuck forever.
+ it("settles BOTH promises when two renders overlap", async () => {
+ const { renderSegmentedWebcam } = await import("./webcamSegmentation");
+ const canvasA = window.document.createElement("canvas");
+ const canvasB = window.document.createElement("canvas");
+
+ const first = renderSegmentedWebcam(makeVideo(), canvasA, {
+ mode: "transparent",
+ blurIntensity: 0,
+ });
+ const second = renderSegmentedWebcam(makeVideo(), canvasB, {
+ mode: "transparent",
+ blurIntensity: 0,
+ });
+
+ // Sends are serialised: the second must not start until the first is delivered.
+ await vi.waitFor(() => expect(sendCount).toBe(1));
+ flushOneSend();
+ await first;
+
+ await vi.waitFor(() => expect(sendCount).toBe(2));
+ flushOneSend();
+ await second;
+
+ await expect(Promise.all([first, second])).resolves.toBeDefined();
+ });
+
+ it("sizes the canvas to the crop and reads each source at its own resolution", async () => {
+ const { renderSegmentedWebcam } = await import("./webcamSegmentation");
+ const canvas = window.document.createElement("canvas");
+
+ const done = renderSegmentedWebcam(makeVideo(640, 360), canvas, {
+ mode: "transparent",
+ blurIntensity: 0,
+ crop: { x: 0.25, y: 0.5, width: 0.5, height: 0.5 },
+ });
+ await vi.waitFor(() => expect(sendCount).toBe(1));
+ flushOneSend();
+ await done;
+
+ expect(canvas.width).toBe(320);
+ expect(canvas.height).toBe(180);
+
+ // The mask is 256x144 while the image is 640x360, so a source rect computed from
+ // the video's dimensions would read the wrong region out of the mask.
+ const maskDraw = drawCalls.find(
+ (c) => (c.args[0] as HTMLCanvasElement)?.width === 256 && c.args.length === 9,
+ );
+ const imageDraw = drawCalls.find(
+ (c) => (c.args[0] as HTMLCanvasElement)?.width === 640 && c.args.length === 9,
+ );
+ expect(maskDraw?.args.slice(1, 5)).toEqual([64, 72, 128, 72]);
+ expect(imageDraw?.args.slice(1, 5)).toEqual([160, 180, 320, 180]);
+ });
+});
diff --git a/src/lib/ai-edition/webcamSegmentation.ts b/src/lib/ai-edition/webcamSegmentation.ts
index 8be27dfa0..62627c5f9 100644
--- a/src/lib/ai-edition/webcamSegmentation.ts
+++ b/src/lib/ai-edition/webcamSegmentation.ts
@@ -1,23 +1,47 @@
// Neural background segmentation for webcam feed using Google MediaPipe SelfieSegmentation.
// Runs locally via WebGL/WASM in real-time.
-import { SelfieSegmentation } from "@mediapipe/selfie_segmentation";
-import type { WebcamBackgroundMode } from "@/components/video-editor/types";
+import { type Results, SelfieSegmentation } from "@mediapipe/selfie_segmentation";
+import { BufferTarget, CanvasSource, Mp4OutputFormat, Output, WebMOutputFormat } from "mediabunny";
+import { toFileUrl } from "@/components/video-editor/projectPersistence";
+import {
+ type CropRegion,
+ DEFAULT_CROP_REGION,
+ type WebcamBackgroundMode,
+} from "@/components/video-editor/types";
+import getAssetPath from "@/lib/assetPath";
+import {
+ getLinearGradientPoints,
+ parseCssGradient,
+ resolveLinearGradientAngle,
+} from "@/lib/exporter/gradientParser";
+import { classifyWallpaper, resolveImageWallpaperUrl } from "@/lib/wallpaper";
+import type { CompositorClipInput } from "@/native/contracts";
let segmenterInstance: SelfieSegmentation | null = null;
let initPromise: Promise<SelfieSegmentation> | null = null;
+let lastInitFailure: { at: number; error: unknown } | null = null;
+
+/** Init is retryable, but the preview asks for a segmenter on every rAF tick — without a
+ * cooldown a persistent failure (missing WASM, no GPU) would construct a new
+ * `SelfieSegmentation` 60 times a second. */
+const INIT_RETRY_COOLDOWN_MS = 5_000;
export function getSelfieSegmenter(): Promise<SelfieSegmentation> {
if (segmenterInstance) return Promise.resolve(segmenterInstance);
if (initPromise) return initPromise;
+ if (lastInitFailure && Date.now() - lastInitFailure.at < INIT_RETRY_COOLDOWN_MS) {
+ return Promise.reject(lastInitFailure.error);
+ }
- initPromise = new Promise<SelfieSegmentation>((resolve, reject) => {
+ const pending = new Promise<SelfieSegmentation>((resolve, reject) => {
try {
const segmenter = new SelfieSegmentation({
- locateFile: (file) => {
- // In Vite dev & Electron build, assets are in /mediapipe/selfie_segmentation/
- return `/mediapipe/selfie_segmentation/${file}`;
- },
+ // The renderer runs from `file://` in a packaged build, so a root-absolute
+ // "/mediapipe/…" would resolve to the filesystem root and 404. `getAssetPath`
+ // is the repo's one way to address `public/` from both dev (http) and packaged
+ // (file:// + electronAPI.assetBaseUrl) — same path wallpapers take.
+ locateFile: (file) => getAssetPath(`mediapipe/selfie_segmentation/${file}`),
});
segmenter.setOptions({
@@ -25,6 +49,18 @@ export function getSelfieSegmenter(): Promise<SelfieSegmentation> {
selfieMode: false,
});
+ // One listener for the lifetime of the segmenter. `onResults` holds a SINGLE
+ // callback, so re-registering per frame lets a second caller overwrite the first
+ // and strand its promise forever. Results are routed to whoever is at the head of
+ // `sendQueue` instead.
+ // Deliver to whoever is at the head of the queue; `settle` is what clears the
+ // slot. (Clearing it HERE would make `settle`'s own identity guard fail and
+ // strand every frame.) A second delivery for the same send finds an empty slot
+ // and is ignored.
+ segmenter.onResults((results) => {
+ pendingResults?.(results);
+ });
+
segmenter
.initialize()
.then(() => {
@@ -41,15 +77,81 @@ export function getSelfieSegmenter(): Promise<SelfieSegmentation> {
}
});
+ // A rejected `initPromise` cached forever makes the first failure permanent for the
+ // session; clearing it lets a later call retry (the assets may just not have been
+ // reachable yet), while `lastInitFailure` keeps that retry from spinning per frame.
+ initPromise = pending.then(
+ (segmenter) => {
+ lastInitFailure = null;
+ return segmenter;
+ },
+ (err) => {
+ initPromise = null;
+ lastInitFailure = { at: Date.now(), error: err };
+ throw err;
+ },
+ );
return initPromise;
}
export interface SegmentationRenderOptions {
mode: WebcamBackgroundMode;
blurIntensity: number;
- threshold?: number;
- feather?: number;
wallpaper?: string;
+ /** Source sub-rect (fractions of the frame) to render, mirroring the native
+ * `webcam_crop`. Omit during export: native applies the crop itself to the
+ * pre-rendered track, and applying it here too would crop twice. */
+ crop?: CropRegion;
+}
+
+/** Head of the single-slot result channel — see the `onResults` comment above. */
+let pendingResults: ((results: Results | null) => void) | null = null;
+/** Serialises `send()` calls: MediaPipe has one result channel, so two overlapping
+ * sends cannot be told apart. Preview rAF, seek re-renders and the export loop all
+ * queue here. */
+let sendQueue: Promise<unknown> = Promise.resolve();
+
+/** A frame MediaPipe silently drops would otherwise wedge the queue for good. */
+const SEGMENTATION_TIMEOUT_MS = 10_000;
+
+function runSegmentation(video: HTMLVideoElement): Promise<Results | null> {
+ const run = sendQueue.then(async () => {
+ const segmenter = await getSelfieSegmenter();
+ return new Promise<Results | null>((resolve) => {
+ const settle = (results: Results | null) => {
+ if (pendingResults !== settle) return;
+ pendingResults = null;
+ clearTimeout(timer);
+ resolve(results);
+ };
+ const timer = setTimeout(() => {
+ console.warn("[WebcamSegmentation] segmentation timed out; dropping frame");
+ settle(null);
+ }, SEGMENTATION_TIMEOUT_MS);
+ pendingResults = settle;
+ segmenter.send({ image: video }).catch((err) => {
+ console.warn("[WebcamSegmentation] segmenter.send failed:", err);
+ settle(null);
+ });
+ });
+ });
+ // Keep the queue alive even when one run rejects, or every later frame is dropped.
+ sendQueue = run.catch(() => undefined);
+ return run;
+}
+
+/** Source sub-rect in a `GpuBuffer`'s OWN pixels. The mask comes back at the model's
+ * resolution (144x256 for the landscape model), not the video's, so a rect computed
+ * from `video.videoWidth` would crop the wrong region out of it. */
+function sourceRect(src: Results["image"], crop: CropRegion): [number, number, number, number] {
+ const iw = "naturalWidth" in src ? src.naturalWidth : src.width;
+ const ih = "naturalHeight" in src ? src.naturalHeight : src.height;
+ return [
+ Math.round(crop.x * iw),
+ Math.round(crop.y * ih),
+ Math.max(1, Math.round(crop.width * iw)),
+ Math.max(1, Math.round(crop.height * ih)),
+ ];
}
let tempCanvas: HTMLCanvasElement | null = null;
@@ -58,113 +160,211 @@ let tempCtx: CanvasRenderingContext2D | null = null;
function getTempCanvas(
width: number,
height: number,
-): { canvas: HTMLCanvasElement; ctx: CanvasRenderingContext2D } {
+): { canvas: HTMLCanvasElement; ctx: CanvasRenderingContext2D } | null {
if (!tempCanvas) {
tempCanvas = document.createElement("canvas");
tempCtx = tempCanvas.getContext("2d", { willReadFrequently: false });
}
+ if (!tempCtx) return null;
if (tempCanvas.width !== width || tempCanvas.height !== height) {
tempCanvas.width = width;
tempCanvas.height = height;
}
- return { canvas: tempCanvas, ctx: tempCtx! };
+ return { canvas: tempCanvas, ctx: tempCtx };
+}
+
+const wallpaperImageCache = new Map<string, HTMLImageElement>();
+
+/** Loads (and caches) an image wallpaper. Resolves to null when the path is
+ * unsafe or the file cannot be decoded — the caller then leaves the background
+ * unpainted rather than failing the whole render. */
+async function loadWallpaperImage(path: string): Promise<HTMLImageElement | null> {
+ const cached = wallpaperImageCache.get(path);
+ if (cached) return cached;
+ let url: string;
+ try {
+ url = resolveImageWallpaperUrl(path);
+ } catch (err) {
+ console.warn("[WebcamSegmentation] Unusable image wallpaper:", err);
+ return null;
+ }
+ return new Promise<HTMLImageElement | null>((resolve) => {
+ const img = new Image();
+ img.onload = () => {
+ wallpaperImageCache.set(path, img);
+ resolve(img);
+ };
+ img.onerror = () => resolve(null);
+ img.src = url;
+ });
+}
+
+/**
+ * Paints a wallpaper string behind the subject, covering `w`x`h`.
+ *
+ * Dispatches through `classifyWallpaper` — the same classifier the picker and the
+ * scene description use — so every value the UI can produce (colour, gradient,
+ * bundled `/wallpapers/…` path, uploaded `data:` URL) reaches the encoded track.
+ * A raw `startsWith("#")` test silently dropped gradients and images, which then
+ * exported as black.
+ */
+type BackgroundPainter = (ctx: CanvasRenderingContext2D, w: number, h: number) => void;
+
+/**
+ * Resolves a wallpaper string into a SYNCHRONOUS painter.
+ *
+ * Async work (decoding an image wallpaper) happens here, before the segmentation
+ * result is in hand, so that everything after it — which writes the shared module-level
+ * `tempCanvas` — runs without an await that another render could interleave into.
+ *
+ * Dispatches through `classifyWallpaper`, the same classifier the picker and the scene
+ * description use, so every value the UI can produce (colour, gradient, bundled
+ * `/wallpapers/…` path, uploaded `data:` URL) reaches the encoded track. A raw
+ * `startsWith("#")` test silently dropped gradients and images, which exported as black.
+ */
+async function resolveBackgroundPainter(wallpaper: string): Promise<BackgroundPainter | null> {
+ const classified = classifyWallpaper(wallpaper);
+
+ if (classified.kind === "color") {
+ return (ctx, w, h) => {
+ ctx.fillStyle = classified.value;
+ ctx.fillRect(0, 0, w, h);
+ };
+ }
+
+ if (classified.kind === "gradient") {
+ const parsed = parseCssGradient(classified.value);
+ if (!parsed || parsed.stops.length === 0) return null;
+ // Same angle convention the native gradient uses (0deg = up, 90deg = right).
+ const angle = resolveLinearGradientAngle(parsed.descriptor);
+ return (ctx, w, h) => {
+ const { x0, y0, x1, y1 } = getLinearGradientPoints(angle, w, h);
+ const grad = ctx.createLinearGradient(x0, y0, x1, y1);
+ for (const stop of parsed.stops) {
+ grad.addColorStop(Math.min(1, Math.max(0, stop.offset)), stop.color);
+ }
+ ctx.fillStyle = grad;
+ ctx.fillRect(0, 0, w, h);
+ };
+ }
+
+ const img = await loadWallpaperImage(classified.path);
+ if (!img?.naturalWidth || !img.naturalHeight) return null;
+ return (ctx, w, h) => {
+ // cover-fit, matching `draw_image_bg` on the native side.
+ const scale = Math.max(w / img.naturalWidth, h / img.naturalHeight);
+ const dw = img.naturalWidth * scale;
+ const dh = img.naturalHeight * scale;
+ ctx.drawImage(img, (w - dw) / 2, (h - dh) / 2, dw, dh);
+ };
}
/**
* Applies neural segmentation on the given video frame and renders into outputCanvas.
+ *
+ * Returns false when nothing was drawn (frame not ready, no 2D context, or MediaPipe
+ * dropped the frame). The live preview can ignore that — it will try again next tick —
+ * but the export MUST NOT, or a dropped frame is silently encoded as a duplicate of the
+ * previous one (or a blank first frame).
*/
export async function renderSegmentedWebcam(
video: HTMLVideoElement,
outputCanvas: HTMLCanvasElement,
options: SegmentationRenderOptions,
-): Promise<void> {
- if (video.videoWidth === 0 || video.videoHeight === 0) return;
+): Promise<boolean> {
+ if (video.videoWidth === 0 || video.videoHeight === 0) return false;
- const segmenter = await getSelfieSegmenter();
const outCtx = outputCanvas.getContext("2d");
- if (!outCtx) return;
+ if (!outCtx) return false;
- const w = video.videoWidth;
- const h = video.videoHeight;
+ // The native path crops first and cover-fits afterwards; CSS `object-fit: cover` on
+ // the canvas supplies that second step, so honouring the crop here is what makes
+ // preview and export agree.
+ const crop = options.crop ?? DEFAULT_CROP_REGION;
+ const w = Math.max(1, Math.round(crop.width * video.videoWidth));
+ const h = Math.max(1, Math.round(crop.height * video.videoHeight));
if (outputCanvas.width !== w || outputCanvas.height !== h) {
outputCanvas.width = w;
outputCanvas.height = h;
}
- return new Promise((resolve) => {
- segmenter.onResults((results) => {
- const { canvas: maskCanvas, ctx: maskCtx } = getTempCanvas(w, h);
-
- outCtx.save();
- outCtx.clearRect(0, 0, w, h);
-
- if (options.mode === "transparent") {
- // 1. Draw segmentation mask to temp canvas
- maskCtx.save();
- maskCtx.clearRect(0, 0, w, h);
- maskCtx.drawImage(results.segmentationMask, 0, 0, w, h);
- // 2. Composite video on top of mask
- maskCtx.globalCompositeOperation = "source-in";
- maskCtx.drawImage(results.image, 0, 0, w, h);
- maskCtx.restore();
-
- // 3. Draw cut out person to output
- outCtx.drawImage(maskCanvas, 0, 0, w, h);
- } else if (options.mode === "blur") {
- // 1. Draw blurred background
- const intensity = typeof options.blurIntensity === "number" ? options.blurIntensity : 0.5;
- const blurPx = Math.round(intensity * 25);
- if (blurPx > 0) {
- outCtx.filter = `blur(${blurPx}px)`;
- }
- outCtx.drawImage(results.image, 0, 0, w, h);
- outCtx.filter = "none";
-
- // 2. Mask the sharp person
- maskCtx.save();
- maskCtx.clearRect(0, 0, w, h);
- maskCtx.drawImage(results.segmentationMask, 0, 0, w, h);
- maskCtx.globalCompositeOperation = "source-in";
- maskCtx.drawImage(results.image, 0, 0, w, h);
- maskCtx.restore();
-
- // 3. Composite person over blurred background
- outCtx.drawImage(maskCanvas, 0, 0, w, h);
- } else if (options.mode === "custom") {
- // 1. Draw custom background behind the person
- if (options.wallpaper) {
- if (options.wallpaper.startsWith("#") || options.wallpaper.startsWith("rgb")) {
- outCtx.fillStyle = options.wallpaper;
- outCtx.fillRect(0, 0, w, h);
- }
- }
-
- // 2. Draw person cut out to temp canvas
- maskCtx.save();
- maskCtx.clearRect(0, 0, w, h);
- maskCtx.drawImage(results.segmentationMask, 0, 0, w, h);
- maskCtx.globalCompositeOperation = "source-in";
- maskCtx.drawImage(results.image, 0, 0, w, h);
- maskCtx.restore();
-
- // 3. Draw cut out person over the custom background
- outCtx.drawImage(maskCanvas, 0, 0, w, h);
- }
+ // Resolved BEFORE the segmentation await so the drawing section below — which owns
+ // the shared `tempCanvas` — contains no await for another render to interleave into.
+ const paintBackground =
+ options.mode === "custom" && options.wallpaper
+ ? await resolveBackgroundPainter(options.wallpaper)
+ : null;
+
+ const results = await runSegmentation(video);
+ if (!results) return false;
+
+ const temp = getTempCanvas(w, h);
+ if (!temp) return false;
+ const { canvas: maskCanvas, ctx: maskCtx } = temp;
+
+ const imageRect = sourceRect(results.image, crop);
+ const maskRect = sourceRect(results.segmentationMask, crop);
+ const drawCropped = (
+ ctx: CanvasRenderingContext2D,
+ src: Results["image"],
+ [rx, ry, rw, rh]: readonly [number, number, number, number],
+ ) => {
+ ctx.drawImage(src, rx, ry, rw, rh, 0, 0, w, h);
+ };
+
+ // The cut-out subject: the mask carries the alpha, `source-in` keeps only the
+ // video pixels that fall inside it. Identical in all three modes.
+ const drawCutout = () => {
+ maskCtx.save();
+ maskCtx.clearRect(0, 0, w, h);
+ drawCropped(maskCtx, results.segmentationMask, maskRect);
+ maskCtx.globalCompositeOperation = "source-in";
+ drawCropped(maskCtx, results.image, imageRect);
+ maskCtx.restore();
+ };
+
+ outCtx.save();
+ outCtx.clearRect(0, 0, w, h);
+
+ if (options.mode === "transparent") {
+ drawCutout();
+ outCtx.drawImage(maskCanvas, 0, 0, w, h);
+ } else if (options.mode === "blur") {
+ const intensity = typeof options.blurIntensity === "number" ? options.blurIntensity : 0.5;
+ const blurPx = Math.round(Math.min(1, Math.max(0, intensity)) * 25);
+ if (blurPx > 0) {
+ outCtx.filter = `blur(${blurPx}px)`;
+ }
+ drawCropped(outCtx, results.image, imageRect);
+ outCtx.filter = "none";
- outCtx.restore();
- resolve();
- });
+ drawCutout();
+ outCtx.drawImage(maskCanvas, 0, 0, w, h);
+ } else if (options.mode === "custom") {
+ paintBackground?.(outCtx, w, h);
- segmenter.send({ image: video }).catch((err) => {
- console.warn("[WebcamSegmentation] segmenter.send failed:", err);
- resolve();
- });
- });
+ drawCutout();
+ outCtx.drawImage(maskCanvas, 0, 0, w, h);
+ }
+
+ outCtx.restore();
+ return true;
}
-import { BufferTarget, CanvasSource, Mp4OutputFormat, Output, WebMOutputFormat } from "mediabunny";
-import { toFileUrl } from "@/components/video-editor/projectPersistence";
+/** Rejects once `ms` elapses, so a seek or a decode that never settles fails the
+ * export instead of hanging it. */
+function withTimeout<T>(work: Promise<T>, ms: number, message: string): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ return Promise.race([
+ work,
+ new Promise<never>((_resolve, reject) => {
+ timer = setTimeout(() => reject(new Error(message)), ms);
+ }),
+ ]).finally(() => clearTimeout(timer)) as Promise<T>;
+}
+
+const SEEK_TIMEOUT_MS = 15_000;
/**
* Pre-renders and encodes the full webcam video track using MediaPipe neural segmentation
@@ -183,14 +383,26 @@ export async function prepareSegmentedWebcamTrack(
video.playsInline = true;
video.crossOrigin = "anonymous";
- await new Promise<void>((resolve, reject) => {
- video.onloadedmetadata = () => resolve();
- video.onerror = () => reject(new Error("Failed to load webcam video metadata"));
- });
+ await withTimeout(
+ new Promise<void>((resolve, reject) => {
+ video.onloadedmetadata = () => resolve();
+ video.onerror = () => reject(new Error("Failed to load webcam video metadata"));
+ }),
+ SEEK_TIMEOUT_MS,
+ "Timed out loading webcam video metadata",
+ );
const width = video.videoWidth || 1280;
const height = video.videoHeight || 720;
- const duration = video.duration || 1;
+ // MediaRecorder WebM files report `Infinity` when the Duration header is missing
+ // (see `repairRecordingContainer`, which patches it only for streamed takes). It is
+ // truthy, so `|| 1` let it through and the frame loop below never terminated.
+ const duration = Number.isFinite(video.duration) && video.duration > 0 ? video.duration : 0;
+ if (duration <= 0) {
+ throw new Error(
+ "Webcam track has no usable duration, so the background effect cannot be pre-rendered",
+ );
+ }
const fps = 30;
const totalFrames = Math.max(1, Math.round(duration * fps));
@@ -214,21 +426,44 @@ export async function prepareSegmentedWebcamTrack(
output.addVideoTrack(videoSource);
await output.start();
- for (let i = 0; i < totalFrames; i++) {
- const time = i / fps;
- video.currentTime = time;
- await new Promise<void>((resolve) => {
- video.onseeked = () => resolve();
- });
-
- await renderSegmentedWebcam(video, canvas, options);
- await videoSource.add(time, 1 / fps);
- onProgress?.((i + 1) / totalFrames);
+ // The crop is deliberately NOT forwarded: native applies `webcam_crop` to this
+ // pre-rendered track itself, and cropping here too would apply it twice.
+ const renderOptions: SegmentationRenderOptions = { ...options, crop: undefined };
+
+ let sourceClosed = false;
+ try {
+ for (let i = 0; i < totalFrames; i++) {
+ const time = i / fps;
+ await withTimeout(
+ new Promise<void>((resolve, reject) => {
+ video.onseeked = () => resolve();
+ video.onerror = () => reject(new Error(`Failed to decode webcam frame at ${time}s`));
+ video.currentTime = time;
+ }),
+ SEEK_TIMEOUT_MS,
+ `Timed out seeking the webcam track to ${time}s`,
+ );
+
+ const drawn = await renderSegmentedWebcam(video, canvas, renderOptions);
+ if (!drawn) {
+ throw new Error(`Background segmentation produced no frame at ${time.toFixed(2)}s`);
+ }
+ await videoSource.add(time, 1 / fps);
+ onProgress?.((i + 1) / totalFrames);
+ }
+ // Close BEFORE finalize: the muxer flushes a source that is done, not one that
+ // might still receive frames.
+ videoSource.close();
+ sourceClosed = true;
+ await output.finalize();
+ } finally {
+ // The encoder and the decoding <video> hold native resources; an aborted export
+ // must not strand them.
+ if (!sourceClosed) videoSource.close();
+ video.removeAttribute("src");
+ video.load();
}
- videoSource.close();
- await output.finalize();
-
const buffer = target.buffer;
if (!buffer) {
throw new Error("Failed to encode segmented webcam video buffer");
@@ -236,11 +471,44 @@ export async function prepareSegmentedWebcamTrack(
const ext = isTransparent ? "webm" : "mp4";
const fileName = `webcam-segmented-${Date.now()}.${ext}`;
- const res = (await window.electronAPI?.storeRecordedVideo?.(buffer, fileName)) as
- | { success?: boolean; path?: string }
- | undefined;
- if (res && typeof res === "object" && typeof res.path === "string") {
- return res.path;
+ const res = await window.electronAPI?.writeDerivedMedia?.(buffer, fileName);
+ if (!res?.success || typeof res.path !== "string") {
+ // Falling back to the bare file name handed the native exporter a relative
+ // path it resolves against the process CWD — an unrelated "cannot open input"
+ // or a silently webcam-less export.
+ throw new Error(res?.message ?? res?.error ?? "Failed to store the pre-rendered webcam track");
+ }
+ return res.path;
+}
+
+/**
+ * Pre-renders every distinct webcam track a clip list references and returns the list with
+ * `webcamPath` pointing at the segmented copies.
+ *
+ * Shared by `ExportDialog` and `CliExportRunner`: both used to carry their own copy of this
+ * loop, which is exactly the divergence `resolveVisibleClips` was introduced to stop for the
+ * clip list itself.
+ */
+export async function applySegmentedWebcamTracks(
+ clips: CompositorClipInput[],
+ options: SegmentationRenderOptions,
+ onProgress?: (progress: number) => void,
+): Promise<CompositorClipInput[]> {
+ if (options.mode === "none") return clips;
+
+ // Distinct tracks first, so per-track progress can be scaled into one 0..1 sweep
+ // instead of restarting at 0 for every track.
+ const sourcePaths = [...new Set(clips.map((clip) => clip.webcamPath).filter(Boolean))];
+ const processedByPath = new Map<string, string>();
+ for (const [index, sourcePath] of sourcePaths.entries()) {
+ const processedPath = await prepareSegmentedWebcamTrack(sourcePath, options, (prog) =>
+ onProgress?.((index + prog) / sourcePaths.length),
+ );
+ processedByPath.set(sourcePath, processedPath);
}
- return fileName;
+
+ return clips.map((clip) => {
+ const processed = clip.webcamPath ? processedByPath.get(clip.webcamPath) : undefined;
+ return processed ? { ...clip, webcamPath: processed } : clip;
+ });
}
diff --git a/src/native/sceneDescription.test.ts b/src/native/sceneDescription.test.ts
index 63d86d4a0..570ae71ee 100644
--- a/src/native/sceneDescription.test.ts
+++ b/src/native/sceneDescription.test.ts
@@ -177,54 +177,6 @@ describe("buildSceneDescription.background", () => {
});
});
-describe("buildSceneDescription.webcamEffect", () => {
- it("serializes default webcamEffect (none mode)", () => {
- const doc = makeDoc();
- expect(buildSceneDescription(doc).webcamEffect).toEqual({
- mode: "none",
- blurIntensity: 0.5,
- background: { kind: "image", path: "/wallpapers/wallpaper1.jpg" },
- });
- });
-
- it("serializes transparent cutout mode", () => {
- const doc = makeDoc({
- legacyEditor: {
- webcamBackgroundMode: "transparent",
- },
- });
- expect(buildSceneDescription(doc).webcamEffect?.mode).toBe("transparent");
- });
-
- it("serializes blur mode with custom blur intensity", () => {
- const doc = makeDoc({
- legacyEditor: {
- webcamBackgroundMode: "blur",
- webcamBlurIntensity: 0.85,
- },
- });
- expect(buildSceneDescription(doc).webcamEffect).toEqual({
- mode: "blur",
- blurIntensity: 0.85,
- background: { kind: "image", path: "/wallpapers/wallpaper1.jpg" },
- });
- });
-
- it("serializes custom background mode with color or gradient", () => {
- const doc = makeDoc({
- legacyEditor: {
- webcamBackgroundMode: "custom",
- webcamWallpaper: "#34b27b",
- },
- });
- expect(buildSceneDescription(doc).webcamEffect).toEqual({
- mode: "custom",
- blurIntensity: 0.5,
- background: { kind: "color", color: "#34b27b" },
- });
- });
-});
-
// --- clips -----------------------------------------------------------------
describe("buildSceneDescription.clips", () => {
diff --git a/src/native/sceneDescription.ts b/src/native/sceneDescription.ts
index 142d70717..38408631c 100644
--- a/src/native/sceneDescription.ts
+++ b/src/native/sceneDescription.ts
@@ -401,20 +401,6 @@ export interface SceneDescription {
cropByClip: Array<{ x: number; y: number; width: number; height: number } | null>;
/** Output frame. `fps` null = use the first clip's source fps. */
output: { width: number; height: number; fps: number | null };
- /** Webcam background / AI cutout effects. */
- webcamEffect?: SceneWebcamEffect;
-}
-
-/** Webcam background / AI cutout effects. */
-export interface SceneWebcamEffect {
- /** "none" | "transparent" | "blur" | "custom" | "presegmented" */
- mode: "none" | "transparent" | "blur" | "custom" | "presegmented";
- /** 0..1 blur intensity when mode is "blur". */
- blurIntensity: number;
- /** Background behind the subject when mode is "custom" (parsed like settings.wallpaper). */
- background?: SceneBackground;
- /** Optional pre-computed alpha matte video path. */
- maskPath?: string;
}
/** Parse the settings wallpaper string into the discriminated SceneBackground union. */
@@ -927,10 +913,5 @@ export function buildSceneDescription(
})),
cropByClip,
output: { ...pickOutputDims(document, settings.aspectRatio), fps: null },
- webcamEffect: {
- mode: settings.webcamBackgroundMode,
- blurIntensity: settings.webcamBlurIntensity,
- background: parseWallpaper(settings.webcamWallpaper),
- },
};
}