337 lines
26 KiB
C#
337 lines
26 KiB
C#
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.SopVideo;
|
|
using SopHelper.Engine.Sop;
|
|
using SopHelper.Engine.Training;
|
|
using SopHelper.VVMs.RecipeEditor;
|
|
using Prism.Dialogs;
|
|
using Avalonia.Controls.Primitives;
|
|
using Avalonia.Input;
|
|
using Window = Avalonia.Controls.Window;
|
|
using Point = Avalonia.Point;
|
|
|
|
internal static class Program
|
|
{
|
|
[STAThread]
|
|
public static void Main(string[] args)
|
|
{
|
|
var root = Path.Combine(Path.GetTempPath(), "recording-limit-smoke-" + Guid.NewGuid().ToString("N"));
|
|
var previousRoot = Environment.GetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT");
|
|
Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT", root);
|
|
try
|
|
{
|
|
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") });
|
|
if (!args.Contains("--usb-camera-only")) { CheckRunStatistics(); CheckStandardDuration(root); }
|
|
Check(VideoRecorder.MaximumDuration == TimeSpan.FromMinutes(5), "Production recording limit is five minutes");
|
|
RunSopRecording(root, args.Contains("--usb-camera-only"));
|
|
}
|
|
finally
|
|
{
|
|
Environment.SetEnvironmentVariable("SOPHELPER_WORKSPACE_ROOT", previousRoot);
|
|
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 CheckRecordingButtons(Control view, CameraViewModel model, bool canStart, bool canStop)
|
|
{
|
|
Dispatcher.UIThread.RunJobs();
|
|
var buttons = view.GetVisualDescendants().OfType<Button>().ToArray();
|
|
var start = buttons.Single(b => ReferenceEquals(b.Command, model.StartRecordingCommand));
|
|
var stop = buttons.Single(b => ReferenceEquals(b.Command, model.StopRecordingCommand));
|
|
Check(start.Content?.ToString() == "开始录像" && stop.Content?.ToString() == "停止录像" && start.IsVisible && stop.IsVisible
|
|
&& start.IsEffectivelyEnabled == canStart && stop.IsEffectivelyEnabled == canStop,
|
|
$"Separate recording buttons keep fixed labels and correct availability (start={canStart}, stop={canStop})");
|
|
}
|
|
private static void RunSopRecording(string root, bool usbCameraOnly)
|
|
{
|
|
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();
|
|
CameraInfo? selected = null;
|
|
var model = new CameraViewModel(camera, root, config.Sop.Name, clock, selectedCameraProvider: () => selected);
|
|
// 在界面边界注入假相机,覆盖标准视频操作且避免占用现场设备。
|
|
typeof(RecipeEditorViewModel).GetProperty(nameof(vm.SopRecording))!.SetValue(vm, model);
|
|
var editor = new RecipeEditor { DataContext = vm };
|
|
var window = new Window { Content = editor, Width = 1040, Height = 760 }; window.Show(); window.UpdateLayout();
|
|
var tabs = editor.GetVisualDescendants().OfType<TabControl>().Single(); tabs.SelectedIndex = 1; window.UpdateLayout();
|
|
Check(tabs.ItemCount == 3 && ((TabItem)tabs.Items[1]!).Header?.ToString() == "SOP流程视频", "Recipe editor contains the SOP recording page");
|
|
var previewButton = editor.GetVisualDescendants().OfType<Button>().Single(b => ReferenceEquals(b.Command, model.PreviewCommand));
|
|
var videoButtons = ((Panel)previewButton.Parent!).Children.OfType<Button>().ToArray();
|
|
Check(ReferenceEquals(videoButtons[0].Command, model.PreviewCommand) && ReferenceEquals(videoButtons[1].Command, model.StartRecordingCommand) && ReferenceEquals(videoButtons[^1].Command, model.RevealCommand), "Preview precedes recording and saved location is last");
|
|
Check(videoButtons[^1].TranslatePoint(new Point(videoButtons[^1].Bounds.Width, 0), editor)!.Value.X <= editor.Bounds.Width, "Video controls fit the minimum editor width");
|
|
window.Width = 840; window.UpdateLayout();
|
|
Check(videoButtons.All(b => b.TranslatePoint(new Point(b.Bounds.Width, 0), editor)!.Value.X <= editor.Bounds.Width), "Separate recording buttons wrap within a narrow editor");
|
|
window.Width = 1040; window.UpdateLayout();
|
|
Check(!editor.GetVisualDescendants().OfType<Button>().Any(b => b.Content?.ToString() == "刷新相机"), "SOP page has no independent camera refresh");
|
|
Check(!model.PreviewCommand.CanExecute(), "Recording requires the camera selected in runtime settings");
|
|
selected = new CameraInfo { Index = 3, Name = "全局SOP相机" };
|
|
Tick(model);
|
|
model.PreviewCommand.Execute(); PumpIdle(model); Thread.Sleep(75); camera.Emit(); Dispatcher.UIThread.RunJobs();
|
|
Check(ReferenceEquals(camera.ConnectedCamera, selected) && camera.EnumerationCount == 0, "SOP recording also uses the global camera directly");
|
|
CheckRecordingButtons(editor, model, true, false);
|
|
model.StartRecordingCommand.Execute();
|
|
CheckRecordingButtons(editor, model, false, true);
|
|
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, "SOP video is stored separately under its current recipe");
|
|
if (usbCameraOnly)
|
|
{
|
|
clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit();
|
|
model.StopRecordingCommand.Execute();
|
|
Check(!model.IsRecording && model.IsPreviewing, "USB recording saves while keeping preview active");
|
|
CheckVideo(expectedPath, 1);
|
|
window.Close(); Pump(vm.ShutdownSopRecordingAsync());
|
|
Check(!camera.IsConnected && !camera.IsGrabbing, "Closing USB recording releases the camera");
|
|
vm.OnDialogClosed();
|
|
return;
|
|
}
|
|
// 以虚拟时钟推进录像时限,仍通过配方编辑器验证保存和通知。
|
|
var notices = 0;
|
|
model.RecordingLimitReached += message =>
|
|
{
|
|
notices++;
|
|
Check(message.Contains("5分钟") && message.Contains(expectedPath), "Timeout notice contains the limit and standard video path");
|
|
};
|
|
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 notification");
|
|
clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit(); Tick(model); Tick(model);
|
|
Check(!model.IsRecording && model.IsPreviewing && notices == 1, "Timeout saves once and keeps preview active");
|
|
CheckVideo(expectedPath, 300);
|
|
var limitDialog = (Window?)typeof(RecipeEditor).GetField("_dialog", BindingFlags.Instance | BindingFlags.NonPublic)!.GetValue(editor);
|
|
Check(limitDialog is { IsVisible: true, Title: "录像时长提示" }, "Recipe editor displays the recording limit notification");
|
|
limitDialog!.Close(); PumpFor(20);
|
|
model.RestartCommand.Execute(); FindSopDialog(editor).Close(true); PumpIdle(model);
|
|
model.StartRecordingCommand.Execute();
|
|
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.StopRecordingCommand.Execute(); CheckVideo(model.LastRecording, 2);
|
|
using (var recordedDuration = new VideoCapture(model.LastRecording))
|
|
Check(Math.Abs(SopStandardVideoDuration.Get(store.DirectoryFor(config.Sop.Name)).TotalSeconds - recordedDuration.FrameCount / recordedDuration.Fps) < .000001
|
|
&& File.Exists(Path.Combine(store.DirectoryFor(config.Sop.Name), "sop_stand", "duration.json")), "Stopping standard recording remembers its encoded duration excluding pauses");
|
|
CheckRecordingButtons(editor, model, false, false);
|
|
Check(!model.StartRecordingCommand.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.ToggleVideoPlaybackCommand.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");
|
|
Pump(model.Playback.SeekAsync(80));
|
|
Check(!model.Playback.IsPlaying && Math.Abs(model.Playback.Progress - 80) < 2, "Paused video seeks forward without starting playback");
|
|
Pump(model.Playback.SeekAsync(20));
|
|
Check(!model.Playback.IsPlaying && Math.Abs(model.Playback.Progress - 20) < 2, "Backward seek updates the displayed frame");
|
|
var seekSlider = editor.FindControl<Slider>("VideoSeekSlider")!; window.UpdateLayout();
|
|
var thumb = seekSlider.GetVisualDescendants().OfType<Thumb>().First();
|
|
var start = thumb.TranslatePoint(new Point(thumb.Bounds.Width / 2, thumb.Bounds.Height / 2), window)!.Value;
|
|
var end = seekSlider.TranslatePoint(new Point(seekSlider.Bounds.Width * .6, seekSlider.Bounds.Height / 2), window)!.Value;
|
|
window.MouseDown(start, MouseButton.Left); window.MouseMove(end); window.MouseUp(end, MouseButton.Left);
|
|
var seekWait = System.Diagnostics.Stopwatch.StartNew();
|
|
while (model.Playback.IsSeeking && seekWait.Elapsed < TimeSpan.FromSeconds(5)) { Dispatcher.UIThread.RunJobs(); Thread.Sleep(1); }
|
|
Check(!model.Playback.IsPlaying && model.Playback.Progress is > 50 and < 70, "Dragging the actual slider seeks the paused video");
|
|
Pump(model.Playback.SeekAsync(100));
|
|
Check(model.Playback.IsAtEnd && model.Playback.Progress == 100 && model.DisplayImage is not null, "Seeking to the end shows the last frame");
|
|
Pump(model.Playback.SeekAsync(0));
|
|
Check(!model.Playback.IsAtEnd && model.Playback.Progress == 0 && !model.Playback.IsPlaying, "Seeking from EOF back to the beginning preserves pause");
|
|
model.PlayVideoCommand.Execute(); PumpIdle(model);
|
|
Pump(model.Playback.SeekAsync(80));
|
|
Check(model.Playback.IsPlaying && Math.Abs(model.Playback.Progress - 80) < 2, "Seeking while playing resumes at the requested position");
|
|
_ = model.Playback.SeekAsync(10); _ = model.Playback.SeekAsync(90); Pump(model.Playback.SeekAsync(30));
|
|
Check(model.Playback.IsPlaying && Math.Abs(model.Playback.Progress - 30) < 2, "Rapid seeks use the final requested position");
|
|
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");
|
|
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.IsPaused && model.IsPreviewing && model.LastRecording == ""
|
|
&& !File.Exists(expectedPath) && model.RecordingInfo == "未录像",
|
|
"Confirming re-record clears the old video and waits in preview without recording");
|
|
Check(model.StartRecordingCommand.CanExecute() && !model.RestartCommand.CanExecute(),
|
|
"Re-record enables manual start and disables replacement until a video exists");
|
|
clock.Advance(TimeSpan.FromSeconds(1)); camera.Emit(); Dispatcher.UIThread.RunJobs();
|
|
Check(!File.Exists(expectedPath) && !model.IsRecording, "Preview frames do not start a replacement recording");
|
|
model.StartRecordingCommand.Execute(); PumpIdle(model);
|
|
Check(model.IsRecording && model.LastRecording == expectedPath, "Manual start creates the replacement 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();
|
|
FindSopDialog(editor).Close(RecipeCloseChoice.Discard);
|
|
Pump(vm.ShutdownAsync()); PumpFor(50);
|
|
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);
|
|
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");
|
|
var pendingSeek = reopened.Playback.SeekAsync(70);
|
|
Pump(reopened.ShutdownAsync());
|
|
Pump(pendingSeek);
|
|
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, "另一配方");
|
|
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");
|
|
fresh.SaveCommand.Execute(); Check(fresh.HasSopRecording, "Saving a new recipe enables its SOP recording page");
|
|
Check(fresh.SopRecording?.StandardVideoPath == Path.Combine(store.DirectoryFor("新配方"), "sop_stand", "sop.avi"), "Saving a new recipe binds SOP recording to its own directory");
|
|
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 CheckRunStatistics()
|
|
{
|
|
var clock = new ManualClock(); var statistics = new SopRunStatistics(clock);
|
|
statistics.StartRound(); clock.Advance(TimeSpan.FromSeconds(2)); statistics.NextStep();
|
|
clock.Advance(TimeSpan.FromSeconds(3)); statistics.Pause(); clock.Advance(TimeSpan.FromMinutes(1));
|
|
Check(statistics.FlowElapsed == TimeSpan.FromSeconds(5) && statistics.StepElapsed == TimeSpan.FromSeconds(3), "Flow and current-step timers exclude paused time");
|
|
statistics.Resume(); clock.Advance(TimeSpan.FromSeconds(1)); statistics.Stop();
|
|
clock.Advance(TimeSpan.FromSeconds(10)); statistics.CompleteRound();
|
|
Check(statistics.CompletedCount == 0 && statistics.FlowElapsed == TimeSpan.FromSeconds(6), "Stopping an unfinished round freezes timers without counting a completion");
|
|
statistics.StartRound(); clock.Advance(TimeSpan.FromSeconds(8)); statistics.StartRound();
|
|
Check(statistics.CompletedCount == 0 && statistics.FlowElapsed == TimeSpan.Zero && statistics.StepElapsed == TimeSpan.Zero, "Reset discards unfinished round timing without changing the count");
|
|
for (var seconds = 1; seconds <= 12; seconds++)
|
|
{
|
|
statistics.StartRound(); clock.Advance(TimeSpan.FromSeconds(seconds)); statistics.CompleteRound(); statistics.CompleteRound();
|
|
Check(statistics.CompletedCount == seconds, "Each completed round counts exactly once");
|
|
if (seconds <= 10) Check(statistics.AverageDuration == TimeSpan.Zero, "Average remains zero through the tenth completion");
|
|
else Check(statistics.AverageDuration == TimeSpan.FromSeconds(seconds - 4.5), "Average uses only the latest ten completed flow times");
|
|
}
|
|
clock.Advance(TimeSpan.FromMinutes(1));
|
|
Check(statistics.FlowElapsed == TimeSpan.FromSeconds(12), "Completion freezes the final flow timer");
|
|
}
|
|
private static void CheckStandardDuration(string root)
|
|
{
|
|
var missing = Path.Combine(root, "duration-missing");
|
|
Check(SopStandardVideoDuration.Get(missing) == TimeSpan.Zero, "A recipe without remembered duration or a video stays at zero");
|
|
var source = Path.Combine(root, "duration-source"); var folder = Path.Combine(source, "sop_stand");
|
|
var clock = new ManualClock(); using var recorder = new VideoRecorder(clock);
|
|
using var frame = new Mat(48, 64, MatType.CV_8UC3, new Scalar(35, 60, 90));
|
|
var video = recorder.Start(folder, frame, 30, "sop.avi"); clock.Advance(TimeSpan.FromSeconds(1)); recorder.Write(frame); clock.Advance(TimeSpan.FromSeconds(1)); recorder.Stop();
|
|
Check(SopStandardVideoDuration.Get(source) == TimeSpan.FromSeconds(2), "Missing duration memory is recovered from standard video metadata");
|
|
Check(File.Exists(Path.Combine(folder, "duration.json")), "Recovered video duration is remembered on disk");
|
|
var restart = Path.Combine(root, "duration-restart"); Directory.CreateDirectory(Path.Combine(restart, "sop_stand"));
|
|
File.Copy(Path.Combine(folder, "duration.json"), Path.Combine(restart, "sop_stand", "duration.json"));
|
|
Check(SopStandardVideoDuration.Get(restart) == TimeSpan.FromSeconds(2), "Positive persisted duration is used without reopening or requiring the video");
|
|
var zero = Path.Combine(root, "duration-zero"); Directory.CreateDirectory(Path.Combine(zero, "sop_stand"));
|
|
File.WriteAllText(Path.Combine(zero, "sop_stand", "duration.json"), "{\"DurationMilliseconds\":0}");
|
|
File.Copy(video, Path.Combine(zero, "sop_stand", "sop.avi"));
|
|
Check(SopStandardVideoDuration.Get(zero) == TimeSpan.FromSeconds(2), "Zero duration memory triggers one fallback read of the standard video");
|
|
var damaged = Path.Combine(root, "duration-damaged"); Directory.CreateDirectory(Path.Combine(damaged, "sop_stand"));
|
|
File.WriteAllText(Path.Combine(damaged, "sop_stand", "duration.json"), "broken"); File.Copy(video, Path.Combine(damaged, "sop_stand", "sop.avi"));
|
|
Check(SopStandardVideoDuration.Get(damaged) == TimeSpan.FromSeconds(2), "Invalid duration memory falls back to video metadata");
|
|
Directory.CreateDirectory(Path.Combine(missing, "sop_stand")); File.Copy(video, Path.Combine(missing, "sop_stand", "sop.avi"));
|
|
Check(SopStandardVideoDuration.Get(missing) == TimeSpan.Zero, "Startup fallback is attempted only once per recipe in a process");
|
|
SopStandardVideoDuration.Remember(source, TimeSpan.FromSeconds(4));
|
|
Check(SopStandardVideoDuration.Get(source) == TimeSpan.FromSeconds(4), "Recording updates the cached standard duration immediately");
|
|
}
|
|
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);
|
|
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 CameraInfo? ConnectedCamera { get; private set; }
|
|
public int EnumerationCount { get; private set; }
|
|
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() { EnumerationCount++; return Task.FromResult(new List<CameraInfo> { new() { Name = "测试相机" } }); }
|
|
public Task<bool> ConnectAsync(CameraInfo camera) { ConnectedCamera = 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);
|
|
}
|
|
}
|