| 1 | using System.Runtime.InteropServices; |
| 2 | using Windows.Foundation; |
| 3 | using Windows.Graphics.Capture; |
| 4 | using Windows.Graphics.DirectX; |
| 5 | using Windows.Graphics.DirectX.Direct3D11; |
| 6 | using Windows.Graphics.Imaging; |
| 7 | using Windows.Storage.Streams; |
| 8 | using WinRT; |
| 9 | |
| 10 | namespace Cage.GuestClipboard; |
| 11 | |
| 12 | |
| 13 | |
| 14 | internal static class ClaudeGraphicsCapture |
| 15 | { |
| 16 | private static readonly Guid ItemInterop = new("3628e81b-3cac-4c60-b7f4-23ce0e0c3356"); |
| 17 | private static readonly Guid ItemInterface = new("79c3f95b-31f7-4ec2-a464-632ef5d30760"); |
| 18 | private static readonly Guid DxgiDevice = new("54ec77fa-1377-44e6-8c32-88fd5f44c84c"); |
| 19 | private static readonly SemaphoreSlim CaptureGate = new(1, 1); |
| 20 | private static readonly System.Threading.Timer Idle = new(state => { _ = Expire(); }); |
| 21 | private static CaptureSession? current; |
| 22 | |
| 23 | private static async Task Expire() |
| 24 | { |
| 25 | if (!await CaptureGate.WaitAsync(0)) return; |
| 26 | try { current?.Dispose(); current = null; } |
| 27 | finally { CaptureGate.Release(); } |
| 28 | } |
| 29 | |
| 30 | internal static async Task<byte[]> Capture(IntPtr window, int pid, int width, int height, Action validate, bool allowSolid = false, bool preserveAlpha = false) |
| 31 | { |
| 32 | await CaptureGate.WaitAsync(); |
| 33 | Idle.Change(Timeout.Infinite, Timeout.Infinite); |
| 34 | try |
| 35 | { |
| 36 | validate(); |
| 37 | try { if (!GraphicsCaptureSession.IsSupported()) throw new InvalidDataException("desktop_graphics_capture_unavailable"); } |
| 38 | catch (COMException error) when ((uint)error.HResult == 0x80070005) |
| 39 | { throw new InvalidDataException("desktop_capture_permission_required", error); } |
| 40 | Exception? hardware = null; |
| 41 | foreach (uint driver in new uint[] { 1, 5 }) |
| 42 | { |
| 43 | try { return await CaptureDevice(window, pid, width, height, validate, driver, allowSolid, preserveAlpha); } |
| 44 | catch (COMException error) when ((uint)error.HResult == 0x80070005) |
| 45 | { throw new InvalidDataException("desktop_capture_permission_required", error); } |
| 46 | catch (Exception error) when (error is COMException || error is TimeoutException || error is InvalidDataException { Message: "desktop_empty_frame" }) |
| 47 | { |
| 48 | current?.Dispose(); |
| 49 | current = null; |
| 50 | hardware = error; |
| 51 | } |
| 52 | } |
| 53 | throw new InvalidDataException(hardware is InvalidDataException ? "desktop_empty_frame" : "desktop_graphics_device_unavailable", hardware); |
| 54 | } |
| 55 | finally { Idle.Change(1500, Timeout.Infinite); CaptureGate.Release(); } |
| 56 | } |
| 57 | private static async Task<byte[]> CaptureDevice(IntPtr window, int pid, int width, int height, Action validate, uint driver, bool allowSolid, bool preserveAlpha) |
| 58 | { |
| 59 | if (current is null || !current.Matches(window, pid, width, height, allowSolid, preserveAlpha)) |
| 60 | { |
| 61 | current?.Dispose(); current = null; |
| 62 | current = new CaptureSession(window, pid, width, height, driver, allowSolid, preserveAlpha); |
| 63 | } |
| 64 | return await current.Read(validate); |
| 65 | } |
| 66 | |
| 67 | private sealed class CaptureSession : IDisposable |
| 68 | { |
| 69 | private readonly IntPtr window; |
| 70 | private readonly int pid, width, height; |
| 71 | private readonly bool allowSolid, preserveAlpha; |
| 72 | private readonly GraphicsCaptureItem item; |
| 73 | private readonly IDirect3DDevice device; |
| 74 | private Direct3D11CaptureFramePool? pool; |
| 75 | private GraphicsCaptureSession? capture; |
| 76 | private readonly object frames = new(); |
| 77 | private TaskCompletionSource<bool> arrived = new(TaskCreationOptions.RunContinuationsAsynchronously); |
| 78 | private Direct3D11CaptureFrame? latest; |
| 79 | private byte[]? encoded; |
| 80 | private Windows.Storage.Streams.Buffer? pixelBuffer; |
| 81 | private byte[] pixelsRead = []; |
| 82 | private byte[]? previousPixels; |
| 83 | private TimeSpan? timestamp; |
| 84 | private bool closed; |
| 85 | |
| 86 | internal CaptureSession(IntPtr window, int pid, int width, int height, uint driver, bool allowSolid, bool preserveAlpha) |
| 87 | { |
| 88 | this.window = window; this.pid = pid; this.width = width; this.height = height; this.allowSolid = allowSolid; this.preserveAlpha = preserveAlpha; |
| 89 | item = Item(window); |
| 90 | if (item.Size.Width < width || item.Size.Height < height || (long)item.Size.Width * item.Size.Height > 40_000_000) |
| 91 | throw new InvalidDataException("desktop_target_changed"); |
| 92 | device = Device(driver); |
| 93 | try |
| 94 | { |
| 95 | pool = Direct3D11CaptureFramePool.CreateFreeThreaded(device, DirectXPixelFormat.B8G8R8A8UIntNormalized, 2, item.Size); |
| 96 | capture = pool.CreateCaptureSession(item); |
| 97 | capture.IsCursorCaptureEnabled = false; |
| 98 | pool.FrameArrived += OnFrame; |
| 99 | item.Closed += OnClosed; |
| 100 | capture.StartCapture(); |
| 101 | } |
| 102 | catch { Dispose(); throw; } |
| 103 | } |
| 104 | |
| 105 | internal bool Matches(IntPtr handle, int process, int w, int h, bool solid, bool alpha) |
| 106 | { |
| 107 | lock (frames) return !closed && window == handle && pid == process && width == w && height == h && allowSolid == solid && preserveAlpha == alpha; |
| 108 | } |
| 109 | |
| 110 | private void OnFrame(Direct3D11CaptureFramePool sender, object args) |
| 111 | { |
| 112 | try |
| 113 | { |
| 114 | var frame = sender.TryGetNextFrame(); |
| 115 | if (frame is null) return; |
| 116 | lock (frames) |
| 117 | { |
| 118 | if (closed) { frame.Dispose(); return; } |
| 119 | latest?.Dispose(); |
| 120 | latest = frame; |
| 121 | arrived.TrySetResult(true); |
| 122 | } |
| 123 | } |
| 124 | catch (Exception error) |
| 125 | { |
| 126 | lock (frames) |
| 127 | { |
| 128 | closed = true; |
| 129 | latest?.Dispose(); latest = null; |
| 130 | arrived.TrySetException(error); |
| 131 | } |
| 132 | } |
| 133 | } |
| 134 | |
| 135 | private void OnClosed(GraphicsCaptureItem sender, object args) |
| 136 | { |
| 137 | lock (frames) { closed = true; arrived.TrySetException(new InvalidDataException("desktop_target_changed")); } |
| 138 | } |
| 139 | |
| 140 | internal async Task<byte[]> Read(Action validate) |
| 141 | { |
| 142 | validate(); |
| 143 | var geometry = Geometry(window, pid, width, height); |
| 144 | Task ready; |
| 145 | lock (frames) |
| 146 | { |
| 147 | if (closed) throw new InvalidDataException("desktop_target_changed"); |
| 148 | if (latest is null && encoded is not null) return encoded; |
| 149 | ready = arrived.Task; |
| 150 | } |
| 151 | await ready.WaitAsync(TimeSpan.FromSeconds(3)); |
| 152 | Direct3D11CaptureFrame frame; |
| 153 | lock (frames) |
| 154 | { |
| 155 | if (closed || latest is null) throw new InvalidDataException("desktop_target_changed"); |
| 156 | frame = latest; latest = null; |
| 157 | arrived = new(TaskCreationOptions.RunContinuationsAsynchronously); |
| 158 | } |
| 159 | using (frame) |
| 160 | { |
| 161 | if (encoded is not null && timestamp == frame.SystemRelativeTime) return encoded; |
| 162 | using var bitmap = await SoftwareBitmap.CreateCopyFromSurfaceAsync(frame.Surface, preserveAlpha ? BitmapAlphaMode.Premultiplied : BitmapAlphaMode.Ignore); |
| 163 | validate(); |
| 164 | var after = Geometry(window, pid, width, height); |
| 165 | if (after != geometry) throw new InvalidDataException("desktop_target_changed"); |
| 166 | var source = geometry.Source(frame.ContentSize.Width, frame.ContentSize.Height); |
| 167 | using var pixels = SoftwareBitmap.Convert(bitmap, BitmapPixelFormat.Bgra8, preserveAlpha ? BitmapAlphaMode.Straight : BitmapAlphaMode.Ignore); |
| 168 | var byteCount = checked(pixels.PixelWidth * pixels.PixelHeight * 4); |
| 169 | if (pixelsRead.Length != byteCount) |
| 170 | { |
| 171 | pixelsRead = new byte[byteCount]; |
| 172 | pixelBuffer = new Windows.Storage.Streams.Buffer((uint)byteCount); |
| 173 | } |
| 174 | pixels.CopyToBuffer(pixelBuffer!); |
| 175 | using (var reader = DataReader.FromBuffer(pixelBuffer!)) reader.ReadBytes(pixelsRead); |
| 176 | var rowBytes = checked(width * 4); |
| 177 | var identical = previousPixels is not null; |
| 178 | for (var row = 0; identical && row < height; row++) |
| 179 | { |
| 180 | var offset = ((source.Y + row) * pixels.PixelWidth + source.X) * 4; |
| 181 | identical = pixelsRead.AsSpan(offset, rowBytes).SequenceEqual(previousPixels!.AsSpan(row * rowBytes, rowBytes)); |
| 182 | } |
| 183 | if (identical) |
| 184 | { |
| 185 | validate(); |
| 186 | timestamp = frame.SystemRelativeTime; |
| 187 | return encoded!; |
| 188 | } |
| 189 | var png = await EncodeClient(pixels, source.X, source.Y, width, height); |
| 190 | validate(); |
| 191 | using var input = new MemoryStream(png, false); |
| 192 | using var client = new Bitmap(input); |
| 193 | if (client.Width != width || client.Height != height || (!allowSolid && !HasContent(client))) throw new InvalidDataException("desktop_empty_frame"); |
| 194 | |
| 195 | |
| 196 | previousPixels ??= new byte[checked(rowBytes * height)]; |
| 197 | for (var row = 0; row < height; row++) |
| 198 | { |
| 199 | var offset = ((source.Y + row) * pixels.PixelWidth + source.X) * 4; |
| 200 | pixelsRead.AsSpan(offset, rowBytes).CopyTo(previousPixels.AsSpan(row * rowBytes, rowBytes)); |
| 201 | } |
| 202 | timestamp = frame.SystemRelativeTime; |
| 203 | encoded = png; |
| 204 | return png; |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | public void Dispose() |
| 209 | { |
| 210 | lock (frames) |
| 211 | { |
| 212 | closed = true; |
| 213 | latest?.Dispose(); latest = null; |
| 214 | arrived.TrySetCanceled(); |
| 215 | } |
| 216 | if (pool is not null) pool.FrameArrived -= OnFrame; |
| 217 | item.Closed -= OnClosed; |
| 218 | capture?.Dispose(); pool?.Dispose(); device.Dispose(); |
| 219 | } |
| 220 | } |
| 221 | internal static bool HasContent(Bitmap bitmap) |
| 222 | { |
| 223 | |
| 224 | int left = bitmap.Width / 12, right = bitmap.Width - left; |
| 225 | int top = bitmap.Height * 15 / 100, bottom = bitmap.Height * 95 / 100; |
| 226 | var first = bitmap.GetPixel(left, top); int varied = 0; |
| 227 | for (int y = top; y < bottom; y += Math.Max(1, (bottom-top)/64)) |
| 228 | for (int x = left; x < right; x += Math.Max(1, (right-left)/64)) |
| 229 | { |
| 230 | var pixel = bitmap.GetPixel(x, y); |
| 231 | if (Math.Abs(pixel.R-first.R)>8 || Math.Abs(pixel.G-first.G)>8 || Math.Abs(pixel.B-first.B)>8) varied++; |
| 232 | } |
| 233 | return varied >= 8; |
| 234 | } |
| 235 | private static async Task<byte[]> EncodeClient(SoftwareBitmap source, int x, int y, int width, int height) |
| 236 | { |
| 237 | if (x < 0 || y < 0 || x + width > source.PixelWidth || y + height > source.PixelHeight) |
| 238 | throw new InvalidDataException("desktop_target_changed"); |
| 239 | using var output = new InMemoryRandomAccessStream(); |
| 240 | var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, output); |
| 241 | encoder.SetSoftwareBitmap(source); |
| 242 | encoder.BitmapTransform.Bounds = new BitmapBounds { X = (uint)x, Y = (uint)y, Width = (uint)width, Height = (uint)height }; |
| 243 | await encoder.FlushAsync(); |
| 244 | if (output.Size is 0 or > Protocol.PngLimit) throw new InvalidDataException("desktop_frame_limit"); |
| 245 | using var input = output.GetInputStreamAt(0); |
| 246 | using var reader = new DataReader(input); |
| 247 | var length = checked((uint)output.Size); |
| 248 | if (await reader.LoadAsync(length) != length) throw new InvalidDataException("desktop_capture_buffer_invalid"); |
| 249 | var bytes = new byte[length]; |
| 250 | reader.ReadBytes(bytes); |
| 251 | return bytes; |
| 252 | } |
| 253 | |
| 254 | private static GraphicsCaptureItem Item(IntPtr window) |
| 255 | { |
| 256 | using var factory = ActivationFactory.Get("Windows.Graphics.Capture.GraphicsCaptureItem", ItemInterop); |
| 257 | var function = Marshal.ReadIntPtr(Marshal.ReadIntPtr(factory.ThisPtr),3*IntPtr.Size); |
| 258 | var create = Marshal.GetDelegateForFunctionPointer<CreateWindow>(function); |
| 259 | var iid = ItemInterface; |
| 260 | Marshal.ThrowExceptionForHR(create(factory.ThisPtr,window,ref iid,out var value)); |
| 261 | try { return MarshalInterface<GraphicsCaptureItem>.FromAbi(value); } finally { Marshal.Release(value); } |
| 262 | } |
| 263 | private static IDirect3DDevice Device(uint driver) |
| 264 | { |
| 265 | IntPtr native=IntPtr.Zero, context=IntPtr.Zero, dxgi=IntPtr.Zero, wrapped=IntPtr.Zero; |
| 266 | try |
| 267 | { |
| 268 | Marshal.ThrowExceptionForHR(D3D11CreateDevice(IntPtr.Zero,driver,IntPtr.Zero,0x20,IntPtr.Zero,0,7,out native,out _,out context)); |
| 269 | var iid=DxgiDevice;Marshal.ThrowExceptionForHR(Marshal.QueryInterface(native,in iid,out dxgi)); |
| 270 | Marshal.ThrowExceptionForHR(CreateDirect3D11DeviceFromDXGIDevice(dxgi,out wrapped)); |
| 271 | return MarshalInterface<IDirect3DDevice>.FromAbi(wrapped); |
| 272 | } |
| 273 | finally |
| 274 | { |
| 275 | if(wrapped!=IntPtr.Zero)Marshal.Release(wrapped);if(dxgi!=IntPtr.Zero)Marshal.Release(dxgi); |
| 276 | if(context!=IntPtr.Zero)Marshal.Release(context);if(native!=IntPtr.Zero)Marshal.Release(native); |
| 277 | } |
| 278 | } |
| 279 | private readonly record struct Snapshot(Rect Window,Rect Visible,int ClientX,int ClientY,int Width,int Height) |
| 280 | { |
| 281 | internal Point Source(int width,int height) |
| 282 | { |
| 283 | Rect frame; |
| 284 | if(Visible.Right-Visible.Left==width && Visible.Bottom-Visible.Top==height)frame=Visible; |
| 285 | else if(Window.Right-Window.Left==width && Window.Bottom-Window.Top==height)frame=Window; |
| 286 | else throw new InvalidDataException("desktop_target_changed"); |
| 287 | return new(ClientX-frame.Left,ClientY-frame.Top); |
| 288 | } |
| 289 | } |
| 290 | private static Snapshot Geometry(IntPtr window,int pid,int width,int height) |
| 291 | { |
| 292 | var prior=SetThreadDpiAwarenessContext(new IntPtr(-4)); |
| 293 | try |
| 294 | { |
| 295 | if(!SessionGuard.Available() || GetWindowThreadProcessId(window,out var actual)==0 || actual!=pid || |
| 296 | !GetWindowRect(window,out var rectangle) || !GetClientRect(window,out var client) || client.Right!=width || client.Bottom!=height) |
| 297 | throw new InvalidDataException("desktop_target_changed"); |
| 298 | var visible=rectangle;if(DwmGetWindowAttribute(window,9,out var drawn,Marshal.SizeOf<Rect>())==0)visible=drawn; |
| 299 | var origin=new Point();if(!ClientToScreen(window,ref origin))throw new InvalidDataException("desktop_target_changed"); |
| 300 | return new(rectangle,visible,origin.X,origin.Y,width,height); |
| 301 | } |
| 302 | finally {if(prior!=IntPtr.Zero)SetThreadDpiAwarenessContext(prior);} |
| 303 | } |
| 304 | [StructLayout(LayoutKind.Sequential)] private readonly record struct Rect(int Left,int Top,int Right,int Bottom); |
| 305 | [StructLayout(LayoutKind.Sequential)] private struct Point {internal int X,Y;internal Point(int x,int y){X=x;Y=y;}} |
| 306 | [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int CreateWindow(IntPtr factory,IntPtr window,ref Guid iid,out IntPtr item); |
| 307 | [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] |
| 308 | [DllImport("d3d11.dll")] private static extern int D3D11CreateDevice(IntPtr adapter,uint driver,IntPtr software,uint flags,IntPtr features,uint featureCount,uint sdk,out IntPtr device,out uint level,out IntPtr context); |
| 309 | [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] |
| 310 | [DllImport("d3d11.dll")] private static extern int CreateDirect3D11DeviceFromDXGIDevice(IntPtr dxgi,out IntPtr device); |
| 311 | [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] |
| 312 | [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr window,out uint pid); |
| 313 | [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] |
| 314 | [DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr window,out Rect rect); |
| 315 | [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] |
| 316 | [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr window,out Rect rect); |
| 317 | [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] |
| 318 | [DllImport("user32.dll")] private static extern bool ClientToScreen(IntPtr window,ref Point point); |
| 319 | [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] |
| 320 | [DllImport("user32.dll")] private static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context); |
| 321 | [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] |
| 322 | [DllImport("dwmapi.dll")] private static extern int DwmGetWindowAttribute(IntPtr window,uint attribute,out Rect rect,int size); |
| 323 | } |