限制相机录像最长五分钟并在自动停止后弹窗提示

This commit is contained in:
tfarcraw 2026-11-10 09:42:57 +08:00
parent 6cdf51ee15
commit 6a6d8dcac7
7 changed files with 188 additions and 17 deletions

View File

@ -49,6 +49,7 @@ Windows Python 环境使用 `tools/Setup-Python.ps1 -Sam2`;Linux 环境和部
- 旧配方首次编辑时汇总已有训练类别、模型配置、步骤和标注项目名称;保存后列表成为唯一来源。重名、空名以及删除仍被步骤或标注项目引用的名称会阻止保存。
- 检测模型的类别表只读;维护零件列表不会更改已训练模型的类别映射。模型输出类别仍以训练版本为准。
3. 零件标注与训练包含相机录像、视频导入、画框、SAM2 传播、复核、数据集导出、YOLO 训练和 ONNX 导出。
- 每段相机录像最长 5 分钟,达到上限后自动停止、保存文件并弹窗提示保存位置;相机预览继续运行,可再次开始录像。
- 在标注页选择所属配方及已有零件类别,每个视频录入一个零件;录像和导入原视频保存在 `recipes/配方名/recordings`,标注数据保存在同配方的 `parts`。
- 点击“训练并更新配方模型”,自动累计导出该配方所有已加入视频的复核数据,并使用上一版配方模型开始新训练;首次使用 `yolo11n.pt`。无需手选权重。
- 同名零件的多个视频共用类别,训练导出按零件列表顺序分配类别编号,并拒绝列表以外的项目类别。每个视频均需完成足够的训练段和末尾验证段复核。
@ -82,6 +83,7 @@ Windows Python 环境使用 `tools/Setup-Python.ps1 -Sam2`;Linux 环境和部
```powershell
dotnet run --project tests/Avalonia.Smoke -c Release
dotnet run --project tests/PartCatalog.Smoke -c Release
dotnet run --project tests/RecordingLimit.Smoke -c Release
python/python.exe tests/Training.Smoke/test_recipe_training.py
dotnet run --project tests/OpenCv.Smoke -c Release
dotnet run --project tests/HandednessSmoke -c Release

View File

@ -17,7 +17,7 @@ namespace SopHelper.Training;
public sealed class CameraViewModel : BindableBase
{
private readonly ICameraService _camera;
private readonly VideoRecorder _recorder = new();
private readonly VideoRecorder _recorder;
private readonly object _frames = new();
private readonly Dispatcher _dispatcher;
private readonly DispatcherTimer _timer;
@ -60,9 +60,11 @@ public sealed class CameraViewModel : BindableBase
public DelegateCommand RecordCommand { get; }
public DelegateCommand BrowseCommand { get; }
public DelegateCommand RevealCommand { get; }
public event Action<string>? RecordingLimitReached;
public CameraViewModel(ICameraService camera, string root, string? recipeName = null)
public CameraViewModel(ICameraService camera, string root, string? recipeName = null, TimeProvider? timeProvider = null)
{
_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");
@ -163,14 +165,14 @@ public sealed class CameraViewModel : BindableBase
if (Stopwatch.GetElapsedTime(_lastFrameTick).TotalSeconds > 2) throw new IOException("超过2秒未收到相机画面,请重新连接后再录像");
LastRecording = _recorder.Start(directory, _latest, RecordingFps);
}
IsRecording = true; Status = "正在录像,点击“停止录像”保存文件"; Tick();
IsRecording = true; Status = "正在录像,最长5分钟;到时自动停止并保存"; Tick();
return Task.CompletedTask;
}
private void StopRecording()
{
RecordingResult? result;
lock (_frames) result = _recorder.Stop();
IsRecording = false;
try { lock (_frames) result = _recorder.Stop(); }
finally { IsRecording = false; }
if (result != null)
{
LastRecording = result.Path;
@ -240,12 +242,28 @@ public sealed class CameraViewModel : BindableBase
if (_closing) return;
if (IsRecording)
{
if (Stopwatch.GetElapsedTime(Interlocked.Read(ref _lastFrameTick)).TotalSeconds > 2)
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 = $"● 正在录像 {_recorder.Elapsed:hh\\:mm\\:ss} · {RecordingFps:F0} fps";
else RecordingInfo = $"● 正在录像 {_recorder.Elapsed:hh\\:mm\\:ss} / 00:05:00 · {RecordingFps:F0} fps";
}
if (IsPreviewing && !_camera.IsGrabbing && !IsBusy)
{

View File

@ -55,10 +55,10 @@
</Grid>
<DockPanel>
<Button DockPanel.Dock="Left" Content="{Binding RecordButtonText}" Command="{Binding RecordCommand}" BorderBrush="{StaticResource Accent}" MinWidth="130" />
<TextBlock Text="AVI / MJPEG · 30 fps · 原始画面,不含标注和界面" Foreground="{StaticResource Dim}" Margin="12,0,0,6" />
<TextBlock Text="AVI / MJPEG · 30 fps · 最长5分钟,到时自动停止并提示" Foreground="{StaticResource Dim}" Margin="12,0,0,6" />
</DockPanel>
<TextBlock Text="{Binding LastRecording}" TextTrimming="CharacterEllipsis" Foreground="{StaticResource Dim}" Margin="0,0,0,8" ToolTip.Tip="{Binding LastRecording}" />
</StackPanel>
<TextBlock Grid.Row="4" Text="{Binding Status}" TextWrapping="Wrap" Margin="0,8,0,0" />
</Grid>
</Window>
</Window>

View File

@ -6,10 +6,36 @@ public partial class CameraWindow : Window
{
public CameraViewModel Model { get; }
private bool _closedSafely,_closeRequested;
public CameraWindow(CameraViewModel model){InitializeComponent();Model=model;DataContext=model;Closing+=OnSafeClosing;}
private Window? _recordingLimitDialog;
public CameraWindow(CameraViewModel model)
{
InitializeComponent();Model=model;DataContext=model;Closing+=OnSafeClosing;
Model.RecordingLimitReached+=ShowRecordingLimit;
Closed+=(_,_)=>Model.RecordingLimitReached-=ShowRecordingLimit;
}
private async void ShowRecordingLimit(string message)
{
if(_closeRequested || !IsVisible || _recordingLimitDialog is not null)return;
var confirm=new Button { Content="确定",HorizontalAlignment=Avalonia.Layout.HorizontalAlignment.Right,MinWidth=80 };
var dialog=new Window
{
Title="录像时长提示",Width=460,SizeToContent=SizeToContent.Height,CanResize=false,
WindowStartupLocation=WindowStartupLocation.CenterOwner,
Content=new StackPanel
{
Margin=new Avalonia.Thickness(20),Spacing=16,
Children={new TextBlock { Text=message,TextWrapping=Avalonia.Media.TextWrapping.Wrap },confirm}
}
};
confirm.Click+=(_,_)=>dialog.Close();
_recordingLimitDialog=dialog;
try { await dialog.ShowDialog(this); }
finally { _recordingLimitDialog=null; }
}
private async void OnSafeClosing(object? sender,WindowClosingEventArgs e)
{
if(_closedSafely)return;e.Cancel=true;if(_closeRequested)return;_closeRequested=true;IsEnabled=false;
_recordingLimitDialog?.Close();
try{await Model.ShutdownAsync();}catch(Exception error){System.Diagnostics.Trace.TraceError("关闭相机时出错:"+error);}
_closedSafely=true;Dispatcher.UIThread.Post(Close);
}

View File

@ -1,4 +1,3 @@
using System.Diagnostics;
using OpenCvSharp;
namespace SopHelper.Engine.Camera;
@ -11,8 +10,10 @@ public sealed record RecordingResult(string Path, long Frames, double Fps)
/// <summary>Thread-safe, bounded-memory MJPEG recording with wall-clock frame pacing.</summary>
public sealed class VideoRecorder : IDisposable
{
public static readonly TimeSpan MaximumDuration = TimeSpan.FromMinutes(5);
private readonly object _gate = new();
private readonly Stopwatch _clock = new();
private readonly TimeProvider _timeProvider;
private long _startedAt;
private VideoWriter? _writer;
private Mat? _previous;
private string _path = "";
@ -20,9 +21,12 @@ 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 ? _clock.Elapsed : TimeSpan.Zero; } }
public TimeSpan Elapsed { get { lock (_gate) return _writer != null ? _timeProvider.GetElapsedTime(_startedAt) : TimeSpan.Zero; } }
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)
{
lock (_gate)
@ -45,7 +49,7 @@ public sealed class VideoRecorder : IDisposable
previous = initialFrame.Clone();
writer.Write(initialFrame);
_size = initialFrame.Size(); _fps = fps; _path = path; _frames = 1;
_previous = previous; _writer = writer; _clock.Restart();
_previous = previous; _writer = writer; _startedAt = _timeProvider.GetTimestamp();
return path;
}
catch
@ -66,7 +70,8 @@ public sealed class VideoRecorder : IDisposable
{
ValidateFrame(frame);
if (frame.Size() != _size) throw new IOException("相机分辨率发生变化,录像已停止");
var target = (long)Math.Floor(_clock.Elapsed.TotalSeconds * _fps);
// Cap the encoded duration even if the UI's timeout callback is delayed.
var target = Math.Min((long)Math.Floor(Elapsed.TotalSeconds * _fps), MaximumFrames - 1);
if (target - _frames > _fps * 2) throw new IOException("相机帧中断超过2秒,录像已停止");
// Repeat the previous frame for slow cameras; skip excess frames for fast cameras.
while (_frames < target) { _writer.Write(_previous!); _frames++; }
@ -89,14 +94,13 @@ public sealed class VideoRecorder : IDisposable
try
{
// Finalize at the wall-clock stop time, including the interval after the last camera frame.
var target = (long)Math.Ceiling(_clock.Elapsed.TotalSeconds * _fps);
var target = Math.Min((long)Math.Ceiling(_timeProvider.GetElapsedTime(_startedAt).TotalSeconds * _fps), MaximumFrames);
if (flushTail && target - _frames <= _fps * 2)
while (_frames < target) { writer.Write(_previous!); _frames++; }
return new RecordingResult(_path, _frames, _fps);
}
finally
{
_clock.Stop();
try { writer.Dispose(); }
finally { _previous?.Dispose(); _previous = null; }
}

View File

@ -0,0 +1,114 @@
using System.Reflection;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Headless;
using Avalonia.Markup.Xaml.Styling;
using Avalonia.Themes.Fluent;
using Avalonia.Threading;
using Avalonia.VisualTree;
using OpenCvSharp;
using SopHelper.Engine.Camera;
using SopHelper.Training;
using Window = Avalonia.Controls.Window;
internal static class Program
{
[STAThread]
public static void Main()
{
var root = Path.Combine(Path.GetTempPath(), "recording-limit-smoke-" + Guid.NewGuid().ToString("N"));
try
{
AppBuilder.Configure<Application>().UseHeadless(new AvaloniaHeadlessPlatformOptions()).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");
var clock = new ManualClock();
using var camera = new FakeCamera();
var model = new CameraViewModel(camera, root, timeProvider: clock);
var window = new CameraWindow(model); window.Show();
model.RefreshCommand.Execute(); model.PreviewCommand.Execute();
Thread.Sleep(75); camera.Emit(); Dispatcher.UIThread.RunJobs();
Check(model.RecordCommand.CanExecute(), "Preview is ready for recording");
var notices = 0;
model.RecordingLimitReached += message => { notices++; Check(message.Contains("5分钟") && message.Contains(model.LastRecording), "Timeout notice contains the limit and saved path"); };
model.RecordCommand.Execute();
for (var second = 1; second <= 299; second++) { clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit(); }
Tick(model);
Check(model.IsRecording && notices == 0, "Recording continues at 4:59 without a popup");
clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit();
// Simulate a delayed UI callback while the acquisition thread keeps receiving frames.
clock.Advance(TimeSpan.FromMilliseconds(700)); camera.Emit();
Tick(model);
Check(!model.IsRecording && model.IsPreviewing && notices == 1, "Timeout stops recording once and keeps the preview running");
CheckVideo(model.LastRecording, 300);
var popup = (Window?)typeof(CameraWindow).GetField("_recordingLimitDialog", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(window);
Check(popup is { IsVisible: true } && popup.Title == "录像时长提示", "Timeout opens the modal notification");
Check(popup!.GetVisualDescendants().OfType<TextBlock>().Any(t => t.Text?.Contains("5分钟") == true), "Popup displays the five-minute explanation");
Tick(model); Tick(model); Check(notices == 1, "Later timer ticks do not repeat the popup");
popup!.Close(); Dispatcher.UIThread.RunJobs();
model.RecordCommand.Execute();
Check(model.IsRecording, "A second recording starts with a fresh timeout");
clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit(); Tick(model);
Check(model.IsRecording && notices == 1, "Previous recording duration does not carry over");
model.RecordCommand.Execute();
Check(!model.IsRecording && notices == 1, "Manual stop saves without a timeout popup");
CheckVideo(model.LastRecording, 1);
clock.Advance(TimeSpan.FromMinutes(6)); Tick(model);
Check(notices == 1, "Stopped recordings do not later trigger a timeout");
camera.Emit(); model.RecordCommand.Execute();
for (var second = 1; second <= 300; second++) { clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit(); }
Tick(model);
Check(notices == 2 && !model.IsRecording, "A later recording independently stops at its own five-minute limit");
CheckVideo(model.LastRecording, 300);
window.Close();
var shutdown = model.ShutdownAsync();
var wait = System.Diagnostics.Stopwatch.StartNew();
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");
}
finally
{
if (Path.GetFileName(root).StartsWith("recording-limit-smoke-") && Directory.Exists(root)) Directory.Delete(root, true);
}
}
private static void Tick(CameraViewModel model) => typeof(CameraViewModel).GetMethod("Tick", BindingFlags.Instance | BindingFlags.NonPublic)!.Invoke(model, null);
private static void CheckVideo(string path, double expectedSeconds)
{
using var video = new VideoCapture(path);
Check(video.IsOpened(), "Automatically/manual saved AVI can be reopened");
var duration = video.FrameCount / video.Fps;
var tolerance = expectedSeconds == 300 ? .001 : 1 / video.Fps + .001;
Check(Math.Abs(duration - expectedSeconds) < tolerance && duration <= 300, $"Encoded video duration is {expectedSeconds} seconds (within frame precision)");
using var frame = new Mat(); Check(video.Read(frame) && !frame.Empty(), "Saved AVI contains decodable frames");
}
private static void Check(bool value, string message) { if (!value) throw new Exception(message); Console.WriteLine("PASS: " + message); }
}
internal sealed class ManualClock : TimeProvider
{
private long _ticks;
public override long TimestampFrequency => TimeSpan.TicksPerSecond;
public override long GetTimestamp() => _ticks;
public void Advance(TimeSpan duration) => _ticks += duration.Ticks;
}
internal sealed class FakeCamera : ICameraService
{
public bool IsConnected { get; private set; }
public bool IsGrabbing { get; private set; }
public event Action<CameraFrame>? FrameArrived;
public event Action<bool>? ConnectionChanged;
public event Action<string>? Error { add { } remove { } }
public Task<List<CameraInfo>> EnumerateAsync() => Task.FromResult(new List<CameraInfo> { new() { Name = "测试相机" } });
public Task<bool> ConnectAsync(CameraInfo camera) { IsConnected = true; ConnectionChanged?.Invoke(true); return Task.FromResult(true); }
public Task<bool> StartAsync() { IsGrabbing = true; return Task.FromResult(true); }
public void Stop() => IsGrabbing = false;
public void Disconnect() { Stop(); IsConnected = false; ConnectionChanged?.Invoke(false); }
public void Dispose() => Disconnect();
public void Emit()
{
using var frame = new CameraFrame { Bgr = new Mat(48, 64, MatType.CV_8UC3, new Scalar(35, 60, 90)) };
FrameArrived?.Invoke(frame);
}
}

View File

@ -0,0 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
<ItemGroup>
<ProjectReference Include="../../src/SopHelper.Avalonia/SopHelper.Avalonia.csproj" />
<PackageReference Include="Avalonia.Headless" Version="12.1.5" />
</ItemGroup>
</Project>