AgoraTestVideo.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. using Agora.Rtc;
  2. using Agora.Util;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6. using UnityEngine.Serialization;
  7. using UnityEngine.UI;
  8. using Logger = Agora.Util.Logger;
  9. public class AgoraTestVideo : MonoBehaviour
  10. {
  11. [FormerlySerializedAs("appIdInput")]
  12. [SerializeField]
  13. private AppIdInput _appIdInput;
  14. [Header("_____________Basic Configuration_____________")]
  15. [FormerlySerializedAs("APP_ID")]
  16. [SerializeField]
  17. private string _appID = "";
  18. [FormerlySerializedAs("TOKEN")]
  19. [SerializeField]
  20. private string _token = "";
  21. [FormerlySerializedAs("CHANNEL_NAME")]
  22. [SerializeField]
  23. private string _channelName = "";
  24. internal static string _channelToken = "";
  25. internal static string _tokenBase = "http://localhost:8080";
  26. internal CONNECTION_STATE_TYPE _state = CONNECTION_STATE_TYPE.CONNECTION_STATE_DISCONNECTED;
  27. public uint uid;
  28. internal Logger Log;
  29. public Text Logtext;
  30. internal IRtcEngine rtcEngine;
  31. private RtcEngineEventHandler rtcEngineEventHandler;
  32. private RtcConnection rtcConnection;
  33. public InputField inputChannelName;
  34. public Button joinChannel;
  35. public Button leaveChannel;
  36. // Start is called before the first frame update
  37. void Start()
  38. {
  39. LoadAssetData();
  40. if (CheckAppId())
  41. {
  42. InitEngine();
  43. }
  44. joinChannel.onClick.AddListener(JoinChannel);
  45. leaveChannel.onClick.AddListener(LeavelChannel);
  46. }
  47. // Update is called once per frame
  48. void Update()
  49. {
  50. PermissionHelper.RequestMicrophontPermission();
  51. PermissionHelper.RequestCameraPermission();
  52. }
  53. [ContextMenu("ShowAgoraBasicProfileData")]
  54. private void LoadAssetData()
  55. {
  56. if (_appIdInput == null) return;
  57. _appID = _appIdInput.appID;
  58. _token = _appIdInput.token;
  59. _channelToken = _appIdInput.token;
  60. _channelName = _appIdInput.channelName;
  61. }
  62. private bool CheckAppId()
  63. {
  64. Log = new Logger(Logtext);
  65. return Log.DebugAssert(_appID.Length > 10, "Please fill in your appId in API-Example/profile/appIdInput.asset");
  66. }
  67. private void InitEngine()
  68. {
  69. rtcEngine = Agora.Rtc.RtcEngine.CreateAgoraRtcEngine();
  70. RtcEngineContext context = new RtcEngineContext(_appID, 0,
  71. CHANNEL_PROFILE_TYPE.CHANNEL_PROFILE_LIVE_BROADCASTING,
  72. AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_DEFAULT);
  73. rtcEngine.Initialize(context);
  74. UserEventHandler handler = new UserEventHandler(this);
  75. rtcEngine.InitEventHandler(handler);
  76. }
  77. private void JoinChannel()
  78. {
  79. _channelName = inputChannelName.text;
  80. rtcEngine.SetClientRole(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  81. rtcEngine.EnableAudio();
  82. rtcEngine.EnableVideo();
  83. //if (_channelToken.Length == 0)
  84. //{
  85. // Logtext.text = " Token NULL";
  86. // return;
  87. //}
  88. rtcEngine.JoinChannel(_channelToken, _channelName, "");
  89. }
  90. private void LeavelChannel()
  91. {
  92. int msg = rtcEngine.LeaveChannel();
  93. switch (msg)
  94. {
  95. case 0:
  96. Logtext.text = " 成功离开频道 "+ _channelName;
  97. break;
  98. default:
  99. Logtext.text = " 离开频道失败 " + msg;
  100. break;
  101. }
  102. }
  103. internal void RenewOrJoinToken(string newToken)
  104. {
  105. AgoraTestVideo._channelToken = newToken;
  106. if (_state == CONNECTION_STATE_TYPE.CONNECTION_STATE_DISCONNECTED
  107. || _state == CONNECTION_STATE_TYPE.CONNECTION_STATE_DISCONNECTED
  108. || _state == CONNECTION_STATE_TYPE.CONNECTION_STATE_FAILED
  109. )
  110. {
  111. // If we are not connected yet, connect to the channel as normal
  112. JoinChannel();
  113. }
  114. else
  115. {
  116. // If we are already connected, we should just update the token
  117. UpdateToken();
  118. }
  119. }
  120. private void UpdateToken()
  121. {
  122. rtcEngine.RenewToken(AgoraTestVideo._channelToken);
  123. }
  124. internal static void DestroyVideoView(uint uid)
  125. {
  126. GameObject go = GameObject.Find(uid.ToString());
  127. if (!ReferenceEquals(go, null))
  128. {
  129. Object.Destroy(go);
  130. }
  131. }
  132. internal static void MakeVideoView(uint uid, string channelId = "")
  133. {
  134. GameObject go = GameObject.Find(uid.ToString());
  135. if (!ReferenceEquals(go, null))
  136. {
  137. return; // reuse
  138. }
  139. // create a GameObject and assign to this new user
  140. VideoSurface videoSurface = MakeImageSurface(uid.ToString());
  141. if (!ReferenceEquals(videoSurface, null))
  142. {
  143. // configure videoSurface
  144. if (uid == 0)
  145. {
  146. videoSurface.SetForUser(uid, channelId);
  147. }
  148. else
  149. {
  150. videoSurface.SetForUser(uid, channelId, VIDEO_SOURCE_TYPE.VIDEO_SOURCE_REMOTE);
  151. }
  152. videoSurface.OnTextureSizeModify += (int width, int height) =>
  153. {
  154. float scale = (float)height / (float)width;
  155. videoSurface.transform.localScale = new Vector3(-5, 5 * scale, 1);
  156. Debug.Log("OnTextureSizeModify: " + width + " " + height);
  157. };
  158. videoSurface.SetEnable(true);
  159. }
  160. }
  161. internal string GetChannelName()
  162. {
  163. return _channelName;
  164. }
  165. private static VideoSurface MakeImageSurface(string goName)
  166. {
  167. GameObject go = new GameObject();
  168. if (go == null)
  169. {
  170. return null;
  171. }
  172. go.name = goName;
  173. // to be renderered onto
  174. go.AddComponent<RawImage>();
  175. // make the object draggable
  176. go.AddComponent<UIElementDrag>();
  177. GameObject canvas = GameObject.Find("VideoCanvas");
  178. if (canvas != null)
  179. {
  180. go.transform.parent = canvas.transform;
  181. Debug.Log("add video view");
  182. }
  183. else
  184. {
  185. Debug.Log("Canvas is null video view");
  186. }
  187. // set up transform
  188. go.transform.Rotate(0f, 0.0f, 180.0f);
  189. go.transform.localPosition = Vector3.zero;
  190. go.transform.localScale = new Vector3(3f, 4f, 1f);
  191. // configure videoSurface
  192. var videoSurface = go.AddComponent<VideoSurface>();
  193. return videoSurface;
  194. }
  195. private void OnDestroy()
  196. {
  197. Debug.Log("OnDestroy");
  198. if (rtcEngine == null) return;
  199. rtcEngine.InitEventHandler(null);
  200. rtcEngine.LeaveChannel();
  201. rtcEngine.Dispose();
  202. }
  203. }
  204. internal class UserEventHandler : IRtcEngineEventHandler
  205. {
  206. private readonly AgoraTestVideo _helloVideoTokenAgora;
  207. internal UserEventHandler(AgoraTestVideo helloVideoTokenAgora)
  208. {
  209. _helloVideoTokenAgora = helloVideoTokenAgora;
  210. }
  211. public override void OnError(int err, string msg)
  212. {
  213. _helloVideoTokenAgora.Log.UpdateLog(string.Format("OnError err: {0}, msg: {1}", err, msg));
  214. }
  215. public override void OnJoinChannelSuccess(RtcConnection connection, int elapsed)
  216. {
  217. int build = 0;
  218. _helloVideoTokenAgora.Log.UpdateLog(string.Format("sdk version: ${0}",
  219. _helloVideoTokenAgora.rtcEngine.GetVersion(ref build)));
  220. _helloVideoTokenAgora.Log.UpdateLog(
  221. string.Format("OnJoinChannelSuccess channelName: {0}, uid: {1}, elapsed: {2}",
  222. connection.channelId, connection.localUid, elapsed));
  223. _helloVideoTokenAgora.Log.UpdateLog(string.Format("New Token: {0}",
  224. AgoraTestVideo._channelToken));
  225. // HelperClass.FetchToken(tokenBase, channelName, 0, this.RenewOrJoinToken);
  226. AgoraTestVideo.MakeVideoView(0);
  227. }
  228. public override void OnRejoinChannelSuccess(RtcConnection connection, int elapsed)
  229. {
  230. _helloVideoTokenAgora.Log.UpdateLog("OnRejoinChannelSuccess");
  231. }
  232. public override void OnLeaveChannel(RtcConnection connection, RtcStats stats)
  233. {
  234. _helloVideoTokenAgora.Log.UpdateLog("OnLeaveChannel");
  235. AgoraTestVideo.DestroyVideoView(0);
  236. }
  237. public override void OnClientRoleChanged(RtcConnection connection, CLIENT_ROLE_TYPE oldRole,
  238. CLIENT_ROLE_TYPE newRole)
  239. {
  240. _helloVideoTokenAgora.Log.UpdateLog("OnClientRoleChanged");
  241. }
  242. public override void OnUserJoined(RtcConnection connection, uint uid, int elapsed)
  243. {
  244. _helloVideoTokenAgora.Log.UpdateLog(string.Format("OnUserJoined uid: ${0} elapsed: ${1}", uid,
  245. elapsed));
  246. AgoraTestVideo.MakeVideoView(uid, _helloVideoTokenAgora.GetChannelName());
  247. }
  248. public override void OnUserOffline(RtcConnection connection, uint uid, USER_OFFLINE_REASON_TYPE reason)
  249. {
  250. _helloVideoTokenAgora.Log.UpdateLog(string.Format("OnUserOffLine uid: ${0}, reason: ${1}", uid,
  251. (int)reason));
  252. AgoraTestVideo.DestroyVideoView(uid);
  253. }
  254. public override void OnTokenPrivilegeWillExpire(RtcConnection connection, string token)
  255. {
  256. _helloVideoTokenAgora.StartCoroutine(HelperClass.FetchToken(AgoraTestVideo._tokenBase,
  257. _helloVideoTokenAgora.GetChannelName(), 0, _helloVideoTokenAgora.RenewOrJoinToken));
  258. }
  259. public override void OnConnectionStateChanged(RtcConnection connection, CONNECTION_STATE_TYPE state,
  260. CONNECTION_CHANGED_REASON_TYPE reason)
  261. {
  262. _helloVideoTokenAgora._state = state;
  263. }
  264. public override void OnConnectionLost(RtcConnection connection)
  265. {
  266. _helloVideoTokenAgora.Log.UpdateLog(string.Format("OnConnectionLost "));
  267. }
  268. }