步骤页增加视频播放控件和选中步骤关键帧保存

This commit is contained in:
tfarcraw 2026-11-19 13:07:30 +08:00
parent 7157cc7777
commit f561e91ce6
8 changed files with 90 additions and 6 deletions

View File

@ -1,4 +1,4 @@
using Avalonia;
using Avalonia;
using Avalonia.Media;
using Avalonia.Platform;
using OpenCvSharp;
@ -25,6 +25,7 @@ public class BitmapSource : IImage, IDisposable
return new BitmapSource { Native = new NativeBitmap(stream) };
}
public void Freeze() { /* Avalonia Bitmap snapshots are immutable already. */ }
public byte[] ToPngBytes() { using var stream = new MemoryStream(); Native!.Save(stream); return stream.ToArray(); }
public void Save(string path) => Native!.Save(path);
public void Dispose() { Native?.Dispose(); Native=null; GC.SuppressFinalize(this); }
public static BitmapSource Create(int width,int height,double dpiX,double dpiY,PixelFormat format,object? palette,

View File

@ -1,4 +1,4 @@
using System.Diagnostics;
using System.Diagnostics;
using Avalonia.Threading;
using OpenCvSharp;
using Prism.Mvvm;
@ -28,6 +28,7 @@ public sealed class RecordedVideoPlayback : BindableBase
public bool IsLoaded { get => _loaded; private set => SetProperty(ref _loaded, value); }
public bool IsAtEnd { get => _atEnd; private set => SetProperty(ref _atEnd, value); }
public bool IsSeeking => _seeking;
public double DisplayedSeconds { get; private set; }
public double Progress
{
get => _duration > 0 ? Math.Clamp(_position / _duration * 100, 0, 100) : 0;
@ -152,6 +153,7 @@ public sealed class RecordedVideoPlayback : BindableBase
}
_capture = opened.Capture;
Frame = opened.Frame.Image;
DisplayedSeconds = opened.Frame.Seconds;
Analysis = opened.Frame.Analysis;
_position = percent == 100 ? _duration : opened.Frame.Seconds;
IsAtEnd = percent == 100;
@ -205,6 +207,7 @@ public sealed class RecordedVideoPlayback : BindableBase
return;
}
Frame = decoded.Image;
DisplayedSeconds = decoded.Seconds;
Analysis = decoded.Analysis;
_position = decoded.Seconds; NotifyTime();
}

View File

@ -1,4 +1,4 @@
using System.Collections.ObjectModel;
using System.Collections.ObjectModel;
using System.Windows.Input;
using Avalonia.Media;
using Prism.Commands;
@ -417,6 +417,7 @@ public class RecipeNode : EditorNode
Id = step.Id,
Name = step.Name,
Description = step.Description,
KeyFrameBase64 = step.KeyFrameBase64, KeyFrameSeconds = step.KeyFrameSeconds,
Timeout = step.Timeout,
StandardDurationMs = step.StandardDurationMs,
SaveCompletionImage = step.SaveCompletionImage,
@ -486,6 +487,7 @@ public class RecipeNode : EditorNode
Id = step.Id,
Name = step.Name,
Description = step.Description,
KeyFrameBase64 = step.KeyFrameBase64, KeyFrameSeconds = step.KeyFrameSeconds,
Timeout = step.Timeout,
StandardDurationMs = step.StandardDurationMs,
SaveCompletionImage = step.SaveCompletionImage,
@ -780,6 +782,12 @@ public class RegionNode : EditorNode
/// </summary>
public class StepNode : EditorNode
{
private string _keyFrameBase64 = "";
private double? _keyFrameSeconds;
public string KeyFrameBase64 { get => _keyFrameBase64; set { if (SetProperty(ref _keyFrameBase64, value)) RaisePropertyChanged(nameof(KeyFrameLabel)); } }
public double? KeyFrameSeconds { get => _keyFrameSeconds; set { if (SetProperty(ref _keyFrameSeconds, value)) RaisePropertyChanged(nameof(KeyFrameLabel)); } }
public string KeyFrameLabel => string.IsNullOrEmpty(KeyFrameBase64) ? "尚未保存关键帧" : $"已保存关键帧:{KeyFrameSeconds:0.###} 秒(保存配方后持久化)";
private int _aiCheckWindowMs = 10000, _aiMaxChecks = 20, _aiCheckSettleMs = 100;
public int AiCheckWindowMs { get => _aiCheckWindowMs; set { if (SetProperty(ref _aiCheckWindowMs, value)) RaisePropertyChanged(nameof(AiContinueAfterWindow)); } }
public bool AiContinueAfterWindow { get => AiCheckWindowMs > 0; set { if (value != AiContinueAfterWindow) AiCheckWindowMs = value ? 10000 : 0; } }

View File

@ -1,4 +1,4 @@
<UserControl xmlns="https://github.com/avaloniaui" xmlns:ed="clr-namespace:SopHelper.VVMs.RecipeEditor" xmlns:prism="http://prismlibrary.com/" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SopHelper.VVMs.RecipeEditor.RecipeEditor" prism:ViewModelLocator.AutoWireViewModel="True" Background="{StaticResource Bg}" xmlns:conv="using:Avalonia.Data.Converters" xmlns:training="clr-namespace:SopHelper.Training" xmlns:sop="clr-namespace:SopHelper.VVMs.SopPage">
<UserControl xmlns="https://github.com/avaloniaui" xmlns:ed="clr-namespace:SopHelper.VVMs.RecipeEditor" xmlns:prism="http://prismlibrary.com/" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="SopHelper.VVMs.RecipeEditor.RecipeEditor" prism:ViewModelLocator.AutoWireViewModel="True" Background="{StaticResource Bg}" xmlns:conv="using:Avalonia.Data.Converters" xmlns:training="clr-namespace:SopHelper.Training" xmlns:sop="clr-namespace:SopHelper.VVMs.SopPage">
<UserControl.DataTemplates>
<DataTemplate DataType="{x:Type ed:TextItem}">
<Grid Classes="Row">
@ -109,6 +109,7 @@
<Grid.ColumnDefinitions>
<ColumnDefinition Width="270" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="330" />
</Grid.ColumnDefinitions>
<DockPanel>
<StackPanel DockPanel.Dock="Top" Spacing="6" Margin="0,0,0,8">
@ -121,6 +122,22 @@
<Button DockPanel.Dock="Bottom" Content="加步骤" Margin="0,8,0,0" Padding="0,6" Command="{Binding Recipe.AddStepCommand}" />
<ListBox ItemTemplate="{StaticResource StepRow}" ItemsSource="{Binding Recipe.Steps}" SelectedItem="{Binding Recipe.SelectedStep}" Classes="Pick" />
</DockPanel>
<StackPanel Grid.Column="2" Margin="12,0,0,0" Spacing="8">
<TextBlock Text="标准视频" FontWeight="Bold" />
<StackPanel DataContext="{Binding SopRecording}" Spacing="8">
<Image Source="{Binding Playback.Frame}" Height="230" Stretch="Uniform" />
<StackPanel Orientation="Horizontal" Spacing="8">
<Button Content="{Binding PlayVideoButtonText}" Command="{Binding PlayVideoCommand}" />
<Button Content="停止" Command="{Binding StopVideoCommand}" />
</StackPanel>
<Slider Minimum="0" Maximum="100" Value="{Binding Playback.Progress, Mode=TwoWay}" IsEnabled="{Binding CanSeekVideo}" ToolTip.Tip="拖动跳转视频位置" />
<TextBlock Text="{Binding Playback.TimeText}" />
<TextBlock Text="{Binding Status}" TextWrapping="Wrap" />
</StackPanel>
<Button Content="获取关键帧" Command="{Binding CaptureStepKeyFrameCommand}" ToolTip.Tip="将当前显示画面保存为选中步骤的关键帧" />
<TextBlock Text="{Binding Recipe.SelectedStep.KeyFrameLabel}" TextWrapping="Wrap" />
<TextBlock Text="{Binding StepKeyFrameStatus}" TextWrapping="Wrap" />
</StackPanel>
<ScrollViewer Grid.Column="1" Margin="12,0,0,0" VerticalScrollBarVisibility="Auto" DataContext="{Binding Recipe.SelectedStep}">
<StackPanel>
<Grid Classes="Row">

View File

@ -1,4 +1,4 @@
using System.Collections.ObjectModel;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Runtime.InteropServices;
@ -106,6 +106,7 @@ public partial class RecipeEditorViewModel : BindableBase, IDialogAware
_closingDialog = true; CloseCommand.RaiseCanExecuteChanged();
await ShutdownAsync(); RequestClose.Invoke(ButtonResult.Cancel);
}, () => !IsCapturing && !_closingDialog);
CaptureStepKeyFrameCommand = new DelegateCommand(CaptureStepKeyFrame);
CaptureImageCommand = new DelegateCommand(async () => await CaptureImageAsync(),
() => !IsCapturing && _camera is not null && _cameraInfo is not null);
OpenImageCommand = new DelegateCommand(OpenImage, () => !IsCapturing);

View File

@ -0,0 +1,27 @@
using Prism.Commands;
namespace SopHelper.VVMs.RecipeEditor;
public partial class RecipeEditorViewModel
{
public DelegateCommand CaptureStepKeyFrameCommand { get; }
private string _stepKeyFrameStatus = "";
public string StepKeyFrameStatus { get => _stepKeyFrameStatus; private set => SetProperty(ref _stepKeyFrameStatus, value); }
private void CaptureStepKeyFrame()
{
if (Recipe.SelectedStep is not { } step) { StepKeyFrameStatus = "请先选中一个步骤。"; return; }
if (IsAgentBusy || IsCapturing || SopRecording is not { } recording || recording.IsTestingFlow
|| recording.Playback.IsSeeking || recording.Playback.Frame is not { } frame)
{ StepKeyFrameStatus = "请先播放标准视频;等待跳转完成后再获取关键帧,流程测试时不可取图。"; return; }
try
{
// UI线程同步取得已显示帧,避免按秒数重新解码造成图像与用户所见不一致。
var bytes = frame.ToPngBytes();
step.KeyFrameBase64 = Convert.ToBase64String(bytes);
step.KeyFrameSeconds = recording.Playback.DisplayedSeconds;
StepKeyFrameStatus = $"已获取步骤 {step.Id}「{step.Name}」关键帧,请保存配方。";
}
catch (Exception) { StepKeyFrameStatus = "关键帧保存失败,请重新获取。"; }
}
}

View File

@ -1,4 +1,4 @@
using YamlDotNet.Serialization;
using YamlDotNet.Serialization;
namespace SopHelper.Engine.Sop;
@ -120,6 +120,10 @@ public class ModelDef
/// </summary>
public class StepDef
{
/// <summary>用户选取的标准关键帧PNG,随步骤交换,不参与在线判定。</summary>
public string KeyFrameBase64 { get; set; } = "";
public double? KeyFrameSeconds { get; set; }
/// <summary>步骤号(不必从 1 开始,状态机取最小值起步)</summary>
public int Id { get; set; }

View File

@ -133,6 +133,29 @@ internal static class Program
}
CheckRealtimePlayback(model.StandardVideoPath);
CheckContinuousPlayback(model.StandardVideoPath);
vm.Recipe.AddStepCommand.Execute();
var selected = vm.Recipe.SelectedStep!;
vm.CaptureStepKeyFrameCommand.Execute();
Check(selected.KeyFrameBase64.Length == 0, "Cannot capture a keyframe without a displayed video frame");
Pump(model.Playback.PlayAsync(model.StandardVideoPath));
model.Playback.Pause();
Pump(model.Playback.SeekAsync(50));
var displayed = Convert.ToBase64String(model.Playback.Frame!.ToPngBytes());
vm.CaptureStepKeyFrameCommand.Execute();
Check(selected.KeyFrameBase64 == displayed && selected.KeyFrameSeconds == model.Playback.DisplayedSeconds,
"Capture stores the exact displayed frame and timestamp after paused seeking");
vm.Recipe.AddStepCommand.Execute();
Check(vm.Recipe.SelectedStep!.KeyFrameBase64.Length == 0 && selected.KeyFrameBase64 == displayed,
"Keyframes belong to the selected step and do not leak across selection changes");
var transferred = SopStepTransfer.Read(SopStepTransfer.Export(vm.Recipe.ToConfig()));
Check(transferred.Sop.Steps[0].KeyFrameBase64 == displayed,
"Keyframe image and timestamp survive step export and import");
vm.SaveCommand.Execute();
var savedKeyFrames = RecipeNode.From(SopConfigLoader.Load(store.ConfigPath(config.Sop.Name)), "test.yaml", false);
Check(savedKeyFrames.Steps[0].KeyFrameBase64 == displayed && savedKeyFrames.Steps[0].KeyFrameSeconds == selected.KeyFrameSeconds,
"Saving and reopening the recipe preserves the selected step keyframe");
Pump(model.Playback.StopAsync());
// Unsupported condition exercises playback and incomplete results without hardware/models/API.
config.Sop.Steps = [new StepDef { Id = 1, Name = "待配置步骤", Description = "验证当前编辑配置", Detection = new() { Method = "unsupported" } }];
config.Sop.Regions["标定区"] = new() { X1 = 10, Y1 = 5, X2 = 50, Y2 = 40, Name = "标定区", Color = "#FF00FF" };