aisop/tests/Pipeline.Smoke/Program.cs

99 lines
5.6 KiB
C#

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");
if (args.Length >= 3)
{
var palm = Path.Combine(args[1], "palm_detection_full_Nx3x192x192_post.onnx");
var landmark = Path.Combine(args[1], "hand_landmark_sparse_Nx3x224x224.onnx");
using var hand = new SopHelper.Engine.Inference.MediaPipeHandDetector();
hand.Load(palm, landmark, preferGpu: false);
using var video = new VideoCapture(args[2]);
using var image = new Mat();
var found = false;
for (var i = 0; i < 300 && video.Read(image); i++)
if (i % 5 == 0 && hand.Detect(image).Count > 0) { found = true; break; }
if (!found) throw new Exception("No hand detected in regression video");
pipeline.LoadModels(new PipelineOptions { YoloModelPath=args[0], PalmModelPath=palm, LandmarkModelPath=landmark, PreferGpu=false });
var completion = new TaskCompletionSource<SopHelper.Engine.Common.FrameResult>(TaskCreationOptions.RunContinuationsAsynchronously);
pipeline.ResultArrived += result => completion.TrySetResult(result);
await pipeline.StartAsync();camera.Emit(100,image);
var frame = await completion.Task.WaitAsync(TimeSpan.FromSeconds(10));pipeline.Stop();
if (frame.Hands.Count == 0 || pipeline.Warnings.Count != 0) throw new Exception("Combined YOLO/hand inference failed");
Console.WriteLine("PASS: Real YOLO and hand models process the same frame despite an outdated configured input size");
// Reproduce the original YOLO dimension exception after loading, to verify fault isolation.
var flags = System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic;
var yolo = typeof(DetectionPipeline).GetField("_yolo", flags)!.GetValue(pipeline)!;
typeof(SopHelper.Engine.Inference.YoloDetector).GetField("_inputSize", flags)!.SetValue(yolo, 641);
var warningCount = 0;pipeline.InferenceWarning += _ => warningCount++;
for (var i=0;i<2;i++)
{
completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
await pipeline.StartAsync();camera.Emit(101+i,image);
frame = await completion.Task.WaitAsync(TimeSpan.FromSeconds(10));pipeline.Stop();
if (frame.Hands.Count == 0) throw new Exception("YOLO failure prevented hand inference");
}
if (warningCount != 1 || !pipeline.Warnings.Single().StartsWith("YOLO 推理异常:")) throw new Exception("Inference warnings were lost or repeated per frame");
Console.WriteLine("PASS: A reproducible YOLO runtime failure preserves real hand detection and reports one visible warning");
}
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, Mat? source = null)
{
using var frame=new CameraFrame {FrameId=id,Timestamp=DateTime.Now,Bgr=source?.Clone() ?? 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();
}