MergePusherBaseV2.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. using FFmpeg.AutoGen;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Linq;
  6. using System.Threading;
  7. using System.Threading.Tasks;
  8. using Vinno.FIS.TRTCClient.Common.Enum;
  9. using Vinno.vCloud.FIS.CrossPlatform.Common;
  10. using Vinno.vCloud.FIS.CrossPlatform.Common.Enum;
  11. using Vinno.vCloud.FIS.CrossPlatform.Common.LiveVideo;
  12. using Vinno.vCloud.FIS.CrossPlatform.Common.LiveVideo.Interface;
  13. using Vinno.vCloud.FIS.CrossPlatform.Windows.LiveVideo.RTC;
  14. namespace Vinno.vCloud.FIS.CrossPlatform.Windows.LiveVideo
  15. {
  16. public abstract unsafe class MergePusherBaseV2 : PusherBase, ILiveVideoPusherV2
  17. {
  18. private readonly ManualResetEvent _handlingImageEvent = new ManualResetEvent(true);
  19. private readonly Dictionary<EnumLiveChannelCategory, ICapturer> _captures;
  20. private readonly Stopwatch _mergeWatcher = new Stopwatch();
  21. private readonly IMergeUtil _mergeUtil;
  22. private readonly FormatConvertUtil _convertUtil;
  23. private AVFrame* _srcFrame;
  24. private AVFrame* _destFrame;
  25. private CancellationTokenSource _tokenSource;
  26. protected bool IsTRTCMode;
  27. protected const int MergeWidth = 1920;
  28. protected const int MergeHeight = 1080;
  29. protected const int MergeFrameRate = 20;
  30. public event EventHandler<ChannelStateEventArgsV2> ChannelStateChanged;
  31. public MergePusherBaseV2()
  32. {
  33. _captures = new Dictionary<EnumLiveChannelCategory, ICapturer>();
  34. _mergeUtil = new RGBMergeUtilV2(MergeWidth, MergeHeight);
  35. _convertUtil = new FormatConvertUtil();
  36. }
  37. public virtual bool StartPusher(IExtendedData pushParams, IEnumerable<CPVideoDeviceOutputInfo> deviceInfos)
  38. {
  39. InitPushersAndMergeOffsets(pushParams, deviceInfos);
  40. StartCaptures();
  41. StartPostMergeImageDataThread();
  42. return true;
  43. }
  44. public virtual bool StopPusher()
  45. {
  46. StopPostMergeImageDataThread();
  47. StopCaptures();
  48. return true;
  49. }
  50. public abstract void SetMute(bool isMute);
  51. public abstract void SwitchMic(string micId);
  52. protected void InitCacheImage(AVPixelFormat destFormat)
  53. {
  54. _srcFrame = AvFrameOperateUtil.Create(MergeWidth, MergeHeight, AVPixelFormat.AV_PIX_FMT_BGRA);
  55. _destFrame = AvFrameOperateUtil.Create(MergeWidth, MergeHeight, destFormat);
  56. }
  57. protected virtual void DealWithFullBuffer(AVFrame* frame)
  58. {
  59. }
  60. protected void PushLiveStateChanged()
  61. {
  62. ChannelStateChanged?.Invoke(this, new ChannelStateEventArgsV2(EnumLiveChannelCategory.Main, EnumDeviceLiveState.Pushing));
  63. }
  64. private void InitPushersAndMergeOffsets(IExtendedData pushParams, IEnumerable<CPVideoDeviceOutputInfo> deviceInfos)
  65. {
  66. var areaImageInfos = new List<AreaImageInfo>();
  67. if (pushParams is RtcExtendedData rtcExtendedData)
  68. {
  69. foreach (var user in rtcExtendedData.UserInfos)
  70. {
  71. var deviceInfo = deviceInfos.FirstOrDefault(c => c.Category == user.Category);
  72. if (deviceInfo != null)
  73. {
  74. ICapturer capturer;
  75. if (!CommonParameter.Instance.IsSonopost && user.Category == EnumLiveChannelCategory.Main)
  76. {
  77. capturer = new TerminalImageCapturerV2(deviceInfo.VideoDeviceId, user.Width, user.Height, EnumImageType.ImageFrameData);
  78. }
  79. else
  80. {
  81. capturer = new Capturer(deviceInfo.VideoDeviceId, user.Width, user.Height, 20, user.Category, deviceInfo.OutputWidth, deviceInfo.OutputHeight);
  82. }
  83. areaImageInfos.Add(new AreaImageInfo { Width = user.Width, Height = user.Height, Category = user.Category });
  84. _captures.Add(user.Category, capturer);
  85. }
  86. else
  87. {
  88. CrossPlatformHelper.Instance.LogWriter?.WriteLineError($"MergePusherBaseV2 Can not find {user.Category} Device Info!");
  89. }
  90. }
  91. }
  92. else if (pushParams is RtmpExtendedData rtmpExtendedData)
  93. {
  94. foreach (var user in rtmpExtendedData.UserInfos)
  95. {
  96. var deviceInfo = deviceInfos.FirstOrDefault(c => c.Category == user.Category);
  97. if (deviceInfo != null)
  98. {
  99. ICapturer capturer;
  100. if (!CommonParameter.Instance.IsSonopost && user.Category == EnumLiveChannelCategory.Main)
  101. {
  102. capturer = new TerminalImageCapturerV2(deviceInfo.VideoDeviceId, user.Width, user.Height, EnumImageType.ImageFrameData);
  103. }
  104. else
  105. {
  106. capturer = new Capturer(deviceInfo.VideoDeviceId, user.Width, user.Height, 20, user.Category, deviceInfo.OutputWidth, deviceInfo.OutputHeight);
  107. }
  108. areaImageInfos.Add(new AreaImageInfo { Width = user.Width, Height = user.Height, Category = user.Category });
  109. _captures.Add(user.Category, capturer);
  110. }
  111. else
  112. {
  113. CrossPlatformHelper.Instance.LogWriter?.WriteLineError($"MergePusherBaseV2 Can not find {user.Category} Device Info!");
  114. }
  115. }
  116. }
  117. _mergeUtil.InitAreaOffset(areaImageInfos);
  118. }
  119. private void StartCaptures()
  120. {
  121. foreach (var capturer in _captures.Values)
  122. {
  123. capturer.ImageFrameReceived += OnImageReceived;
  124. capturer.StartCapture();
  125. }
  126. }
  127. private void StopCaptures()
  128. {
  129. foreach (var capture in _captures.Values)
  130. {
  131. capture.ImageFrameReceived -= OnImageReceived;
  132. capture.StopCapture();
  133. capture.Dispose();
  134. }
  135. _captures.Clear();
  136. }
  137. private unsafe void StartPostMergeImageDataThread()
  138. {
  139. if (_tokenSource != null && !_tokenSource.IsCancellationRequested)
  140. {
  141. _tokenSource.Cancel();
  142. }
  143. _tokenSource = new CancellationTokenSource();
  144. Task.Run(() =>
  145. {
  146. while (!_tokenSource.IsCancellationRequested)
  147. {
  148. try
  149. {
  150. _handlingImageEvent.Reset();
  151. _mergeWatcher.Restart();
  152. _mergeUtil.GetFullBuffer(new IntPtr(_srcFrame->data[0]));
  153. _convertUtil.Convert(_srcFrame, _destFrame);
  154. DealWithFullBuffer(_destFrame);
  155. }
  156. catch (Exception e)
  157. {
  158. CrossPlatformHelper.Instance.LogWriter?.WriteLineError($"Get Full Buffer Error:{e}");
  159. }
  160. finally
  161. {
  162. _handlingImageEvent.Set();
  163. _mergeWatcher.Stop();
  164. var leftTime = 40 - _mergeWatcher.ElapsedMilliseconds;
  165. if (leftTime > 0)
  166. {
  167. Thread.Sleep((int)leftTime);
  168. }
  169. else
  170. {
  171. CrossPlatformHelper.Instance.LogWriter?.WriteLineDebug($"Send Yuv Data Use Time:{_mergeWatcher.ElapsedMilliseconds}");
  172. Thread.Sleep(5);
  173. }
  174. }
  175. }
  176. _convertUtil.Dispose();
  177. }, _tokenSource.Token);
  178. }
  179. private void StopPostMergeImageDataThread()
  180. {
  181. _tokenSource?.Cancel();
  182. }
  183. private void OnImageReceived(object sender, ImageFrameData e)
  184. {
  185. try
  186. {
  187. if (sender is ICapturer capture)
  188. {
  189. var area = GetAreaAndCategory(capture.Id, out var category);
  190. _mergeUtil.CopyToArea(area, e);
  191. CopyPreviewData(category, e);
  192. }
  193. }
  194. catch (Exception ex)
  195. {
  196. CrossPlatformHelper.Instance.LogWriter?.WriteLineError($"OnImageReceived Error:{ex}");
  197. }
  198. }
  199. private EnumArea GetAreaAndCategory(string id, out EnumLiveChannelCategory category)
  200. {
  201. foreach (var item in _captures)
  202. {
  203. if (item.Value.Id == id)
  204. {
  205. category = item.Key;
  206. return GetArea(category);
  207. }
  208. }
  209. throw new Exception("Can not get correct area");
  210. }
  211. protected abstract EnumArea GetArea(EnumLiveChannelCategory category);
  212. public bool StartSpeedTest(uint appId, string userId, string userSign)
  213. {
  214. if (!IsTRTCMode)
  215. {
  216. CrossPlatformHelper.Instance.LogWriter?.WriteLineError($"StartSpeedTest Fail,it only support TRTC Modes");
  217. return false;
  218. }
  219. TRTCPusher pusher = null;
  220. try
  221. {
  222. pusher = new TRTCPusher();
  223. return pusher.StartSpeedTest(appId, userId, userSign);
  224. }
  225. catch (Exception ex)
  226. {
  227. CrossPlatformHelper.Instance.LogWriter?.WriteLineError($"Rtc Single PusherV2 StartSpeedTest Error:{ex}");
  228. return false;
  229. }
  230. finally
  231. {
  232. if (pusher != null)
  233. {
  234. pusher.StopSpeedTest();
  235. pusher = null;
  236. }
  237. }
  238. }
  239. public override void DoDispose()
  240. {
  241. _handlingImageEvent.WaitOne();
  242. AvFrameOperateUtil.Destory(_srcFrame);
  243. AvFrameOperateUtil.Destory(_destFrame);
  244. _mergeUtil?.Dispose();
  245. base.DoDispose();
  246. }
  247. }
  248. }