StartDirectCdnStreaming.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. using Agora.Rtc;
  2. using Agora.Util;
  3. using UnityEngine;
  4. using UnityEngine.Serialization;
  5. using UnityEngine.UI;
  6. using Logger = Agora.Util.Logger;
  7. namespace Agora_RTC_Plugin.API_Example.Examples.Advanced.StartDirectCdnStreaming
  8. {
  9. public class StartDirectCdnStreaming : 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. private const string PUBLISH_URL = "rtmp://push.alexmk.name/live/agora_rtc_unity";
  25. public Text LogText;
  26. internal Logger Log;
  27. internal IRtcEngine RtcEngine = null;
  28. // Use this for initialization
  29. void Start()
  30. {
  31. LoadAssetData();
  32. if (CheckAppId())
  33. {
  34. InitEngine();
  35. SetProfile();
  36. StartDirectCdnStreamingCamera();
  37. }
  38. }
  39. // Update is called once per frame
  40. private void Update()
  41. {
  42. PermissionHelper.RequestMicrophontPermission();
  43. PermissionHelper.RequestCameraPermission();
  44. }
  45. private bool CheckAppId()
  46. {
  47. Log = new Logger(LogText);
  48. return Log.DebugAssert(_appID.Length > 10, "Please fill in your appId in API-Example/profile/appIdInput.asset");
  49. }
  50. //Show data in AgoraBasicProfile
  51. [ContextMenu("ShowAgoraBasicProfileData")]
  52. private void LoadAssetData()
  53. {
  54. if (_appIdInput == null) return;
  55. _appID = _appIdInput.appID;
  56. _token = _appIdInput.token;
  57. _channelName = _appIdInput.channelName;
  58. }
  59. private void InitEngine()
  60. {
  61. RtcEngine = Agora.Rtc.RtcEngine.CreateAgoraRtcEngine();
  62. UserEventHandler handler = new UserEventHandler(this);
  63. RtcEngineContext context = new RtcEngineContext(_appID, 0,
  64. CHANNEL_PROFILE_TYPE.CHANNEL_PROFILE_LIVE_BROADCASTING,
  65. AUDIO_SCENARIO_TYPE.AUDIO_SCENARIO_DEFAULT);
  66. RtcEngine.Initialize(context);
  67. RtcEngine.InitEventHandler(new UserEventHandler(this));
  68. }
  69. private void SetProfile()
  70. {
  71. RtcEngine.EnableAudio();
  72. RtcEngine.EnableVideo();
  73. RtcEngine.SetChannelProfile(CHANNEL_PROFILE_TYPE.CHANNEL_PROFILE_LIVE_BROADCASTING);
  74. RtcEngine.SetClientRole(CLIENT_ROLE_TYPE.CLIENT_ROLE_BROADCASTER);
  75. }
  76. private void StartDirectCdnStreamingCamera()
  77. {
  78. DirectCdnStreamingMediaOptions options = new DirectCdnStreamingMediaOptions();
  79. options.publishMicrophoneTrack.SetValue(true);
  80. options.publishCameraTrack.SetValue(true);
  81. RtcEngine.SetDirectCdnStreamingVideoConfiguration(new VideoEncoderConfiguration
  82. {
  83. dimensions = new VideoDimensions { width = 1280, height = 720 },
  84. frameRate = 15,
  85. bitrate = 2260,
  86. minBitrate = -1,
  87. degradationPreference = DEGRADATION_PREFERENCE.MAINTAIN_QUALITY,
  88. codecType = VIDEO_CODEC_TYPE.VIDEO_CODEC_H264,
  89. mirrorMode = VIDEO_MIRROR_MODE_TYPE.VIDEO_MIRROR_MODE_DISABLED
  90. });
  91. RtcEngine.StartDirectCdnStreaming(PUBLISH_URL, options);
  92. RtcEngine.StartPreview();
  93. MakeVideoView(0);
  94. }
  95. private void OnDestroy()
  96. {
  97. Debug.Log("OnDestroy");
  98. if (RtcEngine == null) return;
  99. RtcEngine.InitEventHandler(null);
  100. DestroyVideoView(0);
  101. RtcEngine.StopPreview();
  102. RtcEngine.StopDirectCdnStreaming();
  103. RtcEngine.Dispose();
  104. }
  105. internal string GetChannelName()
  106. {
  107. return _channelName;
  108. }
  109. #region -- Video Render UI Logic ---
  110. internal static void MakeVideoView(uint uid, string channelId = "")
  111. {
  112. GameObject go = GameObject.Find(uid.ToString());
  113. if (!ReferenceEquals(go, null))
  114. {
  115. return; // reuse
  116. }
  117. // create a GameObject and assign to this new user
  118. VideoSurface videoSurface = MakeImageSurface(uid.ToString());
  119. if (!ReferenceEquals(videoSurface, null))
  120. {
  121. // configure videoSurface
  122. if (uid == 0)
  123. {
  124. videoSurface.SetForUser(uid, channelId);
  125. }
  126. else
  127. {
  128. videoSurface.SetForUser(uid, channelId, VIDEO_SOURCE_TYPE.VIDEO_SOURCE_REMOTE);
  129. }
  130. videoSurface.OnTextureSizeModify += (int width, int height) =>
  131. {
  132. float scale = (float)height / (float)width;
  133. videoSurface.transform.localScale = new Vector3(-5, 5 * scale, 1);
  134. Debug.Log("OnTextureSizeModify: " + width + " " + height);
  135. };
  136. videoSurface.SetEnable(true);
  137. }
  138. }
  139. // VIDEO TYPE 1: 3D Object
  140. private static VideoSurface MakePlaneSurface(string goName)
  141. {
  142. GameObject go = GameObject.CreatePrimitive(PrimitiveType.Plane);
  143. if (go == null)
  144. {
  145. return null;
  146. }
  147. go.name = goName;
  148. // set up transform
  149. go.transform.Rotate(-90.0f, 0.0f, 0.0f);
  150. float yPos = Random.Range(3.0f, 5.0f);
  151. float xPos = Random.Range(-2.0f, 2.0f);
  152. go.transform.position = new Vector3(xPos, yPos, 0f);
  153. go.transform.localScale = new Vector3(0.25f, 0.5f, .5f);
  154. // configure videoSurface
  155. VideoSurface videoSurface = go.AddComponent<VideoSurface>();
  156. return videoSurface;
  157. }
  158. // Video TYPE 2: RawImage
  159. private static VideoSurface MakeImageSurface(string goName)
  160. {
  161. GameObject go = new GameObject();
  162. if (go == null)
  163. {
  164. return null;
  165. }
  166. go.name = goName;
  167. // to be renderered onto
  168. go.AddComponent<RawImage>();
  169. // make the object draggable
  170. go.AddComponent<UIElementDrag>();
  171. GameObject canvas = GameObject.Find("VideoCanvas");
  172. if (canvas != null)
  173. {
  174. go.transform.parent = canvas.transform;
  175. Debug.Log("add video view");
  176. }
  177. else
  178. {
  179. Debug.Log("Canvas is null video view");
  180. }
  181. // set up transform
  182. go.transform.Rotate(0f, 0.0f, 180.0f);
  183. go.transform.localPosition = Vector3.zero;
  184. go.transform.localScale = new Vector3(3f, 4f, 1f);
  185. // configure videoSurface
  186. VideoSurface videoSurface = go.AddComponent<VideoSurface>();
  187. return videoSurface;
  188. }
  189. internal static void DestroyVideoView(uint uid)
  190. {
  191. GameObject go = GameObject.Find(uid.ToString());
  192. if (!ReferenceEquals(go, null))
  193. {
  194. Object.Destroy(go);
  195. }
  196. }
  197. #endregion
  198. }
  199. #region -- Agora Event ---
  200. internal class UserEventHandler : IRtcEngineEventHandler
  201. {
  202. private readonly StartDirectCdnStreaming _startDirectCdnStreaming;
  203. internal UserEventHandler(StartDirectCdnStreaming startDirectCdnStreaming)
  204. {
  205. _startDirectCdnStreaming = startDirectCdnStreaming;
  206. }
  207. public override void OnJoinChannelSuccess(RtcConnection connection, int elapsed)
  208. {
  209. int build = 0;
  210. _startDirectCdnStreaming.Log.UpdateLog(string.Format("sdk version: ${0}",
  211. _startDirectCdnStreaming.RtcEngine.GetVersion(ref build)));
  212. _startDirectCdnStreaming.Log.UpdateLog(string.Format(
  213. "onJoinChannelSuccess channelName: {0}, uid: {1}, elapsed: {2}", connection.channelId,
  214. connection.localUid, elapsed));
  215. StartDirectCdnStreaming.MakeVideoView(0);
  216. }
  217. public override void OnLeaveChannel(RtcConnection connection, RtcStats stats)
  218. {
  219. _startDirectCdnStreaming.Log.UpdateLog("OnLeaveChannelSuccess");
  220. StartDirectCdnStreaming.DestroyVideoView(0);
  221. }
  222. public override void OnUserJoined(RtcConnection connection, uint remoteUid, int elapsed)
  223. {
  224. _startDirectCdnStreaming.Log.UpdateLog(string.Format("OnUserJoined uid: ${0} elapsed: ${1}",
  225. connection.localUid, elapsed));
  226. StartDirectCdnStreaming.MakeVideoView(remoteUid, _startDirectCdnStreaming.GetChannelName());
  227. }
  228. public override void OnUserOffline(RtcConnection connection, uint remoteUid,
  229. USER_OFFLINE_REASON_TYPE reason)
  230. {
  231. _startDirectCdnStreaming.Log.UpdateLog(string.Format("OnUserOffLine uid: ${0}, reason: ${1}", remoteUid,
  232. (int)reason));
  233. StartDirectCdnStreaming.DestroyVideoView(remoteUid);
  234. }
  235. public override void OnError(int error, string msg)
  236. {
  237. _startDirectCdnStreaming.Log.UpdateLog(string.Format("OnSDKError error: {0}, msg: {1}", error, msg));
  238. }
  239. public override void OnConnectionLost(RtcConnection connection)
  240. {
  241. _startDirectCdnStreaming.Log.UpdateLog("OnConnectionLost ");
  242. }
  243. public override void OnDirectCdnStreamingStateChanged(DIRECT_CDN_STREAMING_STATE state, DIRECT_CDN_STREAMING_ERROR error, string message)
  244. {
  245. _startDirectCdnStreaming.Log.UpdateLog(string.Format("OnDirectCdnStreamingStateChanged state: {0}, error: {1}", state, error));
  246. }
  247. public override void OnDirectCdnStreamingStats(DirectCdnStreamingStats stats)
  248. {
  249. _startDirectCdnStreaming.Log.UpdateLog("OnDirectCdnStreamingStats videoHeight:" + stats.videoHeight + " videoWidth:" + stats.videoWidth);
  250. _startDirectCdnStreaming.Log.UpdateLog("OnDirectCdnStreamingStats fps:" + stats.fps);
  251. }
  252. }
  253. #endregion
  254. }