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.

3286 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. RuntimePermissions::request (RuntimePermissions::camera,
  425. [safeThis = WeakReference<Pimpl> { this }] (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 ((float) height / (float) width), jfloat ((float) width / (float) height), (jfloat) 0, (jfloat) 0);
  849. env->CallBooleanMethod (matrix, AndroidMatrix.postRotate, (jfloat) 90 * ((float) 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. owner.callListeners (image);
  941. // Android may take multiple pictures before it handles a request to stop.
  942. if (hasNotifiedListeners.compareAndSetBool (1, 0))
  943. MessageManager::callAsync ([safeThis = WeakReference<ImageReader> { this }, image]() mutable
  944. {
  945. if (safeThis != nullptr)
  946. safeThis->owner.notifyPictureTaken (image);
  947. });
  948. }
  949. struct ImageBuffer
  950. {
  951. LocalRef<jbyteArray> byteArray;
  952. int size;
  953. };
  954. static Image androidImageToJuceWithFixedOrientation (const LocalRef<jobject>& androidImage,
  955. Desktop::DisplayOrientation deviceOrientationFromAccelerometerSensor,
  956. Desktop::DisplayOrientation targetOrientation,
  957. bool cameraLensFrontFacing,
  958. int cameraSensorOrientation)
  959. {
  960. auto* env = getEnv();
  961. auto planes = LocalRef<jobjectArray> ((jobjectArray) env->CallObjectMethod (androidImage, AndroidImage.getPlanes));
  962. jassert (env->GetArrayLength (planes) > 0);
  963. auto plane = LocalRef<jobject> (env->GetObjectArrayElement (planes, 0));
  964. auto byteBuffer = LocalRef<jobject> (env->CallObjectMethod (plane, AndroidImagePlane.getBuffer));
  965. ImageBuffer correctedBuffer = getImageBufferWithCorrectedOrientationFrom (byteBuffer, deviceOrientationFromAccelerometerSensor,
  966. targetOrientation, cameraLensFrontFacing, cameraSensorOrientation);
  967. jbyte* rawBytes = env->GetByteArrayElements (correctedBuffer.byteArray, nullptr);
  968. Image result = ImageFileFormat::loadFrom (rawBytes, (size_t) correctedBuffer.size);
  969. env->ReleaseByteArrayElements (correctedBuffer.byteArray, rawBytes, 0);
  970. return result;
  971. }
  972. static ImageBuffer getImageBufferWithCorrectedOrientationFrom (const LocalRef<jobject>& imagePlaneBuffer,
  973. Desktop::DisplayOrientation deviceOrientationFromAccelerometerSensor,
  974. Desktop::DisplayOrientation targetOrientation,
  975. bool cameraLensFrontFacing,
  976. int cameraSensorOrientation)
  977. {
  978. auto* env = getEnv();
  979. auto bufferSize = env->CallIntMethod (imagePlaneBuffer, JavaByteBuffer.remaining);
  980. auto byteArray = LocalRef<jbyteArray> (env->NewByteArray (bufferSize));
  981. env->CallObjectMethod (imagePlaneBuffer, JavaByteBuffer.get, byteArray.get());
  982. auto rotationAngle = getRotationAngle (deviceOrientationFromAccelerometerSensor, targetOrientation,
  983. cameraLensFrontFacing, cameraSensorOrientation);
  984. if (rotationAngle == 0)
  985. {
  986. // Nothing to do, just get the bytes
  987. return { byteArray, bufferSize };
  988. }
  989. auto origBitmap = LocalRef<jobject> (env->CallStaticObjectMethod (AndroidBitmapFactory,
  990. AndroidBitmapFactory.decodeByteArray,
  991. byteArray.get(), (jint) 0, (jint) bufferSize));
  992. if (origBitmap == nullptr)
  993. {
  994. // Nothing to do, just get the bytes
  995. return { byteArray, bufferSize };
  996. }
  997. auto correctedBitmap = getBitmapWithCorrectOrientationFrom (origBitmap, rotationAngle);
  998. auto byteArrayOutputStream = LocalRef<jobject> (env->NewObject (ByteArrayOutputStream,
  999. ByteArrayOutputStream.constructor));
  1000. auto jCompressFormatString = javaString ("JPEG");
  1001. auto compressFormat = LocalRef<jobject> (env->CallStaticObjectMethod (AndroidBitmapCompressFormat,
  1002. AndroidBitmapCompressFormat.valueOf,
  1003. jCompressFormatString.get()));
  1004. if (env->CallBooleanMethod (correctedBitmap, AndroidBitmap.compress, compressFormat.get(),
  1005. (jint) 100, byteArrayOutputStream.get()) != 0)
  1006. {
  1007. auto correctedByteArray = LocalRef<jbyteArray> ((jbyteArray) env->CallObjectMethod (byteArrayOutputStream,
  1008. ByteArrayOutputStream.toByteArray));
  1009. int correctedByteArraySize = env->CallIntMethod (byteArrayOutputStream, ByteArrayOutputStream.size);
  1010. return { correctedByteArray, correctedByteArraySize };
  1011. }
  1012. jassertfalse;
  1013. // fallback, return original bitmap
  1014. return { byteArray, bufferSize };
  1015. }
  1016. static int getRotationAngle (Desktop::DisplayOrientation deviceOrientationFromAccelerometerSensor,
  1017. Desktop::DisplayOrientation targetOrientation,
  1018. bool cameraLensFrontFacing,
  1019. int cameraSensorOrientation)
  1020. {
  1021. auto isSensorOrientationHorizontal = deviceOrientationFromAccelerometerSensor == Desktop::rotatedAntiClockwise
  1022. || deviceOrientationFromAccelerometerSensor == Desktop::rotatedClockwise;
  1023. if (cameraLensFrontFacing && isSensorOrientationHorizontal)
  1024. {
  1025. // flip angles for front camera
  1026. return getRotationAngle (deviceOrientationFromAccelerometerSensor, targetOrientation, false, (cameraSensorOrientation + 180) % 360);
  1027. }
  1028. switch (targetOrientation)
  1029. {
  1030. case Desktop::rotatedAntiClockwise:
  1031. return cameraSensorOrientation == 90 ? 0 : 180;
  1032. case Desktop::rotatedClockwise:
  1033. return cameraSensorOrientation == 90 ? 180 : 0;
  1034. case Desktop::upright:
  1035. case Desktop::upsideDown:
  1036. if ((targetOrientation == Desktop::upright && ! cameraLensFrontFacing)
  1037. || (targetOrientation == Desktop::upsideDown && cameraLensFrontFacing))
  1038. {
  1039. return cameraSensorOrientation;
  1040. }
  1041. else
  1042. {
  1043. if (deviceOrientationFromAccelerometerSensor == Desktop::upright || deviceOrientationFromAccelerometerSensor == Desktop::upsideDown)
  1044. return cameraSensorOrientation;
  1045. else
  1046. return (cameraSensorOrientation + 180) % 360;
  1047. }
  1048. break;
  1049. case Desktop::allOrientations:
  1050. default:
  1051. return 0;
  1052. }
  1053. }
  1054. static LocalRef<jobject> getBitmapWithCorrectOrientationFrom (LocalRef<jobject>& origBitmap, int rotationAngle)
  1055. {
  1056. auto* env = getEnv();
  1057. auto origBitmapWidth = env->CallIntMethod (origBitmap, AndroidBitmap.getWidth);
  1058. auto origBitmapHeight = env->CallIntMethod (origBitmap, AndroidBitmap.getHeight);
  1059. auto matrix = LocalRef<jobject> (env->NewObject (AndroidMatrix, AndroidMatrix.constructor));
  1060. env->CallBooleanMethod (matrix, AndroidMatrix.postRotate, (jfloat) rotationAngle, (jfloat) 0, (jfloat) 0);
  1061. auto rotatedBitmap = LocalRef<jobject> (env->CallStaticObjectMethod (AndroidBitmap, AndroidBitmap.createBitmapFrom,
  1062. origBitmap.get(), (jint) 0, (jint) 0,
  1063. (jint) origBitmapWidth, (jint) origBitmapHeight,
  1064. matrix.get(), true));
  1065. env->CallVoidMethod (origBitmap, AndroidBitmap.recycle);
  1066. return rotatedBitmap;
  1067. }
  1068. };
  1069. //==============================================================================
  1070. class MediaRecorder : private MediaRecorderOnInfoListener::Owner,
  1071. private MediaRecorderOnErrorListener::Owner
  1072. {
  1073. public:
  1074. MediaRecorder (const String& outputFilePath, int videoWidth, int videoHeight,
  1075. int sensorOrientation, int cameraLensFacing)
  1076. : onInfoListener (*this),
  1077. onErrorListener (*this),
  1078. mediaRecorder (LocalRef<jobject> (getEnv()->NewObject (AndroidMediaRecorder,
  1079. AndroidMediaRecorder.constructor)))
  1080. {
  1081. auto* env = getEnv();
  1082. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setOnInfoListener,
  1083. CreateJavaInterface (&onInfoListener,
  1084. "android/media/MediaRecorder$OnInfoListener").get());
  1085. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setOnErrorListener,
  1086. CreateJavaInterface (&onErrorListener,
  1087. "android/media/MediaRecorder$OnErrorListener").get());
  1088. // NB: the order of function calls here is enforced, and exceptions will be thrown if
  1089. // the order is changed.
  1090. static constexpr int audioSourceMic = 1;
  1091. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setAudioSource, (jint) audioSourceMic);
  1092. static constexpr int videoSourceSurface = 2;
  1093. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setVideoSource, (jint) videoSourceSurface);
  1094. static constexpr int outputFormatMPEG4 = 2;
  1095. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setOutputFormat, (jint) outputFormatMPEG4);
  1096. static constexpr int audioEncoderAAC = 3;
  1097. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setAudioEncoder, (jint) audioEncoderAAC);
  1098. static constexpr int videoEncoderH264 = 2;
  1099. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setVideoEncoder, (jint) videoEncoderH264);
  1100. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setVideoEncodingBitRate, (jint) 10000000);
  1101. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setVideoFrameRate, (jint) 30);
  1102. auto frontFacing = cameraLensFacing == 0;
  1103. auto useInverseDegrees = frontFacing && sensorOrientation == 90;
  1104. int orientationHint = getOrientationHint (useInverseDegrees, sensorOrientation);
  1105. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setOrientationHint, (jint) orientationHint);
  1106. getEnv()->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setVideoSize, (jint) videoWidth, (jint) videoHeight);
  1107. getEnv()->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.setOutputFile, javaString (outputFilePath).get());
  1108. getEnv()->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.prepare);
  1109. }
  1110. ~MediaRecorder() override
  1111. {
  1112. getEnv()->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.release);
  1113. }
  1114. LocalRef<jobject> getSurface()
  1115. {
  1116. return LocalRef<jobject> (getEnv()->CallObjectMethod (mediaRecorder, AndroidMediaRecorder.getSurface));
  1117. }
  1118. void start()
  1119. {
  1120. lockScreenOrientation();
  1121. getEnv()->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.start);
  1122. hasStartedRecording = true;
  1123. }
  1124. void stop()
  1125. {
  1126. // A request to stop can be sent before recording has had a chance to start, so
  1127. // ignore the request rather than calling AndroidMediaRecorder.stop because
  1128. // otherwise MediaRecorder will throw an exception and...
  1129. if (! hasStartedRecording)
  1130. return;
  1131. hasStartedRecording = false;
  1132. auto* env = getEnv();
  1133. env->CallVoidMethod (mediaRecorder, AndroidMediaRecorder.stop);
  1134. // ... ignore RuntimeException that can be thrown if stop() was called after recording
  1135. // has started but before any frame was written to a file. This is not an error.
  1136. jniCheckHasExceptionOccurredAndClear();
  1137. unlockScreenOrientation();
  1138. }
  1139. private:
  1140. MediaRecorderOnInfoListener onInfoListener;
  1141. MediaRecorderOnErrorListener onErrorListener;
  1142. GlobalRef mediaRecorder;
  1143. bool hasStartedRecording = false;
  1144. int orientationsEnabled = -1;
  1145. void lockScreenOrientation()
  1146. {
  1147. orientationsEnabled = Desktop::getInstance().getOrientationsEnabled();
  1148. auto o = Desktop::getInstance().getCurrentOrientation();
  1149. Desktop::getInstance().setOrientationsEnabled (o);
  1150. }
  1151. static jint juceOrientationToNativeOrientation (int orientations) noexcept
  1152. {
  1153. enum
  1154. {
  1155. SCREEN_ORIENTATION_LANDSCAPE = 0,
  1156. SCREEN_ORIENTATION_PORTRAIT = 1,
  1157. SCREEN_ORIENTATION_USER = 2,
  1158. SCREEN_ORIENTATION_REVERSE_LANDSCAPE = 8,
  1159. SCREEN_ORIENTATION_REVERSE_PORTRAIT = 9,
  1160. SCREEN_ORIENTATION_USER_LANDSCAPE = 11,
  1161. SCREEN_ORIENTATION_USER_PORTRAIT = 12,
  1162. };
  1163. switch (orientations)
  1164. {
  1165. case Desktop::upright: return (jint) SCREEN_ORIENTATION_PORTRAIT;
  1166. case Desktop::upsideDown: return (jint) SCREEN_ORIENTATION_REVERSE_PORTRAIT;
  1167. case Desktop::upright + Desktop::upsideDown: return (jint) SCREEN_ORIENTATION_USER_PORTRAIT;
  1168. case Desktop::rotatedAntiClockwise: return (jint) SCREEN_ORIENTATION_LANDSCAPE;
  1169. case Desktop::rotatedClockwise: return (jint) SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
  1170. case Desktop::rotatedClockwise + Desktop::rotatedAntiClockwise: return (jint) SCREEN_ORIENTATION_USER_LANDSCAPE;
  1171. default: return (jint) SCREEN_ORIENTATION_USER;
  1172. }
  1173. }
  1174. void unlockScreenOrientation()
  1175. {
  1176. Desktop::getInstance().setOrientationsEnabled (orientationsEnabled);
  1177. }
  1178. void onInfo (LocalRef<jobject>& recorder, int what, int extra) override
  1179. {
  1180. ignoreUnused (recorder, what, extra);
  1181. JUCE_CAMERA_LOG ("MediaRecorder::OnInfo: " + getInfoStringFromCode (what)
  1182. + ", extra code = " + String (extra));
  1183. }
  1184. void onError (LocalRef<jobject>& recorder, int what, int extra) override
  1185. {
  1186. ignoreUnused (recorder, what, extra);
  1187. JUCE_CAMERA_LOG ("MediaRecorder::onError: " + getErrorStringFromCode (what)
  1188. + ", extra code = " + String (extra));
  1189. }
  1190. static String getInfoStringFromCode (int what)
  1191. {
  1192. enum
  1193. {
  1194. MEDIA_RECORDER_INFO_UNKNOWN = 1,
  1195. MEDIA_RECORDER_INFO_MAX_DURATION_REACHED = 800,
  1196. MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED = 801,
  1197. MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING = 802,
  1198. MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED = 803
  1199. };
  1200. switch (what)
  1201. {
  1202. case MEDIA_RECORDER_INFO_UNKNOWN: return { "Unknown info" };
  1203. case MEDIA_RECORDER_INFO_MAX_DURATION_REACHED: return { "Max duration reached" };
  1204. case MEDIA_RECORDER_INFO_MAX_FILESIZE_REACHED: return { "Max filesize reached" };
  1205. case MEDIA_RECORDER_INFO_MAX_FILESIZE_APPROACHING: return { "Max filesize approaching" };
  1206. case MEDIA_RECORDER_INFO_NEXT_OUTPUT_FILE_STARTED: return { "Next output file started" };
  1207. default: return String (what);
  1208. };
  1209. }
  1210. static String getErrorStringFromCode (int what)
  1211. {
  1212. enum
  1213. {
  1214. MEDIA_RECORDER_ERROR_UNKNOWN = 1,
  1215. MEDIA_ERROR_SERVER_DIED = 100
  1216. };
  1217. switch (what)
  1218. {
  1219. case MEDIA_RECORDER_ERROR_UNKNOWN: return { "Unknown error" };
  1220. case MEDIA_ERROR_SERVER_DIED: return { "Server died" };
  1221. default: return String (what);
  1222. };
  1223. }
  1224. static int getOrientationHint (bool useInverseDegrees, int cameraSensorOrientation)
  1225. {
  1226. auto* env = getEnv();
  1227. auto windowManager = LocalRef<jobject> (env->CallObjectMethod (getAppContext(), AndroidContext.getSystemService, javaString ("window").get()));
  1228. auto display = LocalRef<jobject> (env->CallObjectMethod (windowManager, AndroidWindowManager.getDefaultDisplay));
  1229. auto rotation = env->CallIntMethod (display, AndroidDisplay.getRotation);
  1230. enum
  1231. {
  1232. ROTATION_0 = 0,
  1233. ROTATION_90,
  1234. ROTATION_180,
  1235. ROTATION_270
  1236. };
  1237. int hint = 0;
  1238. switch (rotation)
  1239. {
  1240. case ROTATION_0: hint = cameraSensorOrientation; break;
  1241. case ROTATION_90: hint = useInverseDegrees ? 180 : 0; break;
  1242. case ROTATION_180: hint = cameraSensorOrientation + 180; break;
  1243. case ROTATION_270: hint = useInverseDegrees ? 0 : 180; break;
  1244. default: jassertfalse;
  1245. }
  1246. return (hint + 360) % 360;
  1247. }
  1248. };
  1249. //==============================================================================
  1250. class ScopedCameraDevice
  1251. {
  1252. public:
  1253. //==============================================================================
  1254. class CaptureSession
  1255. {
  1256. public:
  1257. struct ConfiguredCallback
  1258. {
  1259. virtual ~ConfiguredCallback() {}
  1260. virtual void captureSessionConfigured (CaptureSession*) = 0;
  1261. };
  1262. ~CaptureSession()
  1263. {
  1264. bool calledClose = false;
  1265. auto* env = getEnv();
  1266. {
  1267. const ScopedLock lock (captureSessionLock);
  1268. if (captureSession.get() != nullptr)
  1269. {
  1270. calledClose = true;
  1271. env->CallVoidMethod (captureSession, CameraCaptureSession.close);
  1272. }
  1273. }
  1274. // When exception occurs, CameraCaptureSession.close will never finish, so
  1275. // we should not wait for it. For fatal error an exception does occur, but
  1276. // it is caught internally in Java...
  1277. if (jniCheckHasExceptionOccurredAndClear() || scopedCameraDevice.fatalErrorOccurred.get())
  1278. {
  1279. JUCE_CAMERA_LOG ("Exception or fatal error occurred while closing Capture Session, closing by force");
  1280. }
  1281. else if (calledClose)
  1282. {
  1283. pendingClose.set (1);
  1284. closedEvent.wait (-1);
  1285. }
  1286. }
  1287. bool openedOk() const noexcept { return captureSession != nullptr; }
  1288. const GlobalRef& getNativeSession() const { return captureSession; }
  1289. bool start (const LocalRef<jobject>& targetSurfacesList, GlobalRef& handlerToUse)
  1290. {
  1291. if (! openedOk())
  1292. {
  1293. jassertfalse;
  1294. return false;
  1295. }
  1296. auto* env = getEnv();
  1297. auto numSurfaces = env->CallIntMethod (targetSurfacesList, JavaArrayList.size);
  1298. for (int i = 0; i < numSurfaces; ++i)
  1299. {
  1300. auto surface = LocalRef<jobject> (env->CallObjectMethod (targetSurfacesList, JavaArrayList.get, (jint) i));
  1301. env->CallVoidMethod (captureRequestBuilder, CaptureRequestBuilder.addTarget, surface.get());
  1302. }
  1303. previewCaptureRequest = GlobalRef (LocalRef<jobject>(env->CallObjectMethod (captureRequestBuilder, CaptureRequestBuilder.build)));
  1304. env->CallIntMethod (captureSession, CameraCaptureSession.setRepeatingRequest,
  1305. previewCaptureRequest.get(), nullptr, handlerToUse.get());
  1306. return true;
  1307. }
  1308. void takeStillPicture (jobject targetSurface)
  1309. {
  1310. if (stillPictureTaker == nullptr)
  1311. {
  1312. // Can only take picture once session was successfully configured!
  1313. jassertfalse;
  1314. return;
  1315. }
  1316. auto* env = getEnv();
  1317. static constexpr int templateStillCapture = 2;
  1318. auto builder = LocalRef<jobject> (env->CallObjectMethod (scopedCameraDevice.cameraDevice,
  1319. AndroidCameraDevice.createCaptureRequest,
  1320. (jint) templateStillCapture));
  1321. env->CallVoidMethod (builder, CaptureRequestBuilder.addTarget, targetSurface);
  1322. setCaptureRequestBuilderIntegerKey (builder, CaptureRequest.CONTROL_AF_MODE, autoFocusMode);
  1323. auto stillPictureCaptureRequest = LocalRef<jobject> (env->CallObjectMethod (builder, CaptureRequestBuilder.build));
  1324. stillPictureTaker->takePicture (stillPictureCaptureRequest);
  1325. }
  1326. private:
  1327. //==============================================================================
  1328. class StillPictureTaker : private AndroidRunnable::Owner
  1329. {
  1330. public:
  1331. StillPictureTaker (GlobalRef& captureSessionToUse, GlobalRef& captureRequestBuilderToUse,
  1332. GlobalRef& previewCaptureRequestToUse, GlobalRef& handlerToUse,
  1333. int autoFocusModeToUse)
  1334. : captureSession (captureSessionToUse),
  1335. captureRequestBuilder (captureRequestBuilderToUse),
  1336. previewCaptureRequest (previewCaptureRequestToUse),
  1337. handler (handlerToUse),
  1338. runnable (*this),
  1339. captureSessionPreviewCaptureCallback (createCaptureSessionCallback (true)),
  1340. captureSessionStillPictureCaptureCallback (createCaptureSessionCallback (false)),
  1341. autoFocusMode (autoFocusModeToUse)
  1342. {
  1343. }
  1344. void takePicture (const LocalRef<jobject>& stillPictureCaptureRequestToUse)
  1345. {
  1346. JUCE_CAMERA_LOG ("Taking picture...");
  1347. stillPictureCaptureRequest = GlobalRef (LocalRef<jobject>(stillPictureCaptureRequestToUse));
  1348. lockFocus();
  1349. }
  1350. private:
  1351. GlobalRef& captureSession;
  1352. GlobalRef& captureRequestBuilder;
  1353. GlobalRef& previewCaptureRequest;
  1354. GlobalRef& handler;
  1355. AndroidRunnable runnable;
  1356. GlobalRef delayedCaptureRunnable;
  1357. GlobalRef captureSessionPreviewCaptureCallback;
  1358. GlobalRef stillPictureCaptureRequest;
  1359. GlobalRef captureSessionStillPictureCaptureCallback;
  1360. int autoFocusMode;
  1361. //==============================================================================
  1362. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  1363. METHOD (constructor, "<init>", "(JZ)V") \
  1364. CALLBACK (cameraCaptureSessionCaptureCompletedCallback, "cameraCaptureSessionCaptureCompleted", "(JZLandroid/hardware/camera2/CameraCaptureSession;Landroid/hardware/camera2/CaptureRequest;Landroid/hardware/camera2/TotalCaptureResult;)V") \
  1365. CALLBACK (cameraCaptureSessionCaptureFailedCallback, "cameraCaptureSessionCaptureFailed", "(JZLandroid/hardware/camera2/CameraCaptureSession;Landroid/hardware/camera2/CaptureRequest;Landroid/hardware/camera2/CaptureFailure;)V") \
  1366. CALLBACK (cameraCaptureSessionCaptureProgressedCallback, "cameraCaptureSessionCaptureProgressed", "(JZLandroid/hardware/camera2/CameraCaptureSession;Landroid/hardware/camera2/CaptureRequest;Landroid/hardware/camera2/CaptureResult;)V") \
  1367. CALLBACK (cameraCaptureSessionCaptureStartedCallback, "cameraCaptureSessionCaptureStarted", "(JZLandroid/hardware/camera2/CameraCaptureSession;Landroid/hardware/camera2/CaptureRequest;JJ)V") \
  1368. CALLBACK (cameraCaptureSessionCaptureSequenceAbortedCallback, "cameraCaptureSessionCaptureSequenceAborted", "(JZLandroid/hardware/camera2/CameraCaptureSession;I)V") \
  1369. CALLBACK (cameraCaptureSessionCaptureSequenceCompletedCallback, "cameraCaptureSessionCaptureSequenceCompleted", "(JZLandroid/hardware/camera2/CameraCaptureSession;IJ)V")
  1370. DECLARE_JNI_CLASS_WITH_BYTECODE (CameraCaptureSessionCaptureCallback, "com/rmsl/juce/CameraCaptureSessionCaptureCallback", 21, CameraSupportByteCode, sizeof(CameraSupportByteCode))
  1371. #undef JNI_CLASS_MEMBERS
  1372. LocalRef<jobject> createCaptureSessionCallback (bool createPreviewSession)
  1373. {
  1374. return LocalRef<jobject>(getEnv()->NewObject (CameraCaptureSessionCaptureCallback,
  1375. CameraCaptureSessionCaptureCallback.constructor,
  1376. reinterpret_cast<jlong> (this),
  1377. createPreviewSession ? 1 : 0));
  1378. }
  1379. //==============================================================================
  1380. enum class State
  1381. {
  1382. idle = 0,
  1383. pendingFocusLock,
  1384. pendingExposurePrecapture,
  1385. pendingExposurePostPrecapture,
  1386. pictureTaken
  1387. };
  1388. State currentState = State::idle;
  1389. void lockFocus()
  1390. {
  1391. if (jniCheckHasExceptionOccurredAndClear())
  1392. return;
  1393. JUCE_CAMERA_LOG ("Performing auto-focus if possible...");
  1394. currentState = State::pendingFocusLock;
  1395. auto* env = getEnv();
  1396. // NB: auto-focus may be unavailable on a device, in which case it may have already
  1397. // automatically adjusted the exposure. We check for that in updateState().
  1398. static constexpr int controlAfTriggerStart = 1;
  1399. CaptureSession::setCaptureRequestBuilderIntegerKey (captureRequestBuilder.get(),
  1400. CaptureRequest.CONTROL_AF_TRIGGER,
  1401. controlAfTriggerStart);
  1402. auto previewRequest = LocalRef<jobject> (env->CallObjectMethod (captureRequestBuilder,
  1403. CaptureRequestBuilder.build));
  1404. env->CallIntMethod (captureSession, CameraCaptureSession.capture, previewRequest.get(),
  1405. captureSessionPreviewCaptureCallback.get(), handler.get());
  1406. }
  1407. void updateState (jobject captureResult)
  1408. {
  1409. // IllegalStateException can be thrown when accessing CaptureSession,
  1410. // claiming that capture session was already closed but we may not
  1411. // get relevant callback yet, so check for this and bailout when needed.
  1412. if (jniCheckHasExceptionOccurredAndClear())
  1413. return;
  1414. switch (currentState)
  1415. {
  1416. case State::pendingFocusLock:
  1417. {
  1418. JUCE_CAMERA_LOG ("Still picture capture, updateState(), State::pendingFocusLock...");
  1419. auto controlAfStateValue = getCaptureResultIntegerKeyValue (CaptureResult.CONTROL_AF_STATE, captureResult);
  1420. if (controlAfStateValue.get() == nullptr)
  1421. {
  1422. captureStillPictureDelayed();
  1423. return;
  1424. }
  1425. auto autoToFocusNotAvailable = autoFocusMode == 0;
  1426. if (autoToFocusNotAvailable || autoFocusHasFinished (controlAfStateValue))
  1427. {
  1428. auto controlAeStateIntValue = getControlAEState (captureResult);
  1429. static constexpr int controlAeStateConverged = 2;
  1430. if (controlAeStateIntValue == -1 || controlAeStateIntValue == controlAeStateConverged)
  1431. {
  1432. currentState = State::pictureTaken;
  1433. captureStillPictureDelayed();
  1434. }
  1435. else
  1436. {
  1437. runPrecaptureSequence();
  1438. }
  1439. }
  1440. break;
  1441. }
  1442. case State::pendingExposurePrecapture:
  1443. {
  1444. JUCE_CAMERA_LOG ("Still picture capture, updateState(), State::pendingExposurePrecapture...");
  1445. auto controlAeStateIntValue = getControlAEState (captureResult);
  1446. static constexpr int controlAeStateFlashRequired = 4;
  1447. static constexpr int controlAeStatePrecapture = 5;
  1448. if (controlAeStateIntValue == -1 || controlAeStateIntValue == controlAeStateFlashRequired
  1449. || controlAeStateIntValue == controlAeStatePrecapture)
  1450. {
  1451. currentState = State::pendingExposurePostPrecapture;
  1452. }
  1453. break;
  1454. }
  1455. case State::pendingExposurePostPrecapture:
  1456. {
  1457. JUCE_CAMERA_LOG ("Still picture capture, updateState(), State::pendingExposurePostPrecapture...");
  1458. auto controlAeStateIntValue = getControlAEState (captureResult);
  1459. static constexpr int controlAeStatePrecapture = 5;
  1460. if (controlAeStateIntValue == -1 || controlAeStateIntValue != controlAeStatePrecapture)
  1461. {
  1462. currentState = State::pictureTaken;
  1463. captureStillPictureDelayed();
  1464. }
  1465. break;
  1466. }
  1467. case State::idle:
  1468. case State::pictureTaken:
  1469. { /* do nothing */ break; }
  1470. };
  1471. }
  1472. static int getControlAEState (jobject captureResult)
  1473. {
  1474. auto controlAeStateValue = getCaptureResultIntegerKeyValue (CaptureResult.CONTROL_AE_STATE, captureResult);
  1475. return controlAeStateValue.get() != nullptr
  1476. ? getEnv()->CallIntMethod (controlAeStateValue, JavaInteger.intValue) : -1;
  1477. }
  1478. static bool autoFocusHasFinished (const LocalRef<jobject>& controlAfStateValue)
  1479. {
  1480. static constexpr int controlAfStateFocusedLocked = 4;
  1481. static constexpr int controlAfStateNotFocusedLocked = 5;
  1482. auto controlAfStateIntValue = getEnv()->CallIntMethod (controlAfStateValue, JavaInteger.intValue);
  1483. return controlAfStateIntValue == controlAfStateFocusedLocked || controlAfStateIntValue == controlAfStateNotFocusedLocked;
  1484. }
  1485. static LocalRef<jobject> getCaptureResultIntegerKeyValue (jfieldID key, jobject captureResult)
  1486. {
  1487. auto* env = getEnv();
  1488. auto jKey = LocalRef<jobject> (env->GetStaticObjectField (CaptureResult, key));
  1489. return LocalRef<jobject> (env->CallObjectMethod (captureResult, CaptureResult.get, jKey.get()));
  1490. }
  1491. void captureStillPictureDelayed()
  1492. {
  1493. if (jniCheckHasExceptionOccurredAndClear())
  1494. return;
  1495. JUCE_CAMERA_LOG ("Still picture capture, device ready, capturing now...");
  1496. auto* env = getEnv();
  1497. env->CallVoidMethod (captureSession, CameraCaptureSession.stopRepeating);
  1498. if (jniCheckHasExceptionOccurredAndClear())
  1499. return;
  1500. env->CallVoidMethod (captureSession, CameraCaptureSession.abortCaptures);
  1501. if (jniCheckHasExceptionOccurredAndClear())
  1502. return;
  1503. // Delay still picture capture for devices that can't handle it right after
  1504. // stopRepeating/abortCaptures calls.
  1505. if (delayedCaptureRunnable.get() == nullptr)
  1506. delayedCaptureRunnable = GlobalRef (CreateJavaInterface (&runnable, "java/lang/Runnable"));
  1507. env->CallBooleanMethod (handler, AndroidHandler.postDelayed, delayedCaptureRunnable.get(), (jlong) 200);
  1508. }
  1509. void runPrecaptureSequence()
  1510. {
  1511. if (jniCheckHasExceptionOccurredAndClear())
  1512. return;
  1513. auto* env = getEnv();
  1514. static constexpr int controlAePrecaptureTriggerStart = 1;
  1515. CaptureSession::setCaptureRequestBuilderIntegerKey (captureRequestBuilder.get(),
  1516. CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER,
  1517. controlAePrecaptureTriggerStart);
  1518. currentState = State::pendingExposurePrecapture;
  1519. auto previewRequest = LocalRef<jobject> (env->CallObjectMethod (captureRequestBuilder,
  1520. CaptureRequestBuilder.build));
  1521. env->CallIntMethod (captureSession, CameraCaptureSession.capture, previewRequest.get(),
  1522. captureSessionPreviewCaptureCallback.get(), handler.get());
  1523. }
  1524. void unlockFocus()
  1525. {
  1526. if (jniCheckHasExceptionOccurredAndClear())
  1527. return;
  1528. JUCE_CAMERA_LOG ("Unlocking focus...");
  1529. currentState = State::idle;
  1530. auto* env = getEnv();
  1531. static constexpr int controlAfTriggerCancel = 2;
  1532. CaptureSession::setCaptureRequestBuilderIntegerKey (captureRequestBuilder.get(),
  1533. CaptureRequest.CONTROL_AF_TRIGGER,
  1534. controlAfTriggerCancel);
  1535. auto resetAutoFocusRequest = LocalRef<jobject> (env->CallObjectMethod (captureRequestBuilder,
  1536. CaptureRequestBuilder.build));
  1537. env->CallIntMethod (captureSession, CameraCaptureSession.capture, resetAutoFocusRequest.get(),
  1538. nullptr, handler.get());
  1539. if (jniCheckHasExceptionOccurredAndClear())
  1540. return;
  1541. // NB: for preview, using preview capture request again
  1542. env->CallIntMethod (captureSession, CameraCaptureSession.setRepeatingRequest, previewCaptureRequest.get(),
  1543. nullptr, handler.get());
  1544. }
  1545. //==============================================================================
  1546. void run() override
  1547. {
  1548. captureStillPicture();
  1549. }
  1550. void captureStillPicture()
  1551. {
  1552. getEnv()->CallIntMethod (captureSession, CameraCaptureSession.capture,
  1553. stillPictureCaptureRequest.get(), captureSessionStillPictureCaptureCallback.get(),
  1554. nullptr);
  1555. }
  1556. //==============================================================================
  1557. void cameraCaptureSessionCaptureCompleted (bool isPreview, jobject session, jobject request, jobject result)
  1558. {
  1559. JUCE_CAMERA_LOG ("cameraCaptureSessionCaptureCompleted()");
  1560. ignoreUnused (session, request);
  1561. if (isPreview)
  1562. updateState (result);
  1563. else if (currentState != State::idle)
  1564. unlockFocus();
  1565. }
  1566. void cameraCaptureSessionCaptureFailed (bool isPreview, jobject session, jobject request, jobject failure)
  1567. {
  1568. JUCE_CAMERA_LOG ("cameraCaptureSessionCaptureFailed()");
  1569. ignoreUnused (isPreview, session, request, failure);
  1570. }
  1571. void cameraCaptureSessionCaptureProgressed (bool isPreview, jobject session, jobject request, jobject partialResult)
  1572. {
  1573. JUCE_CAMERA_LOG ("cameraCaptureSessionCaptureProgressed()");
  1574. ignoreUnused (session, request);
  1575. if (isPreview)
  1576. updateState (partialResult);
  1577. }
  1578. void cameraCaptureSessionCaptureSequenceAborted (bool isPreview, jobject session, int sequenceId)
  1579. {
  1580. JUCE_CAMERA_LOG ("cameraCaptureSessionCaptureSequenceAborted()");
  1581. ignoreUnused (isPreview, isPreview, session, sequenceId);
  1582. }
  1583. void cameraCaptureSessionCaptureSequenceCompleted (bool isPreview, jobject session, int sequenceId, int64 frameNumber)
  1584. {
  1585. JUCE_CAMERA_LOG ("cameraCaptureSessionCaptureSequenceCompleted()");
  1586. ignoreUnused (isPreview, session, sequenceId, frameNumber);
  1587. }
  1588. void cameraCaptureSessionCaptureStarted (bool isPreview, jobject session, jobject request, int64 timestamp, int64 frameNumber)
  1589. {
  1590. JUCE_CAMERA_LOG ("cameraCaptureSessionCaptureStarted()");
  1591. ignoreUnused (isPreview, session, request, timestamp, frameNumber);
  1592. }
  1593. //==============================================================================
  1594. static void cameraCaptureSessionCaptureCompletedCallback (JNIEnv*, jobject /*object*/, jlong host, jboolean isPreview, jobject rawSession, jobject rawRequest, jobject rawResult)
  1595. {
  1596. if (auto* myself = reinterpret_cast<StillPictureTaker*> (host))
  1597. {
  1598. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1599. LocalRef<jobject> request (getEnv()->NewLocalRef(rawRequest));
  1600. LocalRef<jobject> result (getEnv()->NewLocalRef(rawResult));
  1601. myself->cameraCaptureSessionCaptureCompleted (isPreview != 0, session, request, result);
  1602. }
  1603. }
  1604. static void cameraCaptureSessionCaptureFailedCallback (JNIEnv*, jobject /*object*/, jlong host, jboolean isPreview, jobject rawSession, jobject rawRequest, jobject rawResult)
  1605. {
  1606. if (auto* myself = reinterpret_cast<StillPictureTaker*> (host))
  1607. {
  1608. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1609. LocalRef<jobject> request (getEnv()->NewLocalRef(rawRequest));
  1610. LocalRef<jobject> result (getEnv()->NewLocalRef(rawResult));
  1611. myself->cameraCaptureSessionCaptureFailed (isPreview != 0, session, request, result);
  1612. }
  1613. }
  1614. static void cameraCaptureSessionCaptureProgressedCallback (JNIEnv*, jobject /*object*/, jlong host, jboolean isPreview, jobject rawSession, jobject rawRequest, jobject rawResult)
  1615. {
  1616. if (auto* myself = reinterpret_cast<StillPictureTaker*> (host))
  1617. {
  1618. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1619. LocalRef<jobject> request (getEnv()->NewLocalRef(rawRequest));
  1620. LocalRef<jobject> result (getEnv()->NewLocalRef(rawResult));
  1621. myself->cameraCaptureSessionCaptureProgressed (isPreview != 0, session, request, result);
  1622. }
  1623. }
  1624. static void cameraCaptureSessionCaptureSequenceAbortedCallback (JNIEnv*, jobject /*object*/, jlong host, jboolean isPreview, jobject rawSession, jint sequenceId)
  1625. {
  1626. if (auto* myself = reinterpret_cast<StillPictureTaker*> (host))
  1627. {
  1628. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1629. myself->cameraCaptureSessionCaptureSequenceAborted (isPreview != 0, session, sequenceId);
  1630. }
  1631. }
  1632. static void cameraCaptureSessionCaptureSequenceCompletedCallback (JNIEnv*, jobject /*object*/, jlong host, jboolean isPreview, jobject rawSession, jint sequenceId, jlong frameNumber)
  1633. {
  1634. if (auto* myself = reinterpret_cast<StillPictureTaker*> (host))
  1635. {
  1636. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1637. myself->cameraCaptureSessionCaptureSequenceCompleted (isPreview != 0, session, sequenceId, frameNumber);
  1638. }
  1639. }
  1640. static void cameraCaptureSessionCaptureStartedCallback (JNIEnv*, jobject /*object*/, jlong host, jboolean isPreview, jobject rawSession, jobject rawRequest, jlong timestamp, jlong frameNumber)
  1641. {
  1642. if (auto* myself = reinterpret_cast<StillPictureTaker*> (host))
  1643. {
  1644. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1645. LocalRef<jobject> request (getEnv()->NewLocalRef(rawRequest));
  1646. myself->cameraCaptureSessionCaptureStarted (isPreview != 0, session, request, timestamp, frameNumber);
  1647. }
  1648. }
  1649. };
  1650. //==============================================================================
  1651. ScopedCameraDevice& scopedCameraDevice;
  1652. ConfiguredCallback& configuredCallback;
  1653. GlobalRef& handler;
  1654. GlobalRef captureRequestBuilder;
  1655. GlobalRef previewCaptureRequest;
  1656. GlobalRef captureSessionStateCallback;
  1657. int autoFocusMode;
  1658. GlobalRef captureSession;
  1659. CriticalSection captureSessionLock;
  1660. Atomic<int> pendingClose { 0 };
  1661. std::unique_ptr<StillPictureTaker> stillPictureTaker;
  1662. WaitableEvent closedEvent;
  1663. JUCE_DECLARE_WEAK_REFERENCEABLE (CaptureSession)
  1664. //==============================================================================
  1665. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  1666. METHOD (constructor, "<init>", "(J)V") \
  1667. CALLBACK(cameraCaptureSessionActiveCallback, "cameraCaptureSessionActive", "(JLandroid/hardware/camera2/CameraCaptureSession;)V") \
  1668. CALLBACK(cameraCaptureSessionClosedCallback, "cameraCaptureSessionClosed", "(JLandroid/hardware/camera2/CameraCaptureSession;)V") \
  1669. CALLBACK(cameraCaptureSessionConfigureFailedCallback, "cameraCaptureSessionConfigureFailed", "(JLandroid/hardware/camera2/CameraCaptureSession;)V") \
  1670. CALLBACK(cameraCaptureSessionConfiguredCallback, "cameraCaptureSessionConfigured", "(JLandroid/hardware/camera2/CameraCaptureSession;)V") \
  1671. CALLBACK(cameraCaptureSessionReadyCallback, "cameraCaptureSessionReady", "(JLandroid/hardware/camera2/CameraCaptureSession;)V")
  1672. DECLARE_JNI_CLASS_WITH_MIN_SDK (CameraCaptureSessionStateCallback, "com/rmsl/juce/CameraCaptureSessionStateCallback", 21)
  1673. #undef JNI_CLASS_MEMBERS
  1674. //==============================================================================
  1675. CaptureSession (ScopedCameraDevice& scopedCameraDeviceToUse, ConfiguredCallback& configuredCallbackToUse,
  1676. const LocalRef<jobject>& surfacesList, GlobalRef& handlerToUse,
  1677. int captureSessionTemplate, int autoFocusModeToUse)
  1678. : scopedCameraDevice (scopedCameraDeviceToUse),
  1679. configuredCallback (configuredCallbackToUse),
  1680. handler (handlerToUse),
  1681. captureRequestBuilder (LocalRef<jobject> (getEnv()->CallObjectMethod (scopedCameraDevice.cameraDevice,
  1682. AndroidCameraDevice.createCaptureRequest,
  1683. (jint) captureSessionTemplate))),
  1684. captureSessionStateCallback (LocalRef<jobject> (getEnv()->NewObject (CameraCaptureSessionStateCallback,
  1685. CameraCaptureSessionStateCallback.constructor,
  1686. reinterpret_cast<jlong> (this)))),
  1687. autoFocusMode (autoFocusModeToUse)
  1688. {
  1689. auto* env = getEnv();
  1690. env->CallVoidMethod (scopedCameraDevice.cameraDevice, AndroidCameraDevice.createCaptureSession,
  1691. surfacesList.get(), captureSessionStateCallback.get(), handler.get());
  1692. static constexpr int controlModeAuto = 1;
  1693. setCaptureRequestBuilderIntegerKey (captureRequestBuilder.get(), CaptureRequest.CONTROL_MODE, controlModeAuto);
  1694. setCaptureRequestBuilderIntegerKey (captureRequestBuilder.get(), CaptureRequest.CONTROL_AF_MODE, autoFocusMode);
  1695. }
  1696. static void setCaptureRequestBuilderIntegerKey (jobject captureRequestBuilder, jfieldID key, int value)
  1697. {
  1698. auto* env = getEnv();
  1699. auto jKey = LocalRef<jobject> (env->GetStaticObjectField (CaptureRequest, key));
  1700. auto jValue = LocalRef<jobject> (env->CallStaticObjectMethod (JavaInteger, JavaInteger.valueOf, (jint) value));
  1701. env->CallVoidMethod (captureRequestBuilder, CaptureRequestBuilder.set, jKey.get(), jValue.get());
  1702. }
  1703. void cameraCaptureSessionActive (jobject session)
  1704. {
  1705. JUCE_CAMERA_LOG ("cameraCaptureSessionActive()");
  1706. ignoreUnused (session);
  1707. }
  1708. void cameraCaptureSessionClosed (jobject session)
  1709. {
  1710. JUCE_CAMERA_LOG ("cameraCaptureSessionClosed()");
  1711. ignoreUnused (session);
  1712. closedEvent.signal();
  1713. }
  1714. void cameraCaptureSessionConfigureFailed (jobject session)
  1715. {
  1716. JUCE_CAMERA_LOG ("cameraCaptureSessionConfigureFailed()");
  1717. ignoreUnused (session);
  1718. MessageManager::callAsync ([weakRef = WeakReference<CaptureSession> { this }]
  1719. {
  1720. if (weakRef != nullptr)
  1721. weakRef->configuredCallback.captureSessionConfigured (nullptr);
  1722. });
  1723. }
  1724. void cameraCaptureSessionConfigured (const LocalRef<jobject>& session)
  1725. {
  1726. JUCE_CAMERA_LOG ("cameraCaptureSessionConfigured()");
  1727. if (pendingClose.get() == 1)
  1728. {
  1729. // Already closing, bailout.
  1730. closedEvent.signal();
  1731. GlobalRef s (session);
  1732. MessageManager::callAsync ([s]()
  1733. {
  1734. getEnv()->CallVoidMethod (s, CameraCaptureSession.close);
  1735. });
  1736. return;
  1737. }
  1738. {
  1739. const ScopedLock lock (captureSessionLock);
  1740. captureSession = GlobalRef (session);
  1741. }
  1742. MessageManager::callAsync ([weakRef = WeakReference<CaptureSession> { this }]
  1743. {
  1744. if (weakRef == nullptr)
  1745. return;
  1746. weakRef->stillPictureTaker.reset (new StillPictureTaker (weakRef->captureSession,
  1747. weakRef->captureRequestBuilder,
  1748. weakRef->previewCaptureRequest,
  1749. weakRef->handler,
  1750. weakRef->autoFocusMode));
  1751. weakRef->configuredCallback.captureSessionConfigured (weakRef.get());
  1752. });
  1753. }
  1754. void cameraCaptureSessionReady (const LocalRef<jobject>& session)
  1755. {
  1756. JUCE_CAMERA_LOG ("cameraCaptureSessionReady()");
  1757. ignoreUnused (session);
  1758. }
  1759. //==============================================================================
  1760. static void cameraCaptureSessionActiveCallback (JNIEnv*, jobject, jlong host, jobject rawSession)
  1761. {
  1762. if (auto* myself = reinterpret_cast<CaptureSession*> (host))
  1763. {
  1764. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1765. myself->cameraCaptureSessionActive (session);
  1766. }
  1767. }
  1768. static void cameraCaptureSessionClosedCallback (JNIEnv*, jobject, jlong host, jobject rawSession)
  1769. {
  1770. if (auto* myself = reinterpret_cast<CaptureSession*> (host))
  1771. {
  1772. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1773. myself->cameraCaptureSessionClosed (session);
  1774. }
  1775. }
  1776. static void cameraCaptureSessionConfigureFailedCallback (JNIEnv*, jobject, jlong host, jobject rawSession)
  1777. {
  1778. if (auto* myself = reinterpret_cast<CaptureSession*> (host))
  1779. {
  1780. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1781. myself->cameraCaptureSessionConfigureFailed (session);
  1782. }
  1783. }
  1784. static void cameraCaptureSessionConfiguredCallback (JNIEnv*, jobject, jlong host, jobject rawSession)
  1785. {
  1786. if (auto* myself = reinterpret_cast<CaptureSession*> (host))
  1787. {
  1788. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1789. myself->cameraCaptureSessionConfigured (session);
  1790. }
  1791. }
  1792. static void cameraCaptureSessionReadyCallback (JNIEnv*, jobject, jlong host, jobject rawSession)
  1793. {
  1794. if (auto* myself = reinterpret_cast<CaptureSession*> (host))
  1795. {
  1796. LocalRef<jobject> session (getEnv()->NewLocalRef(rawSession));
  1797. myself->cameraCaptureSessionReady (session);
  1798. }
  1799. }
  1800. //==============================================================================
  1801. friend class ScopedCameraDevice;
  1802. JUCE_DECLARE_NON_COPYABLE (CaptureSession)
  1803. };
  1804. //==============================================================================
  1805. ScopedCameraDevice (Pimpl& ownerToUse, const String& cameraIdToUse, GlobalRef& cameraManagerToUse,
  1806. GlobalRef& handlerToUse, int autoFocusModeToUse)
  1807. : owner (ownerToUse),
  1808. cameraId (cameraIdToUse),
  1809. cameraManager (cameraManagerToUse),
  1810. handler (handlerToUse),
  1811. cameraStateCallback (createCameraStateCallbackObject()),
  1812. autoFocusMode (autoFocusModeToUse)
  1813. {
  1814. open();
  1815. }
  1816. ~ScopedCameraDevice()
  1817. {
  1818. close();
  1819. }
  1820. void open()
  1821. {
  1822. pendingOpen.set (1);
  1823. auto* env = getEnv();
  1824. env->CallVoidMethod (cameraManager, CameraManager.openCamera,
  1825. javaString (cameraId).get(),
  1826. cameraStateCallback.get(), handler.get());
  1827. // If something went wrong we will be pinged in cameraDeviceStateError()
  1828. // callback, silence the redundant exception.
  1829. jniCheckHasExceptionOccurredAndClear();
  1830. }
  1831. void close()
  1832. {
  1833. if (pendingClose.compareAndSetBool (1, 0))
  1834. {
  1835. auto* env = getEnv();
  1836. if (cameraDevice.get() != nullptr)
  1837. {
  1838. env->CallVoidMethod (cameraDevice, AndroidCameraDevice.close);
  1839. closedEvent.wait (-1);
  1840. }
  1841. pendingClose.set (0);
  1842. pendingOpen .set (0);
  1843. cameraDevice.clear();
  1844. }
  1845. }
  1846. bool openedOk() const { return cameraDevice != nullptr; }
  1847. bool hasErrorOccurred() const { return fatalErrorOccurred.get(); }
  1848. CaptureSession* createCaptureSession (CaptureSession::ConfiguredCallback& cc,
  1849. const LocalRef<jobject>& surfacesList,
  1850. GlobalRef& handlerToUse,
  1851. int captureSessionTemplate)
  1852. {
  1853. if (! openedOk())
  1854. {
  1855. jassertfalse;
  1856. return nullptr;
  1857. }
  1858. return new CaptureSession (*this, cc, surfacesList, handlerToUse, captureSessionTemplate, autoFocusMode);
  1859. }
  1860. private:
  1861. Pimpl& owner;
  1862. const String cameraId;
  1863. GlobalRef& cameraManager;
  1864. GlobalRef& handler;
  1865. GlobalRef cameraStateCallback;
  1866. int autoFocusMode;
  1867. GlobalRef cameraDevice;
  1868. Atomic<int> pendingOpen { 0 };
  1869. Atomic<int> pendingClose { 0 };
  1870. Atomic<int> fatalErrorOccurred { 0 };
  1871. String openError;
  1872. WaitableEvent closedEvent;
  1873. //==============================================================================
  1874. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  1875. METHOD (constructor, "<init>", "(J)V") \
  1876. CALLBACK (cameraDeviceStateClosedCallback, "cameraDeviceStateClosed", "(JLandroid/hardware/camera2/CameraDevice;)V") \
  1877. CALLBACK (cameraDeviceStateDisconnectedCallback, "cameraDeviceStateDisconnected", "(JLandroid/hardware/camera2/CameraDevice;)V") \
  1878. CALLBACK (cameraDeviceStateErrorCallback, "cameraDeviceStateError", "(JLandroid/hardware/camera2/CameraDevice;I)V") \
  1879. CALLBACK (cameraDeviceStateOpenedCallback, "cameraDeviceStateOpened", "(JLandroid/hardware/camera2/CameraDevice;)V")
  1880. DECLARE_JNI_CLASS_WITH_MIN_SDK (CameraDeviceStateCallback, "com/rmsl/juce/CameraDeviceStateCallback", 21)
  1881. #undef JNI_CLASS_MEMBERS
  1882. LocalRef<jobject> createCameraStateCallbackObject()
  1883. {
  1884. return LocalRef<jobject> (getEnv()->NewObject (CameraDeviceStateCallback,
  1885. CameraDeviceStateCallback.constructor,
  1886. reinterpret_cast<jlong> (this)));
  1887. }
  1888. //==============================================================================
  1889. void cameraDeviceStateClosed()
  1890. {
  1891. JUCE_CAMERA_LOG ("cameraDeviceStateClosed()");
  1892. closedEvent.signal();
  1893. }
  1894. void cameraDeviceStateDisconnected()
  1895. {
  1896. JUCE_CAMERA_LOG ("cameraDeviceStateDisconnected()");
  1897. if (pendingOpen.compareAndSetBool (0, 1))
  1898. {
  1899. openError = "Device disconnected";
  1900. notifyOpenResult();
  1901. }
  1902. MessageManager::callAsync ([this]() { close(); });
  1903. }
  1904. void cameraDeviceStateError (int errorCode)
  1905. {
  1906. String error = cameraErrorCodeToString (errorCode);
  1907. JUCE_CAMERA_LOG ("cameraDeviceStateError(), error: " + error);
  1908. if (pendingOpen.compareAndSetBool (0, 1))
  1909. {
  1910. openError = error;
  1911. notifyOpenResult();
  1912. }
  1913. fatalErrorOccurred.set (1);
  1914. MessageManager::callAsync ([this, error]()
  1915. {
  1916. owner.cameraDeviceError (error);
  1917. close();
  1918. });
  1919. }
  1920. void cameraDeviceStateOpened (const LocalRef<jobject>& cameraDeviceToUse)
  1921. {
  1922. JUCE_CAMERA_LOG ("cameraDeviceStateOpened()");
  1923. pendingOpen.set (0);
  1924. cameraDevice = GlobalRef (cameraDeviceToUse);
  1925. notifyOpenResult();
  1926. }
  1927. void notifyOpenResult()
  1928. {
  1929. MessageManager::callAsync ([this]() { owner.cameraOpenFinished (openError); });
  1930. }
  1931. //==============================================================================
  1932. static void JNICALL cameraDeviceStateClosedCallback (JNIEnv*, jobject, jlong host, jobject)
  1933. {
  1934. if (auto* myself = reinterpret_cast<ScopedCameraDevice*>(host))
  1935. myself->cameraDeviceStateClosed();
  1936. }
  1937. static void JNICALL cameraDeviceStateDisconnectedCallback (JNIEnv*, jobject, jlong host, jobject)
  1938. {
  1939. if (auto* myself = reinterpret_cast<ScopedCameraDevice*>(host))
  1940. myself->cameraDeviceStateDisconnected();
  1941. }
  1942. static void JNICALL cameraDeviceStateErrorCallback (JNIEnv*, jobject, jlong host, jobject, jint error)
  1943. {
  1944. if (auto* myself = reinterpret_cast<ScopedCameraDevice*>(host))
  1945. myself->cameraDeviceStateError (error);
  1946. }
  1947. static void JNICALL cameraDeviceStateOpenedCallback (JNIEnv*, jobject, jlong host, jobject rawCamera)
  1948. {
  1949. if (auto* myself = reinterpret_cast<ScopedCameraDevice*>(host))
  1950. {
  1951. LocalRef<jobject> camera(getEnv()->NewLocalRef(rawCamera));
  1952. myself->cameraDeviceStateOpened (camera);
  1953. }
  1954. }
  1955. };
  1956. //==============================================================================
  1957. struct CaptureSessionModeBase
  1958. {
  1959. virtual ~CaptureSessionModeBase() = default;
  1960. virtual bool isVideoRecordSession() const = 0;
  1961. virtual void triggerStillPictureCapture() = 0;
  1962. };
  1963. //==============================================================================
  1964. template <typename Mode>
  1965. struct CaptureSessionMode : public CaptureSessionModeBase,
  1966. private PreviewDisplay::Listener,
  1967. private ScopedCameraDevice::CaptureSession::ConfiguredCallback
  1968. {
  1969. ~CaptureSessionMode() override
  1970. {
  1971. captureSession.reset();
  1972. previewDisplay.removeListener (this);
  1973. }
  1974. bool isVideoRecordSession() const override
  1975. {
  1976. return Mode::isVideoRecord();
  1977. }
  1978. void triggerStillPictureCapture() override
  1979. {
  1980. if (captureSession == nullptr)
  1981. {
  1982. // The capture session must be ready before taking a still picture.
  1983. // Did you remember to create and show a preview display?
  1984. jassertfalse;
  1985. return;
  1986. }
  1987. crtp().takeStillPicture();
  1988. }
  1989. protected:
  1990. CaptureSessionMode (Pimpl& ownerToUse, ScopedCameraDevice& cameraDeviceToUse,
  1991. GlobalRef& handlerToUse, PreviewDisplay& pd, int cameraSensorOrientationToUse,
  1992. int cameraLensFacingToUse, StreamConfigurationMap& streamConfigurationMapToUse)
  1993. : owner (ownerToUse),
  1994. scopedCameraDevice (cameraDeviceToUse),
  1995. handler (handlerToUse),
  1996. previewDisplay (pd),
  1997. cameraSensorOrientation (cameraSensorOrientationToUse),
  1998. cameraLensFacing (cameraLensFacingToUse),
  1999. streamConfigurationMap (streamConfigurationMapToUse)
  2000. {
  2001. // async so that the object is fully constructed before the callback gets invoked
  2002. MessageManager::callAsync ([weakRef = WeakReference<CaptureSessionMode<Mode>> { this }]
  2003. {
  2004. if (weakRef != nullptr)
  2005. weakRef->previewDisplay.addListener (weakRef.get());
  2006. });
  2007. }
  2008. Mode& crtp() { return static_cast<Mode&> (*this); }
  2009. void previewDisplayReady() override
  2010. {
  2011. jassert (previewDisplay.isReady());
  2012. JUCE_CAMERA_LOG ("previewDisplayReady()");
  2013. // close previous capture session first
  2014. captureSession.reset();
  2015. if (scopedCameraDevice.hasErrorOccurred())
  2016. {
  2017. JUCE_CAMERA_LOG ("Device error detected, not recreating a new camera session. The device needs to be reopened.");
  2018. return;
  2019. }
  2020. captureSession.reset (scopedCameraDevice.createCaptureSession (*this, crtp().getCaptureSessionSurfaces(),
  2021. handler, Mode::getTemplate()));
  2022. }
  2023. void previewDisplayAboutToBeDestroyed() override
  2024. {
  2025. JUCE_CAMERA_LOG ("previewDisplayAboutToBeDestroyed()");
  2026. stopPreview();
  2027. }
  2028. void captureSessionConfigured (ScopedCameraDevice::CaptureSession* session) override
  2029. {
  2030. if (session == nullptr)
  2031. {
  2032. owner.cameraDeviceError ("Failed to configure camera session.");
  2033. return;
  2034. }
  2035. jassert (session == captureSession.get());
  2036. startSession();
  2037. }
  2038. void startSession()
  2039. {
  2040. if (! captureSession->start (crtp().getTargetSurfaces(), handler))
  2041. {
  2042. jassertfalse;
  2043. JUCE_CAMERA_LOG ("Could not start capture session");
  2044. }
  2045. crtp().sessionStarted();
  2046. }
  2047. void stopPreview()
  2048. {
  2049. if (captureSession != nullptr)
  2050. {
  2051. auto session = captureSession->getNativeSession();
  2052. auto* env = getEnv();
  2053. env->CallVoidMethod (session, CameraCaptureSession.stopRepeating);
  2054. if (jniCheckHasExceptionOccurredAndClear())
  2055. return;
  2056. env->CallVoidMethod (session, CameraCaptureSession.abortCaptures);
  2057. jniCheckHasExceptionOccurredAndClear();
  2058. }
  2059. }
  2060. Pimpl& owner;
  2061. ScopedCameraDevice& scopedCameraDevice;
  2062. GlobalRef& handler;
  2063. PreviewDisplay& previewDisplay;
  2064. int cameraSensorOrientation;
  2065. int cameraLensFacing;
  2066. StreamConfigurationMap& streamConfigurationMap;
  2067. std::unique_ptr<ScopedCameraDevice::CaptureSession> captureSession;
  2068. JUCE_DECLARE_WEAK_REFERENCEABLE (CaptureSessionMode<Mode>)
  2069. };
  2070. //==============================================================================
  2071. struct CaptureSessionPreviewMode : public CaptureSessionMode<CaptureSessionPreviewMode>
  2072. {
  2073. CaptureSessionPreviewMode (Pimpl& ownerToUse, ScopedCameraDevice& cameraDeviceToUse, GlobalRef& handlerToUse,
  2074. PreviewDisplay& pd, ImageReader& ir, int sensorOrientation,
  2075. int cameraLensFacingToUse, StreamConfigurationMap& streamConfigurationMapToUse)
  2076. : CaptureSessionMode<CaptureSessionPreviewMode> (ownerToUse, cameraDeviceToUse, handlerToUse, pd,
  2077. sensorOrientation, cameraLensFacingToUse, streamConfigurationMapToUse),
  2078. imageReader (ir)
  2079. {
  2080. }
  2081. // Surfaces passed to newly created capture session.
  2082. LocalRef<jobject> getCaptureSessionSurfaces() const
  2083. {
  2084. auto* env = getEnv();
  2085. auto previewSurface = LocalRef<jobject> (previewDisplay.createSurface());
  2086. auto imageSurface = LocalRef<jobject> (imageReader.getSurface());
  2087. auto arrayList = LocalRef<jobject> (env->NewObject (JavaArrayList, JavaArrayList.constructor, 2));
  2088. env->CallBooleanMethod (arrayList, JavaArrayList.add, previewSurface.get());
  2089. env->CallBooleanMethod (arrayList, JavaArrayList.add, imageSurface.get());
  2090. auto supported = streamConfigurationMap.isOutputSupportedForSurface (imageSurface);
  2091. // Output surface is not supported by this device, still image capture will not work!
  2092. jassert (supported);
  2093. return arrayList;
  2094. }
  2095. // Surfaces set as target during capture.
  2096. LocalRef<jobject> getTargetSurfaces() const
  2097. {
  2098. auto* env = getEnv();
  2099. auto previewSurface = LocalRef<jobject> (previewDisplay.createSurface());
  2100. auto arrayList = LocalRef<jobject> (env->NewObject (JavaArrayList, JavaArrayList.constructor, 1));
  2101. env->CallBooleanMethod (arrayList, JavaArrayList.add, previewSurface.get());
  2102. return arrayList;
  2103. }
  2104. static int getTemplate()
  2105. {
  2106. static constexpr int templatePreview = 1;
  2107. return templatePreview;
  2108. }
  2109. static bool isVideoRecord() { return false; }
  2110. void sessionStarted() {}
  2111. void takeStillPicture()
  2112. {
  2113. imageReader.resetNotificationFlag();
  2114. captureSession->takeStillPicture (imageReader.getSurface());
  2115. }
  2116. private:
  2117. ImageReader& imageReader;
  2118. };
  2119. //==============================================================================
  2120. struct CaptureSessionVideoRecordingMode : public CaptureSessionMode<CaptureSessionVideoRecordingMode>
  2121. {
  2122. CaptureSessionVideoRecordingMode (Pimpl& ownerToUse, ScopedCameraDevice& cameraDeviceToUse, GlobalRef& handlerToUse,
  2123. PreviewDisplay& pd, MediaRecorder& mr, int sensorOrientation,
  2124. int cameraLensFacingToUse, StreamConfigurationMap& streamConfigurationMapToUse)
  2125. : CaptureSessionMode<CaptureSessionVideoRecordingMode> (ownerToUse, cameraDeviceToUse, handlerToUse, pd,
  2126. sensorOrientation, cameraLensFacingToUse, streamConfigurationMapToUse),
  2127. mediaRecorder (mr)
  2128. {
  2129. }
  2130. ~CaptureSessionVideoRecordingMode()
  2131. {
  2132. // We need to explicitly stop the preview before stopping the media recorder,
  2133. // because legacy devices can't handle recording stop before stopping the preview.
  2134. stopPreview();
  2135. mediaRecorder.stop();
  2136. }
  2137. // Surfaces passed to newly created capture session.
  2138. LocalRef<jobject> getCaptureSessionSurfaces() const
  2139. {
  2140. auto* env = getEnv();
  2141. auto previewSurface = LocalRef<jobject> (previewDisplay.createSurface());
  2142. auto mediaRecorderSurface = LocalRef<jobject> (mediaRecorder.getSurface());
  2143. auto arrayList = LocalRef<jobject> (env->NewObject (JavaArrayList, JavaArrayList.constructor, 2));
  2144. env->CallBooleanMethod (arrayList, JavaArrayList.add, previewSurface.get());
  2145. env->CallBooleanMethod (arrayList, JavaArrayList.add, mediaRecorderSurface.get());
  2146. return arrayList;
  2147. }
  2148. // Surfaces set as target during capture.
  2149. LocalRef<jobject> getTargetSurfaces() const
  2150. {
  2151. // Same surfaces used.
  2152. return getCaptureSessionSurfaces();
  2153. }
  2154. static int getTemplate()
  2155. {
  2156. static constexpr int templateRecord = 3;
  2157. return templateRecord;
  2158. }
  2159. static bool isVideoRecord() { return true; }
  2160. void sessionStarted()
  2161. {
  2162. MessageManager::callAsync ([this]() { mediaRecorder.start(); });
  2163. }
  2164. void takeStillPicture()
  2165. {
  2166. // Taking still pictures while recording video is not supported on Android.
  2167. jassertfalse;
  2168. }
  2169. private:
  2170. MediaRecorder& mediaRecorder;
  2171. };
  2172. //==============================================================================
  2173. class DeviceOrientationChangeListener : private Timer
  2174. {
  2175. public:
  2176. DeviceOrientationChangeListener (PreviewDisplay& pd)
  2177. : previewDisplay (pd),
  2178. orientationEventListener (createOrientationEventListener()),
  2179. canDetectChange (getEnv()->CallBooleanMethod (orientationEventListener,
  2180. OrientationEventListener.canDetectOrientation) != 0),
  2181. deviceOrientation (Desktop::getInstance().getCurrentOrientation()),
  2182. lastKnownScreenOrientation (deviceOrientation)
  2183. {
  2184. setEnabled (true);
  2185. }
  2186. ~DeviceOrientationChangeListener() override
  2187. {
  2188. setEnabled (false);
  2189. }
  2190. void setEnabled (bool shouldBeEnabled)
  2191. {
  2192. if (shouldBeEnabled && ! canDetectChange)
  2193. {
  2194. // This device does not support orientation listening, photos may have wrong orientation!
  2195. jassertfalse;
  2196. return;
  2197. }
  2198. if (shouldBeEnabled)
  2199. getEnv()->CallVoidMethod (orientationEventListener, OrientationEventListener.enable);
  2200. else
  2201. getEnv()->CallVoidMethod (orientationEventListener, OrientationEventListener.disable);
  2202. }
  2203. bool isSupported() const noexcept { return canDetectChange; }
  2204. Desktop::DisplayOrientation getDeviceOrientation() const noexcept
  2205. {
  2206. return deviceOrientation;
  2207. }
  2208. private:
  2209. PreviewDisplay& previewDisplay;
  2210. GlobalRef orientationEventListener;
  2211. static constexpr jint sensorDelayUI = 2;
  2212. bool canDetectChange;
  2213. Desktop::DisplayOrientation deviceOrientation;
  2214. Desktop::DisplayOrientation lastKnownScreenOrientation;
  2215. int numChecksForOrientationChange = 10;
  2216. //==============================================================================
  2217. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  2218. METHOD (canDetectOrientation, "canDetectOrientation", "()Z") \
  2219. METHOD (constructor, "<init>", "(JLandroid/content/Context;I)V") \
  2220. METHOD (disable, "disable", "()V") \
  2221. METHOD (enable, "enable", "()V") \
  2222. CALLBACK (deviceOrientationChanged, "deviceOrientationChanged", "(JI)V")
  2223. DECLARE_JNI_CLASS_WITH_MIN_SDK (OrientationEventListener, "com/rmsl/juce/JuceOrientationEventListener", 21)
  2224. #undef JNI_CLASS_MEMBERS
  2225. LocalRef<jobject> createOrientationEventListener()
  2226. {
  2227. return LocalRef<jobject> (getEnv()->NewObject (OrientationEventListener,
  2228. OrientationEventListener.constructor,
  2229. reinterpret_cast<jlong> (this),
  2230. getAppContext().get(),
  2231. sensorDelayUI));
  2232. }
  2233. //==============================================================================
  2234. void orientationChanged (int orientation)
  2235. {
  2236. jassert (orientation < 360);
  2237. // -1 == unknown
  2238. if (orientation < 0)
  2239. return;
  2240. auto oldOrientation = deviceOrientation;
  2241. // NB: this assumes natural position to be portrait always, but some devices may be landscape...
  2242. if (orientation > (360 - 45) || orientation < 45)
  2243. deviceOrientation = Desktop::upright;
  2244. else if (orientation < 135)
  2245. deviceOrientation = Desktop::rotatedClockwise;
  2246. else if (orientation < 225)
  2247. deviceOrientation = Desktop::upsideDown;
  2248. else
  2249. deviceOrientation = Desktop::rotatedAntiClockwise;
  2250. if (oldOrientation != deviceOrientation)
  2251. {
  2252. lastKnownScreenOrientation = Desktop::getInstance().getCurrentOrientation();
  2253. // Need to update preview transform, but screen orientation will change slightly
  2254. // later than sensor orientation.
  2255. startTimer (500);
  2256. }
  2257. }
  2258. void timerCallback() override
  2259. {
  2260. auto currentOrientation = Desktop::getInstance().getCurrentOrientation();
  2261. if (lastKnownScreenOrientation != currentOrientation)
  2262. {
  2263. lastKnownScreenOrientation = currentOrientation;
  2264. stopTimer();
  2265. numChecksForOrientationChange = 10;
  2266. previewDisplay.updateSurfaceTransform();
  2267. return;
  2268. }
  2269. if (--numChecksForOrientationChange == 0)
  2270. {
  2271. stopTimer();
  2272. numChecksForOrientationChange = 10;
  2273. }
  2274. }
  2275. static void deviceOrientationChanged (JNIEnv*, jobject /*obj*/, jlong host, jint orientation)
  2276. {
  2277. if (auto* myself = reinterpret_cast<DeviceOrientationChangeListener*> (host))
  2278. myself->orientationChanged (orientation);
  2279. }
  2280. };
  2281. //==============================================================================
  2282. CameraDevice& owner;
  2283. int minWidth, minHeight, maxWidth, maxHeight;
  2284. String cameraId;
  2285. InternalOpenCameraResultCallback cameraOpenCallback;
  2286. GlobalRef activityLifeListener;
  2287. GlobalRef cameraManager;
  2288. GlobalRef cameraCharacteristics;
  2289. GlobalRef handlerThread;
  2290. GlobalRef handler;
  2291. StreamConfigurationMap streamConfigurationMap;
  2292. PreviewDisplay previewDisplay;
  2293. DeviceOrientationChangeListener deviceOrientationChangeListener;
  2294. std::unique_ptr<ImageReader> imageReader;
  2295. std::unique_ptr<MediaRecorder> mediaRecorder;
  2296. std::unique_ptr<CaptureSessionModeBase> currentCaptureSessionMode;
  2297. std::unique_ptr<ScopedCameraDevice> scopedCameraDevice;
  2298. CriticalSection listenerLock;
  2299. ListenerList<Listener> listeners;
  2300. std::function<void (const Image&)> pictureTakenCallback;
  2301. Time firstRecordedFrameTimeMs;
  2302. bool notifiedOfCameraOpening = false;
  2303. bool appWasPaused = false;
  2304. //==============================================================================
  2305. int getCameraSensorOrientation() const
  2306. {
  2307. return getCameraCharacteristicsIntegerKeyValue (CameraCharacteristics.SENSOR_ORIENTATION);
  2308. }
  2309. int getAutoFocusModeToUse() const
  2310. {
  2311. auto supportedModes = getSupportedAutoFocusModes();
  2312. enum
  2313. {
  2314. CONTROL_AF_MODE_OFF = 0,
  2315. CONTROL_AF_MODE_AUTO = 1,
  2316. CONTROL_AF_MODE_CONTINUOUS_PICTURE = 4
  2317. };
  2318. if (supportedModes.contains (CONTROL_AF_MODE_CONTINUOUS_PICTURE))
  2319. return CONTROL_AF_MODE_CONTINUOUS_PICTURE;
  2320. if (supportedModes.contains (CONTROL_AF_MODE_AUTO))
  2321. return CONTROL_AF_MODE_AUTO;
  2322. return CONTROL_AF_MODE_OFF;
  2323. }
  2324. Array<int> getSupportedAutoFocusModes() const
  2325. {
  2326. auto* env = getEnv();
  2327. auto jKey = LocalRef<jobject> (env->GetStaticObjectField (CameraCharacteristics, CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES));
  2328. auto supportedModes = LocalRef<jintArray> ((jintArray) env->CallObjectMethod (cameraCharacteristics,
  2329. CameraCharacteristics.get,
  2330. jKey.get()));
  2331. return jintArrayToJuceArray (supportedModes);
  2332. }
  2333. static Array<int> jintArrayToJuceArray (const LocalRef<jintArray>& jArray)
  2334. {
  2335. auto* env = getEnv();
  2336. auto* jArrayElems = env->GetIntArrayElements (jArray, nullptr);
  2337. auto numElems = env->GetArrayLength (jArray);
  2338. Array<int> juceArray;
  2339. for (int s = 0; s < numElems; ++s)
  2340. juceArray.add (jArrayElems[s]);
  2341. env->ReleaseIntArrayElements (jArray, jArrayElems, 0);
  2342. return juceArray;
  2343. }
  2344. int getCameraCharacteristicsIntegerKeyValue (jfieldID key) const
  2345. {
  2346. auto* env = getEnv();
  2347. auto jKey = LocalRef<jobject> (env->GetStaticObjectField (CameraCharacteristics, key));
  2348. auto jValue = LocalRef<jobject> (env->CallObjectMethod (cameraCharacteristics,
  2349. CameraCharacteristics.get,
  2350. jKey.get()));
  2351. return env->CallIntMethod (jValue, JavaInteger.intValue);
  2352. }
  2353. int getCameraLensFacing() const
  2354. {
  2355. return getCameraCharacteristicsIntegerKeyValue (CameraCharacteristics.LENS_FACING);
  2356. }
  2357. //==============================================================================
  2358. void cameraOpenFinished (const String& error)
  2359. {
  2360. JUCE_CAMERA_LOG ("cameraOpenFinished(), error = " + error);
  2361. if (error.isEmpty())
  2362. {
  2363. setupStillImageSize();
  2364. startPreviewMode (*imageReader);
  2365. }
  2366. // Do not notify about camera being reopened on app resume.
  2367. if (! notifiedOfCameraOpening)
  2368. {
  2369. notifiedOfCameraOpening = true;
  2370. invokeCameraOpenCallback (error);
  2371. }
  2372. }
  2373. void cameraDeviceError (const String& error)
  2374. {
  2375. if (owner.onErrorOccurred != nullptr)
  2376. owner.onErrorOccurred (error);
  2377. }
  2378. void invokeCameraOpenCallback (const String& error)
  2379. {
  2380. JUCE_CAMERA_LOG ("invokeCameraOpenCallback(), error = " + error);
  2381. if (cameraOpenCallback != nullptr)
  2382. cameraOpenCallback (cameraId, error);
  2383. }
  2384. //==============================================================================
  2385. void callListeners (const Image& image)
  2386. {
  2387. const ScopedLock sl (listenerLock);
  2388. listeners.call ([=] (Listener& l) { l.imageReceived (image); });
  2389. }
  2390. void notifyPictureTaken (const Image& image)
  2391. {
  2392. JUCE_CAMERA_LOG ("notifyPictureTaken()");
  2393. if (pictureTakenCallback != nullptr)
  2394. pictureTakenCallback (image);
  2395. }
  2396. void triggerStillPictureCapture()
  2397. {
  2398. currentCaptureSessionMode->triggerStillPictureCapture();
  2399. }
  2400. //==============================================================================
  2401. void setupStillImageSize()
  2402. {
  2403. imageReader.reset();
  2404. auto imageSize = chooseBestSize (minWidth, minHeight, maxWidth, maxHeight,
  2405. streamConfigurationMap.getSupportedStillImageOutputSizes());
  2406. imageReader.reset (new ImageReader (*this, handler, imageSize.getWidth(), imageSize.getHeight(),
  2407. getCameraSensorOrientation()));
  2408. }
  2409. static Rectangle<int> chooseBestSize (int minWidth, int minHeight, int maxWidth, int maxHeight,
  2410. Array<Rectangle<int>> supportedSizes)
  2411. {
  2412. Rectangle<int> result;
  2413. for (auto& size : supportedSizes)
  2414. {
  2415. auto width = size.getWidth();
  2416. auto height = size.getHeight();
  2417. if (width < minWidth || width > maxWidth || height < minHeight || height > maxHeight)
  2418. continue;
  2419. if (size.contains (result))
  2420. result = size;
  2421. }
  2422. // None of the supported sizes matches required width & height limitations, picking
  2423. // the first one available...
  2424. jassert (! result.isEmpty());
  2425. if (result.isEmpty())
  2426. result = supportedSizes[0];
  2427. return result;
  2428. }
  2429. //==============================================================================
  2430. void startPreviewMode (ImageReader& ir)
  2431. {
  2432. if (currentCaptureSessionMode != nullptr && ! currentCaptureSessionMode->isVideoRecordSession())
  2433. return;
  2434. // previous mode has to be stopped first
  2435. jassert (currentCaptureSessionMode.get() == nullptr);
  2436. if (scopedCameraDevice == nullptr || ! scopedCameraDevice->openedOk())
  2437. return;
  2438. currentCaptureSessionMode.reset (new CaptureSessionPreviewMode (*this, *scopedCameraDevice, handler,
  2439. previewDisplay, ir,
  2440. getCameraSensorOrientation(),
  2441. getCameraLensFacing(),
  2442. streamConfigurationMap));
  2443. }
  2444. void startVideoRecordingMode (MediaRecorder& mr)
  2445. {
  2446. if (currentCaptureSessionMode != nullptr && currentCaptureSessionMode->isVideoRecordSession())
  2447. return;
  2448. // previous mode has to be stopped first
  2449. jassert (currentCaptureSessionMode.get() == nullptr);
  2450. jassert (scopedCameraDevice != nullptr && scopedCameraDevice->openedOk());
  2451. if (scopedCameraDevice == nullptr || ! scopedCameraDevice->openedOk())
  2452. return;
  2453. currentCaptureSessionMode.reset (new CaptureSessionVideoRecordingMode (*this, *scopedCameraDevice, handler,
  2454. previewDisplay, mr,
  2455. getCameraSensorOrientation(),
  2456. getCameraLensFacing(),
  2457. streamConfigurationMap));
  2458. }
  2459. //==============================================================================
  2460. void onActivityPaused (jobject) override
  2461. {
  2462. JUCE_CAMERA_LOG ("appPaused, closing camera...");
  2463. appWasPaused = true;
  2464. deviceOrientationChangeListener.setEnabled (false);
  2465. // We need to restart the whole session mode when the app gets resumed.
  2466. currentCaptureSessionMode.reset();
  2467. if (scopedCameraDevice != nullptr)
  2468. scopedCameraDevice->close();
  2469. stopBackgroundThread();
  2470. }
  2471. void onActivityResumed (jobject) override
  2472. {
  2473. // Only care about resumed event when paused event was called first.
  2474. if (! appWasPaused)
  2475. return;
  2476. JUCE_CAMERA_LOG ("appResumed, opening camera...");
  2477. deviceOrientationChangeListener.setEnabled (true);
  2478. startBackgroundThread();
  2479. if (scopedCameraDevice != nullptr)
  2480. scopedCameraDevice->open();
  2481. }
  2482. void startBackgroundThread()
  2483. {
  2484. auto* env = getEnv();
  2485. handlerThread = GlobalRef (LocalRef<jobject> (env->NewObject (AndroidHandlerThread,
  2486. AndroidHandlerThread.constructor,
  2487. javaString ("JuceCameraDeviceBackgroundThread").get())));
  2488. // handler thread has to be started before its looper can be fetched
  2489. env->CallVoidMethod (handlerThread, AndroidHandlerThread.start);
  2490. handler = GlobalRef (LocalRef<jobject> (env->NewObject (AndroidHandler,
  2491. AndroidHandler.constructorWithLooper,
  2492. env->CallObjectMethod (handlerThread, AndroidHandlerThread.getLooper))));
  2493. }
  2494. void stopBackgroundThread()
  2495. {
  2496. auto* env = getEnv();
  2497. auto quitSafelyMethod = env->GetMethodID(AndroidHandlerThread, "quitSafely", "()Z");
  2498. // this code will only run on SDK >= 21
  2499. jassert(quitSafelyMethod != nullptr);
  2500. env->CallBooleanMethod (handlerThread, quitSafelyMethod);
  2501. env->CallVoidMethod (handlerThread, AndroidHandlerThread.join);
  2502. jniCheckHasExceptionOccurredAndClear();
  2503. handlerThread.clear();
  2504. handler.clear();
  2505. }
  2506. friend struct CameraDevice::ViewerComponent;
  2507. JUCE_DECLARE_NON_COPYABLE (Pimpl)
  2508. };
  2509. //==============================================================================
  2510. struct CameraDevice::ViewerComponent : public Component,
  2511. private ComponentMovementWatcher
  2512. {
  2513. ViewerComponent (CameraDevice& device) : ComponentMovementWatcher (this)
  2514. {
  2515. auto previewSize = device.pimpl->streamConfigurationMap.getDefaultPreviewSize();
  2516. targetAspectRatio = (float) previewSize.getWidth() / (float) previewSize.getHeight();
  2517. if (isOrientationLandscape())
  2518. setBounds (previewSize);
  2519. else
  2520. setBounds (0, 0, previewSize.getHeight(), previewSize.getWidth());
  2521. addAndMakeVisible (viewerComponent);
  2522. viewerComponent.setView (device.pimpl->previewDisplay.getNativeView());
  2523. }
  2524. private:
  2525. AndroidViewComponent viewerComponent;
  2526. float targetAspectRatio = 1.0f;
  2527. void componentMovedOrResized (bool, bool) override
  2528. {
  2529. auto b = getLocalBounds().toFloat();
  2530. auto targetWidth = b.getWidth();
  2531. auto targetHeight = b.getHeight();
  2532. if (isOrientationLandscape())
  2533. {
  2534. auto currentAspectRatio = b.getWidth() / b.getHeight();
  2535. if (currentAspectRatio > targetAspectRatio)
  2536. targetWidth = targetWidth * targetAspectRatio / currentAspectRatio;
  2537. else
  2538. targetHeight = targetHeight * currentAspectRatio / targetAspectRatio;
  2539. }
  2540. else
  2541. {
  2542. auto currentAspectRatio = b.getHeight() / b.getWidth();
  2543. if (currentAspectRatio > targetAspectRatio)
  2544. targetHeight = targetHeight * targetAspectRatio / currentAspectRatio;
  2545. else
  2546. targetWidth = targetWidth * currentAspectRatio / targetAspectRatio;
  2547. }
  2548. viewerComponent.setBounds (Rectangle<float> (targetWidth, targetHeight).withCentre (b.getCentre()).toNearestInt());
  2549. }
  2550. bool isOrientationLandscape() const
  2551. {
  2552. auto o = Desktop::getInstance().getCurrentOrientation();
  2553. return o == Desktop::rotatedClockwise || o == Desktop::rotatedAntiClockwise;
  2554. }
  2555. void componentPeerChanged() override {}
  2556. void componentVisibilityChanged() override {}
  2557. JUCE_DECLARE_NON_COPYABLE (ViewerComponent)
  2558. };
  2559. String CameraDevice::getFileExtension()
  2560. {
  2561. return ".mp4";
  2562. }
  2563. //==============================================================================
  2564. CameraDevice::Pimpl::ScopedCameraDevice::CaptureSession::StillPictureTaker::CameraCaptureSessionCaptureCallback_Class CameraDevice::Pimpl::ScopedCameraDevice::CaptureSession::StillPictureTaker::CameraCaptureSessionCaptureCallback;
  2565. CameraDevice::Pimpl::ScopedCameraDevice::CameraDeviceStateCallback_Class CameraDevice::Pimpl::ScopedCameraDevice::CameraDeviceStateCallback;
  2566. CameraDevice::Pimpl::ScopedCameraDevice::CaptureSession::CameraCaptureSessionStateCallback_Class CameraDevice::Pimpl::ScopedCameraDevice::CaptureSession::CameraCaptureSessionStateCallback;
  2567. CameraDevice::Pimpl::DeviceOrientationChangeListener::OrientationEventListener_Class CameraDevice::Pimpl::DeviceOrientationChangeListener::OrientationEventListener;