SOP流程视频支持导入并覆盖标准视频

新增原生文件选择入口,将所选视频复制至当前配方sop_stand/sop.avi。先暂存并验证可解码,再释放播放句柄并替换旧文件;更新标准时长与界面状态,保留用户源文件。

验证:隔离构建及VideoFlowTest.Smoke通过,覆盖真实MP4导入播放、已有视频替换、时长刷新、损坏和缺失文件、取消选择、相同路径及Windows文件占用时保留旧视频与临时文件清理。
This commit is contained in:
tfarcraw 2026-11-18 13:54:49 +08:00
parent 69650e076f
commit 2553adf03f
5 changed files with 158 additions and 2 deletions

View File

@ -0,0 +1,73 @@
using System.IO;
using OpenCvSharp;
using SopHelper.Engine.Training;
using SopHelper.Presentation;
namespace SopHelper.Training;
public sealed partial class CameraViewModel
{
public Func<Task<string?>>? SelectImportVideoAsync { get; set; }
private async Task ImportVideoAsync()
{
string? source;
if (SelectImportVideoAsync is { } select) source = await select();
else
{
var dialog = new OpenFileDialog
{
Title = "导入标准 SOP 视频",
Filter = "视频|*.avi;*.mp4;*.mov;*.mkv;*.wmv;*.webm|所有文件|*.*",
InitialDirectory = SaveDirectory
};
source = await dialog.ShowDialogAsync() == true ? dialog.FileName : null;
}
if (string.IsNullOrWhiteSpace(source) || _closing) return;
var destination = Path.GetFullPath(StandardVideoPath);
if (!RecipeWorkspace.IsWithin(destination, _recipeRecordingDirectory!))
throw new IOException("标准视频路径不在当前配方目录中");
if (Path.GetFullPath(source).Equals(destination, OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal))
{ Status = "所选文件已经是当前标准视频"; return; }
Directory.CreateDirectory(SaveDirectory);
var temporary = Path.Combine(SaveDirectory, ".import-" + Guid.NewGuid().ToString("N") + ".avi");
try
{
Status = "正在导入标准视频…";
await using (var input = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read, 1024 * 1024, useAsync: true))
await using (var output = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1024 * 1024, useAsync: true))
await input.CopyToAsync(output);
var duration = await Task.Run(() =>
{
using var video = new VideoCapture(temporary);
using var frame = new Mat();
var seconds = video.IsOpened() && video.Fps > 0 ? video.FrameCount / video.Fps : 0;
if (!double.IsFinite(seconds) || seconds <= 0 || seconds > TimeSpan.MaxValue.TotalSeconds
|| !video.Read(frame) || frame.Empty())
throw new InvalidDataException("视频无法读取,请检查格式或文件是否损坏;原标准视频已保留");
return TimeSpan.FromSeconds(seconds);
});
if (_closing) return;
await Playback.StopAsync();
if (_closing) return;
EndFlowTest("标准视频已替换");
FlowTestRegions = null;
FlowTestStatus = ""; FlowTestDetails = "";
FlowTestDecisionImage = null; FlowTestDecisionLabel = "";
// 同目录临时文件验证成功后再替换,复制或解码失败不会破坏旧视频。
File.Move(temporary, destination, overwrite: true);
LastRecording = destination;
RecordingInfo = $"已导入 · {duration.TotalSeconds:F1} 秒";
Status = "标准视频已导入当前配方的 sop_stand/sop.avi,可播放或测试流程";
StateChanged();
try { SopStandardVideoDuration.Remember(Path.GetDirectoryName(_recipeRecordingDirectory!)!, duration); }
catch (Exception error) when (error is IOException or UnauthorizedAccessException)
{ Status += ";标准用时保存失败:" + error.Message; }
}
finally
{
if (File.Exists(temporary)) File.Delete(temporary);
}
}
}

View File

@ -72,6 +72,7 @@ public sealed partial class CameraViewModel : BindableBase
public DelegateCommand RestartCommand { get; }
public DelegateCommand PlayVideoCommand { get; }
public DelegateCommand StopVideoCommand { get; }
public DelegateCommand ImportVideoCommand { get; }
public event Action<string>? RecordingLimitReached;
public CameraViewModel(ICameraService camera, string root, string? recipeName = null, TimeProvider? timeProvider = null, bool sopStandard = false, Func<CameraInfo?>? selectedCameraProvider = null)
@ -96,6 +97,7 @@ public sealed partial class CameraViewModel : BindableBase
PauseCommand = Command(() => { TogglePause(); return Task.CompletedTask; }, () => !IsBusy && !_closing && IsRecording);
RestartCommand = Command(RestartRecordingAsync, () => _sopStandard && !IsBusy && !_closing && !IsTestingFlow && HasStandardVideo && IsPreviewing && Preview != null && HasRecentFrame);
PlayVideoCommand = Command(ToggleVideoPlaybackAsync, () => _sopStandard && !IsBusy && !_closing && !IsTestingFlow && !IsRecording && HasStandardVideo);
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);
Playback.PropertyChanged += (_, e) =>
@ -137,8 +139,10 @@ public sealed partial class CameraViewModel : BindableBase
_camera.Error += OnError;
_timer = new DispatcherTimer(TimeSpan.FromMilliseconds(250), DispatcherPriority.Background, (_, _) => Tick(), _dispatcher);
_timer.Start();
if (HasStandardVideo) { LastRecording = StandardVideoPath; RecordingInfo = "已有SOP流程视频"; Status = "已有标准操作录像;如需替换,请开启相机后点击“重新录制”"; }
if (SelectedCamera is null) Status = "请先在运行设置中选择相机,再开启录像预览";
if (HasStandardVideo) { LastRecording = StandardVideoPath; RecordingInfo = "已有SOP流程视频"; Status = "已有标准视频,可播放、测试流程或导入视频替换"; }
if (SelectedCamera is null && !HasStandardVideo) Status = _sopStandard
? "可导入标准视频,或先在运行设置中选择相机后录制"
: "请先在运行设置中选择相机,再开启录像预览";
}
private DelegateCommand Command(Func<Task> action, Func<bool> canExecute)

View File

@ -439,6 +439,7 @@
<Button Content="{Binding PauseButtonText}" Command="{Binding PauseCommand}" />
<Button Content="停止录像" Command="{Binding StopRecordingCommand}" />
<Button Content="重新录制" Command="{Binding RestartCommand}" />
<Button Content="导入视频" Command="{Binding ImportVideoCommand}" ToolTip.Tip="选择视频并复制到当前配方的 sop_stand/sop.avi,覆盖已有标准视频" />
<Button Content="{Binding PlayVideoButtonText}" Command="{Binding PlayVideoCommand}" />
<Button Content="测试流程" Command="{Binding TestFlowCommand}" ToolTip.Tip="从头播放标准视频,使用当前编辑的步骤和区域进行流程检测" />
<Button Content="停止播放" Command="{Binding StopVideoCommand}" />

View File

@ -34,6 +34,7 @@ internal static class Program
if (args.Contains("--live")) { LiveVideoFlowChecks.Run(args); return; }
CheckAiFlow();
AgentDraftVerificationChecks.Run(root);
StandardVideoImportChecks.Run(root);
CheckVideoPage(root);
}
finally
@ -120,6 +121,8 @@ internal static class Program
window.UpdateLayout(); Dispatcher.UIThread.RunJobs();
var button = view.GetVisualDescendants().OfType<Button>().Single(b => ReferenceEquals(b.Command, model.TestFlowCommand));
Check(button.Content?.ToString() == "测试流程" && button.IsEffectivelyVisible && model.TestFlowCommand.CanExecute(), "SOP video page exposes the enabled test flow button");
var importButton = view.GetVisualDescendants().OfType<Button>().Single(b => ReferenceEquals(b.Command, model.ImportVideoCommand));
Check(importButton.Content?.ToString() == "导入视频" && importButton.IsEffectivelyVisible && importButton.IsEnabled, "SOP video page exposes the enabled import button");
model.TestFlowCommand.Execute(); Until(() => !model.IsBusy);
Check(model.IsTestingFlow && model.Playback.IsPlaying && model.DisplayImage is { PixelWidth: 64, PixelHeight: 48 }, "Test button plays and displays the standard video without a camera");
Check(!model.TestFlowCommand.CanExecute() && !model.PlayVideoCommand.CanExecute() && !model.PreviewCommand.CanExecute() && !model.CanSeekVideo, "Test run prevents restart, playback switching, camera switching, and seeking");

View File

@ -0,0 +1,75 @@
using Avalonia.Threading;
using OpenCvSharp;
using Prism.Dialogs;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Training;
using SopHelper.VVMs.RecipeEditor;
internal static class StandardVideoImportChecks
{
public static void Run(string root)
{
var store = new RecipeWorkspace(root);
var config = new SopConfig(); config.Sop.Name = "导入标准视频";
var vm = new RecipeEditorViewModel();
vm.OnDialogOpened(new DialogParameters { { "directory", store.RecipesDirectory }, { "config", config }, { "new", true } });
vm.SaveCommand.Execute();
var model = vm.SopRecording!;
var source = Path.Combine(root, "用户选择的.mp4");
WriteVideo(source, VideoWriter.FourCC('m', 'p', '4', 'v'), 20);
var sourceBytes = File.ReadAllBytes(source);
Check(!model.HasStandardVideo && model.ImportVideoCommand.CanExecute(), "Import is available without a camera or previous standard video");
var selection = new TaskCompletionSource<string?>(); model.SelectImportVideoAsync = () => selection.Task;
model.ImportVideoCommand.Execute();
Check(model.IsBusy && !model.ImportVideoCommand.CanExecute(), "Import selection disables duplicate operations");
selection.SetResult(source); Until(() => !model.IsBusy);
Check(model.HasStandardVideo && File.ReadAllBytes(model.StandardVideoPath).SequenceEqual(sourceBytes)
&& model.StandardVideoPath.EndsWith(Path.Combine("sop_stand", "sop.avi")) && File.ReadAllBytes(source).SequenceEqual(sourceBytes),
"Selected MP4 is copied into the standard folder and renamed without moving the source");
Check(Math.Abs(SopStandardVideoDuration.Get(Path.GetDirectoryName(model.SaveDirectory)!).TotalSeconds - 2) < .01,
"Imported duration updates the persistent standard duration");
model.PlayVideoCommand.Execute(); Until(() => !model.IsBusy);
Check(model.Playback.IsLoaded && model.DisplayImage is { PixelWidth: 64, PixelHeight: 48 }, "Renamed MP4 decodes and plays from the standard AVI path");
var replacement = Path.Combine(root, "替换.avi"); WriteVideo(replacement, FourCC.MJPG, 30);
model.SelectImportVideoAsync = () => Task.FromResult<string?>(replacement);
model.ImportVideoCommand.Execute(); Until(() => !model.IsBusy);
var imported = File.ReadAllBytes(model.StandardVideoPath);
Check(imported.SequenceEqual(File.ReadAllBytes(replacement)) && !model.Playback.IsLoaded && model.LastRecording == model.StandardVideoPath,
"Import releases current playback and overwrites the old standard video");
Check(Math.Abs(SopStandardVideoDuration.Get(Path.GetDirectoryName(model.SaveDirectory)!).TotalSeconds - 3) < .01,
"Replacing a video refreshes cached standard duration");
var invalid = Path.Combine(root, "损坏.mp4"); File.WriteAllText(invalid, "invalid video");
foreach (var choice in new[] { invalid, Path.Combine(root, "不存在.mp4"), model.StandardVideoPath, null })
{
model.SelectImportVideoAsync = () => Task.FromResult(choice);
model.ImportVideoCommand.Execute(); Until(() => !model.IsBusy);
Check(File.ReadAllBytes(model.StandardVideoPath).SequenceEqual(imported) && !Directory.EnumerateFiles(model.SaveDirectory, ".import-*").Any(),
"Invalid, missing, same-path and cancelled selection preserve the old video and clean temporary files");
}
if (OperatingSystem.IsWindows())
{
using (var locked = new FileStream(model.StandardVideoPath, FileMode.Open, FileAccess.Read, FileShare.None))
{
model.SelectImportVideoAsync = () => Task.FromResult<string?>(source);
model.ImportVideoCommand.Execute(); Until(() => !model.IsBusy);
}
Check(File.ReadAllBytes(model.StandardVideoPath).SequenceEqual(imported)
&& !Directory.EnumerateFiles(model.SaveDirectory, ".import-*").Any(), "Replacement failure preserves the locked old video and removes staging files");
}
var shutdown = vm.ShutdownAsync(); Until(() => shutdown.IsCompleted); shutdown.GetAwaiter().GetResult(); vm.OnDialogClosed();
}
private static void WriteVideo(string path, int codec, int frames)
{
using var writer = new VideoWriter(path, codec, 10, new Size(64, 48));
Check(writer.IsOpened(), "Import sample video opens");
for (var i = 0; i < frames; i++) { using var image = new Mat(48, 64, MatType.CV_8UC3, new Scalar(20, 60, i * 5)); writer.Write(image); }
}
private static void Until(Func<bool> ready)
{
var watch = System.Diagnostics.Stopwatch.StartNew();
while (!ready() && watch.Elapsed < TimeSpan.FromSeconds(15)) { using var cancellation = new CancellationTokenSource(10); Dispatcher.UIThread.MainLoop(cancellation.Token); }
Check(ready(), "Import completes"); Dispatcher.UIThread.RunJobs();
}
private static void Check(bool value, string message) { if (!value) throw new Exception(message); Console.WriteLine("PASS: " + message); }
}