DualCamera.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. namespace Agora_RTC_Plugin.API_Example.Examples.Advanced.DualCamera
  8. {
  9. public class DualCamera : MonoBehaviour
  10. {
  11. [FormerlySerializedAs("appIdInput")]
  12. [SerializeField]
  13. private AppIdInput _appIdInput;
  14. [Header("_____________Basic Configuration_____________")]
  15. [FormerlySerializedAs("APP_ID")]
  16. [SerializeField]
  17. private string _appID = "";
  18. [FormerlySerializedAs("TOKEN")]
  19. [SerializeField]
  20. private string _token = "";
  21. [FormerlySerializedAs("CHANNEL_NAME")]
  22. [SerializeField]
  23. private string _channelName = "";
  24. public Text LogText;
  25. internal Logger Log;
  26. internal IRtcEngineEx RtcEngine = null;
  27. internal bool IsChannelJoined = false;
  28. private IVideoDeviceManager _videoDeviceManager;
  29. private Agora.Rtc.DeviceInfo[] _videoDeviceInfos;
  30. private CameraCapturerConfiguration _config1;
  31. private CameraCapturerConfiguration _config2;
  32. public uint UID1 = 123;
  33. public uint UID2 = 456;
  34. public Button MainPublishButton;
  35. public Button MainUnpublishButton;
  36. public Button SecondPublishButton;
  37. public Button SecondUnpublishButton;
  38. // Use this for initialization
  39. private void Start()
  40. {
  41. #if UNITY_IPHONE || UNITY_ANDROID
  42. this.LogText.text = "iOS/Android is not supported, but you could see how it works on the Editor for Windows/MacOS";
  43. #else
  44. LoadAssetData();
  45. if (CheckAppId())
  46. {
  47. InitEngine();
  48. GetVideoDeviceManager();
  49. }
  50. #endif
  51. }
  52. // Update is called once per frame
  53. private void Update()
  54. {
  55. PermissionHelper.RequestMicrophontPermission();
  56. PermissionHelper.RequestCameraPermission();
  57. }
  58. private bool CheckAppId()
  59. {
  60. Log = new Logger(LogText);
  61. return Log.DebugAssert(_appID.Length > 10, "Please fill in your appId in API-Example/profile/appIdInput.asset");
  62. }
  63. //Show data in AgoraBasicProfile
  64. [ContextMenu("ShowAgoraBasicProfileData")]
  65. private void LoadAssetData()
  66. {
  67. if (_appIdInput == null) return;
  68. _appID = _appIdInput.appID;
  69. _token = _appIdInput.token;
  70. _channelName = _appIdInput.channelName;
  71. }
  72. private void InitEngine()
  73. {
  74. RtcEngine = Agora.Rtc.RtcEngine.CreateAgoraRtcEngineEx();
  75. UserEventHandler handler = new UserEventHandler(this);
  76. RtcEngineContext context = new RtcEngineContext(_appID, 0,
  77. CHANNEL_PROFILE_TYPE.CHANNEL_PROFILE_LIVE_BROADCASTING,
  78. AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_DEFAULT);
  79. RtcEngine.Initialize(context);
  80. RtcEngine.InitEventHandler(handler);
  81. }
  82. public void MainCameraJoinChannel()
  83. {
  84. RtcEngine.StartPreview();
  85. RtcEngine.EnableAudio();
  86. RtcEngine.EnableVideo();
  87. RtcEngine.SetClientRole(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  88. var ret = RtcEngine.StartPrimaryCameraCapture(_config1);
  89. Log.UpdateLog(
  90. string.Format("StartPrimaryCameraCapture returns: {0}", ret));
  91. ChannelMediaOptions options1 = new ChannelMediaOptions();
  92. options1.publishCameraTrack.SetValue(true);
  93. options1.autoSubscribeAudio.SetValue(true);
  94. options1.autoSubscribeVideo.SetValue(true);
  95. options1.publishScreenTrack.SetValue(false);
  96. options1.enableAudioRecordingOrPlayout.SetValue(true);
  97. options1.clientRoleType.SetValue(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  98. ret = RtcEngine.JoinChannel(_token, _channelName, UID1, options1);
  99. Debug.Log("MainCameraJoinChannel returns: " + ret);
  100. }
  101. public void MainCameraLeaveChannel()
  102. {
  103. RtcEngine.StopPrimaryCameraCapture();
  104. var ret = RtcEngine.LeaveChannel();
  105. Debug.Log("MainCameraLeaveChannel returns: " + ret);
  106. }
  107. public void MainCameraPublish()
  108. {
  109. ChannelMediaOptions options1 = new ChannelMediaOptions();
  110. options1.publishCameraTrack.SetValue(true);
  111. options1.publishMicrophoneTrack.SetValue(true);
  112. var connection = new RtcConnection();
  113. connection.channelId = _channelName;
  114. connection.localUid = UID1;
  115. RtcEngine.UpdateChannelMediaOptionsEx(options1, connection);
  116. MainPublishButton.gameObject.SetActive(false);
  117. MainUnpublishButton.gameObject.SetActive(true);
  118. }
  119. public void MainCameraUnPublish()
  120. {
  121. ChannelMediaOptions options1 = new ChannelMediaOptions();
  122. options1.publishCameraTrack.SetValue(false);
  123. options1.publishMicrophoneTrack.SetValue(false);
  124. var connection = new RtcConnection();
  125. connection.channelId = _channelName;
  126. connection.localUid = UID1;
  127. RtcEngine.UpdateChannelMediaOptions(options1);
  128. MainPublishButton.gameObject.SetActive(true);
  129. MainUnpublishButton.gameObject.SetActive(false);
  130. }
  131. public void SecondCameraJoinChannel()
  132. {
  133. var ret = RtcEngine.StartSecondaryCameraCapture(_config2);
  134. Log.UpdateLog(
  135. string.Format("StartSecondaryCameraCapture returns: {0}", ret));
  136. ChannelMediaOptions options2 = new ChannelMediaOptions();
  137. options2.autoSubscribeAudio.SetValue(false);
  138. options2.autoSubscribeVideo.SetValue(false);
  139. options2.publishCustomAudioTrack.SetValue(false);
  140. options2.publishCameraTrack.SetValue(false);
  141. options2.publishSecondaryCameraTrack.SetValue(true);
  142. options2.enableAudioRecordingOrPlayout.SetValue(false);
  143. options2.clientRoleType.SetValue(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  144. ret = RtcEngine.JoinChannelEx(_token, new RtcConnection(_channelName, UID2), options2);
  145. Debug.Log("JoinChannelEx returns: " + ret);
  146. }
  147. public void SecondCameraLeaveChannel()
  148. {
  149. RtcEngine.StopSecondaryCameraCapture();
  150. var ret = RtcEngine.LeaveChannelEx(new RtcConnection(_channelName, 456));
  151. Debug.Log("SecondCameraLeaveChannel returns: " + ret);
  152. }
  153. public void SecondCameraPublish()
  154. {
  155. ChannelMediaOptions options1 = new ChannelMediaOptions();
  156. options1.publishSecondaryCameraTrack.SetValue(true);
  157. var connection = new RtcConnection();
  158. connection.channelId = _channelName;
  159. connection.localUid = UID2;
  160. RtcEngine.UpdateChannelMediaOptionsEx(options1, connection);
  161. SecondPublishButton.gameObject.SetActive(false);
  162. SecondUnpublishButton.gameObject.SetActive(true);
  163. }
  164. public void SecondCameraUnpublish()
  165. {
  166. ChannelMediaOptions options1 = new ChannelMediaOptions();
  167. options1.publishSecondaryCameraTrack.SetValue(false);
  168. var connection = new RtcConnection();
  169. connection.channelId = _channelName;
  170. connection.localUid = UID2;
  171. RtcEngine.UpdateChannelMediaOptionsEx(options1, connection);
  172. SecondPublishButton.gameObject.SetActive(true);
  173. SecondUnpublishButton.gameObject.SetActive(false);
  174. }
  175. private void GetVideoDeviceManager()
  176. {
  177. _videoDeviceManager = RtcEngine.GetVideoDeviceManager();
  178. _videoDeviceInfos = _videoDeviceManager.EnumerateVideoDevices();
  179. Log.UpdateLog(string.Format("VideoDeviceManager count: {0}", _videoDeviceInfos.Length));
  180. for (var i = 0; i < _videoDeviceInfos.Length; i++)
  181. {
  182. Log.UpdateLog(string.Format("VideoDeviceManager device index: {0}, name: {1}, id: {2}", i,
  183. _videoDeviceInfos[i].deviceName, _videoDeviceInfos[i].deviceId));
  184. }
  185. _config1 = new CameraCapturerConfiguration();
  186. _config1.deviceId = _videoDeviceInfos[0].deviceId;
  187. Debug.Log("PrimaryCamera: " + _config1.deviceId);
  188. _config1.format = new VideoFormat();
  189. if (_videoDeviceInfos.Length > 1)
  190. {
  191. _config2 = new CameraCapturerConfiguration();
  192. _config2.deviceId = _videoDeviceInfos[1].deviceId;
  193. Debug.Log("SecondaryCamera: " + _config2.deviceId);
  194. _config2.format = new VideoFormat();
  195. }
  196. }
  197. private void OnDestroy()
  198. {
  199. Debug.Log("OnDestroy");
  200. if (RtcEngine == null) return;
  201. RtcEngine.InitEventHandler(null);
  202. RtcEngine.StopSecondaryCameraCapture();
  203. RtcEngine.StopPrimaryCameraCapture();
  204. RtcEngine.LeaveChannelEx(new RtcConnection(_channelName, 456));
  205. RtcEngine.LeaveChannel();
  206. RtcEngine.Dispose();
  207. }
  208. internal string GetChannelName()
  209. {
  210. return _channelName;
  211. }
  212. #region -- Video Render UI Logic ---
  213. internal static void MakeVideoView(uint uid, string channelId = "", VIDEO_SOURCE_TYPE videoSourceType = VIDEO_SOURCE_TYPE.VIDEO_SOURCE_CAMERA)
  214. {
  215. var go = GameObject.Find(uid.ToString());
  216. if (!ReferenceEquals(go, null))
  217. {
  218. return; // reuse
  219. }
  220. // create a GameObject and assign to this new user
  221. VideoSurface videoSurface = null;
  222. if (videoSourceType == VIDEO_SOURCE_TYPE.VIDEO_SOURCE_CAMERA)
  223. {
  224. videoSurface = MakeImageSurface("MainCameraView");
  225. }
  226. else if (videoSourceType == VIDEO_SOURCE_TYPE.VIDEO_SOURCE_CAMERA_SECONDARY)
  227. {
  228. videoSurface = MakeImageSurface("SecondCameraView");
  229. }
  230. else
  231. {
  232. videoSurface = MakeImageSurface(uid.ToString());
  233. }
  234. if (ReferenceEquals(videoSurface, null)) return;
  235. // configure videoSurface
  236. videoSurface.SetForUser(uid, channelId, videoSourceType);
  237. videoSurface.OnTextureSizeModify += (int width, int height) =>
  238. {
  239. float scale = (float)height / (float)width;
  240. videoSurface.transform.localScale = new Vector3(-5, 5 * scale, 1);
  241. Debug.Log("OnTextureSizeModify: " + width + " " + height);
  242. };
  243. videoSurface.SetEnable(true);
  244. }
  245. // VIDEO TYPE 1: 3D Object
  246. private static VideoSurface MakePlaneSurface(string goName)
  247. {
  248. var go = GameObject.Find(goName);
  249. if (!ReferenceEquals(go, null))
  250. {
  251. return null; // reuse
  252. }
  253. go = GameObject.CreatePrimitive(PrimitiveType.Plane);
  254. if (go == null)
  255. {
  256. return null;
  257. }
  258. go.name = goName;
  259. // set up transform
  260. go.transform.Rotate(-90.0f, 0.0f, 0.0f);
  261. go.transform.position = Vector3.zero;
  262. go.transform.localScale = new Vector3(0.25f, 0.5f, 0.5f);
  263. // configure videoSurface
  264. var videoSurface = go.AddComponent<VideoSurface>();
  265. return videoSurface;
  266. }
  267. // Video TYPE 2: RawImage
  268. private static VideoSurface MakeImageSurface(string goName)
  269. {
  270. GameObject go = new GameObject();
  271. if (go == null)
  272. {
  273. return null;
  274. }
  275. go.name = goName;
  276. // to be renderered onto
  277. go.AddComponent<RawImage>();
  278. // make the object draggable
  279. go.AddComponent<UIElementDrag>();
  280. var canvas = GameObject.Find("VideoCanvas");
  281. if (canvas != null)
  282. {
  283. go.transform.parent = canvas.transform;
  284. Debug.Log("add video view");
  285. }
  286. else
  287. {
  288. Debug.Log("Canvas is null video view");
  289. }
  290. // set up transform
  291. go.transform.Rotate(0f, 0.0f, 180.0f);
  292. go.transform.localPosition = Vector3.zero;
  293. go.transform.localScale = new Vector3(2f, 3f, 1f);
  294. // configure videoSurface
  295. var videoSurface = go.AddComponent<VideoSurface>();
  296. return videoSurface;
  297. }
  298. internal static void DestroyVideoView(string name)
  299. {
  300. var go = GameObject.Find(name);
  301. if (!ReferenceEquals(go, null))
  302. {
  303. Destroy(go);
  304. }
  305. }
  306. #endregion
  307. }
  308. #region -- Agora Event ---
  309. internal class UserEventHandler : IRtcEngineEventHandler
  310. {
  311. private readonly DualCamera _videoSample;
  312. internal UserEventHandler(DualCamera videoSample)
  313. {
  314. _videoSample = videoSample;
  315. }
  316. public override void OnError(int err, string msg)
  317. {
  318. _videoSample.Log.UpdateLog(string.Format("OnError err: {0}, msg: {1}", err, msg));
  319. }
  320. public override void OnJoinChannelSuccess(RtcConnection connection, int elapsed)
  321. {
  322. int build = 0;
  323. _videoSample.IsChannelJoined = true;
  324. _videoSample.Log.UpdateLog(string.Format("sdk version: ${0}",
  325. _videoSample.RtcEngine.GetVersion(ref build)));
  326. _videoSample.Log.UpdateLog(
  327. string.Format("OnJoinChannelSuccess channelName: {0}, uid: {1}, elapsed: {2}",
  328. connection.channelId, connection.localUid, elapsed));
  329. if (connection.localUid == _videoSample.UID1)
  330. {
  331. DualCamera.MakeVideoView(0);
  332. }
  333. if (connection.localUid == _videoSample.UID2)
  334. {
  335. DualCamera.MakeVideoView(0, "", VIDEO_SOURCE_TYPE.VIDEO_SOURCE_CAMERA_SECONDARY);
  336. }
  337. }
  338. public override void OnRejoinChannelSuccess(RtcConnection connection, int elapsed)
  339. {
  340. _videoSample.Log.UpdateLog("OnRejoinChannelSuccess");
  341. }
  342. public override void OnLeaveChannel(RtcConnection connection, RtcStats stats)
  343. {
  344. _videoSample.IsChannelJoined = false;
  345. _videoSample.Log.UpdateLog("OnLeaveChannel");
  346. if (connection.localUid == _videoSample.UID1)
  347. {
  348. DualCamera.DestroyVideoView("MainCameraView");
  349. }
  350. if (connection.localUid == _videoSample.UID2)
  351. {
  352. DualCamera.DestroyVideoView("SecondCameraView");
  353. }
  354. }
  355. public override void OnClientRoleChanged(RtcConnection connection, CLIENT_ROLE_TYPE oldRole,
  356. CLIENT_ROLE_TYPE newRole)
  357. {
  358. _videoSample.Log.UpdateLog("OnClientRoleChanged");
  359. }
  360. public override void OnUserJoined(RtcConnection connection, uint uid, int elapsed)
  361. {
  362. _videoSample.Log.UpdateLog(string.Format("OnUserJoined uid: ${0} elapsed: ${1}", uid, elapsed));
  363. if (uid != _videoSample.UID1 && uid != _videoSample.UID2)
  364. {
  365. DualCamera.MakeVideoView(uid, _videoSample.GetChannelName(), VIDEO_SOURCE_TYPE.VIDEO_SOURCE_REMOTE);
  366. }
  367. }
  368. public override void OnUserOffline(RtcConnection connection, uint uid, USER_OFFLINE_REASON_TYPE reason)
  369. {
  370. _videoSample.Log.UpdateLog(string.Format("OnUserOffLine uid: ${0}, reason: ${1}", uid,
  371. (int)reason));
  372. if (uid != _videoSample.UID1 && uid != _videoSample.UID2)
  373. {
  374. DualCamera.DestroyVideoView(uid.ToString());
  375. }
  376. }
  377. }
  378. #endregion
  379. }