using OpenCvSharp; namespace SopHelper.Engine.Camera; public sealed record RecordingResult(string Path, long Frames, double Fps) { public TimeSpan Duration => TimeSpan.FromSeconds(Frames / Fps); } /// Thread-safe, bounded-memory MJPEG recording with wall-clock frame pacing. public sealed class VideoRecorder : IDisposable { public static readonly TimeSpan MaximumDuration = TimeSpan.FromMinutes(5); private readonly object _gate = new(); private readonly TimeProvider _timeProvider; private long _startedAt; private VideoWriter? _writer; private Mat? _previous; private string _path = ""; private long _frames; 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 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) { if (_writer != null) throw new InvalidOperationException("正在录像,请先停止"); if (!double.IsFinite(fps) || fps < 1 || fps > 120) throw new ArgumentException("录像帧率需在1–120之间"); ValidateFrame(initialFrame); // AVI codecs use even dimensions; fail explicitly rather than silently crop the image. if (initialFrame.Width % 2 != 0 || initialFrame.Height % 2 != 0) 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"); var writer = new VideoWriter(); Mat? previous = null; try { if (!writer.Open(path, FourCC.MJPG, fps, initialFrame.Size())) throw new IOException("录像编码器无法创建文件,请检查保存目录与磁盘空间"); previous = initialFrame.Clone(); writer.Write(initialFrame); _size = initialFrame.Size(); _fps = fps; _path = path; _frames = 1; _previous = previous; _writer = writer; _startedAt = _timeProvider.GetTimestamp(); return path; } catch { previous?.Dispose(); writer.Dispose(); if (File.Exists(path)) File.Delete(path); throw; } } } public void Write(Mat frame) { lock (_gate) { if (_writer == null) return; try { ValidateFrame(frame); if (frame.Size() != _size) throw new IOException("相机分辨率发生变化,录像已停止"); // 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++; } if (_frames <= target) { _writer.Write(frame); _frames++; } frame.CopyTo(_previous!); } catch { StopCore(flushTail: false); throw; } } } public RecordingResult? Stop() { lock (_gate) return StopCore(flushTail: true); } private RecordingResult? StopCore(bool flushTail) { if (_writer == null) return null; var writer = _writer; _writer = null; 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); if (flushTail && target - _frames <= _fps * 2) while (_frames < target) { writer.Write(_previous!); _frames++; } return new RecordingResult(_path, _frames, _fps); } finally { try { writer.Dispose(); } finally { _previous?.Dispose(); _previous = null; } } } private static void ValidateFrame(Mat frame) { if (frame.Empty() || frame.Type() != MatType.CV_8UC3) throw new ArgumentException("录像需要非空的8位三通道BGR图像"); } public void Dispose() => Stop(); }