移除DirectShow入口并统一跨平台自动与手动曝光控制

This commit is contained in:
tfarcraw 2026-11-18 20:48:22 +08:00
parent bd9e4957f1
commit c3aa4a458c
13 changed files with 163 additions and 282 deletions

View File

@ -20,7 +20,7 @@ pwsh -File tools/Start-HandAiD3.ps1
## 操作流程
1. 在“运行设置”中选择 UVC 或海康相机,新建或选择配方。设置页保留相机、配方和抽帧参数。
2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页。在原始相机画面上绘制区域;相机设置独立于配方,在“运行设置”中点击相机后面的“配置”按钮打开专用窗口。USB 分辨率、目标帧率、视频格式和采集方式使用下拉菜单选择;海康相机可设置曝光时间。设置按设备保存在 workspace/camera-settings.json,保存后下次开启采集、取图或录像预览时生效。要尝试驱动原生图像控制,先在相机“配置”窗口中选定分辨率、帧率及视频格式,再点击“驱动属性”,无需先启动 SOP。属性页使用主相机服务,先应用视频模式再显示驱动页面,关闭页面后保留相机连接;点击“保存”后正式采集复用同一连接及视频模式,不重复设置分辨率、帧率或重建图。取消配置会释放本次驱动会话;设备切换、视频参数改变或停止并断开后仍需重新连接,驱动是否跨连接记住图像选项由驱动决定。原生页面的项目和保存行为由驱动决定,程序不再模拟 EV 补偿或低亮度补偿开关,也不应用旧配置中的这两个字段。原生属性页不可用时静默跳过;SOP 日志显示驱动回读采集模式,状态栏分别显示 USB 实测采集和渲染 fps。
2. 配方编辑器包含“步骤、区域、全局设置、SOP流程视频、Agent助手”五页。在原始相机画面上绘制区域;相机设置独立于配方,在“运行设置”中点击相机后面的“配置”按钮打开专用窗口。USB 分辨率、目标帧率、视频格式和自动曝光使用下拉菜单选择,关闭自动曝光后可填写以毫秒为单位的手动曝光时间(留空保留当前时间);海康相机可设置曝光时间。USB 采集统一使用 OpenCV:Windows 使用 Media Foundation(MSMF),Linux 使用 V4L2,无需选择采集方式。曝光控制分别适配 MSMF 的对数档位及 V4L2 的原始控制值,Windows 会匹配最接近的曝光档位;设备不支持或控制失败时静默跳过。已移除 Windows 专属驱动属性页,旧设置中的采集方式及补偿字段会被忽略。设置按设备保存在 workspace/camera-settings.json,保存后下次开启采集、取图或录像预览时生效。SOP 日志显示驱动回读采集模式,状态栏分别显示 USB 实测采集和渲染 fps。
3. 步骤名描述操作,“说明”填写送检单帧能看到的静态完成状态,AI 用说明判断图片。触发规则支持手在区域内、手进入后离开区域、A→B 移动和持续计时。
4. 送检可选整张画面、固定区域或跟随手部;跟随手部可以设置扩展距离、最小范围和位置保留时间。
5. 保存、应用后开始采集。规则满足只触发送图;AI 确认且完成概率达标后才推进。步骤说明为空、接口失败或证据不足时不会按规则直接完成。

View File

@ -48,7 +48,7 @@ public sealed class CameraSettingsStore(string root)
{
var settings = Load(camera);
settings.Validate();
return service.ConnectAsync(camera, settings.UsbCapture);
return service.ConnectAsync(camera);
}
public async Task<string> ApplyAsync(ICameraService service, CameraInfo camera)
{

View File

@ -1,4 +1,3 @@
using Prism.Commands;
using System.Collections.ObjectModel;
using Prism.Mvvm;
using SopHelper.Engine.Camera;
@ -14,7 +13,7 @@ public sealed record FrameRatePreset(double? Fps)
{
public override string ToString() => Fps is null ? "驱动默认" : $"{Fps:0.##} fps";
}
public sealed record CaptureBackendPreset(UvcCaptureBackend Backend, string Label)
public sealed record AutoExposurePreset(bool? Enabled, string Label)
{
public override string ToString() => Label;
}
@ -23,24 +22,15 @@ public sealed class CameraSettingsViewModel : BindableBase
private readonly CameraInfo _camera;
private readonly CameraSettingsStore _store;
private string _error = "";
private readonly Func<ICameraService> _driverCameraFactory;
private readonly bool _retainDriverConnection;
public bool HasDriverSession { get; private set; }
private bool _isBusy, _canSave = true;
private CaptureBackendPreset _selectedBackend = null!;
public bool IsBusy
private AutoExposurePreset _selectedAutoExposure = null!;
public AutoExposurePreset[] ExposureModes { get; } = [new(null,"不修改"),new(true,"开启"),new(false,"关闭(手动)")];
public AutoExposurePreset SelectedAutoExposure
{
get => _isBusy;
private set
{
if (!SetProperty(ref _isBusy, value)) return;
RaisePropertyChanged(nameof(CanSave)); RaisePropertyChanged(nameof(CanClose));
DriverPropertiesCommand.RaiseCanExecuteChanged();
}
get => _selectedAutoExposure;
set { if (SetProperty(ref _selectedAutoExposure, value)) RaisePropertyChanged(nameof(IsManualExposure)); }
}
public bool CanClose => !IsBusy;
public DelegateCommand DriverPropertiesCommand { get; }
public bool IsManualExposure => SelectedAutoExposure.Enabled == false;
public decimal? UsbExposureTimeMs { get; set; }
public string CameraName => _camera.Name;
public bool IsUsb => _camera.Kind == CameraKind.Uvc;
public bool IsIndustrial => !IsUsb;
@ -50,27 +40,19 @@ 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 CaptureBackendPreset[] Backends { get; } = [
new(UvcCaptureBackend.Default, "自动选择"),
new(UvcCaptureBackend.DirectShow, "DirectShow"),
new(UvcCaptureBackend.MediaFoundation, "Media Foundation")];
public CaptureBackendPreset SelectedBackend { get => _selectedBackend; set => SetProperty(ref _selectedBackend, value); }
public string[] Formats { get; } = ["驱动默认", "MJPG", "YUY2"];
public ResolutionPreset SelectedResolution { get; set; }
public FrameRatePreset SelectedFrameRate { get; set; }
public string SelectedFormat { get; set; } = "驱动默认";
public double? ExposureTimeUs { get; set; }
public string Error { get => _error; private set => SetProperty(ref _error, value); }
public bool CanSave => _canSave && !IsBusy;
public bool CanSave { get; private set; } = true;
public CameraSettingsViewModel(CameraInfo camera, CameraSettingsStore store, Func<ICameraService>? driverCameraFactory = null, bool retainDriverConnection = false)
public CameraSettingsViewModel(CameraInfo camera, CameraSettingsStore store)
{
_camera = camera; _store = store;
_driverCameraFactory = driverCameraFactory ?? (() => new UvcCameraService());
_retainDriverConnection = retainDriverConnection;
DriverPropertiesCommand = new DelegateCommand(async () => await OpenDriverPropertiesAsync(), () => IsUsb && !IsBusy);
SelectedResolution = Resolutions[0]; SelectedFrameRate = FrameRates[0];
SelectedBackend = Backends[0];
SelectedAutoExposure = ExposureModes[0];
try
{
var settings = store.Load(camera);
@ -82,50 +64,12 @@ 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();
SelectedBackend = Backends.Single(p => p.Backend == settings.UsbCapture.Backend);
SelectedAutoExposure = ExposureModes.Single(p => p.Enabled == settings.UsbCapture.AutoExposure);
UsbExposureTimeMs = settings.UsbCapture.ExposureTimeMs is { } ms ? (decimal)ms : null;
ExposureTimeUs = settings.ExposureTimeUs;
}
catch (Exception ex) { Error = "读取相机设置失败:" + ex.Message; _canSave = false; }
catch (Exception ex) { Error = "读取相机设置失败:" + ex.Message; CanSave = false; }
}
private async Task OpenDriverPropertiesAsync()
{
if (!IsUsb || IsBusy) return;
IsBusy = true;
ICameraService? service = null;
try
{
service = _driverCameraFactory();
var options = new UvcCaptureOptions
{
Backend = UvcCaptureBackend.DirectShow,
Width = SelectedResolution.Width, Height = SelectedResolution.Height,
Fps = SelectedFrameRate.Fps, Format = SelectedFormat == Formats[0] ? null : SelectedFormat
};
// 先应用最终视频模式,再打开属性页。正式采集复用这一连接,避免再次协商导致驱动重置。
if (!await service.ConnectAsync(_camera, options)) return;
if (!service.CanShowDriverProperties) return;
await service.ConfigureUvcAsync(options);
if (!await service.StartAsync()) return;
SelectedBackend = Backends.Single(p => p.Backend == UvcCaptureBackend.DirectShow);
HasDriverSession = await service.ShowDriverPropertiesAsync();
}
catch { /* 驱动不支持时静默跳过。 */ }
finally
{
try
{
if (service is not null)
{
if (_retainDriverConnection && HasDriverSession) await Task.Run(service.Stop);
else if (_retainDriverConnection) await Task.Run(service.Disconnect);
else await Task.Run(service.Dispose);
}
}
catch { /* 关闭失败不向界面抛异常。 */ }
IsBusy = false;
}
}
public bool Save()
{
if (!CanSave) return false;
@ -137,7 +81,8 @@ public sealed class CameraSettingsViewModel : BindableBase
{
Width = SelectedResolution.Width, Height = SelectedResolution.Height,
Fps = SelectedFrameRate.Fps, Format = SelectedFormat == Formats[0] ? null : SelectedFormat,
Backend = SelectedBackend.Backend
AutoExposure = SelectedAutoExposure.Enabled,
ExposureTimeMs = IsManualExposure && UsbExposureTimeMs is { } ms ? (double)ms : null
} : new(),
ExposureTimeUs = IsIndustrial ? ExposureTimeUs : null
});

View File

@ -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="520" MinWidth="440" MinHeight="400" Background="{StaticResource Bg}" WindowStartupLocation="CenterOwner">
Width="520" Height="580" MinWidth="440" MinHeight="400" Background="{StaticResource Bg}" WindowStartupLocation="CenterOwner">
<Grid Margin="24" RowDefinitions="Auto,*,Auto">
<StackPanel Spacing="8">
<TextBlock Text="相机配置" Classes="Title" />
@ -22,11 +22,14 @@
<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="CaptureBackendPicker" Grid.Column="1" ItemsSource="{Binding Backends}" SelectedItem="{Binding SelectedBackend, Mode=TwoWay}" HorizontalAlignment="Stretch" />
<TextBlock Text="自动曝光" VerticalAlignment="Center" />
<ComboBox x:Name="AutoExposurePicker" Grid.Column="1" ItemsSource="{Binding ExposureModes}" SelectedItem="{Binding SelectedAutoExposure, Mode=TwoWay}" HorizontalAlignment="Stretch" />
</Grid>
<Button x:Name="DriverPropertiesButton" Content="驱动属性" Command="{Binding DriverPropertiesCommand}" HorizontalAlignment="Left" />
<TextBlock Text="无需先启动采集。调整驱动选项后点击“保存”,正式采集会复用当前连接;如需改变分辨率或帧率,请先修改再打开驱动属性。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
<Grid ColumnDefinitions="100,*">
<TextBlock Text="曝光时间(ms)" VerticalAlignment="Center" />
<NumericUpDown x:Name="UsbExposureInput" Grid.Column="1" Value="{Binding UsbExposureTimeMs, Mode=TwoWay}" Minimum="0.01" Maximum="10000" Increment="1" FormatString="0.###" IsEnabled="{Binding IsManualExposure}" />
</Grid>
<TextBlock Text="关闭自动曝光后可调整时间,值越小通常越暗;留空只关闭自动曝光并保留当前曝光时间。Windows 会匹配最接近的设备曝光档位。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
<TextBlock Text="列表为常用配置,不代表当前相机均支持。选择“驱动默认”可保留默认模式;实际协商结果见运行日志。" TextWrapping="Wrap" Foreground="{StaticResource FgDim}" FontSize="12" />
</StackPanel>
<StackPanel IsVisible="{Binding IsIndustrial}" Spacing="8">
@ -38,7 +41,7 @@
</StackPanel>
</ScrollViewer>
<StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right" Spacing="10">
<Button Content="取消" Click="Cancel" IsEnabled="{Binding CanClose}" />
<Button Content="取消" Click="Cancel" />
<Button x:Name="SaveCameraSettingsButton" Content="保存" Click="Save" IsEnabled="{Binding CanSave}" />
</StackPanel>
</Grid>

View File

@ -9,7 +9,6 @@ public partial class CameraSettingsWindow : Window
public CameraSettingsWindow(CameraSettingsViewModel model)
{
InitializeComponent(); Model = model; DataContext = model;
Closing += (_, e) => { if (Model.IsBusy) e.Cancel = true; };
}
private void Save(object? sender, RoutedEventArgs e) { if (Model.Save()) Close(true); }
private void Cancel(object? sender, RoutedEventArgs e) => Close(false);

View File

@ -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" />

View File

@ -133,7 +133,7 @@ public class SopPageViewModel : ViewModelBase
LoadRecipes();
// 命令接线(DelegateCommand 的可用条件都挂在这里)
ConfigureCameraCommand = new DelegateCommand(async () => await ConfigureCameraAsync(), () => CanSelectCamera && SelectedCamera is not null);
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);
TogglePauseCommand = new DelegateCommand(_engine.TogglePause, () => IsRunning);
@ -598,7 +598,7 @@ public class SopPageViewModel : ViewModelBase
_dispatcher.BeginInvoke(() => RefreshRecipes(fileName))));
parameters.Add("cameraService", _camera);
parameters.Add("selectedCameraProvider", new Func<CameraInfo?>(() => SelectedCamera));
parameters.Add("canUseCamera", new Func<bool>(() => CanSelectCamera && (!IsConnected || !_camera.IsGrabbing)));
parameters.Add("canUseCamera", new Func<bool>(() => CanSelectCamera && !IsConnected));
if (SelectedCamera is not null) parameters.Add("cameraInfo", SelectedCamera);
if (Frame is BitmapSource image)
{
@ -612,17 +612,15 @@ public class SopPageViewModel : ViewModelBase
private async Task ConfigureCameraAsync()
{
if (!CanSelectCamera || SelectedCamera is null) return;
if (!CanSelectCamera || SelectedCamera is null || IsConnected) return;
var camera = SelectedCamera;
SetCameraBusy(true);
try
{
var model = new SopHelper.VVMs.CameraSettings.CameraSettingsViewModel(camera, SopHelper.Models.CameraSettingsStore.Current, () => _camera, retainDriverConnection: true);
var model = new SopHelper.VVMs.CameraSettings.CameraSettingsViewModel(camera, SopHelper.Models.CameraSettingsStore.Current);
var dialog = new SopHelper.VVMs.CameraSettings.CameraSettingsWindow(model);
if (await dialog.ShowDialog<bool>(DesktopPlatform.Owner))
StatusText = "相机配置已保存,下次开启采集生效";
else if (model.HasDriverSession)
await Task.Run(_camera.Disconnect);
}
catch (Exception ex) { Log("error", "打开相机配置失败:" + ex.Message); }
finally { SetCameraBusy(false); }

View File

@ -9,10 +9,6 @@ public sealed class CameraService : ICameraService
private readonly SemaphoreSlim _operations = new(1, 1);
private bool _disposed;
private CameraInfo? _connectedCamera;
private UvcCaptureOptions? _connectionOptions, _configuredOptions;
private string _modeDescription = "";
public CameraService(ICameraService? uvc = null, ICameraService? hik = null)
{
_uvc = uvc ?? new UvcCameraService();
@ -46,27 +42,15 @@ public sealed class CameraService : ICameraService
finally { _operations.Release(); }
}
public Task<bool> ConnectAsync(CameraInfo camera) => ConnectAsync(camera, new());
public async Task<bool> ConnectAsync(CameraInfo camera, UvcCaptureOptions options)
public async Task<bool> ConnectAsync(CameraInfo camera)
{
await _operations.WaitAsync().ConfigureAwait(false);
try
{
ObjectDisposedException.ThrowIf(_disposed, this);
options.Validate();
if (camera.Kind == CameraKind.Uvc && _active?.IsConnected == true && _connectedCamera is { } current
&& current.Kind == camera.Kind && current.Index == camera.Index && _connectionOptions == options)
return true;
_connectedCamera = null; _connectionOptions = null; _configuredOptions = null;
if (_active is not null) await Task.Run(_active.Disconnect).ConfigureAwait(false);
_active = camera.Kind == CameraKind.Hikvision ? _hik : _uvc;
var connected = await _active.ConnectAsync(camera, options).ConfigureAwait(false);
if (connected)
{
_connectedCamera = new CameraInfo { Kind = camera.Kind, Index = camera.Index, SerialNumber = camera.SerialNumber };
_connectionOptions = options with { };
}
return connected;
return await _active.ConnectAsync(camera).ConfigureAwait(false);
}
finally { _operations.Release(); }
}
@ -90,25 +74,11 @@ public sealed class CameraService : ICameraService
{
ObjectDisposedException.ThrowIf(_disposed, this);
if (_active is null || !_active.IsConnected) throw new InvalidOperationException("请先连接相机");
options.Validate();
// 设置属性页后重复 Set(FourCC/Width/Height/Fps) 可能重建采集图,重置驱动的图像控制。
if (_configuredOptions == options) return _modeDescription;
_configuredOptions = null;
_modeDescription = await _active.ConfigureUvcAsync(options).ConfigureAwait(false);
_configuredOptions = options with { };
return _modeDescription;
return await _active.ConfigureUvcAsync(options).ConfigureAwait(false);
}
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);
@ -133,7 +103,6 @@ public sealed class CameraService : ICameraService
try
{
if (!_disposed) _active?.Disconnect();
_connectedCamera = null; _connectionOptions = null; _configuredOptions = null;
}
finally { _operations.Release(); }
}

View File

@ -82,11 +82,6 @@ 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();

View File

@ -1,25 +1,19 @@
using System.Runtime.InteropServices;
using OpenCvSharp;
namespace SopHelper.Engine.Camera;
/// <summary>
/// USB(UVC)相机实现。单相机最小版。
/// 三个坑照搬参考项目实测结论:MSMF 优先、DSHOW 图必须进程级串行、不可重复打开同一索引。
/// </summary>
/// <summary>USB(UVC)相机:Windows 使用 MSMF,Linux 使用 V4L2。</summary>
public class UvcCameraService : ICameraService
{
/// <summary>
/// 进程级 DSHOW 互斥锁:DirectShow 原生图不允许并发创建/销毁,
/// 旧图还在异步销毁时开新图会触发 AccessViolationException。
/// </summary>
private static readonly object DshowLock = new();
/// <summary>串行保护采集后端的设备创建与销毁。</summary>
private static readonly object CameraBackendLock = new();
private readonly object _captureLock = new();
private VideoCapture? _capture;
private CancellationTokenSource? _cts;
private Task? _grabTask;
private long _frameId;
private UvcCaptureOptions _exposureOptions = new();
/// <inheritdoc />
public bool IsConnected { get; private set; }
@ -54,7 +48,7 @@ public class UvcCameraService : ICameraService
{
var index = i;
// 跳过本进程已占用的索引:对同一设备重复开 DSHOW 图会原生崩溃
// 跳过本进程已连接的设备,避免重复打开。
lock (_captureLock)
{
if (_capture is not null && Current?.Index == index)
@ -64,11 +58,11 @@ public class UvcCameraService : ICameraService
}
}
lock (DshowLock)
lock (CameraBackendLock)
{
try
{
using var probe = new VideoCapture(index, OperatingSystem.IsWindows() ? VideoCaptureAPIs.DSHOW : VideoCaptureAPIs.V4L2);
using var probe = new VideoCapture(index, OperatingSystem.IsWindows() ? VideoCaptureAPIs.MSMF : VideoCaptureAPIs.V4L2);
if (!probe.IsOpened()) continue;
var w = probe.Get(VideoCaptureProperties.FrameWidth);
@ -88,35 +82,24 @@ public class UvcCameraService : ICameraService
});
}
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)
/// <inheritdoc />
public Task<bool> ConnectAsync(CameraInfo camera)
{
options.Validate();
return Task.Run(() =>
{
lock (DshowLock)
lock (CameraBackendLock)
{
lock (_captureLock)
{
_exposureOptions = new();
if (_capture is not null)
{
_capture.Dispose();
_capture = null;
}
// MSMF 优先:DSHOW 后端对"反复开图/关图"存在已知原生缺陷,
// 图销毁是系统级异步,紧接的开图仍可能撞上未完成的销毁而崩溃。
_capture = OperatingSystem.IsWindows()
? 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;
_capture = TryOpen(camera.Index,
OperatingSystem.IsWindows() ? VideoCaptureAPIs.MSMF : VideoCaptureAPIs.V4L2);
if (_capture is null)
{
@ -136,7 +119,7 @@ public class UvcCameraService : ICameraService
public Task<string> ConfigureUvcAsync(UvcCaptureOptions options) => Task.Run(() =>
{
options.Validate();
lock (DshowLock)
lock (CameraBackendLock)
lock (_captureLock)
{
var capture = _capture ?? throw new InvalidOperationException("请先连接相机");
@ -155,6 +138,9 @@ 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, "目标帧率");
_exposureOptions = options with { };
var exposureDescription = UvcExposureControl.TryApply(options, (VideoCaptureAPIs)capture.Get(VideoCaptureProperties.Backend),
property => capture.Get(property), (property, value) => capture.Set(property, value));
var actualWidth = capture.Get(VideoCaptureProperties.FrameWidth);
var actualHeight = capture.Get(VideoCaptureProperties.FrameHeight);
var actualFps = capture.Get(VideoCaptureProperties.Fps);
@ -166,50 +152,10 @@ 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 ? ";与请求不一致,请调整到相机支持的模式" : "");
+ (mismatch ? ";与请求不一致,请调整到相机支持的模式" : "") + exposureDescription;
}
});
/// <summary>请求已连接的 DirectShow 后端打开相机驱动属性页,不另启采集流。</summary>
public Task<bool> ShowDriverPropertiesAsync() => Task.Run(() =>
{
if (!OperatingSystem.IsWindows()) return false;
// Connect 与属性操作可能落在不同的线程池线程上,每个 COM 调用线程均需初始化。
var initialized = CoInitializeEx(IntPtr.Zero, 0);
if (initialized < 0 && initialized != unchecked((int)0x80010106)) return false;
try
{
lock (DshowLock)
{
try
{
VideoCapture capture;
lock (_captureLock)
{
if (!CanShowDriverProperties || _capture is null) return false;
capture = _capture;
if (!capture.Set(VideoCaptureProperties.Settings, 1)) return false;
}
// OpenCV 5 在原生线程显示属性页;窗口关闭前保持设备连接,防止页面失效。
while (true)
{
lock (_captureLock)
if (capture.Get(VideoCaptureProperties.Settings) <= 0) break;
Thread.Sleep(50);
}
return true;
}
catch { return false; }
}
}
finally { if (initialized >= 0) CoUninitialize(); }
});
[DllImport("ole32.dll")]
private static extern int CoInitializeEx(IntPtr reserved, uint mode);
[DllImport("ole32.dll")]
private static extern void CoUninitialize();
/// <inheritdoc />
public Task<bool> StartAsync()
{
@ -241,6 +187,7 @@ public class UvcCameraService : ICameraService
{
var fpsWatch = System.Diagnostics.Stopwatch.StartNew();
var framesInWindow = 0;
var exposureAppliedAfterStart = false;
while (!token.IsCancellationRequested)
{
@ -251,6 +198,13 @@ public class UvcCameraService : ICameraService
{
if (captureDisposed) break;
ok = capture.Read(frame);
if (ok && !frame.Empty() && !exposureAppliedAfterStart)
{
// 有些驱动在开始视频流时恢复默认曝光,首帧后补一次用户设置。
UvcExposureControl.TryApply(_exposureOptions, (VideoCaptureAPIs)capture.Get(VideoCaptureProperties.Backend),
property => capture.Get(property), (property, value) => capture.Set(property, value));
exposureAppliedAfterStart = true;
}
}
if (!ok || frame.Empty())
@ -326,7 +280,7 @@ public class UvcCameraService : ICameraService
{
Stop();
lock (DshowLock)
lock (CameraBackendLock)
{
lock (_captureLock)
{
@ -344,7 +298,6 @@ public class UvcCameraService : ICameraService
}
IsConnected = false;
_usesDirectShow = false;
Current = null;
ConnectionChanged?.Invoke(false);
}

View File

@ -1,7 +1,5 @@
namespace SopHelper.Engine.Camera;
public enum UvcCaptureBackend { Default, DirectShow, MediaFoundation }
/// <summary>USB 采集请求;空值使用驱动默认模式。</summary>
public sealed record UvcCaptureOptions
{
@ -9,13 +7,17 @@ public sealed record UvcCaptureOptions
public int? Height { get; set; }
public double? Fps { get; set; }
public string? Format { get; set; }
public UvcCaptureBackend Backend { get; set; }
public bool? AutoExposure { get; set; }
public double? ExposureTimeMs { 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) && Backend == UvcCaptureBackend.Default;
public bool IsDefault => Width is null && Height is null && Fps is null && string.IsNullOrWhiteSpace(Format) && AutoExposure is null && ExposureTimeMs is null;
public void Validate()
{
if (!Enum.IsDefined(Backend)) throw new ArgumentException("无效的 USB 采集方式");
if (ExposureTimeMs is { } ms && (!double.IsFinite(ms) || ms < 0.01 || ms > 10000))
throw new ArgumentException("USB 曝光时间须为 0.01 至 10000 毫秒,或留空保留当前值");
if (ExposureTimeMs is not null && AutoExposure != false)
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))

View File

@ -0,0 +1,51 @@
using OpenCvSharp;
namespace SopHelper.Engine.Camera;
/// <summary>用统一的毫秒设置适配 MSMF 与 V4L2;可选控制失败时静默跳过。</summary>
public static class UvcExposureControl
{
public static string TryApply(UvcCaptureOptions options, VideoCaptureAPIs backend,
Func<VideoCaptureProperties, double> get, Func<VideoCaptureProperties, double, bool> set)
{
if (options.AutoExposure is not { } automatic) return "";
try
{
if (backend == VideoCaptureAPIs.MSMF)
{
// MSMF 的 AutoExposure=0 同时会把曝光值写成 0(1 秒)。
// 关闭自动曝光应写 Exposure:它会使用 Manual 标志并保留当前时间或设置新时间。
var current = get(VideoCaptureProperties.Exposure);
if (!double.IsFinite(current)) return "";
if (automatic)
return set(VideoCaptureProperties.AutoExposure, current == 0 ? 1 : current) ? ";USB 曝光:自动" : "";
var target = options.ExposureTimeMs is { } ms
? Math.Round(Math.Log2(ms / 1000), MidpointRounding.AwayFromZero) : current;
if (!set(VideoCaptureProperties.Exposure, target)) return "";
var actual = get(VideoCaptureProperties.Exposure);
return double.IsFinite(actual) && Math.Abs(actual - target) < 0.5
? $";USB 曝光:手动,时间回读 {Math.Pow(2, actual) * 1000:0.###} ms" : "";
}
if (backend != VideoCaptureAPIs.V4L2) return "";
// V4L2 在 OpenCV 中默认可能归一化控制值。临时关闭归一化,使用内核定义的枚举和 100 μs 单位。
var wasNormalized = get(VideoCaptureProperties.Mode) != 0;
if (!set(VideoCaptureProperties.Mode, 0)) return "";
try
{
if (automatic)
{
// 部分 UVC 驱动仅支持 APERTURE_PRIORITY(3),而不支持 AUTO(0)。
if (!set(VideoCaptureProperties.AutoExposure, 0) && !set(VideoCaptureProperties.AutoExposure, 3)) return "";
return get(VideoCaptureProperties.AutoExposure) is 0 or 3 ? ";USB 曝光:自动" : "";
}
if (!set(VideoCaptureProperties.AutoExposure, 1)) return "";
if (options.ExposureTimeMs is { } ms && !set(VideoCaptureProperties.Exposure, Math.Max(1, Math.Round(ms * 10)))) return "";
if (get(VideoCaptureProperties.AutoExposure) != 1) return "";
var actual = get(VideoCaptureProperties.Exposure);
return actual > 0 ? $";USB 曝光:手动,时间回读 {actual / 10:0.###} ms" : ";USB 曝光:手动";
}
finally { set(VideoCaptureProperties.Mode, wasNormalized ? 1 : 0); }
}
catch { return ""; }
}
}

View File

@ -573,92 +573,68 @@ 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(){Backend=(UvcCaptureBackend)99}})
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(){AutoExposure=false,ExposureTimeMs=0},new(){AutoExposure=true,ExposureTimeMs=10}})
{
var rejected=false;try{invalid.Validate();}catch(ArgumentException){rejected=true;}
Check(rejected,"Invalid USB capture request is rejected before reaching the driver");
}
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 retired=JsonSerializer.Deserialize<UvcCaptureOptions>("{\"Backend\":1,\"ExposureCompensationEv\":-1,\"LowLightCompensation\":false}")!;
Check(retired.IsDefault,"Retired backend and compensation settings are safely ignored");
var controls=new Dictionary<VideoCaptureProperties,double>{{VideoCaptureProperties.Exposure,-3},{VideoCaptureProperties.Mode,1},{VideoCaptureProperties.AutoExposure,3}};
var writes=new List<(VideoCaptureProperties,double)>();
double Get(VideoCaptureProperties property)=>controls.GetValueOrDefault(property);
bool Set(VideoCaptureProperties property,double value){writes.Add((property,value));controls[property]=value;return true;}
UvcExposureControl.TryApply(new(){AutoExposure=false},VideoCaptureAPIs.MSMF,Get,Set);
Check(writes.SequenceEqual(new[]{(VideoCaptureProperties.Exposure,-3d)}),"Disabling MSMF auto exposure preserves current time instead of resetting it to one second");
writes.Clear();
var windows=UvcExposureControl.TryApply(new(){AutoExposure=false,ExposureTimeMs=15.625},VideoCaptureAPIs.MSMF,Get,Set);
Check(controls[VideoCaptureProperties.Exposure]==-6&&windows.Contains("15.625"),"Windows manual milliseconds map to logarithmic camera units and read back correctly");
UvcExposureControl.TryApply(new(){AutoExposure=true},VideoCaptureAPIs.MSMF,Get,Set);
Check(writes.Last()==(VideoCaptureProperties.AutoExposure,-6d),"Enabling MSMF automatic exposure uses a nonzero value with the auto flag");
writes.Clear();
var linux=UvcExposureControl.TryApply(new(){AutoExposure=false,ExposureTimeMs=15.6},VideoCaptureAPIs.V4L2,Get,Set);
Check(controls[VideoCaptureProperties.AutoExposure]==1&&controls[VideoCaptureProperties.Exposure]==156&&controls[VideoCaptureProperties.Mode]==1&&linux.Contains("15.6"),
"Linux exposure uses raw 100-microsecond units and restores OpenCV normalization");
bool LinuxAutoSet(VideoCaptureProperties property,double value)=>property==VideoCaptureProperties.AutoExposure&&value==0 ? false : Set(property,value);
Check(UvcExposureControl.TryApply(new(){AutoExposure=true},VideoCaptureAPIs.V4L2,Get,LinuxAutoSet).Contains("自动")&&controls[VideoCaptureProperties.AutoExposure]==3,
"Linux auto exposure falls back to aperture-priority mode for UVC drivers");
Check(UvcExposureControl.TryApply(new(){AutoExposure=false},VideoCaptureAPIs.MSMF,Get,(_,_)=>false)==""&&
UvcExposureControl.TryApply(new(){AutoExposure=false},VideoCaptureAPIs.V4L2,_=>throw new NotSupportedException(),Set)=="",
"Unsupported exposure controls silently skip without throwing");
var lifetime=(IClassicDesktopStyleApplicationLifetime)Application.Current!.ApplicationLifetime!;
var sop=app.Container.Resolve<SopPageViewModel>();
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 the camera configuration button");
button.Command!.Execute(button.CommandParameter);await Task.Delay(80);
var dialog=lifetime.Windows.OfType<SopHelper.VVMs.CameraSettings.CameraSettingsWindow>().Single();
try
{
Check(dialog.FindControl<Button>("DriverPropertiesButton")!.IsEffectivelyEnabled,"Driver properties are available inside configuration before acquisition starts");
Check(dialog.Model.Backends.Single(p=>p.Backend==UvcCaptureBackend.DirectShow).Label=="DirectShow","DirectShow label has no compatibility suffix");
Check(dialog.FindControl<ComboBox>("ExposureCompensationPicker") is null&&dialog.FindControl<ComboBox>("LowLightCompensationPicker") is null,"EV and low-light controls are removed from the dialog");
Check(dialog.FindControl<Button>("DriverPropertiesButton") is null&&dialog.FindControl<ComboBox>("CaptureBackendPicker") is null,
"Camera configuration has no platform-specific driver dialog or backend selector");
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");
var mode=dialog.FindControl<ComboBox>("AutoExposurePicker")!;
var exposure=dialog.FindControl<NumericUpDown>("UsbExposureInput")!;
Check(!exposure.IsEffectivelyEnabled,"Manual exposure time is disabled until automatic exposure is turned off");
mode.SelectedItem=dialog.Model.ExposureModes.Single(m=>m.Enabled==false);await Task.Delay(20);
Check(exposure.IsEffectivelyEnabled,"Turning off auto exposure enables manual milliseconds input");
exposure.Value=15.625m;await Task.Delay(20);Save(dialog,"camera-settings");
dialog.FindControl<Button>("SaveCameraSettingsButton")!.RaiseEvent(new Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));await Task.Delay(80);
var store=CameraSettingsStore.Current;
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");
Check(store.Load(sop.SelectedCamera!).UsbCapture is {Width:1920,Height:1080,Fps:30,Format:"MJPG",AutoExposure:false,ExposureTimeMs:15.625},
"Unified auto/manual exposure and video settings are saved per camera");
var reopened=new SopHelper.VVMs.CameraSettings.CameraSettingsViewModel(sop.SelectedCamera!,store);
Check(reopened.SelectedBackend.Backend==UvcCaptureBackend.DirectShow,"Capture backend is restored when reopening settings");
Check(reopened.IsManualExposure&&reopened.UsbExposureTimeMs==15.625m,"Manual exposure is restored when reopening configuration");
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.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");
Check(!lifetime.MainWindow!.GetVisualDescendants().OfType<Button>().Any(b=>b.Name=="DriverPropertiesButton"),"Driver properties are removed from the runtime settings row");
sop.IsRunning=true;await Task.Delay(20);Check(!button.IsEffectivelyEnabled,"Connection settings remain disabled while running");sop.IsRunning=false;
Check(!saved.Contains("Backend")&&!saved.Contains("ExposureCompensationEv")&&!saved.Contains("LowLightCompensation"),"Saved settings exclude removed Windows-specific controls");
using var probe=new FakeCamera();await store.ConnectAsync(probe,sop.SelectedCamera!);await store.ApplyAsync(probe,sop.SelectedCamera!);
Check(probe.LastUsbOptions is {AutoExposure:false,ExposureTimeMs:15.625},"Acquisition receives the saved platform-independent exposure settings");
reopened.SelectedAutoExposure=reopened.ExposureModes.Single(m=>m.Enabled==true);Check(reopened.Save()&&store.Load(sop.SelectedCamera!).UsbCapture is {AutoExposure:true,ExposureTimeMs:null},
"Enabling auto exposure clears the manual-time request");
Check(store.Load(new CameraInfo{Index=9}).UsbCapture.IsDefault,"Other cameras preserve their independent defaults");
}
finally {dialog.Close();}
var driverCamera=new FakeCamera {SupportsDriverProperties=true,DriverPropertiesCompletion=new(TaskCreationOptions.RunContinuationsAsynchronously)};
var driverModel=new SopHelper.VVMs.CameraSettings.CameraSettingsViewModel(new CameraInfo{Index=8,Name="驱动属性测试"},CameraSettingsStore.Current,()=>driverCamera);
var driverWindow=new SopHelper.VVMs.CameraSettings.CameraSettingsWindow(driverModel);driverWindow.Show();await Task.Delay(30);
var nativeButton=driverWindow.FindControl<Button>("DriverPropertiesButton")!;
nativeButton.Command!.Execute(nativeButton.CommandParameter);await Task.Delay(20);
Check(driverCamera.LastConnectionOptions?.Backend==UvcCaptureBackend.DirectShow&&driverCamera.DriverPropertiesOpened==1,
"Configuration automatically connects DirectShow before opening native properties");
Check(driverModel.IsBusy&&driverCamera.IsConnected&&driverCamera.IsGrabbing&&!driverWindow.FindControl<Button>("SaveCameraSettingsButton")!.IsEffectivelyEnabled,
"Camera connection is retained while native properties are open and saving is disabled");
driverWindow.Close();Check(driverWindow.IsVisible,"Configuration cannot close while native properties are still open");
driverCamera.DriverPropertiesCompletion!.SetResult(true);
for(var i=0;i<50&&driverModel.IsBusy;i++)await Task.Delay(20);
Check(!driverModel.IsBusy&&driverCamera.DisposeCount==1&&!driverCamera.IsConnected,"Camera is released when native properties close");
Check(driverWindow.FindControl<ComboBox>("CaptureBackendPicker")!.SelectedItem is SopHelper.VVMs.CameraSettings.CaptureBackendPreset {Backend:UvcCaptureBackend.DirectShow},
"The backend selection updates visibly after opening native properties");
driverWindow.Close();
var unsupported=new FakeCamera();
var unsupportedModel=new SopHelper.VVMs.CameraSettings.CameraSettingsViewModel(new CameraInfo(),CameraSettingsStore.Current,()=>unsupported);
unsupportedModel.DriverPropertiesCommand.Execute();
for(var i=0;i<50&&unsupportedModel.IsBusy;i++)await Task.Delay(20);
Check(!unsupportedModel.IsBusy&&unsupported.DisposeCount==1&&unsupported.DriverPropertiesOpened==0,"Unavailable driver properties silently clean up the temporary connection");
var nativeCamera=new FakeCamera {SupportsDriverProperties=true};
using var sharedSession=new CameraService(nativeCamera,new FakeCamera());
var sessionCamera=new CameraInfo {Index=7,Name="保留驱动设置测试"};
var retainedModel=new SopHelper.VVMs.CameraSettings.CameraSettingsViewModel(sessionCamera,CameraSettingsStore.Current,()=>sharedSession,retainDriverConnection:true);
retainedModel.SelectedResolution=retainedModel.Resolutions.Single(r=>r.Width==1280&&r.Height==720);
retainedModel.SelectedFrameRate=retainedModel.FrameRates.Single(r=>r.Fps==30);
retainedModel.DriverPropertiesCommand.Execute();
for(var i=0;i<100&&retainedModel.IsBusy;i++)await Task.Delay(20);
Check(retainedModel.HasDriverSession&&nativeCamera.IsConnected&&!nativeCamera.IsGrabbing&&nativeCamera.DisposeCount==0,
"Closing properties retains the shared camera graph without leaving preview grabbing");
Check(nativeCamera.ConfigureCount==1&&nativeCamera.NativeDriverAdjusted,"Video mode is applied before editing driver properties");
Check(retainedModel.Save(),"Prepared camera mode is saved for acquisition");
var sessionStore=CameraSettingsStore.Current;
await sessionStore.ConnectAsync(sharedSession,sessionCamera);await sessionStore.ApplyAsync(sharedSession,sessionCamera);await sharedSession.StartAsync();
Check(nativeCamera.ConnectCount==1&&nativeCamera.ConfigureCount==1&&nativeCamera.NativeDriverAdjusted&&nativeCamera.IsGrabbing,
"Starting acquisition reuses the graph and does not reset the driver's native adjustment");
sharedSession.Stop();await sessionStore.ConnectAsync(sharedSession,sessionCamera);await sessionStore.ApplyAsync(sharedSession,sessionCamera);
Check(nativeCamera.ConnectCount==1&&nativeCamera.ConfigureCount==1,"Stopping grabbing without disconnecting preserves the prepared mode");
var changed=sessionStore.Load(sessionCamera);changed.UsbCapture.Fps=15;sessionStore.Save(sessionCamera,changed);
await sessionStore.ConnectAsync(sharedSession,sessionCamera);await sessionStore.ApplyAsync(sharedSession,sessionCamera);
Check(nativeCamera.ConnectCount==2&&nativeCamera.ConfigureCount==2&&!nativeCamera.NativeDriverAdjusted,
"Explicit video mode changes reconnect and are never hidden by the reuse cache");
sharedSession.Disconnect();await sessionStore.ConnectAsync(sharedSession,sessionCamera);await sessionStore.ApplyAsync(sharedSession,sessionCamera);
Check(nativeCamera.ConnectCount==3&&nativeCamera.ConfigureCount==3,"Disconnect invalidates the prepared connection and mode");
}
private static async Task CheckCompletionImageSaving(App app,SopPageViewModel sop)
@ -972,19 +948,9 @@ internal sealed class FakeCamera : ICameraService
public event Action<string>? Error {add{}remove{}}
public List<CameraInfo> Devices {get;set;}=[new(){Index=0,Name="测试相机"}];
public Task<List<CameraInfo>> EnumerateAsync()=>Task.FromResult(Devices.ToList());
public int ConnectCount {get;private set;}
public int ConfigureCount {get;private set;}
public bool NativeDriverAdjusted {get;private set;}
public Task<bool> ConnectAsync(CameraInfo camera){ConnectCount++;NativeDriverAdjusted=false;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 TaskCompletionSource<bool>? DriverPropertiesCompletion {get;set;}
public Task<bool> ShowDriverPropertiesAsync(){DriverPropertiesOpened++;NativeDriverAdjusted=true;return DriverPropertiesCompletion?.Task??Task.FromResult(SupportsDriverProperties);}
public Task<bool> ConnectAsync(CameraInfo camera){IsConnected=true;ConnectionChanged?.Invoke(true);return Task.FromResult(true);}
public UvcCaptureOptions? LastUsbOptions {get;private set;}
public Task<string> ConfigureUvcAsync(UvcCaptureOptions options){ConfigureCount++;NativeDriverAdjusted=false;LastUsbOptions=options with {};return Task.FromResult("test USB mode");}
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);}
public void Stop(){IsGrabbing=false;}public void Disconnect(){Stop();IsConnected=false;ConnectionChanged?.Invoke(false);}public int DisposeCount {get;private set;} public void Dispose(){DisposeCount++;Disconnect();}
private long _id;