AgoraVideoAudioManager.cs 31 KB

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