CameraHelperV2.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. using Android;
  2. using Android.App;
  3. using Android.Content;
  4. using Android.Content.PM;
  5. using Android.Hardware.Camera2;
  6. using Android.OS;
  7. using Android.Util;
  8. using Android.Views;
  9. using Java.Lang;
  10. using Java.Util;
  11. using Java.Util.Concurrent;
  12. using System;
  13. using System.Collections.Generic;
  14. using Vinno.vCloud.FIS.CrossPlatform.Common;
  15. using Vinno.vCloud.FIS.CrossPlatform.Common.LiveVideo;
  16. using Exception = System.Exception;
  17. namespace Vinno.vCloud.FIS.CrossPlatform.Android.LiveVideo
  18. {
  19. public class CameraHelperV2
  20. {
  21. private readonly Context _mContext;
  22. private CameraManager _cameraManager;
  23. private PackageManager _packageManager;
  24. private string _mCameraId;
  25. private bool _isFront;
  26. private CameraDevice _mCameraDevice;
  27. private CameraStateCallBack _cameraStateCallBack;
  28. private CameraCaptureSessionCallback _cameraCaptureSessionCallback;
  29. private Handler _mBackgroundHandler;
  30. private HandlerThread _mBackgroundThread;
  31. private CaptureRequest.Builder _mCaptureRequestBuilder;
  32. private CaptureRequest _mCaptureRequest;
  33. private CameraCaptureSession _mCameraCaptureSession;
  34. private readonly Semaphore _mCameraOpenCloseLock = new Semaphore(1);//以防止在关闭相机之前应用程序退出
  35. private CameraReaderHelperV2 _cameraReader;
  36. public event EventHandler<ImageFrameData> ImageFrameReceived;
  37. private int _cameraWidth;
  38. private int _cameraHeight;
  39. private int _fps;
  40. public CameraHelperV2(int cameraWidth, int cameraHeight, string cameraId = null, int fps = 15)
  41. {
  42. _mContext = Application.Context;
  43. _packageManager = _mContext.PackageManager;
  44. _cameraHeight = cameraHeight;
  45. _cameraWidth = cameraWidth;
  46. _fps = fps;
  47. _cameraManager = (CameraManager)_mContext.GetSystemService(Context.CameraService);
  48. _mCameraId = cameraId;
  49. }
  50. public void ChangeCameraId(string cameraId)
  51. {
  52. if (_mCameraId != cameraId)
  53. {
  54. _mCameraId = cameraId;
  55. CloseCamera();
  56. OpenCamera();
  57. }
  58. }
  59. public void Start()
  60. {
  61. try
  62. {
  63. if (string.IsNullOrEmpty(_mCameraId))
  64. {
  65. CrossPlatformHelper.Instance.LogWriter?.WriteLineError($"Camera Helper Init Error : Id is null");
  66. return;
  67. }
  68. else
  69. {
  70. CrossPlatformHelper.Instance.LogWriter?.WriteLineInfo($"Camera HelperV2 Init, Id is {_mCameraId}");
  71. }
  72. var cameraCharacteristics = _cameraManager.GetCameraCharacteristics(_mCameraId);
  73. var isFacing = cameraCharacteristics.Get(CameraCharacteristics.LensFacing);
  74. if (isFacing != null && isFacing == Integer.ValueOf((int)LensFacing.Back))
  75. {
  76. _isFront = false;
  77. }
  78. else
  79. {
  80. _isFront = true;
  81. }
  82. _cameraStateCallBack = new CameraStateCallBack();
  83. _cameraStateCallBack.CameraDeviceChanged += OnCameraDeviceChanged;
  84. _cameraCaptureSessionCallback = new CameraCaptureSessionCallback();
  85. _cameraCaptureSessionCallback.SessionConfigured += OnConfigured;
  86. StartBackgroundThread();
  87. _cameraReader = new CameraReaderHelperV2(_mBackgroundHandler, _fps);
  88. _cameraReader.ImageFrameReceived += OnImageFrameReceived;
  89. _cameraReader.InitImageReader(_cameraWidth, _cameraHeight);
  90. SetupCamera();
  91. }
  92. catch (Exception ex)
  93. {
  94. _mCameraOpenCloseLock.Release();
  95. CrossPlatformHelper.Instance.LogWriter?.WriteLineError($"Camera Helper Init Error : {ex}");
  96. }
  97. }
  98. ~CameraHelperV2()
  99. {
  100. if (_cameraReader != null)
  101. {
  102. _cameraReader.ImageFrameReceived -= ImageFrameReceived;
  103. _cameraReader.Close();
  104. }
  105. if (_cameraStateCallBack != null)
  106. {
  107. _cameraStateCallBack.CameraDeviceChanged -= OnCameraDeviceChanged;
  108. }
  109. if (_cameraCaptureSessionCallback != null)
  110. {
  111. _cameraCaptureSessionCallback.SessionConfigured -= OnConfigured;
  112. }
  113. }
  114. private void OnImageFrameReceived(object sender, ImageFrameData e)
  115. {
  116. ImageFrameReceived?.Invoke(this, e);
  117. }
  118. private void OnConfigured(object sender, CameraCaptureSession session)
  119. {
  120. try
  121. {
  122. //创建捕获请求
  123. _mCaptureRequest = _mCaptureRequestBuilder.Build();
  124. _mCameraCaptureSession = session;
  125. //设置反复捕获数据的请求,这样预览界面就会一直有数据显示
  126. _mCameraCaptureSession.SetRepeatingRequest(_mCaptureRequest, null, _mBackgroundHandler);
  127. }
  128. catch (Exception exception)
  129. {
  130. CrossPlatformHelper.Instance.LogWriter?.WriteLineError($"OnConfigured error:{exception}");
  131. }
  132. }
  133. private void StartBackgroundThread()
  134. {
  135. _mBackgroundThread = new HandlerThread("CameraBackground");
  136. _mBackgroundThread.Start();
  137. _mBackgroundHandler = new Handler(_mBackgroundThread.Looper);
  138. }
  139. private void StopBackgroundThread()
  140. {
  141. try
  142. {
  143. if (_mBackgroundThread != null)
  144. {
  145. _mBackgroundThread.QuitSafely();
  146. _mBackgroundThread.Join();
  147. _mBackgroundThread = null;
  148. }
  149. _mBackgroundHandler = null;
  150. }
  151. catch (InterruptedException e)
  152. {
  153. CrossPlatformHelper.Instance.LogWriter?.WriteLineError($"Stop Background thread error:{e}");
  154. }
  155. }
  156. private void OnCameraDeviceChanged(object sender, CameraDevice cameraDevice)
  157. {
  158. _mCameraOpenCloseLock.Release();
  159. _mCameraDevice = cameraDevice;
  160. if (cameraDevice != null)
  161. {
  162. StartPreview();
  163. }
  164. }
  165. private void StartPreview()
  166. {
  167. try
  168. {
  169. ////创建CaptureRequestBuilder,TEMPLATE_PREVIEW比表示预览请求
  170. _mCaptureRequestBuilder = _mCameraDevice.CreateCaptureRequest(CameraTemplate.Preview);
  171. ////设置Surface作为预览数据的显示界面
  172. var surface = _cameraReader.GetInputSurface();
  173. _mCaptureRequestBuilder.AddTarget(surface);
  174. // Here, we create a CameraCaptureSession for camera preview.
  175. List<Surface> surfaces = new List<Surface>
  176. {
  177. surface
  178. };
  179. /*创建相机捕获会话,
  180. 第一个参数是捕获数据的输出Surface列表,
  181. 第二个参数是CameraCaptureSession的状态回调接口,当它创建好后会回调onConfigured方法,
  182. 第三个参数用来确定Callback在哪个线程执行,为null的话就在当前线程执行*/
  183. _mCameraDevice.CreateCaptureSession(surfaces, _cameraCaptureSessionCallback, _mBackgroundHandler);
  184. }
  185. catch (Exception e)
  186. {
  187. CrossPlatformHelper.Instance.LogWriter?.WriteLineError($"StartPreview error:{e}");
  188. }
  189. }
  190. private void OpenCamera()
  191. {
  192. try
  193. {
  194. if (_packageManager.CheckPermission(Manifest.Permission.Camera, _mContext.PackageName) != Permission.Granted)
  195. {
  196. CrossPlatformHelper.Instance.LogWriter?.WriteLineError($"Open Camera Error:The Camera Permission Denied.");
  197. return;
  198. }
  199. if (!_mCameraOpenCloseLock.TryAcquire(2500, TimeUnit.Milliseconds))
  200. {
  201. throw new RuntimeException("Time out waiting to lock camera opening.");
  202. }
  203. _cameraManager.OpenCamera(_mCameraId, _cameraStateCallBack, _mBackgroundHandler);
  204. }
  205. catch (CameraAccessException e)
  206. {
  207. _mCameraOpenCloseLock.Release();
  208. CrossPlatformHelper.Instance.LogWriter?.WriteLineError($"Open Camera Error:{e}");
  209. }
  210. }
  211. private void CloseCamera()
  212. {
  213. try
  214. {
  215. _mCameraOpenCloseLock.Acquire();
  216. if (_mCameraCaptureSession != null)
  217. {
  218. _mCameraCaptureSession.Close();
  219. _mCameraCaptureSession = null;
  220. }
  221. if (_mCameraDevice != null)
  222. {
  223. _mCameraDevice.Close();
  224. _mCameraDevice = null;
  225. }
  226. }
  227. catch (Exception e)
  228. {
  229. CrossPlatformHelper.Instance.LogWriter?.WriteLineError($"Close Camera Error:{e}");
  230. }
  231. finally
  232. {
  233. _mCameraOpenCloseLock.Release();
  234. }
  235. }
  236. private Size GetOptimalSize(Size[] sizeMap, int width, int height)
  237. {
  238. List<Size> sizeList = new List<Size>();
  239. foreach (Size option in sizeMap)
  240. {
  241. if (width > height)
  242. {
  243. if (option.Width > width && option.Height > height)
  244. {
  245. sizeList.Add(option);
  246. }
  247. }
  248. else
  249. {
  250. if (option.Width > height && option.Height > width)
  251. {
  252. sizeList.Add(option);
  253. }
  254. }
  255. }
  256. if (sizeList.Count > 0)
  257. {
  258. return (Size)Collections.Min(sizeList, new CompareSizesByArea());
  259. }
  260. return sizeMap[0];
  261. }
  262. private void SetupCamera()
  263. {
  264. try
  265. {
  266. OpenCamera();
  267. }
  268. catch (Exception e)
  269. {
  270. _mCameraOpenCloseLock.Release();
  271. CrossPlatformHelper.Instance.LogWriter?.WriteLineError($"SetupCamera error:{e}");
  272. }
  273. }
  274. public void SwitchCamera()
  275. {
  276. _mCameraId = _mCameraId.Equals("0") ? "1" : "0";
  277. CloseCamera();
  278. OpenCamera();
  279. }
  280. public void Stop()
  281. {
  282. CloseCamera();
  283. StopBackgroundThread();
  284. }
  285. }
  286. }