Record your screen, ship a demo. Free and open-source, GPU-accelerated, no watermarks, no subscriptions. Windows, macOS, Linux. Actively maintained.
TypeScript cross-platformelectronffmpegopen-sourceproduct-demorustscreen-capturescreen-recorderscreen-recordingscreen-studioscreencastspeech-to-texttypescriptvideo-editingvideo-editorwaylandwgpuwhisper
fix(editor): stop losing the camera to a fractional offset
Etienne Lescot75686f1aa666
diff --git a/crates/compositor/src/compositor_linux.rs b/crates/compositor/src/compositor_linux.rsindex a2aff4474..6996ca320 100644--- a/crates/compositor/src/compositor_linux.rs+++ b/crates/compositor/src/compositor_linux.rs@@ -1062,7 +1062,13 @@ impl Compositor {// Webcam PiP (mode 0) -- placee par plan_frame (`g.w_dst`, coins// `g.w_radius`), gardee par `g.shape_fade > 0` (webcam visible).// `webcam_planes` garde les vues en vie pendant le pass.- let webcam_planes = if g.shape_fade > 0.0 && !webcam.is_null() {+ // `lp.has_webcam` is the gate Windows (`compositor_windows.rs`) and macOS+ // (`compositor_macos.rs`) both apply and this backend did not. It is false+ // when the clip has no camera — and in that case the "webcam" decoder holds+ // the SCREEN video, because `open_and_seek_clip` falls back to it rather+ // than leave the pair half-open. Without this check a recording with no+ // camera drew its own screen picture inside the PiP box.+ let webcam_planes = if lp.has_webcam && g.shape_fade > 0.0 && !webcam.is_null() {self.nv12_srvs(webcam).ok()} else {Nonediff --git a/crates/compositor/src/live.rs b/crates/compositor/src/live.rsindex 0addf916f..49199a699 100644--- a/crates/compositor/src/live.rs+++ b/crates/compositor/src/live.rs@@ -529,6 +529,26 @@ fn same_source_path(a: &str, b: &str) -> bool {a.eq_ignore_ascii_case(b)}+/// True when the active clip really has a camera to draw.+///+/// TWO ways the app says "no camera", and both must be caught here, because the+/// webcam decoder is opened either way — `open_and_seek_clip` falls back to the+/// SCREEN file when the webcam path won't open, so `wdec` always yields frames.+/// Whether those frames are the camera or a second copy of the screen is decided+/// HERE and nowhere else.+///+/// - the empty string, which is what `sceneDescription.ts` and+/// `NativeCompositorOverlay` send for an asset with no `cameraTrack`;+/// - the screen's own path, the older convention kept working for scenes that+/// still use it.+///+/// Missing the empty-string case is what put the screen recording inside the PiP+/// box: `"" != "/…/recording.mp4"`, so the box was drawn, and the decoder behind+/// it was the screen fallback.+fn webcam_is_real(webcam_path: &str, screen_path: &str) -> bool {+ !webcam_path.trim().is_empty() && !same_source_path(webcam_path, screen_path)+}+fn scene_clip_matches(clip: &crate::scene::SceneClip,screen_path: &str,@@ -1328,11 +1348,9 @@ unsafe fn render_thread(cfg.bg_blur = ip.bg_blur;cfg.mblur_n = ip.mblur_taps;cfg.cursor = ip.cursor_show;- // TS falls `webcamPath` back to the screen asset's own path when a clip has no real- // camera (so the decoder pipeline always has something valid to open) — if we drew the- // PiP box in that case it would just duplicate the screen video into its own corner.- // `same_source_path` already exists for exactly this comparison (scene/clip matching).- let has_real_webcam = !same_source_path(&active_webcam_path, &active_screen_path);+ // A clip with no camera must not draw the PiP box — the decoder behind it is the+ // screen video, so drawing it duplicates the recording into its own corner.+ let has_real_webcam = webcam_is_real(&active_webcam_path, &active_screen_path);comp.set_live_params(LiveParams {bg_color: ip.bg_color,shadow_scale: ip.shadow_scale,@@ -1778,6 +1796,23 @@ mod tests {assert_eq!(webcam_seek_time(0.5, 1.25), 0.0);}+ #[test]+ fn a_clip_without_a_camera_has_no_webcam_to_draw() {+ // What the app actually sends for an asset with no `cameraTrack`. Treating+ // this as a real camera drew the screen recording inside the PiP box, since+ // the webcam decoder falls back to the screen file when the path won't open.+ assert!(!webcam_is_real("", "/rec/recording-1.mp4"));+ assert!(!webcam_is_real(" ", "/rec/recording-1.mp4"));+ // The older sentinel: webcam path == screen path.+ assert!(!webcam_is_real("/rec/recording-1.mp4", "/rec/recording-1.mp4"));+ assert!(!webcam_is_real("/rec/RECORDING-1.mp4", "/rec/recording-1.mp4"));+ }++ #[test]+ fn a_clip_with_a_camera_draws_it() {+ assert!(webcam_is_real("/rec/recording-1-webcam.webm", "/rec/recording-1.mp4"));+ }+// --- transport handed to an export and back -------------------------------// A real `LiveView` needs a D3D device and a decoder; the transport is the only// part an export touches, so these exercise it through `PreviewTransport` alone.diff --git a/crates/compositor/tests/compose_linux.rs b/crates/compositor/tests/compose_linux.rsindex 097f787a6..5d19397a2 100644--- a/crates/compositor/tests/compose_linux.rs+++ b/crates/compositor/tests/compose_linux.rs@@ -988,3 +988,99 @@ fn compose_linux_forme_webcam_cercle() {"le masque cercle ne rogne pas comme un disque (remplissage {circle_fill:.3}, attendu ~0.785)");}++/// Un enregistrement SANS camera ne doit rien dessiner dans la boite PiP.+///+/// Le cas est reproduit tel quel : le decodeur « webcam » recoit la frame de+/// l'ECRAN, ce que `open_and_seek_clip` fait en production des que le chemin+/// webcam est vide ou illisible. Seul `LiveParams::has_webcam` distingue alors+/// une vraie camera d'une seconde copie de l'ecran, et ce backend ne le lisait+/// pas : l'enregistrement d'ecran apparaissait dans sa propre vignette.+///+/// L'assertion est une egalite stricte avec le rendu « no-webcam » : pas un+/// seuil, parce qu'il ne s'agit pas de mesurer une empreinte plus petite mais+/// de verifier qu'il n'y en a aucune.+#[test]+fn compose_linux_sans_camera_ne_dessine_pas_de_vignette() {+ if std::env::var("OPENSCREEN_LINUX_COMPOSE").is_err() || !Path::new(FIXTURE).is_file() {+ eprintln!("compose_linux sans camera: opt-in. Skip.");+ return;+ }++ let gpu = Gpu::create(false).expect("Gpu::create");+ let comp = Compositor::new_sized(&gpu, W, H).expect("Compositor::new_sized");+ let mut screen = Decoder::open(FIXTURE, &gpu).expect("Decoder::open screen");++ let scene_json = r##"{"clips":[],"layout":{"preset":"picture-in-picture","webcamSize":1.6,"webcamShape":"rectangle","webcamMirror":false,"webcamPosition":null,"webcamReactiveZoom":false},"effects":{"padding":0.1,"blur":false,"shadow":0,"roundnessFrac":0.0,"motionBlur":0},"background":{"kind":"color","color":"#00ff00"},"zoomRegions":[],"annotations":[],"cursor":{"show":false,"size":1,"smoothing":0,"motionBlur":0,"clickBounce":0,"clipToBounds":false,"theme":"default"},"cropByClip":[],"output":{"width":1920,"height":1080,"fps":30}}"##;++ let mut render = |has_webcam: bool| -> Vec<u8> {+ let parsed = Scene::from_json(scene_json).expect("scene json");+ let mut lp = openscreen_compositor::compositor::live_params_from_scene(&parsed);+ lp.has_webcam = has_webcam;+ comp.set_live_params(lp);+ comp.set_scene(Some(parsed));+ unsafe {+ let sf = screen.seek_to(1.0).expect("seek screen");+ let mut cfg = Cfg::c8();+ cfg.shadow = false;+ // La frame ecran passee AUSSI comme webcam : le repli exact de+ // `open_and_seek_clip` quand il n'y a pas de fichier camera.+ comp.compose_frame(sf, sf, 1.0, &cfg).expect("compose_frame");+ comp.readback_direct().expect("readback").2+ }+ };++ let with_camera = render(true);+ let without_camera = render(false);+ write_ppm("compose_linux_sans_camera", W, H, &without_camera);++ let differing = with_camera+ .chunks_exact(4)+ .zip(without_camera.chunks_exact(4))+ .filter(|(a, b)| {+ (a[0] as i32 - b[0] as i32).abs()+ + (a[1] as i32 - b[1] as i32).abs()+ + (a[2] as i32 - b[2] as i32).abs()+ > 24+ })+ .count();+ println!("vignette ecran-dans-la-camera : {differing} px");+ assert!(+ differing > 1000,+ "le rendu de controle ne dessine aucune vignette — le test ne prouve rien ({differing} px)"+ );++ // Reference : le preset qui ne veut pas de camera du tout. Il pose le meme+ // rectangle d'ecran (`plan_frame` : « no-webcam » et « picture-in-picture »+ // partagent `full_screen`), donc seule la vignette peut les separer.+ let no_webcam_preset = {+ let parsed = Scene::from_json(&scene_json.replace(+ r#""preset":"picture-in-picture""#,+ r#""preset":"no-webcam""#,+ ))+ .expect("scene json");+ comp.set_live_params(openscreen_compositor::compositor::live_params_from_scene(&parsed));+ comp.set_scene(Some(parsed));+ unsafe {+ let sf = screen.seek_to(1.0).expect("seek screen");+ let mut cfg = Cfg::c8();+ cfg.shadow = false;+ comp.compose_frame(sf, sf, 1.0, &cfg).expect("compose_frame");+ comp.readback_direct().expect("readback").2+ }+ };+ let residual = without_camera+ .chunks_exact(4)+ .zip(no_webcam_preset.chunks_exact(4))+ .filter(|(a, b)| {+ (a[0] as i32 - b[0] as i32).abs()+ + (a[1] as i32 - b[1] as i32).abs()+ + (a[2] as i32 - b[2] as i32).abs()+ > 24+ })+ .count();+ assert_eq!(+ residual, 0,+ "sans camera, le rendu devrait etre celui du preset no-webcam ({residual} px d'ecart)"+ );+}diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.tsindex 4b397823e..19afd52f5 100644--- a/src/hooks/useScreenRecorder.ts+++ b/src/hooks/useScreenRecorder.ts@@ -114,6 +114,30 @@ type NativeLinuxRecordingHandle = {webcamOffsetMs: number | null;};+/**+ * How far AHEAD of the native screen recording the browser-recorded webcam+ * started, in whole milliseconds (negative, since the webcam always starts+ * first). `null` when this session recorded no webcam.+ *+ * WHOLE milliseconds on purpose. Both timestamps come from `performance.now()`,+ * whose resolution is 100 µs, so the raw subtraction is almost never an integer+ * — and this number ends up in `cameraTrack.offsetMs`, which the document schema+ * declares as an int. A fractional value failed validation, the camera link was+ * dropped as if the recording had no camera, and the editor drew the screen+ * video in the camera's place. Rounding loses nothing: one frame at 60 fps is+ * 16.7 ms.+ */+export function webcamOffsetMsFrom(+ webcamRecorder: RecorderHandle | null,+ webcamStartedAtMs: number | null,+ nativeStartedAtMs: number,+): number | null {+ if (!webcamRecorder || webcamStartedAtMs === null) {+ return null;+ }+ return -Math.round(nativeStartedAtMs - webcamStartedAtMs);+}+export function useScreenRecorder(): UseScreenRecorderReturn {const t = useScopedT("editor");const [recording, setRecording] = useState(false);@@ -1180,10 +1204,11 @@ export function useScreenRecorder(): UseScreenRecorderReturn {recordingId: result.recordingId,finalizing: false,paused: false,- webcamOffsetMs:- nativeWebcamRecorder && nativeWebcamRecorderStartedAtMs !== null- ? -(nativeRecordingConfirmedStartedAtMs - nativeWebcamRecorderStartedAtMs)- : null,+ webcamOffsetMs: webcamOffsetMsFrom(+ nativeWebcamRecorder,+ nativeWebcamRecorderStartedAtMs,+ nativeRecordingConfirmedStartedAtMs,+ ),};webcamRecorder.current = nativeWebcamRecorder;accumulatedDurationMs.current = 0;@@ -1304,10 +1329,11 @@ export function useScreenRecorder(): UseScreenRecorderReturn {recordingId: result.recordingId,finalizing: false,paused: false,- webcamOffsetMs:- nativeWebcamRecorder && nativeWebcamRecorderStartedAtMs !== null- ? -(nativeRecordingConfirmedStartedAtMs - nativeWebcamRecorderStartedAtMs)- : null,+ webcamOffsetMs: webcamOffsetMsFrom(+ nativeWebcamRecorder,+ nativeWebcamRecorderStartedAtMs,+ nativeRecordingConfirmedStartedAtMs,+ ),};webcamRecorder.current = nativeWebcamRecorder;accumulatedDurationMs.current = 0;diff --git a/src/hooks/webcamOffset.test.ts b/src/hooks/webcamOffset.test.tsnew file mode 100644index 000000000..29ea39a99--- /dev/null+++ b/src/hooks/webcamOffset.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from "vitest";+import { cameraTrackSchema } from "@/lib/ai-edition/schema";+import type { RecorderHandle } from "./recorderHandle";+import { webcamOffsetMsFrom } from "./useScreenRecorder";++// The offset the native macOS/Linux paths measure lands in `cameraTrack.offsetMs`,+// which the document schema declares as an integer. Both ends are checked here,+// because the failure was invisible in between: an unrounded offset made+// `parseDocument` throw inside the camera auto-link, the throw was caught as a+// lookup failure, and a recording that had a camera opened without one.+const recorder = {} as RecorderHandle;++describe("webcamOffsetMsFrom", () => {+ it("rounds the sub-millisecond gap performance.now() reports", () => {+ expect(webcamOffsetMsFrom(recorder, 1_000.1, 1_192.9000000044703)).toBe(-193);+ expect(webcamOffsetMsFrom(recorder, 0, 202.10000000149012)).toBe(-202);+ });++ it("produces a value the document schema accepts", () => {+ const offsetMs = webcamOffsetMsFrom(recorder, 1_000.1, 1_192.9000000044703);+ const parsed = cameraTrackSchema.safeParse({+ sourcePath: "/rec/recording-1-webcam.webm",+ startMs: 0,+ offsetMs,+ visible: true,+ });+ expect(parsed.success).toBe(true);+ });++ it("is null when this session recorded no webcam", () => {+ expect(webcamOffsetMsFrom(null, 1_000, 1_200)).toBeNull();+ expect(webcamOffsetMsFrom(recorder, null, 1_200)).toBeNull();+ });++ it("keeps the sign: the webcam always starts first", () => {+ expect(webcamOffsetMsFrom(recorder, 100, 350)).toBe(-250);+ });+});diff --git a/src/lib/ai-edition/document/migrate.ts b/src/lib/ai-edition/document/migrate.tsindex efb64644f..283eef372 100644--- a/src/lib/ai-edition/document/migrate.ts+++ b/src/lib/ai-edition/document/migrate.ts@@ -95,7 +95,11 @@ export function migrateProjectDataToAxcutDocument(: null;const webcamVideoPath = input.media?.webcamVideoPath;- const webcamOffsetMs = input.media?.webcamOffsetMs ?? 0;+ // Rounded for the same reason as the auto-link in `projectStore.addAsset`:+ // `cameraTrackSchema.offsetMs` is an integer, and the native capture paths+ // measure this with `performance.now()`. A legacy project carrying the raw+ // value would fail to parse — losing the whole document, not just its camera.+ const webcamOffsetMs = Math.round(input.media?.webcamOffsetMs ?? 0);const assets = screenPath? [diff --git a/src/lib/ai-edition/store/projectStore.test.ts b/src/lib/ai-edition/store/projectStore.test.tsindex 5378843a5..26e593e19 100644--- a/src/lib/ai-edition/store/projectStore.test.ts+++ b/src/lib/ai-edition/store/projectStore.test.ts@@ -192,6 +192,46 @@ describe("useProjectStore", () => {);});+ it("addAsset links the camera when the recorder measured a sub-millisecond offset", async () => {+ // The native capture paths derive this from `performance.now()` (100 µs+ // resolution), so the offset is almost never a whole number — while+ // `cameraTrackSchema.offsetMs` is an int. Unrounded, the document failed+ // validation, the catch below treated it as a lookup failure, and a+ // recording that HAD a camera silently lost it.+ useProjectStore.setState({+ projectId: "proj_test",+ document: sampleDoc,+ revision: 1,+ status: "ready",+ error: null,+ });+ bridgeMocks.save.mockImplementation(async (document) => ({ success: true, document }));+ // biome-ignore lint/suspicious/noExplicitAny: test-only stub of the legacy contextBridge surface+ (window as any).electronAPI.findRecordingCamera.mockResolvedValue({+ success: true,+ webcamVideoPath: "/tmp/screen-webcam.webm",+ offsetMs: -192.80000000447035,+ });+ bridgeMocks.addAsset.mockResolvedValue({+ assetId: "asset_1",+ document: {+ ...sampleDoc,+ assets: [+ { id: "asset_1", kind: "video", label: "screen.mp4", originalPath: "/tmp/screen.mp4" },+ ],+ project: { ...sampleDoc.project, primaryAssetId: "asset_1" },+ },+ });++ await useProjectStore.getState().addAsset("/tmp/screen.mp4");+ await new Promise((resolve) => setTimeout(resolve, 0));++ expect(toastMocks.error).not.toHaveBeenCalled();+ const camera = useProjectStore.getState().document?.assets[0]?.cameraTrack;+ expect(camera?.sourcePath).toBe("/tmp/screen-webcam.webm");+ expect(camera?.offsetMs).toBe(-193);+ });+it("addAsset stays silent (no toast) when a plain imported video has no camera", async () => {useProjectStore.setState({projectId: "proj_test",diff --git a/src/lib/ai-edition/store/projectStore.ts b/src/lib/ai-edition/store/projectStore.tsindex e67d2c798..fec88776f 100644--- a/src/lib/ai-edition/store/projectStore.ts+++ b/src/lib/ai-edition/store/projectStore.ts@@ -154,7 +154,19 @@ export const useProjectStore = create<ProjectState>((set, get) => ({const linked = {sourcePath: camera.webcamVideoPath,startMs: 0,- offsetMs: camera.offsetMs ?? 0,+ // ROUNDED, because `cameraTrackSchema` requires an integer and+ // the native capture paths measure this offset with+ // `performance.now()`, whose resolution is 100 µs — so roughly+ // nine recordings in ten produced something like -192.8 here.+ // `parseDocument` below then threw, the catch treated it as a+ // lookup failure, and the camera was dropped from a recording+ // that had one: the editor showed the screen video in the+ // camera's place. Sub-millisecond precision is meaningless for+ // a frame offset (a 60 fps frame is 16.7 ms), so rounding costs+ // nothing. Recordings already on disk carry the fractional+ // value in their session manifest, which is why this rounds on+ // the way IN rather than only at the recorder.+ offsetMs: Math.round(camera.offsetMs ?? 0),visible: true,};const next: AxcutDocument = {@@ -170,6 +182,10 @@ export const useProjectStore = create<ProjectState>((set, get) => ({// the normal case for a plain imported video. Nothing to surface.} catch (err) {// An actual lookup failure (not "no camera found") — worth surfacing.+ // Logged as well as toasted: a toast is gone in five seconds, and the+ // symptom this produces (a recording that silently loses its camera)+ // is reported from the editor, long after.+ console.warn("[project] camera auto-link failed:", err);const name = addedAsset.originalPath.split(/[\\/]/).pop() ?? addedAsset.originalPath;void import("sonner").then(({ toast }) =>toast.error(`Could not check for a camera recording near ${name}`, {