using OpenCvSharp;
namespace SopHelper.Engine.Camera;
///
/// USB(UVC)相机实现。单相机最小版。
/// 三个坑照搬参考项目实测结论:MSMF 优先、DSHOW 图必须进程级串行、不可重复打开同一索引。
///
public class UvcCameraService : ICameraService
{
///
/// 进程级 DSHOW 互斥锁:DirectShow 原生图不允许并发创建/销毁,
/// 旧图还在异步销毁时开新图会触发 AccessViolationException。
///
private static readonly object DshowLock = new();
private readonly object _captureLock = new();
private VideoCapture? _capture;
private CancellationTokenSource? _cts;
private Task? _grabTask;
private long _frameId;
///
public bool IsConnected { get; private set; }
///
public bool IsGrabbing { get; private set; }
///
public event Action? FrameArrived;
///
public event Action? ConnectionChanged;
///
public event Action? Error;
/// 当前相机
public CameraInfo? Current { get; private set; }
/// 实测帧率(每 2 秒刷新一次)
public double ActualFps { get; private set; }
///
public Task> EnumerateAsync()
{
return Task.Run(() =>
{
var list = new List();
for (var i = 0; i <= 10; i++)
{
var index = i;
// 跳过本进程已占用的索引:对同一设备重复开 DSHOW 图会原生崩溃
lock (_captureLock)
{
if (_capture is not null && Current?.Index == index)
{
list.Add(new CameraInfo { Index = index, Name = $"Camera {index}(当前已连接)" });
continue;
}
}
lock (DshowLock)
{
try
{
using var probe = new VideoCapture(index, VideoCaptureAPIs.DSHOW);
if (!probe.IsOpened()) continue;
var w = probe.Get(VideoCaptureProperties.FrameWidth);
var h = probe.Get(VideoCaptureProperties.FrameHeight);
if (w <= 0 || h <= 0) continue;
list.Add(new CameraInfo { Index = index, Name = $"Camera {index}({w:F0}x{h:F0})" });
}
catch
{
// 探测失败的设备跳过即可
}
}
}
return list;
});
}
///
public Task ConnectAsync(CameraInfo camera)
{
return Task.Run(() =>
{
lock (DshowLock)
{
lock (_captureLock)
{
if (_capture is not null)
{
_capture.Dispose();
_capture = null;
}
// MSMF 优先:DSHOW 后端对"反复开图/关图"存在已知原生缺陷,
// 图销毁是系统级异步,紧接的开图仍可能撞上未完成的销毁而崩溃。
_capture = TryOpen(camera.Index, VideoCaptureAPIs.MSMF)
?? TryOpen(camera.Index, VideoCaptureAPIs.DSHOW);
if (_capture is null)
{
Error?.Invoke($"相机 {camera.Index} 打不开(MSMF 与 DSHOW 均失败)");
return false;
}
}
}
Current = camera;
IsConnected = true;
ConnectionChanged?.Invoke(true);
return true;
});
}
///
public Task StartAsync()
{
return Task.Run(() =>
{
VideoCapture capture;
lock (_captureLock)
{
if (_capture is null) return false;
capture = _capture;
}
if (IsGrabbing) return true;
_cts = new CancellationTokenSource();
IsGrabbing = true;
_grabTask = Task.Run(() => GrabLoop(capture, _cts.Token));
return true;
});
}
///
/// 采集循环
///
private void GrabLoop(VideoCapture capture, CancellationToken token)
{
var fpsWatch = System.Diagnostics.Stopwatch.StartNew();
var framesInWindow = 0;
while (!token.IsCancellationRequested)
{
var frame = new Mat();
bool ok;
lock (_captureLock)
{
if (captureDisposed) break;
ok = capture.Read(frame);
}
if (!ok || frame.Empty())
{
frame.Dispose();
// 读不到帧时轻微退避,不空转
Thread.Sleep(20);
continue;
}
// ⚠ 成功取帧后不强制 Sleep:Read 本身按相机帧节拍阻塞,
// 补一个 Sleep(33) 会把采集帧率白扣一半(参考项目实测踩过)。
_frameId++;
framesInWindow++;
if (fpsWatch.ElapsedMilliseconds >= 2000)
{
ActualFps = framesInWindow * 1000.0 / fpsWatch.ElapsedMilliseconds;
fpsWatch.Restart();
framesInWindow = 0;
}
var cameraFrame = new CameraFrame
{
FrameId = _frameId,
Timestamp = DateTime.Now,
Bgr = frame,
};
try
{
FrameArrived?.Invoke(cameraFrame);
}
catch (Exception ex)
{
Error?.Invoke($"帧回调异常: {ex.Message}");
}
finally
{
cameraFrame.Dispose();
}
}
IsGrabbing = false;
}
private volatile bool captureDisposed;
///
public void Stop()
{
_cts?.Cancel();
try
{
_grabTask?.Wait(TimeSpan.FromSeconds(2));
}
catch
{
// 取消异常忽略
}
_grabTask = null;
_cts?.Dispose();
_cts = null;
IsGrabbing = false;
}
///
public void Disconnect()
{
Stop();
lock (DshowLock)
{
lock (_captureLock)
{
if (_capture is not null)
{
captureDisposed = true;
_capture.Dispose();
_capture = null;
captureDisposed = false;
}
}
// 给系统一点时间把原生图销毁干净,紧接的 ConnectAsync 才安全
Thread.Sleep(500);
}
IsConnected = false;
Current = null;
ConnectionChanged?.Invoke(false);
}
///
public void Dispose()
{
Disconnect();
}
///
/// 用指定后端尝试打开
///
private static VideoCapture? TryOpen(int index, VideoCaptureAPIs api)
{
try
{
var capture = new VideoCapture(index, api);
if (!capture.IsOpened())
{
capture.Dispose();
return null;
}
return capture;
}
catch
{
return null;
}
}
}