diff --git a/src/SopHelper.Avalonia/Presentation/DesktopRendering.cs b/src/SopHelper.Avalonia/Presentation/DesktopRendering.cs new file mode 100644 index 0000000..1a2722d --- /dev/null +++ b/src/SopHelper.Avalonia/Presentation/DesktopRendering.cs @@ -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 }); + } +} diff --git a/src/SopHelper.Avalonia/Presentation/Imaging.cs b/src/SopHelper.Avalonia/Presentation/Imaging.cs index 1cda070..3cd24d1 100644 --- a/src/SopHelper.Avalonia/Presentation/Imaging.cs +++ b/src/SopHelper.Avalonia/Presentation/Imaging.cs @@ -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 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(); diff --git a/src/SopHelper.Avalonia/Program.cs b/src/SopHelper.Avalonia/Program.cs index eea8a6a..fc91d91 100644 --- a/src/SopHelper.Avalonia/Program.cs +++ b/src/SopHelper.Avalonia/Program.cs @@ -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().UsePlatformDetect().LogToTrace().StartWithClassicDesktopLifetime(args); + return Presentation.DesktopRendering.Configure(AppBuilder.Configure().UsePlatformDetect()) + .LogToTrace().StartWithClassicDesktopLifetime(args); } } diff --git a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs index af6c6d0..b20619f 100644 --- a/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs +++ b/src/SopHelper.Avalonia/VVMs/SopPage/SopPageViewModel.cs @@ -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; - /// 采集线程写、UI 线程取最新帧 + /// 采集线程写、UI 线程取最新帧;最多排队一个刷新请求 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 } /// - /// 采集线程:克隆一份交给渲染定时器,避免与相机的释放抢生命周期 + /// 采集线程:克隆最新帧并合并 UI 刷新请求,避免推理或定时轮询拖慢预览 /// 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); } /// @@ -350,7 +352,6 @@ public class SopPageViewModel : ViewModelBase /// public override void Destroy() { - _renderTimer.Stop(); _camera.FrameArrived -= OnCameraFrame; lock (_frameLock) @@ -670,7 +671,7 @@ public class SopPageViewModel : ViewModelBase } /// - /// 渲染定时器:取采集线程留下的最新帧 + /// UI 刷新:取采集线程留下的最新帧,不积压历史画面 /// 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) diff --git a/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs b/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs index 83bda48..75f2893 100644 --- a/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs +++ b/src/SopHelper.CrossPlatform.Engine/Pipeline/DetectionPipeline.cs @@ -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; /// 管线就绪度(缺哪个模型就在这里报告,界面据此提示) public List Warnings { get; private set; } = []; @@ -81,9 +87,11 @@ public class DetectionPipeline : IDisposable /// 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 /// public async Task 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; } } /// @@ -143,7 +164,45 @@ public class DetectionPipeline : IDisposable /// 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) { } } /// @@ -151,11 +210,18 @@ public class DetectionPipeline : IDisposable /// 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); } /// @@ -201,6 +267,8 @@ public class DetectionPipeline : IDisposable if (_disposed) return; _disposed = true; _camera.FrameArrived -= OnFrame; + StopProcessing(); + _frameSignal.Dispose(); _yolo.Dispose(); _hand.Dispose(); } diff --git a/tests/Mvs.Smoke/Program.cs b/tests/Mvs.Smoke/Program.cs index 37fca7c..238b1b7 100644 --- a/tests/Mvs.Smoke/Program.cs +++ b/tests/Mvs.Smoke/Program.cs @@ -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); diff --git a/tests/Pipeline.Smoke/Pipeline.Smoke.csproj b/tests/Pipeline.Smoke/Pipeline.Smoke.csproj new file mode 100644 index 0000000..5716f4b --- /dev/null +++ b/tests/Pipeline.Smoke/Pipeline.Smoke.csproj @@ -0,0 +1,4 @@ + + Exenet8.0enableenable + + diff --git a/tests/Pipeline.Smoke/Program.cs b/tests/Pipeline.Smoke/Program.cs new file mode 100644 index 0000000..7a693fc --- /dev/null +++ b/tests/Pipeline.Smoke/Program.cs @@ -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(); +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? FrameArrived; + public event Action? ConnectionChanged {add{}remove{}} + public event Action? Error {add{}remove{}} + public Task> EnumerateAsync()=>Task.FromResult(new List()); + public Task ConnectAsync(CameraInfo camera)=>Task.FromResult(true); + public Task 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(); +} diff --git a/tests/Preview.Smoke/Preview.Smoke.csproj b/tests/Preview.Smoke/Preview.Smoke.csproj new file mode 100644 index 0000000..41f5e3f --- /dev/null +++ b/tests/Preview.Smoke/Preview.Smoke.csproj @@ -0,0 +1,4 @@ + + Exenet8.0enableenable + + diff --git a/tests/Preview.Smoke/Program.cs b/tests/Preview.Smoke/Program.cs new file mode 100644 index 0000000..4a4d067 --- /dev/null +++ b/tests/Preview.Smoke/Program.cs @@ -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(); + 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(); + 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 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? FrameArrived; + public event Action? ConnectionChanged; + public event Action? Error { add { } remove { } } + public Task> EnumerateAsync() => Task.FromResult(new List { new() { Name = "Synthetic 5MP / 60 fps" } }); + public Task ConnectAsync(CameraInfo camera) { IsConnected = true; ConnectionChanged?.Invoke(true); return Task.FromResult(true); } + public Task 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(); +}