diff --git a/README.md b/README.md index fc41dfd..abf310c 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,7 @@ Windows Python 环境使用 `tools/Setup-Python.ps1 -Sam2`;Linux 环境和部 - 检测模型的类别表只读;维护零件列表不会更改已训练模型的类别映射。模型输出类别仍以训练版本为准。 - “SOP流程视频”页录制当前配方的完整标准操作,固定保存到 `recipes/配方名/sop_stand/sop.avi`,与零件训练录像分开存放。新配方先保存,再开启预览并开始录像。普通录像与SOP录像统一使用运行设置中选中的相机,录制界面只显示相机名称,不再选择或刷新设备。 - 支持暂停、继续和停止保存;暂停时间不计入视频,累计有效录像最长 5 分钟,到时自动保存并弹窗。关闭编辑窗口也会停止并保存录像。 + - 同页可播放已保存视频,支持暂停、继续、停止及播完重播,并显示播放进度和时间。播放不需要连接相机;开始播放时关闭相机预览,重新开启预览或关闭窗口时释放播放器。 - 每份配方保留一段标准视频;“重新录制”先弹窗确认,确认后删除旧视频并重新开始,取消会保留原视频。录制中发起重新录制时会先暂停,取消后恢复原先的录制状态。 3. 零件标注与训练包含相机录像、视频导入、画框、SAM2 传播、复核、数据集导出、YOLO 训练和 ONNX 导出。 - 每段相机录像最长 5 分钟,达到上限后自动停止、保存文件并弹窗提示保存位置;相机预览继续运行,可再次开始录像。 diff --git a/src/SopHelper.Avalonia/Training/CameraViewModel.cs b/src/SopHelper.Avalonia/Training/CameraViewModel.cs index d53b84c..89d6016 100644 --- a/src/SopHelper.Avalonia/Training/CameraViewModel.cs +++ b/src/SopHelper.Avalonia/Training/CameraViewModel.cs @@ -44,7 +44,10 @@ public sealed class CameraViewModel : BindableBase public CameraInfo? SelectedCamera => IsPreviewing ? _previewCamera : _selectedCameraProvider(); public string SelectedCameraName => SelectedCamera?.Name ?? "未选择相机,请先到运行设置中选择"; - public BitmapSource? Preview { get => _preview; private set => SetProperty(ref _preview, value); } + 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(); } } @@ -67,6 +70,8 @@ public sealed class CameraViewModel : BindableBase 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) @@ -89,6 +94,16 @@ public sealed class CameraViewModel : BindableBase RecordCommand = Command(ToggleRecordingAsync, () => !IsBusy && !_closing && (IsRecording || (!HasStandardVideo && IsPreviewing && Preview != null && HasRecentFrame))); PauseCommand = Command(() => { TogglePause(); return Task.CompletedTask; }, () => !IsBusy && !_closing && IsRecording); RestartCommand = Command(RestartRecordingAsync, () => _sopStandard && !IsBusy && !_closing && HasStandardVideo && IsPreviewing && Preview != null && HasRecentFrame); + PlayVideoCommand = Command(ToggleVideoPlaybackAsync, () => _sopStandard && !IsBusy && !_closing && !IsRecording && HasStandardVideo); + StopVideoCommand = Command(async () => { await Playback.StopAsync(); 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.IsAtEnd) && Playback.IsAtEnd) Status = "视频播放结束,可点击“重新播放”再次观看"; + }; + Playback.Failed += message => Status = message; BrowseCommand = Command(async () => { var picker = new OpenFolderDialog { Title = "选择录像保存目录" }; @@ -140,6 +155,7 @@ public sealed class CameraViewModel : BindableBase } private async Task TogglePreviewAsync() { + await Playback.StopAsync(); if (IsPreviewing) { StopRecording(); @@ -159,6 +175,18 @@ public sealed class CameraViewModel : BindableBase _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 ToggleRecordingAsync() { if (IsRecording) { StopRecording(); return Task.CompletedTask; } @@ -200,6 +228,7 @@ public sealed class CameraViewModel : BindableBase // 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); @@ -267,7 +296,8 @@ public sealed class CameraViewModel : BindableBase if (!connected) Post(() => { if (_camera.IsConnected) return; // Ignore a queued disconnect from the previous connection. - StopRecording(); IsPreviewing = false; ClearPreview(); + StopRecording(); IsPreviewing = false; + if (!Playback.IsLoaded) ClearPreview(); }); } private void OnError(string message) => Post(() => Status = message); @@ -283,7 +313,7 @@ public sealed class CameraViewModel : BindableBase { _observedCamera = SelectedCamera; RaisePropertyChanged(nameof(SelectedCameraName)); UpdateCommands(); - if (!IsPreviewing) Status = SelectedCamera is null ? "请先在运行设置中选择相机,再开启录像预览" : "使用运行设置中选中的相机,点击“开启相机预览”"; + if (!IsPreviewing && !Playback.IsLoaded) Status = SelectedCamera is null ? "请先在运行设置中选择相机,再开启录像预览" : "使用运行设置中选中的相机,点击“开启相机预览”"; } if (IsRecording) { @@ -344,6 +374,7 @@ public sealed class CameraViewModel : BindableBase { _closing = true; _timer.Stop(); StateChanged(); await _operation; + await Playback.StopAsync(); try { await Task.Run(_camera.Dispose); } finally { diff --git a/src/SopHelper.Avalonia/Training/RecordedVideoPlayback.cs b/src/SopHelper.Avalonia/Training/RecordedVideoPlayback.cs new file mode 100644 index 0000000..0b8738a --- /dev/null +++ b/src/SopHelper.Avalonia/Training/RecordedVideoPlayback.cs @@ -0,0 +1,138 @@ +using System.Diagnostics; +using Avalonia.Threading; +using OpenCvSharp; +using Prism.Mvvm; +using SopHelper.Presentation.Imaging; + +namespace SopHelper.Training; + +/// 在后台解码录制的 AVI,界面线程只更新当前一帧。 +public sealed class RecordedVideoPlayback : BindableBase +{ + private readonly DispatcherTimer _timer; + private readonly Stopwatch _clock = new(); + private VideoCapture? _capture; + private Task? _readTask; + private BitmapSource? _frame; + private bool _playing, _loaded, _atEnd, _reading; + private double _fps, _duration, _position, _startPosition; + private int _generation; + + public BitmapSource? Frame { get => _frame; private set { var old = _frame; SetProperty(ref _frame, value); old?.Dispose(); } } + public bool IsPlaying { get => _playing; private set => SetProperty(ref _playing, value); } + public bool IsLoaded { get => _loaded; private set => SetProperty(ref _loaded, value); } + public bool IsAtEnd { get => _atEnd; private set => SetProperty(ref _atEnd, value); } + public double Progress => _duration > 0 ? Math.Clamp(_position / _duration * 100, 0, 100) : 0; + public string TimeText => $"{TimeSpan.FromSeconds(_position):mm\\:ss} / {TimeSpan.FromSeconds(_duration):mm\\:ss}"; + public event Action? Failed; + + public RecordedVideoPlayback() + { + _timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(33) }; + _timer.Tick += (_, _) => _ = ReadNextAsync(); + } + + public async Task PlayAsync(string path) + { + // Reopen at EOF: some AVI backends cannot seek after their last Read failed. + if (IsAtEnd) await StopAsync(); + if (_capture is null) + { + var capture = await Task.Run(() => + { + var video = new VideoCapture(); + try + { + if (!video.Open(path)) throw new IOException("无法打开录制的视频"); + return video; + } + catch { video.Dispose(); throw; } + }); + _capture = capture; + try + { + _fps = capture.Fps; + if (!double.IsFinite(_fps) || _fps <= 0) _fps = 30; + _duration = capture.FrameCount / _fps; + if (!double.IsFinite(_duration) || _duration <= 0) throw new IOException("视频中没有可播放画面"); + _position = 0; + IsLoaded = true; + } + catch { await StopAsync(); throw; } + } + _startPosition = _position; + _clock.Restart(); IsPlaying = true; + _timer.Interval = TimeSpan.FromMilliseconds(Math.Clamp(1000 / _fps, 15, 200)); + _timer.Start(); NotifyTime(); + await ReadNextAsync(); + } + + public void Pause() + { + _timer.Stop(); _clock.Stop(); IsPlaying = false; + } + + public async Task StopAsync() + { + Pause(); _generation++; + await WaitForReadAsync(); + _readTask = null; _reading = false; + var capture = _capture; _capture = null; + if (capture is not null) await Task.Run(capture.Dispose); + Frame = null; IsLoaded = false; IsAtEnd = false; + _position = 0; _duration = 0; NotifyTime(); + } + + private async Task WaitForReadAsync() + { + if (_readTask is null) return; + try { await _readTask; } catch { /* ReadNextAsync reports decoding errors. */ } + } + + private async Task ReadNextAsync() + { + if (!IsPlaying || _capture is null || _reading) return; + _reading = true; + var capture = _capture; + var generation = _generation; + var target = (long)Math.Floor((_startPosition + _clock.Elapsed.TotalSeconds) * _fps); + var read = _readTask = Task.Run(() => Decode(capture, target)); + try + { + var decoded = await read; + if (generation != _generation) { decoded.Image?.Dispose(); return; } + if (decoded.Image is null) + { + if (Frame is null) throw new IOException("无法解码视频画面"); + Pause(); IsAtEnd = true; + _position = _duration; NotifyTime(); + return; + } + Frame = decoded.Image; + _position = decoded.Seconds; NotifyTime(); + } + catch (Exception error) + { + if (generation != _generation) return; + await StopAsync(); + Failed?.Invoke("视频播放失败:" + error.Message); + } + finally { if (ReferenceEquals(_readTask, read)) _reading = false; } + } + + private DecodedFrame Decode(VideoCapture capture, long target) + { + while (capture.PosFrames < target) + if (!capture.Grab()) return new(null, 0); + using var frame = new Mat(); + if (!capture.Read(frame) || frame.Empty()) return new(null, 0); + var stride = checked((int)frame.Step()); + var image = BitmapSource.Create(frame.Width, frame.Height, 96, 96, PixelFormats.Bgr24, null, + frame.Data, checked(stride * frame.Height), stride); + image.Freeze(); + return new(image, Math.Max(0, (capture.PosFrames - 1) / _fps)); + } + + private void NotifyTime() { RaisePropertyChanged(nameof(Progress)); RaisePropertyChanged(nameof(TimeText)); } + private sealed record DecodedFrame(BitmapSource? Image, double Seconds); +} diff --git a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml index fce3110..8697e8d 100644 --- a/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml +++ b/src/SopHelper.Avalonia/VVMs/RecipeEditor/RecipeEditor.axaml @@ -451,14 +451,22 @@ - + - -