updated 2026-11-26·6 min read
Zero-Copy Capture & OCR Pipeline
Quarantined Win32 DXGI DuplicateOutput1 capture, cloaked virtual-desktop eframe overlay, WinRT OCR with XY-cut sorting, and HDR scRGB normalization.
My first capture path in Fresnel was broken in three different ways before it ever touched wgpu. An early DuplicateOutput1 call passed duplicate [BGRA8, BGRA8] formats (DXGI_ERROR_UNSUPPORTED), the WGC fallback returned transparent zero buffers, and a mock branch in main.rs quietly masked failures by saving solid 0xF0 light-grey 42 KB PNGs. Switching to synchronous GDI BitBlt plus CreateWindowExW per snip gave real pixels, albeit taking 72 to 167 ms just to freeze the desktop, and worse, triggering a snip from the tray icon froze the fading #32768 Win32 right-click menu shadow straight into the image until a DWM menu flush barrier cleared it. Keeping frames purely in VRAM didn’t work either, for the 15x15 magnifier loupe, WinRT OCR, and clipboard all need CPU bytes, whereas DirectComposition dual-visual layering meant the loupe shader couldn’t sample the background visual. So the pipeline split in two: DXGI exports an NT shared handle directly into wgpu DX12 to uncloak the overlay fast, while an async staging readback fills Frame.data in the background.

Zero-Copy Capture and Overlay Presentation
crates/platform-win32 exports the duplicated ID3D11Texture2D as an NT shared handle (D3D11_RESOURCE_MISC_SHARED_NTHANDLE) into DX12 (ID3D12Device::OpenSharedHandle and wgpu::Device::create_texture_from_hal), leaving most of the codebase in safe Rust.
- Capture via DXGI DuplicateOutput1
IDXGIOutput5::DuplicateOutput1 keeps HDR scan-out formats (R16G16B16A16_FLOAT, R10G10B10A2_UNORM) intact with zero yellow capture borders; WGC handles fallback.
- Uncloak the Virtual-Desktop Overlay
A single pre-warmed deferred eframe viewport (OVERLAY_VIEWPORT_ID) spans the virtual desktop (SM_CXVIRTUALSCREEN x SM_CYVIRTUALSCREEN) and hides under DWMWA_CLOAK, uncloaking in under 0.2 ms with with_no_redirection_bitmap(true) and with_drag_and_drop(false).
- Convert BGRA or scRGB in a Fullscreen Shader
Because egui_wgpu::Renderer::register_native_texture requires Rgba8Unorm, a minimal fullscreen quad shader swizzles BGRA8 and handles portrait rotation on the GPU before egui draws.
- Launch Async OCR with 64x64 Padding & XY-Cut
Full-screen recognition starts immediately off the render thread; dragging a box cancels that pass and runs a padded crop (>= 64x64 px), followed by recursive XY-cut column splitting.
Overlay Traps, Stubs, and HDR Color Normalization
Win11 Overlay, COM, and Stubbed Scaffolds
Instead of spawning separate hidden winit windows per physical monitor (SwapchainConfig still holds a dxgi_from_visual flag, though it isn’t driving per-monitor swapchains), crates/ui/src/app.rs keeps one dormant OVERLAY_VIEWPORT_ID spanning the virtual screen and toggles DWMWA_CLOAK. On the threading side, winit initializes STA COM (COINIT_APARTMENTTHREADED) for drag-and-drop by default and collides straight into MTA WinRT/COM capture crates (don’t ask why COM still works like this) unless with_drag_and_drop(false) is set explicitly.
Every DXGI and NT handle call stays quarantined inside crates/platform-win32 behind RAII Drop guards and traits (CaptureBackend, OcrEngine, VisualSearchClient, VideoEncoderSink). MediaFoundationSinkWriter (whose frame submit method currently just increments a counter) and WasapiAudioEngine (returning zeroed silent buffers), along with PinnedStencil in crates/ui, are still compile-time stubs left out of the active toolbar while capture and OCR stay the focus.
HDR scRGB Color Picker (crates/core)
When Windows 11 Advanced Color is enabled, DWM composites in linear scRGB FP16 (1.0f = 80 nits). Dividing by the monitor’s DISPLAYCONFIG_SDR_WHITE_LEVEL clamped to max(1.0, sdr_white_level / 1000.0) keeps SDR white from reading above 1.0 and avoids divide-by-zero NaNs on virtual displays (lin_srgb = scrgb_fp16 / sdr_white_multiplier).
The 15x15 pixel magnifier loupe samples with nearest-neighbor scaling and formats outputs into #RRGGBB, RGB(r, g, b), and oklch(...) without double-applying ICC profiles under Advanced Color.
Local WinRT OCR and CJK Quirks
I initially planned around ort + PaddleOCR (crates/ocr/Cargo.toml still declares ort, and PpOcrEngine began as a hardcoded stub returning "fn main() {" before becoming a type alias for WindowsOcrEngine), while Microsoft’s Windows AI TextRecognizer demands a Copilot+ NPU that regular x64 laptops lack. Bundling ONNX weights felt pointless once inbox Windows.Media.Ocr worked well enough, albeit with three weird quirks to patch around:
- Concurrent crash (
0x80004004): WinRTOcrEngineexposes no confidence scores and throwsRO_E_BUSYif two threads callRecognizeAsyncon the same pointer, so languages sit behind per-engineArc<Mutex<...>>locks. - CJK code corruption and tofu boxes: Running Japanese OCR alongside English on Rust code turned
|into丨,1;into一;, andOption<i32>intoOpt 土 on く 土 32 >, while loading onlyYuGothM.ttcturned Simplified Chinese (简) and Korean (한) into□tofu boxes.OcrResultArbitergates CJK output at a0.15script density threshold, folds full-width punctuation, and chains multiple Windows fonts in sequence. - Missing small bullets:
4-6 pxlist bullets vanished completely in WinRT OCR, sogutter.rspixel-probes the left margin at sibling bullet anchors to restore•tokens.
OCR Crate Internals & Layout Reconstruction
- WinRT Engine & Alias (
crates/ocr/src/engine.rs): RunsWindowsOcrEngine(WinRTWindows.Media.Ocrin MTA viaensure_winrt_mta) withpub type PpOcrEngine = WindowsOcrEngine;. - Script Arbitration (
OcrResultArbiter): Separates Latin-dominant code from genuine CJK runs (SCRIPT_DENSITY_THRESHOLD = 0.15), folds full-width ASCII punctuation, and exempts valid numeric unit counters (円,年,月,日, etc.). - Padding Floor (
CropPaddingInjector): Enforces a minimum64x64px canvas (and 12 to 16 px margin around tight crops) to eliminate tight-crop detection drops. - Multi-Column Ordering (
RecursiveXyCut): Recursively partitions word bounding boxes on whitespace gutters before sorting lines top-to-bottom and words left-to-right, preventing multi-column IDE interleaving. - Formatting & Gutter Probing (
StructuredTextFormatter,gutter.rs): Preserves visual indentation (indent_spaces), suppresses spurious spaces between adjacent CJK codepoints, and synthesizes missing small margin bullets.
Next: Companion Settings & Visual Search or return to Fresnel Overview.