LiveClient.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. using System;
  2. using System.Threading.Tasks;
  3. using Vinno.IUS.Common.Log;
  4. using Vinno.IUS.Common.Network.Leaf;
  5. using Vinno.IUS.Common.Network.Transfer;
  6. using Vinno.vCloud.FIS.CrossPlatform.Common;
  7. using Vinno.vCloud.FIS.CrossPlatform.Common.Enum;
  8. using Vinno.vCloud.FIS.CrossPlatform.Common.LiveVideo;
  9. using Vinno.vCloud.FIS.CrossPlatform.Common.LiveVideo.Interface;
  10. using Vinno.vCloud.Protocol.Infrastructures;
  11. using Vinno.vCloud.Protocol.Messages.Client.Live;
  12. using Vinno.vCloud.Protocol.Messages.Live;
  13. namespace Vinno.vCloud.Common.FIS.LiveVideos
  14. {
  15. internal class LiveClient : IDisposable
  16. {
  17. private readonly ClientLeaf _clientLeaf;
  18. private readonly object _getLiveProtocolLock = new object();
  19. private readonly int _usScreenWidth;
  20. private readonly int _usScreenHeight;
  21. private ILiveVideoPusher _pusher;
  22. private PushHeartRateKeeper _pushHeartRateKeeper;
  23. private EnumLiveStates _liveState;
  24. private LiveProtocol _liveProtocol;
  25. /// <summary>
  26. /// Preview local camera capured changed
  27. /// </summary>
  28. public event EventHandler<CPVideoFrameData> PreviewCameraCapured;
  29. /// <summary>
  30. /// Raised when live changed to protocol
  31. /// </summary>
  32. public event EventHandler<LiveProtocol> LiveProtocolChanged;
  33. /// <summary>
  34. /// The event to notificate the US to show or hide the live video out put window
  35. /// </summary>
  36. public event EventHandler<LiveNotificationArgs> LiveNotification;
  37. public LiveClient(ClientLeaf clientLeaf, int usScreenWidth, int usScreenHeight)
  38. {
  39. _clientLeaf = clientLeaf;
  40. _liveState = EnumLiveStates.Idle;
  41. _liveProtocol = LiveProtocol.RTC;
  42. _usScreenWidth = usScreenWidth;
  43. _usScreenHeight = usScreenHeight;
  44. }
  45. /// <summary>
  46. /// Start Pusher
  47. /// </summary>
  48. public void Start(LiveProtocol liveProtocol)
  49. {
  50. try
  51. {
  52. var pushConfiguration = CPCombineSmartPushConfiguration.Instance;
  53. if (_liveState == EnumLiveStates.TerminalIsPushing)
  54. {
  55. Logger.WriteLineInfo($"LiveClient is pushing ,not do start");
  56. return;
  57. }
  58. bool isStartPush = false;
  59. pushConfiguration.IsPushOnce = true;
  60. if (liveProtocol == LiveProtocol.RTC)
  61. {
  62. //直播推流
  63. if (pushConfiguration.ShouldPushData)
  64. {
  65. if (_pusher == null)
  66. {
  67. _pusher = CrossPlatformHelper.Instance.LiveVideoPusherCreator.CreateRtcPusher(
  68. pushConfiguration.RoomId,
  69. pushConfiguration.TerminalId,
  70. pushConfiguration.UserSign,
  71. pushConfiguration.Resolution,
  72. pushConfiguration.PushDataSourceType,
  73. _usScreenWidth,
  74. _usScreenHeight,
  75. UpdateLiveState);
  76. _pusher.PreviewCameraCapured += OnPreviewCameraCapured;
  77. _pusher.LiveNotification += OnLiveNotification;
  78. }
  79. isStartPush = _pusher.Start(pushConfiguration);
  80. }
  81. }
  82. else
  83. {
  84. //直播推流
  85. if (pushConfiguration.ShouldPushData)
  86. {
  87. if (_pusher == null)
  88. {
  89. _pusher = CrossPlatformHelper.Instance.LiveVideoPusherCreator.CreateRtmpPusher(pushConfiguration.TerminalId, _usScreenWidth, _usScreenHeight, UpdateLiveState);
  90. _pusher.PreviewCameraCapured += OnPreviewCameraCapured;
  91. _pusher.LiveNotification += OnLiveNotification;
  92. }
  93. isStartPush = _pusher.Start(pushConfiguration);
  94. }
  95. }
  96. if (isStartPush)
  97. {
  98. StopPushHeartRateKeeper();
  99. StartPushHeartRateKeeper(pushConfiguration);
  100. }
  101. }
  102. catch (Exception ex)
  103. {
  104. Logger.WriteLineError($"LiveClient start failed ex;{ex}");
  105. _liveState = EnumLiveStates.Idle;
  106. }
  107. }
  108. private void StartPushHeartRateKeeper(CPCombineSmartPushConfiguration pushConfiguration)
  109. {
  110. _pushHeartRateKeeper = new PushHeartRateKeeper(pushConfiguration.TerminalId, pushConfiguration.LiveServiceUrl, _clientLeaf);
  111. _pushHeartRateKeeper.Offlined += OnOfflined;
  112. _pushHeartRateKeeper.Start();
  113. }
  114. /// <summary>
  115. /// Start only Preview capture camera
  116. /// </summary>
  117. public async void StartOnlyPreviewImage()
  118. {
  119. await Task.Run(() =>
  120. {
  121. try
  122. {
  123. Logger.WriteLineInfo($"LiveClient start Preview Camera begin");
  124. var liveProtocol = GetLiveProtocol();
  125. var pushConfiguration = CPCombineSmartPushConfiguration.Instance;
  126. pushConfiguration.IsPushOnce = true;
  127. if (liveProtocol == LiveProtocol.RTC)
  128. {
  129. //only show local camera data
  130. if (_pusher == null)
  131. {
  132. _pusher = CrossPlatformHelper.Instance.LiveVideoPusherCreator.CreateRtcPusher(
  133. uint.MinValue,
  134. pushConfiguration.TerminalId,
  135. string.Empty,
  136. pushConfiguration.Resolution,
  137. pushConfiguration.PushDataSourceType,
  138. _usScreenWidth,
  139. _usScreenHeight,
  140. UpdateLiveState);
  141. _pusher.PreviewCameraCapured += OnPreviewCameraCapured;
  142. _pusher.LiveNotification += OnLiveNotification;
  143. }
  144. _pusher.Start(pushConfiguration);
  145. }
  146. else
  147. {
  148. if (_pusher == null)
  149. {
  150. _pusher = CrossPlatformHelper.Instance.LiveVideoPusherCreator.CreateRtmpPusher(pushConfiguration.TerminalId, _usScreenWidth, _usScreenHeight, UpdateLiveState);
  151. _pusher.PreviewCameraCapured += OnPreviewCameraCapured;
  152. _pusher.LiveNotification += OnLiveNotification;
  153. }
  154. _pusher.Start(pushConfiguration);
  155. }
  156. Logger.WriteLineInfo($"LiveClient start Preview Camera end");
  157. }
  158. catch (Exception ex)
  159. {
  160. Logger.WriteLineError($"LiveClient start only preview image failed ex;{ex}");
  161. }
  162. });
  163. }
  164. /// <summary>
  165. /// Stop pusher
  166. /// </summary>
  167. public void Stop()
  168. {
  169. StopPushHeartRateKeeper();
  170. CPCombineSmartPushConfiguration.Instance.ShouldPushData = false;
  171. if (_pusher != null)
  172. {
  173. _pusher.Stop();
  174. }
  175. _liveState = EnumLiveStates.Idle;
  176. LiveVideoStatusChecker.Instance.IsPushing = false;
  177. Logger.WriteLineInfo("Live Client Stop Push");
  178. }
  179. private void StopPushHeartRateKeeper()
  180. {
  181. if (_pushHeartRateKeeper != null)
  182. {
  183. _pushHeartRateKeeper.Offlined -= OnOfflined;
  184. _pushHeartRateKeeper.Stop();
  185. _pushHeartRateKeeper = null;
  186. }
  187. }
  188. /// <summary>
  189. /// Set push live status ,but _pusher is exist
  190. /// </summary>
  191. /// <param name="livePushStatus"></param>
  192. public void SetPushStatus(EnumLivePushStatus livePushStatus)
  193. {
  194. if (_pusher != null)
  195. {
  196. CPCombineSmartPushConfiguration.Instance.SetPushStatus(livePushStatus);
  197. Logger.WriteLineInfo($"LiveClient SetPushStatus:{livePushStatus}");
  198. }
  199. }
  200. /// <summary>
  201. /// Set enable preview camera capture data
  202. /// </summary>
  203. /// <param name="isShowPreview"></param>
  204. public void SetPreviewCamera(bool isShowPreview)
  205. {
  206. if (_pusher != null)
  207. {
  208. _pusher.SetPreviewCamera(isShowPreview);
  209. Logger.WriteLineInfo($"LiveClient set preview camera :{isShowPreview}");
  210. }
  211. }
  212. public void ChangeCamera(string cameraId)
  213. {
  214. if (_pusher != null)
  215. {
  216. _pusher.ChangeCamera(cameraId);
  217. Logger.WriteLineInfo($"LiveClient change camera id:{cameraId}");
  218. }
  219. }
  220. public void ChangeMic(string micId)
  221. {
  222. if (_pusher != null)
  223. {
  224. _pusher.ChangeMic(micId);
  225. Logger.WriteLineInfo($"LiveClient change mic id:{micId}");
  226. }
  227. }
  228. /// <summary>
  229. /// Set live mute
  230. /// </summary>
  231. /// <param name="isMute"></param>
  232. public void SetMute(bool isMute)
  233. {
  234. if (_pusher != null)
  235. {
  236. _pusher.SetMute(isMute);
  237. Logger.WriteLineInfo($"LiveClient set mute :{isMute}");
  238. }
  239. }
  240. private async void UpdateLiveState(EnumLiveStates liveState)
  241. {
  242. try
  243. {
  244. await Task.Run(() =>
  245. {
  246. if (_liveState != liveState)
  247. {
  248. try
  249. {
  250. _liveState = liveState;
  251. if (_liveState == EnumLiveStates.TerminalIsPushing)
  252. {
  253. SetPushStatus(EnumLivePushStatus.Pushing);
  254. LiveVideoStatusChecker.Instance.IsPushing = true;
  255. }
  256. _clientLeaf?.Send(new UpdateTerminalLiveStateRequest()
  257. {
  258. TerminalId = CPCombineSmartPushConfiguration.Instance.TerminalId,
  259. State = (LiveStates)liveState
  260. });
  261. Logger.WriteLineInfo($"LiveClient UpdateLiveState: {liveState},TerminalId:{CPCombineSmartPushConfiguration.Instance.TerminalId}");
  262. }
  263. catch (Exception ex)
  264. {
  265. Logger.WriteLineError($"UpdateLiveState {_liveState} Error:{ex}");
  266. _liveState = EnumLiveStates.Idle;
  267. }
  268. }
  269. });
  270. }
  271. catch (Exception e)
  272. {
  273. Logger.WriteLineInfo($"LiveClient UpdateLiveState failed ex:{e}");
  274. }
  275. }
  276. private void OnPreviewCameraCapured(object sender, CPVideoFrameData data)
  277. {
  278. PreviewCameraCapured?.Invoke(this, data);
  279. }
  280. private void OnOfflined(object sender, EventArgs e)
  281. {
  282. Logger.WriteLineInfo($"LiveClient Push OnOfflined TerminalId:{CPCombineSmartPushConfiguration.Instance.TerminalId}");
  283. //Retry();
  284. }
  285. /// <summary>
  286. /// Disposed when live video feature disposed
  287. /// </summary>
  288. public void Dispose()
  289. {
  290. CPCombineSmartPushConfiguration.Instance.ShowPreviewImage = false;
  291. Stop();
  292. if (_pusher != null)
  293. {
  294. _pusher.PreviewCameraCapured -= OnPreviewCameraCapured;
  295. _pusher.LiveNotification -= OnLiveNotification;
  296. _pusher = null;
  297. }
  298. }
  299. /// <summary>
  300. /// retry live pushing
  301. /// </summary>
  302. public void Retry(LiveProtocol liveProtocol)
  303. {
  304. try
  305. {
  306. if (_clientLeaf != null && _clientLeaf.Online && CPCombineSmartPushConfiguration.Instance.PushStatus == EnumLivePushStatus.Pushing)// network connected and Pushing
  307. {
  308. // check server live room exist
  309. var request = MessagePool.GetMessage<CheckTerminalRoomRequest>();
  310. request.TerminalId = CPCombineSmartPushConfiguration.Instance.TerminalId;
  311. var result = _clientLeaf.Send(request);
  312. var checkTerminalRoomResult = CheckTerminalRoomResult.Convert(result);
  313. if (checkTerminalRoomResult == null || !checkTerminalRoomResult.IsExist)
  314. {
  315. Logger.WriteLineError($"LiveClient Retry, Check server live room no exist");
  316. SetPushStatus(EnumLivePushStatus.Ide);
  317. CPCombineSmartPushConfiguration.Instance.PushUrl = string.Empty;
  318. return;
  319. }
  320. //server live room exist ,do next code
  321. lock (CPCombineSmartPushConfiguration.Instance)
  322. {
  323. Logger.WriteLineInfo($"LiveClient RetryLive begin");
  324. Stop();
  325. CPCombineSmartPushConfiguration.Instance.ShouldPushData = true;
  326. SetPushStatus(EnumLivePushStatus.Ide);
  327. Start(liveProtocol);
  328. Logger.WriteLineInfo($"LiveClient RetryLive end");
  329. }
  330. }
  331. else
  332. {
  333. //Logger.WriteLineInfo($"LiveClient RetryLive:_clientLeafOnline:{_clientLeaf.Online} PushStatus:{CombineSmartPushConfiguration.Instance.PushStatus}");
  334. }
  335. }
  336. catch (Exception ex)
  337. {
  338. Logger.WriteLineError($"LiveClient Retry failed:{ex}");
  339. }
  340. }
  341. /// <summary>
  342. /// Speed live test network and auto select good network to server
  343. /// </summary>
  344. /// <param name="configuration"></param>
  345. /// <returns></returns>
  346. public bool StartSpeedTest()
  347. {
  348. bool result = false;
  349. try
  350. {
  351. var liveProtocol = GetLiveProtocol();
  352. if (liveProtocol == LiveProtocol.RTC) // only test live protocol RTC
  353. {
  354. var pusher = CrossPlatformHelper.Instance.LiveVideoPusherCreator.CreateRtcPusher(uint.MinValue, string.Empty, string.Empty, CPCombineSmartPushConfiguration.Instance.Resolution, CPCombineSmartPushConfiguration.Instance.PushDataSourceType, _usScreenWidth,
  355. _usScreenHeight, null);
  356. if (pusher != null)
  357. {
  358. using (var getLiveRoomSignRequest = MessagePool.GetMessage<GetLiveRoomSignRequest>())
  359. {
  360. var userId = Guid.NewGuid().ToString();
  361. getLiveRoomSignRequest.RoomId = userId;
  362. var getLiveRoomSignResult =
  363. GetLiveRoomSignResult.Convert(_clientLeaf?.Send(getLiveRoomSignRequest));
  364. if (getLiveRoomSignResult != null)
  365. {
  366. var userSign = getLiveRoomSignResult.UserSign;
  367. var appId = (uint)getLiveRoomSignResult.AppId;
  368. CPCombineSmartPushConfiguration.Instance.IsPushOnce = true;
  369. result = pusher.StartSpeedTest(appId, userId, userSign);
  370. }
  371. }
  372. }
  373. }
  374. else
  375. {
  376. // 内网 不需要处理
  377. Logger.WriteLineInfo($"LiveClient StartSpeedTest LiveProtocol:{liveProtocol}, do not speedTest ");
  378. return true;
  379. }
  380. }
  381. catch (Exception ex)
  382. {
  383. Logger.WriteLineError($"LiveClient StartSpeedTest ex:{ex}");
  384. }
  385. return result;
  386. }
  387. /// <summary>
  388. /// Notify server satatus and resolutions
  389. /// </summary>
  390. /// <param name="terminalName">The terminal id.</param>
  391. /// <param name="isCameraLiveEnabled"></param>
  392. /// <param name="serialNumber">device dongledId to fix hainan project, if vbox should ingnore</param>
  393. internal async void NotifyStatusAndResolutions(string terminalId)
  394. {
  395. await Task.Run(() =>
  396. {
  397. try
  398. {
  399. var liveProtocol = GetLiveProtocol();
  400. if (liveProtocol == LiveProtocol.RTC)
  401. {
  402. //获取Terminal 和 Camera Resolution
  403. var pusher = CrossPlatformHelper.Instance.LiveVideoPusherCreator.CreateRtcPusher(uint.MinValue, string.Empty, string.Empty, CPCombineSmartPushConfiguration.Instance.Resolution, CPCombineSmartPushConfiguration.Instance.PushDataSourceType, _usScreenWidth,
  404. _usScreenHeight, null);
  405. if (pusher != null)
  406. {
  407. using (var changeCameraSettingRequest = new ChangeCameraSettingRequest()
  408. {
  409. TerminalId = terminalId,
  410. IsMergeChannel = true,
  411. TerminalWidth = pusher.TerminalWidth,
  412. TerminalHeight = pusher.TerminalHeight,
  413. CameraWidth = pusher.CameraWidth,
  414. CameraHeight = pusher.CameraHeight
  415. })
  416. {
  417. var result = _clientLeaf?.Send(changeCameraSettingRequest);
  418. var resultMsg = ChangeCameraSettingResult.Convert(result);
  419. if (resultMsg != null && resultMsg.IsSuccess)
  420. {
  421. Logger.WriteLineInfo($"UpdateTerminalRelatedInfoRequest success RTC, PushDataSourceType :{CPCombineSmartPushConfiguration.Instance.PushDataSourceType}, " +
  422. $"TerminalSize:{changeCameraSettingRequest.TerminalWidth}*{changeCameraSettingRequest.TerminalHeight} " +
  423. $"CameraSize: {changeCameraSettingRequest.CameraWidth}*{changeCameraSettingRequest.CameraHeight}");
  424. }
  425. else
  426. {
  427. Logger.WriteLineError($"ChangeCameraSettingRequest failed");
  428. }
  429. }
  430. }
  431. }
  432. else
  433. {
  434. var pusher = CrossPlatformHelper.Instance.LiveVideoPusherCreator.CreateRtmpPusher(terminalId, _usScreenWidth, _usScreenHeight, null);
  435. pusher.UpdateResolution(CPCombineSmartPushConfiguration.Instance);
  436. if (pusher != null)
  437. {
  438. using (var changeCameraSettingRequest = new ChangeCameraSettingRequest()
  439. {
  440. TerminalId = terminalId,
  441. IsMergeChannel = true,
  442. TerminalWidth = pusher.TerminalWidth,
  443. TerminalHeight = pusher.TerminalHeight,
  444. CameraWidth = pusher.CameraWidth,
  445. CameraHeight = pusher.CameraHeight
  446. })
  447. {
  448. var result = _clientLeaf?.Send(changeCameraSettingRequest);
  449. var resultMsg = ChangeCameraSettingResult.Convert(result);
  450. if (resultMsg != null && resultMsg.IsSuccess)
  451. {
  452. Logger.WriteLineInfo($"UpdateTerminalRelatedInfoRequest success ,RTMP PushDataSourceType :{CPCombineSmartPushConfiguration.Instance.PushDataSourceType}" +
  453. $"TerminalWidth:{pusher.TerminalWidth} TerminalHeight:{pusher.TerminalHeight} " +
  454. $"CameraWidth: {pusher.CameraWidth} CameraHeight:{pusher.CameraHeight}");
  455. }
  456. else
  457. {
  458. Logger.WriteLineError($"UpdateTerminalRelatedInfoRequest failed");
  459. }
  460. }
  461. }
  462. }
  463. Retry(liveProtocol);
  464. }
  465. catch (Exception e)
  466. {
  467. Logger.WriteLineError($"Get resolutions ex:{e}");
  468. }
  469. });
  470. }
  471. /// <summary>
  472. /// get live Protocol Rtmp or Rtc
  473. /// </summary>
  474. private LiveProtocol GetLiveProtocol()
  475. {
  476. lock (_getLiveProtocolLock)
  477. {
  478. LiveProtocol liveProtocol = LiveProtocol.RTC;
  479. try
  480. {
  481. using (var request = MessagePool.GetMessage<GetLiveProtocolRequest>())
  482. {
  483. var result = _clientLeaf?.Send(request);
  484. var getLiveProtocolResult = GetLiveProtocolResult.Convert(result);
  485. if (getLiveProtocolResult != null)
  486. {
  487. liveProtocol = getLiveProtocolResult.LiveProtocol;
  488. }
  489. }
  490. }
  491. catch (Exception ex)
  492. {
  493. Logger.WriteLineError($"Terminal get live protocol failed {ex}");
  494. }
  495. if (_liveProtocol != liveProtocol)
  496. {
  497. _liveProtocol = liveProtocol;
  498. Logger.WriteLineInfo($"Terminal get live protocol:{liveProtocol}");
  499. LiveProtocolChanged?.Invoke(this, _liveProtocol);
  500. }
  501. return liveProtocol;
  502. }
  503. }
  504. private void OnLiveNotification(object sender, LiveNotificationArgs e)
  505. {
  506. LiveNotification?.Invoke(this, e);
  507. }
  508. }
  509. }