JoinChannelVideoToken.cs 11 KB

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