VirtualBackground.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. using System.IO;
  8. namespace Agora_RTC_Plugin.API_Example.Examples.Advanced.VirtualBackground
  9. {
  10. public class VirtualBackground : MonoBehaviour
  11. {
  12. [FormerlySerializedAs("appIdInput")]
  13. [SerializeField]
  14. private AppIdInput _appIdInput;
  15. [Header("_____________Basic Configuration_____________")]
  16. [FormerlySerializedAs("APP_ID")]
  17. [SerializeField]
  18. private string _appID = "";
  19. [FormerlySerializedAs("TOKEN")]
  20. [SerializeField]
  21. private string _token = "";
  22. [FormerlySerializedAs("CHANNEL_NAME")]
  23. [SerializeField]
  24. private string _channelName = "";
  25. public Text LogText;
  26. internal Logger Log;
  27. internal IRtcEngine RtcEngine = null;
  28. // Use this for initialization
  29. private void Start()
  30. {
  31. LoadAssetData();
  32. if (CheckAppId())
  33. {
  34. InitEngine();
  35. InitLogFilePath();
  36. SetupUI();
  37. JoinChannel();
  38. }
  39. }
  40. // Update is called once per frame
  41. private void Update()
  42. {
  43. PermissionHelper.RequestMicrophontPermission();
  44. PermissionHelper.RequestCameraPermission();
  45. }
  46. //Show data in AgoraBasicProfile
  47. [ContextMenu("ShowAgoraBasicProfileData")]
  48. private void LoadAssetData()
  49. {
  50. if (_appIdInput == null) return;
  51. _appID = _appIdInput.appID;
  52. _token = _appIdInput.token;
  53. _channelName = _appIdInput.channelName;
  54. }
  55. private bool CheckAppId()
  56. {
  57. Log = new Logger(LogText);
  58. return Log.DebugAssert(_appID.Length > 10, "Please fill in your appId in API-Example/profile/appIdInput.asset");
  59. }
  60. private void InitEngine()
  61. {
  62. RtcEngine = Agora.Rtc.RtcEngine.CreateAgoraRtcEngine();
  63. UserEventHandler handler = new UserEventHandler(this);
  64. RtcEngineContext context = new RtcEngineContext(_appID, 0,
  65. CHANNEL_PROFILE_TYPE.CHANNEL_PROFILE_LIVE_BROADCASTING,
  66. AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_DEFAULT);
  67. RtcEngine.Initialize(context);
  68. RtcEngine.InitEventHandler(handler);
  69. }
  70. private void JoinChannel()
  71. {
  72. RtcEngine.EnableAudio();
  73. RtcEngine.EnableVideo();
  74. RtcEngine.SetClientRole(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  75. RtcEngine.JoinChannel(_token, _channelName);
  76. }
  77. private void InitLogFilePath()
  78. {
  79. var path = Application.persistentDataPath + "/rtc.log";
  80. #if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
  81. path = path.Replace('/', '\\');
  82. #endif
  83. var nRet = RtcEngine.SetLogFile(path);
  84. this.Log.UpdateLog(string.Format("logPath:{0},nRet:{1}", path, nRet));
  85. }
  86. private void SetupUI()
  87. {
  88. var ui = this.transform.Find("UI");
  89. var btn = ui.Find("StartButton").GetComponent<Button>();
  90. btn.onClick.AddListener(OnStartButtonPress);
  91. btn = ui.Find("StartButton2").GetComponent<Button>();
  92. btn.onClick.AddListener(OnStartButtonPress2);
  93. btn = ui.Find("StopButton").GetComponent<Button>();
  94. btn.onClick.AddListener(OnStopButtonPress);
  95. }
  96. private void OnStartButtonPress()
  97. {
  98. var source = new VirtualBackgroundSource();
  99. source.background_source_type = BACKGROUND_SOURCE_TYPE.BACKGROUND_COLOR;
  100. source.color = 0xffffff;
  101. var segproperty = new SegmentationProperty();
  102. var nRet = RtcEngine.EnableVirtualBackground(true, source, segproperty, MEDIA_SOURCE_TYPE.PRIMARY_CAMERA_SOURCE);
  103. this.Log.UpdateLog("EnableVirtualBackground true :" + nRet);
  104. }
  105. private void OnStartButtonPress2()
  106. {
  107. var source = new VirtualBackgroundSource();
  108. source.background_source_type = BACKGROUND_SOURCE_TYPE.BACKGROUND_IMG;
  109. #if UNITY_ANDROID && !UNITY_EDITOR
  110. // On Android, the StreamingAssetPath is just accessed by /assets instead of Application.streamingAssetPath
  111. var filePath = "/assets/img/png.png";
  112. #else
  113. var filePath = Path.Combine(Application.streamingAssetsPath, "img/png.png");
  114. #endif
  115. source.source = filePath;
  116. var segproperty = new SegmentationProperty();
  117. var nRet = RtcEngine.EnableVirtualBackground(true, source, segproperty, MEDIA_SOURCE_TYPE.PRIMARY_CAMERA_SOURCE);
  118. this.Log.UpdateLog("EnableVirtualBackground true :" + nRet);
  119. }
  120. private void OnStopButtonPress()
  121. {
  122. var source = new VirtualBackgroundSource();
  123. var segproperty = new SegmentationProperty();
  124. var nRet = RtcEngine.EnableVirtualBackground(false, source, segproperty, MEDIA_SOURCE_TYPE.PRIMARY_CAMERA_SOURCE);
  125. this.Log.UpdateLog("EnableVirtualBackground false :" + nRet);
  126. }
  127. private void OnDestroy()
  128. {
  129. Debug.Log("OnDestroy");
  130. if (RtcEngine == null) return;
  131. RtcEngine.InitEventHandler(null);
  132. RtcEngine.LeaveChannel();
  133. RtcEngine.Dispose();
  134. }
  135. internal string GetChannelName()
  136. {
  137. return _channelName;
  138. }
  139. #region -- Video Render UI Logic ---
  140. internal static void MakeVideoView(uint uid, string channelId = "")
  141. {
  142. var go = GameObject.Find(uid.ToString());
  143. if (!ReferenceEquals(go, null))
  144. {
  145. return; // reuse
  146. }
  147. // create a GameObject and assign to this new user
  148. var videoSurface = MakeImageSurface(uid.ToString());
  149. if (ReferenceEquals(videoSurface, null)) return;
  150. // configure videoSurface
  151. if (uid == 0)
  152. {
  153. videoSurface.SetForUser(uid, channelId);
  154. }
  155. else
  156. {
  157. videoSurface.SetForUser(uid, channelId, VIDEO_SOURCE_TYPE.VIDEO_SOURCE_REMOTE);
  158. }
  159. videoSurface.OnTextureSizeModify += (int width, int height) =>
  160. {
  161. float scale = (float)height / (float)width;
  162. videoSurface.transform.localScale = new Vector3(-5, 5 * scale, 1);
  163. Debug.Log("OnTextureSizeModify: " + width + " " + height);
  164. };
  165. videoSurface.SetEnable(true);
  166. }
  167. // VIDEO TYPE 1: 3D Object
  168. private static VideoSurface MakePlaneSurface(string goName)
  169. {
  170. var go = GameObject.CreatePrimitive(PrimitiveType.Plane);
  171. if (go == null)
  172. {
  173. return null;
  174. }
  175. go.name = goName;
  176. // set up transform
  177. go.transform.Rotate(-90.0f, 0.0f, 0.0f);
  178. var yPos = Random.Range(3.0f, 5.0f);
  179. var xPos = Random.Range(-2.0f, 2.0f);
  180. go.transform.position = Vector3.zero;
  181. go.transform.localScale = new Vector3(0.25f, 0.5f, 0.5f);
  182. // configure videoSurface
  183. var videoSurface = go.AddComponent<VideoSurface>();
  184. return videoSurface;
  185. }
  186. // Video TYPE 2: RawImage
  187. private static VideoSurface MakeImageSurface(string goName)
  188. {
  189. GameObject go = new GameObject();
  190. if (go == null)
  191. {
  192. return null;
  193. }
  194. go.name = goName;
  195. // to be renderered onto
  196. go.AddComponent<RawImage>();
  197. // make the object draggable
  198. go.AddComponent<UIElementDrag>();
  199. var canvas = GameObject.Find("VideoCanvas");
  200. if (canvas != null)
  201. {
  202. go.transform.parent = canvas.transform;
  203. Debug.Log("add video view");
  204. }
  205. else
  206. {
  207. Debug.Log("Canvas is null video view");
  208. }
  209. // set up transform
  210. go.transform.Rotate(0f, 0.0f, 180.0f);
  211. go.transform.localPosition = Vector3.zero;
  212. go.transform.localScale = new Vector3(2f, 3f, 1f);
  213. // configure videoSurface
  214. var videoSurface = go.AddComponent<VideoSurface>();
  215. return videoSurface;
  216. }
  217. internal static void DestroyVideoView(uint uid)
  218. {
  219. var go = GameObject.Find(uid.ToString());
  220. if (!ReferenceEquals(go, null))
  221. {
  222. Destroy(go);
  223. }
  224. }
  225. #endregion
  226. }
  227. #region -- Agora Event ---
  228. internal class UserEventHandler : IRtcEngineEventHandler
  229. {
  230. private readonly VirtualBackground _sample;
  231. internal UserEventHandler(VirtualBackground sample)
  232. {
  233. _sample = sample;
  234. }
  235. public override void OnError(int err, string msg)
  236. {
  237. _sample.Log.UpdateLog(string.Format("OnError err: {0}, msg: {1}", err, msg));
  238. }
  239. public override void OnJoinChannelSuccess(RtcConnection connection, int elapsed)
  240. {
  241. int build = 0;
  242. Debug.Log("Agora: OnJoinChannelSuccess ");
  243. _sample.Log.UpdateLog(string.Format("sdk version: ${0}",
  244. _sample.RtcEngine.GetVersion(ref build)));
  245. _sample.Log.UpdateLog(
  246. string.Format("OnJoinChannelSuccess channelName: {0}, uid: {1}, elapsed: {2}",
  247. connection.channelId, connection.localUid, elapsed));
  248. VirtualBackground.MakeVideoView(0);
  249. }
  250. public override void OnRejoinChannelSuccess(RtcConnection connection, int elapsed)
  251. {
  252. _sample.Log.UpdateLog("OnRejoinChannelSuccess");
  253. }
  254. public override void OnLeaveChannel(RtcConnection connection, RtcStats stats)
  255. {
  256. _sample.Log.UpdateLog("OnLeaveChannel");
  257. VirtualBackground.DestroyVideoView(0);
  258. }
  259. public override void OnClientRoleChanged(RtcConnection connection, CLIENT_ROLE_TYPE oldRole, CLIENT_ROLE_TYPE newRole)
  260. {
  261. _sample.Log.UpdateLog("OnClientRoleChanged");
  262. }
  263. public override void OnUserJoined(RtcConnection connection, uint uid, int elapsed)
  264. {
  265. _sample.Log.UpdateLog(string.Format("OnUserJoined uid: ${0} elapsed: ${1}", uid, elapsed));
  266. VirtualBackground.MakeVideoView(uid, _sample.GetChannelName());
  267. }
  268. public override void OnUserOffline(RtcConnection connection, uint uid, USER_OFFLINE_REASON_TYPE reason)
  269. {
  270. _sample.Log.UpdateLog(string.Format("OnUserOffLine uid: ${0}, reason: ${1}", uid,
  271. (int)reason));
  272. VirtualBackground.DestroyVideoView(uid);
  273. }
  274. }
  275. #endregion
  276. }