NRVideoCapture.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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.Record
  10. {
  11. using UnityEngine;
  12. using NRKernal;
  13. using System;
  14. using System.Collections.Generic;
  15. /// <summary>
  16. /// Records a video from the MR images directly to disk. MR images comes from rgb camera or rgb
  17. /// camera image and virtual image blending. The final video recording will be stored on the file
  18. /// system in the MP4 format. </summary>
  19. public class NRVideoCapture : IDisposable
  20. {
  21. /// <summary> Default constructor. </summary>
  22. public NRVideoCapture()
  23. {
  24. IsRecording = false;
  25. }
  26. /// <summary> Finalizer. </summary>
  27. ~NRVideoCapture()
  28. {
  29. }
  30. /// <summary> A list of all the supported device resolutions for recording videos. </summary>
  31. /// <value> The supported resolutions. </value>
  32. public static IEnumerable<Resolution> SupportedResolutions
  33. {
  34. get
  35. {
  36. NativeResolution rgbResolution = new NativeResolution(1280, 720);
  37. if (NRDevice.Subsystem.IsFeatureSupported(NRSupportedFeature.NR_FEATURE_RGB_CAMERA))
  38. rgbResolution = NRFrame.GetDeviceResolution(NativeDevice.RGB_CAMERA);
  39. Resolution stand_resolution = new Resolution()
  40. {
  41. width = rgbResolution.width,
  42. height = rgbResolution.height,
  43. refreshRate = NativeConstants.RECORD_FPS_DEFAULT,
  44. };
  45. yield return stand_resolution;
  46. Resolution low_resolution = new Resolution()
  47. {
  48. width = stand_resolution.width / 2,
  49. height = stand_resolution.height / 2,
  50. refreshRate = NativeConstants.RECORD_FPS_DEFAULT,
  51. };
  52. yield return low_resolution;
  53. Resolution high_resolution = new Resolution()
  54. {
  55. width = stand_resolution.width * 3 / 2,
  56. height = stand_resolution.height * 3 / 2,
  57. refreshRate = NativeConstants.RECORD_FPS_DEFAULT,
  58. };
  59. yield return high_resolution;
  60. }
  61. }
  62. /// <summary>
  63. /// Indicates whether or not the VideoCapture instance is currently recording video. </summary>
  64. /// <value> True if this object is recording, false if not. </value>
  65. public bool IsRecording { get; private set; }
  66. /// <summary> Context for the capture. </summary>
  67. private FrameCaptureContext m_CaptureContext;
  68. /// <summary> Gets the context. </summary>
  69. /// <returns> The context. </returns>
  70. public FrameCaptureContext GetContext()
  71. {
  72. return m_CaptureContext;
  73. }
  74. /// <summary> Gets the preview texture. </summary>
  75. /// <value> The preview texture. </value>
  76. public Texture PreviewTexture
  77. {
  78. get
  79. {
  80. return m_CaptureContext?.PreviewTexture;
  81. }
  82. }
  83. /// <summary> Creates an asynchronous. </summary>
  84. /// <param name="showHolograms"> True to show, false to hide the holograms.</param>
  85. /// <param name="onCreatedCallback"> The on created callback.</param>
  86. public static void CreateAsync(bool showHolograms, OnVideoCaptureResourceCreatedCallback onCreatedCallback)
  87. {
  88. NRVideoCapture capture = new NRVideoCapture();
  89. capture.m_CaptureContext = FrameCaptureContextFactory.Create();
  90. onCreatedCallback?.Invoke(capture);
  91. }
  92. /// <summary>
  93. /// Returns the supported frame rates at which a video can be recorded given a resolution. </summary>
  94. /// <param name="resolution"> A recording resolution.</param>
  95. /// <returns> The frame rates at which the video can be recorded. </returns>
  96. public static IEnumerable<int> GetSupportedFrameRatesForResolution(Resolution resolution)
  97. {
  98. yield return NativeConstants.RECORD_FPS_DEFAULT;
  99. }
  100. /// <summary> Dispose must be called to shutdown the PhotoCapture instance. </summary>
  101. public void Dispose()
  102. {
  103. if (m_CaptureContext != null)
  104. {
  105. m_CaptureContext.Release();
  106. m_CaptureContext = null;
  107. }
  108. }
  109. /// <summary> Starts recording asynchronous. </summary>
  110. /// <param name="filename"> Filename of the file.</param>
  111. /// <param name="onStartedRecordingVideoCallback"> The on started recording video callback.</param>
  112. public void StartRecordingAsync(string filename, OnStartedRecordingVideoCallback onStartedRecordingVideoCallback)
  113. {
  114. float volumeFactorMic = 1.0f;
  115. float volumeFactorApp = 1.0f;
  116. if (NRDevice.Subsystem.GetDeviceType() == NRDeviceType.NrealLight)
  117. {
  118. volumeFactorMic = NativeConstants.RECORD_VOLUME_MIC;
  119. volumeFactorApp = NativeConstants.RECORD_VOLUME_APP;
  120. }
  121. StartRecordingAsync(filename, onStartedRecordingVideoCallback, volumeFactorMic, volumeFactorApp);
  122. }
  123. /// <summary> Starts recording asynchronous. </summary>
  124. /// <param name="filename"> Filename of the file.</param>
  125. /// <param name="onStartedRecordingVideoCallback"> The on started recording video callback.</param>
  126. /// <param name="volumeFactorMic"> The volume factor of mic.</param>
  127. /// <param name="volumeFactorApp"> The volume factor of application.</param>
  128. public void StartRecordingAsync(string filename, OnStartedRecordingVideoCallback onStartedRecordingVideoCallback, float volumeFactorMic, float volumeFactorApp)
  129. {
  130. NRDebugger.Info("[VideoCapture] StartRecordingAsync: IsRecording={0}, volFactorMic={1}, volFactorApp={2}", IsRecording, volumeFactorMic, volumeFactorApp);
  131. var result = new VideoCaptureResult();
  132. if (IsRecording)
  133. {
  134. result.resultType = CaptureResultType.UnknownError;
  135. onStartedRecordingVideoCallback?.Invoke(result);
  136. }
  137. else
  138. {
  139. try
  140. {
  141. VideoEncoder encoder = m_CaptureContext.GetEncoder() as VideoEncoder;
  142. if (encoder != null)
  143. {
  144. encoder.AdjustVolume(RecorderIndex.REC_MIC, volumeFactorMic);
  145. encoder.AdjustVolume(RecorderIndex.REC_APP, volumeFactorApp);
  146. }
  147. var behaviour = m_CaptureContext.GetBehaviour();
  148. ((NRRecordBehaviour)behaviour).SetOutPutPath(filename);
  149. m_CaptureContext.StartCapture();
  150. IsRecording = true;
  151. result.resultType = CaptureResultType.Success;
  152. onStartedRecordingVideoCallback?.Invoke(result);
  153. }
  154. catch (Exception ex)
  155. {
  156. NRDebugger.Warning("[VideoCapture] StartRecordingAsync: {0}\n{1}", ex.Message, ex.StackTrace);
  157. result.resultType = CaptureResultType.UnknownError;
  158. onStartedRecordingVideoCallback?.Invoke(result);
  159. throw;
  160. }
  161. }
  162. }
  163. /// <summary> Starts video mode asynchronous. </summary>
  164. /// <param name="setupParams"> Options for controlling the setup.</param>
  165. /// <param name="onVideoModeStartedCallback"> The on video mode started callback.</param>
  166. /// <param name="autoAdaptBlendMode"> Auto adaption for BlendMode based on supported feature on current device.</param>
  167. public void StartVideoModeAsync(CameraParameters setupParams, OnVideoModeStartedCallback onVideoModeStartedCallback, bool autoAdaptBlendMode = false)
  168. {
  169. if (autoAdaptBlendMode)
  170. {
  171. var blendMode = m_CaptureContext.AutoAdaptBlendMode(setupParams.blendMode);
  172. if (blendMode != setupParams.blendMode)
  173. {
  174. NRDebugger.Warning("[VideoCapture] AutoAdaptBlendMode : {0} => {1}", setupParams.blendMode, blendMode);
  175. setupParams.blendMode = blendMode;
  176. }
  177. }
  178. if (Application.isEditor || Application.platform != RuntimePlatform.Android)
  179. {
  180. StartVideoMode(setupParams, onVideoModeStartedCallback);
  181. return;
  182. }
  183. NRDebugger.Info("[VideoCapture] StartVideoModeAsync: audioState={0}, blendMode={1}", setupParams.audioState, setupParams.blendMode);
  184. bool recordMic = setupParams.CaptureAudioMic;
  185. bool recordApp = setupParams.CaptureAudioApplication;
  186. if (recordApp)
  187. {
  188. NRAndroidPermissionsManager.GetInstance().RequestAndroidPermission("android.permission.RECORD_AUDIO").ThenAction((requestResult) =>
  189. {
  190. if (requestResult.IsAllGranted)
  191. {
  192. NRAndroidPermissionsManager.GetInstance().RequestScreenCapture().ThenAction((AndroidJavaObject mediaProjection) =>
  193. {
  194. if (mediaProjection != null)
  195. {
  196. setupParams.mediaProjection = mediaProjection;
  197. StartVideoMode(setupParams, onVideoModeStartedCallback);
  198. }
  199. else
  200. {
  201. NRDebugger.Error("[VideoCapture] Screen capture is denied by user.");
  202. var result = new VideoCaptureResult();
  203. result.resultType = CaptureResultType.UnknownError;
  204. onVideoModeStartedCallback?.Invoke(result);
  205. NRSessionManager.Instance.OprateInitException(new NRPermissionDenyError(NativeConstants.ScreenCaptureDenyErrorTip));
  206. }
  207. });
  208. }
  209. else {
  210. NRDebugger.Error("[VideoCapture] Record audio need the permission of 'android.permission.RECORD_AUDIO'.");
  211. var result = new VideoCaptureResult();
  212. result.resultType = CaptureResultType.UnknownError;
  213. onVideoModeStartedCallback?.Invoke(result);
  214. NRSessionManager.Instance.OprateInitException(new NRPermissionDenyError(NativeConstants.AudioPermissionDenyErrorTip));
  215. }
  216. });
  217. }
  218. else if (recordMic)
  219. {
  220. NRAndroidPermissionsManager.GetInstance().RequestAndroidPermission("android.permission.RECORD_AUDIO").ThenAction((requestResult) =>
  221. {
  222. if (requestResult.IsAllGranted)
  223. {
  224. StartVideoMode(setupParams, onVideoModeStartedCallback);
  225. }
  226. else {
  227. NRDebugger.Error("[VideoCapture] Record audio need the permission of 'android.permission.RECORD_AUDIO'.");
  228. var result = new VideoCaptureResult();
  229. result.resultType = CaptureResultType.UnknownError;
  230. onVideoModeStartedCallback?.Invoke(result);
  231. NRSessionManager.Instance.OprateInitException(new NRPermissionDenyError(NativeConstants.AudioPermissionDenyErrorTip));
  232. }
  233. });
  234. }
  235. else
  236. {
  237. StartVideoMode(setupParams, onVideoModeStartedCallback);
  238. }
  239. }
  240. private void StartVideoMode(CameraParameters setupParams, OnVideoModeStartedCallback onVideoModeStartedCallback, bool autoAdaptBlendMode = false)
  241. {
  242. setupParams.camMode = CamMode.VideoMode;
  243. setupParams.hologramOpacity = 1;
  244. if (autoAdaptBlendMode)
  245. {
  246. var blendMode = m_CaptureContext.AutoAdaptBlendMode(setupParams.blendMode);
  247. if (blendMode != setupParams.blendMode)
  248. {
  249. NRDebugger.Warning("[VideoCapture] AutoAdaptBlendMode : {0} => {1}", setupParams.blendMode, blendMode);
  250. setupParams.blendMode = blendMode;
  251. }
  252. }
  253. if (setupParams.frameRate <= 0)
  254. NRDebugger.Warning("[PhotoCapture] frameRate need to be bigger than zero");
  255. m_CaptureContext.StartCaptureMode(setupParams);
  256. var result = new VideoCaptureResult();
  257. result.resultType = CaptureResultType.Success;
  258. onVideoModeStartedCallback?.Invoke(result);
  259. }
  260. public void StartVideoModeAsync(CameraParameters setupParams, AudioState audioState, OnVideoModeStartedCallback onVideoModeStartedCallback, bool autoAdaptBlendMode = false)
  261. {
  262. setupParams.audioState = audioState;
  263. StartVideoModeAsync(setupParams, onVideoModeStartedCallback, autoAdaptBlendMode);
  264. }
  265. /// <summary> Stops recording asynchronous. </summary>
  266. /// <param name="onStoppedRecordingVideoCallback"> The on stopped recording video callback.</param>
  267. public void StopRecordingAsync(OnStoppedRecordingVideoCallback onStoppedRecordingVideoCallback)
  268. {
  269. var result = new VideoCaptureResult();
  270. if (!IsRecording)
  271. {
  272. result.resultType = CaptureResultType.UnknownError;
  273. onStoppedRecordingVideoCallback?.Invoke(result);
  274. }
  275. else
  276. {
  277. try
  278. {
  279. m_CaptureContext.StopCapture();
  280. IsRecording = false;
  281. result.resultType = CaptureResultType.Success;
  282. onStoppedRecordingVideoCallback?.Invoke(result);
  283. }
  284. catch (Exception)
  285. {
  286. result.resultType = CaptureResultType.UnknownError;
  287. onStoppedRecordingVideoCallback?.Invoke(result);
  288. throw;
  289. }
  290. }
  291. }
  292. /// <summary> Stops video mode asynchronous. </summary>
  293. /// <param name="onVideoModeStoppedCallback"> The on video mode stopped callback.</param>
  294. public void StopVideoModeAsync(OnVideoModeStoppedCallback onVideoModeStoppedCallback)
  295. {
  296. m_CaptureContext.StopCaptureMode();
  297. var result = new VideoCaptureResult();
  298. result.resultType = CaptureResultType.Success;
  299. onVideoModeStoppedCallback?.Invoke(result);
  300. }
  301. /// <summary> Contains the result of the capture request. </summary>
  302. public enum CaptureResultType
  303. {
  304. /// <summary>
  305. /// Specifies that the desired operation was successful.
  306. /// </summary>
  307. Success = 0,
  308. /// <summary>
  309. /// Specifies that an unknown error occurred.
  310. /// </summary>
  311. UnknownError = 1
  312. }
  313. /// <summary>
  314. /// Specifies what audio sources should be recorded while recording the video.
  315. /// </summary>
  316. public enum AudioState
  317. {
  318. /// <summary>
  319. /// Only include the mic audio in the video recording.
  320. /// </summary>
  321. MicAudio = 0,
  322. /// <summary>
  323. /// Only include the application audio in the video recording.
  324. /// </summary>
  325. ApplicationAudio = 1,
  326. ///// <summary>
  327. ///// Include both the application audio as well as the mic audio in the video recording.
  328. ///// </summary>
  329. ApplicationAndMicAudio = 2,
  330. /// <summary>
  331. /// Do not include any audio in the video recording.
  332. /// </summary>
  333. None = 3
  334. }
  335. /// <summary>
  336. /// A data container that contains the result information of a video recording operation. </summary>
  337. public struct VideoCaptureResult
  338. {
  339. /// <summary>
  340. /// A generic result that indicates whether or not the VideoCapture operation succeeded. </summary>
  341. public CaptureResultType resultType;
  342. /// <summary> The specific HResult value. </summary>
  343. public long hResult;
  344. /// <summary> Indicates whether or not the operation was successful. </summary>
  345. /// <value> True if success, false if not. </value>
  346. public bool success
  347. {
  348. get
  349. {
  350. return resultType == CaptureResultType.Success;
  351. }
  352. }
  353. }
  354. /// <summary> Called when the web camera begins recording the video. </summary>
  355. /// <param name="result"> Indicates whether or not video recording started successfully.</param>
  356. public delegate void OnStartedRecordingVideoCallback(VideoCaptureResult result);
  357. /// <summary> Called when a VideoCapture resource has been created. </summary>
  358. /// <param name="captureObject"> The VideoCapture instance.</param>
  359. public delegate void OnVideoCaptureResourceCreatedCallback(NRVideoCapture captureObject);
  360. /// <summary> Called when video mode has been started. </summary>
  361. /// <param name="result"> Indicates whether or not video mode was successfully activated.</param>
  362. public delegate void OnVideoModeStartedCallback(VideoCaptureResult result);
  363. /// <summary> Called when video mode has been stopped. </summary>
  364. /// <param name="result"> Indicates whether or not video mode was successfully deactivated.</param>
  365. public delegate void OnVideoModeStoppedCallback(VideoCaptureResult result);
  366. /// <summary> Called when the video recording has been saved to the file system. </summary>
  367. /// <param name="result"> Indicates whether or not video recording was saved successfully to the
  368. /// file system.</param>
  369. public delegate void OnStoppedRecordingVideoCallback(VideoCaptureResult result);
  370. }
  371. }