DirectShowCapturer.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. using DirectShowLib;
  2. using System;
  3. using System.Linq;
  4. using System.Runtime.InteropServices;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using Vinno.FIS.TRTCClient.Common.Enum;
  8. using Vinno.FIS.TRTCClient.Common.Log;
  9. namespace Vinno.FIS.TRTCClient.Captures
  10. {
  11. internal class DirectShowCapturer : ISampleGrabberCB
  12. {
  13. private IMediaControl mediaControl = null;
  14. private IFilterGraph2 graphBuilder = null;
  15. private ICaptureGraphBuilder2 captureGraphBuilder = null;
  16. private DsROTEntry rot = null;
  17. private TRTCImageFrameData _imageData;
  18. private int _fps;
  19. private string _id;
  20. private readonly int _outputWidth;
  21. private readonly int _outputHeight;
  22. private EnumLiveChannelCategory _liveChannelCategory;
  23. private readonly ManualResetEvent _handlingImageEvent = new ManualResetEvent(true);
  24. private bool _isCapturing;
  25. public string Id => _id;
  26. public int OutputWidth => _outputWidth;
  27. public int OutputHeight => _outputHeight;
  28. public bool IsCapturing => _isCapturing;
  29. public event EventHandler<TRTCImageFrameData> ImageFrameReceived;
  30. public DirectShowCapturer(string id, int width, int height, int fps, EnumLiveChannelCategory liveChannelCategory)
  31. {
  32. _id = id;
  33. _fps = fps;
  34. _outputWidth = width;
  35. _outputHeight = height;
  36. _liveChannelCategory = liveChannelCategory;
  37. _imageData = new TRTCImageFrameData(width, height);
  38. Logger.WriteLineInfo($"DirectShowCapturer {_id}: Resolution:{width} {height} {liveChannelCategory}");
  39. }
  40. public void StartCapture()
  41. {
  42. if (_isCapturing)
  43. {
  44. Logger.WriteLineWarn($"DirectShowCapturer {_id}: Has Been In Capturing!");
  45. return;
  46. }
  47. var device = DsDevice.GetDevicesOfCat(FilterCategory.VideoInputDevice).FirstOrDefault(x => x.DevicePath.Contains(_id) || _id.Contains(x.DevicePath));
  48. if (device != null)
  49. {
  50. if (CaptureVideo(device))
  51. {
  52. _isCapturing = true;
  53. return;
  54. }
  55. else
  56. {
  57. _isCapturing = false;
  58. return;
  59. }
  60. }
  61. _isCapturing = false;
  62. Logger.WriteLineError($"DirectShowCapturer {_id}:Can not find device {_id},Start Capture Error!");
  63. }
  64. public void StopCapture()
  65. {
  66. try
  67. {
  68. if (_isCapturing)
  69. {
  70. CloseInterfaces();
  71. _isCapturing = false;
  72. }
  73. }
  74. catch (Exception e)
  75. {
  76. Logger.WriteLineError($"DirectShowCapturer {_id}:Stop Capture Error:{e}");
  77. }
  78. }
  79. private bool CaptureVideo(DsDevice device)
  80. {
  81. int step = 0;
  82. int hr = 0;
  83. IBaseFilter sourceFilter = null;
  84. ISampleGrabber sampleGrabber = null;
  85. try
  86. {
  87. // Get DirectShow interfaces
  88. GetInterfaces();
  89. // Attach the filter graph to the capture graph
  90. hr = this.captureGraphBuilder.SetFiltergraph(this.graphBuilder);
  91. DsError.ThrowExceptionForHR(hr);
  92. step++;
  93. // Use the system device enumerator and class enumerator to find
  94. // a video capture/preview device, such as a desktop USB video camera.
  95. sourceFilter = SelectCaptureDevice(device);
  96. // Add Capture filter to graph.
  97. hr = this.graphBuilder.AddFilter(sourceFilter, "Video Capture");
  98. DsError.ThrowExceptionForHR(hr);
  99. step++;
  100. // Initialize SampleGrabber.
  101. sampleGrabber = new SampleGrabber() as ISampleGrabber;
  102. // Configure SampleGrabber. Add preview callback.
  103. ConfigureSampleGrabber(sampleGrabber);
  104. // Add SampleGrabber to graph.
  105. hr = this.graphBuilder.AddFilter(sampleGrabber as IBaseFilter, "Frame Callback");
  106. DsError.ThrowExceptionForHR(hr);
  107. step++;
  108. // Configure preview settings.
  109. SetConfigParams(this.captureGraphBuilder, sourceFilter, _fps, _imageData.Width, _imageData.Height);
  110. // Render the preview
  111. hr = this.captureGraphBuilder.RenderStream(PinCategory.Capture, MediaType.Video, sourceFilter, null, (sampleGrabber as IBaseFilter));
  112. DsError.ThrowExceptionForHR(hr);
  113. step++;
  114. // Add our graph to the running object table, which will allow
  115. // the GraphEdit application to "spy" on our graph
  116. rot = new DsROTEntry(this.graphBuilder);
  117. // Start previewing video data
  118. hr = this.mediaControl.Run();
  119. DsError.ThrowExceptionForHR(hr);
  120. step++;
  121. return true;
  122. }
  123. catch (Exception e)
  124. {
  125. Logger.WriteLineError($"DirectShowCapturer:An unrecoverable error has occurred.Step:{step},Error:{hr},{e}");
  126. return false;
  127. }
  128. finally
  129. {
  130. if (sourceFilter != null)
  131. {
  132. Marshal.ReleaseComObject(sourceFilter);
  133. sourceFilter = null;
  134. }
  135. if (sampleGrabber != null)
  136. {
  137. Marshal.ReleaseComObject(sampleGrabber);
  138. sampleGrabber = null;
  139. }
  140. }
  141. }
  142. private IBaseFilter SelectCaptureDevice(DsDevice device)
  143. {
  144. object source = null;
  145. Guid iid = typeof(IBaseFilter).GUID;
  146. device.Mon.BindToObject(null, null, ref iid, out source);
  147. return (IBaseFilter)source;
  148. }
  149. private void GetInterfaces()
  150. {
  151. int hr = 0;
  152. // An exception is thrown if cast fail
  153. this.graphBuilder = (IFilterGraph2)new FilterGraph();
  154. this.captureGraphBuilder = (ICaptureGraphBuilder2)new CaptureGraphBuilder2();
  155. this.mediaControl = (IMediaControl)this.graphBuilder;
  156. // this.videoWindow = (IVideoWindow)this.graphBuilder;
  157. DsError.ThrowExceptionForHR(hr);
  158. }
  159. private void CloseInterfaces()
  160. {
  161. if (mediaControl != null)
  162. {
  163. int hr = mediaControl.StopWhenReady();
  164. DsError.ThrowExceptionForHR(hr);
  165. }
  166. // Remove filter graph from the running object table.
  167. if (rot != null)
  168. {
  169. rot.Dispose();
  170. rot = null;
  171. }
  172. // Release DirectShow interfaces.
  173. if (mediaControl != null)
  174. {
  175. Marshal.ReleaseComObject(mediaControl);
  176. mediaControl = null;
  177. }
  178. if (graphBuilder != null)
  179. {
  180. Marshal.ReleaseComObject(graphBuilder);
  181. graphBuilder = null;
  182. }
  183. if (captureGraphBuilder != null)
  184. {
  185. Marshal.ReleaseComObject(captureGraphBuilder);
  186. captureGraphBuilder = null;
  187. }
  188. }
  189. private void SetConfigParams(ICaptureGraphBuilder2 capGraph, IBaseFilter capFilter, int iFrameRate, int iWidth, int iHeight)
  190. {
  191. int hr;
  192. object config;
  193. AMMediaType mediaType;
  194. // Find the stream config interface
  195. hr = capGraph.FindInterface(
  196. PinCategory.Capture, MediaType.Video, capFilter, typeof(IAMStreamConfig).GUID, out config);
  197. IAMStreamConfig videoStreamConfig = config as IAMStreamConfig;
  198. if (videoStreamConfig == null)
  199. {
  200. throw new Exception("Failed to get IAMStreamConfig");
  201. }
  202. // Get the existing format block
  203. hr = videoStreamConfig.GetFormat(out mediaType);
  204. DsError.ThrowExceptionForHR(hr);
  205. // copy out the videoinfoheader
  206. VideoInfoHeader videoInfoHeader = new VideoInfoHeader();
  207. Marshal.PtrToStructure(mediaType.formatPtr, videoInfoHeader);
  208. // if overriding the framerate, set the frame rate
  209. if (iFrameRate > 0)
  210. {
  211. videoInfoHeader.AvgTimePerFrame = 10000000 / iFrameRate;
  212. }
  213. // if overriding the width, set the width
  214. if (iWidth > 0)
  215. {
  216. videoInfoHeader.BmiHeader.Width = iWidth;
  217. }
  218. // if overriding the Height, set the Height
  219. if (iHeight > 0)
  220. {
  221. videoInfoHeader.BmiHeader.Height = iHeight;
  222. }
  223. // Copy the media structure back
  224. Marshal.StructureToPtr(videoInfoHeader, mediaType.formatPtr, false);
  225. // Set the new format
  226. hr = videoStreamConfig.SetFormat(mediaType);
  227. DsError.ThrowExceptionForHR(hr);
  228. DsUtils.FreeAMMediaType(mediaType);
  229. mediaType = null;
  230. }
  231. private void ConfigureSampleGrabber(ISampleGrabber sampleGrabber)
  232. {
  233. AMMediaType media;
  234. int hr;
  235. // Set the media type to Video/ARGB32
  236. media = new AMMediaType();
  237. media.majorType = MediaType.Video;
  238. media.subType = MediaSubType.ARGB32;
  239. media.formatType = FormatType.VideoInfo;
  240. hr = sampleGrabber.SetMediaType(media);
  241. DsError.ThrowExceptionForHR(hr);
  242. DsUtils.FreeAMMediaType(media);
  243. media = null;
  244. hr = sampleGrabber.SetCallback(this, 1);
  245. DsError.ThrowExceptionForHR(hr);
  246. }
  247. public int SampleCB(double SampleTime, IMediaSample pSample)
  248. {
  249. return 0;
  250. }
  251. public unsafe int BufferCB(double SampleTime, IntPtr pBuffer, int BufferLen)
  252. {
  253. try
  254. {
  255. _handlingImageEvent.Reset();
  256. //上下翻转
  257. var stride = 4 * _outputWidth;
  258. var height = _imageData.Height;
  259. var tmp = IntPtr.Add(pBuffer, stride * (height - 1));
  260. Parallel.For(0, height, row =>
  261. {
  262. Buffer.MemoryCopy(IntPtr.Subtract(tmp, row * stride).ToPointer(), IntPtr.Add(_imageData.Data, row * stride).ToPointer(), stride, stride);
  263. });
  264. ImageFrameReceived?.Invoke(this, _imageData);
  265. return 0;
  266. }
  267. catch (Exception ex)
  268. {
  269. Logger.WriteLineError($"DirectShowCapturer BufferCB Error:{ex}");
  270. return 0;
  271. }
  272. finally
  273. {
  274. _handlingImageEvent.Set();
  275. }
  276. }
  277. public void Dispose()
  278. {
  279. StopCapture();
  280. _handlingImageEvent.WaitOne();
  281. _imageData?.Dispose();
  282. }
  283. }
  284. }