ScreenShareWhileVideoCall.cs 15 KB

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