优化:启用 Linux GPU 渲染并将预览与推理解耦

This commit is contained in:
tfarcraw 2026-11-08 21:31:54 +08:00
parent 5be8b8587f
commit 23f90e4f10
11 changed files with 370 additions and 47 deletions

View File

@ -0,0 +1,21 @@
using Avalonia;
namespace SopHelper.Presentation;
public static class DesktopRendering
{
public static AppBuilder Configure(AppBuilder builder)
{
// EGL works directly with Mesa on XWayland; retain GLX and software fallbacks.
var mode = Environment.GetEnvironmentVariable("SOPHELPER_RENDERER")?.ToLowerInvariant();
var modes = mode switch
{
null or "" or "auto" => new[] { X11RenderingMode.Egl, X11RenderingMode.Glx, X11RenderingMode.Software },
"egl" => new[] { X11RenderingMode.Egl },
"glx" => new[] { X11RenderingMode.Glx },
"software" => new[] { X11RenderingMode.Software },
_ => throw new ArgumentException("SOPHELPER_RENDERER 必须为 auto、egl、glx 或 software"),
};
return builder.With(new X11PlatformOptions { RenderingMode = modes });
}
}

View File

@ -1,7 +1,9 @@
using System.Runtime.InteropServices;
using Avalonia;
using Avalonia.Media;
using Avalonia.Platform;
using OpenCvSharp;
using Size = Avalonia.Size;
using Rect = Avalonia.Rect;
using NativeBitmap = Avalonia.Media.Imaging.Bitmap;
using NativeWritableBitmap = Avalonia.Media.Imaging.WriteableBitmap;
@ -29,9 +31,8 @@ public class BitmapSource : IImage, IDisposable
IntPtr data,int bufferSize,int stride)
{
if (bufferSize < checked(stride*height)) throw new ArgumentException("图像缓冲不足");
var input=new byte[bufferSize];Marshal.Copy(data,input,0,bufferSize);
using var converted=new WriteableBitmap(width,height,dpiX,dpiY,format,palette);
converted.WritePixels(new PixelRect(0,0,width,height),input,stride,0);
converted.WritePixels(new PixelRect(0,0,width,height),data,stride);
return converted.Snapshot();
}
public static unsafe BitmapSource Create(int width,int height,double dpiX,double dpiY,PixelFormat format,object? palette,byte[] bytes,int stride)
@ -49,17 +50,21 @@ public sealed class WriteableBitmap : BitmapSource
{
public WriteableBitmap(int width,int height,double dpiX,double dpiY,PixelFormat format,object? palette)
{ Native = new NativeWritableBitmap(new PixelSize(width,height),new Vector(dpiX,dpiY),format,AlphaFormat.Opaque); }
public void WritePixels(PixelRect rect,byte[] bytes,int stride,int offset)
public unsafe void WritePixels(PixelRect rect,byte[] bytes,int stride,int offset)
{
if (offset<0 || stride<checked(rect.Width*3) || bytes.Length-offset<checked((rect.Height-1)*stride+rect.Width*3))
throw new ArgumentException("图像缓冲不足");
fixed(byte* data=bytes)WritePixels(rect,(IntPtr)(data+offset),stride);
}
public void WritePixels(PixelRect rect,IntPtr data,int stride)
{
using var framebuffer=((NativeWritableBitmap)Native!).Lock();
if (rect.X!=0 || rect.Y!=0 || rect.Width!=PixelWidth || rect.Height!=PixelHeight) throw new ArgumentException("预览需写入完整帧");
var rowBytes=new byte[rect.Width*4];
for(var row=0;row<rect.Height;row++)
{
for(var x=0;x<rect.Width;x++)
{var source=offset+row*stride+x*3;var target=x*4;rowBytes[target]=bytes[source];rowBytes[target+1]=bytes[source+1];rowBytes[target+2]=bytes[source+2];rowBytes[target+3]=255;}
Marshal.Copy(rowBytes,0,framebuffer.Address+row*framebuffer.RowBytes,rowBytes.Length);
}
if(data==IntPtr.Zero || stride<checked(rect.Width*3))throw new ArgumentException("无效的 BGR 图像缓冲");
using var framebuffer=((NativeWritableBitmap)Native!).Lock();
// OpenCV uses SIMD for conversion and writes directly into the Avalonia surface.
using var source=Mat.FromPixelData(rect.Height,rect.Width,MatType.CV_8UC3,data,stride);
using var target=Mat.FromPixelData(rect.Height,rect.Width,MatType.CV_8UC4,framebuffer.Address,framebuffer.RowBytes);
Cv2.CvtColor(source,target,ColorConversionCodes.BGR2BGRA);
}
internal BitmapSource Snapshot()
{

View File

@ -1,14 +1,18 @@
namespace SopHelper.Presentation.Threading;
// UI scheduling is shared by both targets. No Win32/WPF dispatcher is involved.
public enum DispatcherPriority { Normal, Background }
public enum DispatcherPriority { Normal, Background, Render }
public sealed class Dispatcher
{
public static Dispatcher CurrentDispatcher { get; } = new();
public bool HasShutdownStarted => Avalonia.Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime { MainWindow: null };
public void BeginInvoke(Action action, DispatcherPriority priority = DispatcherPriority.Normal) =>
Avalonia.Threading.Dispatcher.UIThread.Post(action, priority == DispatcherPriority.Background
? Avalonia.Threading.DispatcherPriority.Background : Avalonia.Threading.DispatcherPriority.Normal);
Avalonia.Threading.Dispatcher.UIThread.Post(action, priority switch
{
DispatcherPriority.Background => Avalonia.Threading.DispatcherPriority.Background,
DispatcherPriority.Render => Avalonia.Threading.DispatcherPriority.Render,
_ => Avalonia.Threading.DispatcherPriority.Normal,
});
public void Invoke(Action action)
{
if (Avalonia.Threading.Dispatcher.UIThread.CheckAccess()) action();

View File

@ -7,6 +7,7 @@ internal static class Program
public static int Main(string[] args)
{
if(args.Contains("--check-runtime"))return Diagnostics.RuntimeCheck.Run();
return AppBuilder.Configure<App>().UsePlatformDetect().LogToTrace().StartWithClassicDesktopLifetime(args);
return Presentation.DesktopRendering.Configure(AppBuilder.Configure<App>().UsePlatformDetect())
.LogToTrace().StartWithClassicDesktopLifetime(args);
}
}

View File

@ -1,6 +1,6 @@
using System.Collections.ObjectModel;
using System.IO;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Text.Json;
using Avalonia.Media;
using ImageSource = Avalonia.Media.IImage;
@ -40,9 +40,9 @@ public class SopPageViewModel : ViewModelBase
private readonly IDialogService _dialogs;
private readonly Dispatcher _dispatcher;
private readonly DispatcherTimer _renderTimer;
private int _renderQueued;
/// <summary>采集线程写、UI 线程取最新帧</summary>
/// <summary>采集线程写、UI 线程取最新帧;最多排队一个刷新请求</summary>
private readonly object _frameLock = new();
private Mat? _pending;
@ -54,6 +54,7 @@ public class SopPageViewModel : ViewModelBase
private WriteableBitmap? _bitmap;
private long _frameCount;
private long _lastTickCount;
private readonly Stopwatch _fpsClock = Stopwatch.StartNew();
private CameraInfo? _selectedCamera;
private CameraInfo? _lastUsedCamera;
@ -102,11 +103,6 @@ public class SopPageViewModel : ViewModelBase
_engine.StepSnapshotChanged += snapshot => _dispatcher.BeginInvoke(() => UpdateCard(snapshot));
_engine.Completed += () => _dispatcher.BeginInvoke(() => StatusText = "本轮完成");
// 渲染定时器:从采集线程留下的最新帧取一份画出来(天然限帧,不在采集线程做 UI 活)
_renderTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(40) };
_renderTimer.Tick += (_, _) => RenderFrame();
_renderTimer.Start();
LoadRecipes();
// 命令接线(DelegateCommand 的可用条件都挂在这里)
@ -311,7 +307,7 @@ public class SopPageViewModel : ViewModelBase
}
/// <summary>
/// 采集线程:克隆一份交给渲染定时器,避免与相机的释放抢生命周期
/// 采集线程:克隆最新帧并合并 UI 刷新请求,避免推理或定时轮询拖慢预览
/// </summary>
private void OnCameraFrame(CameraFrame frame)
{
@ -323,6 +319,12 @@ public class SopPageViewModel : ViewModelBase
_pending = clone;
old?.Dispose();
}
if (Interlocked.Exchange(ref _renderQueued, 1) == 0)
_dispatcher.BeginInvoke(() =>
{
Interlocked.Exchange(ref _renderQueued, 0);
if (!_destroyed) RenderFrame();
}, DispatcherPriority.Render);
}
/// <summary>
@ -350,7 +352,6 @@ public class SopPageViewModel : ViewModelBase
/// <inheritdoc />
public override void Destroy()
{
_renderTimer.Stop();
_camera.FrameArrived -= OnCameraFrame;
lock (_frameLock)
@ -670,7 +671,7 @@ public class SopPageViewModel : ViewModelBase
}
/// <summary>
/// 渲染定时器:取采集线程留下的最新帧
/// UI 刷新:取采集线程留下的最新帧,不积压历史画面
/// </summary>
private void RenderFrame()
{
@ -699,14 +700,7 @@ public class SopPageViewModel : ViewModelBase
if (HandResult?.Size != (src.Cols, src.Rows)) HandResult = null;
}
var bytes = new byte[src.Rows * src.Cols * src.Channels()];
Marshal.Copy(src.Data, bytes, 0, bytes.Length);
// Mat.Step 是方法不是属性;这里按行字节数显式算,别依赖 Mat 的内部 stride
var stride = src.Cols * src.ElemSize();
// 注意:rect 是 (宽, 高),OpenCvSharp 的 Rows/Cols 是 (高, 宽),别写反
_bitmap.WritePixels(new Avalonia.PixelRect(0, 0, src.Cols, src.Rows), bytes, stride, 0);
_bitmap.WritePixels(new Avalonia.PixelRect(0, 0, src.Cols, src.Rows), src.Data, checked((int)src.Step()));
}
// 同一 IImage 引用不会触发 Avalonia Image 的重绘;覆盖层的局部刷新会留下旧画面。
@ -715,10 +709,13 @@ public class SopPageViewModel : ViewModelBase
Frame = _bitmap.Snapshot();
previous?.Dispose();
// 帧率:这 40ms 里处理了几帧
var delta = _frameCount - _lastTickCount;
_lastTickCount = _frameCount;
FpsText = $"{delta * 25.0:F1} fps(渲染)";
// 按真实经过的时间统计成功发布的预览帧。
if (_fpsClock.Elapsed.TotalSeconds >= 0.5)
{
FpsText = $"{(_frameCount - _lastTickCount) / _fpsClock.Elapsed.TotalSeconds:F1} fps(渲染)";
_lastTickCount = _frameCount;
_fpsClock.Restart();
}
}
private void UpdateCard(StepSnapshot snapshot)

View File

@ -51,6 +51,12 @@ public class DetectionPipeline : IDisposable
private long _seen;
private long _processed;
private bool _disposed;
private readonly object _frameGate = new();
private readonly SemaphoreSlim _frameSignal = new(0, 1);
private CameraFrame? _pendingFrame;
private CancellationTokenSource? _processingCancellation;
private Task? _processingTask;
private bool _acceptFrames;
/// <summary>管线就绪度(缺哪个模型就在这里报告,界面据此提示)</summary>
public List<string> Warnings { get; private set; } = [];
@ -81,9 +87,11 @@ public class DetectionPipeline : IDisposable
/// </summary>
public void LoadModels(PipelineOptions options)
{
StopProcessing();
_options = options;
Warnings = [];
_yolo.Dispose();
_hand.Dispose();
if (options.YoloModelPath is not null)
{
@ -132,10 +140,23 @@ public class DetectionPipeline : IDisposable
/// </summary>
public async Task<bool> StartAsync()
{
ObjectDisposedException.ThrowIf(_disposed, this);
StopProcessing();
_seen = 0;
_processed = 0;
return await _camera.StartAsync();
AvgInferenceMs = 0;
ResultFps = 0;
_processingCancellation = new CancellationTokenSource();
var token = _processingCancellation.Token;
lock (_frameGate) _acceptFrames = true;
_processingTask = Task.Run(() => ProcessLoopAsync(token));
try
{
if (await _camera.StartAsync()) return true;
StopProcessing();
return false;
}
catch { StopProcessing(); throw; }
}
/// <summary>
@ -143,7 +164,45 @@ public class DetectionPipeline : IDisposable
/// </summary>
public void Stop()
{
_camera.Stop();
lock (_frameGate) _acceptFrames = false;
try { _camera.Stop(); }
finally { StopProcessing(); }
}
private void StopProcessing()
{
lock (_frameGate)
{
_acceptFrames = false;
_pendingFrame?.Dispose();
_pendingFrame = null;
_processingCancellation?.Cancel();
}
_processingTask?.GetAwaiter().GetResult();
_processingTask = null;
_processingCancellation?.Dispose();
_processingCancellation = null;
while (_frameSignal.Wait(0)) { }
}
private async Task ProcessLoopAsync(CancellationToken token)
{
try
{
while (true)
{
await _frameSignal.WaitAsync(token);
CameraFrame? frame;
lock (_frameGate) { frame = _pendingFrame; _pendingFrame = null; }
if (frame is null) continue;
using (frame)
{
if (token.IsCancellationRequested) break;
ProcessFrame(frame, token);
}
}
}
catch (OperationCanceledException) when (token.IsCancellationRequested) { }
}
/// <summary>
@ -151,11 +210,18 @@ public class DetectionPipeline : IDisposable
/// </summary>
private void OnFrame(CameraFrame frame)
{
_seen++;
var stride = Math.Max(1, _options.FrameStride);
if (_seen % stride != 0) return;
lock (_frameGate)
{
if (!_acceptFrames || ++_seen % Math.Max(1, _options.FrameStride) != 0) return;
var copy = new CameraFrame { FrameId = frame.FrameId, Timestamp = frame.Timestamp, Bgr = frame.Bgr.Clone() };
_pendingFrame?.Dispose();
_pendingFrame = copy;
if (_frameSignal.CurrentCount == 0) _frameSignal.Release();
}
}
private void ProcessFrame(CameraFrame frame, CancellationToken token)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
var result = new FrameResult
@ -192,7 +258,7 @@ public class DetectionPipeline : IDisposable
AvgInferenceMs = AvgInferenceMs <= 0 ? ms : AvgInferenceMs * 0.9 + ms * 0.1;
ResultFps = AvgInferenceMs <= 0 ? 0 : 1000.0 / AvgInferenceMs;
ResultArrived?.Invoke(result);
if (!token.IsCancellationRequested) ResultArrived?.Invoke(result);
}
/// <inheritdoc />
@ -201,6 +267,8 @@ public class DetectionPipeline : IDisposable
if (_disposed) return;
_disposed = true;
_camera.FrameArrived -= OnFrame;
StopProcessing();
_frameSignal.Dispose();
_yolo.Dispose();
_hand.Dispose();
}

View File

@ -11,6 +11,23 @@ try
foreach(var device in cameras)Console.WriteLine($"DEVICE: {device.Name}");
if(errors.Count>0)throw new Exception("Camera enumeration reported an error");
Console.WriteLine($"PASS: SDK initialized and enumerated {cameras.Count} camera(s)");
if(args.Contains("--inspect-timing"))
{
var result=DeviceEnumerator.EnumDevices(DeviceTLayerType.MvGigEDevice|DeviceTLayerType.MvUsbDevice,out var infos);
if(result!=MvError.MV_OK||infos.Count==0)throw new Exception("Enumeration failed");
using var device=DeviceFactory.CreateDevice(infos[0]);
if(device.Open()!=MvError.MV_OK)throw new Exception("Open failed");
try
{
foreach(var node in new[]{"ExposureTime","AcquisitionFrameRate","ResultingFrameRate"})
if(device.Parameters.GetFloatValue(node,out var value)==MvError.MV_OK)
Console.WriteLine($"TIMING: {node}={value.CurValue} (max={value.Max})");
foreach(var node in new[]{"PayloadSize","DeviceLinkThroughputLimit","GevSCPSPacketSize","GevSCPD"})
if(device.Parameters.GetIntValue(node,out var value)==MvError.MV_OK)
Console.WriteLine($"TRANSPORT: {node}={value.CurValue}");
}
finally { device.Close(); }
}
if(args.Contains("--inspect-frame"))
{
var result=DeviceEnumerator.EnumDevices(DeviceTLayerType.MvGigEDevice|DeviceTLayerType.MvUsbDevice,out var infos);

View File

@ -0,0 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
<ItemGroup><ProjectReference Include="../../src/SopHelper.CrossPlatform.Engine/SopHelper.CrossPlatform.Engine.csproj" /></ItemGroup>
</Project>

View File

@ -0,0 +1,63 @@
using System.Collections.Concurrent;
using OpenCvSharp;
using SopHelper.Engine.Camera;
using SopHelper.Engine.Pipeline;
using var camera = new TestCamera();
using var pipeline = new DetectionPipeline(camera);
var results = new ConcurrentQueue<long>();
using var entered = new ManualResetEventSlim();
using var release = new ManualResetEventSlim();
pipeline.ResultArrived += frame =>
{
results.Enqueue(frame.FrameId);
if(frame.FrameId == 1) { entered.Set(); if(!release.Wait(TimeSpan.FromSeconds(5)))throw new Exception("Worker release timed out"); }
};
if(!await pipeline.StartAsync())throw new Exception("Start failed");
try
{
await Task.Run(() => camera.Emit(1)).WaitAsync(TimeSpan.FromSeconds(2));
if(!entered.Wait(TimeSpan.FromSeconds(2)))throw new Exception("Worker did not process frame");
// Hold the consumer busy while acquisition delivers more frames and disposes their Mats.
await Task.Run(() => { for(var id=2;id<=10;id++)camera.Emit(id); }).WaitAsync(TimeSpan.FromSeconds(2));
Console.WriteLine("PASS: Busy inference does not block camera callbacks");
}
finally { release.Set(); }
for(var i=0;i<100&&results.Count<2;i++)await Task.Delay(10);
pipeline.Stop();
if(!results.SequenceEqual(new long[]{1,10}))throw new Exception("Stale inference frames were queued: "+string.Join(',',results));
Console.WriteLine("PASS: Only the latest pending frame is processed; camera-owned Mats may be disposed immediately");
camera.Emit(11);await Task.Delay(30);
if(results.Count!=2)throw new Exception("Stopped pipeline accepted a frame");
if(!await pipeline.StartAsync())throw new Exception("Restart failed");
camera.Emit(12);
for(var i=0;i<100&&results.Count<3;i++)await Task.Delay(10);
pipeline.Stop();
if(!results.SequenceEqual(new long[]{1,10,12}))throw new Exception("Restart left stale results");
Console.WriteLine("PASS: Stop drains the worker and restart accepts only new frames");
pipeline.LoadModels(new PipelineOptions { FrameStride = 2 });
await pipeline.StartAsync();camera.Emit(13);camera.Emit(14);
for(var i=0;i<100&&results.Count<4;i++)await Task.Delay(10);
pipeline.Stop();
if(results.Last()!=14||results.Count!=4)throw new Exception("Frame stride was not preserved");
Console.WriteLine("PASS: Frame stride is preserved by the asynchronous worker");
internal sealed class TestCamera : ICameraService
{
public bool IsConnected => true;
public bool IsGrabbing {get;private set;}
public event Action<CameraFrame>? FrameArrived;
public event Action<bool>? ConnectionChanged {add{}remove{}}
public event Action<string>? Error {add{}remove{}}
public Task<List<CameraInfo>> EnumerateAsync()=>Task.FromResult(new List<CameraInfo>());
public Task<bool> ConnectAsync(CameraInfo camera)=>Task.FromResult(true);
public Task<bool> StartAsync(){IsGrabbing=true;return Task.FromResult(true);}
public void Emit(long id)
{
using var frame=new CameraFrame {FrameId=id,Timestamp=DateTime.Now,Bgr=new Mat(32,32,MatType.CV_8UC3,Scalar.Black)};
FrameArrived?.Invoke(frame);
}
public void Stop()=>IsGrabbing=false;
public void Disconnect()=>Stop();
public void Dispose()=>Stop();
}

View File

@ -0,0 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
<ItemGroup><ProjectReference Include="../../src/SopHelper.Avalonia/SopHelper.Avalonia.csproj" /></ItemGroup>
</Project>

View File

@ -0,0 +1,139 @@
using System.Diagnostics;
using System.Text.Json;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.OpenGL;
using Avalonia.OpenGL.Controls;
using Avalonia.Threading;
using OpenCvSharp;
using Prism.Ioc;
using SopHelper;
using SopHelper.Engine.Camera;
using SopHelper.Engine.Pipeline;
using SopHelper.Presentation;
using SopHelper.VVMs.SopPage;
using Window = Avalonia.Controls.Window;
internal static class PreviewSmoke
{
private static ICameraService Camera = null!;
private static long _acquired;
private static int _exit = 1;
[STAThread]
public static int Main(string[] args)
{
Camera = args.Contains("--hardware") ? new HikvisionCameraService() : new SyntheticCamera();
Camera.FrameArrived += _ => Interlocked.Increment(ref _acquired);
Camera.Error += Console.Error.WriteLine;
var cameraPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SopHelper", "last-camera.json");
var previousCamera = File.Exists(cameraPath) ? File.ReadAllBytes(cameraPath) : null;
try
{
Trace.Listeners.Add(new ConsoleTraceListener());
DesktopRendering.Configure(AppBuilder.Configure(() => new App(Camera)).UsePlatformDetect())
.LogToTrace(Avalonia.Logging.LogEventLevel.Warning)
.AfterSetup(_ =>
{
var lifetime = (IClassicDesktopStyleApplicationLifetime)Application.Current!.ApplicationLifetime!;
lifetime.Startup += (_, _) => Dispatcher.UIThread.Post(async () => await Run(lifetime));
}).StartWithClassicDesktopLifetime([], ShutdownMode.OnExplicitShutdown);
return _exit;
}
finally
{
if(previousCamera is not null)File.WriteAllBytes(cameraPath,previousCamera);
else if(File.Exists(cameraPath))File.Delete(cameraPath);
}
}
private static async Task Run(IClassicDesktopStyleApplicationLifetime lifetime)
{
try
{
var gl = new GlProbe();
var probeWindow = new Window { Width = 160, Height = 100, Content = gl, Title = "GPU check" };
probeWindow.Show();
var renderer = await gl.Renderer.Task.WaitAsync(TimeSpan.FromSeconds(15));
Console.WriteLine("OpenGL renderer: " + renderer);
if (renderer.Contains("llvmpipe", StringComparison.OrdinalIgnoreCase) || renderer.Contains("softpipe", StringComparison.OrdinalIgnoreCase))
throw new Exception("Mesa is using a software renderer");
probeWindow.Close();
var sop = ((App)Application.Current!).Container.Resolve<SopPageViewModel>();
for (var i = 0; i < 100 && sop.Cameras.Count == 0; i++) await Task.Delay(20);
sop.SelectedCamera = sop.Cameras.Single();
sop.StartStopCommand.Execute();
for (var i = 0; i < 100 && !sop.IsRunning; i++) await Task.Delay(50);
if (!sop.IsRunning) throw new Exception("Synthetic camera failed to start");
var changes = 0;
System.ComponentModel.PropertyChangedEventHandler changed = (_, e) => { if (e.PropertyName == nameof(sop.Frame)) changes++; };
sop.PropertyChanged += changed;
// Warm up native conversion, texture upload and model sessions before measuring.
await Task.Delay(2000);
changes = 0;
var produced = Interlocked.Read(ref _acquired);
var watch = Stopwatch.StartNew();
await Task.Delay(5000);
var seconds = watch.Elapsed.TotalSeconds;
var fps = changes / seconds;
var pipeline = ((App)Application.Current!).Container.Resolve<DetectionPipeline>();
sop.PropertyChanged -= changed;
Console.WriteLine(JsonSerializer.Serialize(new { renderer, camera = Camera is SyntheticCamera ? "synthetic" : "hikvision",
width = sop.FrameWidth, height = sop.FrameHeight,
previewUpdatesPerSecond = fps, acquisitionFps = (Interlocked.Read(ref _acquired) - produced) / seconds, status = sop.FpsText,
handBackend = pipeline.HandBackend, yoloBackend = pipeline.YoloBackend, inferenceMs = pipeline.AvgInferenceMs }));
if (fps < (Camera is SyntheticCamera ? 28 : 1)) throw new Exception("Preview updates are below the expected rate");
sop.StartStopCommand.Execute();
for (var i = 0; i < 100 && sop.IsRunning; i++) await Task.Delay(50);
if (sop.IsRunning) throw new Exception("Stop failed");
_exit = 0;
}
catch (Exception error) { Console.Error.WriteLine(error); }
finally { lifetime.Shutdown(_exit); }
}
}
internal sealed class GlProbe : OpenGlControlBase
{
public TaskCompletionSource<string> Renderer { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
protected override void OnOpenGlInit(GlInterface gl) => Renderer.TrySetResult(gl.GetString(0x1F01) ?? throw new Exception("OpenGL renderer was not reported"));
protected override void OnOpenGlRender(GlInterface gl, int fb) { gl.ClearColor(0, 0, 0, 1); gl.Clear(0x4000); }
}
internal sealed class SyntheticCamera : ICameraService
{
private CancellationTokenSource? _cancel;
private Task? _task;
public long Produced;
public bool IsConnected { get; private set; }
public bool IsGrabbing { get; private set; }
public event Action<CameraFrame>? FrameArrived;
public event Action<bool>? ConnectionChanged;
public event Action<string>? Error { add { } remove { } }
public Task<List<CameraInfo>> EnumerateAsync() => Task.FromResult(new List<CameraInfo> { new() { Name = "Synthetic 5MP / 60 fps" } });
public Task<bool> ConnectAsync(CameraInfo camera) { IsConnected = true; ConnectionChanged?.Invoke(true); return Task.FromResult(true); }
public Task<bool> StartAsync()
{
_cancel = new();var token = _cancel.Token;IsGrabbing = true;
_task = Task.Run(async () =>
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(1.0 / 60));
try
{
while (await timer.WaitForNextTickAsync(token))
{
var id = Interlocked.Increment(ref Produced);
using var frame = new CameraFrame { FrameId = id, Timestamp = DateTime.Now,
Bgr = new Mat(2048, 2448, MatType.CV_8UC3, new Scalar(35, 60, 90)) };
Cv2.Rectangle(frame.Bgr, new OpenCvSharp.Rect((int)(id * 25 % 2200), 200, 160, 160), new Scalar(0, 0, 255), -1);
FrameArrived?.Invoke(frame);
}
}
catch (OperationCanceledException) when (token.IsCancellationRequested) { }
});
return Task.FromResult(true);
}
public void Stop() { _cancel?.Cancel();_task?.GetAwaiter().GetResult();_task = null;_cancel?.Dispose();_cancel = null;IsGrabbing = false; }
public void Disconnect() { Stop();IsConnected = false;ConnectionChanged?.Invoke(false); }
public void Dispose() => Disconnect();
}