Add one shared engine target for Windows and Linux Avalonia builds
This commit is contained in:
parent
4c7be2b598
commit
528d286b8f
@ -0,0 +1,24 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
|
||||
<NativePlatform Condition="$([System.String]::Copy('$(RuntimeIdentifier)').StartsWith('linux'))">Linux</NativePlatform>
|
||||
<NativePlatform Condition="$([System.String]::Copy('$(RuntimeIdentifier)').StartsWith('win'))">Windows</NativePlatform>
|
||||
<NativePlatform Condition="'$(NativePlatform)' == '' and '$(OS)' == 'Windows_NT'">Windows</NativePlatform>
|
||||
<NativePlatform Condition="'$(NativePlatform)' == ''">Linux</NativePlatform>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="../SopHelper.Engine/**/*.cs" Exclude="../SopHelper.Engine/obj/**;../SopHelper.Engine/bin/**;../SopHelper.Engine/Camera/UvcCameraService.cs" Link="Engine/%(RecursiveDir)%(Filename)%(Extension)" />
|
||||
<Compile Include="*.cs" />
|
||||
<Reference Include="MvCameraControl.Net"><HintPath>../../libs/MvCameraControl.Net.dll</HintPath><Private>true</Private></Reference>
|
||||
<PackageReference Include="OpenCvSharp4" Version="4.13.0.20260627" />
|
||||
<PackageReference Include="OpenCvSharp4.runtime.win" Version="4.13.0.20260627" Condition="'$(NativePlatform)' == 'Windows'" />
|
||||
<PackageReference Include="OpenCvSharp4.official.runtime.linux-x64" Version="4.13.0.20260627" Condition="'$(NativePlatform)' == 'Linux'" />
|
||||
<PackageReference Include="Microsoft.ML.OnnxRuntime.Gpu" Version="1.23.0" Condition="'$(NativePlatform)' == 'Windows'" />
|
||||
<PackageReference Include="Microsoft.ML.OnnxRuntime" Version="1.23.0" Condition="'$(NativePlatform)' == 'Linux'" />
|
||||
<PackageReference Include="YamlDotNet" Version="16.3.0" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
289
src/SopHelper.CrossPlatform.Engine/UvcCameraService.cs
Normal file
289
src/SopHelper.CrossPlatform.Engine/UvcCameraService.cs
Normal file
@ -0,0 +1,289 @@
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace SopHelper.Engine.Camera;
|
||||
|
||||
/// <summary>
|
||||
/// USB(UVC)相机实现。单相机最小版。
|
||||
/// 三个坑照搬参考项目实测结论:MSMF 优先、DSHOW 图必须进程级串行、不可重复打开同一索引。
|
||||
/// </summary>
|
||||
public class UvcCameraService : ICameraService
|
||||
{
|
||||
/// <summary>
|
||||
/// 进程级 DSHOW 互斥锁:DirectShow 原生图不允许并发创建/销毁,
|
||||
/// 旧图还在异步销毁时开新图会触发 AccessViolationException。
|
||||
/// </summary>
|
||||
private static readonly object DshowLock = new();
|
||||
|
||||
private readonly object _captureLock = new();
|
||||
private VideoCapture? _capture;
|
||||
private CancellationTokenSource? _cts;
|
||||
private Task? _grabTask;
|
||||
private long _frameId;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsConnected { get; private set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsGrabbing { get; private set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public event Action<CameraFrame>? FrameArrived;
|
||||
|
||||
/// <inheritdoc />
|
||||
public event Action<bool>? ConnectionChanged;
|
||||
|
||||
/// <inheritdoc />
|
||||
public event Action<string>? Error;
|
||||
|
||||
/// <summary>当前相机</summary>
|
||||
public CameraInfo? Current { get; private set; }
|
||||
|
||||
/// <summary>实测帧率(每 2 秒刷新一次)</summary>
|
||||
public double ActualFps { get; private set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<List<CameraInfo>> EnumerateAsync()
|
||||
{
|
||||
return Task.Run(() =>
|
||||
{
|
||||
var list = new List<CameraInfo>();
|
||||
|
||||
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, OperatingSystem.IsWindows() ? VideoCaptureAPIs.DSHOW : VideoCaptureAPIs.V4L2);
|
||||
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;
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<bool> ConnectAsync(CameraInfo camera)
|
||||
{
|
||||
return Task.Run(() =>
|
||||
{
|
||||
lock (DshowLock)
|
||||
{
|
||||
lock (_captureLock)
|
||||
{
|
||||
if (_capture is not null)
|
||||
{
|
||||
_capture.Dispose();
|
||||
_capture = null;
|
||||
}
|
||||
|
||||
// MSMF 优先:DSHOW 后端对"反复开图/关图"存在已知原生缺陷,
|
||||
// 图销毁是系统级异步,紧接的开图仍可能撞上未完成的销毁而崩溃。
|
||||
_capture = OperatingSystem.IsWindows()
|
||||
? TryOpen(camera.Index, VideoCaptureAPIs.MSMF) ?? TryOpen(camera.Index, VideoCaptureAPIs.DSHOW)
|
||||
: TryOpen(camera.Index, VideoCaptureAPIs.V4L2);
|
||||
|
||||
if (_capture is null)
|
||||
{
|
||||
Error?.Invoke($"相机 {camera.Index} 打不开(系统采集后端打开失败)");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Current = camera;
|
||||
IsConnected = true;
|
||||
ConnectionChanged?.Invoke(true);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<bool> 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;
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 采集循环
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Stop()
|
||||
{
|
||||
_cts?.Cancel();
|
||||
|
||||
try
|
||||
{
|
||||
_grabTask?.Wait(TimeSpan.FromSeconds(2));
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 取消异常忽略
|
||||
}
|
||||
|
||||
_grabTask = null;
|
||||
_cts?.Dispose();
|
||||
_cts = null;
|
||||
IsGrabbing = false;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
Disconnect();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 用指定后端尝试打开
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user