diff --git a/src/SopHelper.Avalonia/Training/CameraVideoImport.cs b/src/SopHelper.Avalonia/Training/CameraVideoImport.cs new file mode 100644 index 0000000..ccb304d --- /dev/null +++ b/src/SopHelper.Avalonia/Training/CameraVideoImport.cs @@ -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>? 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); + } + } +} diff --git a/src/SopHelper.Avalonia/Training/CameraViewModel.cs b/src/SopHelper.Avalonia/Training/CameraViewModel.cs index 7f9f4d0..8c1cec9 100644 --- a/src/SopHelper.Avalonia/Training/CameraViewModel.cs +++ b/src/SopHelper.Avalonia/Training/CameraViewModel.cs @@ -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? RecordingLimitReached; public CameraViewModel(ICameraService camera, string root, string? recipeName = null, TimeProvider? timeProvider = null, bool sopStandard = false, Func? 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 action, Func canExecute) diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml index bfdd6b8..bc3d411 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml @@ -439,6 +439,7 @@