NativeEncoder.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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 AOT;
  12. using NRKernal;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Runtime.InteropServices;
  16. /// <summary> Callback, called when audio data is sampled. </summary>
  17. /// <param name="data"> The sampled audio data.</param>
  18. /// <param name="size"> The size of the audio data.</param>
  19. [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
  20. public delegate void AudioDataCallBack(IntPtr data, UInt32 size);
  21. /// <summary> A native encoder. </summary>
  22. public class NativeEncoder
  23. {
  24. public const string NRNativeEncodeLibrary = "libmedia_codec";
  25. public UInt64 EncodeHandle;
  26. private event AudioDataCallBack m_OnAudioDataCallback;
  27. private bool mVideoEncoderWorking = false;
  28. private bool mAudioEncoderWorking = false;
  29. private List<IEncoderBase> mActiveEncoders = new List<IEncoderBase>();
  30. //NativeEncoder can only exist one instance
  31. private static NativeEncoder gInstance = null;
  32. public static NativeEncoder GetInstance()
  33. {
  34. if(gInstance == null)
  35. {
  36. gInstance = new NativeEncoder();
  37. }
  38. return gInstance;
  39. }
  40. private NativeEncoder()
  41. {
  42. var result = NativeApi.HWEncoderCreate(ref EncodeHandle);
  43. NativeErrorListener.Check(result, this, "HWEncoderCreate");
  44. }
  45. public bool Start()
  46. {
  47. if (mVideoEncoderWorking)
  48. {
  49. NRDebugger.Warning("[NativeEncoder] video encoder is already working");
  50. return false;
  51. }
  52. var result = NativeApi.HWEncoderStart(EncodeHandle);
  53. NativeErrorListener.Check(result, this, "Start");
  54. bool success = (result == NativeResult.Success);
  55. if (success)
  56. {
  57. mVideoEncoderWorking = true;
  58. }
  59. return success;
  60. }
  61. public bool StartAudioRecorder(AudioDataCallBack onAudioDataCallback)
  62. {
  63. if (onAudioDataCallback != null)
  64. m_OnAudioDataCallback += onAudioDataCallback;
  65. if (!mAudioEncoderWorking)
  66. {
  67. var result = NativeApi.HWEncoderStartOnlyAudioRecorder(EncodeHandle, OnAudioDataCallback);
  68. NativeErrorListener.Check(result, this, "StartAudioRecorder");
  69. bool success = (result == NativeResult.Success);
  70. if (success)
  71. {
  72. mAudioEncoderWorking = true;
  73. }
  74. return success;
  75. }
  76. return true;
  77. }
  78. public bool StopAudioRecorder(AudioDataCallBack onAudioDataCallback)
  79. {
  80. if (onAudioDataCallback != null)
  81. m_OnAudioDataCallback -= onAudioDataCallback;
  82. var delegateArray = m_OnAudioDataCallback?.GetInvocationList();
  83. if ((delegateArray == null || delegateArray.Length == 0) && mAudioEncoderWorking)
  84. {
  85. var result = NativeApi.HWEncoderStopOnlyAudioRecorder(EncodeHandle);
  86. NativeErrorListener.Check(result, this, "StopAudioRecorder");
  87. bool success = (result == NativeResult.Success);
  88. if (success)
  89. {
  90. mAudioEncoderWorking = false;
  91. }
  92. return success;
  93. }
  94. return true;
  95. }
  96. [MonoPInvokeCallback(typeof(AudioDataCallBack))]
  97. public static void OnAudioDataCallback(IntPtr data, UInt32 size)
  98. {
  99. if (gInstance != null)
  100. gInstance.m_OnAudioDataCallback?.Invoke(data, size);
  101. }
  102. public void SetConfigration(NativeEncodeConfig config, IntPtr androidMediaProjection)
  103. {
  104. var result = NativeApi.HWEncoderSetConfigration(EncodeHandle, config.ToString());
  105. NativeErrorListener.Check(result, this, "SetConfigration");
  106. NativeApi.HWEncoderSetMediaProjection(EncodeHandle, androidMediaProjection);
  107. // NativeErrorListener.Check(result, this, "SetConfigration-MediaProjection");
  108. }
  109. /// <summary> Adjust the volume of encoder.</summary>
  110. /// <param name="recordIdx"> Recorder index.</param>
  111. /// <param name="factor"> The factor of volume.</param>
  112. public void AdjustVolume(RecorderIndex recordIdx, float factor)
  113. {
  114. //NRDebugger.Info("[NativeEncoder] AdjustVolume: recordIdx={0}, factor={1}", (int)recordIdx, factor);
  115. var result = NativeApi.HWEncoderAdjustVolume(EncodeHandle, (int)recordIdx, factor);
  116. NativeErrorListener.Check(result, this, "AdjustVolume");
  117. }
  118. /// <summary> Updates the surface. </summary>
  119. /// <param name="texture_id"> Identifier for the texture.</param>
  120. /// <param name="time_stamp"> The time stamp.</param>
  121. public void UpdateSurface(IntPtr texture_id, UInt64 time_stamp)
  122. {
  123. NativeApi.HWEncoderUpdateSurface(EncodeHandle, texture_id, time_stamp);
  124. }
  125. public void UpdateAudioData(byte[] audioData, int samplerate, int bytePerSample, int channel)
  126. {
  127. //NRDebugger.Info("[NativeEncode] UpdateAudioData, audioData len:{0} samplerate:{1} bytePerSample:{2} channel:{3}", audioData.Length, samplerate, bytePerSample, channel);
  128. NativeApi.HWEncoderNotifyAudioData(EncodeHandle, audioData, audioData.Length / bytePerSample, bytePerSample, channel, samplerate, 1);
  129. }
  130. public void Register(IEncoderBase encoder)
  131. {
  132. if (!mActiveEncoders.Contains(encoder))
  133. {
  134. mActiveEncoders.Add(encoder);
  135. }
  136. }
  137. public void UnRegister(IEncoderBase encoder)
  138. {
  139. if (mActiveEncoders.Contains(encoder))
  140. {
  141. mActiveEncoders.Remove(encoder);
  142. }
  143. }
  144. public bool Stop()
  145. {
  146. if (mVideoEncoderWorking)
  147. {
  148. var result = NativeApi.HWEncoderStop(EncodeHandle);
  149. NativeErrorListener.Check(result, this, "Stop");
  150. bool success = (result == NativeResult.Success);
  151. if (success)
  152. {
  153. mVideoEncoderWorking = false;
  154. }
  155. return success;
  156. }
  157. return true;
  158. }
  159. public void Destroy()
  160. {
  161. if (mActiveEncoders.Count == 0)
  162. {
  163. var result = NativeApi.HWEncoderDestroy(EncodeHandle);
  164. NativeErrorListener.Check(result, this, "Destroy");
  165. gInstance = null;
  166. }
  167. }
  168. private struct NativeApi
  169. {
  170. /// <summary> Hardware encoder create. </summary>
  171. /// <param name="out_encoder_handle"> [in,out] Handle of the out encoder.</param>
  172. /// <returns> A NativeResult. </returns>
  173. [DllImport(NRNativeEncodeLibrary)]
  174. public static extern NativeResult HWEncoderCreate(ref UInt64 out_encoder_handle);
  175. /// <summary> Hardware encoder start. </summary>
  176. /// <param name="encoder_handle"> Handle of the encoder.</param>
  177. /// <returns> A NativeResult. </returns>
  178. [DllImport(NRNativeEncodeLibrary)]
  179. public static extern NativeResult HWEncoderStart(UInt64 encoder_handle);
  180. /// <summary> Hardware encoder start, only for audio and no video.</summary>
  181. /// <param name="encoder_handle"> Handle of the encoder.</param>
  182. /// <param name="onAudioDataCallback"> Callback for sampled audio data.</param>
  183. /// <returns> A NativeResult. </returns>
  184. [DllImport(NRNativeEncodeLibrary)]
  185. public static extern NativeResult HWEncoderStartOnlyAudioRecorder(UInt64 encoder_handle, AudioDataCallBack onAudioDataCallback);
  186. /// <summary> Hardware encoder stop, only for audio and no video.</summary>
  187. /// <param name="encoder_handle"> Handle of the encoder.</param>
  188. /// <returns> A NativeResult. </returns>
  189. [DllImport(NRNativeEncodeLibrary)]
  190. public static extern NativeResult HWEncoderStopOnlyAudioRecorder(UInt64 encoder_handle);
  191. /// <summary> Hardware encoder set configration. </summary>
  192. /// <param name="encoder_handle"> Handle of the encoder.</param>
  193. /// <param name="config"> The configuration.</param>
  194. /// <returns> A NativeResult. </returns>
  195. [DllImport(NRNativeEncodeLibrary)]
  196. public static extern NativeResult HWEncoderSetConfigration(UInt64 encoder_handle, string config);
  197. /// <summary> Hardware encoder set configration. </summary>
  198. /// <param name="encoder_handle"> Handle of the encoder.</param>
  199. /// <param name="which_recorder"> Recorder index.</param>
  200. /// <param name="scale_factor"> Scale factor.</param>
  201. /// <returns> A NativeResult. </returns>
  202. [DllImport(NRNativeEncodeLibrary)]
  203. public static extern NativeResult HWEncoderAdjustVolume(UInt64 encoder_handle, int which_recorder, float scale_factor);
  204. /// <summary> Hardware encoder set android MediaProjection object. </summary>
  205. /// <param name="encoder_handle"> Handle of the encoder.</param>
  206. /// <param name="mediaProjection"> The android MediaProjection object.</param>
  207. /// <returns> A NativeResult. </returns>
  208. [DllImport(NRNativeEncodeLibrary)]
  209. public static extern NativeResult HWEncoderSetMediaProjection(UInt64 encoder_handle, IntPtr mediaProjection);
  210. /// <summary> Hardware encoder update surface. </summary>
  211. /// <param name="encoder_handle"> Handle of the encoder.</param>
  212. /// <param name="texture_id"> Identifier for the texture.</param>
  213. /// <param name="time_stamp"> The time stamp.</param>
  214. /// <returns> A NativeResult. </returns>
  215. [DllImport(NRNativeEncodeLibrary)]
  216. public static extern NativeResult HWEncoderUpdateSurface(UInt64 encoder_handle, IntPtr texture_id, UInt64 time_stamp);
  217. /// <summary> Push sampled audio data. </summary>
  218. /// <param name="encoder_handle"> Handle of the encoder.</param>
  219. /// <param name="audioSamples"> Sampled audio data.</param>
  220. /// <param name="nSamples"> Count of samples.</param>
  221. /// <param name="nBytesPerSample"> Bytes per sample.</param>
  222. /// <param name="nChannels"> Count of channels.</param>
  223. /// <param name="samples_per_sec"> Count of samples per second.</param>
  224. /// <param name="sample_fmt"> Sample format.</param>
  225. /// <returns> A NativeResult. </returns>
  226. [DllImport(NRNativeEncodeLibrary)]
  227. public static extern NativeResult HWEncoderNotifyAudioData(UInt64 encoder_handle, byte[] audioSamples, int nSamples,
  228. int nBytesPerSample, int nChannels, int samples_per_sec, int sample_fmt); //sample_fmt :0:s16, 8 float
  229. /// <summary> Hardware encoder stop. </summary>
  230. /// <param name="encoder_handle"> Handle of the encoder.</param>
  231. /// <returns> A NativeResult. </returns>
  232. [DllImport(NRNativeEncodeLibrary)]
  233. public static extern NativeResult HWEncoderStop(UInt64 encoder_handle);
  234. /// <summary> Hardware encoder destroy. </summary>
  235. /// <param name="encoder_handle"> Handle of the encoder.</param>
  236. /// <returns> A NativeResult. </returns>
  237. [DllImport(NRNativeEncodeLibrary)]
  238. public static extern NativeResult HWEncoderDestroy(UInt64 encoder_handle);
  239. }
  240. }
  241. }