新增配方SOP流程录像页并支持暂停继续及确认重录

This commit is contained in:
tfarcraw 2026-11-10 10:01:37 +08:00
parent 6a6d8dcac7
commit 86e6b6100b
8 changed files with 328 additions and 19 deletions

View File

@ -44,10 +44,13 @@ Windows Python 环境使用 `tools/Setup-Python.ps1 -Sam2`;Linux 环境和部
## 操作流程
1. 接好 UVC 或海康相机,选择设备和配方,应用后开始检测。
2. 配方编辑器包含步骤、区域、全局设置、零件列表、检测模型五个标签页;区域坐标使用原图像素。
2. 配方编辑器包含步骤、区域、全局设置、零件列表、检测模型、SOP流程视频六个标签页;区域坐标使用原图像素。
- 零件名称只在“零件列表”维护,随配方保存到 `sop.parts`。标注类别、步骤目标类别、必留物品和完成必需物品均从该列表选择。
- 旧配方首次编辑时汇总已有训练类别、模型配置、步骤和标注项目名称;保存后列表成为唯一来源。重名、空名以及删除仍被步骤或标注项目引用的名称会阻止保存。
- 检测模型的类别表只读;维护零件列表不会更改已训练模型的类别映射。模型输出类别仍以训练版本为准。
- “SOP流程视频”页录制当前配方的完整标准操作,固定保存到 `recipes/配方名/sop_stand/sop.avi`,与零件训练录像分开存放。新配方先保存,再选择相机、开启预览并开始录像。
- 支持暂停、继续和停止保存;暂停时间不计入视频,累计有效录像最长 5 分钟,到时自动保存并弹窗。关闭编辑窗口也会停止并保存录像。
- 每份配方保留一段标准视频;“重新录制”先弹窗确认,确认后删除旧视频并重新开始,取消会保留原视频。录制中发起重新录制时会先暂停,取消后恢复原先的录制状态。
3. 零件标注与训练包含相机录像、视频导入、画框、SAM2 传播、复核、数据集导出、YOLO 训练和 ONNX 导出。
- 每段相机录像最长 5 分钟,达到上限后自动停止、保存文件并弹窗提示保存位置;相机预览继续运行,可再次开始录像。
- 在标注页选择所属配方及已有零件类别,每个视频录入一个零件;录像和导入原视频保存在 `recipes/配方名/recordings`,标注数据保存在同配方的 `parts`。

View File

@ -23,6 +23,7 @@ public sealed class CameraViewModel : BindableBase
private readonly DispatcherTimer _timer;
private readonly string _settingsPath;
private readonly string? _recipeRecordingDirectory;
private readonly bool _sopStandard;
private readonly Stopwatch _previewClock = Stopwatch.StartNew();
private Mat? _latest;
private int _previewPending;
@ -30,6 +31,7 @@ public sealed class CameraViewModel : BindableBase
private long _lastFrameTick;
private volatile bool _closing;
private bool _busy, _previewing, _recording;
private bool _paused;
private string _status = "刷新设备列表,选择相机后开启预览";
private string _directory;
private string _lastRecording = "";
@ -47,6 +49,11 @@ public sealed class CameraViewModel : BindableBase
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<Task<bool>>? ConfirmRestartAsync { get; set; }
public bool CanChooseCamera => !IsBusy && !IsPreviewing && !_closing;
public bool CanChangeDirectory => _recipeRecordingDirectory is null && !IsBusy && !IsRecording && !_closing;
public string PreviewButtonText => IsPreviewing ? "关闭相机" : "开启相机预览";
@ -60,16 +67,20 @@ public sealed class CameraViewModel : BindableBase
public DelegateCommand RecordCommand { get; }
public DelegateCommand BrowseCommand { get; }
public DelegateCommand RevealCommand { get; }
public DelegateCommand PauseCommand { get; }
public DelegateCommand RestartCommand { get; }
public event Action<string>? RecordingLimitReached;
public CameraViewModel(ICameraService camera, string root, string? recipeName = null, TimeProvider? timeProvider = null)
public CameraViewModel(ICameraService camera, string root, string? recipeName = null, TimeProvider? timeProvider = null, bool sopStandard = false)
{
_recorder = new VideoRecorder(timeProvider);
_camera = camera; _dispatcher = Dispatcher.CurrentDispatcher;
var recipeDirectory = string.IsNullOrWhiteSpace(recipeName) ? null : new SopHelper.Engine.Training.RecipeWorkspace(root).DirectoryFor(recipeName);
_recipeRecordingDirectory = recipeDirectory is null ? null : Path.Combine(recipeDirectory, "recordings");
_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, "camera-settings.json");
_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);
@ -77,7 +88,9 @@ public sealed class CameraViewModel : BindableBase
catch (Exception e) { Status = "录像目录配置读取失败:" + e.Message; }
RefreshCommand = Command(RefreshAsync, () => CanChooseCamera);
PreviewCommand = Command(TogglePreviewAsync, () => !IsBusy && !_closing && (IsPreviewing || SelectedCamera != null));
RecordCommand = Command(ToggleRecordingAsync, () => !IsBusy && !_closing && (IsRecording || (IsPreviewing && Preview != null && HasRecentFrame)));
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);
BrowseCommand = Command(async () =>
{
var picker = new OpenFolderDialog { Title = "选择录像保存目录" };
@ -103,6 +116,7 @@ public sealed 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 = "已有标准操作录像;如需替换,请开启相机后点击“重新录制”"; }
}
private DelegateCommand Command(Func<Task> action, Func<bool> canExecute)
@ -123,6 +137,7 @@ public sealed class CameraViewModel : BindableBase
{
RaisePropertyChanged(nameof(CanChooseCamera)); RaisePropertyChanged(nameof(CanChangeDirectory));
RaisePropertyChanged(nameof(PreviewButtonText)); RaisePropertyChanged(nameof(RecordButtonText)); UpdateCommands();
RaisePropertyChanged(nameof(PauseButtonText)); RaisePropertyChanged(nameof(HasStandardVideo));
}
private async Task RefreshAsync()
{
@ -156,6 +171,7 @@ public sealed class CameraViewModel : BindableBase
private Task ToggleRecordingAsync()
{
if (IsRecording) { StopRecording(); 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();
@ -163,21 +179,53 @@ public sealed class CameraViewModel : BindableBase
{
if (_latest == null || !_camera.IsGrabbing) throw new InvalidOperationException("尚未收到相机画面,请先开启预览");
if (Stopwatch.GetElapsedTime(_lastFrameTick).TotalSeconds > 2) throw new IOException("超过2秒未收到相机画面,请重新连接后再录像");
LastRecording = _recorder.Start(directory, _latest, RecordingFps);
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();
if (!SopHelper.Engine.Training.RecipeWorkspace.IsWithin(StandardVideoPath, _recipeRecordingDirectory!))
throw new IOException("SOP录像路径不在当前配方目录中");
File.Delete(StandardVideoPath);
LastRecording = "";
StateChanged();
await ToggleRecordingAsync();
}
private void StopRecording()
{
RecordingResult? result;
try { lock (_frames) result = _recorder.Stop(); }
finally { IsRecording = false; }
finally { IsRecording = false; IsPaused = false; }
if (result != null)
{
LastRecording = result.Path;
RecordingInfo = $"已保存 · {result.Duration.TotalSeconds:F1} 秒 · {result.Frames} 帧";
Status = "录像已保存,可在主窗口导入视频继续标注";
Status = _sopStandard ? "SOP流程视频已保存到当前配方的 sop_stand 目录" : "录像已保存,可在主窗口导入视频继续标注";
}
}
private void OnFrame(CameraFrame frame)
@ -208,7 +256,7 @@ public sealed class CameraViewModel : BindableBase
if (recordingError != null)
{
var error = recordingError;
Post(() => { IsRecording = false; Status = error; RecordingInfo = "录像中断,请检查日志提示"; });
Post(() => { IsRecording = false; IsPaused = false; Status = error; RecordingInfo = "录像中断,请检查日志提示"; });
}
if (preview != null)
{
@ -263,7 +311,7 @@ public sealed class CameraViewModel : BindableBase
StopRecording(); Status = "超过2秒未收到相机画面,录像已结束,请检查相机连接";
}
else if (!_recorder.IsRecording) IsRecording = false;
else RecordingInfo = $"● 正在录像 {_recorder.Elapsed:hh\\:mm\\:ss} / 00:05:00 · {RecordingFps:F0} fps";
else RecordingInfo = $"{(IsPaused ? "Ⅱ 已暂停" : "● 正在录像")} {_recorder.Elapsed:hh\\:mm\\:ss} / 00:05:00 · {RecordingFps:F0} fps";
}
if (IsPreviewing && !_camera.IsGrabbing && !IsBusy)
{

View File

@ -440,6 +440,37 @@
</StackPanel>
</StackPanel>
</TabItem>
<TabItem Header="SOP流程视频">
<Grid Margin="10" RowDefinitions="Auto,*">
<TextBlock Text="录制完整标准操作流程,视频单独保存在当前配方的 sop_stand 目录。暂停期间不计时,累计录制最长5分钟。新配方请先保存。" TextWrapping="Wrap" Margin="0,0,0,10" />
<Grid Grid.Row="1" DataContext="{Binding SopRecording}" IsVisible="{Binding DataContext.HasSopRecording, RelativeSource={RelativeSource AncestorType=UserControl}}" RowDefinitions="Auto,*,Auto,Auto,Auto">
<Grid ColumnDefinitions="*,Auto,Auto" Margin="0,0,0,10">
<ComboBox ItemsSource="{Binding Cameras}" SelectedItem="{Binding SelectedCamera, Converter={StaticResource SelectionConverter}}" IsEnabled="{Binding CanChooseCamera}" Margin="0,0,8,0">
<ComboBox.ItemTemplate><DataTemplate><TextBlock Text="{Binding Name}" /></DataTemplate></ComboBox.ItemTemplate>
</ComboBox>
<Button Grid.Column="1" Content="刷新相机" Command="{Binding RefreshCommand}" Margin="0,0,8,0" />
<Button Grid.Column="2" Content="{Binding PreviewButtonText}" Command="{Binding PreviewCommand}" />
</Grid>
<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" />
</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>
<StackPanel Grid.Row="3" Spacing="6">
<TextBlock Text="{Binding RecordingInfo}" />
<TextBlock Text="{Binding Status}" TextWrapping="Wrap" />
</StackPanel>
<TextBlock Grid.Row="4" Text="{Binding StandardVideoPath}" Foreground="{StaticResource FgDim}" TextWrapping="Wrap" Margin="0,8,0,0" />
</Grid>
</Grid>
</TabItem>
</TabControl>
<Grid Grid.Row="2" Margin="0,10,0,0">
<Grid.ColumnDefinitions>

View File

@ -1,4 +1,90 @@
using Avalonia.Controls;
using Avalonia.Threading;
using System.ComponentModel;
using SopHelper.Training;
namespace SopHelper.VVMs.RecipeEditor;
public partial class RecipeEditor : UserControl
{ public RecipeEditor() { InitializeComponent(); } }
{
private RecipeEditorViewModel? _model;
private CameraViewModel? _recording;
private Window? _host, _dialog;
private bool _closing, _closedSafely;
public RecipeEditor()
{
InitializeComponent();
DataContextChanged += (_, _) => BindModel();
AttachedToVisualTree += (_, _) =>
{
BindModel();
if (_host is null && TopLevel.GetTopLevel(this) is Window host) { _host = host; host.Closing += Closing; }
};
DetachedFromVisualTree += (_, _) =>
{
if (_host is not null) _host.Closing -= Closing;
_host = null;
UnbindRecording();
if (_model is not null) { _model.PropertyChanged -= ModelChanged; _ = _model.ShutdownSopRecordingAsync(); }
};
}
private void BindModel()
{
if (!ReferenceEquals(_model, DataContext))
{
if (_model is not null) _model.PropertyChanged -= ModelChanged;
_model = DataContext as RecipeEditorViewModel;
if (_model is not null) _model.PropertyChanged += ModelChanged;
}
BindRecording();
}
private void ModelChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(RecipeEditorViewModel.SopRecording)) BindRecording();
}
private void UnbindRecording()
{
if (_recording is null) return;
_recording.ConfirmRestartAsync = null;
_recording.RecordingLimitReached -= RecordingLimit;
_recording = null;
}
private void BindRecording()
{
if (ReferenceEquals(_recording, _model?.SopRecording)) return;
UnbindRecording();
_recording = _model?.SopRecording;
if (_recording is null) return;
_recording.ConfirmRestartAsync = () => ShowNotice("确认重新录制", "重新录制将删除当前配方已有的SOP流程视频,删除后无法恢复。是否删除旧视频并立即重新录制?", true);
_recording.RecordingLimitReached += RecordingLimit;
}
private async void RecordingLimit(string message) => await ShowNotice("录像时长提示", message, false);
private async Task<bool> ShowNotice(string title, string message, bool confirmation)
{
if (_closing || _dialog is not null || TopLevel.GetTopLevel(this) is not Window owner) return false;
var actions = new StackPanel { Orientation = Avalonia.Layout.Orientation.Horizontal, HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right, Spacing = 8 };
var accept = new Button { Content = confirmation ? "删除旧视频并重新录制" : "确定", IsDefault = !confirmation };
var dialog = new Window { Title = title, Width = 480, SizeToContent = SizeToContent.Height, CanResize = false, WindowStartupLocation = WindowStartupLocation.CenterOwner,
Content = new StackPanel { Margin = new Avalonia.Thickness(20), Spacing = 18, Children = { new TextBlock { Text = message, TextWrapping = Avalonia.Media.TextWrapping.Wrap }, actions } } };
if (confirmation)
{
var cancel = new Button { Content = "取消", IsCancel = true, IsDefault = true };
cancel.Click += (_, _) => dialog.Close(false); actions.Children.Add(cancel);
}
accept.Click += (_, _) => dialog.Close(true); actions.Children.Add(accept);
_dialog = dialog;
try { return await dialog.ShowDialog<bool>(owner); }
finally { _dialog = null; }
}
private async void Closing(object? sender, WindowClosingEventArgs e)
{
if (_closedSafely || _model?.SopRecording is null) return;
if (_closing) { e.Cancel = true; return; }
_closing = true; _dialog?.Close(false);
var shutdown = _model.ShutdownSopRecordingAsync();
// The Close command already awaited shutdown. Let Prism finish that close in one pass.
if (shutdown.IsCompleted) { _closedSafely = true; return; }
e.Cancel = true;
await shutdown;
_closedSafely = true;
if (sender is Window host) Dispatcher.UIThread.Post(host.Close);
}
}

View File

@ -27,6 +27,7 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
private Action<string>? _onSaved;
private readonly HashSet<EditorNode> _observedStepNodes = [];
private string _saveStatus = "";
private bool _closingDialog;
public string SaveStatus { get => _saveStatus; private set => SetProperty(ref _saveStatus, value); }
public string NameValidationMessage => RecipeWorkspace.GetNameError(Recipe.Name) ?? "";
@ -35,6 +36,9 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
private bool _isCapturing;
private ICameraService? _camera;
private CameraInfo? _cameraInfo;
private SopHelper.Training.CameraViewModel? _sopRecording;
public SopHelper.Training.CameraViewModel? SopRecording { get => _sopRecording; private set => SetProperty(ref _sopRecording, value); }
public bool HasSopRecording => SopRecording is not null;
public BitmapSource? PreviewImage { get => _previewImage; private set => SetProperty(ref _previewImage, value); }
public string PreviewStatus { get => _previewStatus; private set => SetProperty(ref _previewStatus, value); }
@ -94,7 +98,11 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
public RecipeEditorViewModel()
{
SaveCommand = new DelegateCommand(Save, () => !IsCapturing && NameValidationMessage.Length == 0);
CloseCommand = new DelegateCommand(() => RequestClose.Invoke(ButtonResult.Cancel), () => !IsCapturing);
CloseCommand = new DelegateCommand(async () =>
{
_closingDialog = true; CloseCommand.RaiseCanExecuteChanged();
await ShutdownSopRecordingAsync(); RequestClose.Invoke(ButtonResult.Cancel);
}, () => !IsCapturing && !_closingDialog);
CaptureImageCommand = new DelegateCommand(async () => await CaptureImageAsync(),
() => !IsCapturing && _camera is not null && _cameraInfo is not null);
OpenImageCommand = new DelegateCommand(OpenImage, () => !IsCapturing);
@ -127,6 +135,7 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
foreach (var name in partNames)
Recipe.Parts.Items.Add(new TextItem { Text = name, RemoveCommand = Recipe.Parts.RemoveCommand });
Recipe.Changed += RefreshWarnings;
InitializeSopRecording();
RefreshWarnings();
}
@ -137,12 +146,29 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
/// <inheritdoc />
public void OnDialogClosed()
{
_ = ShutdownSopRecordingAsync();
Recipe.Changed -= RefreshWarnings;
foreach (var node in _observedStepNodes) node.PropertyChanged -= StepChanged;
_observedStepNodes.Clear();
_onSaved = null;
}
private void InitializeSopRecording()
{
if (SopRecording is not null || string.IsNullOrEmpty(_path) || !File.Exists(_path)) return;
// Use a separate camera service so SOP capture cannot dispose the operator page's service.
var recipeDirectory = Path.GetDirectoryName(_path)!;
var root = Path.GetDirectoryName(Path.GetDirectoryName(recipeDirectory)!)!;
SopRecording = new SopHelper.Training.CameraViewModel(new CameraService(), root, Path.GetFileNameWithoutExtension(_path), sopStandard: true);
RaisePropertyChanged(nameof(HasSopRecording));
}
public async Task ShutdownSopRecordingAsync()
{
if (SopRecording is null) return;
try { await SopRecording.ShutdownAsync(); }
catch (Exception error) { SaveStatus = "关闭SOP录像时出错:" + error.Message; }
}
private void DescribeImage(string source) => PreviewStatus =
$"{source} · {PreviewImage!.PixelWidth} × {PreviewImage.PixelHeight} 像素;选中区域后拖动画框,Esc 取消";
@ -289,6 +315,7 @@ public class RecipeEditorViewModel : BindableBase, IDialogAware
_path = path;
_isNew = false;
Recipe.MarkSaved(Path.GetFileNameWithoutExtension(path));
InitializeSopRecording();
RaisePropertyChanged(nameof(FileNameText));
RaisePropertyChanged(nameof(Title));

View File

@ -14,6 +14,8 @@ public sealed class VideoRecorder : IDisposable
private readonly object _gate = new();
private readonly TimeProvider _timeProvider;
private long _startedAt;
private long? _pausedAt;
private TimeSpan _pausedDuration;
private VideoWriter? _writer;
private Mat? _previous;
private string _path = "";
@ -21,13 +23,15 @@ public sealed class VideoRecorder : IDisposable
private double _fps;
private Size _size;
public bool IsRecording { get { lock (_gate) return _writer != null; } }
public TimeSpan Elapsed { get { lock (_gate) return _writer != null ? _timeProvider.GetElapsedTime(_startedAt) : TimeSpan.Zero; } }
public TimeSpan Elapsed { get { lock (_gate) return _writer != null ? ActiveElapsed : TimeSpan.Zero; } }
public bool IsPaused { get { lock (_gate) return _writer != null && _pausedAt.HasValue; } }
private TimeSpan ActiveElapsed => _timeProvider.GetElapsedTime(_startedAt, _pausedAt ?? _timeProvider.GetTimestamp()) - _pausedDuration;
public string CurrentPath { get { lock (_gate) return _path; } }
public VideoRecorder(TimeProvider? timeProvider = null) => _timeProvider = timeProvider ?? TimeProvider.System;
private long MaximumFrames => (long)Math.Floor(MaximumDuration.TotalSeconds * _fps);
public string Start(string directory, Mat initialFrame, double fps = 30)
public string Start(string directory, Mat initialFrame, double fps = 30, string? fileName = null)
{
lock (_gate)
{
@ -39,7 +43,10 @@ public sealed class VideoRecorder : IDisposable
throw new ArgumentException("录像画面宽高需为偶数,请调整相机分辨率");
directory = Path.GetFullPath(directory);
Directory.CreateDirectory(directory);
var path = Path.Combine(directory, $"part-{DateTime.Now:yyyyMMdd-HHmmss-fff}-{Guid.NewGuid():N}.avi");
if (fileName is not null && (string.IsNullOrWhiteSpace(fileName) || fileName != Path.GetFileName(fileName)))
throw new ArgumentException("录像文件名不能包含目录");
var path = Path.Combine(directory, fileName ?? $"part-{DateTime.Now:yyyyMMdd-HHmmss-fff}-{Guid.NewGuid():N}.avi");
if (File.Exists(path)) throw new IOException("录像已存在,请确认重新录制后再覆盖");
var writer = new VideoWriter();
Mat? previous = null;
try
@ -50,6 +57,7 @@ public sealed class VideoRecorder : IDisposable
writer.Write(initialFrame);
_size = initialFrame.Size(); _fps = fps; _path = path; _frames = 1;
_previous = previous; _writer = writer; _startedAt = _timeProvider.GetTimestamp();
_pausedAt = null; _pausedDuration = TimeSpan.Zero;
return path;
}
catch
@ -65,7 +73,7 @@ public sealed class VideoRecorder : IDisposable
{
lock (_gate)
{
if (_writer == null) return;
if (_writer == null || _pausedAt.HasValue) return;
try
{
ValidateFrame(frame);
@ -86,6 +94,22 @@ public sealed class VideoRecorder : IDisposable
{
lock (_gate) return StopCore(flushTail: true);
}
public void Pause()
{
lock (_gate)
{
if (_writer is not null && !_pausedAt.HasValue) _pausedAt = _timeProvider.GetTimestamp();
}
}
public void Resume()
{
lock (_gate)
{
if (_writer is null || _pausedAt is not { } pausedAt) return;
_pausedDuration += _timeProvider.GetElapsedTime(pausedAt);
_pausedAt = null;
}
}
private RecordingResult? StopCore(bool flushTail)
{
if (_writer == null) return null;
@ -94,13 +118,14 @@ public sealed class VideoRecorder : IDisposable
try
{
// Finalize at the wall-clock stop time, including the interval after the last camera frame.
var target = Math.Min((long)Math.Ceiling(_timeProvider.GetElapsedTime(_startedAt).TotalSeconds * _fps), MaximumFrames);
var target = Math.Min((long)Math.Ceiling(ActiveElapsed.TotalSeconds * _fps), MaximumFrames);
if (flushTail && target - _frames <= _fps * 2)
while (_frames < target) { writer.Write(_previous!); _frames++; }
return new RecordingResult(_path, _frames, _fps);
}
finally
{
_pausedAt = null;
try { writer.Dispose(); }
finally { _previous?.Dispose(); _previous = null; }
}

View File

@ -117,8 +117,13 @@ internal static class Smoke
sop.EditRecipeCommand.Execute();await Task.Delay(150);
var modal=lifetime.Windows.OfType<RecipeDialogWindow>().Single();
Check(modal.Width==1040&&modal.Height==760&&modal.DataContext is RecipeEditorViewModel,"Original edit command opens the sized Prism recipe dialog");
((RecipeEditorViewModel)modal.DataContext!).CloseCommand.Execute();await Task.Delay(80);
((RecipeEditorViewModel)modal.DataContext!).CloseCommand.Execute();
for(var i=0;i<100&&lifetime.Windows.Contains(modal);i++)await Task.Delay(20);
Check(!lifetime.Windows.Contains(modal),"Recipe close command respects the Prism dialog lifecycle");
sop.EditRecipeCommand.Execute();await Task.Delay(150);
var titlebarModal=lifetime.Windows.OfType<RecipeDialogWindow>().Single();titlebarModal.Close();
for(var i=0;i<100&&lifetime.Windows.Contains(titlebarModal);i++)await Task.Delay(20);
Check(!lifetime.Windows.Contains(titlebarModal),"Titlebar close awaits SOP camera shutdown and closes the Prism dialog");
navigation.SelectedIndex=1;await Task.Delay(150);Save(window,"training");
Check(window.GetVisualDescendants().OfType<TrainingPage>().Any(),"Training page navigates");
var trainer=app.Container.Resolve<SopHelper.Training.MainViewModel>();
@ -215,7 +220,7 @@ internal static class Smoke
var recipeBefore=SopHelper.Engine.Sop.SopConfigLoader.ToYaml(editorVm.Recipe.ToConfig());
var dialog=new Window { Width=1180,Height=820,Content=editor };dialog.Show();await Task.Delay(100);
var tabs=editor.GetVisualDescendants().OfType<TabControl>().First();
Check(tabs.ItemCount==5,"Recipe tabs include the central parts catalog");
Check(tabs.ItemCount==6,"Recipe tabs include the central parts catalog and SOP recording");
for(var i=0;i<tabs.ItemCount;i++){tabs.SelectedIndex=i;await Task.Delay(80);Save(dialog,"recipe-"+i);}
Check(editorVm.Recipe.Steps.Count>0,"Original recipe ViewModel loads steps");
Check(editorVm.Recipe.Steps[0].Detection?.Method=="hand_in_region","Recipe bindings preserve selected condition method");

View File

@ -9,6 +9,10 @@ using Avalonia.VisualTree;
using OpenCvSharp;
using SopHelper.Engine.Camera;
using SopHelper.Training;
using SopHelper.Engine.Sop;
using SopHelper.Engine.Training;
using SopHelper.VVMs.RecipeEditor;
using Prism.Dialogs;
using Window = Avalonia.Controls.Window;
internal static class Program
@ -67,6 +71,7 @@ internal static class Program
while (!shutdown.IsCompleted && wait.Elapsed < TimeSpan.FromSeconds(5)) { Dispatcher.UIThread.RunJobs(); Thread.Sleep(1); }
shutdown.GetAwaiter().GetResult(); Dispatcher.UIThread.RunJobs();
Check(!window.IsVisible, "Closing the camera also closes its notification and releases resources");
RunSopRecording(root);
}
finally
{
@ -74,6 +79,85 @@ internal static class Program
}
}
private static void Tick(CameraViewModel model) => typeof(CameraViewModel).GetMethod("Tick", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(model, null);
private static void RunSopRecording(string root)
{
var store = new RecipeWorkspace(root);
var config = new SopConfig(); config.Sop.Name = "标准流程"; config.Sop.Parts = [];
Directory.CreateDirectory(store.DirectoryFor(config.Sop.Name)); SopConfigLoader.Save(config, store.ConfigPath(config.Sop.Name));
var vm = new RecipeEditorViewModel();
vm.OnDialogOpened(new DialogParameters { { "directory", store.RecipesDirectory }, { "path", store.ConfigPath(config.Sop.Name) }, { "config", config }, { "new", false } });
Pump(vm.ShutdownSopRecordingAsync());
var clock = new ManualClock(); using var camera = new FakeCamera();
var model = new CameraViewModel(camera, root, config.Sop.Name, clock, sopStandard: true);
// Substitute the camera at the presentation boundary; never open real test hardware.
typeof(RecipeEditorViewModel).GetProperty(nameof(vm.SopRecording))!.SetValue(vm, model);
var editor = new RecipeEditor { DataContext = vm };
var window = new Window { Content = editor, Width = 1180, Height = 820 }; window.Show(); window.UpdateLayout();
var tabs = editor.GetVisualDescendants().OfType<TabControl>().Single(); tabs.SelectedIndex = 5; window.UpdateLayout();
Check(tabs.ItemCount == 6 && ((TabItem)tabs.Items[5]!).Header?.ToString() == "SOP流程视频", "Recipe editor contains the SOP recording page");
model.RefreshCommand.Execute(); model.PreviewCommand.Execute(); Thread.Sleep(75); camera.Emit(); Dispatcher.UIThread.RunJobs();
model.RecordCommand.Execute();
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();
model.PauseCommand.Execute();
clock.Advance(TimeSpan.FromMinutes(10)); camera.Emit(); Tick(model);
Check(model.IsRecording && model.IsPaused && model.RecordingInfo.Contains("00:00:01"), "Paused time does not advance the recording or trigger the five-minute limit");
model.RestartCommand.Execute(); FindSopDialog(editor).Close(false); PumpIdle(model);
Check(model.IsPaused && model.IsRecording, "Cancelling replacement preserves an intentionally paused recording");
model.PauseCommand.Execute(); clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit();
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.RestartCommand.Execute();
var dialog = FindSopDialog(editor);
Check(dialog.Title == "确认重新录制" && File.ReadAllBytes(expectedPath).SequenceEqual(original), "Re-record opens confirmation before changing the old video");
dialog.Close(false); PumpIdle(model);
Check(!model.IsRecording && File.ReadAllBytes(expectedPath).SequenceEqual(original), "Cancelling confirmation preserves the old video exactly");
model.RestartCommand.Execute(); FindSopDialog(editor).Close(true); PumpIdle(model);
Check(model.IsRecording && model.LastRecording == expectedPath, "Confirming starts a new recording at the standard path");
Check(Directory.GetFiles(Path.GetDirectoryName(expectedPath)!, "*.avi").Length == 1, "Re-recording keeps only one standard video");
clock.Advance(TimeSpan.FromMilliseconds(500)); camera.Emit();
model.RestartCommand.Execute();
Check(model.IsPaused, "Active recording pauses while replacement confirmation is open");
clock.Advance(TimeSpan.FromMinutes(6)); camera.Emit();
FindSopDialog(editor).Close(false); PumpIdle(model);
Check(model.IsRecording && !model.IsPaused, "Cancelling replacement resumes a previously active recording");
clock.Advance(TimeSpan.FromMilliseconds(500)); camera.Emit();
window.Close(); Pump(vm.ShutdownSopRecordingAsync()); Dispatcher.UIThread.RunJobs();
Check(!window.IsVisible && !model.IsRecording, "Closing the editor stops and finalizes the SOP video");
CheckVideo(expectedPath, 1);
Check(!File.ReadAllBytes(expectedPath).SequenceEqual(original), "Confirmed re-record replaces the prior video");
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");
Pump(reopened.ShutdownAsync());
var other = new CameraViewModel(new FakeCamera(), root, "另一配方", sopStandard: true);
Check(!other.HasStandardVideo && other.StandardVideoPath != expectedPath, "SOP recordings are isolated between recipes"); 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");
fresh.SaveCommand.Execute(); Check(fresh.HasSopRecording, "Saving a new recipe enables its SOP recording page");
Pump(fresh.ShutdownSopRecordingAsync()); fresh.OnDialogClosed();
}
private static Window FindSopDialog(RecipeEditor editor)
{
Dispatcher.UIThread.RunJobs();
var dialog = (Window?)typeof(RecipeEditor).GetField("_dialog", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(editor);
Check(dialog is { IsVisible: true }, "Replacement confirmation is visible"); return dialog!;
}
private static void PumpIdle(CameraViewModel model)
{
var wait = System.Diagnostics.Stopwatch.StartNew();
while (model.IsBusy && wait.Elapsed < TimeSpan.FromSeconds(5)) { Dispatcher.UIThread.RunJobs(); Thread.Sleep(1); }
Check(!model.IsBusy, "Recording operation completes after the dialog closes");
}
private static void Pump(Task task)
{
var wait = System.Diagnostics.Stopwatch.StartNew();
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 CheckVideo(string path, double expectedSeconds)
{
using var video = new VideoCapture(path);