AgoraVideoAudioManager.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  1. using Agora.Rtc;
  2. using Agora.Util;
  3. using SC.XR.Unity;
  4. using System;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Text;
  9. using UnityEngine;
  10. using UnityEngine.Rendering;
  11. using UnityEngine.Serialization;
  12. using UnityEngine.UI;
  13. using XRTool.Util;
  14. using Logger = Agora.Util.Logger;
  15. public class AgoraVideoAudioManager : SingletonMono<AgoraVideoAudioManager>
  16. {
  17. [FormerlySerializedAs("appIdInput")]
  18. [SerializeField]
  19. private AppIdInput _appIdInput;
  20. [Header("_____________Basic Configuration_____________")]
  21. [FormerlySerializedAs("APP_ID")]
  22. [SerializeField]
  23. private string _appID = "";
  24. [FormerlySerializedAs("TOKEN")]
  25. [SerializeField]
  26. private string _token = "";
  27. [FormerlySerializedAs("CHANNEL_NAME")]
  28. [SerializeField]
  29. private string _channelName = "";
  30. internal IRtcEngine RtcEngine = null;
  31. internal Logger Log;
  32. private bool isAudio;
  33. private bool isVideo;
  34. //private static List<Agora.Rtc.UserInfo> list_UserInfo;
  35. private Dictionary<string, uint> dicPeeridAndUid;
  36. public Text LogText;
  37. private bool isRoom;
  38. private CustomPeer myPeer;
  39. public uint uid;
  40. public string userAccount;
  41. // private Dictionary<string, RawImage> list_ShowView;
  42. // public MenuIcon menuIcon;
  43. public bool isSwitchCamera;
  44. // Use this for initialization
  45. private string mainViewPeerId;
  46. private bool isSendVideo;
  47. public List<CustomPeer> listCustomPeer;
  48. private void Start()
  49. {
  50. LoadAssetData();
  51. if (CheckAppId())
  52. {
  53. InitEngine();
  54. //SetChinnelName("0003003");
  55. //JoinChannel();
  56. //SetupUI();
  57. }
  58. //list_UserInfo = new List<Agora.Rtc.UserInfo>();
  59. // list_ShowView = new Dictionary<string, RawImage>();
  60. dicPeeridAndUid = new Dictionary<string, uint>();
  61. isRoom = false;
  62. isSwitchCamera = false;
  63. listCustomPeer = new List<CustomPeer>();
  64. //RTCManager.Instance.OnJoinChannel += JoinChannel;
  65. //RTCManager.Instance.OnLeaveChannel += LeaveChannel;
  66. //RTCManager.Instance.OnShowViewRawImage += AddListShowView;
  67. //RTCManager.Instance.OnMuteLocalAudioStream += EnableLoacalAudio;
  68. //RTCManager.Instance.OnMuteLocalVideoStream += EnableLocalVideo;
  69. //RTCManager.Instance.OnMuteRemoteAudioStream += MuteRemoteAudioStream;
  70. //RTCManager.Instance.OnMuteRemoteVideoStream += MuteRemoteVideoStream;
  71. //RTCManager.Instance.OnSetUid += SetUid;
  72. //RTCManager.Instance.OnSetChannelName += SetChinnelName;
  73. //RTCManager.Instance.OnAddPeeridUid += AddPeeridUid;
  74. //RTCManager.Instance.OnRemAtPeeridUid += RemAtPeeridUid;
  75. PermissionHelper.RequestMicrophontPermission();
  76. PermissionHelper.RequestCameraPermission();
  77. }
  78. // Update is called once per frame
  79. private void Update()
  80. {
  81. //if(isRoom&&CommonMethod.MyPeer!=null&&list_ShowView.Count>0)
  82. //{
  83. // if(myPeer==null)
  84. // {
  85. // myPeer = (CustomPeer)StudioRtc.Instance.customPeerList.getPeerName(CommonMethod.MyPeer.PeerId);
  86. // Debug.Log(" Get MyCustomPeer");
  87. // }
  88. // if (myPeer == null) return;
  89. // if (isAudio != myPeer.isAudio)
  90. // {
  91. // isAudio = myPeer.isAudio;
  92. // EnableLoacalAudio(isAudio);
  93. // }
  94. // if(isVideo!= myPeer.isVideo)
  95. // {
  96. // isVideo = myPeer.isVideo;
  97. // EnableLocalVideo(isVideo);
  98. // }
  99. //}
  100. }
  101. //Show data in AgoraBasicProfile
  102. [ContextMenu("ShowAgoraBasicProfileData")]
  103. private void LoadAssetData()
  104. {
  105. if (_appIdInput == null) return;
  106. _appID = _appIdInput.appID;
  107. _token = _appIdInput.token;
  108. _channelName = _appIdInput.channelName;
  109. }
  110. private bool CheckAppId()
  111. {
  112. Log = new Logger(LogText);
  113. return Log.DebugAssert(_appID.Length > 10, "Please fill in your appId in API-Example/profile/appIdInput.asset");
  114. }
  115. private void InitEngine()
  116. {
  117. RtcEngine = Agora.Rtc.RtcEngine.CreateAgoraRtcEngine();
  118. AgoraVideoManagerHandler handler = new AgoraVideoManagerHandler(this);
  119. RtcEngineContext context = new RtcEngineContext(_appID, 0,
  120. CHANNEL_PROFILE_TYPE.CHANNEL_PROFILE_COMMUNICATION,
  121. AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_DEFAULT);
  122. // RtcEngine.SetCameraDeviceOrientation(VIDEO_SOURCE_TYPE.VIDEO_SOURCE_CAMERA, VIDEO_ORIENTATION.VIDEO_ORIENTATION_90);
  123. RtcEngine.Initialize(context);
  124. RtcEngine.InitEventHandler(handler);
  125. }
  126. public void RegisterLocalUserAccount(string peerId)
  127. {
  128. RtcEngine.RegisterLocalUserAccount(_appID, peerId);
  129. }
  130. public void SetChinnelName(string roomid)
  131. {
  132. _channelName = roomid;
  133. }
  134. public void SetUid(string uid)
  135. {
  136. this.uid = StringToUint(uid);
  137. }
  138. public void JoinChannel()
  139. {
  140. Debug.Log(" JoinChannel " + _channelName);
  141. RtcEngine.EnableAudio();
  142. RtcEngine.EnableVideo();
  143. // RtcEngine.DisableAudio();
  144. // RtcEngine.DisableVideo();
  145. // VideoEncoderConfiguration config = new VideoEncoderConfiguration();
  146. //config.dimensions = new VideoDimensions(1280, 720);
  147. //config.frameRate = 15;
  148. //config.bitrate = 0;
  149. // config.orientationMode = ORIENTATION_MODE.ORIENTATION_MODE_ADAPTIVE;
  150. // RtcEngine.SetVideoEncoderConfiguration(config);
  151. RtcEngine.SetChannelProfile(CHANNEL_PROFILE_TYPE.CHANNEL_PROFILE_COMMUNICATION);
  152. RtcEngine.SetClientRole(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  153. // _channelName = roomid;
  154. SenderOptions s = new SenderOptions();
  155. s.targetBitrate = 1000;
  156. RtcEngine.SetExternalVideoSource(true, true, EXTERNAL_VIDEO_SOURCE_TYPE.VIDEO_FRAME,s);
  157. RtcEngine.SetRemoteDefaultVideoStreamType(VIDEO_STREAM_TYPE.VIDEO_STREAM_LOW);
  158. if (DeviceType.type == "DreamGlass")
  159. RtcEngine.SetAudioProfile(0, AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_GAME_STREAMING);
  160. // RtcEngine.SetLocalVideoMirrorMode(VIDEO_MIRROR_MODE_TYPE.VIDEO_MIRROR_MODE_ENABLED);
  161. RtcEngine.JoinChannel(_token, _channelName, "", uid);
  162. Debug.Log("uid " + uid);
  163. //RtcEngine.MuteLocalVideoStream(false);
  164. //RtcEngine.MuteLocalAudioStream(false);
  165. //RtcEngine.MuteAllRemoteAudioStreams(true);
  166. //RtcEngine.MuteAllRemoteVideoStreams(true);
  167. isRoom = true;
  168. EnableLoacalAudio(CustomInfo.isSendAudio);
  169. EnableLocalVideo(CustomInfo.isSendVideo);
  170. isSendVideo = CustomInfo.isSendVideo;
  171. StartCoroutine(RenderTexturesScreenCapture());
  172. }
  173. public void OpenAgoraAudio()
  174. {
  175. Debug.Log(" 打开 OpenAgoraAudio ");
  176. // RtcEngine.SwitchCamera();
  177. //RtcEngine.MuteAllRemoteAudioStreams(false);
  178. //RtcEngine.MuteAllRemoteVideoStreams(false);
  179. // RtcEngine.EnableAudio();
  180. }
  181. Texture2D screenShot;
  182. public Camera ca;
  183. public RawImage img;
  184. IEnumerator RenderTexturesScreenCapture()
  185. {
  186. Debug.Log("RenderTexturesScreenCapture发送图片1");
  187. yield return new WaitForEndOfFrame();
  188. if (screenShot == null)
  189. {
  190. screenShot = new Texture2D(CustomInfo.mWidth, CustomInfo.mHight, TextureFormat.RGBA32, false);
  191. StartCoroutine(GetRenederFPS());
  192. }
  193. while (true)
  194. {
  195. // if (isSendVideo)
  196. // continue;
  197. // img.texture = RemoteRtc.Instance.cam.activeTexture;
  198. // RenderTexture.active = ca.activeTexture;
  199. // screenShot.ReadPixels(new Rect(0, 0, ca.activeTexture.width, ca.activeTexture.height), 0, 0);
  200. // screenShot.Apply();
  201. //Camera.main.targetTexture = null;
  202. // RenderTexture.active = null;
  203. yield return new WaitForSeconds(0.05f);
  204. if(bts!=null)
  205. {
  206. // screenShot = HorizontalFlipTexture(screenShot2);
  207. var timetick = System.DateTime.Now.Ticks / 10000;
  208. ExternalVideoFrame externalVideoFrame = new ExternalVideoFrame();
  209. externalVideoFrame.type = VIDEO_BUFFER_TYPE.VIDEO_BUFFER_RAW_DATA;
  210. externalVideoFrame.format = VIDEO_PIXEL_FORMAT.VIDEO_PIXEL_RGBA;
  211. externalVideoFrame.buffer = bts;// screenShot.GetRawTextureData();
  212. externalVideoFrame.stride = (int)screenShot.width;
  213. externalVideoFrame.height = (int)screenShot.height;
  214. externalVideoFrame.rotation = 180;
  215. externalVideoFrame.cropLeft = 1;
  216. externalVideoFrame.cropRight = 1;
  217. externalVideoFrame.timestamp = timetick;
  218. RtcEngine.PushVideoFrame(externalVideoFrame);
  219. }
  220. }
  221. }
  222. byte[] bts;
  223. IEnumerator GetRenederFPS()
  224. {
  225. while (true)
  226. {
  227. var req = AsyncGPUReadback.Request(RemoteRtc.Instance.cam2.activeTexture);
  228. yield return new WaitUntil(() => req.done);
  229. if (!req.hasError)
  230. {
  231. if (bts == null)
  232. {
  233. bts = new byte[req.layerDataSize];
  234. }
  235. req.GetData<byte>().CopyTo(bts);
  236. // screenShot.LoadRawTextureData(bts);
  237. // screenShot.Apply();
  238. // tex.SetPixels32(req.GetData<Color32>().ToArray());
  239. // img.texture = screenShot;
  240. }
  241. else
  242. {
  243. Debug.LogError("Error AsyncGPUReadbackRequest.hasError");
  244. }
  245. }
  246. }
  247. Texture2D flipTexture;
  248. private IEnumerator CloseChannel(float times)
  249. {
  250. yield return new WaitForSeconds(times);
  251. LeaveChannel();
  252. }
  253. public void LeaveChannel()
  254. {
  255. Debug.Log("LeaveChannel ");
  256. int msg = RtcEngine.LeaveChannel();
  257. switch (msg)
  258. {
  259. case 0:
  260. LogText.text = "成功退出频道: " + _channelName;
  261. break;
  262. default:
  263. LogText.text = "退出频道失败: " + msg;
  264. break;
  265. }
  266. isRoom = false;
  267. myPeer = null;
  268. dicPeeridAndUid.Clear();
  269. dicPeeridAndUid = new Dictionary<string, uint>();
  270. AgoraVideoAudioManager.Instance.listCustomPeer.Clear();
  271. AgoraVideoAudioManager.Instance.listCustomPeer = new List<CustomPeer>();
  272. //list_ShowView.Clear();
  273. //list_ShowView = new Dictionary<string, RawImage>();
  274. mainViewPeerId = "";
  275. RoomMain.Instance.agoraRawImage.gameObject.SetActive(false);
  276. RoomMain.Instance.agoraRawImage.texture = null;
  277. DestroyImmediate(RoomMain.Instance.agoraRawImage.GetComponent<UIElementDrag>());
  278. DestroyImmediate(RoomMain.Instance.agoraRawImage.GetComponent<VideoSurface>());
  279. }
  280. public void VuforiaLeaveChannel()
  281. {
  282. int msg = RtcEngine.LeaveChannel();
  283. switch (msg)
  284. {
  285. case 0:
  286. LogText.text = "成功退出频道: " + _channelName;
  287. break;
  288. default:
  289. LogText.text = "退出频道失败: " + msg;
  290. break;
  291. }
  292. }
  293. public void AddPeeridUid(string peerid, uint uid)
  294. {
  295. Debug.Log(" AddPeeridUid " + peerid + " " + uid);
  296. if (dicPeeridAndUid.ContainsKey(peerid))
  297. return;
  298. dicPeeridAndUid.Add(peerid, uid);
  299. }
  300. public void AddPeeridUid(string peerid, string strUid)
  301. {
  302. uint uid = StringToUint(strUid);
  303. Debug.Log(" AddPeeridUid " + peerid + " " + uid);
  304. if (dicPeeridAndUid.ContainsKey(peerid))
  305. return;
  306. dicPeeridAndUid.Add(peerid, uid);
  307. }
  308. public void RemAtPeeridUid(string peerid)
  309. {
  310. if (!dicPeeridAndUid.ContainsKey(peerid))
  311. return;
  312. Debug.Log(" RemAtPeeridUid " + peerid + " " + dicPeeridAndUid[peerid]);
  313. dicPeeridAndUid.Remove(peerid);
  314. CloseAgoraMainImage(peerid, false);
  315. for (int i = 0; i < listCustomPeer.Count; i++)
  316. {
  317. if (listCustomPeer[i].peerId == peerid)
  318. listCustomPeer.RemoveAt(i);
  319. }
  320. }
  321. private void CloseAgoraMainImage(string peerid, bool isOpen)
  322. {
  323. if (peerid == mainViewPeerId)
  324. RoomMain.Instance.agoraRawImage.gameObject.SetActive(isOpen);
  325. }
  326. public void ShowLocalView(RawImage rawImage)
  327. {
  328. rawImage.gameObject.SetActive(true);
  329. rawImage.rectTransform.localEulerAngles = new Vector3(0, 180, 180);
  330. MakeVideoView(0, rawImage);
  331. }
  332. public void AddListShowView(string peerId, RawImage rawImage, bool isMainView)
  333. {
  334. if (!dicPeeridAndUid.ContainsKey(peerId))
  335. return;
  336. Debug.Log(" AddListShowView " + peerId);
  337. if (isMainView)
  338. mainViewPeerId = peerId;
  339. rawImage.gameObject.SetActive(true);
  340. rawImage.rectTransform.localEulerAngles = new Vector3(0, 180, 180);
  341. MakeVideoView(dicPeeridAndUid[peerId], rawImage, this._channelName);
  342. }
  343. public void AddListShowView(string peerId, RawImage rawImage)
  344. {
  345. if (!dicPeeridAndUid.ContainsKey(peerId))
  346. return;
  347. Debug.Log(" AddListShowView " + peerId);
  348. if (rawImage.name == "AgoraRawImage")
  349. mainViewPeerId = peerId;
  350. // rawImage.gameObject.SetActive(true);
  351. rawImage.rectTransform.localEulerAngles = new Vector3(0, 180, 180);
  352. MakeVideoView(dicPeeridAndUid[peerId], rawImage, this._channelName);
  353. }
  354. public void ShowOneView(RawImage rawImage)
  355. {
  356. if (dicPeeridAndUid.Count < 2)
  357. return;
  358. // rawImage.gameObject.SetActive(true);
  359. rawImage.rectTransform.localEulerAngles = new Vector3(0, 180, 180);
  360. MakeVideoView(dicPeeridAndUid.Values.Skip(1).First(), rawImage, this._channelName);
  361. }
  362. public void UserJoined(uint uid)
  363. {
  364. if (uid == dicPeeridAndUid.Values.Skip(1).First())
  365. {
  366. // RoomMain.Instance.agoraRawImage.gameObject.SetActive(true);
  367. RoomMain.Instance.agoraRawImage.rectTransform.localEulerAngles = new Vector3(0, 180, 180);
  368. MakeVideoView(dicPeeridAndUid.Values.Skip(1).First(), RoomMain.Instance.agoraRawImage, this._channelName);
  369. foreach (var item in dicPeeridAndUid)
  370. {
  371. if (item.Value == uid)
  372. mainViewPeerId = item.Key;
  373. }
  374. }
  375. }
  376. public void EnableLoacalAudio(bool isAudio)
  377. {
  378. int msg = RtcEngine.MuteLocalAudioStream(!isAudio);
  379. // int msg = RtcEngine.EnableLocalAudio(isAudio);
  380. switch (msg)
  381. {
  382. case 0:
  383. Debug.Log(isAudio ? "打开本地音频成功" : "关闭本地音频成功 ");
  384. break;
  385. default:
  386. Debug.LogError("开关本地音频失败: " + msg);
  387. break;
  388. }
  389. }
  390. public void EnableLocalVideo(bool isVideo)
  391. {
  392. int msg = RtcEngine.MuteLocalVideoStream(!isVideo);
  393. //RtcEngine.EnableVideo();
  394. //int msg = RtcEngine.EnableLocalVideo(isVideo);
  395. //if(isVideo)
  396. // RemoteRtc.Instance.InitCamera();
  397. switch (msg)
  398. {
  399. case 0:
  400. Debug.Log(isVideo ? "打开本地视频成功 " : "关闭本地视频成功 ");
  401. break;
  402. default:
  403. Debug.LogError("开关本地视频失败: " + msg);
  404. break;
  405. }
  406. }
  407. public void MuteRemoteAudioStream(string uid, bool isAudio)
  408. {
  409. int msg = RtcEngine.MuteRemoteAudioStream(StringToUint(uid) , !isAudio);
  410. switch (msg)
  411. {
  412. case 0:
  413. Debug.Log(isAudio ? "订阅远端音频成功" : "取订远端音频成功 ");
  414. break;
  415. default:
  416. Debug.LogError("远端音频失败: " + msg);
  417. break;
  418. }
  419. }
  420. public void MuteRemoteVideoStream(string peerid, bool isVideo)
  421. {
  422. if (!dicPeeridAndUid.ContainsKey(peerid))
  423. return;
  424. int msg = RtcEngine.MuteRemoteVideoStream(dicPeeridAndUid[peerid], !isVideo);
  425. switch (msg)
  426. {
  427. case 0:
  428. Debug.Log(isVideo ? "订阅远端视频成功" : "取订远端视频成功 ");
  429. break;
  430. default:
  431. Debug.LogError("远端视频失败: " + msg);
  432. break;
  433. }
  434. CloseAgoraMainImage(peerid, !isVideo);
  435. }
  436. public void RemoteVideoStateChanged(uint uid, REMOTE_VIDEO_STATE state, REMOTE_VIDEO_STATE_REASON
  437. reason)
  438. {
  439. Debug.Log("RemoteVideoStateChanged " + reason);
  440. if (!dicPeeridAndUid.ContainsValue(uid))
  441. return;
  442. for (int i = 0; i < listCustomPeer.Count; i++)
  443. {
  444. if (dicPeeridAndUid[listCustomPeer[i].peerId] == uid)
  445. {
  446. switch (state)
  447. {
  448. case REMOTE_VIDEO_STATE.REMOTE_VIDEO_STATE_STOPPED:
  449. // listCustomPeer[i].isVideo = false;
  450. break;
  451. case REMOTE_VIDEO_STATE.REMOTE_VIDEO_STATE_STARTING:
  452. listCustomPeer[i].isVideo = true;
  453. CloseAgoraMainImage(listCustomPeer[i].peerId, true);
  454. break;
  455. case REMOTE_VIDEO_STATE.REMOTE_VIDEO_STATE_DECODING:
  456. listCustomPeer[i].isCloseVideo = false;
  457. CloseAgoraMainImage(listCustomPeer[i].peerId, true);
  458. break;
  459. case REMOTE_VIDEO_STATE.REMOTE_VIDEO_STATE_FROZEN:
  460. break;
  461. case REMOTE_VIDEO_STATE.REMOTE_VIDEO_STATE_FAILED:
  462. // listCustomPeer[i].isVideo = false;
  463. break;
  464. default:
  465. break;
  466. }
  467. switch (reason)
  468. {
  469. case REMOTE_VIDEO_STATE_REASON.REMOTE_VIDEO_STATE_REASON_INTERNAL:
  470. break;
  471. case REMOTE_VIDEO_STATE_REASON.REMOTE_VIDEO_STATE_REASON_NETWORK_CONGESTION://网络阻塞。
  472. // listCustomPeer[i].isVideo = false;
  473. break;
  474. case REMOTE_VIDEO_STATE_REASON.REMOTE_VIDEO_STATE_REASON_NETWORK_RECOVERY:// 网络恢复正常。
  475. // listCustomPeer[i].isVideo = true;
  476. break;
  477. case REMOTE_VIDEO_STATE_REASON.REMOTE_VIDEO_STATE_REASON_LOCAL_MUTED://本地用户停止接收远端视频流或本地用户禁用视频模块
  478. listCustomPeer[i].isCloseVideo = true;
  479. CloseAgoraMainImage(listCustomPeer[i].peerId, false);
  480. break;
  481. case REMOTE_VIDEO_STATE_REASON.REMOTE_VIDEO_STATE_REASON_LOCAL_UNMUTED://本地用户恢复接收远端视频流或本地用户启动视频模块
  482. listCustomPeer[i].isCloseVideo = false;
  483. CloseAgoraMainImage(listCustomPeer[i].peerId, true);
  484. break;
  485. case REMOTE_VIDEO_STATE_REASON.REMOTE_VIDEO_STATE_REASON_REMOTE_MUTED://远端用户停止发送视频流或远端用户禁用视频模块。
  486. listCustomPeer[i].isVideo = false;
  487. CloseAgoraMainImage(listCustomPeer[i].peerId, false);
  488. break;
  489. case REMOTE_VIDEO_STATE_REASON.REMOTE_VIDEO_STATE_REASON_REMOTE_UNMUTED://远端用户恢复发送视频流或远端用户启用视频模块。
  490. listCustomPeer[i].isVideo = true;
  491. CloseAgoraMainImage(listCustomPeer[i].peerId, true);
  492. break;
  493. case REMOTE_VIDEO_STATE_REASON.REMOTE_VIDEO_STATE_REASON_REMOTE_OFFLINE: //远端用户离开频道。
  494. listCustomPeer[i].isVideo = false;
  495. break;
  496. case REMOTE_VIDEO_STATE_REASON.REMOTE_VIDEO_STATE_REASON_AUDIO_FALLBACK:
  497. break;
  498. case REMOTE_VIDEO_STATE_REASON.REMOTE_VIDEO_STATE_REASON_AUDIO_FALLBACK_RECOVERY:
  499. break;
  500. case REMOTE_VIDEO_STATE_REASON.REMOTE_VIDEO_STATE_REASON_VIDEO_STREAM_TYPE_CHANGE_TO_LOW:
  501. break;
  502. case REMOTE_VIDEO_STATE_REASON.REMOTE_VIDEO_STATE_REASON_VIDEO_STREAM_TYPE_CHANGE_TO_HIGH:
  503. break;
  504. default:
  505. break;
  506. }
  507. break;
  508. }
  509. }
  510. }
  511. public void RemoteAudioStateChanged(uint uid, REMOTE_AUDIO_STATE state, REMOTE_AUDIO_STATE_REASON reason)
  512. {
  513. Debug.Log(listCustomPeer.Count);
  514. Debug.Log("RemoteAudioStateChanged " + uid);
  515. if (!dicPeeridAndUid.ContainsValue(uid))
  516. return;
  517. Debug.Log("RemoteAudioStateChanged " + 1);
  518. for (int i = 0; i < listCustomPeer.Count; i++)
  519. {
  520. Debug.Log(listCustomPeer[i].peerId);
  521. if (dicPeeridAndUid[listCustomPeer[i].peerId] == uid)
  522. {
  523. Debug.Log("RemoteAudioStateChanged " + 2);
  524. switch (reason)
  525. {
  526. case REMOTE_AUDIO_STATE_REASON.REMOTE_AUDIO_REASON_INTERNAL:
  527. break;
  528. case REMOTE_AUDIO_STATE_REASON.REMOTE_AUDIO_REASON_NETWORK_CONGESTION:
  529. // listCustomPeer[i].isAudio = false;
  530. break;
  531. case REMOTE_AUDIO_STATE_REASON.REMOTE_AUDIO_REASON_NETWORK_RECOVERY:
  532. // listCustomPeer[i].isAudio = true;
  533. break;
  534. case REMOTE_AUDIO_STATE_REASON.REMOTE_AUDIO_REASON_LOCAL_MUTED:
  535. listCustomPeer[i].isCloseAudio = true;
  536. break;
  537. case REMOTE_AUDIO_STATE_REASON.REMOTE_AUDIO_REASON_LOCAL_UNMUTED:
  538. listCustomPeer[i].isCloseAudio = false;
  539. break;
  540. case REMOTE_AUDIO_STATE_REASON.REMOTE_AUDIO_REASON_REMOTE_MUTED:
  541. listCustomPeer[i].isAudio = false;
  542. break;
  543. case REMOTE_AUDIO_STATE_REASON.REMOTE_AUDIO_REASON_REMOTE_UNMUTED:
  544. listCustomPeer[i].isAudio = true;
  545. break;
  546. case REMOTE_AUDIO_STATE_REASON.REMOTE_AUDIO_REASON_REMOTE_OFFLINE:
  547. listCustomPeer[i].isAudio = false;
  548. break;
  549. default:
  550. break;
  551. }
  552. break;
  553. }
  554. }
  555. }
  556. private uint StringToUint(string value)
  557. {
  558. //byte[] bytes = Encoding.ASCII.GetBytes(value);
  559. return (uint)int.Parse(value);
  560. // return BitConverter.ToUInt32(bytes);
  561. }
  562. private void StopPublish()
  563. {
  564. var options = new ChannelMediaOptions();
  565. options.publishMicrophoneTrack.SetValue(false);
  566. options.publishCameraTrack.SetValue(false);
  567. var nRet = RtcEngine.UpdateChannelMediaOptions(options);
  568. this.Log.UpdateLog("UpdateChannelMediaOptions: " + nRet);
  569. }
  570. private void StartPublish()
  571. {
  572. var options = new ChannelMediaOptions();
  573. options.publishMicrophoneTrack.SetValue(true);
  574. options.publishCameraTrack.SetValue(true);
  575. var nRet = RtcEngine.UpdateChannelMediaOptions(options);
  576. this.Log.UpdateLog("UpdateChannelMediaOptions: " + nRet);
  577. }
  578. private void OnDestroy()
  579. {
  580. Debug.Log("OnDestroy");
  581. if (RtcEngine == null) return;
  582. RtcEngine.InitEventHandler(null);
  583. RtcEngine.LeaveChannel();
  584. RtcEngine.Dispose();
  585. }
  586. internal string GetChannelName()
  587. {
  588. return _channelName;
  589. }
  590. internal static void MakeVideoView(uint uid, RawImage rawImage, string channelId = "")
  591. {
  592. Debug.Log("MakeVideoView " + uid);
  593. //var go = GameObject.Find(uid.ToString());
  594. //if (!ReferenceEquals(go, null))
  595. //{
  596. // return; // reuse
  597. //}
  598. // rawImage.gameObject.SetActive(true);
  599. // create a GameObject and assign to this new user
  600. var videoSurface = MakeImageSurface(rawImage);
  601. // var videoSurface = MakePlaneSurface(uid.ToString());
  602. if (ReferenceEquals(videoSurface, null)) return;
  603. // configure videoSurface
  604. if (uid == 0)
  605. {
  606. // videoSurface.SetForUser(uid, channelId);
  607. }
  608. else
  609. {
  610. videoSurface.SetForUser(uid, channelId, VIDEO_SOURCE_TYPE.VIDEO_SOURCE_REMOTE);
  611. }
  612. //videoSurface.OnTextureSizeModify += (int width, int height) =>
  613. //{
  614. // float scale = (float)height / (float)width;
  615. // videoSurface.transform.localScale = new Vector3(-5, 5 * scale, 1);
  616. // Debug.Log("OnTextureSizeModify: " + width + " " + height);
  617. //};
  618. videoSurface.SetEnable(true);
  619. // AgoraVideoAudioManager.Instance.EnableLocalVideo(false);
  620. }
  621. //internal static void OnUserInfoUpdated(uint uid, Agora.Rtc.UserInfo info)
  622. //{
  623. // Debug.Log(info.uid);
  624. // disUserPeer_Uid.Add("", info);
  625. //}
  626. internal static void OnUserJoined(uint uid)
  627. {
  628. // _videoSample.Log.UpdateLog(string.Format("OnUserJoined uid: ${0} elapsed: ${1}", uid, elapsed));
  629. // Debug.Log(string.Format("OnUserJoined uid: ${0} elapsed: ${1}", uid, elapsed))
  630. AgoraVideoAudioManager.Instance.UserJoined(uid);
  631. }
  632. internal static void OnRemoteVideoStateChanged(uint uid, REMOTE_VIDEO_STATE state, REMOTE_VIDEO_STATE_REASON
  633. reason)
  634. {
  635. AgoraVideoAudioManager.Instance.RemoteVideoStateChanged(uid, state, reason);
  636. }
  637. internal static void OnRemoteAudioStateChanged(uint uid, REMOTE_AUDIO_STATE state, REMOTE_AUDIO_STATE_REASON reason)
  638. {
  639. AgoraVideoAudioManager.Instance.RemoteAudioStateChanged(uid, state, reason);
  640. }
  641. #region -- Video Render UI Logic ---
  642. // VIDEO TYPE 1: 3D Object
  643. private static VideoSurface MakePlaneSurface(string goName)
  644. {
  645. var go = GameObject.CreatePrimitive(PrimitiveType.Quad);
  646. //for (int i = 0; i < list_UserInfo.Count; i++)
  647. //{
  648. // if (list_UserInfo[i].uid.ToString() == goName)
  649. // {
  650. // string userAccount = list_UserInfo[i].userAccount;
  651. // if (AgoraVideoAudioManager.Instance.list_ShowView.ContainsKey(list_UserInfo[i].userAccount))
  652. // {
  653. // go = AgoraVideoAudioManager.Instance.list_ShowView[list_UserInfo[i].userAccount].gameObject;
  654. // }
  655. // else
  656. // Debug.LogError(" Agora ShowView is NULL ");
  657. // }
  658. //}
  659. if (go == null)
  660. {
  661. go = GameObject.CreatePrimitive(PrimitiveType.Plane);
  662. return null;
  663. }
  664. go.name = goName;
  665. // set up transform
  666. go.transform.Rotate(-90.0f, 0.0f, 0.0f);
  667. //var yPos = Random.Range(3.0f, 5.0f);
  668. //var xPos = Random.Range(-2.0f, 2.0f);
  669. go.transform.position = Vector3.zero;
  670. go.transform.localScale = new Vector3(0.25f, 0.5f, 0.5f);
  671. // configure videoSurface
  672. var videoSurface = go.AddComponent<VideoSurface>();
  673. return videoSurface;
  674. }
  675. // Video TYPE 2: RawImage
  676. private static VideoSurface MakeImageSurface(RawImage rawImage)
  677. {
  678. //GameObject go = rawImage.gameObject;
  679. //if (go == null)
  680. //{
  681. // go = new GameObject();
  682. // //go.name = goName;
  683. // // to be renderered onto
  684. // go.AddComponent<RawImage>();
  685. // // set up transform
  686. // //go.transform.Rotate(0f, 0.0f, 180.0f);
  687. // //go.transform.localPosition = Vector3.zero;
  688. // //go.transform.localScale = new Vector3(2f, 3f, 1f);
  689. //}
  690. //if (go == null)
  691. //{
  692. // return null;
  693. //}
  694. // make the object draggable
  695. if (rawImage.gameObject.GetComponent<UIElementDrag>() != null)
  696. Destroy(rawImage.gameObject.GetComponent<UIElementDrag>());
  697. rawImage.gameObject.AddComponent<UIElementDrag>();
  698. //var canvas = GameObject.Find("VideoCanvas");
  699. //if (canvas != null)
  700. //{
  701. // go.transform.parent = canvas.transform;
  702. // Debug.Log("add video view");
  703. //}
  704. //else
  705. //{
  706. // Debug.Log("Canvas is null video view");
  707. //}
  708. // configure videoSurface
  709. if (rawImage.gameObject.GetComponent<VideoSurface>() != null)
  710. Destroy(rawImage.gameObject.GetComponent<VideoSurface>());
  711. var videoSurface = rawImage.gameObject.AddComponent<VideoSurface>();
  712. return videoSurface;
  713. }
  714. internal static void DestroyVideoView(uint uid)
  715. {
  716. var go = GameObject.Find(uid.ToString());
  717. if (!ReferenceEquals(go, null))
  718. {
  719. Destroy(go);
  720. }
  721. }
  722. internal static void OnUserInfoUpdated(uint uid, Agora.Rtc.UserInfo info)
  723. {
  724. Debug.Log(uid.ToString() + " " + info.uid + " " + info.userAccount);
  725. // list_UserInfo.Add(info);
  726. }
  727. internal static void OnLocalUserRegistered(uint uid, string userAccount)
  728. {
  729. //AgoraVideoAudioManager.Instance.uid = uid;
  730. //AgoraVideoAudioManager.Instance.userAccount = userAccount;
  731. }
  732. #endregion
  733. }
  734. #region -- Agora Event ---
  735. public class AgoraVideoManagerHandler : IRtcEngineEventHandler
  736. {
  737. private readonly AgoraVideoAudioManager _videoSample;
  738. internal AgoraVideoManagerHandler(AgoraVideoAudioManager videoSample)
  739. {
  740. _videoSample = videoSample;
  741. }
  742. public override void OnError(int err, string msg)
  743. {
  744. _videoSample.Log.UpdateLog(string.Format("OnError err: {0}, msg: {1}", err, msg));
  745. }
  746. public override void OnJoinChannelSuccess(RtcConnection connection, int elapsed)
  747. {
  748. int build = 0;
  749. Debug.Log("Agora: OnJoinChannelSuccess ");
  750. _videoSample.Log.UpdateLog(string.Format("sdk version: ${0}",
  751. _videoSample.RtcEngine.GetVersion(ref build)));
  752. _videoSample.Log.UpdateLog(string.Format("sdk build: ${0}",
  753. build));
  754. _videoSample.Log.UpdateLog(
  755. string.Format("OnJoinChannelSuccess channelName: {0}, uid: {1}, elapsed: {2}",
  756. connection.channelId, connection.localUid, elapsed));
  757. // _videoSample.ClickSelf();
  758. // AgoraVideoAudioManager.MakeVideoView(0);
  759. }
  760. public override void OnLeaveChannel(RtcConnection connection, RtcStats stats)
  761. {
  762. _videoSample.Log.UpdateLog("OnLeaveChannel");
  763. AgoraVideoAudioManager.DestroyVideoView(0);
  764. }
  765. public override void OnClientRoleChanged(RtcConnection connection, CLIENT_ROLE_TYPE oldRole, CLIENT_ROLE_TYPE newRole)
  766. {
  767. _videoSample.Log.UpdateLog("OnClientRoleChanged");
  768. }
  769. public override void OnUserJoined(RtcConnection connection, uint uid, int elapsed)
  770. {
  771. Debug.Log(string.Format("OnUserJoined uid: ${0} elapsed: ${1}", uid, elapsed));
  772. _videoSample.Log.UpdateLog(string.Format("OnUserJoined uid: ${0} elapsed: ${1}", uid, elapsed));
  773. AgoraVideoAudioManager.OnUserJoined(uid);
  774. // AgoraVideoAudioManager.MakeVideoView(uid, _videoSample.GetChannelName());
  775. }
  776. public override void OnUserOffline(RtcConnection connection, uint uid, USER_OFFLINE_REASON_TYPE reason)
  777. {
  778. _videoSample.Log.UpdateLog(string.Format("OnUserOffLine uid: ${0}, reason: ${1}", uid,
  779. (int)reason));
  780. // AgoraVideoAudioManager.DestroyVideoView(uid);
  781. }
  782. public override void OnUserInfoUpdated(uint uid, Agora.Rtc.UserInfo info)
  783. {
  784. _videoSample.Log.UpdateLog(string.Format(" 用户 :${0} 加入房间", uid));
  785. AgoraVideoAudioManager.OnUserInfoUpdated(uid, info);
  786. }
  787. public override void OnUplinkNetworkInfoUpdated(UplinkNetworkInfo info)
  788. {
  789. _videoSample.Log.UpdateLog("OnUplinkNetworkInfoUpdated");
  790. }
  791. public override void OnDownlinkNetworkInfoUpdated(DownlinkNetworkInfo info)
  792. {
  793. _videoSample.Log.UpdateLog("OnDownlinkNetworkInfoUpdated");
  794. }
  795. public override void OnRemoteVideoStateChanged(RtcConnection connection, uint remoteUid, REMOTE_VIDEO_STATE state, REMOTE_VIDEO_STATE_REASON reason, int elapsed)
  796. {
  797. AgoraVideoAudioManager.OnRemoteVideoStateChanged(remoteUid, state, reason);
  798. }
  799. public override void OnRemoteAudioStateChanged(RtcConnection connection, uint remoteUid, REMOTE_AUDIO_STATE state, REMOTE_AUDIO_STATE_REASON reason, int elapsed)
  800. {
  801. AgoraVideoAudioManager.OnRemoteAudioStateChanged(remoteUid, state, reason);
  802. }
  803. }
  804. #endregion