diff --git a/src/SopHelper.Avalonia/Training/CameraFlowTest.cs b/src/SopHelper.Avalonia/Training/CameraFlowTest.cs index ed19ef0..c2fddf8 100644 --- a/src/SopHelper.Avalonia/Training/CameraFlowTest.cs +++ b/src/SopHelper.Avalonia/Training/CameraFlowTest.cs @@ -72,7 +72,6 @@ public sealed partial class CameraViewModel FlowTestDetails = test.Details; FlowTestStatus = "正在播放标准视频并检测流程(使用当前编辑配置)"; Playback.FrameProcessor = test.ProcessFrame; - Playback.WaitForFrameProcessingAsync = test.FinishPendingDecisionAsync; await Playback.PlayAsync(StandardVideoPath); if (IsTestingFlow) Status = "正在测试流程;点击“停止播放”可停止测试"; } @@ -98,7 +97,6 @@ public sealed partial class CameraViewModel private void EndFlowTest(string reason) { Playback.FrameProcessor = null; - Playback.WaitForFrameProcessingAsync = null; if (_flowTest is { } test) { FlowTestStatus = test.Finish(reason); diff --git a/src/SopHelper.Avalonia/Training/RecordedVideoPlayback.cs b/src/SopHelper.Avalonia/Training/RecordedVideoPlayback.cs index b0d3ec7..7fef933 100644 --- a/src/SopHelper.Avalonia/Training/RecordedVideoPlayback.cs +++ b/src/SopHelper.Avalonia/Training/RecordedVideoPlayback.cs @@ -21,7 +21,6 @@ public sealed class RecordedVideoPlayback : BindableBase private bool _seeking, _reportingProgress; private double? _pendingSeek; private Task _seekTask = Task.CompletedTask; - private CancellationTokenSource? _readCancellation; public BitmapSource? Frame { get => _frame; private set { var old = _frame; SetProperty(ref _frame, value); old?.Dispose(); } } public bool IsPlaying { get => _playing; private set => SetProperty(ref _playing, value); } @@ -41,8 +40,6 @@ public sealed class RecordedVideoPlayback : BindableBase public event Action? Failed; /// 在解码线程处理即将显示的原始帧;Mat 仅在回调期间有效。 public Action? FrameProcessor { get; set; } - /// 流程测试时先收取上一帧的 AI 结果,再读取下一帧。 - public Func? WaitForFrameProcessingAsync { get; set; } public RecordedVideoPlayback() { @@ -81,7 +78,6 @@ public sealed class RecordedVideoPlayback : BindableBase catch { await StopAsync(); throw; } } _startPosition = _position; - _readCancellation ??= new CancellationTokenSource(); _clock.Restart(); IsPlaying = true; _timer.Interval = TimeSpan.FromMilliseconds(Math.Clamp(1000 / _fps, 15, 200)); _timer.Start(); NotifyTime(); @@ -96,12 +92,10 @@ public sealed class RecordedVideoPlayback : BindableBase public async Task StopAsync() { Pause(); _generation++; - _readCancellation?.Cancel(); _pendingSeek = null; await _seekTask; _pendingSeek = null; await WaitForReadAsync(); - _readCancellation?.Dispose(); _readCancellation = null; _readTask = null; _reading = false; var capture = _capture; _capture = null; if (capture is not null) await Task.Run(capture.Dispose); @@ -190,16 +184,9 @@ public sealed class RecordedVideoPlayback : BindableBase _reading = true; var capture = _capture; var generation = _generation; - // 普通观看追赶实时时钟;流程测试逐帧前进,模型耗时不能丢掉中间动作。 - var target = FrameProcessor is null ? (long)Math.Floor((_startPosition + _clock.Elapsed.TotalSeconds) * _fps) : (long)capture.PosFrames; - var waitForProcessing = WaitForFrameProcessingAsync; - var token = _readCancellation?.Token ?? CancellationToken.None; - var read = _readTask = Task.Run(async () => - { - if (waitForProcessing is not null) await waitForProcessing(token); - token.ThrowIfCancellationRequested(); - return Decode(capture, target); - }); + // 测试与现场一样按实时时钟推进,AI 在后台判定,不阻塞后续画面。 + var target = (long)Math.Floor((_startPosition + _clock.Elapsed.TotalSeconds) * _fps); + var read = _readTask = Task.Run(() => Decode(capture, target)); try { var decoded = await read; diff --git a/tests/VideoFlowTest.Smoke/Program.cs b/tests/VideoFlowTest.Smoke/Program.cs index d04f1c7..f0aae5e 100644 --- a/tests/VideoFlowTest.Smoke/Program.cs +++ b/tests/VideoFlowTest.Smoke/Program.cs @@ -101,7 +101,7 @@ internal static class Program using var image = new Mat(48, 64, MatType.CV_8UC3, new Scalar(30, 60, 90)); writer.Write(image); } } - CheckSequentialPlayback(model.StandardVideoPath); + CheckRealtimePlayback(model.StandardVideoPath); // Unsupported condition exercises playback and incomplete results without hardware/models/API. config.Sop.Steps = [new StepDef { Id = 1, Name = "待配置步骤", Description = "验证当前编辑配置", Detection = new() { Method = "unsupported" } }]; model.FlowTestConfigProvider = () => config; @@ -130,26 +130,45 @@ internal static class Program window.Close(); vm.OnDialogClosed(); } - private static void CheckSequentialPlayback(string path) + private static void CheckRealtimePlayback(string path) { var playback = new RecordedVideoPlayback(); var ids = new System.Collections.Concurrent.ConcurrentQueue(); - var acknowledgement = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - playback.FrameProcessor = (_, id, _) => { Thread.Sleep(140); ids.Enqueue(id); }; - playback.WaitForFrameProcessingAsync = token => ids.IsEmpty ? Task.CompletedTask : acknowledgement.Task.WaitAsync(token); + var config = SopConfigLoader.Parse(""" + sop: + name: 连续播放 + regions: { work: { x1: 0, y1: 0, x2: 64, y2: 48 } } + steps: + - id: 1 + name: 装配 + description: 盒内可见零件 + detection: { method: hand_in_region, region: work, stable_frames: 1 } + ai_confirmation: { timeout_seconds: 5 } + """); + var fake = new FakeDecision(); + using var test = new SopVideoFlowTest(config, fake); test.Start(); + playback.FrameProcessor = (image, id, _) => + { + ids.Enqueue(id); + test.ProcessResult(new FrameResult { FrameId = id, Timestamp = DateTime.Now, Size = (64, 48), Hands = [new Hand { Rect = new(20, 20, 10, 10) }] }, image); + }; Pump(playback.PlayAsync(path)); using (var wait = new CancellationTokenSource(350)) Dispatcher.UIThread.MainLoop(wait.Token); - Check(ids.Count == 1 && playback.IsPlaying, "Playback holds the trigger frame while its AI decision is pending"); - acknowledgement.SetResult(); + Check(fake.Request is not null && !fake.Result.Task.IsCompleted && ids.Count > 1 && playback.IsPlaying && playback.Progress > 0, + "Video and frame detection continue while AI is still pending"); Until(() => playback.IsAtEnd); - Check(ids.SequenceEqual(Enumerable.Range(0, 10).Select(i => (long)i)), "Slow flow detection processes every video frame in order without clock catch-up or dropped actions"); + Check(!fake.Result.Task.IsCompleted && !test.IsCompleted && ids.Last() > ids.First(), "Video reaches EOF without waiting for AI or reporting premature success"); + fake.Result.SetResult(new(true, .99, "盒内可见零件")); + Pump(test.FinishPendingDecisionAsync()); + Check(test.IsCompleted, "Background AI result can still complete the flow after video EOF"); Pump(playback.StopAsync()); ids.Clear(); - acknowledgement = new(TaskCreationOptions.RunContinuationsAsynchronously); + playback.FrameProcessor = (_, id, _) => { Thread.Sleep(140); ids.Enqueue(id); }; Pump(playback.PlayAsync(path)); - using (var wait = new CancellationTokenSource(200)) Dispatcher.UIThread.MainLoop(wait.Token); + Until(() => playback.IsAtEnd); + Check(ids.Count < 10 && ids.SequenceEqual(ids.OrderBy(id => id)), "Slow inference catches up with the video clock instead of slowing playback to process every frame"); Pump(playback.StopAsync()); - Check(!playback.IsLoaded && ids.Count == 1, "Stop cancels a pending AI wait without reading later frames"); + Check(!playback.IsLoaded, "Stopping realtime playback releases the video reader"); } private static void Until(Func ready)