using AForge.Video; using AForge.Video.DirectShow; using AIDiagnosisDemo.Infrastucture; using System; using System.Drawing; using System.Linq; using System.Threading; namespace AIDiagnosisDemo.Service { internal class VideoCapturePlayer : IPlayer { private readonly string _deviceId; private readonly object _deviceLocker = new object(); private int _startTickCount; private int _displayCount; private int _fps; /// /// 接收到图像输入的事件 /// public event EventHandler InputFrameReceived; /// /// FPS变更的事件 /// public event EventHandler FPSChanged; private VideoCaptureDevice _videoCaptureDevice; /// /// VideoPlayer构造函数 /// /// Device Id public VideoCapturePlayer(string deviceId) { _deviceId = deviceId; } /// /// 播放 /// /// 是视频为True,是图片为False /// 播放成功为True,播放失败为False public bool Play() { lock (_deviceLocker) { try { var videoFilterInfos = new FilterInfoCollection(FilterCategory.VideoInputDevice).OfType(); if (videoFilterInfos.FirstOrDefault(i => i.MonikerString == _deviceId) == null) { Logger.Info("Video Device is Empty!!!"); return false; } _videoCaptureDevice = new VideoCaptureDevice(_deviceId); _videoCaptureDevice.NewFrame += OnNewFrame; _startTickCount = -1; _videoCaptureDevice.Start(); return true; } catch { _videoCaptureDevice = null; Logger.Info("Video Device Play Fail!!!"); } return false; } } private void OnNewFrame(object sender, NewFrameEventArgs eventArgs) { if (_startTickCount == -1) { _displayCount = 0; _startTickCount = Environment.TickCount; } else { var currentTickCount = Environment.TickCount; var fpsTimeUsed = currentTickCount - _startTickCount; _displayCount++; if (fpsTimeUsed > 1000) { var fps = (int)((double)_displayCount / fpsTimeUsed * 1000); if (_fps != fps) { _fps = fps; FPSChanged?.Invoke(this, _fps); } _startTickCount = currentTickCount; _displayCount = 0; } } InputFrameReceived?.Invoke(this, eventArgs.Frame); } /// /// 停止播放 /// public void Stop() { lock (_deviceLocker) { if (_videoCaptureDevice == null) { return; } try { _videoCaptureDevice.NewFrame -= OnNewFrame; if (_videoCaptureDevice.IsRunning) { DoStop(); } } catch { } finally { _videoCaptureDevice = null; } } } private void DoStop() { var stopThread = new Thread(() => { try { _videoCaptureDevice.SignalToStop(); _videoCaptureDevice.WaitForStop(); } catch { } }); stopThread.Start(); try { if (!stopThread.Join(2000)) { stopThread.Abort(); } } catch { } } /// /// 继续播放 /// public void Continue() { Play(); } /// /// 暂停播放 /// public void Pause() { Stop(); } } }