ScreenShare.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. using System;
  2. using System.Linq;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. using Agora.Rtc;
  6. using Agora.Util;
  7. using UnityEngine.Serialization;
  8. using Logger = Agora.Util.Logger;
  9. namespace Agora_RTC_Plugin.API_Example.Examples.Advanced.ScreenShare
  10. {
  11. public class ScreenShare : MonoBehaviour
  12. {
  13. [FormerlySerializedAs("appIdInput")]
  14. [SerializeField]
  15. private AppIdInput _appIdInput;
  16. [Header("_____________Basic Configuration_____________")]
  17. [FormerlySerializedAs("APP_ID")]
  18. [SerializeField]
  19. private string _appID = "";
  20. [FormerlySerializedAs("TOKEN")]
  21. [SerializeField]
  22. private string _token = "";
  23. [FormerlySerializedAs("CHANNEL_NAME")]
  24. [SerializeField]
  25. private string _channelName = "";
  26. public Text LogText;
  27. internal Logger Log;
  28. internal IRtcEngine RtcEngine = null;
  29. private Dropdown _winIdSelect;
  30. private Button _startShareBtn;
  31. private Button _stopShareBtn;
  32. private Button _updateShareBtn;
  33. private Button _publishBtn;
  34. private Button _unpublishBtn;
  35. // Use this for initialization
  36. private void Start()
  37. {
  38. LoadAssetData();
  39. if (CheckAppId())
  40. {
  41. EnableUI();
  42. InitEngine();
  43. #if UNITY_ANDROID || UNITY_IPHONE
  44. GameObject.Find("winIdSelect").SetActive(false);
  45. _updateShareBtn.gameObject.SetActive(true);
  46. #else
  47. _updateShareBtn.gameObject.SetActive(false);
  48. PrepareScreenCapture();
  49. #endif
  50. JoinChannel();
  51. }
  52. }
  53. private bool CheckAppId()
  54. {
  55. Log = new Logger(LogText);
  56. return Log.DebugAssert(_appID.Length > 10, "Please fill in your appId in API-Example/profile/appIdInput.asset");
  57. }
  58. //Show data in AgoraBasicProfile
  59. [ContextMenu("ShowAgoraBasicProfileData")]
  60. private void LoadAssetData()
  61. {
  62. if (_appIdInput == null) return;
  63. _appID = _appIdInput.appID;
  64. _token = _appIdInput.token;
  65. _channelName = _appIdInput.channelName;
  66. }
  67. private void JoinChannel()
  68. {
  69. RtcEngine.EnableAudio();
  70. RtcEngine.EnableVideo();
  71. RtcEngine.SetClientRole(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  72. var ret = RtcEngine.JoinChannel(_token, _channelName);
  73. Debug.Log("JoinChannel returns: " + ret);
  74. }
  75. private void OnPublishButtonClick()
  76. {
  77. ChannelMediaOptions options = new ChannelMediaOptions();
  78. options.publishCameraTrack.SetValue(false);
  79. options.publishScreenTrack.SetValue(true);
  80. #if UNITY_ANDROID || UNITY_IPHONE
  81. options.publishScreenCaptureAudio.SetValue(true);
  82. options.publishScreenCaptureVideo.SetValue(true);
  83. #endif
  84. var ret = RtcEngine.UpdateChannelMediaOptions(options);
  85. Debug.Log("UpdateChannelMediaOptions returns: " + ret);
  86. _publishBtn.gameObject.SetActive(false);
  87. _unpublishBtn.gameObject.SetActive(true);
  88. }
  89. private void OnUnplishButtonClick()
  90. {
  91. ChannelMediaOptions options = new ChannelMediaOptions();
  92. options.publishCameraTrack.SetValue(true);
  93. options.publishScreenTrack.SetValue(false);
  94. #if UNITY_ANDROID || UNITY_IPHONE
  95. options.publishScreenCaptureAudio.SetValue(false);
  96. options.publishScreenCaptureVideo.SetValue(false);
  97. #endif
  98. var ret = RtcEngine.UpdateChannelMediaOptions(options);
  99. Debug.Log("UpdateChannelMediaOptions returns: " + ret);
  100. _publishBtn.gameObject.SetActive(true);
  101. _unpublishBtn.gameObject.SetActive(false);
  102. }
  103. private void InitEngine()
  104. {
  105. RtcEngine = Agora.Rtc.RtcEngine.CreateAgoraRtcEngine();
  106. UserEventHandler handler = new UserEventHandler(this);
  107. RtcEngineContext context = new RtcEngineContext(_appID, 0,
  108. CHANNEL_PROFILE_TYPE.CHANNEL_PROFILE_LIVE_BROADCASTING,
  109. AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_DEFAULT);
  110. RtcEngine.Initialize(context);
  111. RtcEngine.InitEventHandler(new UserEventHandler(this));
  112. }
  113. private void PrepareScreenCapture()
  114. {
  115. _winIdSelect = GameObject.Find("winIdSelect").GetComponent<Dropdown>();
  116. if (_winIdSelect == null || RtcEngine == null) return;
  117. _winIdSelect.ClearOptions();
  118. SIZE t = new SIZE();
  119. t.width = 360;
  120. t.height = 240;
  121. SIZE s = new SIZE();
  122. s.width = 360;
  123. s.height = 240;
  124. var info = RtcEngine.GetScreenCaptureSources(t, s, true);
  125. _winIdSelect.AddOptions(info.Select(w =>
  126. new Dropdown.OptionData(
  127. string.Format("{0}: {1}-{2} | {3}", w.type, w.sourceName, w.sourceTitle, w.sourceId)))
  128. .ToList());
  129. }
  130. private void EnableUI()
  131. {
  132. _startShareBtn = GameObject.Find("startShareBtn").GetComponent<Button>();
  133. _stopShareBtn = GameObject.Find("stopShareBtn").GetComponent<Button>();
  134. if (_startShareBtn != null) _startShareBtn.onClick.AddListener(OnStartShareBtnClick);
  135. if (_stopShareBtn != null)
  136. {
  137. _stopShareBtn.onClick.AddListener(OnStopShareBtnClick);
  138. _stopShareBtn.gameObject.SetActive(false);
  139. }
  140. var gameObject = GameObject.Find("updateShareBtn");
  141. if (gameObject != null)
  142. {
  143. _updateShareBtn = gameObject.GetComponent<Button>();
  144. _updateShareBtn.onClick.AddListener(OnUpdateShareBtnClick);
  145. }
  146. _publishBtn = GameObject.Find("publishBtn").GetComponent<Button>();
  147. _publishBtn.onClick.AddListener(OnPublishButtonClick);
  148. _publishBtn.gameObject.SetActive(false);
  149. _unpublishBtn = GameObject.Find("unpublishBtn").GetComponent<Button>();
  150. _unpublishBtn.onClick.AddListener(OnUnplishButtonClick);
  151. _unpublishBtn.gameObject.SetActive(false);
  152. }
  153. private void OnStartShareBtnClick()
  154. {
  155. if (RtcEngine == null) return;
  156. if (_startShareBtn != null) _startShareBtn.gameObject.SetActive(false);
  157. if (_stopShareBtn != null) _stopShareBtn.gameObject.SetActive(true);
  158. #if UNITY_ANDROID || UNITY_IPHONE
  159. var parameters2 = new ScreenCaptureParameters2();
  160. parameters2.captureAudio = true;
  161. parameters2.captureVideo = true;
  162. var nRet = RtcEngine.StartScreenCapture(parameters2);
  163. this.Log.UpdateLog("StartScreenCapture :" + nRet);
  164. #else
  165. RtcEngine.StopScreenCapture();
  166. if (_winIdSelect == null) return;
  167. var option = _winIdSelect.options[_winIdSelect.value].text;
  168. if (string.IsNullOrEmpty(option)) return;
  169. if (option.Contains("ScreenCaptureSourceType_Window"))
  170. {
  171. var windowId = option.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1];
  172. Log.UpdateLog(string.Format(">>>>> Start sharing {0}", windowId));
  173. var nRet = RtcEngine.StartScreenCaptureByWindowId(ulong.Parse(windowId), default(Rectangle),
  174. default(ScreenCaptureParameters));
  175. this.Log.UpdateLog("StartScreenCaptureByWindowId:" + nRet);
  176. }
  177. else
  178. {
  179. var dispId = uint.Parse(option.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[1]);
  180. Log.UpdateLog(string.Format(">>>>> Start sharing display {0}", dispId));
  181. var nRet = RtcEngine.StartScreenCaptureByDisplayId(dispId, default(Rectangle),
  182. new ScreenCaptureParameters { captureMouseCursor = true, frameRate = 30 });
  183. this.Log.UpdateLog("StartScreenCaptureByDisplayId:" + nRet);
  184. }
  185. #endif
  186. OnPublishButtonClick();
  187. }
  188. private void OnStopShareBtnClick()
  189. {
  190. if (_startShareBtn != null) _startShareBtn.gameObject.SetActive(true);
  191. if (_stopShareBtn != null) _stopShareBtn.gameObject.SetActive(false);
  192. _publishBtn.gameObject.SetActive(false);
  193. _unpublishBtn.gameObject.SetActive(false);
  194. RtcEngine.StopScreenCapture();
  195. }
  196. private void OnUpdateShareBtnClick()
  197. {
  198. //only work in ios or android
  199. var config = new ScreenCaptureParameters2();
  200. config.captureAudio = true;
  201. config.captureVideo = true;
  202. config.videoParams.dimensions.width = 960;
  203. config.videoParams.dimensions.height = 640;
  204. var nRet = RtcEngine.UpdateScreenCapture(config);
  205. this.Log.UpdateLog("UpdateScreenCapture: " + nRet);
  206. }
  207. private void OnDestroy()
  208. {
  209. Debug.Log("OnDestroy");
  210. if (RtcEngine == null) return;
  211. RtcEngine.InitEventHandler(null);
  212. RtcEngine.LeaveChannel();
  213. RtcEngine.Dispose();
  214. }
  215. internal string GetChannelName()
  216. {
  217. return _channelName;
  218. }
  219. #region -- Video Render UI Logic ---
  220. internal static void MakeVideoView(uint uid, string channelId = "", VIDEO_SOURCE_TYPE videoSourceType = VIDEO_SOURCE_TYPE.VIDEO_SOURCE_CAMERA)
  221. {
  222. var go = GameObject.Find(uid.ToString());
  223. if (!ReferenceEquals(go, null))
  224. {
  225. return; // reuse
  226. }
  227. // create a GameObject and assign to this new user
  228. var videoSurface = MakeImageSurface(uid.ToString());
  229. if (ReferenceEquals(videoSurface, null)) return;
  230. // configure videoSurface
  231. videoSurface.SetForUser(uid, channelId, videoSourceType);
  232. videoSurface.SetEnable(true);
  233. videoSurface.OnTextureSizeModify += (int width, int height) =>
  234. {
  235. float scale = (float)height / (float)width;
  236. videoSurface.transform.localScale = new Vector3(-5, 5 * scale, 1);
  237. Debug.Log("OnTextureSizeModify: " + width + " " + height);
  238. };
  239. }
  240. // VIDEO TYPE 1: 3D Object
  241. private static VideoSurface MakePlaneSurface(string goName)
  242. {
  243. var go = GameObject.CreatePrimitive(PrimitiveType.Plane);
  244. if (go == null)
  245. {
  246. return null;
  247. }
  248. go.name = goName;
  249. // set up transform
  250. go.transform.Rotate(-90.0f, 0.0f, 0.0f);
  251. go.transform.position = Vector3.zero;
  252. go.transform.localScale = new Vector3(0.25f, 0.5f, .5f);
  253. // configure videoSurface
  254. var videoSurface = go.AddComponent<VideoSurface>();
  255. return videoSurface;
  256. }
  257. // Video TYPE 2: RawImage
  258. private static VideoSurface MakeImageSurface(string goName)
  259. {
  260. var go = new GameObject();
  261. if (go == null)
  262. {
  263. return null;
  264. }
  265. go.name = goName;
  266. // to be renderered onto
  267. go.AddComponent<RawImage>();
  268. // make the object draggable
  269. go.AddComponent<UIElementDrag>();
  270. var canvas = GameObject.Find("VideoCanvas");
  271. if (canvas != null)
  272. {
  273. go.transform.parent = canvas.transform;
  274. Debug.Log("add video view");
  275. }
  276. else
  277. {
  278. Debug.Log("Canvas is null video view");
  279. }
  280. // set up transform
  281. go.transform.Rotate(0f, 0.0f, 180.0f);
  282. go.transform.localPosition = Vector3.zero;
  283. go.transform.localScale = new Vector3(3f, 4f, 1f);
  284. // configure videoSurface
  285. var videoSurface = go.AddComponent<VideoSurface>();
  286. return videoSurface;
  287. }
  288. internal static void DestroyVideoView(uint uid)
  289. {
  290. var go = GameObject.Find(uid.ToString());
  291. if (!ReferenceEquals(go, null))
  292. {
  293. Destroy(go);
  294. }
  295. }
  296. #endregion
  297. }
  298. #region -- Agora Event ---
  299. internal class UserEventHandler : IRtcEngineEventHandler
  300. {
  301. private readonly ScreenShare _desktopScreenShare;
  302. internal UserEventHandler(ScreenShare desktopScreenShare)
  303. {
  304. _desktopScreenShare = desktopScreenShare;
  305. }
  306. public override void OnError(int err, string msg)
  307. {
  308. _desktopScreenShare.Log.UpdateLog(string.Format("OnError err: {0}, msg: {1}", err, msg));
  309. }
  310. public override void OnJoinChannelSuccess(RtcConnection connection, int elapsed)
  311. {
  312. int build = 0;
  313. _desktopScreenShare.Log.UpdateLog(string.Format("sdk version: ${0}",
  314. _desktopScreenShare.RtcEngine.GetVersion(ref build)));
  315. _desktopScreenShare.Log.UpdateLog(
  316. string.Format("OnJoinChannelSuccess channelName: {0}, uid: {1}, elapsed: {2}",
  317. connection.channelId, connection.localUid, elapsed));
  318. ScreenShare.MakeVideoView(0, "", VIDEO_SOURCE_TYPE.VIDEO_SOURCE_SCREEN);
  319. }
  320. public override void OnRejoinChannelSuccess(RtcConnection connection, int elapsed)
  321. {
  322. _desktopScreenShare.Log.UpdateLog("OnRejoinChannelSuccess");
  323. }
  324. public override void OnLeaveChannel(RtcConnection connection, RtcStats stats)
  325. {
  326. _desktopScreenShare.Log.UpdateLog("OnLeaveChannel");
  327. ScreenShare.DestroyVideoView(connection.localUid);
  328. ScreenShare.DestroyVideoView(0);
  329. }
  330. public override void OnClientRoleChanged(RtcConnection connection, CLIENT_ROLE_TYPE oldRole, CLIENT_ROLE_TYPE newRole)
  331. {
  332. _desktopScreenShare.Log.UpdateLog("OnClientRoleChanged");
  333. }
  334. public override void OnUserJoined(RtcConnection connection, uint uid, int elapsed)
  335. {
  336. _desktopScreenShare.Log.UpdateLog(string.Format("OnUserJoined uid: ${0} elapsed: ${1}", uid, elapsed));
  337. ScreenShare.MakeVideoView(uid, _desktopScreenShare.GetChannelName(), VIDEO_SOURCE_TYPE.VIDEO_SOURCE_REMOTE);
  338. }
  339. public override void OnUserOffline(RtcConnection connection, uint uid, USER_OFFLINE_REASON_TYPE reason)
  340. {
  341. _desktopScreenShare.Log.UpdateLog(string.Format("OnUserOffLine uid: ${0}, reason: ${1}", uid,
  342. (int)reason));
  343. ScreenShare.DestroyVideoView(uid);
  344. }
  345. }
  346. #endregion
  347. }