The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

3294 lines
146KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. //==============================================================================
  19. // This byte-code is generated from:
  20. //
  21. // native/java/com/rmsl/juce/CameraCaptureSessionCaptureCallback.java
  22. // native/java/com/rmsl/juce/CameraCaptureSessionStateCallback.java
  23. // native/java/com/rmsl/juce/CameraDeviceStateCallback.java
  24. // native/java/com/rmsl/juce/JuceOrientationEventListener.java
  25. //
  26. // files with min sdk version 21
  27. // See juce_core/native/java/README.txt on how to generate this byte-code.
  28. static const uint8 CameraSupportByteCode[] =
  29. {31,139,8,8,187,110,161,94,0,3,67,97,109,101,114,97,83,117,112,112,111,114,116,66,121,116,101,67,111,100,101,46,100,101,120,0,
  30. 149,152,93,108,28,213,21,199,207,157,157,221,89,239,174,215,227,181,243,217,36,56,95,182,3,113,54,137,227,40,101,29,59,198,113,
  31. 192,102,133,169,215,182,34,3,45,147,221,73,188,176,222,89,102,215,139,171,86,37,68,84,208,151,42,80,90,168,4,136,170,20,181,15,
  32. 84,110,9,132,7,30,82,21,149,240,0,10,136,190,165,18,84,133,7,154,7,132,42,20,85,60,244,127,63,198,158,93,175,93,99,233,183,
  33. 255,51,115,206,61,247,222,115,239,140,103,38,103,47,68,14,246,246,209,213,103,22,174,255,247,133,96,249,25,246,233,195,151,255,
  34. 18,189,241,193,31,255,57,248,226,196,252,238,238,4,81,137,136,22,166,143,192,146,127,79,181,18,157,38,121,190,13,92,99,68,91,
  35. 160,219,52,162,32,244,174,0,81,55,247,67,117,232,34,126,110,198,136,14,194,249,86,152,232,10,248,2,36,154,136,14,131,62,112,12,
  36. 220,7,170,224,50,248,26,116,69,136,190,15,158,4,127,6,255,0,70,148,232,40,248,1,120,22,188,11,190,2,29,200,191,27,116,129,219,
  37. 120,95,160,15,164,192,9,112,39,24,7,167,193,131,32,7,242,192,1,85,240,99,240,24,120,18,252,22,188,7,110,128,182,102,162,65,48,7,
  38. 158,6,175,129,143,192,87,160,57,78,212,9,70,192,3,160,10,30,3,191,6,47,131,63,128,55,193,219,224,93,240,33,248,12,124,13,162,
  39. 45,68,123,193,16,200,128,7,64,9,252,4,252,28,60,7,126,3,46,131,43,224,125,112,29,124,6,254,13,254,3,190,1,97,147,168,21,236,2,
  40. 221,166,172,55,95,3,3,160,196,132,50,18,202,70,40,17,97,58,132,97,19,186,39,52,37,132,19,150,146,18,106,29,219,193,6,176,17,
  41. 116,42,109,85,107,190,73,217,139,72,188,89,217,111,25,114,221,185,125,5,246,119,148,125,21,246,86,101,127,236,179,175,251,98,
  42. 254,5,123,155,178,191,132,189,93,217,55,97,239,80,182,142,9,220,162,236,118,216,29,202,222,227,179,143,248,236,147,176,119,41,
  43. 123,18,246,78,101,223,239,59,159,131,189,91,217,5,216,123,148,189,0,123,175,178,159,240,217,23,125,246,11,190,156,191,247,229,
  44. 92,12,243,186,50,234,23,245,77,208,184,168,177,60,110,81,106,42,13,168,122,234,74,67,74,99,98,69,120,251,176,210,56,237,19,26,
  45. 163,91,133,54,211,109,66,155,104,191,208,8,245,8,141,210,1,161,27,105,80,104,59,157,16,186,129,134,132,182,210,29,106,92,195,66,
  46. 219,232,164,24,159,38,250,137,99,183,116,43,77,42,61,168,244,144,210,195,66,77,26,80,58,162,244,148,210,59,149,166,197,124,
  47. 101,222,22,204,172,87,233,17,161,6,245,169,227,163,66,55,137,60,92,239,18,186,153,70,213,241,152,168,151,172,144,137,138,29,83,
  48. 245,187,155,228,254,101,190,58,50,165,31,155,164,230,35,207,121,245,213,148,38,212,70,110,81,126,175,238,94,158,83,202,111,
  49. 42,127,172,110,125,92,229,15,34,51,247,247,154,242,250,42,153,60,126,6,151,208,253,237,12,189,199,224,231,215,222,113,83,230,
  50. 200,92,32,154,122,130,145,241,184,241,75,227,85,227,114,213,8,146,63,238,212,170,113,161,154,184,241,85,227,12,17,23,193,76,248,
  51. 88,79,155,242,90,207,184,136,171,32,238,17,227,167,236,87,213,80,88,68,201,245,228,227,126,208,203,247,52,226,126,129,184,139,
  52. 198,43,236,13,253,111,213,112,147,136,74,160,87,126,223,200,155,178,166,153,63,33,238,117,196,45,26,239,24,127,215,63,15,226,
  53. 198,83,141,68,68,172,142,190,121,77,202,166,172,87,201,100,162,38,154,240,105,98,45,126,164,124,153,14,141,74,39,18,164,29,90,
  54. 246,93,168,241,181,213,248,126,86,227,107,175,241,93,172,241,109,168,241,61,87,227,219,168,124,114,156,47,45,141,83,19,227,12,
  55. 248,198,249,234,82,187,0,218,109,175,201,249,90,141,111,135,240,5,145,147,223,111,47,249,125,147,183,212,180,123,187,166,93,
  56. 135,240,133,68,75,162,191,122,99,57,24,160,161,224,76,66,247,141,229,253,165,118,58,218,117,138,118,222,126,103,10,205,119,61,
  57. 48,181,219,229,185,160,82,67,249,12,159,47,33,242,115,13,146,252,127,225,217,222,181,33,143,155,136,137,76,203,199,225,154,248,
  58. 38,177,71,252,199,81,213,135,55,174,160,178,131,106,140,94,31,242,255,148,204,31,80,118,120,41,70,230,245,236,168,106,99,168,
  59. 92,92,67,253,249,98,190,50,64,221,195,214,156,237,90,195,86,169,50,239,218,25,187,92,206,59,69,117,52,108,21,10,103,172,236,195,
  60. 7,30,178,170,22,117,54,138,204,84,172,74,93,220,14,25,119,210,174,230,179,118,3,63,27,37,54,70,59,199,230,179,246,184,155,
  61. 183,139,136,64,162,145,42,172,116,190,92,177,139,182,43,3,183,164,173,98,206,117,242,185,100,214,41,226,124,37,57,204,117,161,
  62. 146,162,193,37,215,172,229,230,30,181,92,59,153,21,189,30,78,54,26,229,158,186,9,165,232,248,183,76,80,51,143,20,37,191,93,243,
  63. 20,245,253,191,6,178,92,245,253,116,173,175,89,138,246,173,21,40,134,114,202,202,23,32,235,9,157,176,31,153,183,203,40,115,247,
  64. 58,66,203,243,5,68,246,172,30,57,233,84,172,66,93,248,242,188,170,121,251,209,228,106,251,32,69,189,233,172,51,151,116,231,
  65. 202,133,228,67,216,48,13,171,187,98,113,15,173,163,81,93,161,247,53,108,210,96,15,167,104,127,93,232,90,27,57,69,108,154,180,
  66. 233,81,48,70,129,233,177,81,254,147,38,29,63,194,156,161,32,126,96,135,132,140,145,193,53,61,54,38,79,164,211,104,152,70,32,34,
  67. 244,105,238,15,78,11,47,14,224,99,51,20,146,85,166,173,217,6,115,28,202,86,242,85,155,246,52,242,121,69,115,230,74,5,187,98,231,
  68. 104,231,26,81,124,239,32,100,239,26,33,247,186,206,57,23,103,16,118,235,26,97,25,190,181,138,89,123,232,140,227,242,94,247,
  69. 175,35,118,121,140,187,214,138,174,88,34,99,195,74,12,23,28,62,178,221,13,125,78,241,108,254,220,242,44,119,172,25,148,163,45,
  70. 141,252,19,182,149,251,33,109,202,174,216,54,178,227,237,43,28,39,243,101,220,213,138,118,150,143,121,227,10,247,136,235,58,
  71. 110,131,124,227,37,108,171,28,25,89,121,39,164,205,57,225,243,237,191,225,89,171,120,14,33,65,91,164,48,206,202,235,158,162,103,
  72. 93,36,187,103,126,238,140,237,146,62,235,148,43,212,196,127,39,157,169,178,77,225,165,221,146,104,176,55,90,234,119,66,91,
  73. 163,117,223,188,234,42,111,93,99,77,205,21,43,24,94,90,175,214,149,171,19,171,89,139,184,83,172,41,164,129,235,79,76,27,57,84,
  74. 169,218,97,173,172,142,225,45,89,212,89,118,82,115,9,35,200,91,5,121,155,34,163,228,218,252,254,68,186,139,210,147,225,202,251,
  75. 34,133,92,233,143,148,213,108,70,145,176,44,55,2,181,148,103,157,249,66,238,14,84,70,53,174,204,230,203,212,84,201,207,161,173,
  76. 53,87,162,30,109,96,218,136,247,247,244,208,209,192,212,68,198,136,95,162,126,24,41,110,12,195,24,231,198,168,54,53,105,196,
  77. 127,71,227,129,169,201,126,126,98,90,159,154,56,13,235,35,218,207,6,120,115,234,101,83,70,124,134,190,43,101,80,202,136,148,187,
  78. 165,116,169,208,3,172,155,31,30,145,114,187,214,125,59,215,19,242,176,51,48,112,236,123,70,252,56,15,187,135,159,32,13,15,
  79. 207,26,211,244,243,231,245,197,8,187,128,167,188,6,68,217,181,8,99,55,193,203,81,198,174,130,47,193,243,49,98,161,160,166,181,
  80. 162,237,59,177,70,237,54,177,79,98,140,125,3,158,111,102,236,18,184,134,151,191,160,30,208,182,161,205,141,230,250,248,157,236,
  81. 169,56,99,175,128,43,224,58,30,225,52,166,107,123,31,63,175,223,140,115,127,23,123,182,69,190,215,120,207,117,158,122,223,88,
  82. 248,51,143,247,157,133,63,19,121,223,90,188,119,125,254,189,133,171,247,205,37,68,203,223,93,88,135,124,175,231,223,94,152,41,
  83. 223,221,249,59,188,214,33,243,243,239,49,1,21,195,223,105,248,203,52,111,43,222,167,76,57,14,254,189,231,127,249,28,121,55,40,18,
  84. 0,0,0,0};
  85. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  86. STATICMETHOD (valueOf, "valueOf", "(Ljava/lang/String;)Landroid/graphics/Bitmap$CompressFormat;")
  87. DECLARE_JNI_CLASS_WITH_MIN_SDK (AndroidBitmapCompressFormat, "android/graphics/Bitmap$CompressFormat", 21)
  88. #undef JNI_CLASS_MEMBERS
  89. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  90. METHOD (close, "close", "()V") \
  91. METHOD (createCaptureRequest, "createCaptureRequest", "(I)Landroid/hardware/camera2/CaptureRequest$Builder;") \
  92. METHOD (createCaptureSession, "createCaptureSession", "(Ljava/util/List;Landroid/hardware/camera2/CameraCaptureSession$StateCallback;Landroid/os/Handler;)V")
  93. DECLARE_JNI_CLASS_WITH_MIN_SDK (AndroidCameraDevice, "android/hardware/camera2/CameraDevice", 21)
  94. #undef JNI_CLASS_MEMBERS
  95. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  96. METHOD (close, "close", "()V") \
  97. METHOD (getPlanes, "getPlanes", "()[Landroid/media/Image$Plane;")
  98. DECLARE_JNI_CLASS_WITH_MIN_SDK (AndroidImage, "android/media/Image", 21)
  99. #undef JNI_CLASS_MEMBERS
  100. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  101. METHOD (getBuffer, "getBuffer", "()Ljava/nio/ByteBuffer;")
  102. DECLARE_JNI_CLASS_WITH_MIN_SDK (AndroidImagePlane, "android/media/Image$Plane", 21)
  103. #undef JNI_CLASS_MEMBERS
  104. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  105. METHOD (acquireLatestImage, "acquireLatestImage", "()Landroid/media/Image;") \
  106. METHOD (close, "close", "()V") \
  107. METHOD (getSurface, "getSurface", "()Landroid/view/Surface;") \
  108. METHOD (setOnImageAvailableListener, "setOnImageAvailableListener", "(Landroid/media/ImageReader$OnImageAvailableListener;Landroid/os/Handler;)V") \
  109. STATICMETHOD (newInstance, "newInstance", "(IIII)Landroid/media/ImageReader;")
  110. DECLARE_JNI_CLASS_WITH_MIN_SDK (AndroidImageReader, "android/media/ImageReader", 21)
  111. #undef JNI_CLASS_MEMBERS
  112. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  113. METHOD (constructor, "<init>", "()V") \
  114. METHOD (getSurface, "getSurface", "()Landroid/view/Surface;") \
  115. METHOD (prepare, "prepare", "()V") \
  116. METHOD (release, "release", "()V") \
  117. METHOD (setAudioEncoder, "setAudioEncoder", "(I)V") \
  118. METHOD (setAudioSource, "setAudioSource", "(I)V") \
  119. METHOD (setOnErrorListener, "setOnErrorListener", "(Landroid/media/MediaRecorder$OnErrorListener;)V") \
  120. METHOD (setOnInfoListener, "setOnInfoListener", "(Landroid/media/MediaRecorder$OnInfoListener;)V") \
  121. METHOD (setOrientationHint, "setOrientationHint", "(I)V") \
  122. METHOD (setOutputFile, "setOutputFile", "(Ljava/lang/String;)V") \
  123. METHOD (setOutputFormat, "setOutputFormat", "(I)V") \
  124. METHOD (setVideoEncoder, "setVideoEncoder", "(I)V") \
  125. METHOD (setVideoEncodingBitRate, "setVideoEncodingBitRate", "(I)V") \
  126. METHOD (setVideoFrameRate, "setVideoFrameRate", "(I)V") \
  127. METHOD (setVideoSize, "setVideoSize", "(II)V") \
  128. METHOD (setVideoSource, "setVideoSource", "(I)V") \
  129. METHOD (start, "start", "()V") \
  130. METHOD (stop, "stop", "()V")
  131. DECLARE_JNI_CLASS_WITH_MIN_SDK (AndroidMediaRecorder, "android/media/MediaRecorder", 21)
  132. #undef JNI_CLASS_MEMBERS
  133. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  134. METHOD (constructor, "<init>", "(Landroid/content/Context;)V") \
  135. METHOD (getSurfaceTexture, "getSurfaceTexture", "()Landroid/graphics/SurfaceTexture;") \
  136. METHOD (isAvailable, "isAvailable", "()Z") \
  137. METHOD (setSurfaceTextureListener, "setSurfaceTextureListener", "(Landroid/view/TextureView$SurfaceTextureListener;)V") \
  138. METHOD (setTransform, "setTransform", "(Landroid/graphics/Matrix;)V")
  139. DECLARE_JNI_CLASS_WITH_MIN_SDK (AndroidTextureView, "android/view/TextureView", 21)
  140. #undef JNI_CLASS_MEMBERS
  141. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  142. METHOD (constructor, "<init>", "(Landroid/graphics/SurfaceTexture;)V")
  143. DECLARE_JNI_CLASS_WITH_MIN_SDK (AndroidSurface, "android/view/Surface", 21)
  144. #undef JNI_CLASS_MEMBERS
  145. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  146. METHOD (setDefaultBufferSize, "setDefaultBufferSize", "(II)V")
  147. DECLARE_JNI_CLASS_WITH_MIN_SDK (AndroidSurfaceTexture, "android/graphics/SurfaceTexture", 21)
  148. #undef JNI_CLASS_MEMBERS
  149. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  150. METHOD (getOutputSizesForClass, "getOutputSizes", "(Ljava/lang/Class;)[Landroid/util/Size;") \
  151. METHOD (getOutputSizesForFormat, "getOutputSizes", "(I)[Landroid/util/Size;") \
  152. METHOD (isOutputSupportedFor, "isOutputSupportedFor", "(I)Z") \
  153. METHOD (isOutputSupportedForSurface, "isOutputSupportedFor", "(Landroid/view/Surface;)Z")
  154. DECLARE_JNI_CLASS_WITH_MIN_SDK (AndroidStreamConfigurationMap, "android/hardware/camera2/params/StreamConfigurationMap", 21)
  155. #undef JNI_CLASS_MEMBERS
  156. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  157. METHOD (constructor, "<init>", "()V") \
  158. METHOD (toByteArray, "toByteArray", "()[B") \
  159. METHOD (size, "size", "()I")
  160. DECLARE_JNI_CLASS_WITH_MIN_SDK (ByteArrayOutputStream, "java/io/ByteArrayOutputStream", 21)
  161. #undef JNI_CLASS_MEMBERS
  162. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  163. METHOD (abortCaptures, "abortCaptures", "()V") \
  164. METHOD (capture, "capture", "(Landroid/hardware/camera2/CaptureRequest;Landroid/hardware/camera2/CameraCaptureSession$CaptureCallback;Landroid/os/Handler;)I") \
  165. METHOD (close, "close", "()V") \
  166. METHOD (setRepeatingRequest, "setRepeatingRequest", "(Landroid/hardware/camera2/CaptureRequest;Landroid/hardware/camera2/CameraCaptureSession$CaptureCallback;Landroid/os/Handler;)I") \
  167. METHOD (stopRepeating, "stopRepeating", "()V")
  168. DECLARE_JNI_CLASS_WITH_MIN_SDK (CameraCaptureSession, "android/hardware/camera2/CameraCaptureSession", 21)
  169. #undef JNI_CLASS_MEMBERS
  170. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  171. METHOD (get, "get", "(Landroid/hardware/camera2/CameraCharacteristics$Key;)Ljava/lang/Object;") \
  172. METHOD (getKeys, "getKeys", "()Ljava/util/List;") \
  173. STATICFIELD (CONTROL_AF_AVAILABLE_MODES, "CONTROL_AF_AVAILABLE_MODES", "Landroid/hardware/camera2/CameraCharacteristics$Key;") \
  174. STATICFIELD (LENS_FACING, "LENS_FACING", "Landroid/hardware/camera2/CameraCharacteristics$Key;") \
  175. STATICFIELD (SCALER_STREAM_CONFIGURATION_MAP, "SCALER_STREAM_CONFIGURATION_MAP", "Landroid/hardware/camera2/CameraCharacteristics$Key;") \
  176. STATICFIELD (SENSOR_ORIENTATION, "SENSOR_ORIENTATION", "Landroid/hardware/camera2/CameraCharacteristics$Key;")
  177. DECLARE_JNI_CLASS_WITH_MIN_SDK (CameraCharacteristics, "android/hardware/camera2/CameraCharacteristics", 21)
  178. #undef JNI_CLASS_MEMBERS
  179. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  180. METHOD (getName, "getName", "()Ljava/lang/String;")
  181. DECLARE_JNI_CLASS_WITH_MIN_SDK (CameraCharacteristicsKey, "android/hardware/camera2/CameraCharacteristics$Key", 21)
  182. #undef JNI_CLASS_MEMBERS
  183. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  184. METHOD (getCameraCharacteristics, "getCameraCharacteristics", "(Ljava/lang/String;)Landroid/hardware/camera2/CameraCharacteristics;") \
  185. METHOD (getCameraIdList, "getCameraIdList", "()[Ljava/lang/String;") \
  186. METHOD (openCamera, "openCamera", "(Ljava/lang/String;Landroid/hardware/camera2/CameraDevice$StateCallback;Landroid/os/Handler;)V")
  187. DECLARE_JNI_CLASS_WITH_MIN_SDK (CameraManager, "android/hardware/camera2/CameraManager", 21)
  188. #undef JNI_CLASS_MEMBERS
  189. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  190. STATICFIELD (CONTROL_AE_PRECAPTURE_TRIGGER, "CONTROL_AE_PRECAPTURE_TRIGGER", "Landroid/hardware/camera2/CaptureRequest$Key;") \
  191. STATICFIELD (CONTROL_AF_MODE, "CONTROL_AF_MODE", "Landroid/hardware/camera2/CaptureRequest$Key;") \
  192. STATICFIELD (CONTROL_AF_TRIGGER, "CONTROL_AF_TRIGGER", "Landroid/hardware/camera2/CaptureRequest$Key;") \
  193. STATICFIELD (CONTROL_MODE, "CONTROL_MODE", "Landroid/hardware/camera2/CaptureRequest$Key;")
  194. DECLARE_JNI_CLASS_WITH_MIN_SDK (CaptureRequest, "android/hardware/camera2/CaptureRequest", 21)
  195. #undef JNI_CLASS_MEMBERS
  196. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  197. METHOD (addTarget, "addTarget", "(Landroid/view/Surface;)V") \
  198. METHOD (build, "build", "()Landroid/hardware/camera2/CaptureRequest;") \
  199. METHOD (set, "set", "(Landroid/hardware/camera2/CaptureRequest$Key;Ljava/lang/Object;)V")
  200. DECLARE_JNI_CLASS_WITH_MIN_SDK (CaptureRequestBuilder, "android/hardware/camera2/CaptureRequest$Builder", 21)
  201. #undef JNI_CLASS_MEMBERS
  202. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  203. METHOD (get, "get", "(Landroid/hardware/camera2/CaptureResult$Key;)Ljava/lang/Object;") \
  204. STATICFIELD (CONTROL_AE_STATE, "CONTROL_AE_STATE", "Landroid/hardware/camera2/CaptureResult$Key;") \
  205. STATICFIELD (CONTROL_AF_STATE, "CONTROL_AF_STATE", "Landroid/hardware/camera2/CaptureResult$Key;")
  206. DECLARE_JNI_CLASS_WITH_MIN_SDK (CaptureResult, "android/hardware/camera2/CaptureResult", 21)
  207. #undef JNI_CLASS_MEMBERS
  208. //==============================================================================
  209. class AndroidRunnable : public juce::AndroidInterfaceImplementer
  210. {
  211. public:
  212. struct Owner
  213. {
  214. virtual ~Owner() {}
  215. virtual void run() = 0;
  216. };
  217. AndroidRunnable (Owner& ownerToUse)
  218. : owner (ownerToUse)
  219. {}
  220. private:
  221. Owner& owner;
  222. jobject invoke (jobject proxy, jobject method, jobjectArray args) override
  223. {
  224. auto* env = getEnv();
  225. auto methodName = juce::juceString ((jstring) env->CallObjectMethod (method, JavaMethod.getName));
  226. if (methodName == "run")
  227. {
  228. owner.run();
  229. return nullptr;
  230. }
  231. // invoke base class
  232. return AndroidInterfaceImplementer::invoke (proxy, method, args);
  233. }
  234. };
  235. //==============================================================================
  236. class TextureViewSurfaceTextureListener : public AndroidInterfaceImplementer
  237. {
  238. public:
  239. struct Owner
  240. {
  241. virtual ~Owner() {}
  242. virtual void onSurfaceTextureAvailable (LocalRef<jobject>& surface, int width, int height) = 0;
  243. virtual bool onSurfaceTextureDestroyed (LocalRef<jobject>& surface) = 0;
  244. virtual void onSurfaceTextureSizeChanged (LocalRef<jobject>& surface, int width, int height) = 0;
  245. virtual void onSurfaceTextureUpdated (LocalRef<jobject>& surface) = 0;
  246. };
  247. TextureViewSurfaceTextureListener (Owner& ownerToUse)
  248. : owner (ownerToUse)
  249. {}
  250. jobject invoke (jobject proxy, jobject method, jobjectArray args) override
  251. {
  252. auto* env = getEnv();
  253. auto methodName = juceString ((jstring) env->CallObjectMethod (method, JavaMethod.getName));
  254. int numArgs = args != nullptr ? env->GetArrayLength (args) : 0;
  255. if (methodName == "onSurfaceTextureAvailable" && numArgs == 3)
  256. {
  257. auto surface = LocalRef<jobject> (env->GetObjectArrayElement (args, 0));
  258. auto width = LocalRef<jobject> (env->GetObjectArrayElement (args, 1));
  259. auto height = LocalRef<jobject> (env->GetObjectArrayElement (args, 2));
  260. auto widthInt = env->CallIntMethod (width, JavaInteger.intValue);
  261. auto heightInt = env->CallIntMethod (height, JavaInteger.intValue);
  262. owner.onSurfaceTextureAvailable (surface, widthInt, heightInt);
  263. return nullptr;
  264. }
  265. else if (methodName == "onSurfaceTextureDestroyed" && numArgs == 1)
  266. {
  267. auto surface = LocalRef<jobject> (env->GetObjectArrayElement (args, 0));
  268. auto result = owner.onSurfaceTextureDestroyed (surface);
  269. return env->CallStaticObjectMethod (JavaBoolean, JavaBoolean.valueOf, result);
  270. }
  271. else if (methodName == "onSurfaceTextureSizeChanged" && numArgs == 3)
  272. {
  273. auto surface = LocalRef<jobject> (env->GetObjectArrayElement (args, 0));
  274. auto width = LocalRef<jobject> (env->GetObjectArrayElement (args, 1));
  275. auto height = LocalRef<jobject> (env->GetObjectArrayElement (args, 2));
  276. auto widthInt = env->CallIntMethod (width, JavaInteger.intValue);
  277. auto heightInt = env->CallIntMethod (height, JavaInteger.intValue);
  278. owner.onSurfaceTextureSizeChanged (surface, widthInt, heightInt);
  279. return nullptr;
  280. }
  281. else if (methodName == "onSurfaceTextureUpdated" && numArgs == 1)
  282. {
  283. auto surface = LocalRef<jobject> (env->GetObjectArrayElement (args, 0));
  284. owner.onSurfaceTextureUpdated (surface);
  285. return nullptr;
  286. }
  287. return AndroidInterfaceImplementer::invoke (proxy, method, args);
  288. }
  289. private:
  290. Owner& owner;
  291. };
  292. //==============================================================================
  293. class ImageReaderOnImageAvailableListener : public AndroidInterfaceImplementer
  294. {
  295. public:
  296. struct Owner
  297. {
  298. virtual ~Owner() {}
  299. virtual void onImageAvailable (LocalRef<jobject>& imageReader) = 0;
  300. };
  301. ImageReaderOnImageAvailableListener (Owner& ownerToUse)
  302. : owner (ownerToUse)
  303. {}
  304. jobject invoke (jobject proxy, jobject method, jobjectArray args) override
  305. {
  306. auto* env = getEnv();
  307. auto methodName = juceString ((jstring) env->CallObjectMethod (method, JavaMethod.getName));
  308. int numArgs = args != nullptr ? env->GetArrayLength (args) : 0;
  309. if (methodName == "onImageAvailable" && numArgs == 1)
  310. {
  311. auto imageReader = LocalRef<jobject> (env->GetObjectArrayElement (args, 0));
  312. owner.onImageAvailable (imageReader);
  313. return nullptr;
  314. }
  315. return AndroidInterfaceImplementer::invoke (proxy, method, args);
  316. }
  317. private:
  318. Owner& owner;
  319. };
  320. //==============================================================================
  321. class MediaRecorderOnInfoListener : public AndroidInterfaceImplementer
  322. {
  323. public:
  324. struct Owner
  325. {
  326. virtual ~Owner() {}
  327. virtual void onInfo (LocalRef<jobject>& mediaRecorder, int what, int extra) = 0;
  328. };
  329. MediaRecorderOnInfoListener (Owner& ownerToUse)
  330. : owner (ownerToUse)
  331. {}
  332. jobject invoke (jobject proxy, jobject method, jobjectArray args) override
  333. {
  334. auto* env = getEnv();
  335. auto methodName = juceString ((jstring) env->CallObjectMethod (method, JavaMethod.getName));
  336. int numArgs = args != nullptr ? env->GetArrayLength (args) : 0;
  337. if (methodName == "onInfo" && numArgs == 3)
  338. {
  339. auto mediaRecorder = LocalRef<jobject> (env->GetObjectArrayElement (args, 0));
  340. auto what = LocalRef<jobject> (env->GetObjectArrayElement (args, 1));
  341. auto extra = LocalRef<jobject> (env->GetObjectArrayElement (args, 2));
  342. auto whatInt = (int) env->CallIntMethod (what, JavaInteger.intValue);
  343. auto extraInt = (int) env->CallIntMethod (extra, JavaInteger.intValue);
  344. owner.onInfo (mediaRecorder, whatInt, extraInt);
  345. return nullptr;
  346. }
  347. return AndroidInterfaceImplementer::invoke (proxy, method, args);
  348. }
  349. private:
  350. Owner& owner;
  351. };
  352. //==============================================================================
  353. class MediaRecorderOnErrorListener : public AndroidInterfaceImplementer
  354. {
  355. public:
  356. struct Owner
  357. {
  358. virtual ~Owner() {}
  359. virtual void onError (LocalRef<jobject>& mediaRecorder, int what, int extra) = 0;
  360. };
  361. MediaRecorderOnErrorListener (Owner& ownerToUse)
  362. : owner (ownerToUse)
  363. {}
  364. jobject invoke (jobject proxy, jobject method, jobjectArray args) override
  365. {
  366. auto* env = getEnv();
  367. auto methodName = juceString ((jstring) env->CallObjectMethod (method, JavaMethod.getName));
  368. int numArgs = args != nullptr ? env->GetArrayLength (args) : 0;
  369. if (methodName == "onError" && numArgs == 3)
  370. {
  371. auto mediaRecorder = LocalRef<jobject> (env->GetObjectArrayElement (args, 0));
  372. auto what = LocalRef<jobject> (env->GetObjectArrayElement (args, 1));
  373. auto extra = LocalRef<jobject> (env->GetObjectArrayElement (args, 2));
  374. auto whatInt = (int) env->CallIntMethod (what, JavaInteger.intValue);
  375. auto extraInt = (int) env->CallIntMethod (extra, JavaInteger.intValue);
  376. owner.onError (mediaRecorder, whatInt, extraInt);
  377. return nullptr;
  378. }
  379. return AndroidInterfaceImplementer::invoke (proxy, method, args);
  380. }
  381. private:
  382. Owner& owner;
  383. };
  384. //==============================================================================
  385. struct CameraDevice::Pimpl
  386. : private ActivityLifecycleCallbacks
  387. {
  388. using InternalOpenCameraResultCallback = std::function<void (const String& /*cameraId*/, const String& /*error*/)>;
  389. Pimpl (CameraDevice& ownerToUse, const String& cameraIdToUse, int /*index*/,
  390. int minWidthToUse, int minHeightToUse, int maxWidthToUse, int maxHeightToUse,
  391. bool /*useHighQuality*/)
  392. : owner (ownerToUse),
  393. minWidth (minWidthToUse),
  394. minHeight (minHeightToUse),
  395. maxWidth (maxWidthToUse),
  396. maxHeight (maxHeightToUse),
  397. cameraId (cameraIdToUse),
  398. activityLifeListener (CreateJavaInterface (this, "android/app/Application$ActivityLifecycleCallbacks")),
  399. cameraManager (initialiseCameraManager()),
  400. cameraCharacteristics (initialiseCameraCharacteristics (cameraManager, cameraId)),
  401. streamConfigurationMap (cameraCharacteristics),
  402. previewDisplay (streamConfigurationMap.getPreviewBufferSize()),
  403. deviceOrientationChangeListener (previewDisplay)
  404. {
  405. startBackgroundThread();
  406. }
  407. ~Pimpl() override
  408. {
  409. auto* env = getEnv();
  410. env->CallVoidMethod (getAppContext().get(), AndroidApplication.unregisterActivityLifecycleCallbacks, activityLifeListener.get());
  411. activityLifeListener.clear();
  412. }
  413. JUCE_DECLARE_WEAK_REFERENCEABLE (Pimpl)
  414. String getCameraId() const noexcept { return cameraId; }
  415. void open (InternalOpenCameraResultCallback cameraOpenCallbackToUse)
  416. {
  417. cameraOpenCallback = std::move (cameraOpenCallbackToUse);
  418. // A valid camera open callback must be passed.
  419. jassert (cameraOpenCallback != nullptr);
  420. // The same camera can be opened only once!
  421. jassert (scopedCameraDevice == nullptr);
  422. if (cameraOpenCallback == nullptr || scopedCameraDevice != nullptr)
  423. return;
  424. WeakReference<Pimpl> safeThis (this);
  425. RuntimePermissions::request (RuntimePermissions::camera, [safeThis] (bool granted) mutable
  426. {
  427. if (safeThis != nullptr)
  428. safeThis->continueOpenRequest (granted);
  429. });
  430. }
  431. void continueOpenRequest (bool granted)
  432. {
  433. if (getAndroidSDKVersion() >= 21)
  434. {
  435. if (granted)
  436. {
  437. getEnv()->CallVoidMethod (getAppContext().get(), AndroidApplication.registerActivityLifecycleCallbacks, activityLifeListener.get());
  438. scopedCameraDevice.reset (new ScopedCameraDevice (*this, cameraId, cameraManager, handler, getAutoFocusModeToUse()));
  439. }
  440. else
  441. {
  442. invokeCameraOpenCallback ("Camera permission not granted");
  443. }
  444. }
  445. else
  446. {
  447. invokeCameraOpenCallback ("Camera requires android sdk version 21 or greater");
  448. }
  449. }
  450. bool openedOk() const noexcept { return scopedCameraDevice->openedOk(); }
  451. void takeStillPicture (std::function<void (const Image&)> pictureTakenCallbackToUse)
  452. {
  453. if (pictureTakenCallbackToUse == nullptr || currentCaptureSessionMode == nullptr)
  454. {
  455. jassertfalse;
  456. return;
  457. }
  458. if (currentCaptureSessionMode->isVideoRecordSession())
  459. {
  460. // Taking still pictures while recording video is not supported on Android.
  461. jassertfalse;
  462. return;
  463. }
  464. pictureTakenCallback = std::move (pictureTakenCallbackToUse);
  465. triggerStillPictureCapture();
  466. }
  467. void startRecordingToFile (const File& file, int /*quality*/)
  468. {
  469. if (! openedOk())
  470. {
  471. jassertfalse;
  472. return;
  473. }
  474. if (! previewDisplay.isReady())
  475. {
  476. // Did you remember to create and show a preview display?
  477. jassertfalse;
  478. return;
  479. }
  480. file.deleteFile();
  481. file.create();
  482. jassert (file.existsAsFile());
  483. // MediaRecorder can't handle videos larger than 1080p
  484. auto videoSize = chooseBestSize (minWidth, minHeight, jmin (maxWidth, 1080), maxHeight,
  485. streamConfigurationMap.getSupportedVideoRecordingOutputSizes());
  486. mediaRecorder.reset (new MediaRecorder (file.getFullPathName(), videoSize.getWidth(), videoSize.getHeight(),
  487. getCameraSensorOrientation(), getCameraLensFacing()));
  488. firstRecordedFrameTimeMs = Time::getCurrentTime();
  489. currentCaptureSessionMode.reset();
  490. startVideoRecordingMode (*mediaRecorder);
  491. }
  492. void stopRecording()
  493. {
  494. currentCaptureSessionMode.reset();
  495. mediaRecorder.reset();
  496. startPreviewMode (*imageReader);
  497. }
  498. Time getTimeOfFirstRecordedFrame() const
  499. {
  500. return firstRecordedFrameTimeMs;
  501. }
  502. static StringArray getAvailableDevices()
  503. {
  504. if (getAndroidSDKVersion() < 21)
  505. return StringArray(); // Camera requires SDK version 21 or later
  506. StringArray results;
  507. auto* env = getEnv();
  508. auto cameraManagerToUse = initialiseCameraManager();
  509. auto cameraIdArray = LocalRef<jobjectArray> ((jobjectArray) env->CallObjectMethod (cameraManagerToUse,
  510. CameraManager.getCameraIdList));
  511. results = javaStringArrayToJuce (cameraIdArray);
  512. for (auto& result : results)
  513. printDebugCameraInfo (cameraManagerToUse, result);
  514. return results;
  515. }
  516. void addListener (CameraDevice::Listener* listenerToAdd)
  517. {
  518. const ScopedLock sl (listenerLock);
  519. listeners.add (listenerToAdd);
  520. if (listeners.size() == 1)
  521. triggerStillPictureCapture();
  522. }
  523. void removeListener (CameraDevice::Listener* listenerToRemove)
  524. {
  525. const ScopedLock sl (listenerLock);
  526. listeners.remove (listenerToRemove);
  527. }
  528. private:
  529. enum
  530. {
  531. ERROR_CAMERA_IN_USE = 1,
  532. ERROR_MAX_CAMERAS_IN_USE = 2,
  533. ERROR_CAMERA_DISABLED = 3,
  534. ERROR_CAMERA_DEVICE = 4,
  535. ERROR_CAMERA_SERVICE = 5
  536. };
  537. static String cameraErrorCodeToString (int errorCode)
  538. {
  539. switch (errorCode)
  540. {
  541. case ERROR_CAMERA_IN_USE: return "Camera already in use.";
  542. case ERROR_MAX_CAMERAS_IN_USE: return "Too many opened camera devices.";
  543. case ERROR_CAMERA_DISABLED: return "Camera disabled.";
  544. case ERROR_CAMERA_DEVICE: return "Fatal error.";
  545. case ERROR_CAMERA_SERVICE: return "Fatal error. Reboot required or persistent hardware problem.";
  546. default: return "Unknown error.";
  547. }
  548. }
  549. static LocalRef<jobject> initialiseCameraManager()
  550. {
  551. return LocalRef<jobject> (getEnv()->CallObjectMethod (getAppContext().get(), AndroidContext.getSystemService,
  552. javaString ("camera").get()));
  553. }
  554. static LocalRef<jobject> initialiseCameraCharacteristics (const GlobalRef& cameraManager, const String& cameraId)
  555. {
  556. return LocalRef<jobject> (getEnv()->CallObjectMethod (cameraManager,
  557. CameraManager.getCameraCharacteristics,
  558. javaString (cameraId).get()));
  559. }
  560. static void printDebugCameraInfo (const LocalRef<jobject>& cameraManagerToUse, const String& cameraId)
  561. {
  562. auto* env = getEnv();
  563. auto characteristics = LocalRef<jobject> (env->CallObjectMethod (cameraManagerToUse,
  564. CameraManager.getCameraCharacteristics,
  565. javaString (cameraId).get()));
  566. auto keysList = LocalRef<jobject> (env->CallObjectMethod (characteristics, CameraCharacteristics.getKeys));
  567. const int size = env->CallIntMethod (keysList, JavaList.size);
  568. JUCE_CAMERA_LOG ("Camera id: " + cameraId + ", characteristics keys num: " + String (size));
  569. for (int i = 0; i < size; ++i)
  570. {
  571. auto key = LocalRef<jobject> (env->CallObjectMethod (keysList, JavaList.get, i));
  572. auto jKeyName = LocalRef<jstring> ((jstring) env->CallObjectMethod (key, CameraCharacteristicsKey.getName));
  573. auto keyName = juceString (jKeyName);
  574. auto keyValue = LocalRef<jobject> (env->CallObjectMethod (characteristics, CameraCharacteristics.get, key.get()));
  575. auto jKeyValueString = LocalRef<jstring> ((jstring) env->CallObjectMethod (keyValue, JavaObject.toString));
  576. auto keyValueString = juceString (jKeyValueString);
  577. auto &kvs = keyValueString;
  578. if (kvs.startsWith ("[I") || kvs.startsWith ("[F") || kvs.startsWith ("[Z") || kvs.startsWith ("[B"))
  579. {
  580. printPrimitiveArrayElements (keyValue, keyName, keyValueString);
  581. }
  582. else if (kvs.startsWith ("[Landroid.util.Range"))
  583. {
  584. printRangeArrayElements (keyValue, keyName);
  585. }
  586. else
  587. {
  588. int chunkSize = 256;
  589. if (keyValueString.length() > chunkSize)
  590. {
  591. JUCE_CAMERA_LOG ("Key: " + keyName);
  592. for (int j = 0, k = 1; j < keyValueString.length(); j += chunkSize, ++k)
  593. JUCE_CAMERA_LOG ("value part " + String (k) + ": " + keyValueString.substring (j, k + chunkSize));
  594. }
  595. else
  596. {
  597. JUCE_CAMERA_LOG ("Key: " + keyName + ", value: " + keyValueString);
  598. }
  599. }
  600. ignoreUnused (keyName);
  601. }
  602. }
  603. static void printPrimitiveArrayElements (const LocalRef<jobject>& keyValue, const String& keyName,
  604. const String& keyValueString)
  605. {
  606. ignoreUnused (keyName);
  607. String result = "[";
  608. auto* env = getEnv();
  609. #define PRINT_ELEMENTS(elem_type, array_type, fun_name_middle) \
  610. { \
  611. elem_type* elements = env->Get##fun_name_middle##ArrayElements ((array_type) keyValue.get(), nullptr); \
  612. int size = env->GetArrayLength ((array_type) keyValue.get()); \
  613. \
  614. for (int i = 0; i < size - 1; ++i) \
  615. result << String (elements[i]) << " "; \
  616. \
  617. if (size > 0) \
  618. result << String (elements[size - 1]); \
  619. \
  620. env->Release##fun_name_middle##ArrayElements ((array_type) keyValue.get(), elements, 0); \
  621. }
  622. if (keyValueString.startsWith ("[I"))
  623. PRINT_ELEMENTS (jint, jintArray, Int)
  624. else if (keyValueString.startsWith ("[F"))
  625. PRINT_ELEMENTS (float, jfloatArray, Float)
  626. else if (keyValueString.startsWith ("[Z"))
  627. PRINT_ELEMENTS (jboolean, jbooleanArray, Boolean)
  628. else if (keyValueString.startsWith ("[B"))
  629. PRINT_ELEMENTS (jbyte, jbyteArray, Byte);
  630. #undef PRINT_ELEMENTS
  631. result << "]";
  632. JUCE_CAMERA_LOG ("Key: " + keyName + ", value: " + result);
  633. }
  634. static void printRangeArrayElements (const LocalRef<jobject>& rangeArray, const String& keyName)
  635. {
  636. auto* env = getEnv();
  637. jobjectArray ranges = static_cast<jobjectArray> (rangeArray.get());
  638. int numRanges = env->GetArrayLength (ranges);
  639. String result;
  640. for (int i = 0; i < numRanges; ++i)
  641. {
  642. auto range = LocalRef<jobject> (env->GetObjectArrayElement (ranges, i));
  643. auto jRangeString = LocalRef<jstring> ((jstring) env->CallObjectMethod (range, AndroidRange.toString));
  644. result << juceString (jRangeString) << " ";
  645. }
  646. ignoreUnused (keyName);
  647. JUCE_CAMERA_LOG ("Key: " + keyName + ", value: " + result);
  648. }
  649. //==============================================================================
  650. class StreamConfigurationMap
  651. {
  652. public:
  653. StreamConfigurationMap (const GlobalRef& cameraCharacteristicsToUse)
  654. : scalerStreamConfigurationMap (getStreamConfigurationMap (cameraCharacteristicsToUse)),
  655. supportedPreviewOutputSizes (retrieveOutputSizes (scalerStreamConfigurationMap,
  656. getClassForName ("android.graphics.SurfaceTexture"),
  657. -1)),
  658. supportedStillImageOutputSizes (retrieveOutputSizes (scalerStreamConfigurationMap,
  659. LocalRef<jobject>(),
  660. jpegImageFormat)),
  661. supportedVideoRecordingOutputSizes (retrieveOutputSizes (scalerStreamConfigurationMap,
  662. getClassForName ("android.media.MediaRecorder"),
  663. -1)),
  664. defaultPreviewSize (getSmallestSize (supportedPreviewOutputSizes)),
  665. previewBufferSize (getLargestSize (supportedPreviewOutputSizes))
  666. {
  667. printSizesLog (supportedPreviewOutputSizes, "SurfaceTexture");
  668. printSizesLog (supportedStillImageOutputSizes, "JPEG");
  669. printSizesLog (supportedVideoRecordingOutputSizes, "MediaRecorder");
  670. }
  671. Array<Rectangle<int>> getSupportedPreviewOutputSizes() const noexcept { return supportedPreviewOutputSizes; }
  672. Array<Rectangle<int>> getSupportedStillImageOutputSizes() const noexcept { return supportedStillImageOutputSizes; }
  673. Array<Rectangle<int>> getSupportedVideoRecordingOutputSizes() const noexcept { return supportedVideoRecordingOutputSizes; }
  674. Rectangle<int> getDefaultPreviewSize() const noexcept { return defaultPreviewSize; }
  675. Rectangle<int> getPreviewBufferSize() const noexcept { return previewBufferSize; }
  676. bool isOutputSupportedForSurface (const LocalRef<jobject>& surface) const
  677. {
  678. return getEnv()->CallBooleanMethod (scalerStreamConfigurationMap, AndroidStreamConfigurationMap.isOutputSupportedForSurface, surface.get()) != 0;
  679. }
  680. static constexpr int jpegImageFormat = 256;
  681. private:
  682. GlobalRef scalerStreamConfigurationMap;
  683. Array<Rectangle<int>> supportedPreviewOutputSizes;
  684. Array<Rectangle<int>> supportedStillImageOutputSizes;
  685. Array<Rectangle<int>> supportedVideoRecordingOutputSizes;
  686. Rectangle<int> defaultPreviewSize, previewBufferSize;
  687. GlobalRef getStreamConfigurationMap (const GlobalRef& cameraCharacteristicsToUse)
  688. {
  689. auto* env = getEnv();
  690. auto scalerStreamConfigurationMapKey = LocalRef<jobject> (env->GetStaticObjectField (CameraCharacteristics,
  691. CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP));
  692. return GlobalRef (LocalRef<jobject> (env->CallObjectMethod (cameraCharacteristicsToUse,
  693. CameraCharacteristics.get,
  694. scalerStreamConfigurationMapKey.get())));
  695. }
  696. static Array<Rectangle<int>> retrieveOutputSizes (GlobalRef& scalerStreamConfigurationMap,
  697. const LocalRef<jobject>& outputClass,
  698. int format)
  699. {
  700. Array<Rectangle<int>> result;
  701. auto* env = getEnv();
  702. auto outputSizes = outputClass.get() != nullptr
  703. ? LocalRef<jobjectArray> ((jobjectArray) env->CallObjectMethod (scalerStreamConfigurationMap,
  704. AndroidStreamConfigurationMap.getOutputSizesForClass,
  705. outputClass.get()))
  706. : LocalRef<jobjectArray> ((jobjectArray) env->CallObjectMethod (scalerStreamConfigurationMap,
  707. AndroidStreamConfigurationMap.getOutputSizesForFormat,
  708. (jint) format));
  709. if (format != -1)
  710. {
  711. auto supported = (env->CallBooleanMethod (scalerStreamConfigurationMap, AndroidStreamConfigurationMap.isOutputSupportedFor, (jint) format) != 0);
  712. if (! supported)
  713. {
  714. // The output format is not supported by this device, still image capture will not work!
  715. jassertfalse;
  716. return {};
  717. }
  718. }
  719. int numSizes = env->GetArrayLength (outputSizes);
  720. jassert (numSizes > 0);
  721. for (int i = 0; i < numSizes; ++i)
  722. {
  723. auto size = LocalRef<jobject> (env->GetObjectArrayElement (outputSizes, i));
  724. auto width = env->CallIntMethod (size, AndroidSize.getWidth);
  725. auto height = env->CallIntMethod (size, AndroidSize.getHeight);
  726. result.add (Rectangle<int> (0, 0, width, height));
  727. }
  728. return result;
  729. }
  730. static LocalRef<jobject> getClassForName (const String& name)
  731. {
  732. return LocalRef<jobject> (getEnv()->CallStaticObjectMethod (JavaClass, JavaClass.forName,
  733. javaString (name).get()));
  734. }
  735. static void printSizesLog (const Array<Rectangle<int>>& sizes, const String& className)
  736. {
  737. ignoreUnused (sizes, className);
  738. JUCE_CAMERA_LOG ("Sizes for class " + className);
  739. #if JUCE_CAMERA_LOG_ENABLED
  740. for (auto& s : sizes)
  741. JUCE_CAMERA_LOG (s.toString() + "\n");
  742. #endif
  743. }
  744. Rectangle<int> getSmallestSize (const Array<Rectangle<int>>& sizes) const
  745. {
  746. if (sizes.size() == 0)
  747. return {};
  748. auto smallestSize = sizes[0];
  749. for (auto& size : sizes)
  750. {
  751. if (size.getWidth() < smallestSize.getWidth() && size.getHeight() < smallestSize.getHeight())
  752. smallestSize = size;
  753. }
  754. return smallestSize;
  755. }
  756. Rectangle<int> getLargestSize (const Array<Rectangle<int>>& sizes) const
  757. {
  758. if (sizes.size() == 0)
  759. return {};
  760. auto largestSize = sizes[0];
  761. for (auto& size : sizes)
  762. {
  763. if (size.getWidth() > largestSize.getWidth() && size.getHeight() > largestSize.getHeight())
  764. largestSize = size;
  765. }
  766. return largestSize;
  767. }
  768. };
  769. //==============================================================================
  770. class PreviewDisplay : private TextureViewSurfaceTextureListener::Owner
  771. {
  772. public:
  773. struct Listener
  774. {
  775. virtual ~Listener() {}
  776. virtual void previewDisplayReady() = 0;
  777. virtual void previewDisplayAboutToBeDestroyed() = 0;
  778. };
  779. PreviewDisplay (Rectangle<int> bufferSize)
  780. : textureViewSurfaceTextureListener (*this),
  781. textureView (LocalRef<jobject> (getEnv()->NewObject (AndroidTextureView, AndroidTextureView.constructor,
  782. getAppContext().get()))),
  783. bufferWidth (bufferSize.getWidth()),
  784. bufferHeight (bufferSize.getHeight())
  785. {
  786. auto* env = getEnv();
  787. if (! isReady())
  788. env->CallVoidMethod (textureView, AndroidTextureView.setSurfaceTextureListener,
  789. CreateJavaInterface (&textureViewSurfaceTextureListener,
  790. "android/view/TextureView$SurfaceTextureListener").get());
  791. }
  792. ~PreviewDisplay() override
  793. {
  794. getEnv()->CallVoidMethod (textureView, AndroidTextureView.setSurfaceTextureListener, nullptr);
  795. }
  796. void addListener (Listener* l)
  797. {
  798. if (l == nullptr)
  799. {
  800. jassertfalse;
  801. return;
  802. }
  803. listeners.add (l);
  804. if (isReady())
  805. l->previewDisplayReady();
  806. }
  807. void removeListener (Listener* l)
  808. {
  809. if (l == nullptr)
  810. {
  811. jassertfalse;
  812. return;
  813. }
  814. listeners.remove (l);
  815. }
  816. bool isReady() const
  817. {
  818. return (getEnv()->CallBooleanMethod (textureView, AndroidTextureView.isAvailable) != 0)
  819. && width > 0 && height > 0;
  820. }
  821. LocalRef<jobject> createSurface()
  822. {
  823. // Surface may get destroyed while session is being configured, if
  824. // the preview gets hidden in the meantime, so bailout.
  825. if (! isReady())
  826. return LocalRef<jobject> (nullptr);
  827. auto* env = getEnv();
  828. auto surfaceTexture = LocalRef<jobject> (env->CallObjectMethod (textureView,
  829. AndroidTextureView.getSurfaceTexture));
  830. // NB: too small buffer will result in pixelated preview. A buffer with wrong aspect ratio
  831. // can result in a cropped preview.
  832. env->CallVoidMethod (surfaceTexture, AndroidSurfaceTexture.setDefaultBufferSize, (jint) bufferWidth, (jint) bufferHeight);
  833. auto surface = LocalRef<jobject> (env->NewObject (AndroidSurface, AndroidSurface.constructor, surfaceTexture.get()));
  834. return surface;
  835. }
  836. const GlobalRef& getNativeView() { return textureView; }
  837. void updateSurfaceTransform()
  838. {
  839. auto* env = getEnv();
  840. auto windowManager = LocalRef<jobject> (env->CallObjectMethod (getAppContext(), AndroidContext.getSystemService, javaString ("window").get()));
  841. auto display = LocalRef<jobject> (env->CallObjectMethod (windowManager, AndroidWindowManager.getDefaultDisplay));
  842. auto rotation = env->CallIntMethod (display, AndroidDisplay.getRotation);
  843. static constexpr int rotation90 = 1;
  844. static constexpr int rotation270 = 3;
  845. auto matrix = LocalRef<jobject> (env->NewObject (AndroidMatrix, AndroidMatrix.constructor));
  846. if (rotation == rotation90 || rotation == rotation270)
  847. {
  848. env->CallBooleanMethod (matrix, AndroidMatrix.postScale, jfloat (height / (float) width), jfloat (width / (float) height), (jfloat) 0, (jfloat) 0);
  849. env->CallBooleanMethod (matrix, AndroidMatrix.postRotate, (jfloat) 90 * (rotation - 2), (jfloat) 0, (jfloat) 0);
  850. env->CallBooleanMethod (matrix, AndroidMatrix.postTranslate, (jfloat) (rotation == 3 ? width : 0), (jfloat) (rotation == 1 ? height : 0));
  851. }
  852. env->CallVoidMethod (textureView, AndroidTextureView.setTransform, matrix.get());
  853. }
  854. private:
  855. ListenerList<Listener> listeners;
  856. TextureViewSurfaceTextureListener textureViewSurfaceTextureListener;
  857. GlobalRef textureView;
  858. int width = -1, height = -1;
  859. int bufferWidth, bufferHeight;
  860. void onSurfaceTextureAvailable (LocalRef<jobject>& /*surface*/, int widthToUse, int heightToUse) override
  861. {
  862. JUCE_CAMERA_LOG ("onSurfaceTextureAvailable()");
  863. width = widthToUse;
  864. height = heightToUse;
  865. updateSurfaceTransform();
  866. listeners.call (&Listener::previewDisplayReady);
  867. }
  868. bool onSurfaceTextureDestroyed (LocalRef<jobject>& /*surface*/) override
  869. {
  870. JUCE_CAMERA_LOG ("onSurfaceTextureDestroyed()");
  871. listeners.call (&Listener::previewDisplayAboutToBeDestroyed);
  872. return true;
  873. }
  874. void onSurfaceTextureSizeChanged (LocalRef<jobject>& /*surface*/, int widthToUse, int heightToUse) override
  875. {
  876. JUCE_CAMERA_LOG ("onSurfaceTextureSizeChanged()");
  877. width = widthToUse;
  878. height = heightToUse;
  879. updateSurfaceTransform();
  880. }
  881. void onSurfaceTextureUpdated (LocalRef<jobject>& /*surface*/) override
  882. {
  883. JUCE_CAMERA_LOG ("onSurfaceTextureUpdated()");
  884. }
  885. JUCE_DECLARE_NON_COPYABLE (PreviewDisplay)
  886. };
  887. //==============================================================================
  888. class ImageReader : private ImageReaderOnImageAvailableListener::Owner
  889. {
  890. public:
  891. ImageReader (Pimpl& ownerToUse, GlobalRef& handlerToUse,
  892. int imageWidth, int imageHeight, int cameraSensorOrientationToUse)
  893. : owner (ownerToUse),
  894. cameraSensorOrientation (cameraSensorOrientationToUse),
  895. imageReader (LocalRef<jobject> (getEnv()->CallStaticObjectMethod (AndroidImageReader, AndroidImageReader.newInstance,
  896. imageWidth, imageHeight, StreamConfigurationMap::jpegImageFormat,
  897. numImagesToKeep))),
  898. onImageAvailableListener (*this)
  899. {
  900. getEnv()->CallVoidMethod (imageReader, AndroidImageReader.setOnImageAvailableListener,
  901. CreateJavaInterface (&onImageAvailableListener,
  902. "android/media/ImageReader$OnImageAvailableListener").get(),
  903. handlerToUse.get());
  904. }
  905. ~ImageReader() override
  906. {
  907. getEnv()->CallVoidMethod (imageReader, AndroidImageReader.close);
  908. }
  909. LocalRef<jobject> getSurface() const
  910. {
  911. return LocalRef<jobject> (getEnv()->CallObjectMethod (imageReader, AndroidImageReader.getSurface));
  912. }
  913. void resetNotificationFlag()
  914. {
  915. hasNotifiedListeners.set (0);
  916. }
  917. private:
  918. Pimpl& owner;
  919. int cameraSensorOrientation;
  920. GlobalRef imageReader;
  921. ImageReaderOnImageAvailableListener onImageAvailableListener;
  922. static constexpr int numImagesToKeep = 2;
  923. Atomic<int> hasNotifiedListeners { 0 };
  924. JUCE_DECLARE_WEAK_REFERENCEABLE (ImageReader)
  925. void onImageAvailable (LocalRef<jobject>& /*imageReader*/) override
  926. {
  927. JUCE_CAMERA_LOG ("onImageAvailable()");
  928. auto* env = getEnv();
  929. auto jImage = LocalRef<jobject> (env->CallObjectMethod (imageReader, AndroidImageReader.acquireLatestImage));
  930. if (jImage.get() == nullptr)
  931. return;
  932. auto cameraLensFrontFacing = owner.getCameraLensFacing() == 0;
  933. // NB: could use sensor orientation here to get real-world orientation, but then the resulting
  934. // image could not match the UI orientation.
  935. auto image = androidImageToJuceWithFixedOrientation (jImage, owner.deviceOrientationChangeListener.getDeviceOrientation(),
  936. Desktop::getInstance().getCurrentOrientation(),
  937. cameraLensFrontFacing,
  938. cameraSensorOrientation);
  939. env->CallVoidMethod (jImage, AndroidImage.close);
  940. WeakReference<ImageReader> safeThis (this);
  941. owner.callListeners (image);
  942. // Android may take multiple pictures before it handles a request to stop.
  943. if (hasNotifiedListeners.compareAndSetBool (1, 0))
  944. MessageManager::callAsync ([safeThis, image]() mutable { if (safeThis != nullptr) safeThis->owner.notifyPictureTaken (image); });
  945. }
  946. struct ImageBuffer
  947. {
  948. LocalRef<jbyteArray> byteArray;
  949. int size;
  950. };
  951. static Image androidImageToJuceWithFixedOrientation (const LocalRef<jobject>& androidImage,
  952. Desktop::DisplayOrientation deviceOrientationFromAccelerometerSensor,
  953. Desktop::DisplayOrientation targetOrientation,
  954. bool cameraLensFrontFacing,
  955. int cameraSensorOrientation)
  956. {
  957. auto* env = getEnv();
  958. auto planes = LocalRef<jobjectArray> ((jobjectArray) env->CallObjectMethod (androidImage, AndroidImage.getPlanes));
  959. jassert (env->GetArrayLength (planes) > 0);
  960. auto plane = LocalRef<jobject> (env->GetObjectArrayElement (planes, 0));
  961. auto byteBuffer = LocalRef<jobject> (env->CallObjectMethod (plane, AndroidImagePlane.getBuffer));
  962. ImageBuffer correctedBuffer = getImageBufferWithCorrectedOrientationFrom (byteBuffer, deviceOrientationFromAccelerometerSensor,
  963. targetOrientation, cameraLensFrontFacing, cameraSensorOrientation);
  964. jbyte* rawBytes = env->GetByteArrayElements (correctedBuffer.byteArray, nullptr);
  965. Image result = ImageFileFormat::loadFrom (rawBytes, (size_t) correctedBuffer.size);
  966. env->ReleaseByteArrayElements (correctedBuffer.byteArray, rawBytes, 0);
  967. return result;
  968. }
  969. static ImageBuffer getImageBufferWithCorrectedOrientationFrom (const LocalRef<jobject>& imagePlaneBuffer,
  970. Desktop::DisplayOrientation deviceOrientationFromAccelerometerSensor,
  971. Desktop::DisplayOrientation targetOrientation,
  972. bool cameraLensFrontFacing,
  973. int cameraSensorOrientation)
  974. {
  975. auto* env = getEnv();
  976. auto bufferSize = env->CallIntMethod (imagePlaneBuffer, JavaByteBuffer.remaining);
  977. auto byteArray = LocalRef<jbyteArray> (env->NewByteArray (bufferSize));
  978. env->CallObjectMethod (imagePlaneBuffer, JavaByteBuffer.get, byteArray.get());
  979. auto rotationAngle = getRotationAngle (deviceOrientationFromAccelerometerSensor, targetOrientation,
  980. cameraLensFrontFacing, cameraSensorOrientation);
  981. if (rotationAngle == 0)
  982. {
  983. // Nothing to do, just get the bytes
  984. return { byteArray, bufferSize };
  985. }
  986. auto origBitmap = LocalRef<jobject> (env->CallStaticObjectMethod (AndroidBitmapFactory,
  987. AndroidBitmapFactory.decodeByteArray,
  988. byteArray.get(), (jint) 0, (jint) bufferSize));
  989. if (origBitmap == nullptr)
  990. {
  991. // Nothing to do, just get the bytes
  992. return { byteArray, bufferSize };
  993. }
  994. auto correctedBitmap = getBitmapWithCorrectOrientationFrom (origBitmap, rotationAngle);
  995. auto byteArrayOutputStream = LocalRef<jobject> (env->NewObject (ByteArrayOutputStream,
  996. ByteArrayOutputStream.constructor));
  997. auto jCompressFormatString = javaString ("JPEG");
  998. auto compressFormat = LocalRef<jobject> (env->CallStaticObjectMethod (AndroidBitmapCompressFormat,
  999. AndroidBitmapCompressFormat.valueOf,
  1000. jCompressFormatString.get()));
  1001. if (env->CallBooleanMethod (correctedBitmap, AndroidBitmap.compress, compressFormat.get(),
  1002. (jint) 100, byteArrayOutputStream.get()) != 0)
  1003. {
  1004. auto correctedByteArray = LocalRef<jbyteArray> ((jbyteArray) env->CallObjectMethod (byteArrayOutputStream,
  1005. ByteArrayOutputStream.toByteArray));
  1006. int correctedByteArraySize = env->CallIntMethod (byteArrayOutputStream, ByteArrayOutputStream.size);
  1007. return { correctedByteArray, correctedByteArraySize };
  1008. }
  1009. jassertfalse;
  1010. // fallback, return original bitmap
  1011. return { byteArray, bufferSize };
  1012. }
  1013. static int getRotationAngle (Desktop::DisplayOrientation deviceOrientationFromAccelerometerSensor,
  1014. Desktop::DisplayOrientation targetOrientation,
  1015. bool cameraLensFrontFacing,
  1016. int cameraSensorOrientation)
  1017. {
  1018. auto isSensorOrientationHorizontal = deviceOrientationFromAccelerometerSensor == Desktop::rotatedAntiClockwise
  1019. || deviceOrientationFromAccelerometerSensor == Desktop::rotatedClockwise;
  1020. if (cameraLensFrontFacing && isSensorOrientationHorizontal)
  1021. {
  1022. // flip angles for front camera
  1023. return getRotationAngle (deviceOrientationFromAccelerometerSensor, targetOrientation, false, (cameraSensorOrientation + 180) % 360);
  1024. }
  1025. switch (targetOrientation)
  1026. {
  1027. case Desktop::rotatedAntiClockwise:
  1028. return cameraSensorOrientation == 90 ? 0 : 180;
  1029. case Desktop::rotatedClockwise:
  1030. return cameraSensorOrientation == 90 ? 180 : 0;
  1031. case Desktop::upright:
  1032. case Desktop::upsideDown:
  1033. if ((targetOrientation == Desktop::upright && ! cameraLensFrontFacing)
  1034. || (targetOrientation == Desktop::upsideDown && cameraLensFrontFacing))
  1035. {
  1036. return cameraSensorOrientation;
  1037. }
  1038. else
  1039. {
  1040. if (deviceOrientationFromAccelerometerSensor == Desktop::upright || deviceOrientationFromAccelerometerSensor == Desktop::upsideDown)
  1041. return cameraSensorOrientation;
  1042. else
  1043. return (cameraSensorOrientation + 180) % 360;
  1044. }
  1045. break;
  1046. case Desktop::allOrientations:
  1047. default:
  1048. return 0;
  1049. }
  1050. }
  1051. static LocalRef<jobject> getBitmapWithCorrectOrientationFrom (LocalRef<jobject>& origBitmap, int rotationAngle)
  1052. {
  1053. auto* env = getEnv();
  1054. auto origBitmapWidth = env->CallIntMethod (origBitmap, AndroidBitmap.getWidth);
  1055. auto origBitmapHeight = env->CallIntMethod (origBitmap, AndroidBitmap.getHeight);
  1056. auto matrix = LocalRef<jobject> (env->NewObject (AndroidMatrix, AndroidMatrix.constructor));
  1057. env->CallBooleanMethod (matrix, AndroidMatrix.postRotate, (jfloat) rotationAngle, (jfloat) 0, (jfloat) 0);
  1058. auto rotatedBitmap = LocalRef<jobject> (env->CallStaticObjectMethod (AndroidBitmap, AndroidBitmap.createBitmapFrom,
  1059. origBitmap.get(), (jint) 0, (jint) 0,
  1060. (jint) origBitmapWidth, (jint) origBitmapHeight,
  1061. matrix.get(), true));
  1062. env->CallVoidMethod (origBitmap, AndroidBitmap.recycle);
  1063. return rotatedBitmap;
  1064. }
  1065. };
  1066. //==============================================================================
  1067. class MediaRecorder : private MediaRecorderOnInfoListener::Owner,
  1068. private MediaRecorderOnErrorListener::Owner
  1069. {
  1070. public:
  1071. MediaRecorder (const String& outputFilePath, int videoWidth, int videoHeight,
  1072. int sensorOrientation, int cameraLensFacing)
  1073. : onInfoListener (*this),
  1074. onErrorListener (*this),
  1075. mediaRecorder (LocalRef<jobject> (getEnv()->NewObject (AndroidMediaRecorder,
  1076. AndroidMediaRecorder.constructor)))
  1077. {
  1078. auto* env = getEnv();
  1079. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setOnInfoListener,
  1080. CreateJavaInterface (&onInfoListener,
  1081. "android/media/MediaRecorder$OnInfoListener").get());
  1082. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setOnErrorListener,
  1083. CreateJavaInterface (&onErrorListener,
  1084. "android/media/MediaRecorder$OnErrorListener").get());
  1085. // NB: the order of function calls here is enforced, and exceptions will be thrown if
  1086. // the order is changed.
  1087. static constexpr int audioSourceMic = 1;
  1088. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setAudioSource, (jint) audioSourceMic);
  1089. static constexpr int videoSourceSurface = 2;
  1090. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setVideoSource, (jint) videoSourceSurface);
  1091. static constexpr int outputFormatMPEG4 = 2;
  1092. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setOutputFormat, (jint) outputFormatMPEG4);
  1093. static constexpr int audioEncoderAAC = 3;
  1094. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setAudioEncoder, (jint) audioEncoderAAC);
  1095. static constexpr int videoEncoderH264 = 2;
  1096. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setVideoEncoder, (jint) videoEncoderH264);
  1097. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setVideoEncodingBitRate, (jint) 10000000);
  1098. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setVideoFrameRate, (jint) 30);
  1099. auto frontFacing = cameraLensFacing == 0;
  1100. auto useInverseDegrees = frontFacing && sensorOrientation == 90;
  1101. int orientationHint = getOrientationHint (useInverseDegrees, sensorOrientation);
  1102. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setOrientationHint, (jint) orientationHint);
  1103. getEnv()->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setVideoSize, (jint) videoWidth, (jint) videoHeight);
  1104. getEnv()->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setOutputFile, javaString (outputFilePath).get());
  1105. getEnv()->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.prepare);
  1106. }
  1107. ~MediaRecorder() override
  1108. {
  1109. getEnv()->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.release);
  1110. }
  1111. LocalRef<jobject> getSurface()
  1112. {
  1113. return LocalRef<jobject> (getEnv()->CallObjectMethod (mediaRecorder, AndroidMediaRecorder.getSurface));
  1114. }
  1115. void start()
  1116. {
  1117. lockScreenOrientation();
  1118. getEnv()->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.start);
  1119. hasStartedRecording = true;
  1120. }
  1121. void stop()
  1122. {
  1123. // A request to stop can be sent before recording has had a chance to start, so
  1124. // ignore the request rather than calling AndroidMediaRecorder.stop because
  1125. // otherwise MediaRecorder will throw an exception and...
  1126. if (! hasStartedRecording)
  1127. return;
  1128. hasStartedRecording = false;
  1129. auto* env = getEnv();
  1130. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.stop);
  1131. // ... ignore RuntimeException that can be thrown if stop() was called after recording
  1132. // has started but before any frame was written to a file. This is not an error.
  1133. jniCheckHasExceptionOccurredAndClear();
  1134. unlockScreenOrientation();
  1135. }
  1136. private:
  1137. MediaRecorderOnInfoListener onInfoListener;
  1138. MediaRecorderOnErrorListener onErrorListener;
  1139. GlobalRef mediaRecorder;
  1140. bool hasStartedRecording = false;
  1141. int orientationsEnabled = -1;
  1142. void lockScreenOrientation()
  1143. {
  1144. orientationsEnabled = Desktop::getInstance().getOrientationsEnabled();
  1145. auto o = Desktop::getInstance().getCurrentOrientation();
  1146. Desktop::getInstance().setOrientationsEnabled (o);
  1147. }
  1148. static jint juceOrientationToNativeOrientation (int orientations) noexcept
  1149. {
  1150. enum
  1151. {
  1152. SCREEN_ORIENTATION_LANDSCAPE = 0,
  1153. SCREEN_ORIENTATION_PORTRAIT = 1,
  1154. SCREEN_ORIENTATION_USER = 2,
  1155. SCREEN_ORIENTATION_REVERSE_LANDSCAPE = 8,
  1156. SCREEN_ORIENTATION_REVERSE_PORTRAIT = 9,
  1157. SCREEN_ORIENTATION_USER_LANDSCAPE = 11,
  1158. SCREEN_ORIENTATION_USER_PORTRAIT = 12,
  1159. };
  1160. switch (orientations)
  1161. {
  1162. case Desktop::upright: return (jint) SCREEN_ORIENTATION_PORTRAIT;
  1163. case Desktop::upsideDown: return (jint) SCREEN_ORIENTATION_REVERSE_PORTRAIT;
  1164. case Desktop::upright + Desktop::upsideDown: return (jint) SCREEN_ORIENTATION_USER_PORTRAIT;
  1165. case Desktop::rotatedAntiClockwise: return (jint) SCREEN_ORIENTATION_LANDSCAPE;
  1166. case Desktop::rotatedClockwise: return (jint) SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
  1167. case Desktop::rotatedClockwise + Desktop::rotatedAntiClockwise: return (jint) SCREEN_ORIENTATION_USER_LANDSCAPE;
  1168. default: return (jint) SCREEN_ORIENTATION_USER;
  1169. }
  1170. }
  1171. void unlockScreenOrientation()
  1172. {
  1173. Desktop::getInstance().setOrientationsEnabled (orientationsEnabled);
  1174. }
  1175. void onInfo (LocalRef<jobject>& recorder, int what, int extra) override
  1176. {
  1177. ignoreUnused (recorder, what, extra);
  1178. JUCE_CAMERA_LOG ("MediaRecorder::OnInfo: " + getInfoStringFromCode (what)
  1179. + ", extra code = " + String (extra));
  1180. }
  1181. void onError (LocalRef<jobject>& recorder, int what, int extra) override
  1182. {
  1183. ignoreUnused (recorder, what, extra);
  1184. JUCE_CAMERA_LOG ("MediaRecorder::onError: " + getErrorStringFromCode (what)
  1185. + ", extra code = " + String (extra));
  1186. }
  1187. static String getInfoStringFromCode (int what)
  1188. {
  1189. enum
  1190. {
  1191. MEDIA_RECORDER_INFO_UNKNOWN = 1,
  1192. MEDIA_RECORDER_INFO_MAX_DURATION_REACHED = 800,
  1193. MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED = 801,
  1194. MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING = 802,
  1195. MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED = 803
  1196. };
  1197. switch (what)
  1198. {
  1199. case MEDIA_RECORDER_INFO_UNKNOWN: return { "Unknown info" };
  1200. case MEDIA_RECORDER_INFO_MAX_DURATION_REACHED: return { "Max duration reached" };
  1201. case MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED: return { "Max filesize reached" };
  1202. case MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING: return { "Max filesize approaching" };
  1203. case MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED: return { "Next output file started" };
  1204. default: return String (what);
  1205. };
  1206. }
  1207. static String getErrorStringFromCode (int what)
  1208. {
  1209. enum
  1210. {
  1211. MEDIA_RECORDER_ERROR_UNKNOWN = 1,
  1212. MEDIA_ERROR_SERVER_DIED = 100
  1213. };
  1214. switch (what)
  1215. {
  1216. case MEDIA_RECORDER_ERROR_UNKNOWN: return { "Unknown error" };
  1217. case MEDIA_ERROR_SERVER_DIED: return { "Server died" };
  1218. default: return String (what);
  1219. };
  1220. }
  1221. static int getOrientationHint (bool useInverseDegrees, int cameraSensorOrientation)
  1222. {
  1223. auto* env = getEnv();
  1224. auto windowManager = LocalRef<jobject> (env->CallObjectMethod (getAppContext(), AndroidContext.getSystemService, javaString ("window").get()));
  1225. auto display = LocalRef<jobject> (env->CallObjectMethod (windowManager, AndroidWindowManager.getDefaultDisplay));
  1226. auto rotation = env->CallIntMethod (display, AndroidDisplay.getRotation);
  1227. enum
  1228. {
  1229. ROTATION_0 = 0,
  1230. ROTATION_90,
  1231. ROTATION_180,
  1232. ROTATION_270
  1233. };
  1234. int hint = 0;
  1235. switch (rotation)
  1236. {
  1237. case ROTATION_0: hint = cameraSensorOrientation; break;
  1238. case ROTATION_90: hint = useInverseDegrees ? 180 : 0; break;
  1239. case ROTATION_180: hint = cameraSensorOrientation + 180; break;
  1240. case ROTATION_270: hint = useInverseDegrees ? 0 : 180; break;
  1241. default: jassertfalse;
  1242. }
  1243. return (hint + 360) % 360;
  1244. }
  1245. };
  1246. //==============================================================================
  1247. class ScopedCameraDevice
  1248. {
  1249. public:
  1250. //==============================================================================
  1251. class CaptureSession
  1252. {
  1253. public:
  1254. struct ConfiguredCallback
  1255. {
  1256. virtual ~ConfiguredCallback() {}
  1257. virtual void captureSessionConfigured (CaptureSession*) = 0;
  1258. };
  1259. ~CaptureSession()
  1260. {
  1261. bool calledClose = false;
  1262. auto* env = getEnv();
  1263. {
  1264. const ScopedLock lock (captureSessionLock);
  1265. if (captureSession.get() != nullptr)
  1266. {
  1267. calledClose = true;
  1268. env->CallVoidMethod (captureSession, CameraCaptureSession.close);
  1269. }
  1270. }
  1271. // When exception occurs, CameraCaptureSession.close will never finish, so
  1272. // we should not wait for it. For fatal error an exception does occur, but
  1273. // it is caught internally in Java...
  1274. if (jniCheckHasExceptionOccurredAndClear() || scopedCameraDevice.fatalErrorOccurred.get())
  1275. {
  1276. JUCE_CAMERA_LOG ("Exception or fatal error occurred while closing Capture Session, closing by force");
  1277. }
  1278. else if (calledClose)
  1279. {
  1280. pendingClose.set (1);
  1281. closedEvent.wait (-1);
  1282. }
  1283. }
  1284. bool openedOk() const noexcept { return captureSession != nullptr; }
  1285. const GlobalRef& getNativeSession() const { return captureSession; }
  1286. bool start (const LocalRef<jobject>& targetSurfacesList, GlobalRef& handlerToUse)
  1287. {
  1288. if (! openedOk())
  1289. {
  1290. jassertfalse;
  1291. return false;
  1292. }
  1293. auto* env = getEnv();
  1294. auto numSurfaces = env->CallIntMethod (targetSurfacesList, JavaArrayList.size);
  1295. for (int i = 0; i < numSurfaces; ++i)
  1296. {
  1297. auto surface = LocalRef<jobject> (env->CallObjectMethod (targetSurfacesList, JavaArrayList.get, (jint) i));
  1298. env->CallVoidMethod (captureRequestBuilder, CaptureRequestBuilder.addTarget, surface.get());
  1299. }
  1300. previewCaptureRequest = GlobalRef (LocalRef<jobject>(env->CallObjectMethod (captureRequestBuilder, CaptureRequestBuilder.build)));
  1301. env->CallIntMethod (captureSession, CameraCaptureSession.setRepeatingRequest,
  1302. previewCaptureRequest.get(), nullptr, handlerToUse.get());
  1303. return true;
  1304. }
  1305. void takeStillPicture (jobject targetSurface)
  1306. {
  1307. if (stillPictureTaker == nullptr)
  1308. {
  1309. // Can only take picture once session was successfully configured!
  1310. jassertfalse;
  1311. return;
  1312. }
  1313. auto* env = getEnv();
  1314. static constexpr int templateStillCapture = 2;
  1315. auto builder = LocalRef<jobject> (env->CallObjectMethod (scopedCameraDevice.cameraDevice,
  1316. AndroidCameraDevice.createCaptureRequest,
  1317. (jint) templateStillCapture));
  1318. env->CallVoidMethod (builder, CaptureRequestBuilder.addTarget, targetSurface);
  1319. setCaptureRequestBuilderIntegerKey (builder, CaptureRequest.CONTROL_AF_MODE, autoFocusMode);
  1320. auto stillPictureCaptureRequest = LocalRef<jobject> (env->CallObjectMethod (builder, CaptureRequestBuilder.build));
  1321. stillPictureTaker->takePicture (stillPictureCaptureRequest);
  1322. }
  1323. private:
  1324. //==============================================================================
  1325. class StillPictureTaker : private AndroidRunnable::Owner
  1326. {
  1327. public:
  1328. StillPictureTaker (GlobalRef& captureSessionToUse, GlobalRef& captureRequestBuilderToUse,
  1329. GlobalRef& previewCaptureRequestToUse, GlobalRef& handlerToUse,
  1330. int autoFocusModeToUse)
  1331. : captureSession (captureSessionToUse),
  1332. captureRequestBuilder (captureRequestBuilderToUse),
  1333. previewCaptureRequest (previewCaptureRequestToUse),
  1334. handler (handlerToUse),
  1335. runnable (*this),
  1336. captureSessionPreviewCaptureCallback (createCaptureSessionCallback (true)),
  1337. captureSessionStillPictureCaptureCallback (createCaptureSessionCallback (false)),
  1338. autoFocusMode (autoFocusModeToUse)
  1339. {
  1340. }
  1341. void takePicture (const LocalRef<jobject>& stillPictureCaptureRequestToUse)
  1342. {
  1343. JUCE_CAMERA_LOG ("Taking picture...");
  1344. stillPictureCaptureRequest = GlobalRef (LocalRef<jobject>(stillPictureCaptureRequestToUse));
  1345. lockFocus();
  1346. }
  1347. private:
  1348. GlobalRef& captureSession;
  1349. GlobalRef& captureRequestBuilder;
  1350. GlobalRef& previewCaptureRequest;
  1351. GlobalRef& handler;
  1352. AndroidRunnable runnable;
  1353. GlobalRef delayedCaptureRunnable;
  1354. GlobalRef captureSessionPreviewCaptureCallback;
  1355. GlobalRef stillPictureCaptureRequest;
  1356. GlobalRef captureSessionStillPictureCaptureCallback;
  1357. int autoFocusMode;
  1358. //==============================================================================
  1359. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  1360. METHOD (constructor, "<init>", "(JZ)V") \
  1361. CALLBACK (cameraCaptureSessionCaptureCompletedCallback, "cameraCaptureSessionCaptureCompleted", "(JZLandroid/hardware/camera2/CameraCaptureSession;Landroid/hardware/camera2/CaptureRequest;Landroid/hardware/camera2/TotalCaptureResult;)V") \
  1362. CALLBACK (cameraCaptureSessionCaptureFailedCallback, "cameraCaptureSessionCaptureFailed", "(JZLandroid/hardware/camera2/CameraCaptureSession;Landroid/hardware/camera2/CaptureRequest;Landroid/hardware/camera2/CaptureFailure;)V") \
  1363. CALLBACK (cameraCaptureSessionCaptureProgressedCallback, "cameraCaptureSessionCaptureProgressed", "(JZLandroid/hardware/camera2/CameraCaptureSession;Landroid/hardware/camera2/CaptureRequest;Landroid/hardware/camera2/CaptureResult;)V") \
  1364. CALLBACK (cameraCaptureSessionCaptureStartedCallback, "cameraCaptureSessionCaptureStarted", "(JZLandroid/hardware/camera2/CameraCaptureSession;Landroid/hardware/camera2/CaptureRequest;JJ)V") \
  1365. CALLBACK (cameraCaptureSessionCaptureSequenceAbortedCallback, "cameraCaptureSessionCaptureSequenceAborted", "(JZLandroid/hardware/camera2/CameraCaptureSession;I)V") \
  1366. CALLBACK (cameraCaptureSessionCaptureSequenceCompletedCallback, "cameraCaptureSessionCaptureSequenceCompleted", "(JZLandroid/hardware/camera2/CameraCaptureSession;IJ)V")
  1367. DECLARE_JNI_CLASS_WITH_BYTECODE (CameraCaptureSessionCaptureCallback, "com/rmsl/juce/CameraCaptureSessionCaptureCallback", 21, CameraSupportByteCode, sizeof(CameraSupportByteCode))
  1368. #undef JNI_CLASS_MEMBERS
  1369. LocalRef<jobject> createCaptureSessionCallback (bool createPreviewSession)
  1370. {
  1371. return LocalRef<jobject>(getEnv()->NewObject (CameraCaptureSessionCaptureCallback,
  1372. CameraCaptureSessionCaptureCallback.constructor,
  1373. reinterpret_cast<jlong> (this),
  1374. createPreviewSession ? 1 : 0));
  1375. }
  1376. //==============================================================================
  1377. enum class State
  1378. {
  1379. idle = 0,
  1380. pendingFocusLock,
  1381. pendingExposurePrecapture,
  1382. pendingExposurePostPrecapture,
  1383. pictureTaken
  1384. };
  1385. State currentState = State::idle;
  1386. void lockFocus()
  1387. {
  1388. if (jniCheckHasExceptionOccurredAndClear())
  1389. return;
  1390. JUCE_CAMERA_LOG ("Performing auto-focus if possible...");
  1391. currentState = State::pendingFocusLock;
  1392. auto* env = getEnv();
  1393. // NB: auto-focus may be unavailable on a device, in which case it may have already
  1394. // automatically adjusted the exposure. We check for that in updateState().
  1395. static constexpr int controlAfTriggerStart = 1;
  1396. CaptureSession::setCaptureRequestBuilderIntegerKey (captureRequestBuilder.get(),
  1397. CaptureRequest.CONTROL_AF_TRIGGER,
  1398. controlAfTriggerStart);
  1399. auto previewRequest = LocalRef<jobject> (env->CallObjectMethod (captureRequestBuilder,
  1400. CaptureRequestBuilder.build));
  1401. env->CallIntMethod (captureSession, CameraCaptureSession.capture, previewRequest.get(),
  1402. captureSessionPreviewCaptureCallback.get(), handler.get());
  1403. }
  1404. void updateState (jobject captureResult)
  1405. {
  1406. // IllegalStateException can be thrown when accessing CaptureSession,
  1407. // claiming that capture session was already closed but we may not
  1408. // get relevant callback yet, so check for this and bailout when needed.
  1409. if (jniCheckHasExceptionOccurredAndClear())
  1410. return;
  1411. switch (currentState)
  1412. {
  1413. case State::pendingFocusLock:
  1414. {
  1415. JUCE_CAMERA_LOG ("Still picture capture, updateState(), State::pendingFocusLock...");
  1416. auto controlAfStateValue = getCaptureResultIntegerKeyValue (CaptureResult.CONTROL_AF_STATE, captureResult);
  1417. if (controlAfStateValue.get() == nullptr)
  1418. {
  1419. captureStillPictureDelayed();
  1420. return;
  1421. }
  1422. auto autoToFocusNotAvailable = autoFocusMode == 0;
  1423. if (autoToFocusNotAvailable || autoFocusHasFinished (controlAfStateValue))
  1424. {
  1425. auto controlAeStateIntValue = getControlAEState (captureResult);
  1426. static constexpr int controlAeStateConverged = 2;
  1427. if (controlAeStateIntValue == -1 || controlAeStateIntValue == controlAeStateConverged)
  1428. {
  1429. currentState = State::pictureTaken;
  1430. captureStillPictureDelayed();
  1431. }
  1432. else
  1433. {
  1434. runPrecaptureSequence();
  1435. }
  1436. }
  1437. break;
  1438. }
  1439. case State::pendingExposurePrecapture:
  1440. {
  1441. JUCE_CAMERA_LOG ("Still picture capture, updateState(), State::pendingExposurePrecapture...");
  1442. auto controlAeStateIntValue = getControlAEState (captureResult);
  1443. static constexpr int controlAeStateFlashRequired = 4;
  1444. static constexpr int controlAeStatePrecapture = 5;
  1445. if (controlAeStateIntValue == -1 || controlAeStateIntValue == controlAeStateFlashRequired
  1446. || controlAeStateIntValue == controlAeStatePrecapture)
  1447. {
  1448. currentState = State::pendingExposurePostPrecapture;
  1449. }
  1450. break;
  1451. }
  1452. case State::pendingExposurePostPrecapture:
  1453. {
  1454. JUCE_CAMERA_LOG ("Still picture capture, updateState(), State::pendingExposurePostPrecapture...");
  1455. auto controlAeStateIntValue = getControlAEState (captureResult);
  1456. static constexpr int controlAeStatePrecapture = 5;
  1457. if (controlAeStateIntValue == -1 || controlAeStateIntValue != controlAeStatePrecapture)
  1458. {
  1459. currentState = State::pictureTaken;
  1460. captureStillPictureDelayed();
  1461. }
  1462. break;
  1463. }
  1464. case State::idle:
  1465. case State::pictureTaken:
  1466. { /* do nothing */ break; }
  1467. };
  1468. }
  1469. static int getControlAEState (jobject captureResult)
  1470. {
  1471. auto controlAeStateValue = getCaptureResultIntegerKeyValue (CaptureResult.CONTROL_AE_STATE, captureResult);
  1472. return controlAeStateValue.get() != nullptr
  1473. ? getEnv()->CallIntMethod (controlAeStateValue, JavaInteger.intValue) : -1;
  1474. }
  1475. static bool autoFocusHasFinished (const LocalRef<jobject>& controlAfStateValue)
  1476. {
  1477. static constexpr int controlAfStateFocusedLocked = 4;
  1478. static constexpr int controlAfStateNotFocusedLocked = 5;
  1479. auto controlAfStateIntValue = getEnv()->CallIntMethod (controlAfStateValue, JavaInteger.intValue);
  1480. return controlAfStateIntValue == controlAfStateFocusedLocked || controlAfStateIntValue == controlAfStateNotFocusedLocked;
  1481. }
  1482. static LocalRef<jobject> getCaptureResultIntegerKeyValue (jfieldID key, jobject captureResult)
  1483. {
  1484. auto* env = getEnv();
  1485. auto jKey = LocalRef<jobject> (env->GetStaticObjectField (CaptureResult, key));
  1486. return LocalRef<jobject> (env->CallObjectMethod (captureResult, CaptureResult.get, jKey.get()));
  1487. }
  1488. void captureStillPictureDelayed()
  1489. {
  1490. if (jniCheckHasExceptionOccurredAndClear())
  1491. return;
  1492. JUCE_CAMERA_LOG ("Still picture capture, device ready, capturing now...");
  1493. auto* env = getEnv();
  1494. env->CallVoidMethod (captureSession, CameraCaptureSession.stopRepeating);
  1495. if (jniCheckHasExceptionOccurredAndClear())
  1496. return;
  1497. env->CallVoidMethod (captureSession, CameraCaptureSession.abortCaptures);
  1498. if (jniCheckHasExceptionOccurredAndClear())
  1499. return;
  1500. // Delay still picture capture for devices that can't handle it right after
  1501. // stopRepeating/abortCaptures calls.
  1502. if (delayedCaptureRunnable.get() == nullptr)
  1503. delayedCaptureRunnable = GlobalRef (CreateJavaInterface (&runnable, "java/lang/Runnable"));
  1504. env->CallBooleanMethod (handler, AndroidHandler.postDelayed, delayedCaptureRunnable.get(), (jlong) 200);
  1505. }
  1506. void runPrecaptureSequence()
  1507. {
  1508. if (jniCheckHasExceptionOccurredAndClear())
  1509. return;
  1510. auto* env = getEnv();
  1511. static constexpr int controlAePrecaptureTriggerStart = 1;
  1512. CaptureSession::setCaptureRequestBuilderIntegerKey (captureRequestBuilder.get(),
  1513. CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
  1514. controlAePrecaptureTriggerStart);
  1515. currentState = State::pendingExposurePrecapture;
  1516. auto previewRequest = LocalRef<jobject> (env->CallObjectMethod (captureRequestBuilder,
  1517. CaptureRequestBuilder.build));
  1518. env->CallIntMethod (captureSession, CameraCaptureSession.capture, previewRequest.get(),
  1519. captureSessionPreviewCaptureCallback.get(), handler.get());
  1520. }
  1521. void unlockFocus()
  1522. {
  1523. if (jniCheckHasExceptionOccurredAndClear())
  1524. return;
  1525. JUCE_CAMERA_LOG ("Unlocking focus...");
  1526. currentState = State::idle;
  1527. auto* env = getEnv();
  1528. static constexpr int controlAfTriggerCancel = 2;
  1529. CaptureSession::setCaptureRequestBuilderIntegerKey (captureRequestBuilder.get(),
  1530. CaptureRequest.CONTROL_AF_TRIGGER,
  1531. controlAfTriggerCancel);
  1532. auto resetAutoFocusRequest = LocalRef<jobject> (env->CallObjectMethod (captureRequestBuilder,
  1533. CaptureRequestBuilder.build));
  1534. env->CallIntMethod (captureSession, CameraCaptureSession.capture, resetAutoFocusRequest.get(),
  1535. nullptr, handler.get());
  1536. if (jniCheckHasExceptionOccurredAndClear())
  1537. return;
  1538. // NB: for preview, using preview capture request again
  1539. env->CallIntMethod (captureSession, CameraCaptureSession.setRepeatingRequest, previewCaptureRequest.get(),
  1540. nullptr, handler.get());
  1541. }
  1542. //==============================================================================
  1543. void run() override
  1544. {
  1545. captureStillPicture();
  1546. }
  1547. void captureStillPicture()
  1548. {
  1549. getEnv()->CallIntMethod (captureSession, CameraCaptureSession.capture,
  1550. stillPictureCaptureRequest.get(), captureSessionStillPictureCaptureCallback.get(),
  1551. nullptr);
  1552. }
  1553. //==============================================================================
  1554. void cameraCaptureSessionCaptureCompleted (bool isPreview, jobject session, jobject request, jobject result)
  1555. {
  1556. JUCE_CAMERA_LOG ("cameraCaptureSessionCaptureCompleted()");
  1557. ignoreUnused (session, request);
  1558. if (isPreview)
  1559. updateState (result);
  1560. else if (currentState != State::idle)
  1561. unlockFocus();
  1562. }
  1563. void cameraCaptureSessionCaptureFailed (bool isPreview, jobject session, jobject request, jobject failure)
  1564. {
  1565. JUCE_CAMERA_LOG ("cameraCaptureSessionCaptureFailed()");
  1566. ignoreUnused (isPreview, session, request, failure);
  1567. }
  1568. void cameraCaptureSessionCaptureProgressed (bool isPreview, jobject session, jobject request, jobject partialResult)
  1569. {
  1570. JUCE_CAMERA_LOG ("cameraCaptureSessionCaptureProgressed()");
  1571. ignoreUnused (session, request);
  1572. if (isPreview)
  1573. updateState (partialResult);
  1574. }
  1575. void cameraCaptureSessionCaptureSequenceAborted (bool isPreview, jobject session, int sequenceId)
  1576. {
  1577. JUCE_CAMERA_LOG ("cameraCaptureSessionCaptureSequenceAborted()");
  1578. ignoreUnused (isPreview, isPreview, session, sequenceId);
  1579. }
  1580. void cameraCaptureSessionCaptureSequenceCompleted (bool isPreview, jobject session, int sequenceId, int64 frameNumber)
  1581. {
  1582. JUCE_CAMERA_LOG ("cameraCaptureSessionCaptureSequenceCompleted()");
  1583. ignoreUnused (isPreview, session, sequenceId, frameNumber);
  1584. }
  1585. void cameraCaptureSessionCaptureStarted (bool isPreview, jobject session, jobject request, int64 timestamp, int64 frameNumber)
  1586. {
  1587. JUCE_CAMERA_LOG ("cameraCaptureSessionCaptureStarted()");
  1588. ignoreUnused (isPreview, session, request, timestamp, frameNumber);
  1589. }
  1590. //==============================================================================
  1591. static void cameraCaptureSessionCaptureCompletedCallback (JNIEnv*, jobject /*object*/, jlong host, jboolean isPreview, jobject rawSession, jobject rawRequest, jobject rawResult)
  1592. {
  1593. if (auto* myself = reinterpret_cast<StillPictureTaker*> (host))
  1594. {
  1595. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1596. LocalRef<jobject> request (getEnv()->NewLocalRef(rawRequest));
  1597. LocalRef<jobject> result (getEnv()->NewLocalRef(rawResult));
  1598. myself->cameraCaptureSessionCaptureCompleted (isPreview != 0, session, request, result);
  1599. }
  1600. }
  1601. static void cameraCaptureSessionCaptureFailedCallback (JNIEnv*, jobject /*object*/, jlong host, jboolean isPreview, jobject rawSession, jobject rawRequest, jobject rawResult)
  1602. {
  1603. if (auto* myself = reinterpret_cast<StillPictureTaker*> (host))
  1604. {
  1605. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1606. LocalRef<jobject> request (getEnv()->NewLocalRef(rawRequest));
  1607. LocalRef<jobject> result (getEnv()->NewLocalRef(rawResult));
  1608. myself->cameraCaptureSessionCaptureFailed (isPreview != 0, session, request, result);
  1609. }
  1610. }
  1611. static void cameraCaptureSessionCaptureProgressedCallback (JNIEnv*, jobject /*object*/, jlong host, jboolean isPreview, jobject rawSession, jobject rawRequest, jobject rawResult)
  1612. {
  1613. if (auto* myself = reinterpret_cast<StillPictureTaker*> (host))
  1614. {
  1615. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1616. LocalRef<jobject> request (getEnv()->NewLocalRef(rawRequest));
  1617. LocalRef<jobject> result (getEnv()->NewLocalRef(rawResult));
  1618. myself->cameraCaptureSessionCaptureProgressed (isPreview != 0, session, request, result);
  1619. }
  1620. }
  1621. static void cameraCaptureSessionCaptureSequenceAbortedCallback (JNIEnv*, jobject /*object*/, jlong host, jboolean isPreview, jobject rawSession, jint sequenceId)
  1622. {
  1623. if (auto* myself = reinterpret_cast<StillPictureTaker*> (host))
  1624. {
  1625. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1626. myself->cameraCaptureSessionCaptureSequenceAborted (isPreview != 0, session, sequenceId);
  1627. }
  1628. }
  1629. static void cameraCaptureSessionCaptureSequenceCompletedCallback (JNIEnv*, jobject /*object*/, jlong host, jboolean isPreview, jobject rawSession, jint sequenceId, jlong frameNumber)
  1630. {
  1631. if (auto* myself = reinterpret_cast<StillPictureTaker*> (host))
  1632. {
  1633. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1634. myself->cameraCaptureSessionCaptureSequenceCompleted (isPreview != 0, session, sequenceId, frameNumber);
  1635. }
  1636. }
  1637. static void cameraCaptureSessionCaptureStartedCallback (JNIEnv*, jobject /*object*/, jlong host, jboolean isPreview, jobject rawSession, jobject rawRequest, jlong timestamp, jlong frameNumber)
  1638. {
  1639. if (auto* myself = reinterpret_cast<StillPictureTaker*> (host))
  1640. {
  1641. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1642. LocalRef<jobject> request (getEnv()->NewLocalRef(rawRequest));
  1643. myself->cameraCaptureSessionCaptureStarted (isPreview != 0, session, request, timestamp, frameNumber);
  1644. }
  1645. }
  1646. };
  1647. //==============================================================================
  1648. ScopedCameraDevice& scopedCameraDevice;
  1649. ConfiguredCallback& configuredCallback;
  1650. GlobalRef& handler;
  1651. GlobalRef captureRequestBuilder;
  1652. GlobalRef previewCaptureRequest;
  1653. GlobalRef captureSessionStateCallback;
  1654. int autoFocusMode;
  1655. GlobalRef captureSession;
  1656. CriticalSection captureSessionLock;
  1657. Atomic<int> pendingClose { 0 };
  1658. std::unique_ptr<StillPictureTaker> stillPictureTaker;
  1659. WaitableEvent closedEvent;
  1660. JUCE_DECLARE_WEAK_REFERENCEABLE (CaptureSession)
  1661. //==============================================================================
  1662. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  1663. METHOD (constructor, "<init>", "(J)V") \
  1664. CALLBACK(cameraCaptureSessionActiveCallback, "cameraCaptureSessionActive", "(JLandroid/hardware/camera2/CameraCaptureSession;)V") \
  1665. CALLBACK(cameraCaptureSessionClosedCallback, "cameraCaptureSessionClosed", "(JLandroid/hardware/camera2/CameraCaptureSession;)V") \
  1666. CALLBACK(cameraCaptureSessionConfigureFailedCallback, "cameraCaptureSessionConfigureFailed", "(JLandroid/hardware/camera2/CameraCaptureSession;)V") \
  1667. CALLBACK(cameraCaptureSessionConfiguredCallback, "cameraCaptureSessionConfigured", "(JLandroid/hardware/camera2/CameraCaptureSession;)V") \
  1668. CALLBACK(cameraCaptureSessionReadyCallback, "cameraCaptureSessionReady", "(JLandroid/hardware/camera2/CameraCaptureSession;)V")
  1669. DECLARE_JNI_CLASS_WITH_MIN_SDK (CameraCaptureSessionStateCallback, "com/rmsl/juce/CameraCaptureSessionStateCallback", 21)
  1670. #undef JNI_CLASS_MEMBERS
  1671. //==============================================================================
  1672. CaptureSession (ScopedCameraDevice& scopedCameraDeviceToUse, ConfiguredCallback& configuredCallbackToUse,
  1673. const LocalRef<jobject>& surfacesList, GlobalRef& handlerToUse,
  1674. int captureSessionTemplate, int autoFocusModeToUse)
  1675. : scopedCameraDevice (scopedCameraDeviceToUse),
  1676. configuredCallback (configuredCallbackToUse),
  1677. handler (handlerToUse),
  1678. captureRequestBuilder (LocalRef<jobject> (getEnv()->CallObjectMethod (scopedCameraDevice.cameraDevice,
  1679. AndroidCameraDevice.createCaptureRequest,
  1680. (jint) captureSessionTemplate))),
  1681. captureSessionStateCallback (LocalRef<jobject> (getEnv()->NewObject (CameraCaptureSessionStateCallback,
  1682. CameraCaptureSessionStateCallback.constructor,
  1683. reinterpret_cast<jlong> (this)))),
  1684. autoFocusMode (autoFocusModeToUse)
  1685. {
  1686. auto* env = getEnv();
  1687. env->CallVoidMethod (scopedCameraDevice.cameraDevice, AndroidCameraDevice.createCaptureSession,
  1688. surfacesList.get(), captureSessionStateCallback.get(), handler.get());
  1689. static constexpr int controlModeAuto = 1;
  1690. setCaptureRequestBuilderIntegerKey (captureRequestBuilder.get(), CaptureRequest.CONTROL_MODE, controlModeAuto);
  1691. setCaptureRequestBuilderIntegerKey (captureRequestBuilder.get(), CaptureRequest.CONTROL_AF_MODE, autoFocusMode);
  1692. }
  1693. static void setCaptureRequestBuilderIntegerKey (jobject captureRequestBuilder, jfieldID key, int value)
  1694. {
  1695. auto* env = getEnv();
  1696. auto jKey = LocalRef<jobject> (env->GetStaticObjectField (CaptureRequest, key));
  1697. auto jValue = LocalRef<jobject> (env->CallStaticObjectMethod (JavaInteger, JavaInteger.valueOf, (jint) value));
  1698. env->CallVoidMethod (captureRequestBuilder, CaptureRequestBuilder.set, jKey.get(), jValue.get());
  1699. }
  1700. void cameraCaptureSessionActive (jobject session)
  1701. {
  1702. JUCE_CAMERA_LOG ("cameraCaptureSessionActive()");
  1703. ignoreUnused (session);
  1704. }
  1705. void cameraCaptureSessionClosed (jobject session)
  1706. {
  1707. JUCE_CAMERA_LOG ("cameraCaptureSessionClosed()");
  1708. ignoreUnused (session);
  1709. closedEvent.signal();
  1710. }
  1711. void cameraCaptureSessionConfigureFailed (jobject session)
  1712. {
  1713. JUCE_CAMERA_LOG ("cameraCaptureSessionConfigureFailed()");
  1714. ignoreUnused (session);
  1715. WeakReference<CaptureSession> weakRef (this);
  1716. MessageManager::callAsync ([this, weakRef]()
  1717. {
  1718. if (weakRef == nullptr)
  1719. return;
  1720. configuredCallback.captureSessionConfigured (nullptr);
  1721. });
  1722. }
  1723. void cameraCaptureSessionConfigured (const LocalRef<jobject>& session)
  1724. {
  1725. JUCE_CAMERA_LOG ("cameraCaptureSessionConfigured()");
  1726. if (pendingClose.get() == 1)
  1727. {
  1728. // Already closing, bailout.
  1729. closedEvent.signal();
  1730. GlobalRef s (session);
  1731. MessageManager::callAsync ([s]()
  1732. {
  1733. getEnv()->CallVoidMethod (s, CameraCaptureSession.close);
  1734. });
  1735. return;
  1736. }
  1737. {
  1738. const ScopedLock lock (captureSessionLock);
  1739. captureSession = GlobalRef (session);
  1740. }
  1741. WeakReference<CaptureSession> weakRef (this);
  1742. MessageManager::callAsync ([this, weakRef]()
  1743. {
  1744. if (weakRef == nullptr)
  1745. return;
  1746. stillPictureTaker.reset (new StillPictureTaker (captureSession, captureRequestBuilder,
  1747. previewCaptureRequest, handler, autoFocusMode));
  1748. configuredCallback.captureSessionConfigured (this);
  1749. });
  1750. }
  1751. void cameraCaptureSessionReady (const LocalRef<jobject>& session)
  1752. {
  1753. JUCE_CAMERA_LOG ("cameraCaptureSessionReady()");
  1754. ignoreUnused (session);
  1755. }
  1756. //==============================================================================
  1757. static void cameraCaptureSessionActiveCallback (JNIEnv*, jobject, jlong host, jobject rawSession)
  1758. {
  1759. if (auto* myself = reinterpret_cast<CaptureSession*> (host))
  1760. {
  1761. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1762. myself->cameraCaptureSessionActive (session);
  1763. }
  1764. }
  1765. static void cameraCaptureSessionClosedCallback (JNIEnv*, jobject, jlong host, jobject rawSession)
  1766. {
  1767. if (auto* myself = reinterpret_cast<CaptureSession*> (host))
  1768. {
  1769. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1770. myself->cameraCaptureSessionClosed (session);
  1771. }
  1772. }
  1773. static void cameraCaptureSessionConfigureFailedCallback (JNIEnv*, jobject, jlong host, jobject rawSession)
  1774. {
  1775. if (auto* myself = reinterpret_cast<CaptureSession*> (host))
  1776. {
  1777. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1778. myself->cameraCaptureSessionConfigureFailed (session);
  1779. }
  1780. }
  1781. static void cameraCaptureSessionConfiguredCallback (JNIEnv*, jobject, jlong host, jobject rawSession)
  1782. {
  1783. if (auto* myself = reinterpret_cast<CaptureSession*> (host))
  1784. {
  1785. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1786. myself->cameraCaptureSessionConfigured (session);
  1787. }
  1788. }
  1789. static void cameraCaptureSessionReadyCallback (JNIEnv*, jobject, jlong host, jobject rawSession)
  1790. {
  1791. if (auto* myself = reinterpret_cast<CaptureSession*> (host))
  1792. {
  1793. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1794. myself->cameraCaptureSessionReady (session);
  1795. }
  1796. }
  1797. //==============================================================================
  1798. friend class ScopedCameraDevice;
  1799. JUCE_DECLARE_NON_COPYABLE (CaptureSession)
  1800. };
  1801. //==============================================================================
  1802. ScopedCameraDevice (Pimpl& ownerToUse, const String& cameraIdToUse, GlobalRef& cameraManagerToUse,
  1803. GlobalRef& handlerToUse, int autoFocusModeToUse)
  1804. : owner (ownerToUse),
  1805. cameraId (cameraIdToUse),
  1806. cameraManager (cameraManagerToUse),
  1807. handler (handlerToUse),
  1808. cameraStateCallback (createCameraStateCallbackObject()),
  1809. autoFocusMode (autoFocusModeToUse)
  1810. {
  1811. open();
  1812. }
  1813. ~ScopedCameraDevice()
  1814. {
  1815. close();
  1816. }
  1817. void open()
  1818. {
  1819. pendingOpen.set (1);
  1820. auto* env = getEnv();
  1821. env->CallVoidMethod (cameraManager, CameraManager.openCamera,
  1822. javaString (cameraId).get(),
  1823. cameraStateCallback.get(), handler.get());
  1824. // If something went wrong we will be pinged in cameraDeviceStateError()
  1825. // callback, silence the redundant exception.
  1826. jniCheckHasExceptionOccurredAndClear();
  1827. }
  1828. void close()
  1829. {
  1830. if (pendingClose.compareAndSetBool (1, 0))
  1831. {
  1832. auto* env = getEnv();
  1833. if (cameraDevice.get() != nullptr)
  1834. {
  1835. env->CallVoidMethod (cameraDevice, AndroidCameraDevice.close);
  1836. closedEvent.wait (-1);
  1837. }
  1838. pendingClose.set (0);
  1839. pendingOpen .set (0);
  1840. cameraDevice.clear();
  1841. }
  1842. }
  1843. bool openedOk() const { return cameraDevice != nullptr; }
  1844. bool hasErrorOccurred() const { return fatalErrorOccurred.get(); }
  1845. CaptureSession* createCaptureSession (CaptureSession::ConfiguredCallback& cc,
  1846. const LocalRef<jobject>& surfacesList,
  1847. GlobalRef& handlerToUse,
  1848. int captureSessionTemplate)
  1849. {
  1850. if (! openedOk())
  1851. {
  1852. jassertfalse;
  1853. return nullptr;
  1854. }
  1855. return new CaptureSession (*this, cc, surfacesList, handlerToUse, captureSessionTemplate, autoFocusMode);
  1856. }
  1857. private:
  1858. Pimpl& owner;
  1859. const String cameraId;
  1860. GlobalRef& cameraManager;
  1861. GlobalRef& handler;
  1862. GlobalRef cameraStateCallback;
  1863. int autoFocusMode;
  1864. GlobalRef cameraDevice;
  1865. Atomic<int> pendingOpen { 0 };
  1866. Atomic<int> pendingClose { 0 };
  1867. Atomic<int> fatalErrorOccurred { 0 };
  1868. String openError;
  1869. WaitableEvent closedEvent;
  1870. //==============================================================================
  1871. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  1872. METHOD (constructor, "<init>", "(J)V") \
  1873. CALLBACK (cameraDeviceStateClosedCallback, "cameraDeviceStateClosed", "(JLandroid/hardware/camera2/CameraDevice;)V") \
  1874. CALLBACK (cameraDeviceStateDisconnectedCallback, "cameraDeviceStateDisconnected", "(JLandroid/hardware/camera2/CameraDevice;)V") \
  1875. CALLBACK (cameraDeviceStateErrorCallback, "cameraDeviceStateError", "(JLandroid/hardware/camera2/CameraDevice;I)V") \
  1876. CALLBACK (cameraDeviceStateOpenedCallback, "cameraDeviceStateOpened", "(JLandroid/hardware/camera2/CameraDevice;)V")
  1877. DECLARE_JNI_CLASS_WITH_MIN_SDK (CameraDeviceStateCallback, "com/rmsl/juce/CameraDeviceStateCallback", 21)
  1878. #undef JNI_CLASS_MEMBERS
  1879. LocalRef<jobject> createCameraStateCallbackObject()
  1880. {
  1881. return LocalRef<jobject> (getEnv()->NewObject (CameraDeviceStateCallback,
  1882. CameraDeviceStateCallback.constructor,
  1883. reinterpret_cast<jlong> (this)));
  1884. }
  1885. //==============================================================================
  1886. void cameraDeviceStateClosed()
  1887. {
  1888. JUCE_CAMERA_LOG ("cameraDeviceStateClosed()");
  1889. closedEvent.signal();
  1890. }
  1891. void cameraDeviceStateDisconnected()
  1892. {
  1893. JUCE_CAMERA_LOG ("cameraDeviceStateDisconnected()");
  1894. if (pendingOpen.compareAndSetBool (0, 1))
  1895. {
  1896. openError = "Device disconnected";
  1897. notifyOpenResult();
  1898. }
  1899. MessageManager::callAsync ([this]() { close(); });
  1900. }
  1901. void cameraDeviceStateError (int errorCode)
  1902. {
  1903. String error = cameraErrorCodeToString (errorCode);
  1904. JUCE_CAMERA_LOG ("cameraDeviceStateError(), error: " + error);
  1905. if (pendingOpen.compareAndSetBool (0, 1))
  1906. {
  1907. openError = error;
  1908. notifyOpenResult();
  1909. }
  1910. fatalErrorOccurred.set (1);
  1911. MessageManager::callAsync ([this, error]()
  1912. {
  1913. owner.cameraDeviceError (error);
  1914. close();
  1915. });
  1916. }
  1917. void cameraDeviceStateOpened (const LocalRef<jobject>& cameraDeviceToUse)
  1918. {
  1919. JUCE_CAMERA_LOG ("cameraDeviceStateOpened()");
  1920. pendingOpen.set (0);
  1921. cameraDevice = GlobalRef (cameraDeviceToUse);
  1922. notifyOpenResult();
  1923. }
  1924. void notifyOpenResult()
  1925. {
  1926. MessageManager::callAsync ([this]() { owner.cameraOpenFinished (openError); });
  1927. }
  1928. //==============================================================================
  1929. static void JNICALL cameraDeviceStateClosedCallback (JNIEnv*, jobject, jlong host, jobject)
  1930. {
  1931. if (auto* myself = reinterpret_cast<ScopedCameraDevice*>(host))
  1932. myself->cameraDeviceStateClosed();
  1933. }
  1934. static void JNICALL cameraDeviceStateDisconnectedCallback (JNIEnv*, jobject, jlong host, jobject)
  1935. {
  1936. if (auto* myself = reinterpret_cast<ScopedCameraDevice*>(host))
  1937. myself->cameraDeviceStateDisconnected();
  1938. }
  1939. static void JNICALL cameraDeviceStateErrorCallback (JNIEnv*, jobject, jlong host, jobject, jint error)
  1940. {
  1941. if (auto* myself = reinterpret_cast<ScopedCameraDevice*>(host))
  1942. myself->cameraDeviceStateError (error);
  1943. }
  1944. static void JNICALL cameraDeviceStateOpenedCallback (JNIEnv*, jobject, jlong host, jobject rawCamera)
  1945. {
  1946. if (auto* myself = reinterpret_cast<ScopedCameraDevice*>(host))
  1947. {
  1948. LocalRef<jobject> camera(getEnv()->NewLocalRef(rawCamera));
  1949. myself->cameraDeviceStateOpened (camera);
  1950. }
  1951. }
  1952. };
  1953. //==============================================================================
  1954. struct CaptureSessionModeBase
  1955. {
  1956. virtual ~CaptureSessionModeBase() = default;
  1957. virtual bool isVideoRecordSession() const = 0;
  1958. virtual void triggerStillPictureCapture() = 0;
  1959. };
  1960. //==============================================================================
  1961. template <typename Mode>
  1962. struct CaptureSessionMode : public CaptureSessionModeBase,
  1963. private PreviewDisplay::Listener,
  1964. private ScopedCameraDevice::CaptureSession::ConfiguredCallback
  1965. {
  1966. ~CaptureSessionMode() override
  1967. {
  1968. captureSession.reset();
  1969. previewDisplay.removeListener (this);
  1970. }
  1971. bool isVideoRecordSession() const override
  1972. {
  1973. return Mode::isVideoRecord();
  1974. }
  1975. void triggerStillPictureCapture() override
  1976. {
  1977. if (captureSession == nullptr)
  1978. {
  1979. // The capture session must be ready before taking a still picture.
  1980. // Did you remember to create and show a preview display?
  1981. jassertfalse;
  1982. return;
  1983. }
  1984. crtp().takeStillPicture();
  1985. }
  1986. protected:
  1987. CaptureSessionMode (Pimpl& ownerToUse, ScopedCameraDevice& cameraDeviceToUse,
  1988. GlobalRef& handlerToUse, PreviewDisplay& pd, int cameraSensorOrientationToUse,
  1989. int cameraLensFacingToUse, StreamConfigurationMap& streamConfigurationMapToUse)
  1990. : owner (ownerToUse),
  1991. scopedCameraDevice (cameraDeviceToUse),
  1992. handler (handlerToUse),
  1993. previewDisplay (pd),
  1994. cameraSensorOrientation (cameraSensorOrientationToUse),
  1995. cameraLensFacing (cameraLensFacingToUse),
  1996. streamConfigurationMap (streamConfigurationMapToUse)
  1997. {
  1998. WeakReference<CaptureSessionMode<Mode>> weakRef (this);
  1999. if (weakRef == nullptr)
  2000. return;
  2001. // async so that the object is fully constructed before the callback gets invoked
  2002. MessageManager::callAsync ([this, weakRef]()
  2003. {
  2004. if (weakRef == nullptr)
  2005. return;
  2006. previewDisplay.addListener (this);
  2007. });
  2008. }
  2009. Mode& crtp() { return static_cast<Mode&> (*this); }
  2010. void previewDisplayReady() override
  2011. {
  2012. jassert (previewDisplay.isReady());
  2013. JUCE_CAMERA_LOG ("previewDisplayReady()");
  2014. // close previous capture session first
  2015. captureSession.reset();
  2016. if (scopedCameraDevice.hasErrorOccurred())
  2017. {
  2018. JUCE_CAMERA_LOG ("Device error detected, not recreating a new camera session. The device needs to be reopened.");
  2019. return;
  2020. }
  2021. captureSession.reset (scopedCameraDevice.createCaptureSession (*this, crtp().getCaptureSessionSurfaces(),
  2022. handler, Mode::getTemplate()));
  2023. }
  2024. void previewDisplayAboutToBeDestroyed() override
  2025. {
  2026. JUCE_CAMERA_LOG ("previewDisplayAboutToBeDestroyed()");
  2027. stopPreview();
  2028. }
  2029. void captureSessionConfigured (ScopedCameraDevice::CaptureSession* session) override
  2030. {
  2031. if (session == nullptr)
  2032. {
  2033. owner.cameraDeviceError ("Failed to configure camera session.");
  2034. return;
  2035. }
  2036. jassert (session == captureSession.get());
  2037. startSession();
  2038. }
  2039. void startSession()
  2040. {
  2041. if (! captureSession->start (crtp().getTargetSurfaces(), handler))
  2042. {
  2043. jassertfalse;
  2044. JUCE_CAMERA_LOG ("Could not start capture session");
  2045. }
  2046. crtp().sessionStarted();
  2047. }
  2048. void stopPreview()
  2049. {
  2050. if (captureSession != nullptr)
  2051. {
  2052. auto session = captureSession->getNativeSession();
  2053. auto* env = getEnv();
  2054. env->CallVoidMethod (session, CameraCaptureSession.stopRepeating);
  2055. if (jniCheckHasExceptionOccurredAndClear())
  2056. return;
  2057. env->CallVoidMethod (session, CameraCaptureSession.abortCaptures);
  2058. jniCheckHasExceptionOccurredAndClear();
  2059. }
  2060. }
  2061. Pimpl& owner;
  2062. ScopedCameraDevice& scopedCameraDevice;
  2063. GlobalRef& handler;
  2064. PreviewDisplay& previewDisplay;
  2065. int cameraSensorOrientation;
  2066. int cameraLensFacing;
  2067. StreamConfigurationMap& streamConfigurationMap;
  2068. std::unique_ptr<ScopedCameraDevice::CaptureSession> captureSession;
  2069. JUCE_DECLARE_WEAK_REFERENCEABLE (CaptureSessionMode<Mode>)
  2070. };
  2071. //==============================================================================
  2072. struct CaptureSessionPreviewMode : public CaptureSessionMode<CaptureSessionPreviewMode>
  2073. {
  2074. CaptureSessionPreviewMode (Pimpl& ownerToUse, ScopedCameraDevice& cameraDeviceToUse, GlobalRef& handlerToUse,
  2075. PreviewDisplay& pd, ImageReader& ir, int sensorOrientation,
  2076. int cameraLensFacingToUse, StreamConfigurationMap& streamConfigurationMapToUse)
  2077. : CaptureSessionMode<CaptureSessionPreviewMode> (ownerToUse, cameraDeviceToUse, handlerToUse, pd,
  2078. sensorOrientation, cameraLensFacingToUse, streamConfigurationMapToUse),
  2079. imageReader (ir)
  2080. {
  2081. }
  2082. // Surfaces passed to newly created capture session.
  2083. LocalRef<jobject> getCaptureSessionSurfaces() const
  2084. {
  2085. auto* env = getEnv();
  2086. auto previewSurface = LocalRef<jobject> (previewDisplay.createSurface());
  2087. auto imageSurface = LocalRef<jobject> (imageReader.getSurface());
  2088. auto arrayList = LocalRef<jobject> (env->NewObject (JavaArrayList, JavaArrayList.constructor, 2));
  2089. env->CallBooleanMethod (arrayList, JavaArrayList.add, previewSurface.get());
  2090. env->CallBooleanMethod (arrayList, JavaArrayList.add, imageSurface.get());
  2091. auto supported = streamConfigurationMap.isOutputSupportedForSurface (imageSurface);
  2092. // Output surface is not supported by this device, still image capture will not work!
  2093. jassert (supported);
  2094. return arrayList;
  2095. }
  2096. // Surfaces set as target during capture.
  2097. LocalRef<jobject> getTargetSurfaces() const
  2098. {
  2099. auto* env = getEnv();
  2100. auto previewSurface = LocalRef<jobject> (previewDisplay.createSurface());
  2101. auto arrayList = LocalRef<jobject> (env->NewObject (JavaArrayList, JavaArrayList.constructor, 1));
  2102. env->CallBooleanMethod (arrayList, JavaArrayList.add, previewSurface.get());
  2103. return arrayList;
  2104. }
  2105. static int getTemplate()
  2106. {
  2107. static constexpr int templatePreview = 1;
  2108. return templatePreview;
  2109. }
  2110. static bool isVideoRecord() { return false; }
  2111. void sessionStarted() {}
  2112. void takeStillPicture()
  2113. {
  2114. imageReader.resetNotificationFlag();
  2115. captureSession->takeStillPicture (imageReader.getSurface());
  2116. }
  2117. private:
  2118. ImageReader& imageReader;
  2119. };
  2120. //==============================================================================
  2121. struct CaptureSessionVideoRecordingMode : public CaptureSessionMode<CaptureSessionVideoRecordingMode>
  2122. {
  2123. CaptureSessionVideoRecordingMode (Pimpl& ownerToUse, ScopedCameraDevice& cameraDeviceToUse, GlobalRef& handlerToUse,
  2124. PreviewDisplay& pd, MediaRecorder& mr, int sensorOrientation,
  2125. int cameraLensFacingToUse, StreamConfigurationMap& streamConfigurationMapToUse)
  2126. : CaptureSessionMode<CaptureSessionVideoRecordingMode> (ownerToUse, cameraDeviceToUse, handlerToUse, pd,
  2127. sensorOrientation, cameraLensFacingToUse, streamConfigurationMapToUse),
  2128. mediaRecorder (mr)
  2129. {
  2130. }
  2131. ~CaptureSessionVideoRecordingMode()
  2132. {
  2133. // We need to explicitly stop the preview before stopping the media recorder,
  2134. // because legacy devices can't handle recording stop before stopping the preview.
  2135. stopPreview();
  2136. mediaRecorder.stop();
  2137. }
  2138. // Surfaces passed to newly created capture session.
  2139. LocalRef<jobject> getCaptureSessionSurfaces() const
  2140. {
  2141. auto* env = getEnv();
  2142. auto previewSurface = LocalRef<jobject> (previewDisplay.createSurface());
  2143. auto mediaRecorderSurface = LocalRef<jobject> (mediaRecorder.getSurface());
  2144. auto arrayList = LocalRef<jobject> (env->NewObject (JavaArrayList, JavaArrayList.constructor, 2));
  2145. env->CallBooleanMethod (arrayList, JavaArrayList.add, previewSurface.get());
  2146. env->CallBooleanMethod (arrayList, JavaArrayList.add, mediaRecorderSurface.get());
  2147. return arrayList;
  2148. }
  2149. // Surfaces set as target during capture.
  2150. LocalRef<jobject> getTargetSurfaces() const
  2151. {
  2152. // Same surfaces used.
  2153. return getCaptureSessionSurfaces();
  2154. }
  2155. static int getTemplate()
  2156. {
  2157. static constexpr int templateRecord = 3;
  2158. return templateRecord;
  2159. }
  2160. static bool isVideoRecord() { return true; }
  2161. void sessionStarted()
  2162. {
  2163. MessageManager::callAsync ([this]() { mediaRecorder.start(); });
  2164. }
  2165. void takeStillPicture()
  2166. {
  2167. // Taking still pictures while recording video is not supported on Android.
  2168. jassertfalse;
  2169. }
  2170. private:
  2171. MediaRecorder& mediaRecorder;
  2172. };
  2173. //==============================================================================
  2174. class DeviceOrientationChangeListener : private Timer
  2175. {
  2176. public:
  2177. DeviceOrientationChangeListener (PreviewDisplay& pd)
  2178. : previewDisplay (pd),
  2179. orientationEventListener (createOrientationEventListener()),
  2180. canDetectChange (getEnv()->CallBooleanMethod (orientationEventListener,
  2181. OrientationEventListener.canDetectOrientation) != 0),
  2182. deviceOrientation (Desktop::getInstance().getCurrentOrientation()),
  2183. lastKnownScreenOrientation (deviceOrientation)
  2184. {
  2185. setEnabled (true);
  2186. }
  2187. ~DeviceOrientationChangeListener() override
  2188. {
  2189. setEnabled (false);
  2190. }
  2191. void setEnabled (bool shouldBeEnabled)
  2192. {
  2193. if (shouldBeEnabled && ! canDetectChange)
  2194. {
  2195. // This device does not support orientation listening, photos may have wrong orientation!
  2196. jassertfalse;
  2197. return;
  2198. }
  2199. if (shouldBeEnabled)
  2200. getEnv()->CallVoidMethod (orientationEventListener, OrientationEventListener.enable);
  2201. else
  2202. getEnv()->CallVoidMethod (orientationEventListener, OrientationEventListener.disable);
  2203. }
  2204. bool isSupported() const noexcept { return canDetectChange; }
  2205. Desktop::DisplayOrientation getDeviceOrientation() const noexcept
  2206. {
  2207. return deviceOrientation;
  2208. }
  2209. private:
  2210. PreviewDisplay& previewDisplay;
  2211. GlobalRef orientationEventListener;
  2212. static constexpr jint sensorDelayUI = 2;
  2213. bool canDetectChange;
  2214. Desktop::DisplayOrientation deviceOrientation;
  2215. Desktop::DisplayOrientation lastKnownScreenOrientation;
  2216. int numChecksForOrientationChange = 10;
  2217. //==============================================================================
  2218. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  2219. METHOD (canDetectOrientation, "canDetectOrientation", "()Z") \
  2220. METHOD (constructor, "<init>", "(JLandroid/content/Context;I)V") \
  2221. METHOD (disable, "disable", "()V") \
  2222. METHOD (enable, "enable", "()V") \
  2223. CALLBACK (deviceOrientationChanged, "deviceOrientationChanged", "(JI)V")
  2224. DECLARE_JNI_CLASS_WITH_MIN_SDK (OrientationEventListener, "com/rmsl/juce/JuceOrientationEventListener", 21)
  2225. #undef JNI_CLASS_MEMBERS
  2226. LocalRef<jobject> createOrientationEventListener()
  2227. {
  2228. return LocalRef<jobject> (getEnv()->NewObject (OrientationEventListener,
  2229. OrientationEventListener.constructor,
  2230. reinterpret_cast<jlong> (this),
  2231. getAppContext().get(),
  2232. sensorDelayUI));
  2233. }
  2234. //==============================================================================
  2235. void orientationChanged (int orientation)
  2236. {
  2237. jassert (orientation < 360);
  2238. // -1 == unknown
  2239. if (orientation < 0)
  2240. return;
  2241. auto oldOrientation = deviceOrientation;
  2242. // NB: this assumes natural position to be portrait always, but some devices may be landscape...
  2243. if (orientation > (360 - 45) || orientation < 45)
  2244. deviceOrientation = Desktop::upright;
  2245. else if (orientation < 135)
  2246. deviceOrientation = Desktop::rotatedClockwise;
  2247. else if (orientation < 225)
  2248. deviceOrientation = Desktop::upsideDown;
  2249. else
  2250. deviceOrientation = Desktop::rotatedAntiClockwise;
  2251. if (oldOrientation != deviceOrientation)
  2252. {
  2253. lastKnownScreenOrientation = Desktop::getInstance().getCurrentOrientation();
  2254. // Need to update preview transform, but screen orientation will change slightly
  2255. // later than sensor orientation.
  2256. startTimer (500);
  2257. }
  2258. }
  2259. void timerCallback() override
  2260. {
  2261. auto currentOrientation = Desktop::getInstance().getCurrentOrientation();
  2262. if (lastKnownScreenOrientation != currentOrientation)
  2263. {
  2264. lastKnownScreenOrientation = currentOrientation;
  2265. stopTimer();
  2266. numChecksForOrientationChange = 10;
  2267. previewDisplay.updateSurfaceTransform();
  2268. return;
  2269. }
  2270. if (--numChecksForOrientationChange == 0)
  2271. {
  2272. stopTimer();
  2273. numChecksForOrientationChange = 10;
  2274. }
  2275. }
  2276. static void deviceOrientationChanged (JNIEnv*, jobject /*obj*/, jlong host, jint orientation)
  2277. {
  2278. if (auto* myself = reinterpret_cast<DeviceOrientationChangeListener*> (host))
  2279. myself->orientationChanged (orientation);
  2280. }
  2281. };
  2282. //==============================================================================
  2283. CameraDevice& owner;
  2284. int minWidth, minHeight, maxWidth, maxHeight;
  2285. String cameraId;
  2286. InternalOpenCameraResultCallback cameraOpenCallback;
  2287. GlobalRef activityLifeListener;
  2288. GlobalRef cameraManager;
  2289. GlobalRef cameraCharacteristics;
  2290. GlobalRef handlerThread;
  2291. GlobalRef handler;
  2292. StreamConfigurationMap streamConfigurationMap;
  2293. PreviewDisplay previewDisplay;
  2294. DeviceOrientationChangeListener deviceOrientationChangeListener;
  2295. std::unique_ptr<ImageReader> imageReader;
  2296. std::unique_ptr<MediaRecorder> mediaRecorder;
  2297. std::unique_ptr<CaptureSessionModeBase> currentCaptureSessionMode;
  2298. std::unique_ptr<ScopedCameraDevice> scopedCameraDevice;
  2299. CriticalSection listenerLock;
  2300. ListenerList<Listener> listeners;
  2301. std::function<void (const Image&)> pictureTakenCallback;
  2302. Time firstRecordedFrameTimeMs;
  2303. bool notifiedOfCameraOpening = false;
  2304. bool appWasPaused = false;
  2305. //==============================================================================
  2306. int getCameraSensorOrientation() const
  2307. {
  2308. return getCameraCharacteristicsIntegerKeyValue (CameraCharacteristics.SENSOR_ORIENTATION);
  2309. }
  2310. int getAutoFocusModeToUse() const
  2311. {
  2312. auto supportedModes = getSupportedAutoFocusModes();
  2313. enum
  2314. {
  2315. CONTROL_AF_MODE_OFF = 0,
  2316. CONTROL_AF_MODE_AUTO = 1,
  2317. CONTROL_AF_MODE_CONTINUOUS_PICTURE = 4
  2318. };
  2319. if (supportedModes.contains (CONTROL_AF_MODE_CONTINUOUS_PICTURE))
  2320. return CONTROL_AF_MODE_CONTINUOUS_PICTURE;
  2321. if (supportedModes.contains (CONTROL_AF_MODE_AUTO))
  2322. return CONTROL_AF_MODE_AUTO;
  2323. return CONTROL_AF_MODE_OFF;
  2324. }
  2325. Array<int> getSupportedAutoFocusModes() const
  2326. {
  2327. auto* env = getEnv();
  2328. auto jKey = LocalRef<jobject> (env->GetStaticObjectField (CameraCharacteristics, CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES));
  2329. auto supportedModes = LocalRef<jintArray> ((jintArray) env->CallObjectMethod (cameraCharacteristics,
  2330. CameraCharacteristics.get,
  2331. jKey.get()));
  2332. return jintArrayToJuceArray (supportedModes);
  2333. }
  2334. static Array<int> jintArrayToJuceArray (const LocalRef<jintArray>& jArray)
  2335. {
  2336. auto* env = getEnv();
  2337. auto* jArrayElems = env->GetIntArrayElements (jArray, nullptr);
  2338. auto numElems = env->GetArrayLength (jArray);
  2339. Array<int> juceArray;
  2340. for (int s = 0; s < numElems; ++s)
  2341. juceArray.add (jArrayElems[s]);
  2342. env->ReleaseIntArrayElements (jArray, jArrayElems, 0);
  2343. return juceArray;
  2344. }
  2345. int getCameraCharacteristicsIntegerKeyValue (jfieldID key) const
  2346. {
  2347. auto* env = getEnv();
  2348. auto jKey = LocalRef<jobject> (env->GetStaticObjectField (CameraCharacteristics, key));
  2349. auto jValue = LocalRef<jobject> (env->CallObjectMethod (cameraCharacteristics,
  2350. CameraCharacteristics.get,
  2351. jKey.get()));
  2352. return env->CallIntMethod (jValue, JavaInteger.intValue);
  2353. }
  2354. int getCameraLensFacing() const
  2355. {
  2356. return getCameraCharacteristicsIntegerKeyValue (CameraCharacteristics.LENS_FACING);
  2357. }
  2358. //==============================================================================
  2359. void cameraOpenFinished (const String& error)
  2360. {
  2361. JUCE_CAMERA_LOG ("cameraOpenFinished(), error = " + error);
  2362. if (error.isEmpty())
  2363. {
  2364. setupStillImageSize();
  2365. startPreviewMode (*imageReader);
  2366. }
  2367. // Do not notify about camera being reopened on app resume.
  2368. if (! notifiedOfCameraOpening)
  2369. {
  2370. notifiedOfCameraOpening = true;
  2371. invokeCameraOpenCallback (error);
  2372. }
  2373. }
  2374. void cameraDeviceError (const String& error)
  2375. {
  2376. if (owner.onErrorOccurred != nullptr)
  2377. owner.onErrorOccurred (error);
  2378. }
  2379. void invokeCameraOpenCallback (const String& error)
  2380. {
  2381. JUCE_CAMERA_LOG ("invokeCameraOpenCallback(), error = " + error);
  2382. if (cameraOpenCallback != nullptr)
  2383. cameraOpenCallback (cameraId, error);
  2384. }
  2385. //==============================================================================
  2386. void callListeners (const Image& image)
  2387. {
  2388. const ScopedLock sl (listenerLock);
  2389. listeners.call ([=] (Listener& l) { l.imageReceived (image); });
  2390. }
  2391. void notifyPictureTaken (const Image& image)
  2392. {
  2393. JUCE_CAMERA_LOG ("notifyPictureTaken()");
  2394. if (pictureTakenCallback != nullptr)
  2395. pictureTakenCallback (image);
  2396. }
  2397. void triggerStillPictureCapture()
  2398. {
  2399. currentCaptureSessionMode->triggerStillPictureCapture();
  2400. }
  2401. //==============================================================================
  2402. void setupStillImageSize()
  2403. {
  2404. imageReader.reset();
  2405. auto imageSize = chooseBestSize (minWidth, minHeight, maxWidth, maxHeight,
  2406. streamConfigurationMap.getSupportedStillImageOutputSizes());
  2407. imageReader.reset (new ImageReader (*this, handler, imageSize.getWidth(), imageSize.getHeight(),
  2408. getCameraSensorOrientation()));
  2409. }
  2410. static Rectangle<int> chooseBestSize (int minWidth, int minHeight, int maxWidth, int maxHeight,
  2411. Array<Rectangle<int>> supportedSizes)
  2412. {
  2413. Rectangle<int> result;
  2414. for (auto& size : supportedSizes)
  2415. {
  2416. auto width = size.getWidth();
  2417. auto height = size.getHeight();
  2418. if (width < minWidth || width > maxWidth || height < minHeight || height > maxHeight)
  2419. continue;
  2420. if (size.contains (result))
  2421. result = size;
  2422. }
  2423. // None of the supported sizes matches required width & height limitations, picking
  2424. // the first one available...
  2425. jassert (! result.isEmpty());
  2426. if (result.isEmpty())
  2427. result = supportedSizes[0];
  2428. return result;
  2429. }
  2430. //==============================================================================
  2431. void startPreviewMode (ImageReader& ir)
  2432. {
  2433. if (currentCaptureSessionMode != nullptr && ! currentCaptureSessionMode->isVideoRecordSession())
  2434. return;
  2435. // previous mode has to be stopped first
  2436. jassert (currentCaptureSessionMode.get() == nullptr);
  2437. if (scopedCameraDevice == nullptr || ! scopedCameraDevice->openedOk())
  2438. return;
  2439. currentCaptureSessionMode.reset (new CaptureSessionPreviewMode (*this, *scopedCameraDevice, handler,
  2440. previewDisplay, ir,
  2441. getCameraSensorOrientation(),
  2442. getCameraLensFacing(),
  2443. streamConfigurationMap));
  2444. }
  2445. void startVideoRecordingMode (MediaRecorder& mr)
  2446. {
  2447. if (currentCaptureSessionMode != nullptr && currentCaptureSessionMode->isVideoRecordSession())
  2448. return;
  2449. // previous mode has to be stopped first
  2450. jassert (currentCaptureSessionMode.get() == nullptr);
  2451. jassert (scopedCameraDevice != nullptr && scopedCameraDevice->openedOk());
  2452. if (scopedCameraDevice == nullptr || ! scopedCameraDevice->openedOk())
  2453. return;
  2454. currentCaptureSessionMode.reset (new CaptureSessionVideoRecordingMode (*this, *scopedCameraDevice, handler,
  2455. previewDisplay, mr,
  2456. getCameraSensorOrientation(),
  2457. getCameraLensFacing(),
  2458. streamConfigurationMap));
  2459. }
  2460. //==============================================================================
  2461. void onActivityPaused (jobject) override
  2462. {
  2463. JUCE_CAMERA_LOG ("appPaused, closing camera...");
  2464. appWasPaused = true;
  2465. deviceOrientationChangeListener.setEnabled (false);
  2466. // We need to restart the whole session mode when the app gets resumed.
  2467. currentCaptureSessionMode.reset();
  2468. if (scopedCameraDevice != nullptr)
  2469. scopedCameraDevice->close();
  2470. stopBackgroundThread();
  2471. }
  2472. void onActivityResumed (jobject) override
  2473. {
  2474. // Only care about resumed event when paused event was called first.
  2475. if (! appWasPaused)
  2476. return;
  2477. JUCE_CAMERA_LOG ("appResumed, opening camera...");
  2478. deviceOrientationChangeListener.setEnabled (true);
  2479. startBackgroundThread();
  2480. if (scopedCameraDevice != nullptr)
  2481. scopedCameraDevice->open();
  2482. }
  2483. void startBackgroundThread()
  2484. {
  2485. auto* env = getEnv();
  2486. handlerThread = GlobalRef (LocalRef<jobject> (env->NewObject (AndroidHandlerThread,
  2487. AndroidHandlerThread.constructor,
  2488. javaString ("JuceCameraDeviceBackgroundThread").get())));
  2489. // handler thread has to be started before its looper can be fetched
  2490. env->CallVoidMethod (handlerThread, AndroidHandlerThread.start);
  2491. handler = GlobalRef (LocalRef<jobject> (env->NewObject (AndroidHandler,
  2492. AndroidHandler.constructorWithLooper,
  2493. env->CallObjectMethod (handlerThread, AndroidHandlerThread.getLooper))));
  2494. }
  2495. void stopBackgroundThread()
  2496. {
  2497. auto* env = getEnv();
  2498. auto quitSafelyMethod = env->GetMethodID(AndroidHandlerThread, "quitSafely", "()Z");
  2499. // this code will only run on SDK >= 21
  2500. jassert(quitSafelyMethod != nullptr);
  2501. env->CallBooleanMethod (handlerThread, quitSafelyMethod);
  2502. env->CallVoidMethod (handlerThread, AndroidHandlerThread.join);
  2503. jniCheckHasExceptionOccurredAndClear();
  2504. handlerThread.clear();
  2505. handler.clear();
  2506. }
  2507. friend struct CameraDevice::ViewerComponent;
  2508. JUCE_DECLARE_NON_COPYABLE (Pimpl)
  2509. };
  2510. //==============================================================================
  2511. struct CameraDevice::ViewerComponent : public Component,
  2512. private ComponentMovementWatcher
  2513. {
  2514. ViewerComponent (CameraDevice& device) : ComponentMovementWatcher (this)
  2515. {
  2516. auto previewSize = device.pimpl->streamConfigurationMap.getDefaultPreviewSize();
  2517. targetAspectRatio = previewSize.getWidth() / (float) previewSize.getHeight();
  2518. if (isOrientationLandscape())
  2519. setBounds (previewSize);
  2520. else
  2521. setBounds (0, 0, previewSize.getHeight(), previewSize.getWidth());
  2522. addAndMakeVisible (viewerComponent);
  2523. viewerComponent.setView (device.pimpl->previewDisplay.getNativeView());
  2524. }
  2525. private:
  2526. AndroidViewComponent viewerComponent;
  2527. float targetAspectRatio = 1.0f;
  2528. void componentMovedOrResized (bool, bool) override
  2529. {
  2530. auto b = getLocalBounds();
  2531. auto targetWidth = b.getWidth();
  2532. auto targetHeight = b.getHeight();
  2533. if (isOrientationLandscape())
  2534. {
  2535. auto currentAspectRatio = b.getWidth() / (float) b.getHeight();
  2536. if (currentAspectRatio > targetAspectRatio)
  2537. targetWidth = static_cast<int> (targetWidth * targetAspectRatio / currentAspectRatio);
  2538. else
  2539. targetHeight = static_cast<int> (targetHeight * currentAspectRatio / targetAspectRatio);
  2540. }
  2541. else
  2542. {
  2543. auto currentAspectRatio = b.getHeight() / (float) b.getWidth();
  2544. if (currentAspectRatio > targetAspectRatio)
  2545. targetHeight = static_cast<int> (targetHeight * targetAspectRatio / currentAspectRatio);
  2546. else
  2547. targetWidth = static_cast<int> (targetWidth * currentAspectRatio / targetAspectRatio);
  2548. }
  2549. viewerComponent.setBounds (Rectangle<int> (0, 0, targetWidth, targetHeight).withCentre (b.getCentre()));
  2550. }
  2551. bool isOrientationLandscape() const
  2552. {
  2553. auto o = Desktop::getInstance().getCurrentOrientation();
  2554. return o == Desktop::rotatedClockwise || o == Desktop::rotatedAntiClockwise;
  2555. }
  2556. void componentPeerChanged() override {}
  2557. void componentVisibilityChanged() override {}
  2558. JUCE_DECLARE_NON_COPYABLE (ViewerComponent)
  2559. };
  2560. String CameraDevice::getFileExtension()
  2561. {
  2562. return ".mp4";
  2563. }
  2564. //==============================================================================
  2565. CameraDevice::Pimpl::ScopedCameraDevice::CaptureSession::StillPictureTaker::CameraCaptureSessionCaptureCallback_Class CameraDevice::Pimpl::ScopedCameraDevice::CaptureSession::StillPictureTaker::CameraCaptureSessionCaptureCallback;
  2566. CameraDevice::Pimpl::ScopedCameraDevice::CameraDeviceStateCallback_Class CameraDevice::Pimpl::ScopedCameraDevice::CameraDeviceStateCallback;
  2567. CameraDevice::Pimpl::ScopedCameraDevice::CaptureSession::CameraCaptureSessionStateCallback_Class CameraDevice::Pimpl::ScopedCameraDevice::CaptureSession::CameraCaptureSessionStateCallback;
  2568. CameraDevice::Pimpl::DeviceOrientationChangeListener::OrientationEventListener_Class CameraDevice::Pimpl::DeviceOrientationChangeListener::OrientationEventListener;