ChannelMediaRelay.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using Agora.Rtc;
  4. using Agora.Util;
  5. using UnityEngine.Serialization;
  6. using Logger = Agora.Util.Logger;
  7. namespace Agora_RTC_Plugin.API_Example.Examples.Advanced.ChannelMediaRelay
  8. {
  9. public class ChannelMediaRelay : MonoBehaviour
  10. {
  11. [FormerlySerializedAs("appIdInput")]
  12. [SerializeField]
  13. private AppIdInput _appIdInput;
  14. [Header("_____________Basic Configuration_____________")]
  15. [FormerlySerializedAs("APP_ID")]
  16. [SerializeField]
  17. public string _appID = "";
  18. [FormerlySerializedAs("TOKEN")]
  19. [SerializeField]
  20. public string _token = "";
  21. [FormerlySerializedAs("CHANNEL_NAME")]
  22. [SerializeField]
  23. public string _channelName = "";
  24. public Text LogText;
  25. internal Logger Log;
  26. internal IRtcEngine RtcEngine = null;
  27. private void Start()
  28. {
  29. LoadAssetData();
  30. if (CheckAppId())
  31. {
  32. InitEngine();
  33. SetupUI();
  34. EnableUI(false);
  35. JoinChannel();
  36. }
  37. }
  38. [ContextMenu("ShowAgoraBasicProfileData")]
  39. private void LoadAssetData()
  40. {
  41. if (_appIdInput == null) return;
  42. _appID = _appIdInput.appID;
  43. _token = _appIdInput.token;
  44. _channelName = _appIdInput.channelName;
  45. }
  46. private bool CheckAppId()
  47. {
  48. Log = new Logger(LogText);
  49. return Log.DebugAssert(_appID.Length > 10, "Please fill in your appId in API-Example/profile/appIdInput.asset");
  50. }
  51. private void InitEngine()
  52. {
  53. RtcEngine = Agora.Rtc.RtcEngine.CreateAgoraRtcEngine();
  54. UserEventHandler handler = new UserEventHandler(this);
  55. RtcEngineContext context = new RtcEngineContext(_appID, 0,
  56. CHANNEL_PROFILE_TYPE.CHANNEL_PROFILE_LIVE_BROADCASTING,
  57. AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_GAME_STREAMING);
  58. RtcEngine.Initialize(context);
  59. RtcEngine.InitEventHandler(handler);
  60. }
  61. private void JoinChannel()
  62. {
  63. RtcEngine.SetClientRole(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  64. RtcEngine.EnableAudio();
  65. RtcEngine.EnableVideo();
  66. RtcEngine.JoinChannel(_token, _channelName, "");
  67. }
  68. private void Update()
  69. {
  70. PermissionHelper.RequestMicrophontPermission();
  71. PermissionHelper.RequestCameraPermission();
  72. }
  73. private void SetupUI()
  74. {
  75. var ui = this.transform.Find("UI");
  76. var btn = ui.Find("StartButton").GetComponent<Button>();
  77. btn.onClick.AddListener(OnStartButtonClick);
  78. btn = ui.Find("UpdateButton").GetComponent<Button>();
  79. btn.onClick.AddListener(onUpdateButtonClick);
  80. btn = ui.Find("StopButton").GetComponent<Button>();
  81. btn.onClick.AddListener(OnStopButtonClick);
  82. btn = ui.Find("PauseAllButton").GetComponent<Button>();
  83. btn.onClick.AddListener(onPauseAllButtonClick);
  84. btn = ui.Find("ResumAllButton").GetComponent<Button>();
  85. btn.onClick.AddListener(OnResumeAllButtonClick);
  86. }
  87. public void EnableUI(bool visible)
  88. {
  89. var ui = this.transform.Find("UI");
  90. ui.gameObject.SetActive(visible);
  91. }
  92. private void OnStartButtonClick()
  93. {
  94. ChannelMediaRelayConfiguration config = new ChannelMediaRelayConfiguration();
  95. config.srcInfo = new ChannelMediaInfo
  96. {
  97. channelName = this._appIdInput.channelName,
  98. uid = 0,
  99. token = this._appIdInput.token
  100. };
  101. //you can relay to another channels (limit max is 4)
  102. config.destInfos = new ChannelMediaInfo[1];
  103. config.destInfos[0] = new ChannelMediaInfo
  104. {
  105. channelName = this._appIdInput.channelName + "_2",
  106. uid = 0,
  107. token = this._appIdInput.token
  108. };
  109. config.destCount = 1;
  110. var nRet = RtcEngine.StartChannelMediaRelay(config);
  111. this.Log.UpdateLog("StartChannelMediaRelay nRet:" + nRet + " new ChannelName: " + this._appIdInput.channelName + "_2");
  112. }
  113. private void onUpdateButtonClick()
  114. {
  115. ChannelMediaRelayConfiguration config = new ChannelMediaRelayConfiguration();
  116. config.srcInfo = new ChannelMediaInfo
  117. {
  118. channelName = this._appIdInput.channelName,
  119. uid = 0,
  120. token = this._appIdInput.token
  121. };
  122. config.destInfos = new ChannelMediaInfo[1];
  123. config.destInfos[0] = new ChannelMediaInfo
  124. {
  125. channelName = this._appIdInput.channelName + "_3",
  126. uid = 0,
  127. token = this._appIdInput.token
  128. };
  129. config.destCount = 1;
  130. //after StartChannelMediaRelay you can use StartChannelMediaRelay to remove or relay to anthoner channel
  131. var nRet = RtcEngine.UpdateChannelMediaRelay(config);
  132. this.Log.UpdateLog("UpdateChannelMediaRelay nRet:" + nRet + " new ChannelName: " + this._appIdInput.channelName + "_3");
  133. }
  134. private void onPauseAllButtonClick()
  135. {
  136. var nRet = RtcEngine.PauseAllChannelMediaRelay();
  137. this.Log.UpdateLog("onPauseAllButtonClick nRet:" + nRet);
  138. }
  139. private void OnResumeAllButtonClick()
  140. {
  141. var nRet = RtcEngine.ResumeAllChannelMediaRelay();
  142. this.Log.UpdateLog("OnResumeAllButtonClick nRet:" + nRet);
  143. }
  144. private void OnStopButtonClick()
  145. {
  146. var nRet = RtcEngine.StopChannelMediaRelay();
  147. this.Log.UpdateLog("OnStopButtonClick nRet:" + nRet);
  148. }
  149. private void OnDestroy()
  150. {
  151. Debug.Log("OnDestroy");
  152. if (RtcEngine == null) return;
  153. RtcEngine.InitEventHandler(null);
  154. RtcEngine.LeaveChannel();
  155. RtcEngine.Dispose();
  156. RtcEngine = null;
  157. }
  158. #region -- Video Render UI Logic ---
  159. internal static void MakeVideoView(uint uid, string channelId = "", VIDEO_SOURCE_TYPE type = VIDEO_SOURCE_TYPE.VIDEO_SOURCE_CAMERA)
  160. {
  161. var go = GameObject.Find(uid.ToString());
  162. if (!ReferenceEquals(go, null))
  163. {
  164. return; // reuse
  165. }
  166. // create a GameObject and assign to this new user
  167. var videoSurface = MakeImageSurface(uid.ToString());
  168. if (ReferenceEquals(videoSurface, null)) return;
  169. // configure videoSurface
  170. videoSurface.SetForUser(uid, channelId, type);
  171. videoSurface.OnTextureSizeModify += (int width, int height) =>
  172. {
  173. float scale = (float)height / (float)width;
  174. videoSurface.transform.localScale = new Vector3(-5, 5 * scale, 1);
  175. Debug.Log("OnTextureSizeModify: " + width + " " + height);
  176. };
  177. videoSurface.SetEnable(true);
  178. }
  179. // VIDEO TYPE 1: 3D Object
  180. private static VideoSurface MakePlaneSurface(string goName)
  181. {
  182. var go = GameObject.CreatePrimitive(PrimitiveType.Plane);
  183. if (go == null)
  184. {
  185. return null;
  186. }
  187. go.name = goName;
  188. // set up transform
  189. go.transform.Rotate(-90.0f, 0.0f, 0.0f);
  190. go.transform.position = Vector3.zero;
  191. go.transform.localScale = new Vector3(0.25f, 0.5f, 0.5f);
  192. // configure videoSurface
  193. var videoSurface = go.AddComponent<VideoSurface>();
  194. return videoSurface;
  195. }
  196. // Video TYPE 2: RawImage
  197. private static VideoSurface MakeImageSurface(string goName)
  198. {
  199. GameObject go = new GameObject();
  200. if (go == null)
  201. {
  202. return null;
  203. }
  204. go.name = goName;
  205. // to be renderered onto
  206. go.AddComponent<RawImage>();
  207. // make the object draggable
  208. go.AddComponent<UIElementDrag>();
  209. var canvas = GameObject.Find("VideoCanvas");
  210. if (canvas != null)
  211. {
  212. go.transform.parent = canvas.transform;
  213. Debug.Log("add video view");
  214. }
  215. else
  216. {
  217. Debug.Log("Canvas is null video view");
  218. }
  219. // set up transform
  220. go.transform.Rotate(0f, 0.0f, 180.0f);
  221. go.transform.localPosition = Vector3.zero;
  222. go.transform.localScale = new Vector3(2f, 3f, 1f);
  223. // configure videoSurface
  224. var videoSurface = go.AddComponent<VideoSurface>();
  225. return videoSurface;
  226. }
  227. internal static void DestroyVideoView(uint uid)
  228. {
  229. var go = GameObject.Find(uid.ToString());
  230. if (!ReferenceEquals(go, null))
  231. {
  232. Destroy(go);
  233. }
  234. }
  235. #endregion
  236. }
  237. #region -- Agora Event ---
  238. internal class UserEventHandler : IRtcEngineEventHandler
  239. {
  240. private readonly ChannelMediaRelay _channelMediaRelay;
  241. internal UserEventHandler(ChannelMediaRelay videoSample)
  242. {
  243. _channelMediaRelay = videoSample;
  244. }
  245. public override void OnError(int err, string msg)
  246. {
  247. _channelMediaRelay.Log.UpdateLog(string.Format("OnError err: {0}, msg: {1}", err, msg));
  248. }
  249. public override void OnJoinChannelSuccess(RtcConnection connection, int elapsed)
  250. {
  251. int build = 0;
  252. Debug.Log("Agora: OnJoinChannelSuccess ");
  253. _channelMediaRelay.Log.UpdateLog(string.Format("sdk version: ${0}",
  254. _channelMediaRelay.RtcEngine.GetVersion(ref build)));
  255. _channelMediaRelay.Log.UpdateLog(
  256. string.Format("OnJoinChannelSuccess channelName: {0}, uid: {1}, elapsed: {2}",
  257. connection.channelId, connection.localUid, elapsed));
  258. _channelMediaRelay.EnableUI(true);
  259. ChannelMediaRelay.MakeVideoView(0);
  260. }
  261. public override void OnRejoinChannelSuccess(RtcConnection connection, int elapsed)
  262. {
  263. _channelMediaRelay.Log.UpdateLog("OnRejoinChannelSuccess");
  264. }
  265. public override void OnLeaveChannel(RtcConnection connection, RtcStats stats)
  266. {
  267. _channelMediaRelay.Log.UpdateLog("OnLeaveChannel");
  268. _channelMediaRelay.EnableUI(false);
  269. ChannelMediaRelay.DestroyVideoView(0);
  270. }
  271. public override void OnClientRoleChanged(RtcConnection connection, CLIENT_ROLE_TYPE oldRole, CLIENT_ROLE_TYPE newRole)
  272. {
  273. _channelMediaRelay.Log.UpdateLog(string.Format("OnClientRoleChanged {0}, {1}", oldRole, newRole));
  274. }
  275. public override void OnUserJoined(RtcConnection connection, uint uid, int elapsed)
  276. {
  277. _channelMediaRelay.Log.UpdateLog(string.Format("OnUserJoined uid: ${0} elapsed: ${1}", uid, elapsed));
  278. ChannelMediaRelay.MakeVideoView(uid, _channelMediaRelay._channelName, VIDEO_SOURCE_TYPE.VIDEO_SOURCE_REMOTE);
  279. }
  280. public override void OnUserOffline(RtcConnection connection, uint uid, USER_OFFLINE_REASON_TYPE reason)
  281. {
  282. _channelMediaRelay.Log.UpdateLog(string.Format("OnUserOffLine uid: ${0}, reason: ${1}", uid,
  283. (int)reason));
  284. ChannelMediaRelay.DestroyVideoView(uid);
  285. }
  286. public override void OnChannelMediaRelayEvent(int code)
  287. {
  288. _channelMediaRelay.Log.UpdateLog(string.Format("OnChannelMediaRelayEvent: {0}", code));
  289. }
  290. public override void OnChannelMediaRelayStateChanged(int state, int code)
  291. {
  292. _channelMediaRelay.Log.UpdateLog(string.Format("OnChannelMediaRelayStateChanged state: {0}, code: {1}", state, code));
  293. }
  294. }
  295. #endregion
  296. }