TakeSnapshot.cs 9.5 KB

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