移除无效补偿控件并增加DirectShow原生驱动属性入口
This commit is contained in:
parent
89db34bc18
commit
6b2d42dc31
@ -20,7 +20,7 @@ pwsh -File tools/Start-HandAiD3.ps1
|
||||
## 操作流程
|
||||
|
||||
1. 在“运行设置”中选择 UVC 或海康相机,新建或选择配方。设置页保留相机、配方和抽帧参数。
|
||||
2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页。在原始相机画面上绘制区域;相机设置独立于配方,在“运行设置”中点击相机后面的“配置”按钮打开专用窗口。USB 分辨率、目标帧率、视频格式、曝光补偿和低亮度补偿使用下拉菜单选择,列表提供常用配置,不代表设备均支持;海康相机可设置曝光时间。设置按设备保存在 workspace/camera-settings.json,保存后下次开启采集、取图或录像预览时生效。SOP 日志显示驱动回读模式,状态栏分别显示 USB 实测采集和渲染 fps。曝光补偿以 EV 为单位,负值压低自动曝光;选择“不修改”保留当前值,0 EV 清除补偿。当前通过 Windows MSMF 对应设备的 KS 扩展接口写入并回读确认,不支持的设备、步长或平台,以及曝光补偿设置失败时,均静默跳过,不提示、不阻断采集。低亮度补偿提供“不修改/关闭/开启”,对应 UVC 属性页同名开关(自动曝光优先级),按设备保存,并在采集、取图、录像预览启动前应用;不支持或设置失败时同样静默跳过,成功回读后记录运行日志。
|
||||
2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页。在原始相机画面上绘制区域;相机设置独立于配方,在“运行设置”中点击相机后面的“配置”按钮打开专用窗口。USB 分辨率、目标帧率、视频格式和采集方式使用下拉菜单选择;海康相机可设置曝光时间。设置按设备保存在 workspace/camera-settings.json,保存后下次开启采集、取图或录像预览时生效。要尝试驱动原生图像控制,选择“DirectShow(兼容 VideoCap)”并保存,开启采集后点击“驱动属性”,通过当前 DirectShow 后端打开所选相机驱动提供的原生页面,可调整其中的曝光、亮度或其他受支持开关。原生页面的项目和保存行为由驱动决定,程序不再模拟 EV 补偿或低亮度补偿开关,也不应用旧配置中的这两个字段。原生属性页不可用时静默跳过;SOP 日志显示驱动回读采集模式,状态栏分别显示 USB 实测采集和渲染 fps。
|
||||
3. 步骤名描述操作,“说明”填写送检单帧能看到的静态完成状态,AI 用说明判断图片。触发规则支持手在区域内、手进入后离开区域、A→B 移动和持续计时。
|
||||
4. 送检可选整张画面、固定区域或跟随手部;跟随手部可以设置扩展距离、最小范围和位置保留时间。
|
||||
5. 保存、应用后开始采集。规则满足只触发送图;AI 确认且完成概率达标后才推进。步骤说明为空、接口失败或证据不足时不会按规则直接完成。
|
||||
|
||||
@ -44,6 +44,12 @@ public sealed class CameraSettingsStore(string root)
|
||||
}
|
||||
finally { if (File.Exists(temporary)) File.Delete(temporary); }
|
||||
}
|
||||
public Task<bool> ConnectAsync(ICameraService service, CameraInfo camera)
|
||||
{
|
||||
var settings = Load(camera);
|
||||
settings.Validate();
|
||||
return service.ConnectAsync(camera, settings.UsbCapture);
|
||||
}
|
||||
public async Task<string> ApplyAsync(ICameraService service, CameraInfo camera)
|
||||
{
|
||||
var settings = Load(camera);
|
||||
|
||||
@ -178,7 +178,7 @@ public sealed partial class CameraViewModel : BindableBase
|
||||
}
|
||||
var selected = _selectedCameraProvider() ?? throw new InvalidOperationException("请先在运行设置中选择相机");
|
||||
Status = "正在连接 " + selected.Name;
|
||||
if (!await _camera.ConnectAsync(selected)) throw new IOException("相机连接失败,请检查设备是否被其他程序占用");
|
||||
if (!await SopHelper.Models.CameraSettingsStore.Current.ConnectAsync(_camera, selected)) throw new IOException("相机连接失败,请检查设备是否被其他程序占用");
|
||||
if (_closing) return;
|
||||
try { await SopHelper.Models.CameraSettingsStore.Current.ApplyAsync(_camera, selected); }
|
||||
catch { await Task.Run(_camera.Disconnect); throw; }
|
||||
|
||||
@ -13,13 +13,9 @@ public sealed record FrameRatePreset(double? Fps)
|
||||
{
|
||||
public override string ToString() => Fps is null ? "驱动默认" : $"{Fps:0.##} fps";
|
||||
}
|
||||
public sealed record ExposureCompensationPreset(double? Ev)
|
||||
public sealed record CaptureBackendPreset(UvcCaptureBackend Backend, string Label)
|
||||
{
|
||||
public override string ToString() => Ev is null ? "不修改" : $"{Ev:+0.##;-0.##;0} EV";
|
||||
}
|
||||
public sealed record LowLightCompensationPreset(bool? Enabled)
|
||||
{
|
||||
public override string ToString() => Enabled switch { true => "开启", false => "关闭", null => "不修改" };
|
||||
public override string ToString() => Label;
|
||||
}
|
||||
public sealed class CameraSettingsViewModel : BindableBase
|
||||
{
|
||||
@ -35,12 +31,11 @@ public sealed class CameraSettingsViewModel : BindableBase
|
||||
new(3264,2448), new(3840,2160), new(4096,2160), new(4608,3456), new(4656,3496)]);
|
||||
public ObservableCollection<FrameRatePreset> FrameRates { get; } = new([
|
||||
new(null), new(5), new(10), new(15), new(20), new(24), new(25), new(30), new(50), new(60), new(120)]);
|
||||
public ObservableCollection<ExposureCompensationPreset> ExposureCompensations { get; } = new([
|
||||
new(null), new(-3), new(-2), new(-5d/3), new(-4d/3), new(-1), new(-2d/3), new(-1d/3),
|
||||
new(0), new(1d/3), new(2d/3), new(1), new(2), new(3)]);
|
||||
public ExposureCompensationPreset SelectedExposureCompensation { get; set; }
|
||||
public LowLightCompensationPreset[] LowLightCompensations { get; } = [new(null), new(false), new(true)];
|
||||
public LowLightCompensationPreset SelectedLowLightCompensation { get; set; }
|
||||
public CaptureBackendPreset[] Backends { get; } = [
|
||||
new(UvcCaptureBackend.Default, "自动选择"),
|
||||
new(UvcCaptureBackend.DirectShow, "DirectShow(兼容 VideoCap)"),
|
||||
new(UvcCaptureBackend.MediaFoundation, "Media Foundation")];
|
||||
public CaptureBackendPreset SelectedBackend { get; set; }
|
||||
public string[] Formats { get; } = ["驱动默认", "MJPG", "YUY2"];
|
||||
public ResolutionPreset SelectedResolution { get; set; }
|
||||
public FrameRatePreset SelectedFrameRate { get; set; }
|
||||
@ -53,8 +48,7 @@ public sealed class CameraSettingsViewModel : BindableBase
|
||||
{
|
||||
_camera = camera; _store = store;
|
||||
SelectedResolution = Resolutions[0]; SelectedFrameRate = FrameRates[0];
|
||||
SelectedExposureCompensation = ExposureCompensations[0];
|
||||
SelectedLowLightCompensation = LowLightCompensations[0];
|
||||
SelectedBackend = Backends[0];
|
||||
try
|
||||
{
|
||||
var settings = store.Load(camera);
|
||||
@ -66,10 +60,7 @@ public sealed class CameraSettingsViewModel : BindableBase
|
||||
if (!FrameRates.Contains(rate)) FrameRates.Add(rate);
|
||||
SelectedFrameRate = FrameRates.First(r => r == rate);
|
||||
SelectedFormat = string.IsNullOrWhiteSpace(settings.UsbCapture.Format) ? Formats[0] : settings.UsbCapture.Format.Trim().ToUpperInvariant();
|
||||
var compensation = new ExposureCompensationPreset(settings.UsbCapture.ExposureCompensationEv);
|
||||
if (!ExposureCompensations.Contains(compensation)) ExposureCompensations.Add(compensation);
|
||||
SelectedExposureCompensation = ExposureCompensations.First(c => c == compensation);
|
||||
SelectedLowLightCompensation = LowLightCompensations.Single(p => p.Enabled == settings.UsbCapture.LowLightCompensation);
|
||||
SelectedBackend = Backends.Single(p => p.Backend == settings.UsbCapture.Backend);
|
||||
ExposureTimeUs = settings.ExposureTimeUs;
|
||||
}
|
||||
catch (Exception ex) { Error = "读取相机设置失败:" + ex.Message; CanSave = false; }
|
||||
@ -85,8 +76,7 @@ public sealed class CameraSettingsViewModel : BindableBase
|
||||
{
|
||||
Width = SelectedResolution.Width, Height = SelectedResolution.Height,
|
||||
Fps = SelectedFrameRate.Fps, Format = SelectedFormat == Formats[0] ? null : SelectedFormat,
|
||||
ExposureCompensationEv = SelectedExposureCompensation.Ev,
|
||||
LowLightCompensation = SelectedLowLightCompensation.Enabled
|
||||
Backend = SelectedBackend.Backend
|
||||
} : new(),
|
||||
ExposureTimeUs = IsIndustrial ? ExposureTimeUs : null
|
||||
});
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
x:Class="SopHelper.VVMs.CameraSettings.CameraSettingsWindow" Title="相机配置"
|
||||
Width="520" Height="600" MinWidth="440" MinHeight="400" Background="{StaticResource Bg}" WindowStartupLocation="CenterOwner">
|
||||
Width="520" Height="520" MinWidth="440" MinHeight="400" Background="{StaticResource Bg}" WindowStartupLocation="CenterOwner">
|
||||
<Grid Margin="24" RowDefinitions="Auto,*,Auto">
|
||||
<StackPanel Spacing="8">
|
||||
<TextBlock Text="相机配置" Classes="Title" />
|
||||
@ -22,15 +22,10 @@
|
||||
<ComboBox x:Name="FormatPicker" Grid.Column="1" ItemsSource="{Binding Formats}" SelectedItem="{Binding SelectedFormat, Mode=TwoWay}" HorizontalAlignment="Stretch" />
|
||||
</Grid>
|
||||
<Grid ColumnDefinitions="100,*">
|
||||
<TextBlock Text="曝光补偿" VerticalAlignment="Center" />
|
||||
<ComboBox x:Name="ExposureCompensationPicker" Grid.Column="1" ItemsSource="{Binding ExposureCompensations}" SelectedItem="{Binding SelectedExposureCompensation, Mode=TwoWay}" HorizontalAlignment="Stretch" />
|
||||
<TextBlock Text="采集方式" VerticalAlignment="Center" />
|
||||
<ComboBox x:Name="CaptureBackendPicker" Grid.Column="1" ItemsSource="{Binding Backends}" SelectedItem="{Binding SelectedBackend, Mode=TwoWay}" HorizontalAlignment="Stretch" />
|
||||
</Grid>
|
||||
<TextBlock Text="自动曝光偏亮可先试 −0.33 或 −0.67 EV;0 EV 为无补偿,“不修改”保留相机当前值。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
|
||||
<Grid ColumnDefinitions="100,*">
|
||||
<TextBlock Text="低亮度补偿" VerticalAlignment="Center" />
|
||||
<ComboBox x:Name="LowLightCompensationPicker" Grid.Column="1" ItemsSource="{Binding LowLightCompensations}" SelectedItem="{Binding SelectedLowLightCompensation, Mode=TwoWay}" HorizontalAlignment="Stretch" />
|
||||
</Grid>
|
||||
<TextBlock Text="对应相机属性页的同名开关。选择“关闭”可关闭低亮度补偿;“不修改”保留相机当前值。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
|
||||
<TextBlock Text="要尝试驱动提供的开关,请选择 DirectShow,保存并开启采集,再点击运行设置中的“驱动属性”。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
|
||||
<TextBlock Text="列表为常用配置,不代表当前相机均支持。选择“驱动默认”可保留默认模式;实际协商结果见运行日志。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
|
||||
</StackPanel>
|
||||
<StackPanel IsVisible="{Binding IsIndustrial}" Spacing="8">
|
||||
|
||||
@ -234,7 +234,7 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware
|
||||
}
|
||||
try
|
||||
{
|
||||
if (!await camera.ConnectAsync(_cameraInfo)) throw new InvalidOperationException("连接相机失败,请查看 SOP 页日志");
|
||||
if (!await SopHelper.Models.CameraSettingsStore.Current.ConnectAsync(camera, _cameraInfo)) throw new InvalidOperationException("连接相机失败,请查看 SOP 页日志");
|
||||
await SopHelper.Models.CameraSettingsStore.Current.ApplyAsync(camera, _cameraInfo);
|
||||
camera.FrameArrived += Receive;
|
||||
if (!await camera.StartAsync()) throw new InvalidOperationException("启动采集失败");
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
<ScrollViewer HorizontalScrollBarVisibility="Disabled">
|
||||
<StackPanel Margin="10" MaxWidth="760" HorizontalAlignment="Stretch" Spacing="12">
|
||||
<TextBlock Text="运行设置" Classes="Title" />
|
||||
<TextBlock Text="配置相机、配方和手部采集参数,运行期间不可修改。" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" />
|
||||
<TextBlock Text="配置相机、配方和手部采集参数,运行期间可通过“驱动属性”调整相机图像。" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" />
|
||||
<Border Classes="panel">
|
||||
<StackPanel>
|
||||
<TextBlock Text="相机与配方" Classes="Title" />
|
||||
@ -12,6 +12,7 @@
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Text="相机" Width="40" />
|
||||
<ComboBox Grid.Column="1" Height="26" VerticalContentAlignment="Center" ItemsSource="{Binding Cameras}" IsEnabled="{Binding CanSelectCamera}" SelectedItem="{Binding SelectedCamera, Converter={StaticResource SelectionConverter}}" ToolTip.Tip="支持 UVC 和海康 GigE/USB 工业相机">
|
||||
@ -22,6 +23,7 @@
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
<Button x:Name="ConfigureCameraButton" Grid.Column="2" Content="配置" Margin="6,0,0,0" Padding="10,4" Command="{Binding ConfigureCameraCommand}" />
|
||||
<Button x:Name="DriverPropertiesButton" Grid.Column="4" Content="驱动属性" Margin="6,0,0,0" Padding="10,4" Command="{Binding DriverPropertiesCommand}" ToolTip.Tip="使用 DirectShow 开启采集后,可打开相机驱动的原生属性页" />
|
||||
<Button Grid.Column="3" Content="刷新" Margin="6,0,0,0" Padding="10,4" Command="{Binding RefreshCamerasCommand}" />
|
||||
</Grid>
|
||||
<Grid Margin="0,8,0,0">
|
||||
|
||||
@ -133,6 +133,13 @@ public class SopPageViewModel : ViewModelBase
|
||||
LoadRecipes();
|
||||
|
||||
// 命令接线(DelegateCommand 的可用条件都挂在这里)
|
||||
DriverPropertiesCommand = new DelegateCommand(async () =>
|
||||
{
|
||||
if (!_camera.CanShowDriverProperties || _isCameraBusy) return;
|
||||
SetCameraBusy(true);
|
||||
try { await _camera.ShowDriverPropertiesAsync(); }
|
||||
finally { SetCameraBusy(false); }
|
||||
}, () => !_isCameraBusy && _camera.CanShowDriverProperties);
|
||||
ConfigureCameraCommand = new DelegateCommand(async () => await ConfigureCameraAsync(), () => CanSelectCamera && SelectedCamera is not null && !IsConnected);
|
||||
RefreshCamerasCommand = new DelegateCommand(async () => await RefreshCamerasAsync(), () => CanSelectCamera);
|
||||
StartStopCommand = new DelegateCommand(async () => await StartStopAsync(), CanStart);
|
||||
@ -310,6 +317,8 @@ public class SopPageViewModel : ViewModelBase
|
||||
set { SetProperty(ref _frameStride, value); }
|
||||
}
|
||||
|
||||
/// <summary>打开已连接相机的原生驱动属性</summary>
|
||||
public DelegateCommand DriverPropertiesCommand { get; private set; } = null!;
|
||||
/// <summary>打开所选相机的独立配置窗口</summary>
|
||||
public DelegateCommand ConfigureCameraCommand { get; private set; } = null!;
|
||||
|
||||
@ -360,6 +369,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
private void RaiseCommands()
|
||||
{
|
||||
// 构造函数里 LoadRecipes() 会先设 SelectedRecipe,那时命令还没创建,必须空安全
|
||||
DriverPropertiesCommand?.RaiseCanExecuteChanged();
|
||||
ConfigureCameraCommand?.RaiseCanExecuteChanged();
|
||||
RefreshCamerasCommand?.RaiseCanExecuteChanged();
|
||||
StartStopCommand?.RaiseCanExecuteChanged();
|
||||
@ -729,7 +739,7 @@ public class SopPageViewModel : ViewModelBase
|
||||
return;
|
||||
}
|
||||
|
||||
if (!await _camera.ConnectAsync(SelectedCamera)) return;
|
||||
if (!await SopHelper.Models.CameraSettingsStore.Current.ConnectAsync(_camera, SelectedCamera)) return;
|
||||
|
||||
ApplyRecipe();
|
||||
|
||||
|
||||
@ -40,7 +40,8 @@ public sealed class CameraService : ICameraService
|
||||
finally { _operations.Release(); }
|
||||
}
|
||||
|
||||
public async Task<bool> ConnectAsync(CameraInfo camera)
|
||||
public Task<bool> ConnectAsync(CameraInfo camera) => ConnectAsync(camera, new());
|
||||
public async Task<bool> ConnectAsync(CameraInfo camera, UvcCaptureOptions options)
|
||||
{
|
||||
await _operations.WaitAsync().ConfigureAwait(false);
|
||||
try
|
||||
@ -48,7 +49,7 @@ public sealed class CameraService : ICameraService
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
if (_active is not null) await Task.Run(_active.Disconnect).ConfigureAwait(false);
|
||||
_active = camera.Kind == CameraKind.Hikvision ? _hik : _uvc;
|
||||
return await _active.ConnectAsync(camera).ConfigureAwait(false);
|
||||
return await _active.ConnectAsync(camera, options).ConfigureAwait(false);
|
||||
}
|
||||
finally { _operations.Release(); }
|
||||
}
|
||||
@ -77,6 +78,14 @@ public sealed class CameraService : ICameraService
|
||||
finally { _operations.Release(); }
|
||||
}
|
||||
|
||||
public bool CanShowDriverProperties => _active?.CanShowDriverProperties == true;
|
||||
public async Task<bool> ShowDriverPropertiesAsync()
|
||||
{
|
||||
await _operations.WaitAsync().ConfigureAwait(false);
|
||||
try { return !_disposed && _active is not null && await _active.ShowDriverPropertiesAsync().ConfigureAwait(false); }
|
||||
finally { _operations.Release(); }
|
||||
}
|
||||
|
||||
public async Task<bool> StartAsync()
|
||||
{
|
||||
await _operations.WaitAsync().ConfigureAwait(false);
|
||||
|
||||
@ -82,6 +82,11 @@ public interface ICameraService : IDisposable
|
||||
? Task.FromResult("")
|
||||
: Task.FromException<string>(new NotSupportedException("当前相机不支持 USB 采集参数"));
|
||||
|
||||
/// <summary>连接时选择 USB 后端;其他设备保留原有连接方式。</summary>
|
||||
Task<bool> ConnectAsync(CameraInfo camera, UvcCaptureOptions options) => ConnectAsync(camera);
|
||||
bool CanShowDriverProperties => false;
|
||||
Task<bool> ShowDriverPropertiesAsync() => Task.FromResult(false);
|
||||
|
||||
/// <summary>开始采集</summary>
|
||||
Task<bool> StartAsync();
|
||||
|
||||
|
||||
@ -87,9 +87,12 @@ public class UvcCameraService : ICameraService
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<bool> ConnectAsync(CameraInfo camera)
|
||||
private bool _usesDirectShow;
|
||||
public bool CanShowDriverProperties => IsConnected && _usesDirectShow;
|
||||
public Task<bool> ConnectAsync(CameraInfo camera) => ConnectAsync(camera, new());
|
||||
public Task<bool> ConnectAsync(CameraInfo camera, UvcCaptureOptions options)
|
||||
{
|
||||
options.Validate();
|
||||
return Task.Run(() =>
|
||||
{
|
||||
lock (DshowLock)
|
||||
@ -105,8 +108,14 @@ public class UvcCameraService : ICameraService
|
||||
// MSMF 优先:DSHOW 后端对"反复开图/关图"存在已知原生缺陷,
|
||||
// 图销毁是系统级异步,紧接的开图仍可能撞上未完成的销毁而崩溃。
|
||||
_capture = OperatingSystem.IsWindows()
|
||||
? TryOpen(camera.Index, VideoCaptureAPIs.MSMF) ?? TryOpen(camera.Index, VideoCaptureAPIs.DSHOW)
|
||||
? options.Backend switch
|
||||
{
|
||||
UvcCaptureBackend.DirectShow => TryOpen(camera.Index, VideoCaptureAPIs.DSHOW),
|
||||
UvcCaptureBackend.MediaFoundation => TryOpen(camera.Index, VideoCaptureAPIs.MSMF),
|
||||
_ => TryOpen(camera.Index, VideoCaptureAPIs.MSMF) ?? TryOpen(camera.Index, VideoCaptureAPIs.DSHOW)
|
||||
}
|
||||
: TryOpen(camera.Index, VideoCaptureAPIs.V4L2);
|
||||
_usesDirectShow = _capture?.Get(VideoCaptureProperties.Backend) == (double)VideoCaptureAPIs.DSHOW;
|
||||
|
||||
if (_capture is null)
|
||||
{
|
||||
@ -145,18 +154,6 @@ public class UvcCameraService : ICameraService
|
||||
if (options.Width is { } width) Set(VideoCaptureProperties.FrameWidth, width, "宽度");
|
||||
if (options.Height is { } height) Set(VideoCaptureProperties.FrameHeight, height, "高度");
|
||||
if (options.Fps is { } fps) Set(VideoCaptureProperties.Fps, fps, "目标帧率");
|
||||
var exposureDescription = "";
|
||||
if (options.ExposureCompensationEv is { } ev && OperatingSystem.IsWindows()
|
||||
&& capture.Get(VideoCaptureProperties.Backend) == (double)VideoCaptureAPIs.MSMF
|
||||
&& Current is { } current
|
||||
&& WindowsUvcControls.TrySet(current.Index, ev) is { } actualEv)
|
||||
exposureDescription = $";曝光补偿回读 {actualEv:+0.##;-0.##;0} EV";
|
||||
var lowLightDescription = "";
|
||||
if (options.LowLightCompensation is { } lowLight && OperatingSystem.IsWindows()
|
||||
&& capture.Get(VideoCaptureProperties.Backend) == (double)VideoCaptureAPIs.MSMF
|
||||
&& Current is { } lowLightCamera
|
||||
&& WindowsUvcControls.TrySetLowLightCompensation(lowLightCamera.Index, lowLight) is { } actualLowLight)
|
||||
lowLightDescription = actualLowLight ? ";低亮度补偿已开启" : ";低亮度补偿已关闭";
|
||||
var actualWidth = capture.Get(VideoCaptureProperties.FrameWidth);
|
||||
var actualHeight = capture.Get(VideoCaptureProperties.FrameHeight);
|
||||
var actualFps = capture.Get(VideoCaptureProperties.Fps);
|
||||
@ -168,7 +165,21 @@ public class UvcCameraService : ICameraService
|
||||
|| !string.IsNullOrWhiteSpace(options.Format) && actualFormat != options.Format.Trim().ToUpperInvariant();
|
||||
ActualFps = 0;
|
||||
return $"USB 驱动回读:{actualWidth:F0}×{actualHeight:F0},{actualFps:F1} fps,格式 {actualFormat}(非实测帧率)"
|
||||
+ (mismatch ? ";与请求不一致,请调整到相机支持的模式" : "") + exposureDescription + lowLightDescription;
|
||||
+ (mismatch ? ";与请求不一致,请调整到相机支持的模式" : "");
|
||||
}
|
||||
});
|
||||
|
||||
/// <summary>请求已连接的 DirectShow 后端打开相机驱动属性页,不另启采集流。</summary>
|
||||
public Task<bool> ShowDriverPropertiesAsync() => Task.Run(() =>
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return false;
|
||||
lock (DshowLock)
|
||||
lock (_captureLock)
|
||||
{
|
||||
if (!CanShowDriverProperties || _capture is null) return false;
|
||||
// OpenCV 的 DirectShow 后端在自己的线程中显示驱动页面;Settings 的值不参与配置。
|
||||
try { return _capture.Set(VideoCaptureProperties.Settings, 1); }
|
||||
catch { return false; }
|
||||
}
|
||||
});
|
||||
|
||||
@ -306,6 +317,7 @@ public class UvcCameraService : ICameraService
|
||||
}
|
||||
|
||||
IsConnected = false;
|
||||
_usesDirectShow = false;
|
||||
Current = null;
|
||||
ConnectionChanged?.Invoke(false);
|
||||
}
|
||||
|
||||
@ -1,5 +1,7 @@
|
||||
namespace SopHelper.Engine.Camera;
|
||||
|
||||
public enum UvcCaptureBackend { Default, DirectShow, MediaFoundation }
|
||||
|
||||
/// <summary>USB 采集请求;空值使用驱动默认模式。</summary>
|
||||
public sealed record UvcCaptureOptions
|
||||
{
|
||||
@ -7,15 +9,13 @@ public sealed record UvcCaptureOptions
|
||||
public int? Height { get; set; }
|
||||
public double? Fps { get; set; }
|
||||
public string? Format { get; set; }
|
||||
public double? ExposureCompensationEv { get; set; }
|
||||
public bool? LowLightCompensation { get; set; }
|
||||
public UvcCaptureBackend Backend { get; set; }
|
||||
[YamlDotNet.Serialization.YamlIgnore, System.Text.Json.Serialization.JsonIgnore]
|
||||
public bool IsDefault => Width is null && Height is null && Fps is null && string.IsNullOrWhiteSpace(Format) && ExposureCompensationEv is null && LowLightCompensation is null;
|
||||
public bool IsDefault => Width is null && Height is null && Fps is null && string.IsNullOrWhiteSpace(Format) && Backend == UvcCaptureBackend.Default;
|
||||
|
||||
public void Validate()
|
||||
{
|
||||
if (ExposureCompensationEv is { } ev && (!double.IsFinite(ev) || ev < -10 || ev > 10))
|
||||
throw new ArgumentException("曝光补偿必须是 -10 至 +10 EV 内的有限数值,或留空不修改;实际范围由相机决定");
|
||||
if (!Enum.IsDefined(Backend)) throw new ArgumentException("无效的 USB 采集方式");
|
||||
if ((Width is null) != (Height is null) || Width is <= 0 || Height is <= 0)
|
||||
throw new ArgumentException("USB 分辨率的宽、高必须同时填写正整数,或同时留空");
|
||||
if (Fps is { } fps && (!double.IsFinite(fps) || fps <= 0))
|
||||
|
||||
@ -1,215 +0,0 @@
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Win32.SafeHandles;
|
||||
|
||||
namespace SopHelper.Engine.Camera;
|
||||
|
||||
/// <summary>Windows KS 相机控制接口。只打开控制句柄,不创建第二条视频采集流。</summary>
|
||||
internal static unsafe class WindowsUvcControls
|
||||
{
|
||||
private const uint IoctlKsProperty = 0x002f0003;
|
||||
private static readonly Guid ExtendedControl = new("1CB79112-C0D2-4213-9CA6-CD4FDB927972");
|
||||
private static readonly Guid CameraControlSet = new("C6E13370-30AC-11D0-A18C-00A0C9118956");
|
||||
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");
|
||||
|
||||
/// <summary>曝光补偿是可选功能,驱动不支持或应用失败时静默跳过。</summary>
|
||||
public static double? TrySet(int index, double ev)
|
||||
{
|
||||
try { return Set(index, ev); }
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
// KSPROPERTY_CAMERACONTROL_AUTO_EXPOSURE_PRIORITY(19)即 UVC 属性页的低亮度补偿。
|
||||
// https://learn.microsoft.com/windows-hardware/drivers/stream/ksproperty-cameracontrol-auto-exposure-priority
|
||||
public static bool? TrySetLowLightCompensation(int index, bool enabled)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return null;
|
||||
using var device = OpenDevice(index);
|
||||
var current = ReadLowLightCompensation(device);
|
||||
if ((current.Value != 0) == enabled) return enabled;
|
||||
var request = new CameraControlProperty
|
||||
{
|
||||
Property = new KsProperty { Set = CameraControlSet, Id = 19, Flags = 2 },
|
||||
Value = enabled ? 1 : 0, Flags = 2
|
||||
};
|
||||
var response = request;
|
||||
if (!CameraControlIoctl(device, IoctlKsProperty, ref request, 40, ref response, 40, out _, IntPtr.Zero))
|
||||
return null;
|
||||
var actual = ReadLowLightCompensation(device);
|
||||
return (actual.Value != 0) == enabled ? enabled : null;
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
public static bool? QueryLowLightCompensation(int index)
|
||||
{
|
||||
if (!OperatingSystem.IsWindows()) return null;
|
||||
using var device = OpenDevice(index);
|
||||
return ReadLowLightCompensation(device).Value != 0;
|
||||
}
|
||||
|
||||
private static CameraControlProperty ReadLowLightCompensation(SafeFileHandle device)
|
||||
{
|
||||
var request = new CameraControlProperty
|
||||
{
|
||||
Property = new KsProperty { Set = CameraControlSet, Id = 19, Flags = 1 }
|
||||
};
|
||||
var response = request;
|
||||
if (!CameraControlIoctl(device, IoctlKsProperty, ref request, 40, ref response, 40, out var count, IntPtr.Zero))
|
||||
throw Failure("无法读取相机低亮度补偿");
|
||||
if (count < 40 || response.Value is not (0 or 1))
|
||||
throw new NotSupportedException($"低亮度补偿返回值无效:长度 {count},值 {response.Value}");
|
||||
return response;
|
||||
}
|
||||
|
||||
private 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; }
|
||||
// KSIDENTIFIER 包含 LONGLONG 对齐成员,原生相机控制结构尾部需补齐到 40 字节。
|
||||
[StructLayout(LayoutKind.Sequential, Size = 40)]
|
||||
private struct CameraControlProperty
|
||||
{
|
||||
public KsProperty Property;
|
||||
public int Value;
|
||||
public uint Flags, Capabilities;
|
||||
}
|
||||
[DllImport("kernel32.dll", SetLastError = true, EntryPoint = "DeviceIoControl")]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool CameraControlIoctl(SafeFileHandle device, uint code, ref CameraControlProperty input,
|
||||
uint inputSize, ref CameraControlProperty output, uint outputSize, out uint returned, IntPtr overlapped);
|
||||
[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("相机返回了无法识别的曝光补偿步长");
|
||||
}
|
||||
}
|
||||
@ -33,27 +33,6 @@ internal static class Smoke
|
||||
[STAThread]
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
if(args.Length==2&&args[0]=="--probe-usb-ev")
|
||||
{
|
||||
try
|
||||
{
|
||||
var type=typeof(UvcCameraService).Assembly.GetType("SopHelper.Engine.Camera.WindowsUvcControls")!;
|
||||
var range=type.GetMethod("Query")!.Invoke(null,[int.Parse(args[1])]);
|
||||
Console.WriteLine("USB EV capability (read only): "+range);return 0;
|
||||
}
|
||||
catch(Exception ex) { Console.WriteLine("USB EV probe: "+(ex.InnerException?.Message??ex.Message));return 2; }
|
||||
}
|
||||
if(args.Length==2&&args[0]=="--probe-usb-low-light")
|
||||
{
|
||||
try
|
||||
{
|
||||
var type=typeof(UvcCameraService).Assembly.GetType("SopHelper.Engine.Camera.WindowsUvcControls")!;
|
||||
var value=type.GetMethod("QueryLowLightCompensation")!.Invoke(null,[int.Parse(args[1])]);
|
||||
Console.WriteLine("USB low-light compensation (read only): "+(value is bool enabled ? (enabled ? "on" : "off") : "unavailable"));
|
||||
}
|
||||
catch(Exception ex){Console.WriteLine("USB low-light probe: "+(ex.InnerException?.Message??ex.Message));}
|
||||
return 0;
|
||||
}
|
||||
_visionOnly=args.Contains("--vision-only");
|
||||
_processImagesOnly=args.Contains("--process-images-only");
|
||||
_recipeSelectionOnly=args.Contains("--recipe-selection-only");
|
||||
@ -594,84 +573,50 @@ internal static class Smoke
|
||||
|
||||
private static async Task CheckUsbCapture(App app)
|
||||
{
|
||||
foreach(var invalid in new UvcCaptureOptions[] {new(){Width=1920},new(){Width=0,Height=1080},new(){Fps=double.NaN},new(){Fps=-1},new(){Format="bad"},new(){ExposureCompensationEv=double.NaN},new(){ExposureCompensationEv=11}})
|
||||
foreach(var invalid in new UvcCaptureOptions[] {new(){Width=1920},new(){Width=0,Height=1080},new(){Fps=double.NaN},new(){Fps=-1},new(){Format="bad"},new(){Backend=(UvcCaptureBackend)99}})
|
||||
{
|
||||
var rejected=false;
|
||||
try {invalid.Validate();} catch(ArgumentException){rejected=true;}
|
||||
var rejected=false;try{invalid.Validate();}catch(ArgumentException){rejected=true;}
|
||||
Check(rejected,"Invalid USB capture request is rejected before reaching the driver");
|
||||
}
|
||||
var thirds=new ExposureCompensationRange(-2,2,4);
|
||||
Check(thirds.Encode(-2d/3)==(4UL,-2)&&Math.Abs(ExposureCompensationRange.Decode(4,-2)+2d/3)<0.0001,"EV values convert to the camera's supported step units without changing exposure time");
|
||||
var wholeOnly=new ExposureCompensationRange(-2,2,16);
|
||||
var rejectedFraction=false;try{wholeOnly.Encode(-1d/3);}catch(NotSupportedException){rejectedFraction=true;}
|
||||
Check(rejectedFraction&&wholeOnly.Encode(-1)==(16UL,-1),"Unsupported fractional EV is rejected rather than silently rounded");
|
||||
var rejectedRange=false;try{thirds.Encode(-3);}catch(ArgumentOutOfRangeException){rejectedRange=true;}
|
||||
Check(rejectedRange,"Requested EV is checked against the actual device range");
|
||||
var native=typeof(UvcCameraService).Assembly.GetType("SopHelper.Engine.Camera.WindowsUvcControls")!;
|
||||
Check(native.GetMethod("TrySet")!.Invoke(null,[-1,-1d]) is null,
|
||||
"Unavailable exposure compensation silently returns without throwing or writing to a camera");
|
||||
Check(native.GetMethod("TrySetLowLightCompensation")!.Invoke(null,[-1,false]) is null,
|
||||
"Unavailable low-light compensation is silently skipped");
|
||||
Check(System.Runtime.InteropServices.Marshal.SizeOf(native.GetNestedType("CameraControlProperty",System.Reflection.BindingFlags.NonPublic)!)==40,
|
||||
"Low-light control layout matches the Windows SDK");
|
||||
Check(!new UvcCaptureOptions {LowLightCompensation=false}.IsDefault,
|
||||
"Explicitly disabling low-light compensation is distinct from leaving the camera unchanged");
|
||||
Check(System.Runtime.InteropServices.Marshal.SizeOf(native.GetNestedType("EvPayload",System.Reflection.BindingFlags.NonPublic)!)==56,
|
||||
"Native EV payload layout matches the Windows SDK");
|
||||
var retired=JsonSerializer.Deserialize<UvcCaptureOptions>("{\"ExposureCompensationEv\":-1,\"LowLightCompensation\":false}")!;
|
||||
Check(retired.IsDefault,"Retired camera controls are ignored when loading existing settings");
|
||||
using(var unavailable=new UvcCameraService())
|
||||
Check(!unavailable.CanShowDriverProperties&&!await unavailable.ShowDriverPropertiesAsync(),"Native properties silently skip unavailable devices");
|
||||
var lifetime=(IClassicDesktopStyleApplicationLifetime)Application.Current!.ApplicationLifetime!;
|
||||
var sop=app.Container.Resolve<SopPageViewModel>();
|
||||
app.Container.Resolve<NavigationModel>().SelectedIndex=1;
|
||||
await Task.Delay(120);
|
||||
app.Container.Resolve<NavigationModel>().SelectedIndex=1;await Task.Delay(120);
|
||||
var button=lifetime.MainWindow!.GetVisualDescendants().OfType<Button>().Single(b=>b.Name=="ConfigureCameraButton");
|
||||
Check(button.IsEffectivelyEnabled,"Runtime settings expose a camera configuration button next to the camera selector");
|
||||
button.Command!.Execute(button.CommandParameter);
|
||||
await Task.Delay(80);
|
||||
Check(button.IsEffectivelyEnabled,"Runtime settings expose the camera configuration button");
|
||||
button.Command!.Execute(button.CommandParameter);await Task.Delay(80);
|
||||
var dialog=lifetime.Windows.OfType<SopHelper.VVMs.CameraSettings.CameraSettingsWindow>().Single();
|
||||
try
|
||||
{
|
||||
var resolution=dialog.FindControl<ComboBox>("ResolutionPicker")!;
|
||||
var rate=dialog.FindControl<ComboBox>("FrameRatePicker")!;
|
||||
var format=dialog.FindControl<ComboBox>("FormatPicker")!;
|
||||
var compensation=dialog.FindControl<ComboBox>("ExposureCompensationPicker")!;
|
||||
var lowLight=dialog.FindControl<ComboBox>("LowLightCompensationPicker")!;
|
||||
Check(dialog.Model.Resolutions.Any(r=>r.Width==4608)&&dialog.Model.FrameRates.Any(r=>r.Fps==30),"Resolution and frame rate dropdowns contain common presets including 16 MP and 30 fps");
|
||||
resolution.SelectedItem=dialog.Model.Resolutions.Single(r=>r.Width==1920&&r.Height==1080);
|
||||
rate.SelectedItem=dialog.Model.FrameRates.Single(r=>r.Fps==30);
|
||||
format.SelectedItem="MJPG";
|
||||
compensation.SelectedItem=dialog.Model.ExposureCompensations.Single(c=>c.Ev==-2d/3);
|
||||
lowLight.SelectedItem=dialog.Model.LowLightCompensations.Single(p=>p.Enabled==false);
|
||||
await Task.Delay(60);
|
||||
Save(dialog,"camera-settings");
|
||||
dialog.FindControl<Button>("SaveCameraSettingsButton")!.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
|
||||
await Task.Delay(80);
|
||||
Check(dialog.FindControl<ComboBox>("ExposureCompensationPicker") is null&&dialog.FindControl<ComboBox>("LowLightCompensationPicker") is null,"EV and low-light controls are removed from the dialog");
|
||||
dialog.FindControl<ComboBox>("ResolutionPicker")!.SelectedItem=dialog.Model.Resolutions.Single(r=>r.Width==1920&&r.Height==1080);
|
||||
dialog.FindControl<ComboBox>("FrameRatePicker")!.SelectedItem=dialog.Model.FrameRates.Single(r=>r.Fps==30);
|
||||
dialog.FindControl<ComboBox>("FormatPicker")!.SelectedItem="MJPG";
|
||||
dialog.FindControl<ComboBox>("CaptureBackendPicker")!.SelectedItem=dialog.Model.Backends.Single(r=>r.Backend==UvcCaptureBackend.DirectShow);
|
||||
await Task.Delay(60);Save(dialog,"camera-settings");
|
||||
dialog.FindControl<Button>("SaveCameraSettingsButton")!.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));await Task.Delay(80);
|
||||
var store=CameraSettingsStore.Current;
|
||||
var settings=store.Load(sop.SelectedCamera!);
|
||||
Check(settings.UsbCapture is {Width:1920,Height:1080,Fps:30,Format:"MJPG",LowLightCompensation:false,ExposureCompensationEv:var savedEv} && Math.Abs(savedEv!.Value+2d/3)<0.0001,"Camera dialog saves selected dropdown values independently of recipes");
|
||||
Check(store.Load(sop.SelectedCamera!).UsbCapture is {Width:1920,Height:1080,Fps:30,Format:"MJPG",Backend:UvcCaptureBackend.DirectShow},"Selected capture backend and format are saved per camera");
|
||||
var reopened=new SopHelper.VVMs.CameraSettings.CameraSettingsViewModel(sop.SelectedCamera!,store);
|
||||
Check(reopened.SelectedResolution.Width==1920&&reopened.SelectedFrameRate.Fps==30&&reopened.SelectedFormat=="MJPG"&&reopened.SelectedLowLightCompensation.Enabled==false&&Math.Abs(reopened.SelectedExposureCompensation.Ev!.Value+2d/3)<0.0001,"Camera settings restore on reopening the dialog");
|
||||
reopened.SelectedResolution=reopened.Resolutions[0];
|
||||
Check(store.Load(sop.SelectedCamera!).UsbCapture.Width==1920,"Unsaved changes do not overwrite stored camera settings");
|
||||
Check(store.Load(new CameraInfo{Index=9}).UsbCapture.IsDefault,"Each camera keeps its own independent settings");
|
||||
var yaml=SopHelper.Engine.Sop.SopConfigLoader.ToYaml(new());
|
||||
Check(!yaml.Contains("usb_capture")&&!yaml.Contains("exposure_time_us"),"Recipe YAML contains no camera settings");
|
||||
Check(reopened.SelectedBackend.Backend==UvcCaptureBackend.DirectShow,"Capture backend is restored when reopening settings");
|
||||
var saved=File.ReadAllText(store.FilePath);
|
||||
Check(!saved.Contains("ExposureCompensationEv")&&!saved.Contains("LowLightCompensation"),"Saved settings no longer contain the retired controls");
|
||||
Check(store.Load(new CameraInfo{Index=9}).UsbCapture.IsDefault,"Other cameras retain independent settings");
|
||||
using var probe=new FakeCamera();
|
||||
await store.ApplyAsync(probe,sop.SelectedCamera!);
|
||||
Check(probe.LastUsbOptions is {Width:1920,Height:1080,Fps:30,Format:"MJPG",LowLightCompensation:false,ExposureCompensationEv:var appliedEv} && Math.Abs(appliedEv!.Value+2d/3)<0.0001,"Acquisition receives settings from the per-camera store");
|
||||
reopened.SelectedLowLightCompensation=reopened.LowLightCompensations.Single(p=>p.Enabled==true);
|
||||
Check(reopened.Save()&&store.Load(sop.SelectedCamera!).UsbCapture.LowLightCompensation==true,
|
||||
"Low-light compensation can also be enabled and saved");
|
||||
reopened.SelectedLowLightCompensation=reopened.LowLightCompensations.Single(p=>p.Enabled is null);
|
||||
Check(reopened.Save()&&store.Load(sop.SelectedCamera!).UsbCapture.LowLightCompensation is null,
|
||||
"Leaving low-light compensation unchanged is preserved independently from on and off");
|
||||
sop.IsRunning=true;await Task.Delay(20);
|
||||
Check(!button.IsEffectivelyEnabled&&!sop.ConfigureCameraCommand.CanExecute(),"Camera configuration is disabled while running");
|
||||
sop.IsRunning=false;
|
||||
await store.ConnectAsync(probe,sop.SelectedCamera!);await store.ApplyAsync(probe,sop.SelectedCamera!);
|
||||
Check(probe.LastConnectionOptions?.Backend==UvcCaptureBackend.DirectShow&&probe.LastUsbOptions is {Width:1920,Height:1080,Fps:30,Format:"MJPG"},"Capture backend reaches connection before applying frame settings");
|
||||
var driverButton=lifetime.MainWindow!.GetVisualDescendants().OfType<Button>().Single(b=>b.Name=="DriverPropertiesButton");
|
||||
Check(!driverButton.IsEffectivelyEnabled,"Native driver settings are disabled before connecting a compatible camera");
|
||||
Camera.SupportsDriverProperties=true;sop.IsConnected=true;await Task.Delay(20);
|
||||
driverButton.Command!.Execute(driverButton.CommandParameter);await Task.Delay(20);
|
||||
Check(Camera.DriverPropertiesOpened==1,"Runtime settings open native properties through the active camera service");
|
||||
Camera.SupportsDriverProperties=false;sop.IsConnected=false;
|
||||
sop.IsRunning=true;await Task.Delay(20);Check(!button.IsEffectivelyEnabled,"Connection settings remain disabled while running");sop.IsRunning=false;
|
||||
}
|
||||
finally {dialog.Close();}
|
||||
var recipeModel=new RecipeEditorViewModel();recipeModel.OnDialogOpened(new DialogParameters{{"new",true}});
|
||||
var editor=new RecipeEditor {DataContext=recipeModel};
|
||||
Check(editor.FindControl<TextBox>("CameraExposureInput") is null&&editor.FindControl<TextBox>("UsbWidthInput") is null,"Recipe editor no longer exposes camera settings");
|
||||
await recipeModel.ShutdownAsync();
|
||||
}
|
||||
|
||||
private static async Task CheckCompletionImageSaving(App app,SopPageViewModel sop)
|
||||
@ -986,6 +931,12 @@ internal sealed class FakeCamera : ICameraService
|
||||
public List<CameraInfo> Devices {get;set;}=[new(){Index=0,Name="测试相机"}];
|
||||
public Task<List<CameraInfo>> EnumerateAsync()=>Task.FromResult(Devices.ToList());
|
||||
public Task<bool> ConnectAsync(CameraInfo camera){IsConnected=true;ConnectionChanged?.Invoke(true);return Task.FromResult(true);}
|
||||
public UvcCaptureOptions? LastConnectionOptions {get;private set;}
|
||||
public Task<bool> ConnectAsync(CameraInfo camera,UvcCaptureOptions options){LastConnectionOptions=options with {};return ConnectAsync(camera);}
|
||||
public bool SupportsDriverProperties {get;set;}
|
||||
public bool CanShowDriverProperties=>SupportsDriverProperties;
|
||||
public int DriverPropertiesOpened {get;private set;}
|
||||
public Task<bool> ShowDriverPropertiesAsync(){DriverPropertiesOpened++;return Task.FromResult(SupportsDriverProperties);}
|
||||
public UvcCaptureOptions? LastUsbOptions {get;private set;}
|
||||
public Task<string> ConfigureUvcAsync(UvcCaptureOptions options){LastUsbOptions=options with {};return Task.FromResult("test USB mode");}
|
||||
public Task<bool> StartAsync(){IsGrabbing=true;return Task.FromResult(true);}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user