aisop/tests/Pipeline.Smoke/Program.cs

133 lines
7.1 KiB
C#

using System.Collections.Concurrent;
using OpenCvSharp;
using SopHelper.Engine.Camera;
using SopHelper.Engine.Pipeline;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Common;
// The first step must not enable hands merely because a later step uses them.
var engine = new SopEngine { VisionDecisionClient = new ImmediateDecision() };
var config = new SopConfig();
config.Sop.Settings.AutoResetOnComplete = false;
config.Sop.Regions["work"] = new RegionDef { X1=0, Y1=0, X2=100, Y2=100 };
config.Sop.Steps = [
new StepDef { Id=1, Detection=new StepCondition { Method=ConditionMethod.TimeElapsed, DurationMs=1, StableFrames=1 } },
new StepDef { Id=2, Detection=new StepCondition { Method=ConditionMethod.HandInRegion, Region="work", StableFrames=1 } },
new StepDef { Id=3, Detection=new StepCondition { Method=ConditionMethod.TimeElapsed, DurationMs=1, StableFrames=1 } }
];
foreach(var step in config.Sop.Steps)step.Description="测试步骤完成";
engine.Load(config);
if(engine.RequiresHandDetection)throw new Exception("Idle engine enabled hands");
engine.Start();
if(engine.RequiresHandDetection)throw new Exception("Future hand step enabled hands early");
var partFrame = new FrameResult { Detections=[new Detection { Label="part", Confidence=1 }] };
await Drive(partFrame);
if(!engine.RequiresHandDetection)throw new Exception("Entering hand step did not enable hands");
engine.TogglePause();
if(engine.RequiresHandDetection)throw new Exception("Paused step enabled hands");
engine.TogglePause();
if(!engine.RequiresHandDetection)throw new Exception("Resuming hand step did not enable hands");
await Drive(new FrameResult { Hands=[new Hand { Rect=new DetRect(10,10,20,20) }] });
if(engine.RequiresHandDetection)throw new Exception("Leaving hand step did not disable hands");
await Drive(partFrame);
if(engine.State!=EngineState.Completed||engine.RequiresHandDetection)throw new Exception("Completed engine enabled hands");
engine.Reset();
if(engine.RequiresHandDetection)throw new Exception("Reset kept previous hand requirement");
foreach(var method in new[]{ConditionMethod.HandInRegion,ConditionMethod.HandMove,ConditionMethod.HandLeaveRegion})
if(!ConditionMethod.RequiresHandDetection(method.ToUpperInvariant()))throw new Exception("Hand method not recognized: "+method);
Console.WriteLine("PASS: Hand inference follows only the current running step across transitions, pause, completion and reset");
async Task Drive(FrameResult frame)
{
var previous=engine.CurrentStep?.Id;
for(var i=0;i<100 && engine.CurrentStep?.Id==previous;i++) {engine.ProcessFrame(frame,()=>[1]);await Task.Delay(10);}
}
using var camera = new TestCamera();
using var pipeline = new DetectionPipeline(camera);
var results = new ConcurrentQueue<long>();
var imageResults = new ConcurrentQueue<long>();
pipeline.ResultFrameArrived += (result, image) =>
{
if (image.Empty() || result.Size != (image.Width, image.Height))
throw new Exception("Result image is invalid or does not match the inference dimensions");
imageResults.Enqueue(result.FrameId);
};
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");
if(!imageResults.SequenceEqual(results))throw new Exception("Result images do not match the processed frames");
Console.WriteLine("PASS: Each result carries its still-valid corresponding image");
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");
// 视频模式应排除相机帧,且解码方可以在提交后立即释放原图。
pipeline.StartVideoInput();
if (camera.IsGrabbing) throw new Exception("Video input started camera capture");
camera.Emit(15);
using (var video = new Mat(24, 40, MatType.CV_8UC3, Scalar.Black))
{
pipeline.SubmitVideoFrame(video, 16);
pipeline.SubmitVideoFrame(video, 17);
}
for (var i = 0; i < 100 && imageResults.Count < 5; i++) await Task.Delay(10);
pipeline.StopVideoInput();
if (results.Count != 5 || results.Last() != 17 || !imageResults.SequenceEqual(results))
throw new Exception("Video input did not isolate sources or preserve stride and frame ownership");
Console.WriteLine("PASS: Video input isolates sources and uses the regular inference 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, 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();
}
internal sealed class ImmediateDecision : IVisionDecisionClient
{
public Task<VisionDecisionResult> DecideAsync(VisionDecisionRequest request,CancellationToken token)=>Task.FromResult(new VisionDecisionResult(true,1,"测试AI确认"));
}