AgoraVideoAudioManager.cs 29 KB

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