UVCInterface_Android.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. using UnityEngine;
  2. using System;
  3. using System.Collections;
  4. using System.Runtime.InteropServices;
  5. using SLAMUVC;
  6. using UnityEngine.UI;
  7. using System.Collections.Generic;
  8. using AOT;
  9. using System.Threading;
  10. using UnityEngine.Events;
  11. using UnityEngine.Android;
  12. namespace SLAMUVC
  13. {
  14. //UVC������
  15. public class UVCInterface_Android : UVCInterface
  16. {
  17. private const string UVC_MANAGER = "com.slambb.myuvc.MyUVCManager";
  18. //java����
  19. private AndroidJavaObject uvcManagerObj = null;
  20. CameraFormat mCameraFormat = CameraFormat.MJPEG;
  21. CameraMirror mCameraMirror = CameraMirror.VERTICAL;//Ĭ�ϴ�ֱ
  22. int Width = 1280;
  23. int Height = 720;
  24. Texture2D _cameraTexture;
  25. public override Texture2D CameraTexture => _cameraTexture;
  26. private UVCCtrl[] uvcCtrls;
  27. public override UVCCtrl[] UVCCtrls => uvcCtrls;
  28. //修改时候的分辨率
  29. int[] tempSize = new int[2] { 1280, 720 };
  30. public override int[] tempCameraSize => tempSize;
  31. private SynchronizationContext mainContext;
  32. ///// <summary>
  33. ///// ��ʼ�����Ȩ�޳ɹ�
  34. ///// </summary>
  35. //public CameraPermissionHandle systemCameraPermissionHandle;
  36. //public void CameraPermissionHandle();
  37. ///// <summary>
  38. ///// ��������¼�
  39. ///// </summary>
  40. //public CameraTextureHandle cameraTextureHandle;
  41. //public void CameraTextureHandle();
  42. private static readonly string ActivityClassName = "com.slambb.myuvc.UsbPermissionActivity";
  43. //public void RequestUsbPermission()
  44. //{
  45. // using (AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
  46. // {
  47. // AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
  48. // AndroidJavaClass usbPermissionActivity = new AndroidJavaClass(ActivityClassName);
  49. // // Start UsbPermissionActivity
  50. // activity.Call("startActivity", usbPermissionActivity.CallStatic<AndroidJavaObject>("newIntent", activity));
  51. // }
  52. //}
  53. void Awake()
  54. {
  55. try
  56. {
  57. // ���� uvcManagerObj ����
  58. uvcManagerObj = new AndroidJavaObject(UVC_MANAGER);
  59. }
  60. catch (Exception e)
  61. {
  62. Debug.LogError("UVC_MANAGER Exception: " + e.Message);
  63. }
  64. //RequestUsbPermission();
  65. }
  66. void Start()
  67. {
  68. OpenCameraPermisson();
  69. }
  70. private void OnDestroy()
  71. {
  72. Remove(this);
  73. uvcManagerObj.Call("clearCameraHelper");
  74. }
  75. /// <summary>
  76. /// ����һ������id�����
  77. /// </summary>
  78. private void CreateTextureAndPassToPlugin()
  79. {
  80. // ��������
  81. if (_cameraTexture != null)
  82. {
  83. Destroy(_cameraTexture);
  84. _cameraTexture = null;
  85. }
  86. // Create a texture
  87. Texture2D tex = new Texture2D(Width, Height, TextureFormat.ARGB32, false);
  88. // ���õ���ˣ��Ա����ǿ�������ؿ�������
  89. tex.filterMode = FilterMode.Point;
  90. // ����Apply()��ʹ��ʵ���ϴ���GPU
  91. tex.Apply();
  92. _cameraTexture = tex;
  93. //������ָ�봫�ݸ����
  94. SetTexture(tex.GetNativeTexturePtr(), tex.width, tex.height);
  95. //cameraTextureHandle?.Invoke();
  96. OnCameraTextureUpdated();
  97. }
  98. //private IEnumerator CallPluginAtEndOfFrames()
  99. //{
  100. // while (true)
  101. // {
  102. // //�ȴ�����֡��Ⱦ���
  103. // yield return new WaitForEndOfFrame();
  104. // //������������������ʶ���IJ���¼���
  105. // //�ò���������ֲ�ͬ��
  106. // //����Ҫ�������ID�������顣
  107. // //�������ǵļ򵥲�������������ﴫ���ĸ�ID������Ҫ��
  108. // if(GetIsPreviewing()) GL.IssuePluginEvent(GetRenderEventFunc(), 1);
  109. // }
  110. //}
  111. /// <summary>
  112. /// ��������
  113. /// </summary>
  114. /// <param name="width"></param>
  115. /// <param name="height"></param>
  116. /// <param name="bUpdate"></param>
  117. public override void OnTextureUpdate(int width, int height, bool bUpdate)
  118. {
  119. mainContext.Post(__ =>
  120. {
  121. if (bUpdate)
  122. {
  123. Debug.Log("�����������size=[" + width + "," + height + "]");
  124. Width = width;
  125. Height = height;
  126. CreateTextureAndPassToPlugin();
  127. }
  128. else
  129. {
  130. GL.IssuePluginEvent(GetRenderEventFunc(), 1);
  131. }
  132. }, null);
  133. }
  134. public override bool GetIsPreviewing()
  135. {
  136. if (uvcManagerObj != null)
  137. {
  138. if (uvcManagerObj.Call<int>("GetIsPreviewing") == 1)
  139. {
  140. return true;
  141. }
  142. }
  143. return false;
  144. }
  145. /// <summary>
  146. /// ��ʼ������Ͷ�Ӧ�IJ�������ʼ������Զ������
  147. /// </summary>
  148. /// <param name="width"></param>
  149. /// <param name="height"></param>
  150. public override void InitCamera(int width, int height)
  151. {
  152. Width = width;
  153. Height = height;
  154. uvcManagerObj.Call("initCameraHelper", Width, Height, mCameraFormat.ToString(), mCameraMirror.ToString());
  155. //���߳�
  156. mainContext = SynchronizationContext.Current;
  157. //ע��c�ص�
  158. Add(this);
  159. //mainContext.Post(__ =>
  160. //{
  161. // //CreateTextureAndPassToPlugin();
  162. //}, null);
  163. //StartCoroutine("CallPluginAtEndOfFrames");
  164. }
  165. public override void OpenCamera()
  166. {
  167. uvcManagerObj.Call("OpenCamera");
  168. }
  169. public override void CloseCamera()
  170. {
  171. uvcManagerObj.Call("CloseCamera");
  172. }
  173. public override void ChangeCameraInfo(int width, int height)
  174. {
  175. uvcManagerObj.Call("ChangeCameraInfo", width, height, mCameraFormat.ToString());
  176. }
  177. public override string[] GetSupportedResolutions()
  178. {
  179. if (uvcManagerObj != null)
  180. {
  181. var objPtr = uvcManagerObj.Call<AndroidJavaObject>("GetSupportedResolutions").GetRawObject();
  182. if (objPtr != IntPtr.Zero)
  183. return AndroidJNIHelper.ConvertFromJNIArray<string[]>(objPtr);
  184. }
  185. return null;
  186. }
  187. /// <summary>
  188. /// ˮƽ��ת
  189. /// </summary>
  190. public override void FlipHorizontally()
  191. {
  192. uvcManagerObj.Call("FlipHorizontally");
  193. }
  194. /// <summary>
  195. /// ��ֱ��ת
  196. /// </summary>
  197. public override void FlipVertically()
  198. {
  199. uvcManagerObj.Call("FlipVertically");
  200. }
  201. public override void resetControlParams()
  202. {
  203. uvcManagerObj.Call("resetControlParams");
  204. }
  205. public override string GetUvcCtrlList()
  206. {
  207. if (uvcManagerObj != null)
  208. {
  209. string json = uvcManagerObj.Call<string>("GetUvcCtrlList");
  210. UVCCtrlWrapper wrapper = JsonUtility.FromJson<UVCCtrlWrapper>("{\"uvcCtrls\":" + json + "}");
  211. if (wrapper != null && wrapper.uvcCtrls != null)
  212. {
  213. //��ֵ
  214. uvcCtrls = wrapper.uvcCtrls;
  215. //foreach (UVCCtrl ctrl in wrapper.uvcCtrls)
  216. //{
  217. // Debug.Log($"name:{ctrl.name}, isAuto: {ctrl.isAuto}, isEnable: {ctrl.isEnable}, limit: {string.Join(", ", ctrl.limit)}, value: {ctrl.value}");
  218. //}
  219. }
  220. else
  221. {
  222. Debug.LogError("Failed to parse JSON data.");
  223. }
  224. }
  225. return "";
  226. }
  227. public override void SetBrightness(int value)
  228. {
  229. uvcManagerObj.Call("SetBrightness", value);
  230. }
  231. public override void SetContrast(int value)
  232. {
  233. uvcManagerObj.Call("SetContrast", value);
  234. }
  235. public override int SetCtrlValue(string type, Int32 value)
  236. {
  237. int result = -1;
  238. if (type == "PU_BRIGHTNESS")
  239. {
  240. uvcManagerObj.Call("SetBrightness", value);
  241. result = 0;
  242. }
  243. else if (type == "PU_CONTRAST")
  244. {
  245. uvcManagerObj.Call("SetContrast", value);
  246. result = 0;
  247. }
  248. return result;
  249. }
  250. //--------------------------------------------------------------------------------
  251. /**
  252. * �ȴ������Ȩ��
  253. */
  254. private void OpenCameraPermisson()
  255. {
  256. if (Permission.HasUserAuthorizedPermission(Permission.Camera))
  257. {
  258. Debug.LogError("HasUserAuthorizedPermission��");
  259. //systemCameraPermissionHandle?.Invoke();
  260. OnCameraPermissionGranted();
  261. return;
  262. }
  263. bool useCallbacks = true;
  264. if (!useCallbacks)
  265. {
  266. // We do not have permission to use the microphone.
  267. // Ask for permission or proceed without the functionality enabled.
  268. Permission.RequestUserPermission(Permission.Camera);
  269. }
  270. else
  271. {
  272. var callbacks = new PermissionCallbacks();
  273. callbacks.PermissionDenied += PermissionCallbacks_PermissionDenied;
  274. callbacks.PermissionGranted += PermissionCallbacks_PermissionGranted;
  275. callbacks.PermissionDeniedAndDontAskAgain += PermissionCallbacks_PermissionDeniedAndDontAskAgain;
  276. Permission.RequestUserPermission(Permission.Camera, callbacks);
  277. }
  278. }
  279. void PermissionCallbacks_PermissionDenied(string PermissionName)
  280. {
  281. Debug.LogError($"PermissionCallbacks_PermissionDenied[{PermissionName}]");
  282. }
  283. //��������
  284. void PermissionCallbacks_PermissionGranted(string PermissionName)
  285. {
  286. Debug.Log($"PermissionCallbacks_PermissionGranted[{PermissionName}]");
  287. //systemCameraPermissionHandle?.Invoke();
  288. OnCameraPermissionGranted();
  289. }
  290. void PermissionCallbacks_PermissionDeniedAndDontAskAgain(string PermissionName)
  291. {
  292. Debug.Log($"PermissionCallbacks_PermissionDeniedAndDontAskAgain[{PermissionName}]");
  293. //systemCameraPermissionHandle?.Invoke();
  294. OnCameraPermissionGranted();
  295. }
  296. //����GL����
  297. [DllImport("TransferTexture")]
  298. private static extern void SetTexture(IntPtr texture, int w, int h);
  299. //GL��Ⱦ�¼�
  300. [DllImport("TransferTexture")]
  301. private static extern IntPtr GetRenderEventFunc();
  302. [UnmanagedFunctionPointer(CallingConvention.StdCall)]
  303. public delegate void TextureUpdateDelegate(Int32 id, int width, int height, bool bUpdate);
  304. [DllImport("TransferTexture")]
  305. private static extern void RegisterTextureUpdateCallback(Int32 id, TextureUpdateDelegate callback);
  306. [DllImport("TransferTexture")]
  307. private static extern void UnregisterTextureUpdateCallback(Int32 id, TextureUpdateDelegate callback);
  308. //��¼MyUVCInterface
  309. private static Dictionary<Int32, UVCInterface> mUVCInterfaces = new Dictionary<Int32, UVCInterface>();
  310. private static TextureUpdateDelegate textureUpdateDelegate;
  311. //ע��ص��¼�
  312. public static void Add(UVCInterface myUVCInterface)
  313. {
  314. Int32 id = myUVCInterface.GetHashCode();
  315. textureUpdateDelegate = new TextureUpdateDelegate(TextureUpdateHandler);
  316. mUVCInterfaces.Add(id, myUVCInterface);
  317. RegisterTextureUpdateCallback(id, textureUpdateDelegate);
  318. }
  319. //�Ƴ��ص��¼�
  320. public static void Remove(UVCInterface myUVCInterface)
  321. {
  322. Int32 id = myUVCInterface.GetHashCode();
  323. UnregisterTextureUpdateCallback(id, textureUpdateDelegate);
  324. mUVCInterfaces.Remove(id);
  325. }
  326. //���ݸ���ʱ��ص�
  327. [MonoPInvokeCallback(typeof(TextureUpdateDelegate))]
  328. private static void TextureUpdateHandler(Int32 id, int width, int height, bool bUpdate)
  329. {
  330. var myUVCInterface = mUVCInterfaces.ContainsKey(id) ? mUVCInterfaces[id] : null;
  331. if (myUVCInterface != null)
  332. {
  333. myUVCInterface.OnTextureUpdate(width, height, bUpdate);
  334. }
  335. }
  336. public override void ChangeCameraInfoCallback(int width, int height)
  337. {
  338. throw new NotImplementedException();
  339. }
  340. }
  341. }