aisop/src/SopHelper.CrossPlatform.Engine/Camera/WindowsExposureCompensation.cs

151 lines
8.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.ComponentModel;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace SopHelper.Engine.Camera;
/// <summary>Windows KS EV 补偿接口。只打开控制句柄,不创建第二条视频采集流。</summary>
internal static unsafe class WindowsExposureCompensation
{
private const uint IoctlKsProperty = 0x002f0003;
private static readonly Guid ExtendedControl = new("1CB79112-C0D2-4213-9CA6-CD4FDB927972");
private static readonly Guid SourceType = new("C60AC5FE-252A-478F-A0EF-BC8FA5F7CAD3");
private static readonly Guid VideoCapture = new("8AC3587A-4AE7-42D8-99E0-0A6013EEF90F");
private static readonly Guid SymbolicLink = new("58F0AAD8-22BF-4F8A-BB3D-D2C4978C6E2F");
public static double Set(int index, double ev)
{
if (!OperatingSystem.IsWindows()) throw new NotSupportedException("当前平台尚不支持 USB 曝光补偿");
using var device = OpenDevice(index);
var payload = Read(device);
var range = new ExposureCompensationRange(payload.Min, payload.Max, payload.Capability);
var (flag, steps) = range.Encode(ev);
payload.Version = 1; payload.PinId = uint.MaxValue; payload.Size = 56; payload.Result = 0;
payload.Flags = flag; payload.Mode = 0; payload.Value = steps; payload.Reserved = 0;
var property = new KsProperty { Set = ExtendedControl, Id = 16, Flags = 2 };
if (!DeviceIoControl(device, IoctlKsProperty, ref property, 24, ref payload, 56, out _, IntPtr.Zero))
throw Failure("相机驱动拒绝设置曝光补偿");
// 此扩展控制允许异步完成;只有回读一致才报告成功。
for (var i = 0; i < 20; i++)
{
var actual = Read(device);
if (actual.Result == 997) { Thread.Sleep(50); continue; }
var value = ExposureCompensationRange.Decode(actual.Flags, actual.Value);
if (Math.Abs(value - ev) < 0.01) return value;
Thread.Sleep(50);
}
throw new InvalidOperationException("曝光补偿回读与请求不一致,请确认相机支持该设置,或选择“不修改”后重试");
}
public static ExposureCompensationRange Query(int index)
{
if (!OperatingSystem.IsWindows()) throw new NotSupportedException("当前平台尚不支持 USB 曝光补偿");
using var device = OpenDevice(index);
var payload = Read(device);
return new(payload.Min, payload.Max, payload.Capability);
}
private static SafeFileHandle OpenDevice(int index)
{
var device = CreateFile(GetMediaFoundationDevicePath(index), 0xc0000000, 3, IntPtr.Zero, 3, 0, IntPtr.Zero);
if (!device.IsInvalid) return device;
var failure = Failure("无法访问相机曝光补偿控制接口");
device.Dispose(); throw failure;
}
private static EvPayload Read(SafeFileHandle device)
{
var property = new KsProperty { Set = ExtendedControl, Id = 16, Flags = 1 };
var payload = new EvPayload { Version = 1, PinId = uint.MaxValue, Size = 56 };
if (!DeviceIoControl(device, IoctlKsProperty, ref property, 24, ref payload, 56, out var count, IntPtr.Zero))
throw Failure("相机或驱动未提供可用的曝光补偿接口,请选择“不修改”继续使用默认设置");
if (count < 56 || payload.Size < 56 || (payload.Result != 0 && payload.Result != 997))
throw new NotSupportedException("相机曝光补偿接口返回的数据无效,请选择“不修改”");
return payload;
}
// 与 OpenCV MSMF 后端使用同一套枚举顺序,避免按其他后端的索引操作另一台相机。
private static string GetMediaFoundationDevicePath(int index)
{
var initialized = CoInitializeEx(IntPtr.Zero, 0);
if (initialized < 0 && initialized != unchecked((int)0x80010106)) Marshal.ThrowExceptionForHR(initialized);
IntPtr attributes = IntPtr.Zero, devices = IntPtr.Zero;
uint count = 0;
var started = false;
try
{
Marshal.ThrowExceptionForHR(MFStartup(0x20070, 0)); started = true;
Marshal.ThrowExceptionForHR(MFCreateAttributes(out attributes, 1));
var key = SourceType; var value = VideoCapture;
var setGuid = (delegate* unmanaged[Stdcall]<IntPtr, Guid*, Guid*, int>)(*(IntPtr**)attributes)[24];
Marshal.ThrowExceptionForHR(setGuid(attributes, &key, &value));
Marshal.ThrowExceptionForHR(MFEnumDeviceSources(attributes, out devices, out count));
if (index < 0 || index >= count) throw new InvalidOperationException("找不到当前 USB 相机的曝光补偿控制接口,请刷新相机列表");
var activate = Marshal.ReadIntPtr(devices, index * IntPtr.Size);
var getString = (delegate* unmanaged[Stdcall]<IntPtr, Guid*, IntPtr*, uint*, int>)(*(IntPtr**)activate)[13];
key = SymbolicLink; IntPtr text = IntPtr.Zero; uint length = 0;
try
{
Marshal.ThrowExceptionForHR(getString(activate, &key, &text, &length));
return Marshal.PtrToStringUni(text, checked((int)length)) ?? throw new InvalidOperationException("相机设备路径为空");
}
finally { Marshal.FreeCoTaskMem(text); }
}
finally
{
if (devices != IntPtr.Zero)
{
for (var i = 0; i < count; i++) Marshal.Release(Marshal.ReadIntPtr(devices, i * IntPtr.Size));
Marshal.FreeCoTaskMem(devices);
}
if (attributes != IntPtr.Zero) Marshal.Release(attributes);
if (started) MFShutdown();
if (initialized >= 0) CoUninitialize();
}
}
private static Exception Failure(string message) => new InvalidOperationException(message + "(" + new Win32Exception(Marshal.GetLastWin32Error()).Message + ")");
[StructLayout(LayoutKind.Sequential)]
private struct KsProperty { public Guid Set; public uint Id, Flags; }
[StructLayout(LayoutKind.Sequential)]
private struct EvPayload
{
public uint Version, PinId, Size, Result;
public ulong Flags, Capability;
public uint Mode;
public int Min, Max, Value;
public ulong Reserved;
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, EntryPoint = "CreateFileW")]
private static extern SafeFileHandle CreateFile(string name, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool DeviceIoControl(SafeFileHandle device, uint code, ref KsProperty input, uint inputSize, ref EvPayload output, uint outputSize, out uint returned, IntPtr overlapped);
[DllImport("ole32.dll")] private static extern int CoInitializeEx(IntPtr reserved, uint mode);
[DllImport("ole32.dll")] private static extern void CoUninitialize();
[DllImport("mfplat.dll")] private static extern int MFStartup(uint version, uint flags);
[DllImport("mfplat.dll")] private static extern int MFShutdown();
[DllImport("mfplat.dll")] private static extern int MFCreateAttributes(out IntPtr attributes, uint initialSize);
[DllImport("mf.dll")] private static extern int MFEnumDeviceSources(IntPtr attributes, out IntPtr devices, out uint count);
}
/// <summary>KS 补偿范围是绝对 EV,Value 则是 Flags 指定的步数,不能直接把 EV 当步数发送。</summary>
public sealed record ExposureCompensationRange(int MinEv, int MaxEv, ulong Capabilities)
{
private static readonly (ulong Flag, int Denominator)[] Steps = [(1,6),(2,4),(4,3),(8,2),(16,1)];
public (ulong Flag, int Value) Encode(double ev)
{
if (!double.IsFinite(ev) || ev < MinEv || ev > MaxEv)
throw new ArgumentOutOfRangeException(nameof(ev), $"相机曝光补偿支持范围为 {MinEv} 至 {MaxEv} EV");
foreach (var (flag, denominator) in Steps)
if ((Capabilities & flag) != 0 && Math.Abs(ev * denominator - Math.Round(ev * denominator)) < 0.01)
return (flag, checked((int)Math.Round(ev * denominator)));
throw new NotSupportedException("相机不支持所选曝光补偿步长,请尝试整数 EV,或选择“不修改”");
}
public static double Decode(ulong flag, int value)
{
foreach (var step in Steps) if (step.Flag == flag) return (double)value / step.Denominator;
throw new NotSupportedException("相机返回了无法识别的曝光补偿步长");
}
}