Skip to content

perf(recording): overlap the Windows screen readback with the previous encode - #4885

Open
kyzer1023 wants to merge 9 commits into
CapSoftware:mainfrom
kyzer1023:perf/windows-amd-readback-overlap
Open

kyzer1023 wants to merge 9 commits into
CapSoftware:mainfrom
kyzer1023:perf/windows-amd-readback-overlap

Conversation

@kyzer1023

@kyzer1023 kyzer1023 commented Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary

On Windows, the software encode path copies each captured D3D11 frame into a staging texture and then calls Map on it right away, so the capture thread waits for the GPU copy to finish before it can encode. This PR overlaps that wait with the previous frame's encode: it issues CopyResource for frame N, then maps and encodes frame N-1. The Map wait now happens while the previous encode runs, so the readback wait is gone.

What changed

  • scap-direct3d: a readback schedule (readback_schedule.rs) that tracks the in-flight staging copy, so a mapped slot is never reused and a failed Map is emitted, or dropped, before any later frame. Timestamps stay strictly increasing. The Windows-only code moved to windows_lib.rs.
  • cap-recording (win_readback.rs, win.rs, win_segmented.rs, win_fragmented_m4s.rs, oop_fragmented_m4s_win.rs, frame_pacing.rs): use the overlapped readback for the software encoders. Overlap is used only when the immediate context reports ID3D11Multithread protection and the opened codec is h264_amf or libx264. Anything else keeps the synchronous path. Pause, repeat, idle and end of stream flush the in-flight frame. Frames dropped by a failed encode, including the final flush, are counted.
  • scap-ffmpeg (direct3d.rs): reads the frame stride before the readback copy.
  • cap-enc-ffmpeg: exposes the segmented encoder's codec name and adds a RespawnExhausted error, so the pipeline can decide whether to overlap and can finalize once.

Benchmark (Windows desktop, Ryzen with Radeon 780M, h264_amf)

main this PR
Staging Map wait 0.6 to 1.3 ms 0.2 ms
Frame time at 30 fps (median / p95) 5.48 / 16.9 ms 4.23 / 8.0 ms
Frame time at 60 fps (median / p95) 4.08 / 7.9 ms 3.99 / 5.4 ms
Dropped frames 0 0

There were no dropped frames on main or on this branch, so this PR doesn't reduce drops. What it improves is per-frame time, mainly p95.

Cost

Each frame reaches the encoder one frame later than it does on main, so this adds one frame of latency (about 33 ms at 30 fps, 17 ms at 60 fps). Drop counts don't change.

Tests

On Windows (Radeon 780M), at this head:

  • cargo clippy -j1 -p cap-enc-ffmpeg -p cap-recording -p scap-direct3d -p scap-ffmpeg --all-targets -- -D warnings: the only findings are 11 existing lints in cap-recording files this PR doesn't touch (cursor.rs, capture_pipeline.rs, recovery/needs_remux_tests.rs, screen_capture/cadence.rs). Those files are identical on main. The changed files have no warnings.
  • cargo test -j1 --lib: cap-recording 920 passed, 0 failed, 4 ignored. scap-direct3d 17 passed, 1 ignored (includes the new readback schedule tests). scap-ffmpeg 1 passed. cap-enc-ffmpeg 283 passed, 1 failed: media_foundation_self_test_fault_falls_back_to_libx264_at_odd_sizes. That test expects the Media Foundation self-test to fail and fall back to libx264, but this machine has a working h264_mf. It fails the same way on main.
  • The benchmark above: a release build on the same machine, main against this branch.

Not run locally: macOS (none of this code runs there) or other GPU vendors.

Confidence Score: 5/5RetriggerView in Greptile

The latest changes appear safe to merge, with both previous findings addressed.

Summary

The PR overlaps Windows screen readback with the previous frame’s encode for supported codecs and protected contexts.

  • D3D11 frames can be copied now and read back on the next frame.
  • Windows software recording submits each captured frame after the next copy is queued.

Reviews (2) · Last reviewed commit: "fix(recording): count a frame that fails..." · Reviewed by Greptile

…encode

Issue CopyResource for frame N and Map frame N-1 so the staging Map wait
sits under the previous libx264 encode. Pause, repeat, and end flush the
in-flight frame, and a mapped slot is never reused.
`stride(0)` borrowed the frame while `data_mut(0)` was still borrowed.
The overlapped Map removes that readback wait under the previous encode
(h264_amf on AMD) and lowers per-frame p95. The frame is one encode late;
drop counts are unchanged.
…back

Overlap only when the immediate context reports ID3D11Multithread
protection and the opened codec is h264_amf or libx264. A failed Map
emits its fallback before any later frame, or drops it, so timestamps
stay strictly increasing. Pause and an idle receive flush the pending
surface, and an encoder error counts the already-copied next frame as
discarded.
Query ID3D11Multithread from the immediate context the capture callback
uses. A dropped real frame still replaces the pixels a repeat would copy.
A failed encode counts the frames it drops, including the final flush, and
respawn exhaustion is matched before it becomes a generic ffmpeg error.
The segmented pending wait is 1.5 frame intervals.
as_buffer again returns a buffer borrowed from the frame, with no unsafe
Send. Send is only on the overlapped ticket, and only that ticket is
created after multithread protection is confirmed. A respawn-exhausted
or poisoned-mutex failure at end of stream returns without draining.
Converter and ordinary FFmpeg failures still continue, and they now
increment the same discard counter as a failed final submit. Disk-stop
flushes count a failed submit. The manifest tracker finalizes once.
Disk-stop leaves the tracker open so the finalize after encoder flush
and subprocess finish still sees the child's last fragments. Early
finalization stays on fatal returns that never reach that path.
The pre-existing Crashed string check stays as on main. It no longer
sets the finalized flag, which only RespawnExhausted uses.
@kyzer1023

Copy link
Copy Markdown
Contributor Author

@greptileai review

@vercel

vercel Bot commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

@kyzer1023 is attempting to deploy a commit to the Cap Software Inc Team on Vercel.

A member of the Team first needs to authorize it.

Comment on lines 86 to 89
if let Some(since) = self.paused_since.take() {
if let Some(last) = self.last.as_mut() {
last.arrived += since.elapsed();
}

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.

P1 Pause checks fail clippy

FramePacer::next now nests two if let checks that can be joined with &&. This violates the repository's instruction to use the clippy-clean form and triggers the workspace's denied collapsible_if lint. Combine these checks so clippy can pass.

Context Used: AGENTS.md (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/recording/src/output_pipeline/frame_pacing.rs
Line: 86-89

Comment:
**Pause checks fail clippy**

`FramePacer::next` now nests two `if let` checks that can be joined with `&&`. This violates the repository's instruction to use the clippy-clean form and triggers the workspace's denied `collapsible_if` lint. Combine these checks so clippy can pass.

**Context Used:** AGENTS.md ([source](https://github.com/capsoftware/cap/blob/main/AGENTS.md))

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in bc81855: the two pause resume checks are now one let chain, so collapsible_if is clean. cargo clippy -p cap-recording --lib --tests passes on Windows.

Comment on lines +241 to +242
if let Err(error) = submit(delivered) {
break Err(error);

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.

P2 Discard counts miss failed frames

submit_batch does not count the frame whose submit call returns an error. That frame has already left the iterator, so the later loop counts only the remaining frames and discard_pending counts only the next copy. Normal callers do not call note_failed_final_submit.

For example, an encode error with one copy pending loses two frames but records only one discard. Count the failed submission here and remove the extra final-submit increment to avoid counting it twice.

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/recording/src/output_pipeline/win_readback.rs
Line: 241-242

Comment:
**Discard counts miss failed frames**

`submit_batch` does not count the frame whose `submit` call returns an error. That frame has already left the iterator, so the later loop counts only the remaining frames and `discard_pending` counts only the next copy. Normal callers do not call `note_failed_final_submit`.

For example, an encode error with one copy pending loses two frames but records only one discard. Count the failed submission here and remove the extra final-submit increment to avoid counting it twice.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in bc81855. submit_batch now counts the frame whose submit call fails, and also counts a failed readback frame, before discarding the rest. note_failed_final_submit no longer increments; callers read the total through discarded_total(), so nothing is counted twice. OOP converter and ffmpeg errors still count inside encode_one and return Ok, so they do not reach this path. 221 output_pipeline tests pass on Windows.

submit_batch counts the failed submission and a failed readback itself, so callers only read the total. Join the pause resume checks for clippy.
@kyzer1023

Copy link
Copy Markdown
Contributor Author

@greptileai review

This branch has not been deployed

No deployments
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