using System.Diagnostics; using System.IO; using System.Text.Json; using Avalonia; using SopHelper.Presentation; using Avalonia.Media; using SopHelper.Presentation.Imaging; using SopHelper.Presentation.Threading; using OpenCvSharp; using SopHelper.Engine.Camera; using Prism.Commands; using Prism.Mvvm; namespace SopHelper.Training; public sealed partial class CameraViewModel : BindableBase { private readonly ICameraService _camera; private readonly VideoRecorder _recorder; private readonly object _frames = new(); private readonly Dispatcher _dispatcher; private readonly DispatcherTimer _timer; private readonly string _settingsPath; private readonly string? _recipeRecordingDirectory; private readonly bool _sopStandard; private readonly Func _selectedCameraProvider; private readonly Stopwatch _previewClock = Stopwatch.StartNew(); private Mat? _latest; private int _previewPending; private int _generation; private long _lastFrameTick; private volatile bool _closing; private bool _busy, _previewing, _recording; private bool _paused; private string _status = "使用运行设置中选中的相机,点击“开启相机预览”"; private string _directory; private string _lastRecording = ""; private string _recordingInfo = "未录像"; private CameraInfo? _previewCamera, _observedCamera; private BitmapSource? _preview; private Task _operation = Task.CompletedTask; private Task? _shutdown; private readonly List _commands = []; public CameraInfo? SelectedCamera => IsPreviewing ? _previewCamera : _selectedCameraProvider(); public string SelectedCameraName => SelectedCamera?.Name ?? "未选择相机,请先到运行设置中选择"; public BitmapSource? Preview { get => _preview; private set { SetProperty(ref _preview, value); RaisePropertyChanged(nameof(DisplayImage)); } } public RecordedVideoPlayback Playback { get; } = new(); public BitmapSource? DisplayImage => Playback.IsLoaded ? Playback.Frame : Preview; public string PlayVideoButtonText => Playback.IsPlaying ? "暂停播放" : Playback.IsAtEnd ? "重新播放" : Playback.IsLoaded ? "继续播放" : "播放视频"; public string Status { get => _status; private set => SetProperty(ref _status, value); } public bool IsBusy { get => _busy; private set { SetProperty(ref _busy, value); StateChanged(); } } public bool IsPreviewing { get => _previewing; private set { SetProperty(ref _previewing, value); StateChanged(); } } public bool IsRecording { get => _recording; private set { SetProperty(ref _recording, value); StateChanged(); } } public bool IsPaused { get => _paused; private set { SetProperty(ref _paused, value); StateChanged(); } } public string PauseButtonText => IsPaused ? "继续录制" : "暂停录制"; public string StandardVideoPath => Path.Combine(SaveDirectory, "sop.avi"); public bool HasStandardVideo => _sopStandard && File.Exists(StandardVideoPath); public Func>? ConfirmRestartAsync { get; set; } public bool CanChangeDirectory => _recipeRecordingDirectory is null && !IsBusy && !IsRecording && !_closing; public string PreviewButtonText => IsPreviewing ? "关闭相机" : "开启相机预览"; public string RecordingInfo { get => _recordingInfo; private set => SetProperty(ref _recordingInfo, value); } public string SaveDirectory { get => _directory; set => SetProperty(ref _directory, _recipeRecordingDirectory ?? value); } public string LastRecording { get => _lastRecording; private set { SetProperty(ref _lastRecording, value); UpdateCommands(); } } public double RecordingFps { get; set; } = 30; public DelegateCommand PreviewCommand { get; } public DelegateCommand StartRecordingCommand { get; } public DelegateCommand StopRecordingCommand { get; } public DelegateCommand BrowseCommand { get; } public DelegateCommand RevealCommand { get; } public DelegateCommand PauseCommand { get; } public DelegateCommand RestartCommand { get; } public DelegateCommand PlayVideoCommand { get; } public DelegateCommand StopVideoCommand { get; } public event Action? RecordingLimitReached; public CameraViewModel(ICameraService camera, string root, string? recipeName = null, TimeProvider? timeProvider = null, bool sopStandard = false, Func? selectedCameraProvider = null) { _selectedCameraProvider = selectedCameraProvider ?? (() => null); _recorder = new VideoRecorder(timeProvider); _camera = camera; _dispatcher = Dispatcher.CurrentDispatcher; var recipeDirectory = string.IsNullOrWhiteSpace(recipeName) ? null : new SopHelper.Engine.Training.RecipeWorkspace(root).DirectoryFor(recipeName); _sopStandard = sopStandard; if (sopStandard && recipeDirectory is null) throw new ArgumentException("SOP录像必须属于已保存的配方"); _recipeRecordingDirectory = recipeDirectory is null ? null : Path.Combine(recipeDirectory, sopStandard ? "sop_stand" : "recordings"); _directory = _recipeRecordingDirectory ?? Path.Combine(root, "workspace", "recordings"); _settingsPath = recipeDirectory is null ? Path.Combine(root, "workspace", "camera-settings.json") : Path.Combine(recipeDirectory, sopStandard ? "sop-camera-settings.json" : "camera-settings.json"); try { SaveDirectory = _recipeRecordingDirectory ?? ReadSaveDirectory(root); } catch (Exception e) { Status = "录像目录配置读取失败:" + e.Message; } PreviewCommand = Command(TogglePreviewAsync, () => !IsBusy && !_closing && !IsTestingFlow && (IsPreviewing || SelectedCamera != null)); StartRecordingCommand = Command(StartRecordingAsync, () => !IsBusy && !_closing && !IsRecording && !HasStandardVideo && IsPreviewing && Preview != null && HasRecentFrame); StopRecordingCommand = Command(() => { StopRecording(); return Task.CompletedTask; }, () => !IsBusy && !_closing && IsRecording); 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); 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) => { 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.IsLoaded)) RaisePropertyChanged(nameof(CanSeekVideo)); if (e.PropertyName == nameof(Playback.IsAtEnd) && Playback.IsAtEnd) { if (IsTestingFlow) _ = CompleteFlowTestAsync(); Status = "视频播放结束,可点击“重新播放”再次观看"; } }; Playback.Failed += message => { EndFlowTest(message); Status = message; }; BrowseCommand = Command(async () => { var picker = new OpenFolderDialog { Title = "选择录像保存目录" }; if (Directory.Exists(SaveDirectory)) picker.InitialDirectory = SaveDirectory; if (await picker.ShowDialogAsync() == true) { SaveDirectory = picker.FolderName; SaveSettings(); } }, () => CanChangeDirectory); RevealCommand = Command(() => { if (!string.IsNullOrEmpty(LastRecording) && File.Exists(LastRecording)) { DesktopPlatform.Reveal(LastRecording); } else { Directory.CreateDirectory(SaveDirectory); var info = new ProcessStartInfo("explorer.exe") { UseShellExecute = true }; info.ArgumentList.Add(Path.GetFullPath(SaveDirectory)); Process.Start(info); } return Task.CompletedTask; }, () => !IsBusy && !_closing); _camera.FrameArrived += OnFrame; _camera.ConnectionChanged += OnConnection; _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 = "请先在运行设置中选择相机,再开启录像预览"; } private DelegateCommand Command(Func action, Func canExecute) { var command = new DelegateCommand(() => _operation = PerformAsync(action), canExecute); _commands.Add(command); return command; } private async Task PerformAsync(Func action) { if (IsBusy || _closing) return; IsBusy = true; try { await action(); } catch (Exception e) { Status = e.Message; } finally { IsBusy = false; } } private void UpdateCommands() { foreach (var command in _commands) command.RaiseCanExecuteChanged(); } private void StateChanged() { RaisePropertyChanged(nameof(CanChangeDirectory)); RaisePropertyChanged(nameof(SelectedCameraName)); RaisePropertyChanged(nameof(PreviewButtonText)); UpdateCommands(); RaisePropertyChanged(nameof(PauseButtonText)); RaisePropertyChanged(nameof(HasStandardVideo)); RaisePropertyChanged(nameof(CanSeekVideo)); } private async Task TogglePreviewAsync() { await Playback.StopAsync(); if (IsPreviewing) { StopRecording(); await Task.Run(_camera.Disconnect); ClearPreview(); IsPreviewing = false; Status = "相机已关闭"; return; } var selected = _selectedCameraProvider() ?? throw new InvalidOperationException("请先在运行设置中选择相机"); Status = "正在连接 " + selected.Name; if (!await _camera.ConnectAsync(selected)) throw new IOException("相机连接失败,请检查设备是否被其他程序占用"); if (_closing) return; if (!await _camera.StartAsync()) { await Task.Run(_camera.Disconnect); throw new IOException("相机已连接,但采集启动失败"); } _previewCamera = selected; IsPreviewing = true; Status = "相机预览中,可开始录像"; } private async Task ToggleVideoPlaybackAsync() { if (IsRecording) throw new InvalidOperationException("请先停止录像并保存,再播放视频"); if (Playback.IsPlaying) { Playback.Pause(); Status = "视频播放已暂停"; return; } if (IsPreviewing) { await Task.Run(_camera.Disconnect); ClearPreview(); IsPreviewing = false; } await Playback.PlayAsync(StandardVideoPath); if (Playback.IsPlaying) Status = "正在播放已录制的SOP流程视频"; } private Task StartRecordingAsync() { if (IsRecording) return Task.CompletedTask; if (HasStandardVideo) throw new InvalidOperationException("已有SOP流程视频,请使用“重新录制”并确认删除旧视频"); if (string.IsNullOrWhiteSpace(SaveDirectory)) throw new ArgumentException("请选择录像保存目录"); var directory = Path.GetFullPath(SaveDirectory.Trim()); SaveDirectory = directory; SaveSettings(); lock (_frames) { if (_latest == null || !_camera.IsGrabbing) throw new InvalidOperationException("尚未收到相机画面,请先开启预览"); if (Stopwatch.GetElapsedTime(_lastFrameTick).TotalSeconds > 2) throw new IOException("超过2秒未收到相机画面,请重新连接后再录像"); LastRecording = _recorder.Start(directory, _latest, RecordingFps, _sopStandard ? "sop.avi" : null); } IsRecording = true; Status = "正在录像,最长5分钟;到时自动停止并保存"; Tick(); return Task.CompletedTask; } private void TogglePause() { lock (_frames) { if (IsPaused) _recorder.Resume(); else _recorder.Pause(); IsPaused = _recorder.IsPaused; } Status = IsPaused ? "录制已暂停,暂停期间不计入视频时长;点击“继续录制”接着录制" : "已继续录制"; Tick(); } private async Task RestartRecordingAsync() { if (ConfirmRestartAsync is null) throw new InvalidOperationException("请先确认删除旧SOP流程视频"); var resumeOnCancel = IsRecording && !IsPaused; if (resumeOnCancel) TogglePause(); var confirmed = false; try { confirmed = await ConfirmRestartAsync(); } finally { if (!confirmed && resumeOnCancel && IsRecording && IsPaused) TogglePause(); } if (!confirmed) { Status = "已取消重新录制,原视频已保留"; return; } // Do not delete until the camera is ready and the user has explicitly confirmed. if (_closing || !_camera.IsGrabbing || !HasRecentFrame) throw new IOException("相机画面已中断,原视频保留,请重新连接后再试"); StopRecording(); await Playback.StopAsync(); if (!SopHelper.Engine.Training.RecipeWorkspace.IsWithin(StandardVideoPath, _recipeRecordingDirectory!)) throw new IOException("SOP录像路径不在当前配方目录中"); File.Delete(StandardVideoPath); SopHelper.Engine.Training.SopStandardVideoDuration.Remember(Path.GetDirectoryName(_recipeRecordingDirectory!)!, TimeSpan.Zero); LastRecording = ""; RecordingInfo = "未录像"; Status = "已清除旧视频,请点击“开始录像”进行重新录制"; StateChanged(); } private void StopRecording() { RecordingResult? result; try { lock (_frames) result = _recorder.Stop(); } finally { IsRecording = false; IsPaused = false; } if (result != null) { LastRecording = result.Path; RecordingInfo = $"已保存 · {result.Duration.TotalSeconds:F1} 秒 · {result.Frames} 帧"; Status = _sopStandard ? "SOP流程视频已保存到当前配方的 sop_stand 目录" : "录像已保存,可在主窗口导入视频继续标注"; if (_sopStandard) { try { SopHelper.Engine.Training.SopStandardVideoDuration.Remember(Path.GetDirectoryName(_recipeRecordingDirectory!)!, result.Duration); } catch (Exception error) { Status += ";标准用时记忆保存失败:" + error.Message; } } } } private void OnFrame(CameraFrame frame) { if (_closing) return; BitmapSource? preview = null; string? recordingError = null; var generation = Volatile.Read(ref _generation); lock (_frames) { if (_closing) return; Interlocked.Exchange(ref _lastFrameTick, Stopwatch.GetTimestamp()); if (_latest == null) _latest = frame.Bgr.Clone(); else frame.Bgr.CopyTo(_latest); try { _recorder.Write(frame.Bgr); } catch (Exception e) { recordingError = "录像中断:" + e.Message + ";已写入内容保存在 " + _recorder.CurrentPath; } if (_previewClock.ElapsedMilliseconds >= 66 && Interlocked.CompareExchange(ref _previewPending, 1, 0) == 0) { try { var stride = checked((int)frame.Bgr.Step()); preview = BitmapSource.Create(frame.Bgr.Width, frame.Bgr.Height, 96, 96, PixelFormats.Bgr24, null, frame.Bgr.Data, checked(stride * frame.Bgr.Height), stride); preview.Freeze(); _previewClock.Restart(); } catch { Interlocked.Exchange(ref _previewPending, 0); throw; } } } if (recordingError != null) { var error = recordingError; Post(() => { IsRecording = false; IsPaused = false; Status = error; RecordingInfo = "录像中断,请检查日志提示"; }); } if (preview != null) { var bitmap = preview; Post(() => { try { if (generation == Volatile.Read(ref _generation)) { Preview = bitmap; UpdateCommands(); } } finally { Interlocked.Exchange(ref _previewPending, 0); } }); } } private void OnConnection(bool connected) { if (!connected) Post(() => { if (_camera.IsConnected) return; // Ignore a queued disconnect from the previous connection. StopRecording(); IsPreviewing = false; if (!Playback.IsLoaded) ClearPreview(); }); } private void OnError(string message) => Post(() => Status = message); private void Post(Action action) { if (!_closing && !_dispatcher.HasShutdownStarted) _dispatcher.BeginInvoke(() => { if (!_closing) action(); }, DispatcherPriority.Background); } private void Tick() { if (_closing) return; if (!ReferenceEquals(_observedCamera, SelectedCamera)) { _observedCamera = SelectedCamera; RaisePropertyChanged(nameof(SelectedCameraName)); UpdateCommands(); if (!IsPreviewing && !Playback.IsLoaded) Status = SelectedCamera is null ? "请先在运行设置中选择相机,再开启录像预览" : "使用运行设置中选中的相机,点击“开启相机预览”"; } if (IsRecording) { if (_recorder.Elapsed >= VideoRecorder.MaximumDuration) { string message; try { StopRecording(); Status = "录像已达到5分钟上限,已自动停止并保存"; message = Status + "。\n\n保存位置:" + LastRecording; } catch (Exception error) { Status = "录像已达到5分钟上限并停止,保存时出错:" + error.Message; message = Status; } RecordingLimitReached?.Invoke(message); } else if (Stopwatch.GetElapsedTime(Interlocked.Read(ref _lastFrameTick)).TotalSeconds > 2) { StopRecording(); Status = "超过2秒未收到相机画面,录像已结束,请检查相机连接"; } else if (!_recorder.IsRecording) IsRecording = false; else RecordingInfo = $"{(IsPaused ? "Ⅱ 已暂停" : "● 正在录像")} {_recorder.Elapsed:hh\\:mm\\:ss} / 00:05:00 · {RecordingFps:F0} fps"; } if (IsPreviewing && !_camera.IsGrabbing && !IsBusy) { StopRecording(); IsPreviewing = false; ClearPreview(); Status = "相机采集已中断,请重新连接"; } } private bool HasRecentFrame => Interlocked.Read(ref _lastFrameTick) != 0 && Stopwatch.GetElapsedTime(Interlocked.Read(ref _lastFrameTick)).TotalSeconds <= 2; private void ClearPreview() { Interlocked.Increment(ref _generation); lock (_frames) { _latest?.Dispose(); _latest = null; } Preview = null; } internal static string ReadSaveDirectory(string root) { var path = Path.Combine(root, "workspace", "camera-settings.json"); if (File.Exists(path)) { using var json = JsonDocument.Parse(File.ReadAllText(path)); var directory = json.RootElement.GetProperty("directory").GetString(); if (!string.IsNullOrWhiteSpace(directory)) return directory; } return Path.Combine(root, "workspace", "recordings"); } private void SaveSettings() { Directory.CreateDirectory(Path.GetDirectoryName(_settingsPath)!); File.WriteAllText(_settingsPath, JsonSerializer.Serialize(new { directory = SaveDirectory })); } public Task ShutdownAsync() => _shutdown ??= ShutdownCoreAsync(); private async Task ShutdownCoreAsync() { _closing = true; _timer.Stop(); StateChanged(); await _operation; await Playback.StopAsync(); EndFlowTest("测试已关闭"); FlowTestDecisionImage = null; try { await Task.Run(_camera.Dispose); } finally { try { StopRecording(); } finally { ClearPreview(); _camera.FrameArrived -= OnFrame; _camera.ConnectionChanged -= OnConnection; _camera.Error -= OnError; IsPreviewing = false; } } } }