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(); }