FirstPersonStreammingCast.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. /****************************************************************************
  2. * Copyright 2019 Nreal Techonology Limited. All rights reserved.
  3. *
  4. * This file is part of NRSDK.
  5. *
  6. * https://www.nreal.ai/
  7. *
  8. *****************************************************************************/
  9. namespace NRKernal.Experimental.StreammingCast
  10. {
  11. using NRKernal.Record;
  12. using System.Linq;
  13. using UnityEngine;
  14. using System;
  15. using NRKernal.Experimental.NetWork;
  16. using System.IO;
  17. using System.Collections;
  18. /// <summary> A first person streamming cast. </summary>
  19. public class FirstPersonStreammingCast : MonoBehaviour
  20. {
  21. public delegate void OnResponse(bool result);
  22. /// <summary> The FPS configuration view. </summary>
  23. [SerializeField]
  24. private FPSConfigView m_FPSConfigView;
  25. public BlendMode m_BlendMode = BlendMode.Blend;
  26. public ResolutionLevel m_ResolutionLevel = ResolutionLevel.Middle;
  27. public LayerMask m_CullingMask = -1;
  28. public NRVideoCapture.AudioState m_AudioState = NRVideoCapture.AudioState.None;
  29. public bool useGreenBackGround = false;
  30. /// <summary> The net worker. </summary>
  31. private NetWorkBehaviour m_NetWorker;
  32. /// <summary> The video capture. </summary>
  33. private NRVideoCapture m_VideoCapture = null;
  34. public NRVideoCapture VideoCapture
  35. {
  36. get
  37. {
  38. return m_VideoCapture;
  39. }
  40. }
  41. private string m_ServerIP;
  42. /// <summary> Gets the full pathname of the rtp file. </summary>
  43. /// <value> The full pathname of the rtp file. </value>
  44. public string RTPPath
  45. {
  46. get
  47. {
  48. return string.Format(@"rtp://{0}:5555", m_ServerIP);
  49. }
  50. }
  51. public string VideoSavePath
  52. {
  53. get
  54. {
  55. string timeStamp = Time.time.ToString().Replace(".", "").Replace(":", "");
  56. string filename = string.Format("Nreal_Record_{0}.mp4", timeStamp);
  57. string filepath = Path.Combine(Application.persistentDataPath, filename);
  58. return filepath;
  59. }
  60. }
  61. private bool m_IsInitialized = false;
  62. private bool m_IsStreamLock = false;
  63. private bool m_IsStreamStarted = false;
  64. private bool m_IsRecordStarted = false;
  65. public enum ResolutionLevel
  66. {
  67. High,
  68. Middle,
  69. Low,
  70. }
  71. /// <summary> Starts this object. </summary>
  72. void Start()
  73. {
  74. this.Init();
  75. }
  76. /// <summary> Initializes this object. </summary>
  77. private void Init()
  78. {
  79. if (m_IsInitialized)
  80. {
  81. return;
  82. }
  83. m_FPSConfigView.OnStreamBtnClicked += OnStream;
  84. m_FPSConfigView.OnRecordBtnClicked += OnRecord;
  85. m_IsInitialized = true;
  86. }
  87. private void OnRecord(OnResponse response)
  88. {
  89. if (!m_IsRecordStarted)
  90. {
  91. CreateAndStart();
  92. }
  93. else
  94. {
  95. StopVideoCapture();
  96. }
  97. response?.Invoke(true);
  98. m_IsRecordStarted = !m_IsRecordStarted;
  99. }
  100. private void OnStream(OnResponse response)
  101. {
  102. if (m_IsStreamLock)
  103. {
  104. return;
  105. }
  106. m_IsStreamLock = true;
  107. if (m_NetWorker == null)
  108. {
  109. m_NetWorker = new NetWorkBehaviour();
  110. m_NetWorker.Listen();
  111. }
  112. if (!m_IsStreamStarted)
  113. {
  114. LocalServerSearcher.Instance.Search((result) =>
  115. {
  116. NRDebugger.Info("[FPStreammingCast] Get the server result:{0} ip:{1}", result.isSuccess, result.endPoint?.Address);
  117. if (result.isSuccess)
  118. {
  119. string ip = result.endPoint.Address.ToString();
  120. m_NetWorker.CheckServerAvailable(ip, (isavailable) =>
  121. {
  122. NRDebugger.Info("[FPStreammingCast] Is the server {0} ok? {1}", ip, result);
  123. if (isavailable)
  124. {
  125. m_ServerIP = ip;
  126. m_IsStreamStarted = true;
  127. CreateAndStart();
  128. }
  129. response?.Invoke(isavailable);
  130. m_IsStreamLock = false;
  131. });
  132. }
  133. else
  134. {
  135. m_IsStreamLock = false;
  136. response?.Invoke(false);
  137. NRDebugger.Error("[FPStreammingCast] Can not find the server...");
  138. }
  139. });
  140. }
  141. else
  142. {
  143. StopVideoCapture();
  144. m_IsStreamStarted = false;
  145. m_IsStreamLock = false;
  146. response?.Invoke(true);
  147. }
  148. }
  149. /// <summary> Converts this object to a server. </summary>
  150. private void CreateAndStart()
  151. {
  152. CreateVideoCapture(delegate ()
  153. {
  154. NRDebugger.Info("[FPStreammingCast] Start video capture.");
  155. StartCoroutine(StartVideoCapture());
  156. });
  157. }
  158. private Resolution GetResolutionByLevel(ResolutionLevel level)
  159. {
  160. var resolutions = NRVideoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height);
  161. Resolution resolution = new Resolution();
  162. switch (level)
  163. {
  164. case ResolutionLevel.High:
  165. resolution = resolutions.ElementAt(0);
  166. break;
  167. case ResolutionLevel.Middle:
  168. resolution = resolutions.ElementAt(1);
  169. break;
  170. case ResolutionLevel.Low:
  171. resolution = resolutions.ElementAt(2);
  172. break;
  173. default:
  174. break;
  175. }
  176. return resolution;
  177. }
  178. #region video capture
  179. /// <summary> Creates video capture. </summary>
  180. /// <param name="callback"> The callback.</param>
  181. private void CreateVideoCapture(Action callback)
  182. {
  183. NRDebugger.Info("[FPStreammingCast] Created VideoCapture Instance!");
  184. if (m_VideoCapture != null)
  185. {
  186. callback?.Invoke();
  187. return;
  188. }
  189. NRVideoCapture.CreateAsync(false, delegate (NRVideoCapture videoCapture)
  190. {
  191. if (videoCapture != null)
  192. {
  193. m_VideoCapture = videoCapture;
  194. callback?.Invoke();
  195. }
  196. else
  197. {
  198. NRDebugger.Error("[FPStreammingCast] Failed to create VideoCapture Instance!");
  199. }
  200. });
  201. }
  202. /// <summary> Starts video capture. </summary>
  203. public IEnumerator StartVideoCapture()
  204. {
  205. Resolution cameraResolution = GetResolutionByLevel(m_ResolutionLevel);
  206. NRDebugger.Info("[FPStreammingCast] cameraResolution:" + cameraResolution);
  207. if (m_VideoCapture != null)
  208. {
  209. CameraParameters cameraParameters = new CameraParameters();
  210. cameraParameters.hologramOpacity = 1f;
  211. cameraParameters.frameRate = cameraResolution.refreshRate;
  212. cameraParameters.cameraResolutionWidth = cameraResolution.width;
  213. cameraParameters.cameraResolutionHeight = cameraResolution.height;
  214. cameraParameters.pixelFormat = CapturePixelFormat.BGRA32;
  215. cameraParameters.blendMode = m_BlendMode;
  216. cameraParameters.audioState = m_AudioState;
  217. // Send the audioState to server.
  218. if (m_NetWorker != null)
  219. {
  220. LitJson.JsonData json = new LitJson.JsonData();
  221. json["useAudio"] = (cameraParameters.audioState != NRVideoCapture.AudioState.None);
  222. m_NetWorker.SendMsg(json, (response) =>
  223. {
  224. bool result;
  225. if (bool.TryParse(response["success"].ToString(), out result) && result)
  226. {
  227. m_VideoCapture.StartVideoModeAsync(cameraParameters, OnStartedVideoCaptureMode, true);
  228. }
  229. else
  230. {
  231. NRDebugger.Error("[FPStreammingCast] Can not received response from server.");
  232. }
  233. });
  234. }
  235. else
  236. {
  237. m_VideoCapture.StartVideoModeAsync(cameraParameters, OnStartedVideoCaptureMode, true);
  238. }
  239. }
  240. else
  241. {
  242. NRDebugger.Info("[FPStreammingCast] VideoCapture object is null...");
  243. }
  244. yield return new WaitForEndOfFrame();
  245. }
  246. /// <summary> Stops video capture. </summary>
  247. public void StopVideoCapture()
  248. {
  249. NRDebugger.Info("[FPStreammingCast] Stop Video Capture!");
  250. m_VideoCapture.StopRecordingAsync(OnStoppedRecordingVideo);
  251. }
  252. /// <summary> Executes the 'started video capture mode' action. </summary>
  253. /// <param name="result"> The result.</param>
  254. void OnStartedVideoCaptureMode(NRVideoCapture.VideoCaptureResult result)
  255. {
  256. if (!result.success)
  257. {
  258. NRDebugger.Info("[FPStreammingCast] Started Video Capture Mode Faild!");
  259. return;
  260. }
  261. NRDebugger.Info("[FPStreammingCast] Started Video Capture Mode!");
  262. m_VideoCapture.StartRecordingAsync(m_IsStreamStarted ? RTPPath : VideoSavePath, OnStartedRecordingVideo);
  263. m_VideoCapture.GetContext().GetBehaviour().CaptureCamera.cullingMask = m_CullingMask.value;
  264. m_VideoCapture.GetContext().GetBehaviour().CaptureCamera.backgroundColor = useGreenBackGround ? Color.green : Color.black;
  265. }
  266. /// <summary> Executes the 'stopped video capture mode' action. </summary>
  267. /// <param name="result"> The result.</param>
  268. void OnStoppedVideoCaptureMode(NRVideoCapture.VideoCaptureResult result)
  269. {
  270. NRDebugger.Info("[FPStreammingCast] Stopped Video Capture Mode!");
  271. m_VideoCapture = null;
  272. }
  273. /// <summary> Executes the 'started recording video' action. </summary>
  274. /// <param name="result"> The result.</param>
  275. void OnStartedRecordingVideo(NRVideoCapture.VideoCaptureResult result)
  276. {
  277. NRDebugger.Info("[FPStreammingCast] Started Recording Video!");
  278. }
  279. /// <summary> Executes the 'stopped recording video' action. </summary>
  280. /// <param name="result"> The result.</param>
  281. void OnStoppedRecordingVideo(NRVideoCapture.VideoCaptureResult result)
  282. {
  283. NRDebugger.Info("[FPStreammingCast] Stopped Recording Video!");
  284. m_VideoCapture.StopVideoModeAsync(OnStoppedVideoCaptureMode);
  285. if (m_NetWorker != null)
  286. {
  287. m_NetWorker?.Close();
  288. m_NetWorker = null;
  289. }
  290. }
  291. #endregion
  292. }
  293. }