支持在SOP流程视频页播放暂停及重播已录视频

This commit is contained in:
tfarcraw 2026-11-10 10:15:05 +08:00
parent 90db7695c3
commit 823027e7e6
5 changed files with 224 additions and 11 deletions

View File

@ -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 分钟,达到上限后自动停止、保存文件并弹窗提示保存位置;相机预览继续运行,可再次开始录像。

View File

@ -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<string>? RecordingLimitReached;
public CameraViewModel(ICameraService camera, string root, string? recipeName = null, TimeProvider? timeProvider = null, bool sopStandard = false, Func<CameraInfo?>? 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
{

View File

@ -0,0 +1,138 @@
using System.Diagnostics;
using Avalonia.Threading;
using OpenCvSharp;
using Prism.Mvvm;
using SopHelper.Presentation.Imaging;
namespace SopHelper.Training;
/// <summary>在后台解码录制的 AVI,界面线程只更新当前一帧。</summary>
public sealed class RecordedVideoPlayback : BindableBase
{
private readonly DispatcherTimer _timer;
private readonly Stopwatch _clock = new();
private VideoCapture? _capture;
private Task<DecodedFrame>? _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<string>? 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);
}

View File

@ -451,14 +451,22 @@
<Border Grid.Row="1" Background="#080E14" CornerRadius="6" MinHeight="180">
<Grid>
<TextBlock Text="使用运行设置中选中的相机,开启预览后录制标准操作流程" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="{StaticResource FgDim}" />
<Image Source="{Binding Preview}" Stretch="Uniform" />
<Image Source="{Binding DisplayImage}" Stretch="Uniform" />
</Grid>
</Border>
<StackPanel Grid.Row="2" Orientation="Horizontal" Spacing="8" Margin="0,12,0,8">
<Button Content="{Binding RecordButtonText}" Command="{Binding RecordCommand}" />
<Button Content="{Binding PauseButtonText}" Command="{Binding PauseCommand}" />
<Button Content="重新录制" Command="{Binding RestartCommand}" />
<Button Content="打开保存位置" Command="{Binding RevealCommand}" />
<StackPanel Grid.Row="2" Spacing="8" Margin="0,12,0,8">
<StackPanel Orientation="Horizontal" Spacing="8">
<Button Content="{Binding RecordButtonText}" Command="{Binding RecordCommand}" />
<Button Content="{Binding PauseButtonText}" Command="{Binding PauseCommand}" />
<Button Content="重新录制" Command="{Binding RestartCommand}" />
<Button Content="打开保存位置" Command="{Binding RevealCommand}" />
<Button Content="{Binding PlayVideoButtonText}" Command="{Binding PlayVideoCommand}" />
<Button Content="停止播放" Command="{Binding StopVideoCommand}" />
</StackPanel>
<Grid ColumnDefinitions="*,Auto">
<ProgressBar Minimum="0" Maximum="100" Value="{Binding Playback.Progress}" Height="6" VerticalAlignment="Center" />
<TextBlock Grid.Column="1" Text="{Binding Playback.TimeText}" Margin="12,0,0,0" />
</Grid>
</StackPanel>
<StackPanel Grid.Row="3" Spacing="6">
<TextBlock Text="{Binding RecordingInfo}" />

View File

@ -23,7 +23,7 @@ internal static class Program
var root = Path.Combine(Path.GetTempPath(), "recording-limit-smoke-" + Guid.NewGuid().ToString("N"));
try
{
AppBuilder.Configure<Application>().UseHeadless(new AvaloniaHeadlessPlatformOptions()).SetupWithoutStarting();
AppBuilder.Configure<Application>().UseSkia().UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false }).SetupWithoutStarting();
Application.Current!.Styles.Add(new FluentTheme());
Application.Current.Styles.Add(new StyleInclude(new Uri("avares://SopHelper.Avalonia/")) { Source = new Uri("avares://SopHelper.Avalonia/Themes/Styles.axaml") });
Check(VideoRecorder.MaximumDuration == TimeSpan.FromMinutes(5), "Production recording limit is five minutes");
@ -105,6 +105,7 @@ internal static class Program
model.PreviewCommand.Execute(); Thread.Sleep(75); camera.Emit(); Dispatcher.UIThread.RunJobs();
Check(ReferenceEquals(camera.ConnectedCamera, selected) && camera.EnumerationCount == 0, "SOP recording also uses the global camera directly");
model.RecordCommand.Execute();
Check(!model.PlayVideoCommand.CanExecute(), "Playback is disabled until recording has stopped and saved");
var expectedPath = Path.Combine(store.DirectoryFor(config.Sop.Name), "sop_stand", "sop.avi");
Check(model.LastRecording == expectedPath && !model.CanChangeDirectory, "SOP video is stored separately under its current recipe");
clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit();
@ -117,6 +118,23 @@ internal static class Program
model.RecordCommand.Execute(); CheckVideo(model.LastRecording, 2);
Check(!model.RecordCommand.CanExecute() && model.RestartCommand.CanExecute(), "Existing video can only be replaced through confirmed re-recording");
var original = File.ReadAllBytes(expectedPath);
model.PlayVideoCommand.Execute(); PumpIdle(model);
Check(model.Playback.IsPlaying && !model.IsPreviewing && model.DisplayImage is { PixelWidth: 64, PixelHeight: 48 }, "Saved SOP video plays inside the page after releasing the camera");
Check(editor.GetVisualDescendants().OfType<Image>().Any(i => ReferenceEquals(i.Source, model.Playback.Frame)), "SOP image control displays the decoded video frame");
model.PlayVideoCommand.Execute(); PumpIdle(model); PumpFor(100);
var pausedProgress = model.Playback.Progress; PumpFor(100);
Check(!model.Playback.IsPlaying && model.Playback.Progress == pausedProgress && model.DisplayImage is not null, "Playback pause holds the frame and progress");
model.PlayVideoCommand.Execute(); PumpIdle(model);
var playbackWait = System.Diagnostics.Stopwatch.StartNew();
while (model.Playback.IsPlaying && playbackWait.Elapsed < TimeSpan.FromSeconds(4)) PumpFor(20);
Check(model.Playback.IsAtEnd && model.Playback.Progress == 100 && model.PlayVideoButtonText == "重新播放", "Playback stops at the end and offers replay");
model.PlayVideoCommand.Execute(); PumpIdle(model);
Check(model.Playback.IsPlaying && model.Playback.Progress < 50, "Replay starts from the beginning");
model.StopVideoCommand.Execute(); PumpIdle(model);
Check(!model.Playback.IsLoaded && model.Playback.Frame is null, "Stop playback clears the player and releases its file");
Check(File.ReadAllBytes(expectedPath).SequenceEqual(original), "Playback leaves the recorded file unchanged");
model.PreviewCommand.Execute(); PumpIdle(model); camera.Emit(); Dispatcher.UIThread.RunJobs();
Check(model.IsPreviewing && !model.Playback.IsLoaded, "Camera preview can restart after playback");
model.RestartCommand.Execute();
var dialog = FindSopDialog(editor);
Check(dialog.Title == "确认重新录制" && File.ReadAllBytes(expectedPath).SequenceEqual(original), "Re-record opens confirmation before changing the old video");
@ -139,9 +157,21 @@ internal static class Program
vm.OnDialogClosed();
var reopened = new CameraViewModel(new FakeCamera(), root, config.Sop.Name, sopStandard: true);
Check(reopened.HasStandardVideo && reopened.LastRecording == expectedPath, "Reopening the recipe restores its existing SOP video");
Check(reopened.PlayVideoCommand.CanExecute() && !reopened.PreviewCommand.CanExecute(), "Existing videos can play without a selected or connected camera");
reopened.PlayVideoCommand.Execute(); PumpIdle(reopened);
Check(reopened.Playback.IsPlaying && reopened.DisplayImage is not null, "Reopened recipe plays its saved video");
Pump(reopened.ShutdownAsync());
Check(!reopened.Playback.IsLoaded, "Closing playback disposes the video reader");
using (var exclusive = new FileStream(expectedPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
Check(exclusive.Length > 0, "Video file is unlocked after player shutdown");
var other = new CameraViewModel(new FakeCamera(), root, "另一配方", sopStandard: true);
Check(!other.HasStandardVideo && other.StandardVideoPath != expectedPath, "SOP recordings are isolated between recipes"); Pump(other.ShutdownAsync());
Check(!other.HasStandardVideo && other.StandardVideoPath != expectedPath, "SOP recordings are isolated between recipes");
Check(!other.PlayVideoCommand.CanExecute(), "Playback is disabled when the recipe has no saved video");
Directory.CreateDirectory(Path.GetDirectoryName(other.StandardVideoPath)!);
File.WriteAllText(other.StandardVideoPath, "damaged-video");
other.PlayVideoCommand.Execute(); PumpIdle(other);
Check(!other.Playback.IsLoaded && !other.Playback.IsPlaying && other.Status.Contains("无法打开"), "Damaged video reports an error without leaving a running player");
Pump(other.ShutdownAsync());
var fresh = new RecipeEditorViewModel(); var newConfig = new SopConfig(); newConfig.Sop.Name = "新配方";
fresh.OnDialogOpened(new DialogParameters { { "directory", store.RecipesDirectory }, { "config", newConfig }, { "new", true } });
Check(!fresh.HasSopRecording, "Unsaved recipes cannot record into an ambiguous directory");
@ -166,6 +196,11 @@ internal static class Program
while (!task.IsCompleted && wait.Elapsed < TimeSpan.FromSeconds(5)) { Dispatcher.UIThread.RunJobs(); Thread.Sleep(1); }
Check(task.IsCompleted, "Camera shutdown completes"); task.GetAwaiter().GetResult();
}
private static void PumpFor(int milliseconds)
{
using var cancellation = new CancellationTokenSource(milliseconds);
Dispatcher.UIThread.MainLoop(cancellation.Token);
}
private static void CheckVideo(string path, double expectedSeconds)
{
using var video = new VideoCapture(path);