Skip to content

fix(recording): write fragmented MP4 so a killed helper keeps its file - #338

Merged
EtienneLescot merged 1 commit into
mainfrom
claude/fmp4-native-capture-822580
Aug 11, 2026
Merged

fix(recording): write fragmented MP4 so a killed helper keeps its file#338
EtienneLescot merged 1 commit into
mainfrom
claude/fmp4-native-capture-822580

Conversation

@EtienneLescot

@EtienneLescot EtienneLescot commented Aug 11, 2026

Copy link
Copy Markdown
Collaborator

Summary

The kill test passed, with the ablation. Killed 20 s into a recording, the pre-change binary leaves an unreadable file and this one leaves a file that plays to the end. Numbers in Testing.

On #252 / #292 / #327 a Windows recording freezes and the user loses the whole file. The freeze is not what causes that.

A plain MP4 has no index until IMFSinkWriter::Finalize() writes moov at the very end (mf_encoder.cpp). When the shutdown watchdog force-exits a wedged helper with TerminateProcess, the .mp4 on disk holds every captured frame and no way to read them. Minutes of capture thrown away for ~8 KB of table.

A fragmented MP4 writes its index up front and its samples in self-describing moof+mdat pairs. The same kill leaves a file that plays up to the last complete fragment (1 s here).

  • What this changes: the data loss.
  • What it does not change: the freeze. The user still sees a recording that stops on its own. That stays open.

The reason to take this angle: it works without knowing which call is stuck. Every other lead in the investigation moves probabilities; this one moves the outcome.

Related issue

Refs #252
Refs #292
Refs #327

Type of change

  • Bug fix

Release impact

  • Patch

Desktop impact

  • Windows
  • macOS

Linux is deliberately out of scope — see below.


What actually changed

WindowsMFCreateFMPEG4MediaSink requires both output media types at construction, which inverts the order the encoder was written in (create the sink writer, then AddStream). So:

  • the AAC output type moves out of configureAudioStream into buildAacOutputType, and the sampleRate/channels/blockAlign guard moves with it;
  • createSinkWriterFromUrl becomes createSinkWriter with a fragmented switch, rather than a second copy of the software-MFT registration, the hardware-transform flag and the D3D manager;
  • stream positions are read back off the sink by major type, not assumed to be 0/1. A wrong index would aim audio writes at the video track. It would also fail loudly at SetInputMediaType — an H.264 input type against an AAC stream sink has no encoder that can bridge it — so the failure mode here is a refused init, never silent corruption.

macOS — one line: writer.movieFragmentInterval = CMTime(seconds: 1, ...). finishWriting() still writes a normal moov on a clean stop; the interval only matters if the process dies first.

Linux — deferred, not forgotten. frag_keyframe+empty_moov would work, but empty_moov makes the output permanently non-seekable and the native Linux path never passes through reindexRecordingOnDisk (that normalization is WebM/MediaRecorder only). Nothing would put an index back. The editor's scrub cost on a long fMP4 has to be measured before this ships.

Two things beyond the plan, both about not regressing

This area is the fallback chain that produced #336 last week, so:

  1. A fifth attempt with the plain container, tried only after every fragmented attempt has failed. A machine where anything about MFCreateFMPEG4MediaSink does not work — an output type it refuses, a stream layout that does not resolve — records exactly as it does today instead of not recording. The container is the point of this PR and it is still not worth a recording. container in the encoder-selection event reports fragmented-mp4 or mp4, because a bug report that cannot tell them apart cannot say whether a truncated file was supposed to survive its kill.

  2. releaseSinkWriter(). MFCreateSinkWriterFromMediaSink does not take ownership: releasing the writer left the fragmented sink live and the output file open, so the next attempt's MFCreateFile(MF_OPENMODE_DELETE_IF_EXIST) would have raced the previous attempt's own handle. That alone would have broken the fallback chain this PR is required to preserve. It now shuts the sink down and closes the byte stream, both between attempts and at finalize().

The four existing fallback paths (preferSoftwareEncoder, default, DXGI→CPU, software encoder) all stay fragmented. injectDefaultSinkWriterFailureOnce still fires exactly once, and now fires before the byte stream is created so an injected failure cannot leave the output file open.


Testing

Results

Compiles (Windows x64, /W4) run 31477279713 — no warnings from mf_encoder.cpp
Compiles (macOS arm64 + x64) ✅ same run
Kill test + ablation the merge criterion, below
Nominal recording test:wgc-helper:win, exit 0
Nominal + system audio --system-audio, exit 0
Injected-failure → software encoder --software-fallback, exit 0, still fragmented-mp4
macOS runtime ⬜ not run — builds, but no macOS machine here

The kill test — the merge criterion

Record 20 s, taskkill /F the helper by PID (the watchdog's TerminateProcess, reproduced), then ask ffprobe and a full ffmpeg -f null - decode what survived. Same sequence against the CI build of main @ 4f9d74a4, this branch's base — that ablation is the half that makes it mean anything.

container on disk result
before / video only 4.5 MB unreadableInvalid data found when processing input
before / system audio 8.4 MB unreadable — same
after / video only fragmented-mp4 8.8 MB ✅ readable, 20.0 s, h264, full decode clean
after / system audio fragmented-mp4 7.2 MB ✅ readable, 19.5 s, h264 + aac, full decode clean

Both "before" rows are the bug exactly as reported: every captured frame is on disk, and none of it is reachable.

The audio row also settles the one thing this PR could not check by reading: MFCreateFMPEG4MediaSink accepts the hand-built AAC output type, so no MF_MT_AUDIO_BLOCK_ALIGNMENT / MF_MT_AAC_AUDIO_PROFILE_LEVEL_INDICATION is needed and the container does not silently fall back to plain MP4 when audio is on. Fragments also close on schedule — no CODECAPI_AVEncMPVGOPSize work needed.

Nominal and fallback paths

Against the same binary, via OPENSCREEN_WGC_CAPTURE_EXE so no MSVC is required:

$env:OPENSCREEN_WGC_CAPTURE_EXE = "C:\path\to\wgc-capture.exe"; npm run test:wgc-helper:win

npm run test:wgc-helper:win, --system-audio and --software-fallback all exit 0, including the two assertions added here: container === "fragmented-mp4", and a 60 % prefix of the output still decodes.

Honest about coverage: --software-fallback exercises attempt 1 (fragmented, default, injected failure) → attempt 2 (fragmented, software encoder). It does not reach the DXGI→CPU retry (the GPU path is off by default) or the unfragmented last resort, which by construction only runs when every fragmented attempt has failed. Neither has been exercised on real hardware.

Reproducing

Put the helper somewhere with a short path. A helper whose own .exe path approaches MAX_PATH dies at startup with STATUS_STACK_BUFFER_OVERRUN (0xC0000409) and no output at all — unrelated to anything here, but it will waste an afternoon. 259 characters crashed; ~250 was fine.

Still open after this

The freeze itself is neither reproduced nor fixed. Also unrelated-but-adjacent and untouched here: the --selftest probe only checks that the file exists, the frozen-helper leak on macOS, and pinning the D3D device to the captured monitor's adapter.

A frozen recording on Windows costs the user the whole file, and the freeze is
not why. A plain MP4 has no index until IMFSinkWriter::Finalize() writes moov at
the very end, so when the shutdown watchdog force-exits a wedged helper the .mp4
on disk holds every frame and no way to read them. Minutes of capture thrown
away for about eight kilobytes of table. That is issues #252 / #292 / #327.

A fragmented MP4 writes its index up front and its samples in self-describing
moof+mdat pairs, so the same kill leaves a file that plays up to the last
complete fragment. This does not fix the freeze -- the recording still stops on
its own -- it stops the freeze from destroying the recording, and it does so
without anyone knowing which call is stuck.

MFCreateFMPEG4MediaSink wants both output media types at construction, which
inverts the order the encoder was written in: it created the sink writer and
described the streams afterwards with AddStream. So the AAC output type moves
out of configureAudioStream into buildAacOutputType, the format guard moves with
it, and createSinkWriter grows a `fragmented` switch instead of a second copy of
the software-MFT registration, the hardware-transform flag and the D3D manager.
The stream positions are read back off the sink by major type rather than
assumed: a wrong index would aim audio writes at the video track.

Two things this had to not break. The first is the fallback chain that produced
the #336 regression -- all four paths stay fragmented, and a fifth attempt with
the plain container runs only after every fragmented one has failed, so a
machine the fragmented sink does not fit records exactly as it did before this
commit rather than not recording. `container` in the encoder-selection event
says which one was used, because a bug report that cannot tell them apart cannot
say whether a truncated file was supposed to survive its kill. The second is
ownership: MFCreateSinkWriterFromMediaSink does not take it, so releasing the
writer left the sink live and the output file open, and the next attempt's
MFCreateFile(DELETE_IF_EXIST) would have raced the previous attempt's own
handle. releaseSinkWriter() shuts the sink down and closes the byte stream,
between attempts and at finalize().

macOS gets the same property from one AVAssetWriter.movieFragmentInterval;
finishWriting() still writes a normal moov on a clean stop. Linux stays plain:
empty_moov makes the output permanently non-seekable and the native Linux path
has no re-index step, so the editor's scrub cost has to be measured first.

The helper test truncates its own output to 60% and reprobes it. That is a proxy
for the kill, not a replacement -- it proves the container survives losing its
tail, not that the helper flushed anything before dying.
@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Recording now uses one-second fragmented MP4 output on macOS and Windows. Windows retries with plain MP4 when fragmented setup fails, reports the selected container, and tests truncated output readability.

Changes

Fragmented MP4 recording

Layer / File(s) Summary
Windows sink creation and ownership
electron/native/wgc-capture/src/mf_encoder.h, electron/native/wgc-capture/src/mf_encoder.cpp
MFEncoder creates fragmented or plain MP4 sinks, prepares output types before sink creation, resolves fragmented stream indices, and releases media-sink resources during finalization.
Windows container selection and validation
electron/native/wgc-capture/src/mf_encoder.cpp, electron/native/wgc-capture/src/main.cpp, scripts/test-windows-wgc-helper.mjs
Windows attempts fragmented MP4 first, falls back to plain MP4, reports the selected container, and verifies truncated screen and webcam recordings.
Platform fragmentation behavior
electron/native/screencapturekit/Sources/OpenScreenScreenCaptureKitHelper/ScreenCaptureRecorder.swift, electron/native/README.md, technical-documentation/architecture/recording.md
macOS configures one-second movie fragments. Documentation describes Windows fallback, macOS and Windows recovery behavior, and Linux plain MP4 output.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant CaptureHelper
  participant MFEncoder
  participant MP4Sink
  participant EncoderEvent
  CaptureHelper->>MFEncoder: Initialize recording
  MFEncoder->>MP4Sink: Create one-second fragmented MP4 sink
  MP4Sink-->>MFEncoder: Return sink or setup failure
  MFEncoder->>MP4Sink: Retry plain MP4 when fragmented setup fails
  MFEncoder->>EncoderEvent: Report selected container
Loading

Possibly related PRs

Suggested reviewers: my-denia

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 35.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the main change: fragmented MP4 preserves recordings after forced helper termination.
Description check ✅ Passed The description covers all required template sections and provides detailed scope, platform impact, testing, and known limitations.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/fmp4-native-capture-822580

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
electron/native/wgc-capture/src/mf_encoder.cpp (1)

795-850: 🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift

The plain-MP4 fallback forces the software encoder, so a container failure downgrades the video encoder.

configureUnfragmentedFallback is called with forceSoftwareEncoder = true on both exit paths (Line 817 and Line 850). Consider a machine where MFCreateFMPEG4MediaSink or the fragmented stream layout is unavailable, but the default hardware encoder works. Every fragmented attempt fails for a container reason, and the only plain attempt then runs with forceSoftwareEncoder = true. The recording lands on the Microsoft software H.264 encoder, reports software-fallback, and shows the HUD software-encoder notice, even though the default encoder was never tried with the plain container.

Try the plain container with the default encoder before falling back to the software encoder.

♻️ Proposed change to keep the encoder ladder independent of the container
-    if (configureSinkWriterAttempt(true, kVideoEncoderSelectionSoftwareFallback, false, true)) {
-        return true;
-    }
-    return configureUnfragmentedFallback(true, kVideoEncoderSelectionSoftwareFallback);
+    if (configureSinkWriterAttempt(true, kVideoEncoderSelectionSoftwareFallback, false, true)) {
+        return true;
+    }
+    // Plain container with the default encoder first: a fragmented-sink failure
+    // is a container problem, and it must not decide which encoder is used.
+    if (configureUnfragmentedFallback(false, kVideoEncoderSelectionDefault)) {
+        return true;
+    }
+    return configureSinkWriterAttempt(true, kVideoEncoderSelectionSoftwareFallback, true, false);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@electron/native/wgc-capture/src/mf_encoder.cpp` around lines 795 - 850,
Update the fallback flow around configureUnfragmentedFallback so a
fragmented-container failure first retries the plain MP4 container with the
default encoder selection and forceSoftwareEncoder=false, including after the
DXGI retry path. Only invoke the software-encoder plain-container fallback after
the default-encoder plain-container attempt fails, preserving the existing
software fallback behavior and selection symbols.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@electron/native/wgc-capture/src/mf_encoder.cpp`:
- Around line 795-850: Update the fallback flow around
configureUnfragmentedFallback so a fragmented-container failure first retries
the plain MP4 container with the default encoder selection and
forceSoftwareEncoder=false, including after the DXGI retry path. Only invoke the
software-encoder plain-container fallback after the default-encoder
plain-container attempt fails, preserving the existing software fallback
behavior and selection symbols.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 052ab637-8bd8-4c44-8cfa-b1817555ebe3

📥 Commits

Reviewing files that changed from the base of the PR and between 4f9d74a and 9a368cd.

📒 Files selected for processing (7)
  • electron/native/README.md
  • electron/native/screencapturekit/Sources/OpenScreenScreenCaptureKitHelper/ScreenCaptureRecorder.swift
  • electron/native/wgc-capture/src/main.cpp
  • electron/native/wgc-capture/src/mf_encoder.cpp
  • electron/native/wgc-capture/src/mf_encoder.h
  • scripts/test-windows-wgc-helper.mjs
  • technical-documentation/architecture/recording.md

@EtienneLescot
EtienneLescot merged commit a6795d2 into main Aug 11, 2026
19 checks passed
@EtienneLescot
EtienneLescot deleted the claude/fmp4-native-capture-822580 branch August 11, 2026 10:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant