XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEEDToolBox

【WinUI】XFE精英危险工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Diagnostics;
using System.Runtime.InteropServices;
using Vortice.Direct3D;
using Vortice.Direct3D11;
using Vortice.DXGI;
using Windows.Graphics.Capture;
using Windows.Graphics.DirectX;
using Windows.Graphics.DirectX.Direct3D11;
using XFEEDToolBox.Core.Notifications;
using static Vortice.Direct3D11.D3D11;

namespace XFEEDToolBox.Services.Arrival;

internal sealed record ArrivalFrame(int Width,int Height,byte[] Bgra);

/// <summary>Captures only the bound game HWND, without activating it or capturing the desktop.</summary>
internal static class ArrivalWindowCapture
{
    public static Task<ArrivalFrame?> CaptureAsync(int processId,CancellationToken token)=>CaptureCoreAsync(processId,token,false);
    internal static Task<ArrivalFrame?> CaptureOwnPreviewAsync(CancellationToken token)=>CaptureCoreAsync(Environment.ProcessId,token,true);
    private static async Task<ArrivalFrame?> CaptureCoreAsync(int processId,CancellationToken token,bool ownPreview)
    {
        if(processId<=0||!GraphicsCaptureSession.IsSupported())return null;
        using var process=Process.GetProcessById(processId);
        if(ownPreview?processId!=Environment.ProcessId:!process.ProcessName.Equals("EliteDangerous64",StringComparison.OrdinalIgnoreCase))return null;
        var window=process.MainWindowHandle;
        if(window==0||IsIconic(window)||!IsWindowVisible(window))return null;
        GetWindowThreadProcessId(window,out var owner);
        if(owner!=processId)return null;
        var item=ForWindow(window);
        if(item.Size.Width is <64 or >7680||item.Size.Height is <64 or >4320)return null;
        D3D11CreateDevice(IntPtr.Zero,DriverType.Hardware,DeviceCreationFlags.BgraSupport,
            [FeatureLevel.Level_11_1,FeatureLevel.Level_11_0],out var device,out _,out var context).CheckError();
        using(device)using(context)
        using(var dxgi=device.QueryInterface<IDXGIDevice>())
        {
            Marshal.ThrowExceptionForHR(CreateDirect3D11DeviceFromDXGIDevice(dxgi.NativePointer,out var pointer));
            IDirect3DDevice winrt;
            try{winrt=WinRT.MarshalInterface<IDirect3DDevice>.FromAbi(pointer);}finally{Marshal.Release(pointer);}
            using(winrt)
            using(var pool=Direct3D11CaptureFramePool.CreateFreeThreaded(winrt,DirectXPixelFormat.B8G8R8A8UIntNormalized,2,item.Size))
            using(var session=pool.CreateCaptureSession(item))
            {
                var completed=new TaskCompletionSource<ArrivalFrame>(TaskCreationOptions.RunContinuationsAsynchronously);
                var gate=new object();var active=true;long lastCheck=0;
                void Frame(Direct3D11CaptureFramePool sender,object args)
                {
                    lock(gate)
                    {
                        if(!active)return;
                        try
                        {
                            using var frame=sender.TryGetNextFrame();if(frame is null||frame.ContentSize.Width<64)return;
                            var tick=Stopwatch.GetTimestamp();if(lastCheck>0&&tick-lastCheck<Stopwatch.Frequency/10)return;lastCheck=tick;
                            using var texture=Texture(frame.Surface);
                            var description=texture.Description;var width=Math.Min(frame.ContentSize.Width,(int)description.Width);
                            var height=Math.Min(frame.ContentSize.Height,(int)description.Height);
                            description.BindFlags=BindFlags.None;description.CPUAccessFlags=CpuAccessFlags.Read;
                            description.Usage=ResourceUsage.Staging;description.MiscFlags=ResourceOptionFlags.None;
                            using var staging=device.CreateTexture2D(description);context.CopyResource(staging,texture);
                            var mapped=context.Map(staging,0,MapMode.Read);var pixels=new byte[checked(width*height*4)];
                            try{for(var y=0;y<height;y++)Marshal.Copy(mapped.DataPointer+(int)(y*mapped.RowPitch),pixels,y*width*4,width*4);}
                            finally{context.Unmap(staging,0);}
                            // Empty protected/minimized frames must not become a misleading black hero.
                            var bright=0;for(var p=0;p<pixels.Length;p+=64)if(Math.Max(pixels[p],Math.Max(pixels[p+1],pixels[p+2]))>24)bright++;
                            if(bright>32&&!process.HasExited&&StarFrameCandidate.HasStar(width,height,pixels))completed.TrySetResult(new(width,height,pixels));
                        }
                        catch(Exception error){completed.TrySetException(error);}
                    }
                }
                pool.FrameArrived+=Frame;session.IsCursorCaptureEnabled=false;
                try{session.IsBorderRequired=false;}catch(COMException){/* Windows may require its capture border. */}
                try
                {
                    session.StartCapture();
                    return await completed.Task.WaitAsync(TimeSpan.FromSeconds(2),token);
                }
                finally{lock(gate)active=false;pool.FrameArrived-=Frame;}
            }
        }
    }
    private static GraphicsCaptureItem ForWindow(nint window)
    {
        const string type="Windows.Graphics.Capture.GraphicsCaptureItem";
        Marshal.ThrowExceptionForHR(WindowsCreateString(type,type.Length,out var text));
        nint factory=0,item=0;
        try
        {
            var factoryId=new Guid("3628E81B-3CAC-4C60-B7F4-23CE0E0C3356");
            Marshal.ThrowExceptionForHR(RoGetActivationFactory(text,in factoryId,out factory));
            var create=Marshal.GetDelegateForFunctionPointer<CreateItem>(Marshal.ReadIntPtr(Marshal.ReadIntPtr(factory),3*IntPtr.Size));
            var itemId=new Guid("79C3F95B-31F7-4EC2-A464-632EF5D30760");
            Marshal.ThrowExceptionForHR(create(factory,window,in itemId,out item));
            return WinRT.MarshalInterface<GraphicsCaptureItem>.FromAbi(item);
        }
        finally{if(item!=0)Marshal.Release(item);if(factory!=0)Marshal.Release(factory);WindowsDeleteString(text);}
    }
    private static ID3D11Texture2D Texture(IDirect3DSurface surface)
    {
        var unknown=WinRT.MarshalInterface<IDirect3DSurface>.FromManaged(surface);nint access=0;
        try
        {
            var accessId=new Guid("A9B3D012-3DF2-4EE3-B8D1-8695F457D3C1");Marshal.ThrowExceptionForHR(Marshal.QueryInterface(unknown,in accessId,out access));
            var get=Marshal.GetDelegateForFunctionPointer<GetInterface>(Marshal.ReadIntPtr(Marshal.ReadIntPtr(access),3*IntPtr.Size));
            var textureId=typeof(ID3D11Texture2D).GUID;Marshal.ThrowExceptionForHR(get(access,in textureId,out var texture));return new(texture);
        }
        finally{if(access!=0)Marshal.Release(access);Marshal.Release(unknown);}
    }
    [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int CreateItem(nint self,nint hwnd,in Guid iid,out nint item);
    [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetInterface(nint self,in Guid iid,out nint item);
    [DllImport("combase.dll")] private static extern int WindowsCreateString([MarshalAs(UnmanagedType.LPWStr)]string value,int length,out nint text);
    [DllImport("combase.dll")] private static extern int WindowsDeleteString(nint text);
    [DllImport("combase.dll")] private static extern int RoGetActivationFactory(nint text,in Guid iid,out nint factory);
    [DllImport("d3d11.dll")] private static extern int CreateDirect3D11DeviceFromDXGIDevice(nint dxgi,out nint device);
    [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(nint window,out uint process);
    [DllImport("user32.dll")] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool IsIconic(nint window);
    [DllImport("user32.dll")] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool IsWindowVisible(nint window);
}