步骤编辑支持半速播放和逐帧定位并调整关键帧按钮顺序

This commit is contained in:
tfarcraw 2026-11-21 11:05:56 +08:00
parent e102ac9597
commit 25341c7fd2
5 changed files with 110 additions and 15 deletions

View File

@ -56,6 +56,8 @@ public sealed partial class CameraViewModel
if (IsRecording || IsTestingFlow) return;
await Playback.StopAsync();
EndFlowTest("开始新的测试");
// 回测按现场实时时钟推进,不沿用步骤编辑的半速设置。
Playback.HalfSpeed = false;
FlowTestDetails = "";
FlowTestDecisionImage = null;
FlowTestDecisionLabel = "";

View File

@ -75,6 +75,9 @@ public sealed partial class CameraViewModel : BindableBase
public DelegateCommand PlayVideoCommand { get; }
public DelegateCommand PauseVideoCommand { get; }
public DelegateCommand ToggleVideoPlaybackCommand { get; }
/// <summary>步骤编辑逐帧定位,执行后保持暂停以便获取关键帧。</summary>
public DelegateCommand PreviousVideoFrameCommand { get; }
public DelegateCommand NextVideoFrameCommand { get; }
public DelegateCommand StopVideoCommand { get; }
public DelegateCommand ImportVideoCommand { get; }
public event Action<string>? RecordingLimitReached;
@ -110,11 +113,14 @@ public sealed partial class CameraViewModel : BindableBase
ImportVideoCommand = Command(ImportVideoAsync, () => _sopStandard && !IsBusy && !_closing && !IsTestingFlow && !IsRecording);
TestFlowCommand = Command(StartFlowTestAsync, () => _sopStandard && !IsBusy && !_closing && !IsTestingFlow && !IsRecording && HasStandardVideo && FlowTestConfigProvider is not null);
StopVideoCommand = Command(async () => { await Playback.StopAsync(); EndFlowTest("测试已停止"); Status = "视频播放已停止"; }, () => !IsBusy && !_closing && Playback.IsLoaded);
PreviousVideoFrameCommand = Command(() => Playback.StepFrameAsync(-1), () => CanSeekVideo && !_closing && !Playback.IsSeeking);
NextVideoFrameCommand = Command(() => Playback.StepFrameAsync(1), () => CanSeekVideo && !_closing && !Playback.IsSeeking);
Playback.PropertyChanged += (_, e) =>
{
if (e.PropertyName is nameof(Playback.Frame) or nameof(Playback.IsLoaded)) RaisePropertyChanged(nameof(DisplayImage));
if (e.PropertyName is nameof(Playback.IsPlaying) or nameof(Playback.IsLoaded) or nameof(Playback.IsAtEnd))
{ RaisePropertyChanged(nameof(PlayVideoButtonText)); UpdateCommands(); }
if (e.PropertyName == nameof(Playback.IsSeeking)) UpdateCommands();
if (e.PropertyName == nameof(Playback.IsLoaded))
{
RaisePropertyChanged(nameof(CanSeekVideo)); RaisePropertyChanged(nameof(ShowFlowTestOverlay));

View File

@ -22,7 +22,9 @@ public sealed class RecordedVideoPlayback : BindableBase
private int _generation;
private string _path = "";
private bool _seeking, _reportingProgress;
private double? _pendingSeek;
private (long Frame, bool AtEnd)? _pendingSeek;
private long _frameCount;
private bool _halfSpeed;
private Task _seekTask = Task.CompletedTask;
public BitmapSource? Frame { get => _frame; private set { var old = _frame; SetProperty(ref _frame, value); old?.Dispose(); } }
@ -40,6 +42,19 @@ public sealed class RecordedVideoPlayback : BindableBase
_ = SeekAsync(value);
}
}
/// <summary>普通播放可切换半速;切换时重设时钟基准,避免播放位置突跳。</summary>
public bool HalfSpeed
{
get => _halfSpeed;
set
{
if (_halfSpeed == value || FrameProcessor is not null || FrameAnalyzer is not null) return;
_startPosition = _position;
_clock.Restart();
SetProperty(ref _halfSpeed, value);
}
}
public string TimeText => $"{TimeSpan.FromSeconds(_position):mm\\:ss} / {TimeSpan.FromSeconds(_duration):mm\\:ss}";
public event Action<string>? Failed;
/// <summary>在解码线程处理即将显示的原始帧;Mat 仅在回调期间有效。</summary>
@ -80,7 +95,8 @@ public sealed class RecordedVideoPlayback : BindableBase
{
_fps = capture.Fps;
if (!double.IsFinite(_fps) || _fps <= 0) _fps = 30;
_duration = capture.FrameCount / _fps;
_frameCount = capture.FrameCount;
_duration = _frameCount / _fps;
if (!double.IsFinite(_duration) || _duration <= 0) throw new IOException("视频中没有可播放画面");
_position = 0;
IsLoaded = true;
@ -118,7 +134,24 @@ public sealed class RecordedVideoPlayback : BindableBase
public Task SeekAsync(double percent)
{
if (!IsLoaded || FrameProcessor is not null || FrameAnalyzer is not null || !double.IsFinite(percent)) return Task.CompletedTask;
_pendingSeek = Math.Clamp(percent, 0, 100);
percent = Math.Clamp(percent, 0, 100);
return SeekFrameAsync((long)Math.Floor(percent / 100 * _frameCount), percent == 100);
}
/// <summary>按当前显示帧前后移动一帧并暂停;首尾钳位,流程分析期间禁止切帧。</summary>
public async Task StepFrameAsync(int direction)
{
if (!IsLoaded || FrameProcessor is not null || FrameAnalyzer is not null || direction == 0) return;
Pause();
await _seekTask;
if (!IsLoaded) return;
var frame = (long)Math.Round(DisplayedSeconds * _fps);
await SeekFrameAsync(frame + Math.Sign(direction), false);
}
private Task SeekFrameAsync(long frame, bool atEnd)
{
_pendingSeek = (Math.Clamp(frame, 0, Math.Max(0, _frameCount - 1)), atEnd);
if (!_seeking) _seekTask = SeekPendingAsync();
return _seekTask;
}
@ -132,7 +165,7 @@ public sealed class RecordedVideoPlayback : BindableBase
{
await WaitForReadAsync();
_readTask = null; _reading = false;
while (_pendingSeek is { } percent && generation == _generation)
while (_pendingSeek is { } seek && generation == _generation)
{
_pendingSeek = null;
var old = _capture; _capture = null;
@ -144,7 +177,7 @@ public sealed class RecordedVideoPlayback : BindableBase
try
{
if (!capture.Open(_path)) throw new IOException("无法打开录制的视频");
var target = Math.Clamp((long)Math.Floor(percent / 100 * capture.FrameCount), 0, Math.Max(0, capture.FrameCount - 1));
var target = seek.Frame;
if (target > 0) capture.Set(VideoCaptureProperties.PosFrames, target);
var decoded = Decode(capture, (long)target);
if (decoded.Image is null) throw new IOException("无法读取指定位置的视频画面");
@ -162,8 +195,8 @@ public sealed class RecordedVideoPlayback : BindableBase
Frame = opened.Frame.Image;
DisplayedSeconds = opened.Frame.Seconds;
Analysis = opened.Frame.Analysis;
_position = percent == 100 ? _duration : opened.Frame.Seconds;
IsAtEnd = percent == 100;
_position = seek.AtEnd ? _duration : opened.Frame.Seconds;
IsAtEnd = seek.AtEnd;
if (IsAtEnd) Pause();
NotifyTime();
}
@ -201,7 +234,10 @@ public sealed class RecordedVideoPlayback : BindableBase
var capture = _capture;
var generation = _generation;
// 测试与现场一样按实时时钟推进,AI 在后台判定,不阻塞后续画面。
var target = (long)Math.Floor((_startPosition + _clock.Elapsed.TotalSeconds) * _fps);
var rate = HalfSpeed && FrameProcessor is null && FrameAnalyzer is null ? 0.5 : 1;
var target = (long)Math.Floor((_startPosition + _clock.Elapsed.TotalSeconds * rate) * _fps);
// 半速及高频定时器下,同一目标帧尚未到期时不提前读取下一帧。
if (capture.PosFrames > target) { _reading = false; return; }
var read = _readTask = Task.Run(() => Decode(capture, target));
try
{

View File

@ -290,8 +290,12 @@
<StackPanel Grid.Row="2" Spacing="6" Margin="0,8,0,8">
<WrapPanel>
<Button x:Name="StepPlayPauseButton" Content="{Binding SopRecording.PlayVideoButtonText}" Command="{Binding SopRecording.ToggleVideoPlaybackCommand}" Margin="0,0,8,6" />
<Button Content="停止" Command="{Binding SopRecording.StopVideoCommand}" Margin="0,0,8,6" />
<Button Content="获取关键帧" Command="{Binding CaptureStepKeyFrameCommand}" Margin="0,0,0,6" />
<!-- 逐帧定位后保持暂停,获取关键帧紧邻停止之前。 -->
<Button Content="上一帧" Command="{Binding SopRecording.PreviousVideoFrameCommand}" Margin="0,0,8,6" />
<Button Content="下一帧" Command="{Binding SopRecording.NextVideoFrameCommand}" Margin="0,0,8,6" />
<CheckBox x:Name="StepHalfSpeed" Content="0.5倍速" IsChecked="{Binding SopRecording.Playback.HalfSpeed, Mode=TwoWay}" IsEnabled="{Binding !SopRecording.IsTestingFlow}" Margin="0,0,8,6" />
<Button Content="获取关键帧" Command="{Binding CaptureStepKeyFrameCommand}" Margin="0,0,8,6" />
<Button Content="停止" Command="{Binding SopRecording.StopVideoCommand}" Margin="0,0,0,6" />
</WrapPanel>
<Grid ColumnDefinitions="*,Auto">
<Slider Minimum="0" Maximum="100" Value="{Binding SopRecording.Playback.Progress, Mode=TwoWay}" IsEnabled="{Binding SopRecording.CanSeekVideo}" ToolTip.Tip="拖动跳转视频位置" />

View File

@ -1,4 +1,4 @@
using Avalonia;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless;
using Avalonia.Markup.Xaml.Styling;
@ -161,7 +161,7 @@ internal static class Program
var runtime = runtimeStore.Read() ?? new();
var originalTimeout = runtime.DjevTimeoutMs;
runtime.DjevTimeoutMs = 1000; runtimeStore.Save(runtime);
try { CheckStridedHandPlayback(model.StandardVideoPath); CheckRealtimePlayback(model.StandardVideoPath); CheckContinuousPlayback(model.StandardVideoPath); }
try { CheckStridedHandPlayback(model.StandardVideoPath); CheckRealtimePlayback(model.StandardVideoPath); CheckContinuousPlayback(model.StandardVideoPath); CheckEditorPlayback(model.StandardVideoPath); }
finally { runtime.DjevTimeoutMs = originalTimeout; runtimeStore.Save(runtime); }
vm.Recipe.AddStepCommand.Execute();
var selected = vm.Recipe.SelectedStep!;
@ -204,6 +204,8 @@ internal static class Program
Check(regionNavigation.TranslatePoint(default, window)!.Value.Y >= stepVideo.TranslatePoint(default, window)!.Value.Y + stepVideo.Bounds.Height
&& regionParameters.TranslatePoint(default, window)!.Value.Y >= stepVideo.TranslatePoint(default, window)!.Value.Y + stepVideo.Bounds.Height,
"Region navigation and parameters sit below the step video player");
// 前面的保存检查已停止播放器;先加载并暂停,确保界面绑定与逐帧命令使用真实视频画面。
Pump(model.Playback.PlayAsync(model.StandardVideoPath)); model.Playback.Pause();
Pump(model.Playback.SeekAsync(50)); window.UpdateLayout(); Dispatcher.UIThread.RunJobs();
var regionCanvas = view.FindControl<RegionCanvas>("StepVideoRegions")!;
Check(ReferenceEquals(regionCanvas.Image, model.Playback.Frame) && ReferenceEquals(regionCanvas.Regions, vm.Recipe.Regions),
@ -212,9 +214,21 @@ internal static class Program
Check(ReferenceEquals(regionCanvas.SelectedRegion, vm.Recipe.SelectedRegion)
&& ReferenceEquals(regionNavigation.SelectedItem, vm.Recipe.SelectedRegion),
"Region navigation, parameters and canvas share the selected editable region");
var playbackButtons = ((Panel)view.FindControl<Button>("StepPlayPauseButton")!.Parent!).Children.OfType<Button>().ToArray();
Check(playbackButtons.Length == 3 && playbackButtons[1].Content?.ToString() == "停止" && playbackButtons[2].Content?.ToString() == "获取关键帧",
"Combined play/pause, stop and capture-keyframe buttons appear in order");
var playbackButtons = ((Panel)view.FindControl<Button>("StepPlayPauseButton")!.Parent!).Children.OfType<Button>().Where(button => button is not CheckBox).ToArray();
Check(playbackButtons.Length == 5 && playbackButtons[1].Content?.ToString() == "上一帧"
&& playbackButtons[2].Content?.ToString() == "下一帧"
&& playbackButtons[3].Content?.ToString() == "获取关键帧" && playbackButtons[4].Content?.ToString() == "停止",
"步骤播放控件包含逐帧按钮,获取关键帧位于停止之前");
var halfSpeed = view.FindControl<CheckBox>("StepHalfSpeed")!;
halfSpeed.IsChecked = true;
Check(model.Playback.HalfSpeed, "步骤半速控件绑定实际播放速度");
halfSpeed.IsChecked = false;
model.NextVideoFrameCommand.Execute(); Until(() => !model.IsBusy);
Check(Math.Abs(model.Playback.DisplayedSeconds - .6) < .001 && !model.Playback.IsPlaying,
"步骤下一帧命令定位并暂停");
model.PreviousVideoFrameCommand.Execute(); Until(() => !model.IsBusy);
Check(Math.Abs(model.Playback.DisplayedSeconds - .5) < .001,
"步骤上一帧命令精确返回原帧");
Pump(model.Playback.StopAsync());
vm.Recipe.SelectedStep = selected;
Dispatcher.UIThread.RunJobs(); window.UpdateLayout();
@ -394,6 +408,39 @@ internal static class Program
}
}
/// <summary>用已知帧率视频验证逐帧边界、播放中暂停定位和半速实际耗时。</summary>
private static void CheckEditorPlayback(string path)
{
var playback = new RecordedVideoPlayback();
try
{
Pump(playback.PlayAsync(path));
Pump(playback.StepFrameAsync(1));
Check(!playback.IsPlaying && Math.Abs(playback.DisplayedSeconds - .1) < .001,
"播放中下一帧暂停且精确前进一帧");
Pump(playback.StepFrameAsync(-1));
Pump(playback.StepFrameAsync(-1));
Check(playback.DisplayedSeconds == 0, "上一帧在视频起点钳位");
Pump(playback.SeekAsync(100));
Pump(playback.StepFrameAsync(1));
Check(Math.Abs(playback.DisplayedSeconds - .9) < .001, "下一帧在视频终点钳位");
Pump(playback.StepFrameAsync(-1));
Check(Math.Abs(playback.DisplayedSeconds - .8) < .001, "视频尾部可以返回上一帧");
Pump(playback.StopAsync());
playback.HalfSpeed = true;
var elapsed = System.Diagnostics.Stopwatch.StartNew();
Pump(playback.PlayAsync(path));
Until(() => playback.IsAtEnd);
Check(elapsed.Elapsed.TotalSeconds >= 1.8, "0.5倍速按实时时钟播放,1秒视频至少播放1.8秒");
playback.HalfSpeed = false;
Pump(playback.PlayAsync(path));
Pump(playback.SeekAsync(50));
playback.HalfSpeed = true;
Check(playback.DisplayedSeconds >= .5 && playback.IsPlaying, "播放中切换半速保持当前位置与播放状态");
}
finally { Pump(playback.StopAsync()); }
}
private static void CheckRealtimePlayback(string path)
{
var playback = new RecordedVideoPlayback();