TRTCChatRoom.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. 
  2. using Newtonsoft.Json;
  3. using Newtonsoft.Json.Linq;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using fis.media.Library.Players;
  10. using ManageLiteAV;
  11. namespace fis.media.ThirdPartLibrary.Tencent
  12. {
  13. /// <summary>
  14. /// TRTC SDK 实现
  15. /// </summary>
  16. public class TRTCChatRoom : ITRTCCloudCallback
  17. {
  18. private static TRTCChatRoom? _instance;
  19. public static TRTCChatRoom Instance => _instance ?? (_instance = new TRTCChatRoom());
  20. private ITRTCScreenCaptureSourceList? _mScreenList;
  21. private string _localId;
  22. private int _roomId;
  23. private bool _chatUserEnterRoomSuccess = false;
  24. private const int JoinAndLeaveRoomTimeout = 8000;
  25. AutoResetEvent _joinRoomWaitor = new AutoResetEvent(false);
  26. AutoResetEvent _leafRoomWaitor = new AutoResetEvent(false);
  27. ITRTCCloud? _tRTCCloud;
  28. private TRTCVideoFrame? _videoFrame;
  29. private LocalVideoRenderCallback _localVideoRenderCallback;
  30. private RemoteVideoRenderCallback _remoteVideoRenderCallback;
  31. /// <summary>
  32. /// 本地摄像头数据
  33. /// </summary>
  34. public event EventHandler<VideoFrameData>? LocalVideoFrameArrived;
  35. /// <summary>
  36. /// 远端摄像头数据
  37. /// </summary>
  38. public event EventHandler<RemoteVideoFrameData>? RemoteVideoFrameArrived;
  39. /// <summary>
  40. /// 本地屏幕分享数据
  41. /// </summary>
  42. public event EventHandler<VideoFrameData>? LocalVideoScreenFrameArrived;
  43. /// <summary>
  44. /// 远端屏幕分享数据
  45. /// </summary>
  46. public event EventHandler<RemoteVideoFrameData>? RemoteVideoScreenFrameArrived;
  47. /// <summary>
  48. /// 远端用户离开房间
  49. /// </summary>
  50. public event Action<string, int>? RemoteUserLeaveRoomNotification;
  51. public event Action<string>? RemoteUserEnterRoomNotification;
  52. /// <summary>
  53. /// SDK 跟服务器的连接恢复
  54. /// </summary>
  55. public event Action? TryToReconnectNotification;
  56. /// <summary>
  57. /// SDK 尝试重新连接到服务器
  58. /// </summary>
  59. public event Action? ConnectionRecoveryNotification;
  60. /// <summary>
  61. /// SDK 跟服务器的连接断开
  62. /// </summary>
  63. public event Action? ConnectionLostNotification;
  64. private TRTCChatRoom()
  65. {
  66. _localVideoRenderCallback = new LocalVideoRenderCallback(OnLocalVideoFrameArrived);
  67. _remoteVideoRenderCallback = new RemoteVideoRenderCallback(OnRemoteVideoFrameArrived);
  68. }
  69. /// <summary>
  70. /// 视频参数设置
  71. /// </summary>
  72. /// <returns></returns>
  73. private TRTCVideoEncParam GetVideoEncParam()
  74. {
  75. TRTCVideoEncParam tRTCVideoEncParam = new TRTCVideoEncParam();
  76. tRTCVideoEncParam.videoResolution = TRTCVideoResolution.TRTCVideoResolution_640_480;
  77. tRTCVideoEncParam.videoFps = 15;
  78. tRTCVideoEncParam.videoBitrate = 600;
  79. return tRTCVideoEncParam;
  80. }
  81. /// <summary>
  82. /// 进入房间
  83. /// </summary>
  84. /// <param name="accountId"></param>
  85. /// <param name="integerRoomId"></param>
  86. /// <param name="isVideo"></param>
  87. /// <param name="userSign"></param>
  88. /// <param name="appId"></param>
  89. public void Enter(string accountId, int integerRoomId, bool isVideo, string userSign, int appId)
  90. {
  91. if (_roomId <= 0 || _tRTCCloud == null)
  92. {
  93. _roomId = integerRoomId;
  94. _localId = accountId;
  95. _tRTCCloud = ITRTCCloud.getTRTCShareInstance();
  96. SIZE thumbSize = new SIZE() { cx = 120, cy = 70 };
  97. SIZE iconSize = new SIZE() { cx = 20, cy = 20 };
  98. _mScreenList = _tRTCCloud.getScreenCaptureSources(ref thumbSize, ref iconSize);
  99. //设置log路径
  100. var tRTCRenderParams = new TRTCRenderParams() { rotation = TRTCVideoRotation.TRTCVideoRotation270 };
  101. _tRTCCloud.setLocalRenderParams(ref tRTCRenderParams);
  102. var videoParam = GetVideoEncParam();
  103. _tRTCCloud.setVideoEncoderParam(ref videoParam);
  104. TRTCParams trtcParams = new TRTCParams();
  105. trtcParams.sdkAppId = (uint)appId;
  106. trtcParams.userSig = userSign;
  107. trtcParams.privateMapKey = "";
  108. trtcParams.businessInfo = "";
  109. _tRTCCloud.addCallback(this);
  110. _tRTCCloud.enterRoom(ref trtcParams, TRTCAppScene.TRTCAppSceneVideoCall);
  111. if (isVideo)
  112. {
  113. _tRTCCloud.startLocalPreview(IntPtr.Zero);
  114. var retValue = _tRTCCloud.setLocalVideoRenderCallback(TRTCVideoPixelFormat.TRTCVideoPixelFormat_BGRA32, TRTCVideoBufferType.TRTCVideoBufferType_Buffer, _localVideoRenderCallback);
  115. if (retValue == 0)
  116. {
  117. //设置本地视频自定义渲染成功
  118. }
  119. else
  120. {
  121. //设置本地视频自定义渲染失败
  122. }
  123. var localVideoRenderParams = new TRTCRenderParams()
  124. {
  125. fillMode = TRTCVideoFillMode.TRTCVideoFillMode_Fit
  126. };
  127. _tRTCCloud.setLocalRenderParams(ref localVideoRenderParams);
  128. }
  129. _tRTCCloud.startLocalAudio(TRTCAudioQuality.TRTCAudioQualitySpeech);
  130. if (!_joinRoomWaitor.WaitOne(JoinAndLeaveRoomTimeout))
  131. {
  132. //RtcChatRoom Joint Room timeout
  133. }
  134. }
  135. else
  136. {
  137. if (isVideo)
  138. {
  139. _tRTCCloud.startLocalPreview(IntPtr.Zero);
  140. var retValue = _tRTCCloud.setLocalVideoRenderCallback(TRTCVideoPixelFormat.TRTCVideoPixelFormat_BGRA32, TRTCVideoBufferType.TRTCVideoBufferType_Buffer, _localVideoRenderCallback);
  141. if (retValue == 0)
  142. {
  143. //设置本地视频自定义渲染成功
  144. }
  145. else
  146. {
  147. //设置本地视频自定义渲染失败
  148. }
  149. }
  150. _tRTCCloud.startLocalAudio(TRTCAudioQuality.TRTCAudioQualitySpeech);
  151. }
  152. }
  153. /// <summary>
  154. /// 退出房间
  155. /// </summary>
  156. public void Exit()
  157. {
  158. if (_tRTCCloud == null)
  159. {
  160. return;
  161. }
  162. _tRTCCloud.stopAllRemoteView();
  163. _tRTCCloud.stopLocalPreview();
  164. _tRTCCloud.stopLocalAudio();
  165. _tRTCCloud.muteLocalAudio(true);
  166. _tRTCCloud.muteLocalVideo(TRTCVideoStreamType.TRTCVideoStreamTypeBig, true);
  167. _tRTCCloud.stopScreenCapture();
  168. _roomId = 0;
  169. _tRTCCloud.exitRoom();
  170. if (_chatUserEnterRoomSuccess && !_leafRoomWaitor.WaitOne(JoinAndLeaveRoomTimeout))
  171. {
  172. }
  173. _chatUserEnterRoomSuccess = false;
  174. _tRTCCloud.removeCallback(this);
  175. _tRTCCloud.setLogCallback(null);
  176. }
  177. /// <summary>
  178. /// 静音/取消静音
  179. /// </summary>
  180. /// <param name="isMute"></param>
  181. public void Mute(bool isMute)
  182. {
  183. _tRTCCloud?.muteLocalAudio(isMute);
  184. }
  185. /// <summary>
  186. /// 开始分享屏幕|默认分享第一块屏幕
  187. /// </summary>
  188. public void StartShareScreen()
  189. {
  190. TRTCScreenCaptureSourceInfo sourceInfo = _mScreenList?.getSourceInfo(0)!;
  191. RECT rect = new RECT()
  192. {
  193. top = 0,
  194. left = 0,
  195. right = 0,
  196. bottom = 0,
  197. };
  198. TRTCScreenCaptureProperty property = new TRTCScreenCaptureProperty() { enableHighLight = false };
  199. _tRTCCloud?.selectScreenCaptureTarget(ref sourceInfo, ref rect, ref property);
  200. _tRTCCloud?.startScreenCapture(IntPtr.Zero, TRTCVideoStreamType.TRTCVideoStreamTypeSub, null);
  201. }
  202. /// <summary>
  203. /// 停止分享屏幕
  204. /// </summary>
  205. public void StopShareScreen()
  206. {
  207. _tRTCCloud?.stopScreenCapture();
  208. }
  209. /// <summary>
  210. /// 发送自己采集的视频
  211. /// </summary>
  212. /// <param name="width"></param>
  213. /// <param name="height"></param>
  214. /// <param name="frameBuffer"></param>
  215. private void SendCustomData(int width, int height, byte[] frameBuffer)
  216. {
  217. if (_videoFrame == null)
  218. {
  219. _videoFrame = new TRTCVideoFrame();
  220. _videoFrame.videoFormat = TRTCVideoPixelFormat.TRTCVideoPixelFormat_I420;
  221. _videoFrame.bufferType = TRTCVideoBufferType.TRTCVideoBufferType_Buffer;
  222. }
  223. _videoFrame.width = (uint)width;
  224. _videoFrame.height = (uint)height;
  225. _videoFrame.data = frameBuffer;
  226. _videoFrame.length = (uint)frameBuffer.Length;
  227. _videoFrame.timestamp = 0;
  228. _tRTCCloud?.sendCustomVideoData(TRTCVideoStreamType.TRTCVideoStreamTypeBig, _videoFrame);
  229. }
  230. /// <summary>
  231. /// 本地视频数据
  232. /// </summary>
  233. /// <param name="data"></param>
  234. /// <param name="streamType"></param>
  235. private void OnLocalVideoFrameArrived(VideoFrameData data, TRTCVideoStreamType streamType)
  236. {
  237. if (streamType == TRTCVideoStreamType.TRTCVideoStreamTypeBig)
  238. {
  239. LocalVideoFrameArrived?.Invoke(this, data);
  240. }
  241. else
  242. {
  243. LocalVideoScreenFrameArrived?.Invoke(this, data);
  244. }
  245. }
  246. /// <summary>
  247. /// 远端视频数据
  248. /// </summary>
  249. /// <param name="data"></param>
  250. /// <param name="streamType"></param>
  251. private void OnRemoteVideoFrameArrived(RemoteVideoFrameData data, TRTCVideoStreamType streamType)
  252. {
  253. if (streamType == TRTCVideoStreamType.TRTCVideoStreamTypeBig)
  254. {
  255. RemoteVideoFrameArrived?.Invoke(this, data);
  256. }
  257. else
  258. {
  259. RemoteVideoScreenFrameArrived?.Invoke(this, data);
  260. }
  261. }
  262. public void onUserSubStreamAvailable(string userId, bool available)
  263. {
  264. //用户是否开启屏幕分享
  265. if (available)
  266. {
  267. var localVideoRenderParams = new TRTCRenderParams()
  268. {
  269. fillMode = TRTCVideoFillMode.TRTCVideoFillMode_Fit
  270. };
  271. _tRTCCloud?.setRemoteRenderParams(userId, TRTCVideoStreamType.TRTCVideoStreamTypeSub, ref localVideoRenderParams);
  272. _tRTCCloud?.startRemoteView(userId, TRTCVideoStreamType.TRTCVideoStreamTypeSub, IntPtr.Zero);
  273. }
  274. else
  275. {
  276. _tRTCCloud?.stopRemoteView(userId, TRTCVideoStreamType.TRTCVideoStreamTypeSub);
  277. }
  278. }
  279. //用户是否开启摄像头视频
  280. public void onUserVideoAvailable(string userId, bool available)
  281. {
  282. if (available)
  283. {
  284. _tRTCCloud?.startRemoteView(userId, TRTCVideoStreamType.TRTCVideoStreamTypeBig, IntPtr.Zero);
  285. _tRTCCloud?.setRemoteVideoRenderCallback(userId, TRTCVideoPixelFormat.TRTCVideoPixelFormat_BGRA32, TRTCVideoBufferType.TRTCVideoBufferType_Buffer, _remoteVideoRenderCallback);
  286. }
  287. else
  288. {
  289. _tRTCCloud?.stopRemoteView(userId, TRTCVideoStreamType.TRTCVideoStreamTypeBig);
  290. _tRTCCloud?.setRemoteVideoRenderCallback(userId, TRTCVideoPixelFormat.TRTCVideoPixelFormat_BGRA32, TRTCVideoBufferType.TRTCVideoBufferType_Buffer, null);
  291. }
  292. }
  293. public void onConnectionLost()
  294. {
  295. // SDK 跟服务器的连接断开
  296. ConnectionLostNotification?.Invoke();
  297. }
  298. public void onConnectionRecovery()
  299. {
  300. // SDK 跟服务器的连接恢复
  301. ConnectionRecoveryNotification?.Invoke();
  302. }
  303. public void onTryToReconnect()
  304. {
  305. //SDK尝试重新连接到服务器
  306. TryToReconnectNotification?.Invoke();
  307. }
  308. public void onDeviceChange(string deviceId, TXMediaDeviceType type, TRTCDeviceState state)
  309. {
  310. //本地设备通断回调
  311. }
  312. public void onEnterRoom(int result)
  313. {
  314. //已加入房间的回调
  315. _joinRoomWaitor.Set();
  316. if (result >= 0)
  317. {
  318. _chatUserEnterRoomSuccess = true;
  319. }
  320. else
  321. {
  322. //添加加入房间失败事件
  323. }
  324. }
  325. public void onExitRoom(int reason)
  326. {
  327. //离开房间的事件回调
  328. _leafRoomWaitor.Set();
  329. }
  330. public void onRemoteUserEnterRoom(string userId)
  331. {
  332. // 有用户加入当前房间
  333. RemoteUserEnterRoomNotification?.Invoke(userId);
  334. }
  335. public void onRemoteUserLeaveRoom(string userId, int reason)
  336. {
  337. // 有用户离开当前房间
  338. RemoteUserLeaveRoomNotification?.Invoke(userId, reason);
  339. }
  340. public void onWarning(TXLiteAVWarning warningCode, string warningMsg, IntPtr arg)
  341. {
  342. //警告回调:告知一些非严重性问题,卡顿或可恢复的解码失败
  343. }
  344. public void onError(TXLiteAVError errCode, string errMsg, IntPtr arg)
  345. {
  346. //错误回调,SDK不可恢复的错误,一定要监听,并分情况给用户界面适当的提示
  347. }
  348. #region 未使用事件
  349. public void onAudioDeviceCaptureVolumeChanged(uint volume, bool muted)
  350. {
  351. // 当前音频采集设备音量变化通知
  352. }
  353. public void onAudioDevicePlayoutVolumeChanged(uint volume, bool muted)
  354. {
  355. // 当前音频播放设备音量变化通知
  356. }
  357. public void onFirstAudioFrame(string userId)
  358. {
  359. //开始播放远程用户的首帧音频(本地声音不通知)
  360. }
  361. public void onFirstVideoFrame(string userId, TRTCVideoStreamType streamType, int width, int height)
  362. {
  363. //开始渲染本地或远程用户看到的首帧画面
  364. }
  365. public void onLocalRecordBegin(int errCode, string storagePath)
  366. {
  367. //录制任务已开始
  368. }
  369. public void onLocalRecordComplete(int errCode, string storagePath)
  370. {
  371. //录制任务已结束
  372. }
  373. public void onLocalRecording(int duration, string storagePath)
  374. {
  375. //录制任务进行中
  376. }
  377. public void onMicDidReady()
  378. {
  379. //麦克风准备就绪
  380. }
  381. public void onAudioEffectFinished(int effectId, int code)
  382. {
  383. //播放音效结束回调
  384. }
  385. public void onCameraDidReady()
  386. {
  387. // 摄像头准备就绪
  388. }
  389. public void onMissCustomCmdMsg(string userId, int cmdId, int errCode, int missed)
  390. {
  391. //自定义消息丢失回调
  392. }
  393. public void onNetworkQuality(TRTCQualityInfo localQuality, TRTCQualityInfo[] remoteQuality, uint remoteQualityCount)
  394. {
  395. //网络质量回调(统计上行与下行质量,2s调用一次)
  396. }
  397. public void onPlayBGMBegin(TXLiteAVError errCode)
  398. {
  399. //开始播放背景音乐(已被废弃)
  400. }
  401. public void onPlayBGMComplete(TXLiteAVError errCode)
  402. {
  403. //播放背景音乐结束(已被废弃)
  404. }
  405. public void onPlayBGMProgress(uint progressMS, uint durationMS)
  406. {
  407. // 播放背景音乐的进度(已被废弃)
  408. }
  409. public void onRecvCustomCmdMsg(string userId, int cmdID, uint seq, byte[] msg, uint msgSize)
  410. {
  411. //收到自定义消息回调
  412. }
  413. public void onRecvSEIMsg(string userId, byte[] message, uint msgSize)
  414. {
  415. //收到SEI消息的回调
  416. }
  417. public void onRemoteVideoStatusUpdated(string userId, TRTCVideoStreamType streamType, TRTCAVStatusType status, TRTCAVStatusChangeReason reason, IntPtr extrainfo)
  418. {
  419. //远端视频状态变化的事件回调
  420. }
  421. public void onScreenCaptureCovered()
  422. {
  423. // 屏幕分享被遮挡回调
  424. }
  425. public void onScreenCapturePaused(int reason)
  426. {
  427. // 屏幕分享暂停回调
  428. }
  429. public void onScreenCaptureResumed(int reason)
  430. {
  431. // 屏幕分享恢复回调
  432. }
  433. public void onScreenCaptureStarted()
  434. {
  435. // 屏幕开始分享回调
  436. }
  437. public void onScreenCaptureStoped(int reason)
  438. {
  439. // 屏幕停止分享回调
  440. }
  441. public void onSendFirstLocalAudioFrame()
  442. {
  443. //首帧本地音频已被发送
  444. }
  445. public void onSendFirstLocalVideoFrame(TRTCVideoStreamType streamType)
  446. {
  447. //首帧本地视频数据已被发送
  448. }
  449. public void onSetMixTranscodingConfig(int errCode, string errMsg)
  450. {
  451. // 设置云端混流转码参数的回调
  452. }
  453. public void onSnapshotComplete(string userId, TRTCVideoStreamType type, byte[] data, uint length, uint width, uint height, TRTCVideoPixelFormat format)
  454. {
  455. //截图完成时的回调
  456. }
  457. public void onSpeedTest(TRTCSpeedTestResult currentResult, uint finishedCount, uint totalCount)
  458. {
  459. //服务器测速回调
  460. }
  461. public void onStartPublishCDNStream(int errCode, string errMsg)
  462. {
  463. // 启动旁路推流到CDN完成的回调
  464. }
  465. public void onStartPublishing(int errCode, string errMsg)
  466. {
  467. //开始向腾讯云的直播CDN推流的回调,对应于TRTCCloud中的startPublishing()接口
  468. }
  469. public void onStatistics(TRTCStatistics statis)
  470. {
  471. //技术指标回调
  472. }
  473. public void onStopPublishCDNStream(int errCode, string errMsg)
  474. {
  475. //停止旁路推流到CDN完成的回调
  476. }
  477. public void onStopPublishing(int errCode, string errMsg)
  478. {
  479. //停止想腾讯云的直播CDN推流的回调,对应于TRTCCloud中的stopPublishing()接口
  480. }
  481. public void onSwitchRole(TXLiteAVError errCode, string errMsg)
  482. {
  483. // 切换角色的回调
  484. }
  485. public void onSwitchRoom(TXLiteAVError errCode, string errMsg)
  486. {
  487. //切换房间(switchRoom)结果的回调
  488. }
  489. public void onTestMicVolume(uint volume)
  490. {
  491. //麦克风测试音量回调
  492. }
  493. public void onTestSpeakerVolume(uint volume)
  494. {
  495. // 扬声器测试音量回调
  496. }
  497. public void onUserAudioAvailable(string userId, bool available)
  498. {
  499. // 用户是否开启音频上行
  500. }
  501. public void onUserEnter(string userId)
  502. {
  503. //有主播加入当前房间(废弃接口)
  504. }
  505. public void onUserExit(string userId, int reason)
  506. {
  507. //由用户离开当前房间(废弃接口)
  508. }
  509. public void onUserVoiceVolume(TRTCVolumeInfo[] userVolumes, uint userVolumesCount, uint totalVolume)
  510. {
  511. //用于提示音量大小的回调
  512. }
  513. public void onConnectOtherRoom(string userId, TXLiteAVError errCode, string errMsg)
  514. {
  515. throw new NotImplementedException();
  516. }
  517. public void onDisconnectOtherRoom(TXLiteAVError errCode, string errMsg)
  518. {
  519. throw new NotImplementedException();
  520. }
  521. #endregion
  522. }
  523. }