aisop/tests/Training.CameraSmoke/Program.cs

215 lines
12 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using OpenCvSharp;
using SopHelper.Training;
using SopHelper.Engine.Camera;
internal static class Program
{
[STAThread]
public static int Main(string[] args)
{
var root = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../../workspace/camera-smoke-" + Guid.NewGuid().ToString("N")));
Directory.CreateDirectory(root);
var app = new SopHelper.App(); app.InitializeComponent();
app.ShutdownMode = ShutdownMode.OnExplicitShutdown;
SynchronizationContext.SetSynchronizationContext(new DispatcherSynchronizationContext(app.Dispatcher));
try
{
TestRecorder(root);
TestViewModel(root);
TestCloseWhileConnecting(root);
TestStalledCamera(root);
TestSopStopReleasesCamera();
Console.WriteLine("PASS: recording and camera lifecycle checks; artifacts: " + root);
return 0;
}
catch (Exception e) { Console.Error.WriteLine(e); return 1; }
}
private static void Require(bool condition, string error) { if (!condition) throw new Exception(error); }
private static void TestSopStopReleasesCamera()
{
using var camera = new FakeCamera();
using var pipeline = new SopHelper.Engine.Pipeline.DetectionPipeline(camera);
var sop = new SopHelper.VVMs.SopPage.SopPageViewModel(camera, pipeline,
new SopHelper.Engine.Sop.SopEngine(), null!);
try
{
for (var cycle = 0; cycle < 2; cycle++)
{
camera.ConnectAsync(new CameraInfo { Name = "Test" }).GetAwaiter().GetResult();
PumpUntil(() => sop.IsConnected);
sop.IsRunning = true;
sop.StartStopCommand.Execute();
PumpUntil(() => sop.CanSelectCamera);
Require(!camera.IsConnected && !camera.IsGrabbing && !sop.IsConnected && !sop.IsRunning,
"SOP stop retained camera ownership and would block recording");
}
Console.WriteLine("PASS: repeated SOP stop releases device and clears recording entry blockers");
}
finally { sop.Destroy(); }
}
private static void PumpUntil(Func<bool> ready, int timeout = 5000)
{
var watch = Stopwatch.StartNew();
while (!ready())
{
if (watch.ElapsedMilliseconds > timeout) throw new TimeoutException("Dispatcher test timed out");
Application.Current.Dispatcher.Invoke(() => { }, DispatcherPriority.ApplicationIdle);
Thread.Sleep(10);
}
Application.Current.Dispatcher.Invoke(() => { }, DispatcherPriority.ApplicationIdle);
}
private static void TestRecorder(string root)
{
using var recorder = new VideoRecorder();
using var frame = new Mat(120, 160, MatType.CV_8UC3, new Scalar(30,50,80));
var watch = Stopwatch.StartNew();
var path = recorder.Start(Path.Combine(root, "中文录像目录"), frame);
watch.Restart();
for (var i = 0; i < 10; i++)
{
Thread.Sleep(100); frame.SetTo(new Scalar(30+i*10,50,80)); recorder.Write(frame);
}
var result = recorder.Stop()!;
Require(!recorder.IsRecording && recorder.Stop() == null, "Stop must be idempotent");
Require(Math.Abs(result.Duration.TotalSeconds - watch.Elapsed.TotalSeconds) < 0.2, "Recording duration differs from wall clock");
using (var capture = new VideoCapture(path))
using (var decoded = new Mat())
{
Require(capture.IsOpened() && capture.Read(decoded), "AVI could not be decoded");
Require(decoded.Width == 160 && decoded.Height == 120, "Video resolution changed");
Require(Cv2.Mean(decoded).Val0 > 20, "Video pixels missing");
Require(Math.Abs(capture.Get(VideoCaptureProperties.Fps) - 30) < 0.01, "Unexpected recording FPS");
Require((long)capture.Get(VideoCaptureProperties.FrameCount) == result.Frames, "AVI frame count mismatch");
}
var second = recorder.Start(root, frame); recorder.Stop();
Require(second != path && File.Exists(path) && File.Exists(second), "New recording overwrote the previous file");
recorder.Start(root, frame);
using var changed = new Mat(80, 160, MatType.CV_8UC3, Scalar.Black);
try { recorder.Write(changed); throw new Exception("Resolution change accepted"); }
catch (IOException) { }
Require(!recorder.IsRecording, "Failed writer was not finalized");
using var odd = new Mat(121,161,MatType.CV_8UC3,Scalar.Black);
try { recorder.Start(root, odd); throw new Exception("Odd size accepted"); }
catch (ArgumentException) { }
var file = Path.Combine(root, "not-a-directory"); File.WriteAllText(file, "test");
try { recorder.Start(file, frame); throw new Exception("File accepted as directory"); }
catch (IOException) { }
Require(!recorder.IsRecording, "Failed start changed recording state");
Console.WriteLine($"PASS: real MJPEG encode/decode, Chinese directory, {result.Frames} frames / {result.Duration.TotalSeconds:F2}s, pacing, repeated recordings, failure cleanup");
}
private static void TestViewModel(string root)
{
var fake = new FakeCamera();
var model = new CameraViewModel(fake, root);
Require(!model.RecordCommand.CanExecute(), "Recording enabled without camera");
model.RefreshCommand.Execute(); PumpUntil(() => !model.IsBusy);
Require(model.Cameras.Count == 1 && model.SelectedCamera != null, "Camera list failed");
model.PreviewCommand.Execute(); PumpUntil(() => !model.IsBusy && model.Preview != null);
Require(model.IsPreviewing, "Live preview failed");
model.SaveDirectory = Path.Combine(root,"自选保存位置");
model.RecordCommand.Execute(); PumpUntil(() => !model.IsBusy && model.IsRecording);
Require(!model.CanChooseCamera && !model.CanChangeDirectory && !model.RefreshCommand.CanExecute(), "Controls should be locked while recording");
Thread.Sleep(300);
model.RecordCommand.Execute(); PumpUntil(() => !model.IsBusy && !model.IsRecording);
Require(model.IsPreviewing && model.CanChangeDirectory, "Stop recording should preserve preview and unlock the directory");
var firstRecording = model.LastRecording;
model.RecordCommand.Execute(); PumpUntil(() => !model.IsBusy && model.IsRecording);
Require(model.LastRecording != firstRecording, "Second recording should use a new filename");
Thread.Sleep(300);
var window = new CameraWindow(model);
Render(window, Path.Combine(root, "camera-preview.png"));
var shutdown = model.ShutdownAsync(); PumpUntil(() => shutdown.IsCompleted); shutdown.GetAwaiter().GetResult();
Require(fake.Disposed && !model.IsRecording && !model.IsPreviewing, "Closing did not release camera/recording");
using (var capture = new VideoCapture(model.LastRecording)) Require(capture.IsOpened() && capture.Get(VideoCaptureProperties.FrameCount) > 0, "Close did not finalize AVI");
var closed = false; window.Closed += (_, _) => closed = true;
window.Close(); PumpUntil(() => closed);
var secondFake = new FakeCamera();
var reopened = new CameraViewModel(secondFake, root);
Require(reopened.SaveDirectory == model.SaveDirectory, "Selected recording directory not persisted");
var task = reopened.ShutdownAsync(); PumpUntil(() => task.IsCompleted); task.GetAwaiter().GetResult();
Console.WriteLine("PASS: WPF live preview, directory persistence, record state, closing while recording, preview rendering");
}
private static void TestCloseWhileConnecting(string root)
{
var fake = new FakeCamera { ConnectDelay = 200 };
var model = new CameraViewModel(fake, root) { SelectedCamera = new CameraInfo { Name = "Test" } };
model.PreviewCommand.Execute();
var close = model.ShutdownAsync(); PumpUntil(() => close.IsCompleted); close.GetAwaiter().GetResult();
Require(fake.Disposed && fake.Starts == 0 && !fake.IsGrabbing, "Pending connect reopened camera after close");
Console.WriteLine("PASS: close waits for pending connection and prevents late acquisition");
}
private static void TestStalledCamera(string root)
{
var fake = new FakeCamera();
var model = new CameraViewModel(fake, root) { SelectedCamera = new CameraInfo { Name = "Test" } };
model.PreviewCommand.Execute(); PumpUntil(() => !model.IsBusy && model.Preview != null);
model.RecordCommand.Execute(); PumpUntil(() => model.IsRecording && !model.IsBusy);
fake.PauseFrames = true;
PumpUntil(() => !model.IsRecording, 4000);
Require(!model.RecordCommand.CanExecute(), "Recording enabled on stale preview");
var close = model.ShutdownAsync(); PumpUntil(() => close.IsCompleted); close.GetAwaiter().GetResult();
using var capture = new VideoCapture(model.LastRecording);
Require(capture.IsOpened(), "Stall did not finalize recording");
Console.WriteLine("PASS: stalled camera automatically stops and finalizes recording, stale preview cannot start a new recording");
}
private static void Render(CameraWindow window, string path)
{
var content = (FrameworkElement)window.Content; window.Content = null;
content.DataContext = window.Model; content.Margin = new Thickness(0);
content.Width = 1044; content.Height = 744;
content.Measure(new System.Windows.Size(1044,744)); content.Arrange(new System.Windows.Rect(0,0,1044,744));
content.Dispatcher.Invoke(() => { }, DispatcherPriority.ApplicationIdle); content.UpdateLayout();
var bitmap = new RenderTargetBitmap(1044,744,96,96,PixelFormats.Pbgra32); bitmap.Render(content);
var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap));
using var stream = File.Create(path); encoder.Save(stream);
}
}
internal sealed class FakeCamera : ICameraService
{
private CancellationTokenSource? _stop;
private Task? _loop;
public bool IsConnected { get; private set; }
public bool IsGrabbing { get; private set; }
public bool Disposed { get; private set; }
public int ConnectDelay { get; init; }
public int Starts { get; private set; }
public volatile bool PauseFrames;
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 = "模拟 UVC 相机 · 160×120" } });
public async Task<bool> ConnectAsync(CameraInfo info)
{
if (ConnectDelay > 0) await Task.Delay(ConnectDelay);
IsConnected = true; ConnectionChanged?.Invoke(true); return true;
}
public Task<bool> StartAsync()
{
Starts++; IsGrabbing = true; _stop = new CancellationTokenSource();
var token = _stop.Token;
_loop = Task.Run(() =>
{
long index = 0;
while (!token.IsCancellationRequested)
{
if (PauseFrames) { Thread.Sleep(33); continue; }
var image = new Mat(120,160,MatType.CV_8UC3,new Scalar(40,60,80));
Cv2.Rectangle(image, new OpenCvSharp.Rect(30,25,90,60), new Scalar(170,190,210), -1);
using var frame = new CameraFrame { Bgr = image, FrameId = index++, Timestamp = DateTime.Now };
FrameArrived?.Invoke(frame); Thread.Sleep(33);
}
});
return Task.FromResult(true);
}
public void Stop() { _stop?.Cancel(); _loop?.GetAwaiter().GetResult(); _stop?.Dispose(); _stop = null; _loop = null; IsGrabbing = false; }
public void Disconnect() { Stop(); IsConnected = false; ConnectionChanged?.Invoke(false); }
public void Dispose() { Disconnect(); Disposed = true; }
}