Skip to content

perf(recording): submit Windows screen frames as D3D11 NV12 textures - #4491

Open
kyzer1023 wants to merge 4 commits into
CapSoftware:mainfrom
kyzer1023:perf/windows-fragmented-texture-encode
Open

kyzer1023 wants to merge 4 commits into
CapSoftware:mainfrom
kyzer1023:perf/windows-fragmented-texture-encode

Conversation

@kyzer1023

@kyzer1023 kyzer1023 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Why

On Windows, the default in-process fragmented Studio recording path (crash recovery enabled) and Instant screen recording pick a hardware H.264 encoder (h264_amf, h264_nvenc, h264_qsv, or h264_mf), then read each captured D3D11 texture back to CPU memory via staging Map and re-upload BGRA frames into the encoder.

What changed

  • Pass the capture ID3D11Device into the fragmented Studio and Instant screen encoders (cap-recording and cap-enc-ffmpeg).
  • When a hardware H.264 encoder accepts D3D11 frames, allocate a 32-slot NV12 texture ring (sized above FFmpeg 7.1 h264_amf's 16-surface input queue), convert captured BGRA/RGBA textures to NV12 on the GPU via D3D11 VideoProcessor with BT.709 studio color, and queue the D3D11 texture directly into the encoder.
  • Repeated frames resubmit the last ring slot without re-converting.
  • h264_qsv opens from a derived QSV context when the device supports it; libx264, a refused hardware open, a size/format change, or a removed D3D11 device stays on the existing CPU as_ffmpeg path.
  • Added the release benchmark example d3d11-texture-encode-benchmark in cap-recording to compare CPU readback vs D3D11 texture submission under identical synthetic input.

Scope & Tradeoffs

  • Screen track only; camera encoding and the out-of-process muxer stay on CPU frames.
  • Capture textures are recycled on drop, so one GPU-side conversion/copy into the private 32-slot ring remains.
  • Scaling and format/size changes stay on the CPU path; if the ring fills, the frame is dropped rather than mixing software frames into a D3D11-backed encoder context.
  • Non-fragmented WindowsMuxer is unchanged.

Benchmarks (Windows 11, AMD Radeon 780M, h264_amf)

Command: cargo run -p cap-recording --example d3d11-texture-encode-benchmark --release
Workload (captured at commit 0650913cc): 30 warmup + 300 measured frames (330 encoded frames per run), 30 fps synthetic input, 5 repeats per mode, D3D11 hw sw_format=nv12, ring capacity 32 (observed high-water 16, 0 ring-full drops, 0 errors):

Resolution Path Wall median (min–max) Process CPU median (min–max) Decoded frames (5 runs) Speedup
1920×1080 CPU readback (Map + upload) 1284 ms (1274–1426 ms) 1109 ms (1093–1250 ms) 330 × 5 1.00×
1920×1080 D3D11 texture (nv12) 486 ms (482–514 ms) 78 ms (46–453 ms) 330 × 5 2.64× wall
3840×2160 CPU readback (Map + upload) 5453 ms (5407–5666 ms) 6140 ms (5859–6375 ms) 330 × 5 1.00×
3840×2160 D3D11 texture (nv12) 1669 ms (1661–1684 ms) 109 ms (93–437 ms) 330 × 5 3.27× wall

Verification

  • cargo test -p cap-recording --lib texture_slots (6/6 passed) and cargo test -p cap-enc-ffmpeg --lib d3d11_format (3/3 passed) on Windows x86_64-pc-windows-msvc.
  • cargo xwin clippy --all-targets -- -D warnings clean on cap-enc-ffmpeg and cap-recording.
  • Hardware-verified on AMD Radeon 780M (h264_amf); NVIDIA (h264_nvenc) and Intel (h264_qsv) paths are compile- and unit-tested only (no local Windows NVIDIA/Intel GPU available).

RetriggerView in GreptileConfidence Score: 5/5

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

Summary

Windows screen recording can now send GPU-converted NV12 textures directly to supported hardware H.264 encoders.

  • Windows hardware encoders can take NV12 textures directly.
  • Windows screen recordings send supported frames from the GPU to the encoder.
  • A Windows example compares CPU readback with texture submission.
  • Recording test checks stay the same across platform-specific cleanup.

Reviews (2) · Last reviewed commit: "fix(recording): size the D3D11 texture r..." · Reviewed by Greptile

The fragmented Studio and Instant screen encoders copy the capture
texture into a private ring and queue that texture when a hardware
encoder accepts D3D11 input. libx264, a refused MFT, and a dead device
stay on the Map plus BGRA upload path.

Co-authored-by: Kyzer  <kyzer1023@users.noreply.github.com>
@vercel

vercel Bot commented Nov 23, 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.

@kyzer1023

Copy link
Copy Markdown
Contributor Author

@greptileai

Comment on lines +719 to +731
match open_d3d11_encoder(
D3d11EncoderTarget {
frames_ctx,
pixel,
hw_frames: &hw_frames,
},
codec,
encoder_options,
&input_config,
output_width,
output_height,
self.bpp,
) {

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 Startup crashes bypass recovery

HardwareEncoderSession::begin runs only after open_d3d11_encoder succeeds. If opening the encoder crashes inside a shared GPU driver, such as nvwgf2um or igd, crash recovery has no live encoder to blame. The next launch retries the same encoder and can crash again.

Start the session before opening the hardware encoder, as build already does, and keep it on the returned encoder.

Knowledge Base Used: Stop Hardware Encoder Crash Loops

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/enc-ffmpeg/src/video/h264.rs
Line: 719-731

Comment:
**Startup crashes bypass recovery**

`HardwareEncoderSession::begin` runs only after `open_d3d11_encoder` succeeds. If opening the encoder crashes inside a shared GPU driver, such as `nvwgf2um` or `igd`, crash recovery has no live encoder to blame. The next launch retries the same encoder and can crash again.

Start the session before opening the hardware encoder, as `build` already does, and keep it on the returned encoder.

**Knowledge Base Used:** [Stop Hardware Encoder Crash Loops](https://app.greptile.com/-/switch-tenant?tenant=cap&next=%2Fcustom-context%2Fknowledge-base%2Fcapsoftware%2Fcap%2F-%2Freverts%2Fincident-mitigation_3904-20261107-hardware-encoder-crash-loop-06e15fa.md)

---

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 84c28a4b9: HardwareEncoderSession::begin now runs before open_d3d11_encoder (matching build), keeping the session on success and dropping it if open returns an error so driver crashes inside open stay attributed on the next launch.

Comment on lines +632 to +635
match self.encoder.replace_with_software() {
Ok(()) => {
tracing::warn!("D3D11 texture input stopped; later frames use the CPU path");
true

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 Fallback loses queued frames

abandon_d3d11_input drops the hardware encoder without first draining it. This also happens when texture conversion becomes unavailable, not just when the encoder fails. Valid frames still queued in a working encoder are then discarded.

Try flushing those packets into self.mux before replacing the encoder. If flushing fails, report the lost frames.

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/enc-ffmpeg/src/mux/segmented_stream.rs
Line: 632-635

Comment:
**Fallback loses queued frames**

`abandon_d3d11_input` drops the hardware encoder without first draining it. This also happens when texture conversion becomes unavailable, not just when the encoder fails. Valid frames still queued in a working encoder are then discarded.

Try flushing those packets into `self.mux` before replacing the encoder. If flushing fails, report the lost frames.

---

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 84c28a4b9: abandon_d3d11_input now drains queued packets from the hardware encoder into the mux before falling back to libx264 (logging any flush error with the encoder name and continuing the CPU fallback).

println!("adapter: {}", adapter_description(&device.device));
println!("frames {FRAMES} warmup {WARMUP} runs {RUNS} expected decoded {expected}");
for (width, height) in [(1920u32, 1080u32), (3840, 2160)] {
let info = VideoInfo::from_raw(RawVideoFormat::Rgba, width, height, 30);

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 Benchmark misses the stated workload

The benchmark creates 30 fps input, uses 33 ms timestamps, and calls submit_from for every frame, including all 30 warmup frames. It never resubmits the last slot, so it does not check the advertised 60 fps workload or repeated-frame behavior.

Use 60 fps input and matching timestamps, then add actual repeated submissions on both paths so the comparison covers the new slot-sharing behavior.

Prompt To Fix With AI
This is a comment left during a code review.
Path: crates/recording/examples/d3d11-texture-encode-benchmark.rs
Line: 475

Comment:
**Benchmark misses the stated workload**

The benchmark creates 30 fps input, uses 33 ms timestamps, and calls `submit_from` for every frame, including all 30 warmup frames. It never resubmits the last slot, so it does not check the advertised 60 fps workload or repeated-frame behavior.

Use 60 fps input and matching timestamps, then add actual repeated submissions on both paths so the comparison covers the new slot-sharing behavior.

---

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 84c28a4b9: updated the benchmark example to submit 60 fps timestamps (1_000_000 / 60 us) and repeat the previous frame on every odd tick (resubmit_last on the texture path, reusing the last CPU frame on readback). The 780M comparison table in the PR description remains the 30 fps measurement from 0650913cc.

…lback

Start the hardware encoder session before open_d3d11_encoder, and drop it
when open fails. Flush queued packets into the mux before leaving the
texture path. The bench submits 60 fps frames and resubmits the previous
frame on every other tick.

Co-authored-by: Kyzer  <kyzer1023@users.noreply.github.com>
@kyzer1023

Copy link
Copy Markdown
Contributor Author

@greptileai

kyzer1023 added a commit to kyzer1023/Cap that referenced this pull request Nov 23, 2026
kyzer1023 added a commit to kyzer1023/Cap that referenced this pull request Nov 23, 2026
kyzer1023 and others added 2 commits November 24, 2026 12:00
FFmpeg 7.1 rejects an RGBA D3D11 frames context, and h264_amf rejects
BGRA. The texture path now creates NV12 frames, converts RGBA or BGRA
capture on the GPU with BT.709 studio color, and keeps the CPU fallback.
QSV is opened from a derived QSV context when the device can build one.
The bench prints the adapter, the encoder that opened, the sw_format,
and the AVERROR string when the texture path is refused.

Co-authored-by: Kyzer  <kyzer1023@users.noreply.github.com>
FFmpeg 7.1 keeps 16 D3D11 input surfaces referenced and only waits for
output once that queue is full. A ring of 8 filled first, so the bench
stopped with "texture ring full" before AMF could drain a slot. The ring
is now 32, and the bench prints the encoder, sw_format, capacity, and
high-water mark.

Co-authored-by: Kyzer  <kyzer1023@users.noreply.github.com>

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