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(recording): sync the webcam to native capture and compensate its start offset
Etienne Lescotb1eb59f44145
diff --git a/docs/engineering/windows-native-recorder-roadmap.md b/docs/engineering/windows-native-recorder-roadmap.mdindex 146582a5c..6ddd74557 100644--- a/docs/engineering/windows-native-recorder-roadmap.md+++ b/docs/engineering/windows-native-recorder-roadmap.md@@ -155,6 +155,10 @@ Acceptance:### 4. Webcam Capture+Status: the webcam encoder's `writeBgraFrame()` calls are paced to real elapsed wall-clock time, anchored to the same recording-start origin used by screen video and the audio mixer (`CaptureControl::recordingStartedAt`) and reduced by the same accumulated pause duration (`CaptureControl::pausedDurationHns()`), duplicating the latest available camera frame when the camera hasn't produced a newer one by the next due slot. This replaced a `frameIndex / fps` clock that was purely a local counter with no anchor to the recording's actual start time or accumulated pause duration, so it drifted out of alignment with screen video and audio.++Note: an earlier iteration of this fix tried timestamping each webcam frame with its true per-frame host-clock capture time (i.e. genuine variable-frame-rate timestamps) and passing that through to the encoder. That was verified *not* to work: Media Foundation's H.264 encoder MFT does not honor irregular per-sample timestamps for a VFR source -- empirically, correctly-varying, monotonically increasing input `SampleTime` values still produced perfectly evenly-spaced output samples, because the encoder numbers output samples sequentially at its configured nominal frame rate regardless of the timestamp attached to each input sample. Since the encoder can't be made to respect real capture time, the encoder's assumption is instead made true by controlling *when* `writeBgraFrame()` is called (a real-time-paced cadence), rather than *what timestamp* is attached to each call.+- Add Media Foundation webcam source reader.- Select requested dimensions/fps or the nearest format accepted by Media Foundation.- Convert webcam samples to BGRA and compose them into the primary helper MP4 as an initial bottom-right picture-in-picture overlay.diff --git a/electron/ipc/handlers.ts b/electron/ipc/handlers.tsindex 934ca846a..8dd6445ef 100644--- a/electron/ipc/handlers.ts+++ b/electron/ipc/handlers.ts@@ -368,6 +368,8 @@ type AttachNativeMacWebcamRecordingInput = {recordingId?: number;webcam?: RecordedVideoAssetInput;cursorCaptureMode?: CursorCaptureMode;+ /** See {@link ProjectMedia.webcamOffsetMs}. */+ webcamOffsetMs?: number;};let selectedSource: SelectedSource | null = null;@@ -897,7 +899,11 @@ async function writePendingCursorTelemetry(videoPath: string) {// Best-effort: a registry write hiccup must never fail the recording flow.async function registerRecordingMediaLinks(screenVideoPath: string,- options: { webcamVideoPath?: string; cursorCaptureMode?: CursorCaptureMode },+ options: {+ webcamVideoPath?: string;+ webcamOffsetMs?: number;+ cursorCaptureMode?: CursorCaptureMode;+ },) {try {const cursorTelemetryPath = `${screenVideoPath}.cursor.json`;@@ -907,6 +913,9 @@ async function registerRecordingMediaLinks(.catch(() => false);await registerMediaLinks(RECORDINGS_DIR, screenVideoPath, {...(options.webcamVideoPath ? { webcamVideoPath: options.webcamVideoPath } : {}),+ ...(options.webcamVideoPath && Number.isFinite(options.webcamOffsetMs)+ ? { webcamOffsetMs: options.webcamOffsetMs }+ : {}),...(hasCursorTelemetry ? { cursorTelemetryPath } : {}),...(options.cursorCaptureMode ? { cursorCaptureMode: options.cursorCaptureMode } : {}),});@@ -1394,12 +1403,18 @@ async function resolveMediaLinksForVideo(videoPath: string): Promise<{// recording predates the registry, or if its sidecar doesn't travel with it.await registerMediaLinks(RECORDINGS_DIR, videoPath, {...(session?.webcamVideoPath ? { webcamVideoPath: session.webcamVideoPath } : {}),+ ...(session?.webcamVideoPath && Number.isFinite(session.webcamOffsetMs)+ ? { webcamOffsetMs: session.webcamOffsetMs }+ : {}),...(hasCursorTelemetry ? { cursorTelemetryPath } : {}),}).catch((error) => console.warn("[media-links] backfill failed:", error));return {...(session?.webcamVideoPath- ? { webcamVideoPath: session.webcamVideoPath, webcamOffsetMs: 0 }+ ? {+ webcamVideoPath: session.webcamVideoPath,+ webcamOffsetMs: session.webcamOffsetMs ?? 0,+ }: {}),...(hasCursorTelemetry ? { cursorTelemetryPath } : {}),resolvedVia: "sidecar",@@ -2367,10 +2382,14 @@ export function registerIpcHandlers(? payload.recordingId: Date.now();const cursorCaptureMode = normalizeCursorCaptureMode(payload.cursorCaptureMode);+ const webcamOffsetMs = Number.isFinite(payload.webcamOffsetMs)+ ? payload.webcamOffsetMs+ : undefined;const session: RecordingSession = {screenVideoPath,webcamVideoPath,createdAt,+ ...(webcamOffsetMs !== undefined ? { webcamOffsetMs } : {}),...(cursorCaptureMode ? { cursorCaptureMode } : {}),};setCurrentRecordingSessionState(session);@@ -2381,7 +2400,11 @@ export function registerIpcHandlers(`${path.parse(screenVideoPath).name}${RECORDING_SESSION_SUFFIX}`,);await fs.writeFile(sessionManifestPath, JSON.stringify(session, null, 2), "utf-8");- await registerRecordingMediaLinks(screenVideoPath, { webcamVideoPath, cursorCaptureMode });+ await registerRecordingMediaLinks(screenVideoPath, {+ webcamVideoPath,+ webcamOffsetMs,+ cursorCaptureMode,+ });return {success: true,@@ -2487,11 +2510,16 @@ export function registerIpcHandlers(await Promise.all(patches);}+ const webcamOffsetMs =+ webcamVideoPath && Number.isFinite(payload.webcamOffsetMs)+ ? payload.webcamOffsetMs+ : undefined;const session: RecordingSession = webcamVideoPath? {screenVideoPath,webcamVideoPath,createdAt,+ ...(webcamOffsetMs !== undefined ? { webcamOffsetMs } : {}),...(cursorCaptureMode ? { cursorCaptureMode } : {}),}: { screenVideoPath, createdAt, ...(cursorCaptureMode ? { cursorCaptureMode } : {}) };@@ -2505,7 +2533,11 @@ export function registerIpcHandlers(`${path.parse(payload.screen.fileName).name}${RECORDING_SESSION_SUFFIX}`,);await fs.writeFile(sessionManifestPath, JSON.stringify(session, null, 2), "utf-8");- await registerRecordingMediaLinks(screenVideoPath, { webcamVideoPath, cursorCaptureMode });+ await registerRecordingMediaLinks(screenVideoPath, {+ webcamVideoPath,+ webcamOffsetMs,+ cursorCaptureMode,+ });return {success: true,diff --git a/electron/native/wgc-capture/src/main.cpp b/electron/native/wgc-capture/src/main.cppindex 1c0f08140..6c092347d 100644--- a/electron/native/wgc-capture/src/main.cpp+++ b/electron/native/wgc-capture/src/main.cpp@@ -17,6 +17,7 @@#include <iostream>#include <memory>#include <mutex>+#include <ratio>#include <string>#include <thread>@@ -59,6 +60,10 @@ struct CaptureControl {std::condition_variable cv;std::chrono::steady_clock::time_point pauseStartedAt;std::chrono::steady_clock::duration totalPausedDuration{};+ // Shared T0 for every stream's timeline (screen video, audio, webcam).+ // Set once, right before the video writer thread starts, so all streams+ // measure elapsed time from the same real-world instant.+ std::chrono::steady_clock::time_point recordingStartedAt;int64_t pausedDurationHns() {std::scoped_lock lock(mutex);@@ -457,15 +462,25 @@ int main(int argc, char* argv[]) {config.webcamWidth,config.webcamHeight,config.webcamFps > 0 ? config.webcamFps : config.fps)) {- std::cerr << "ERROR: Failed to initialize native webcam capture" << std::endl;- return 1;+ // Non-fatal: a screen+audio recording the user can still use is far+ // better than losing the whole recording because one camera device+ // didn't match. Report it so the renderer can inform the user (and,+ // historically, fall back to a browser-recorded webcam sidecar), but+ // let capture continue without a native webcam track.+ std::cerr << "WARNING: Failed to initialize native webcam capture; continuing without webcam"+ << std::endl;+ std::cout << "{\"event\":\"warning\",\"code\":\"webcam-unavailable\",\"message\":"+ "\"Failed to initialize native webcam capture\"}"+ << std::endl;+ config.webcamEnabled = false;+ } else {+ std::cout << "{\"event\":\"webcam-format\",\"schemaVersion\":2,\"width\":" << webcamCapture.width()+ << ",\"height\":" << webcamCapture.height()+ << ",\"fps\":" << webcamCapture.fps()+ << ",\"deviceName\":\"" << jsonEscape(wideToUtf8(webcamCapture.selectedDeviceName()))+ << "\"}" << std::endl;+ writeSeparateWebcam = !config.webcamOutputPath.empty();}- std::cout << "{\"event\":\"webcam-format\",\"schemaVersion\":2,\"width\":" << webcamCapture.width()- << ",\"height\":" << webcamCapture.height()- << ",\"fps\":" << webcamCapture.fps()- << ",\"deviceName\":\"" << jsonEscape(wideToUtf8(webcamCapture.selectedDeviceName()))- << "\"}" << std::endl;- writeSeparateWebcam = !config.webcamOutputPath.empty();}WasapiLoopbackCapture loopbackCapture;@@ -601,9 +616,21 @@ int main(int argc, char* argv[]) {const auto frameDuration = std::chrono::duration_cast<std::chrono::steady_clock::duration>(std::chrono::duration<double>(1.0 / config.fps));uint64_t frameIndex = 0;- uint64_t lastWrittenWebcamSequence = 0;- uint64_t webcamOutputFrameIndex = 0;int64_t lastEncodedVideoTimestampHns = -1;+ int64_t lastWebcamTimestampHns = -1;+ // Media Foundation's H.264 encoder MFT does not honor irregular input+ // sample times for a VFR source: it numbers output samples+ // sequentially at its configured nominal frame rate regardless of the+ // SampleTime we attach (confirmed empirically -- varying, correctly+ // increasing input timestamps still produced perfectly even output+ // spacing). Since we cannot make the encoder respect real capture+ // time, we instead make the encoder's assumption true: call+ // writeBgraFrame() on a real-time-paced cadence (duplicating the+ // latest available camera frame when the camera hasn't produced a+ // newer one yet), so "sample N is at N/fps" is actually correct.+ int64_t nextWebcamWriteDueHns = 0;+ const int64_t nominalWebcamIntervalHns =+ static_cast<int64_t>(10'000'000ULL / std::max(1, webcamCapture.fps()));while (!control.stopRequested && !encodeFailed) {Microsoft::WRL::ComPtr<IMFSample> videoSample;@@ -654,19 +681,43 @@ int main(int argc, char* argv[]) {frameTimestampHns =lastEncodedVideoTimestampHns + static_cast<int64_t>(10'000'000ULL / config.fps);}- if (writeSeparateWebcam && webcamFrame.data &&- latestWebcamSequence != lastWrittenWebcamSequence) {- const int64_t webcamTimestampHns = static_cast<int64_t>(- (webcamOutputFrameIndex * 10'000'000ULL) / std::max(1, webcamCapture.fps()));- hasWebcamSample = webcamEncoder.captureBgraSample(webcamFrame, webcamTimestampHns, webcamSample);- if (!hasWebcamSample) {- encodeFailed = true;- control.stopRequested = true;- control.cv.notify_all();- break;+ if (writeSeparateWebcam && webcamFrame.data) {+ // Anchor to the same recording-start origin as screen video/audio,+ // using real elapsed host-clock time (not a synthetic frame-index+ // clock) so a long recording can't accumulate clock-origin drift.+ const auto elapsedSinceStart = std::chrono::steady_clock::now() - control.recordingStartedAt;+ const int64_t elapsedHns = std::chrono::duration_cast<+ std::chrono::duration<int64_t, std::ratio<1, 10'000'000>>>(elapsedSinceStart)+ .count();+ const int64_t targetElapsedHns =+ std::max<int64_t>(0, elapsedHns - control.pausedDurationHns());+ // The H.264 encoder MFT does not honor irregular per-sample+ // timestamps for a VFR source -- it numbers output samples+ // sequentially at its configured nominal rate regardless of the+ // SampleTime attached to each input sample. So the only way to+ // keep the encoded webcam file in sync with real elapsed time is+ // to call writeBgraFrame() *at* that nominal cadence, duplicating+ // the latest available camera frame when the camera hasn't+ // produced a newer one yet (VFR capture -> CFR encode resampling).+ if (targetElapsedHns >= nextWebcamWriteDueHns) {+ int64_t webcamTimestampHns = targetElapsedHns;+ if (lastWebcamTimestampHns >= 0 && webcamTimestampHns <= lastWebcamTimestampHns) {+ webcamTimestampHns = lastWebcamTimestampHns + nominalWebcamIntervalHns;+ }+ if (!webcamEncoder.writeBgraFrame(webcamFrame, webcamTimestampHns)) {+ encodeFailed = true;+ control.stopRequested = true;+ control.cv.notify_all();+ return;+ }+ lastWebcamTimestampHns = webcamTimestampHns;+ nextWebcamWriteDueHns += nominalWebcamIntervalHns;+ if (nextWebcamWriteDueHns <= targetElapsedHns) {+ // Fell behind (e.g. coming out of a pause, or a stall) --+ // resync to now instead of trying to catch up frame-by-frame.+ nextWebcamWriteDueHns = targetElapsedHns + nominalWebcamIntervalHns;+ }}- lastWrittenWebcamSequence = latestWebcamSequence;- webcamOutputFrameIndex += 1;}if (latestFrameTexture) {// captureVideoSample performs the GPU readback@@ -869,6 +920,7 @@ int main(int argc, char* argv[]) {if (audioMixer) {audioMixer->beginTimeline();}+ control.recordingStartedAt = std::chrono::steady_clock::now();startVideoWriter();std::cout << "{\"event\":\"recording-started\",\"schemaVersion\":2}" << std::endl;diff --git a/electron/native/wgc-capture/src/webcam_capture.cpp b/electron/native/wgc-capture/src/webcam_capture.cppindex 783b854a4..1b911a4ce 100644--- a/electron/native/wgc-capture/src/webcam_capture.cpp+++ b/electron/native/wgc-capture/src/webcam_capture.cpp@@ -242,11 +242,15 @@ bool WebcamCapture::selectDevice(const std::wstring& deviceId, const std::wstrinbool WebcamCapture::configureReader(int requestedWidth, int requestedHeight, int requestedFps) {Microsoft::WRL::ComPtr<IMFAttributes> attributes;- if (!succeeded(MFCreateAttributes(&attributes, 2), "MFCreateAttributes(webcam reader)")) {+ if (!succeeded(MFCreateAttributes(&attributes, 3), "MFCreateAttributes(webcam reader)")) {return false;}attributes->SetUINT32(MF_SOURCE_READER_ENABLE_VIDEO_PROCESSING, TRUE);attributes->SetUINT32(MF_READWRITE_DISABLE_CONVERTERS, FALSE);+ // Ask the pipeline to minimize internal buffering/lookahead so a frame+ // reaches ReadSample() as soon as possible after the driver delivers it,+ // rather than sitting queued behind MF's default lookahead buffering.+ attributes->SetUINT32(MF_LOW_LATENCY, TRUE);if (!succeeded(MFCreateSourceReaderFromMediaSource(mediaSource_.Get(), attributes.Get(), &sourceReader_),"MFCreateSourceReaderFromMediaSource(webcam)")) {diff --git a/electron/preload.ts b/electron/preload.tsindex 79e42a95e..a7db6b5dd 100644--- a/electron/preload.ts+++ b/electron/preload.ts@@ -142,6 +142,7 @@ contextBridge.exposeInMainWorld("electronAPI", {recordingId: number;webcam: { fileName: string; videoData: ArrayBuffer };cursorCaptureMode?: import("../src/lib/recordingSession").CursorCaptureMode;+ webcamOffsetMs?: number;}) => {return ipcRenderer.invoke("attach-native-mac-webcam-recording", payload);},diff --git a/scripts/build-windows-wgc-helper.mjs b/scripts/build-windows-wgc-helper.mjsindex e0e3219bb..10566a657 100644--- a/scripts/build-windows-wgc-helper.mjs+++ b/scripts/build-windows-wgc-helper.mjs@@ -42,27 +42,55 @@ function findVcVarsAll() {}}- const roots = [- process.env.VSINSTALLDIR,- "C:\\Program Files\\Microsoft Visual Studio\\2026\\Community",- "C:\\Program Files\\Microsoft Visual Studio\\2026\\Professional",- "C:\\Program Files\\Microsoft Visual Studio\\2026\\Enterprise",- "C:\\Program Files (x86)\\Microsoft Visual Studio\\2026\\BuildTools",- "C:\\Program Files (x86)\\Microsoft Visual Studio\\2026\\Community",- "C:\\Program Files\\Microsoft Visual Studio\\2022\\Community",- "C:\\Program Files\\Microsoft Visual Studio\\2022\\Professional",- "C:\\Program Files\\Microsoft Visual Studio\\2022\\Enterprise",- "C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\BuildTools",- "C:\\Program Files (x86)\\Microsoft Visual Studio\\2022\\Community",- ];-- for (const root of roots.filter(Boolean)) {- const candidate = path.join(root, "VC", "Auxiliary", "Build", "vcvarsall.bat");+ if (process.env.VSINSTALLDIR) {+ const candidate = path.join(process.env.VSINSTALLDIR, "VC", "Auxiliary", "Build", "vcvarsall.bat");if (fs.existsSync(candidate)) {return candidate;}}+ // vswhere doesn't always enumerate pre-release channels (e.g. "Insiders"+ // builds), and the on-disk layout for those isn't a stable "<year>\<edition>"+ // path -- Visual Studio 2026 Insiders installs under a numeric product+ // version folder like "18\Insiders\<edition>" instead of "2026\<edition>".+ // Walk the install roots generically instead of hard-coding version/channel+ // names so new VS releases and preview channels are found automatically.+ const editions = ["Community", "Professional", "Enterprise", "BuildTools"];+ const installRoots = [+ "C:\\Program Files\\Microsoft Visual Studio",+ "C:\\Program Files (x86)\\Microsoft Visual Studio",+ ];++ const listDirs = (dir) => {+ try {+ return fs+ .readdirSync(dir, { withFileTypes: true })+ .filter((entry) => entry.isDirectory())+ .map((entry) => path.join(dir, entry.name));+ } catch {+ return [];+ }+ };++ for (const installRoot of installRoots) {+ for (const versionDir of listDirs(installRoot)) {+ // versionDir is either an edition directly ("2022\Community") or a+ // channel that nests editions ("18\Insiders\Community").+ for (const channelDir of [versionDir, ...listDirs(versionDir)]) {+ const direct = path.join(channelDir, "VC", "Auxiliary", "Build", "vcvarsall.bat");+ if (fs.existsSync(direct)) {+ return direct;+ }+ for (const edition of editions) {+ const nested = path.join(channelDir, edition, "VC", "Auxiliary", "Build", "vcvarsall.bat");+ if (fs.existsSync(nested)) {+ return nested;+ }+ }+ }+ }+ }+return null;}diff --git a/src/hooks/useScreenRecorder.ts b/src/hooks/useScreenRecorder.tsindex 72ddc529b..e0ca56a8b 100644--- a/src/hooks/useScreenRecorder.ts+++ b/src/hooks/useScreenRecorder.ts@@ -79,13 +79,21 @@ type NativeWindowsRecordingHandle = {recordingId: number;finalizing: boolean;paused: boolean;- webcamRecorder: RecorderHandle | null;};type NativeMacRecordingHandle = {recordingId: number;finalizing: boolean;paused: boolean;+ /**+ * Milliseconds the browser-recorded webcam clip started before the native+ * macOS helper confirmed its screen recording actually began (negative --+ * the webcam MediaRecorder starts immediately in the renderer, but the+ * ScreenCaptureKit helper needs to spawn a process and start capturing+ * before its own recording truly starts). `null` if webcam wasn't+ * recorded via the browser sidecar for this session.+ */+ webcamOffsetMs: number | null;};export function useScreenRecorder(): UseScreenRecorderReturn {@@ -427,109 +435,62 @@ export function useScreenRecorder(): UseScreenRecorderReturn {[cursorCaptureMode, teardownMedia],);- const finalizeNativeWindowsRecording = useCallback(- async (discard = false) => {- const activeNativeRecording = nativeWindowsRecording.current;- if (!activeNativeRecording || activeNativeRecording.finalizing) {- return false;- }-- activeNativeRecording.finalizing = true;- if (!discard) {- setSaving(true);- }- const activeWebcamRecorder = activeNativeRecording.webcamRecorder;- const duration = Math.max(0, getRecordingDurationMs());- if (- activeWebcamRecorder?.recorder.state === "recording" ||- activeWebcamRecorder?.recorder.state === "paused"- ) {- try {- activeWebcamRecorder.recorder.stop();- } catch {- // Recorder may already be stopping.- }- }- if (activeWebcamRecorder && webcamRecorder.current === activeWebcamRecorder) {- webcamRecorder.current = null;- }-- const clearNativeRecordingState = () => {- nativeWindowsRecording.current = null;- setRecording(false);- setPaused(false);- setElapsedSeconds(0);- accumulatedDurationMs.current = 0;- segmentStartedAt.current = null;- };+ const finalizeNativeWindowsRecording = useCallback(async (discard = false) => {+ const activeNativeRecording = nativeWindowsRecording.current;+ if (!activeNativeRecording || activeNativeRecording.finalizing) {+ return false;+ }- try {- const result = await window.electronAPI.stopNativeWindowsRecording(discard);- if (discard || result.discarded) {- clearNativeRecordingState();- return true;- }- if (!result.success) {- console.error("Failed to stop native Windows recording:", result.error);- toast.error(result.error ?? "Failed to stop native Windows recording");- activeNativeRecording.finalizing = false;- return true;- }+ activeNativeRecording.finalizing = true;+ if (!discard) {+ setSaving(true);+ }- const nativeScreenPath = result.session?.screenVideoPath ?? result.path;- let storedSession = result.session;- if (activeWebcamRecorder && nativeScreenPath) {- const webcamBlob = await activeWebcamRecorder.recordedBlobPromise.catch(() => null);- const screenRead = await window.electronAPI.readBinaryFile(nativeScreenPath);- if (webcamBlob && webcamBlob.size > 0 && screenRead.success && screenRead.data) {- const fixedWebcamBlob = await fixWebmDuration(webcamBlob, duration);- const nativeScreenFileName =- nativeScreenPath.split(/[\\/]/).pop() ??- `${RECORDING_FILE_PREFIX}${activeNativeRecording.recordingId}.mp4`;- const webcamFileName = `${RECORDING_FILE_PREFIX}${activeNativeRecording.recordingId}${WEBCAM_FILE_SUFFIX}${VIDEO_FILE_EXTENSION}`;- const stored = await window.electronAPI.storeRecordedSession({- screen: {- videoData: screenRead.data,- fileName: nativeScreenFileName,- },- webcam: {- videoData: await fixedWebcamBlob.arrayBuffer(),- fileName: webcamFileName,- },- createdAt: activeNativeRecording.recordingId,- cursorCaptureMode,- });- if (stored.success && stored.session) {- storedSession = stored.session;- }- }- }+ const clearNativeRecordingState = () => {+ nativeWindowsRecording.current = null;+ setRecording(false);+ setPaused(false);+ setElapsedSeconds(0);+ accumulatedDurationMs.current = 0;+ segmentStartedAt.current = null;+ };+ try {+ const result = await window.electronAPI.stopNativeWindowsRecording(discard);+ if (discard || result.discarded) {clearNativeRecordingState();- if (storedSession) {- await window.electronAPI.setCurrentRecordingSession(storedSession);- } else if (result.path) {- await window.electronAPI.setCurrentVideoPath(result.path);- }-- await window.electronAPI.switchToEditor();return true;- } catch (error) {- console.error("Error saving native Windows recording:", error);- toast.error(- error instanceof Error ? error.message : "Failed to save native Windows recording",- );+ }+ if (!result.success) {+ console.error("Failed to stop native Windows recording:", result.error);+ toast.error(result.error ?? "Failed to stop native Windows recording");activeNativeRecording.finalizing = false;return true;- } finally {- if (discardRecordingId.current === activeNativeRecording.recordingId) {- discardRecordingId.current = null;- }- setSaving(false);}- },- [cursorCaptureMode, getRecordingDurationMs],- );++ clearNativeRecordingState();+ if (result.session) {+ await window.electronAPI.setCurrentRecordingSession(result.session);+ } else if (result.path) {+ await window.electronAPI.setCurrentVideoPath(result.path);+ }++ await window.electronAPI.switchToEditor();+ return true;+ } catch (error) {+ console.error("Error saving native Windows recording:", error);+ toast.error(+ error instanceof Error ? error.message : "Failed to save native Windows recording",+ );+ activeNativeRecording.finalizing = false;+ return true;+ } finally {+ if (discardRecordingId.current === activeNativeRecording.recordingId) {+ discardRecordingId.current = null;+ }+ setSaving(false);+ }+ }, []);const finalizeNativeMacRecording = useCallback(async (discard = false) => {@@ -560,7 +521,16 @@ export function useScreenRecorder(): UseScreenRecorderReturn {if (!webcamBlob || webcamBlob.size === 0) {return undefined;}- const fixedWebcamBlob = await fixWebmDuration(webcamBlob, duration);+ // The webcam MediaRecorder started before the native recording did (see+ // webcamOffsetMs on NativeMacRecordingHandle), so its real content is+ // longer than the screen's active `duration` by that same head start.+ // Patching the WebM's declared duration to the screen's shorter duration+ // would make that extra leading footage unseekable in a standard <video>+ // element (which trusts the container's declared duration/seek range) --+ // exactly the footage the editor needs to skip into to compensate for+ // webcamOffsetMs, so it must stay reachable.+ const webcamHeadStartMs = Math.max(0, -(activeNativeRecording.webcamOffsetMs ?? 0));+ const fixedWebcamBlob = await fixWebmDuration(webcamBlob, duration + webcamHeadStartMs);return {videoData: await fixedWebcamBlob.arrayBuffer(),fileName: `${RECORDING_FILE_PREFIX}${activeNativeRecording.recordingId}${WEBCAM_FILE_SUFFIX}${VIDEO_FILE_EXTENSION}`,@@ -600,6 +570,9 @@ export function useScreenRecorder(): UseScreenRecorderReturn {recordingId: activeNativeRecording.recordingId,webcam: webcamAsset,cursorCaptureMode,+ ...(typeof activeNativeRecording.webcamOffsetMs === "number"+ ? { webcamOffsetMs: activeNativeRecording.webcamOffsetMs }+ : {}),});if (attachResult.success) {result.session = attachResult.session;@@ -831,15 +804,12 @@ export function useScreenRecorder(): UseScreenRecorderReturn {if (!isCountdownRunActive(countdownRunToken)) {return true;}- }- const browserWebcamRecorder =- webcamEnabled && webcamStream.current- ? createRecorderHandle(webcamStream.current, {- mimeType: selectMimeType(),- videoBitsPerSecond: BITRATE_BASE,- })- : null;- if (webcamEnabled && !browserWebcamRecorder) {+ // Release the renderer-side validation stream before asking the native+ // helper to open the same device: most webcams only allow one exclusive+ // capture session, and native (Media Foundation/DirectShow) now owns+ // webcam capture directly, sharing the same recording-start clock as+ // screen video and audio instead of racing a separately-started browser+ // MediaRecorder against the helper's own process-spawn/WGC-init latency.stopWebcamPreviewStream();}const request: NativeWindowsRecordingRequest = {@@ -867,7 +837,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {},},webcam: {- enabled: webcamEnabled && !browserWebcamRecorder,+ enabled: webcamEnabled,deviceId: webcamDeviceId,deviceName: webcamDeviceName,width: 0,@@ -880,12 +850,6 @@ export function useScreenRecorder(): UseScreenRecorderReturn {};const result = await window.electronAPI.startNativeWindowsRecording(request);if (!result.success || !result.recordingId) {- if (- browserWebcamRecorder?.recorder.state === "recording" ||- browserWebcamRecorder?.recorder.state === "paused"- ) {- browserWebcamRecorder.recorder.stop();- }throw new Error(result.error ?? "Native Windows capture failed.");}@@ -894,9 +858,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {recordingId: result.recordingId,finalizing: false,paused: false,- webcamRecorder: browserWebcamRecorder,};- webcamRecorder.current = browserWebcamRecorder;accumulatedDurationMs.current = 0;segmentStartedAt.current = Date.now();allowAutoFinalize.current = true;@@ -943,6 +905,13 @@ export function useScreenRecorder(): UseScreenRecorderReturn {Number(selectedSource.display_id) || parseMacDisplayIdFromSourceId(selectedSource.id);const windowId = parseMacWindowIdFromSourceId(selectedSource.id);let nativeWebcamRecorder: RecorderHandle | null = null;+ // createRecorderHandle() calls MediaRecorder.start() synchronously, so the+ // webcam clip's first frame is captured right now -- before the native+ // ScreenCaptureKit helper below has even been spawned. Stamp that instant+ // so the gap to the helper's confirmed start can be trimmed from the+ // webcam asset later instead of leaving the camera looking like it lags+ // behind screen/audio (see webcamOffsetMs on NativeMacRecordingHandle).+ let nativeWebcamRecorderStartedAtMs: number | null = null;if (webcamEnabled) {if (!webcamReady.current) {await new Promise<void>((resolve) => {@@ -962,6 +931,7 @@ export function useScreenRecorder(): UseScreenRecorderReturn {return true;}if (webcamStream.current) {+ nativeWebcamRecorderStartedAtMs = performance.now();nativeWebcamRecorder = createRecorderHandle(webcamStream.current, {mimeType: selectMimeType(),videoBitsPerSecond: BITRATE_BASE,@@ -1034,11 +1004,20 @@ export function useScreenRecorder(): UseScreenRecorderReturn {return true;}+ // The IPC call above only resolves once the helper's stdout confirms its+ // screen capture has truly started (see waitForNativeMacCaptureStart in+ // electron/ipc/handlers.ts), so this is a reliable proxy for the native+ // recording's real t=0 in the same clock the webcam timestamp used above.+ const nativeRecordingConfirmedStartedAtMs = performance.now();recordingId.current = result.recordingId;nativeMacRecording.current = {recordingId: result.recordingId,finalizing: false,paused: false,+ webcamOffsetMs:+ nativeWebcamRecorder && nativeWebcamRecorderStartedAtMs !== null+ ? -(nativeRecordingConfirmedStartedAtMs - nativeWebcamRecorderStartedAtMs)+ : null,};webcamRecorder.current = nativeWebcamRecorder;accumulatedDurationMs.current = 0;@@ -1438,9 +1417,6 @@ export function useScreenRecorder(): UseScreenRecorderReturn {if (!result.success) {throw new Error(result.error ?? "Failed to resume native Windows recording");}- if (activeNativeWindowsRecording.webcamRecorder?.recorder.state === "paused") {- activeNativeWindowsRecording.webcamRecorder.recorder.resume();- }activeNativeWindowsRecording.paused = false;segmentStartedAt.current = Date.now();setPaused(false);@@ -1452,9 +1428,6 @@ export function useScreenRecorder(): UseScreenRecorderReturn {if (!result.success) {throw new Error(result.error ?? "Failed to pause native Windows recording");}- if (activeNativeWindowsRecording.webcamRecorder?.recorder.state === "recording") {- activeNativeWindowsRecording.webcamRecorder.recorder.pause();- }activeNativeWindowsRecording.paused = true;accumulatedDurationMs.current = pausedAtMs;segmentStartedAt.current = null;diff --git a/src/lib/ai-edition/document/migrate.ts b/src/lib/ai-edition/document/migrate.tsindex 02632d83c..3bfb37073 100644--- a/src/lib/ai-edition/document/migrate.ts+++ b/src/lib/ai-edition/document/migrate.ts@@ -59,6 +59,7 @@ function toLegacyMedia(input: ProjectMedia | undefined): ProjectMedia | null {if (!input) return null;const media: ProjectMedia = { screenVideoPath: input.screenVideoPath };if (input.webcamVideoPath) media.webcamVideoPath = input.webcamVideoPath;+ if (typeof input.webcamOffsetMs === "number") media.webcamOffsetMs = input.webcamOffsetMs;if (input.cursorCaptureMode) media.cursorCaptureMode = input.cursorCaptureMode;return media;}@@ -84,6 +85,7 @@ export function migrateProjectDataToAxcutDocument(: null;const webcamVideoPath = input.media?.webcamVideoPath;+ const webcamOffsetMs = input.media?.webcamOffsetMs ?? 0;const assets = screenPath? [@@ -93,7 +95,7 @@ export function migrateProjectDataToAxcutDocument(label: screenPath.split(/[\\/]/).pop() || "Recording",originalPath: screenPath,cameraTrack: webcamVideoPath- ? { sourcePath: webcamVideoPath, startMs: 0, offsetMs: 0, visible: true }+ ? { sourcePath: webcamVideoPath, startMs: 0, offsetMs: webcamOffsetMs, visible: true }: null,},]diff --git a/src/lib/recordingSession.ts b/src/lib/recordingSession.tsindex f7d69cbf7..5fd06bc25 100644--- a/src/lib/recordingSession.ts+++ b/src/lib/recordingSession.ts@@ -1,6 +1,15 @@export interface ProjectMedia {screenVideoPath: string;webcamVideoPath?: string;+ /**+ * Milliseconds to shift the webcam asset's playback position relative to+ * the screen recording. Negative when the webcam started capturing before+ * the screen recording's real start (e.g. the browser MediaRecorder for+ * the webcam is started in the renderer before the native Windows helper+ * process finishes spawning and confirms recording), so the editor skips+ * that much extra leading footage instead of showing stale camera frames.+ */+ webcamOffsetMs?: number;cursorCaptureMode?: CursorCaptureMode;}@@ -27,6 +36,8 @@ export interface StoreRecordedSessionInput {* timeline for anything that took the streaming path.*/durationMs?: number;+ /** See {@link ProjectMedia.webcamOffsetMs}. */+ webcamOffsetMs?: number;}export function normalizeCursorCaptureMode(value: unknown): CursorCaptureMode | undefined {@@ -56,10 +67,15 @@ export function normalizeProjectMedia(candidate: unknown): ProjectMedia | null {const webcamVideoPath = normalizePath(raw.webcamVideoPath);const cursorCaptureMode = normalizeCursorCaptureMode(raw.cursorCaptureMode);+ const webcamOffsetMs =+ typeof raw.webcamOffsetMs === "number" && Number.isFinite(raw.webcamOffsetMs)+ ? raw.webcamOffsetMs+ : undefined;return {screenVideoPath,...(webcamVideoPath ? { webcamVideoPath } : {}),+ ...(webcamOffsetMs !== undefined ? { webcamOffsetMs } : {}),...(cursorCaptureMode ? { cursorCaptureMode } : {}),};}