xref: /aosp_15_r20/frameworks/base/core/jni/android_hardware_Camera.cpp (revision d57664e9bc4670b3ecf6748a746a57c557b6bc9e)
1 /*
2 **
3 ** Copyright 2008, The Android Open Source Project
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 **     http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17 
18 //#define LOG_NDEBUG 0
19 #define LOG_TAG "Camera-JNI"
20 #include <android/content/AttributionSourceState.h>
21 #include <android_os_Parcel.h>
22 #include <android_runtime/android_graphics_SurfaceTexture.h>
23 #include <android_runtime/android_view_Surface.h>
24 #include <binder/IMemory.h>
25 #include <binder/Parcel.h>
26 #include <camera/Camera.h>
27 #include <camera/StringUtils.h>
28 #include <com_android_internal_camera_flags.h>
29 #include <cutils/properties.h>
30 #include <gui/Flags.h>
31 #include <gui/GLConsumer.h>
32 #include <gui/Surface.h>
33 #include <nativehelper/JNIHelp.h>
34 #include <utils/Errors.h>
35 #include <utils/Log.h>
36 #include <utils/Vector.h>
37 
38 #include "core_jni_helpers.h"
39 #include "jni.h"
40 
41 using namespace android;
42 namespace flags = com::android::internal::camera::flags;
43 
44 enum {
45     // Keep up to date with Camera.java
46     CAMERA_HAL_API_VERSION_NORMAL_CONNECT = -2,
47 };
48 
49 struct fields_t {
50     jfieldID    context;
51     jfieldID    facing;
52     jfieldID    orientation;
53     jfieldID    canDisableShutterSound;
54     jfieldID    face_rect;
55     jfieldID    face_score;
56     jfieldID    face_id;
57     jfieldID    face_left_eye;
58     jfieldID    face_right_eye;
59     jfieldID    face_mouth;
60     jfieldID    rect_left;
61     jfieldID    rect_top;
62     jfieldID    rect_right;
63     jfieldID    rect_bottom;
64     jfieldID    point_x;
65     jfieldID    point_y;
66     jmethodID   post_event;
67     jmethodID   rect_constructor;
68     jmethodID   face_constructor;
69     jmethodID   point_constructor;
70 };
71 
72 static fields_t fields;
73 static Mutex sLock;
74 
75 // provides persistent context for calls from native code to Java
76 class JNICameraContext: public CameraListener
77 {
78 public:
79     JNICameraContext(JNIEnv* env, jobject weak_this, jclass clazz, const sp<Camera>& camera);
~JNICameraContext()80     ~JNICameraContext() { release(); }
81     virtual void notify(int32_t msgType, int32_t ext1, int32_t ext2);
82     virtual void postData(int32_t msgType, const sp<IMemory>& dataPtr,
83                           camera_frame_metadata_t *metadata);
84     virtual void postDataTimestamp(nsecs_t timestamp, int32_t msgType, const sp<IMemory>& dataPtr);
85     virtual void postRecordingFrameHandleTimestamp(nsecs_t timestamp, native_handle_t* handle);
86     virtual void postRecordingFrameHandleTimestampBatch(
87             const std::vector<nsecs_t>& timestamps,
88             const std::vector<native_handle_t*>& handles);
89     void postMetadata(JNIEnv *env, int32_t msgType, camera_frame_metadata_t *metadata);
90     void addCallbackBuffer(JNIEnv *env, jbyteArray cbb, int msgType);
91     void setCallbackMode(JNIEnv *env, bool installed, bool manualMode);
getCamera()92     sp<Camera> getCamera() { Mutex::Autolock _l(mLock); return mCamera; }
93     bool isRawImageCallbackBufferAvailable() const;
94     void release();
95 
96 private:
97     void copyAndPost(JNIEnv* env, const sp<IMemory>& dataPtr, int msgType);
98     void clearCallbackBuffers_l(JNIEnv *env, Vector<jbyteArray> *buffers);
99     void clearCallbackBuffers_l(JNIEnv *env);
100     jbyteArray getCallbackBuffer(JNIEnv *env, Vector<jbyteArray> *buffers, size_t bufferSize);
101 
102     jobject     mCameraJObjectWeak;     // weak reference to java object
103     jclass      mCameraJClass;          // strong reference to java class
104     sp<Camera>  mCamera;                // strong reference to native object
105     jclass      mFaceClass;  // strong reference to Face class
106     jclass      mRectClass;  // strong reference to Rect class
107     jclass      mPointClass;  // strong reference to Point class
108     Mutex       mLock;
109 
110     /*
111      * Global reference application-managed raw image buffer queue.
112      *
113      * Manual-only mode is supported for raw image callbacks, which is
114      * set whenever method addCallbackBuffer() with msgType =
115      * CAMERA_MSG_RAW_IMAGE is called; otherwise, null is returned
116      * with raw image callbacks.
117      */
118     Vector<jbyteArray> mRawImageCallbackBuffers;
119 
120     /*
121      * Application-managed preview buffer queue and the flags
122      * associated with the usage of the preview buffer callback.
123      */
124     Vector<jbyteArray> mCallbackBuffers; // Global reference application managed byte[]
125     bool mManualBufferMode;              // Whether to use application managed buffers.
126     bool mManualCameraCallbackSet;       // Whether the callback has been set, used to
127                                          // reduce unnecessary calls to set the callback.
128 };
129 
isRawImageCallbackBufferAvailable() const130 bool JNICameraContext::isRawImageCallbackBufferAvailable() const
131 {
132     return !mRawImageCallbackBuffers.isEmpty();
133 }
134 
get_native_camera(JNIEnv * env,jobject thiz,JNICameraContext ** pContext)135 sp<Camera> get_native_camera(JNIEnv *env, jobject thiz, JNICameraContext** pContext)
136 {
137     sp<Camera> camera;
138     Mutex::Autolock _l(sLock);
139     JNICameraContext* context = reinterpret_cast<JNICameraContext*>(env->GetLongField(thiz, fields.context));
140     if (context != NULL) {
141         camera = context->getCamera();
142     }
143     ALOGV("get_native_camera: context=%p, camera=%p", context, camera.get());
144     if (camera == 0) {
145         jniThrowRuntimeException(env,
146                 "Camera is being used after Camera.release() was called");
147     }
148 
149     if (pContext != NULL) *pContext = context;
150     return camera;
151 }
152 
JNICameraContext(JNIEnv * env,jobject weak_this,jclass clazz,const sp<Camera> & camera)153 JNICameraContext::JNICameraContext(JNIEnv* env, jobject weak_this, jclass clazz, const sp<Camera>& camera)
154 {
155     mCameraJObjectWeak = env->NewGlobalRef(weak_this);
156     mCameraJClass = (jclass)env->NewGlobalRef(clazz);
157     mCamera = camera;
158 
159     jclass faceClazz = env->FindClass("android/hardware/Camera$Face");
160     mFaceClass = (jclass) env->NewGlobalRef(faceClazz);
161 
162     jclass rectClazz = env->FindClass("android/graphics/Rect");
163     mRectClass = (jclass) env->NewGlobalRef(rectClazz);
164 
165     jclass pointClazz = env->FindClass("android/graphics/Point");
166     mPointClass = (jclass) env->NewGlobalRef(pointClazz);
167 
168     mManualBufferMode = false;
169     mManualCameraCallbackSet = false;
170 }
171 
release()172 void JNICameraContext::release()
173 {
174     ALOGV("release");
175     Mutex::Autolock _l(mLock);
176     JNIEnv *env = AndroidRuntime::getJNIEnv();
177 
178     if (mCameraJObjectWeak != NULL) {
179         env->DeleteGlobalRef(mCameraJObjectWeak);
180         mCameraJObjectWeak = NULL;
181     }
182     if (mCameraJClass != NULL) {
183         env->DeleteGlobalRef(mCameraJClass);
184         mCameraJClass = NULL;
185     }
186     if (mFaceClass != NULL) {
187         env->DeleteGlobalRef(mFaceClass);
188         mFaceClass = NULL;
189     }
190     if (mRectClass != NULL) {
191         env->DeleteGlobalRef(mRectClass);
192         mRectClass = NULL;
193     }
194     if (mPointClass != NULL) {
195         env->DeleteGlobalRef(mPointClass);
196         mPointClass = NULL;
197     }
198     clearCallbackBuffers_l(env);
199     mCamera.clear();
200 }
201 
notify(int32_t msgType,int32_t ext1,int32_t ext2)202 void JNICameraContext::notify(int32_t msgType, int32_t ext1, int32_t ext2)
203 {
204     ALOGV("notify");
205 
206     // VM pointer will be NULL if object is released
207     Mutex::Autolock _l(mLock);
208     if (mCameraJObjectWeak == NULL) {
209         ALOGW("callback on dead camera object");
210         return;
211     }
212     JNIEnv *env = AndroidRuntime::getJNIEnv();
213 
214     /*
215      * If the notification or msgType is CAMERA_MSG_RAW_IMAGE_NOTIFY, change it
216      * to CAMERA_MSG_RAW_IMAGE since CAMERA_MSG_RAW_IMAGE_NOTIFY is not exposed
217      * to the Java app.
218      */
219     if (msgType == CAMERA_MSG_RAW_IMAGE_NOTIFY) {
220         msgType = CAMERA_MSG_RAW_IMAGE;
221     }
222 
223     env->CallStaticVoidMethod(mCameraJClass, fields.post_event,
224             mCameraJObjectWeak, msgType, ext1, ext2, NULL);
225 }
226 
getCallbackBuffer(JNIEnv * env,Vector<jbyteArray> * buffers,size_t bufferSize)227 jbyteArray JNICameraContext::getCallbackBuffer(
228         JNIEnv* env, Vector<jbyteArray>* buffers, size_t bufferSize)
229 {
230     jbyteArray obj = NULL;
231 
232     // Vector access should be protected by lock in postData()
233     if (!buffers->isEmpty()) {
234         ALOGV("Using callback buffer from queue of length %zu", buffers->size());
235         jbyteArray globalBuffer = buffers->itemAt(0);
236         buffers->removeAt(0);
237 
238         obj = (jbyteArray)env->NewLocalRef(globalBuffer);
239         env->DeleteGlobalRef(globalBuffer);
240 
241         if (obj != NULL) {
242             jsize bufferLength = env->GetArrayLength(obj);
243             if ((int)bufferLength < (int)bufferSize) {
244                 ALOGE("Callback buffer was too small! Expected %zu bytes, but got %d bytes!",
245                     bufferSize, bufferLength);
246                 env->DeleteLocalRef(obj);
247                 return NULL;
248             }
249         }
250     }
251 
252     return obj;
253 }
254 
copyAndPost(JNIEnv * env,const sp<IMemory> & dataPtr,int msgType)255 void JNICameraContext::copyAndPost(JNIEnv* env, const sp<IMemory>& dataPtr, int msgType)
256 {
257     jbyteArray obj = NULL;
258 
259     // allocate Java byte array and copy data
260     if (dataPtr != NULL) {
261         ssize_t offset;
262         size_t size;
263         sp<IMemoryHeap> heap = dataPtr->getMemory(&offset, &size);
264         if (heap == NULL) {
265             ALOGV("copyAndPost: skipping null memory callback!");
266             return;
267         }
268         ALOGV("copyAndPost: off=%zd, size=%zu", offset, size);
269         uint8_t *heapBase = (uint8_t*)heap->base();
270 
271         if (heapBase != NULL) {
272             const jbyte* data = reinterpret_cast<const jbyte*>(heapBase + offset);
273 
274             if (msgType == CAMERA_MSG_RAW_IMAGE) {
275                 obj = getCallbackBuffer(env, &mRawImageCallbackBuffers, size);
276             } else if (msgType == CAMERA_MSG_PREVIEW_FRAME && mManualBufferMode) {
277                 obj = getCallbackBuffer(env, &mCallbackBuffers, size);
278 
279                 if (mCallbackBuffers.isEmpty()) {
280                     ALOGV("Out of buffers, clearing callback!");
281                     mCamera->setPreviewCallbackFlags(CAMERA_FRAME_CALLBACK_FLAG_NOOP);
282                     mManualCameraCallbackSet = false;
283 
284                     if (obj == NULL) {
285                         return;
286                     }
287                 }
288             } else {
289                 ALOGV("Allocating callback buffer");
290                 obj = env->NewByteArray(size);
291             }
292 
293             if (obj == NULL) {
294                 ALOGE("Couldn't allocate byte array for JPEG data");
295                 env->ExceptionClear();
296             } else {
297                 env->SetByteArrayRegion(obj, 0, size, data);
298             }
299         } else {
300             ALOGE("image heap is NULL");
301         }
302     }
303 
304     // post image data to Java
305     env->CallStaticVoidMethod(mCameraJClass, fields.post_event,
306             mCameraJObjectWeak, msgType, 0, 0, obj);
307     if (obj) {
308         env->DeleteLocalRef(obj);
309     }
310 }
311 
postData(int32_t msgType,const sp<IMemory> & dataPtr,camera_frame_metadata_t * metadata)312 void JNICameraContext::postData(int32_t msgType, const sp<IMemory>& dataPtr,
313                                 camera_frame_metadata_t *metadata)
314 {
315     // VM pointer will be NULL if object is released
316     Mutex::Autolock _l(mLock);
317     JNIEnv *env = AndroidRuntime::getJNIEnv();
318     if (mCameraJObjectWeak == NULL) {
319         ALOGW("callback on dead camera object");
320         return;
321     }
322 
323     int32_t dataMsgType = msgType & ~CAMERA_MSG_PREVIEW_METADATA;
324 
325     // return data based on callback type
326     switch (dataMsgType) {
327         case CAMERA_MSG_VIDEO_FRAME:
328             // should never happen
329             break;
330 
331         // For backward-compatibility purpose, if there is no callback
332         // buffer for raw image, the callback returns null.
333         case CAMERA_MSG_RAW_IMAGE:
334             ALOGV("rawCallback");
335             if (mRawImageCallbackBuffers.isEmpty()) {
336                 env->CallStaticVoidMethod(mCameraJClass, fields.post_event,
337                         mCameraJObjectWeak, dataMsgType, 0, 0, NULL);
338             } else {
339                 copyAndPost(env, dataPtr, dataMsgType);
340             }
341             break;
342 
343         // There is no data.
344         case 0:
345             break;
346 
347         default:
348             ALOGV("dataCallback(%d, %p)", dataMsgType, dataPtr.get());
349             copyAndPost(env, dataPtr, dataMsgType);
350             break;
351     }
352 
353     // post frame metadata to Java
354     if (metadata && (msgType & CAMERA_MSG_PREVIEW_METADATA)) {
355         postMetadata(env, CAMERA_MSG_PREVIEW_METADATA, metadata);
356     }
357 }
358 
postDataTimestamp(nsecs_t timestamp,int32_t msgType,const sp<IMemory> & dataPtr)359 void JNICameraContext::postDataTimestamp(nsecs_t timestamp, int32_t msgType, const sp<IMemory>& dataPtr)
360 {
361     // TODO: plumb up to Java. For now, just drop the timestamp
362     postData(msgType, dataPtr, NULL);
363 }
364 
postRecordingFrameHandleTimestamp(nsecs_t,native_handle_t * handle)365 void JNICameraContext::postRecordingFrameHandleTimestamp(nsecs_t, native_handle_t* handle) {
366     // Video buffers are not needed at app layer so just return the video buffers here.
367     // This may be called when stagefright just releases camera but there are still outstanding
368     // video buffers.
369     if (mCamera != nullptr) {
370         mCamera->releaseRecordingFrameHandle(handle);
371     } else {
372         native_handle_close(handle);
373         native_handle_delete(handle);
374     }
375 }
376 
postRecordingFrameHandleTimestampBatch(const std::vector<nsecs_t> &,const std::vector<native_handle_t * > & handles)377 void JNICameraContext::postRecordingFrameHandleTimestampBatch(
378         const std::vector<nsecs_t>&,
379         const std::vector<native_handle_t*>& handles) {
380     // Video buffers are not needed at app layer so just return the video buffers here.
381     // This may be called when stagefright just releases camera but there are still outstanding
382     // video buffers.
383     if (mCamera != nullptr) {
384         mCamera->releaseRecordingFrameHandleBatch(handles);
385     } else {
386         for (auto& handle : handles) {
387             native_handle_close(handle);
388             native_handle_delete(handle);
389         }
390     }
391 }
392 
postMetadata(JNIEnv * env,int32_t msgType,camera_frame_metadata_t * metadata)393 void JNICameraContext::postMetadata(JNIEnv *env, int32_t msgType, camera_frame_metadata_t *metadata)
394 {
395     jobjectArray obj = NULL;
396     obj = (jobjectArray) env->NewObjectArray(metadata->number_of_faces,
397                                              mFaceClass, NULL);
398     if (obj == NULL) {
399         ALOGE("Couldn't allocate face metadata array");
400         return;
401     }
402 
403     for (int i = 0; i < metadata->number_of_faces; i++) {
404         jobject face = env->NewObject(mFaceClass, fields.face_constructor);
405         env->SetObjectArrayElement(obj, i, face);
406 
407         jobject rect = env->NewObject(mRectClass, fields.rect_constructor);
408         env->SetIntField(rect, fields.rect_left, metadata->faces[i].rect[0]);
409         env->SetIntField(rect, fields.rect_top, metadata->faces[i].rect[1]);
410         env->SetIntField(rect, fields.rect_right, metadata->faces[i].rect[2]);
411         env->SetIntField(rect, fields.rect_bottom, metadata->faces[i].rect[3]);
412 
413         env->SetObjectField(face, fields.face_rect, rect);
414         env->SetIntField(face, fields.face_score, metadata->faces[i].score);
415 
416         bool optionalFields = metadata->faces[i].id != 0
417             && metadata->faces[i].left_eye[0] != -2000 && metadata->faces[i].left_eye[1] != -2000
418             && metadata->faces[i].right_eye[0] != -2000 && metadata->faces[i].right_eye[1] != -2000
419             && metadata->faces[i].mouth[0] != -2000 && metadata->faces[i].mouth[1] != -2000;
420         if (optionalFields) {
421             int32_t id = metadata->faces[i].id;
422             env->SetIntField(face, fields.face_id, id);
423 
424             jobject leftEye = env->NewObject(mPointClass, fields.point_constructor);
425             env->SetIntField(leftEye, fields.point_x, metadata->faces[i].left_eye[0]);
426             env->SetIntField(leftEye, fields.point_y, metadata->faces[i].left_eye[1]);
427             env->SetObjectField(face, fields.face_left_eye, leftEye);
428             env->DeleteLocalRef(leftEye);
429 
430             jobject rightEye = env->NewObject(mPointClass, fields.point_constructor);
431             env->SetIntField(rightEye, fields.point_x, metadata->faces[i].right_eye[0]);
432             env->SetIntField(rightEye, fields.point_y, metadata->faces[i].right_eye[1]);
433             env->SetObjectField(face, fields.face_right_eye, rightEye);
434             env->DeleteLocalRef(rightEye);
435 
436             jobject mouth = env->NewObject(mPointClass, fields.point_constructor);
437             env->SetIntField(mouth, fields.point_x, metadata->faces[i].mouth[0]);
438             env->SetIntField(mouth, fields.point_y, metadata->faces[i].mouth[1]);
439             env->SetObjectField(face, fields.face_mouth, mouth);
440             env->DeleteLocalRef(mouth);
441         }
442 
443         env->DeleteLocalRef(face);
444         env->DeleteLocalRef(rect);
445     }
446     env->CallStaticVoidMethod(mCameraJClass, fields.post_event,
447             mCameraJObjectWeak, msgType, 0, 0, obj);
448     env->DeleteLocalRef(obj);
449 }
450 
setCallbackMode(JNIEnv * env,bool installed,bool manualMode)451 void JNICameraContext::setCallbackMode(JNIEnv *env, bool installed, bool manualMode)
452 {
453     Mutex::Autolock _l(mLock);
454     mManualBufferMode = manualMode;
455     mManualCameraCallbackSet = false;
456 
457     // In order to limit the over usage of binder threads, all non-manual buffer
458     // callbacks use CAMERA_FRAME_CALLBACK_FLAG_BARCODE_SCANNER mode now.
459     //
460     // Continuous callbacks will have the callback re-registered from handleMessage.
461     // Manual buffer mode will operate as fast as possible, relying on the finite supply
462     // of buffers for throttling.
463 
464     if (!installed) {
465         mCamera->setPreviewCallbackFlags(CAMERA_FRAME_CALLBACK_FLAG_NOOP);
466         clearCallbackBuffers_l(env, &mCallbackBuffers);
467     } else if (mManualBufferMode) {
468         if (!mCallbackBuffers.isEmpty()) {
469             mCamera->setPreviewCallbackFlags(CAMERA_FRAME_CALLBACK_FLAG_CAMERA);
470             mManualCameraCallbackSet = true;
471         }
472     } else {
473         mCamera->setPreviewCallbackFlags(CAMERA_FRAME_CALLBACK_FLAG_BARCODE_SCANNER);
474         clearCallbackBuffers_l(env, &mCallbackBuffers);
475     }
476 }
477 
addCallbackBuffer(JNIEnv * env,jbyteArray cbb,int msgType)478 void JNICameraContext::addCallbackBuffer(
479         JNIEnv *env, jbyteArray cbb, int msgType)
480 {
481     ALOGV("addCallbackBuffer: 0x%x", msgType);
482     if (cbb != NULL) {
483         Mutex::Autolock _l(mLock);
484         switch (msgType) {
485             case CAMERA_MSG_PREVIEW_FRAME: {
486                 jbyteArray callbackBuffer = (jbyteArray)env->NewGlobalRef(cbb);
487                 mCallbackBuffers.push(callbackBuffer);
488 
489                 ALOGV("Adding callback buffer to queue, %zu total",
490                         mCallbackBuffers.size());
491 
492                 // We want to make sure the camera knows we're ready for the
493                 // next frame. This may have come unset had we not had a
494                 // callbackbuffer ready for it last time.
495                 if (mManualBufferMode && !mManualCameraCallbackSet) {
496                     mCamera->setPreviewCallbackFlags(CAMERA_FRAME_CALLBACK_FLAG_CAMERA);
497                     mManualCameraCallbackSet = true;
498                 }
499                 break;
500             }
501             case CAMERA_MSG_RAW_IMAGE: {
502                 jbyteArray callbackBuffer = (jbyteArray)env->NewGlobalRef(cbb);
503                 mRawImageCallbackBuffers.push(callbackBuffer);
504                 break;
505             }
506             default: {
507                 jniThrowException(env,
508                         "java/lang/IllegalArgumentException",
509                         "Unsupported message type");
510                 return;
511             }
512         }
513     } else {
514        ALOGE("Null byte array!");
515     }
516 }
517 
clearCallbackBuffers_l(JNIEnv * env)518 void JNICameraContext::clearCallbackBuffers_l(JNIEnv *env)
519 {
520     clearCallbackBuffers_l(env, &mCallbackBuffers);
521     clearCallbackBuffers_l(env, &mRawImageCallbackBuffers);
522 }
523 
clearCallbackBuffers_l(JNIEnv * env,Vector<jbyteArray> * buffers)524 void JNICameraContext::clearCallbackBuffers_l(JNIEnv *env, Vector<jbyteArray> *buffers) {
525     ALOGV("Clearing callback buffers, %zu remained", buffers->size());
526     while (!buffers->isEmpty()) {
527         env->DeleteGlobalRef(buffers->top());
528         buffers->pop();
529     }
530 }
531 
attributionSourceStateForJavaParcel(JNIEnv * env,jobject jClientAttributionParcel,bool useContextAttributionSource,AttributionSourceState & clientAttribution)532 static bool attributionSourceStateForJavaParcel(JNIEnv *env, jobject jClientAttributionParcel,
533                                                 bool useContextAttributionSource,
534                                                 AttributionSourceState &clientAttribution) {
535     const Parcel *clientAttributionParcel = parcelForJavaObject(env, jClientAttributionParcel);
536     if (clientAttribution.readFromParcel(clientAttributionParcel) != ::android::OK) {
537         jniThrowRuntimeException(env, "Fail to unparcel AttributionSourceState");
538         return false;
539     }
540 
541     if (!(useContextAttributionSource && flags::data_delivery_permission_checks())) {
542         clientAttribution.uid = Camera::USE_CALLING_UID;
543         clientAttribution.pid = Camera::USE_CALLING_PID;
544     }
545 
546     return true;
547 }
548 
android_hardware_Camera_getNumberOfCameras(JNIEnv * env,jobject thiz,jobject jClientAttributionParcel,jint devicePolicy)549 static jint android_hardware_Camera_getNumberOfCameras(JNIEnv *env, jobject thiz,
550                                                        jobject jClientAttributionParcel,
551                                                        jint devicePolicy) {
552     AttributionSourceState clientAttribution;
553     if (!attributionSourceStateForJavaParcel(env, jClientAttributionParcel,
554                                              /* useContextAttributionSource= */ false,
555                                              clientAttribution)) {
556         return 0;
557     }
558     return Camera::getNumberOfCameras(clientAttribution, devicePolicy);
559 }
560 
android_hardware_Camera_getCameraInfo(JNIEnv * env,jobject thiz,jint cameraId,jint rotationOverride,jobject jClientAttributionParcel,jint devicePolicy,jobject info_obj)561 static void android_hardware_Camera_getCameraInfo(JNIEnv *env, jobject thiz, jint cameraId,
562                                                   jint rotationOverride,
563                                                   jobject jClientAttributionParcel,
564                                                   jint devicePolicy, jobject info_obj) {
565     AttributionSourceState clientAttribution;
566     if (!attributionSourceStateForJavaParcel(env, jClientAttributionParcel,
567                                              /* useContextAttributionSource= */ false,
568                                              clientAttribution)) {
569         return;
570     }
571 
572     CameraInfo cameraInfo;
573     if (cameraId >= Camera::getNumberOfCameras(clientAttribution, devicePolicy) || cameraId < 0) {
574         ALOGE("%s: Unknown camera ID %d", __FUNCTION__, cameraId);
575         jniThrowRuntimeException(env, "Unknown camera ID");
576         return;
577     }
578 
579     status_t rc = Camera::getCameraInfo(cameraId, rotationOverride, clientAttribution, devicePolicy,
580                                         &cameraInfo);
581     if (rc != NO_ERROR) {
582         jniThrowRuntimeException(env, "Fail to get camera info");
583         return;
584     }
585     env->SetIntField(info_obj, fields.facing, cameraInfo.facing);
586     env->SetIntField(info_obj, fields.orientation, cameraInfo.orientation);
587 
588     char value[PROPERTY_VALUE_MAX];
589     property_get("ro.camera.sound.forced", value, "0");
590     jboolean canDisableShutterSound = (strncmp(value, "0", 2) == 0);
591     env->SetBooleanField(info_obj, fields.canDisableShutterSound,
592             canDisableShutterSound);
593 }
594 
595 // connect to camera service
android_hardware_Camera_native_setup(JNIEnv * env,jobject thiz,jobject weak_this,jint cameraId,jint rotationOverride,jboolean forceSlowJpegMode,jobject jClientAttributionParcel,jint devicePolicy)596 static jint android_hardware_Camera_native_setup(JNIEnv *env, jobject thiz, jobject weak_this,
597                                                  jint cameraId, jint rotationOverride,
598                                                  jboolean forceSlowJpegMode,
599                                                  jobject jClientAttributionParcel,
600                                                  jint devicePolicy) {
601     AttributionSourceState clientAttribution;
602     if (!attributionSourceStateForJavaParcel(env, jClientAttributionParcel,
603                                              /* useContextAttributionSource= */ true,
604                                              clientAttribution)) {
605         return -EACCES;
606     }
607 
608     int targetSdkVersion = android_get_application_target_sdk_version();
609     sp<Camera> camera = Camera::connect(cameraId, targetSdkVersion, rotationOverride,
610                                         forceSlowJpegMode, clientAttribution, devicePolicy);
611     if (camera == NULL) {
612         return -EACCES;
613     }
614 
615     // make sure camera hardware is alive
616     if (camera->getStatus() != NO_ERROR) {
617         return NO_INIT;
618     }
619 
620     jclass clazz = env->GetObjectClass(thiz);
621     if (clazz == NULL) {
622         // This should never happen
623         jniThrowRuntimeException(env, "Can't find android/hardware/Camera");
624         return INVALID_OPERATION;
625     }
626 
627     // We use a weak reference so the Camera object can be garbage collected.
628     // The reference is only used as a proxy for callbacks.
629     sp<JNICameraContext> context = new JNICameraContext(env, weak_this, clazz, camera);
630     context->incStrong((void*)android_hardware_Camera_native_setup);
631     camera->setListener(context);
632 
633     // save context in opaque field
634     env->SetLongField(thiz, fields.context, (jlong)context.get());
635 
636     // Update default display orientation in case the sensor is reverse-landscape
637     CameraInfo cameraInfo;
638     status_t rc = Camera::getCameraInfo(cameraId, rotationOverride, clientAttribution, devicePolicy,
639                                         &cameraInfo);
640     if (rc != NO_ERROR) {
641         ALOGE("%s: getCameraInfo error: %d", __FUNCTION__, rc);
642         return rc;
643     }
644     int defaultOrientation = 0;
645     switch (cameraInfo.orientation) {
646         case 0:
647             break;
648         case 90:
649             if (cameraInfo.facing == CAMERA_FACING_FRONT) {
650                 defaultOrientation = 180;
651             }
652             break;
653         case 180:
654             defaultOrientation = 180;
655             break;
656         case 270:
657             if (cameraInfo.facing != CAMERA_FACING_FRONT) {
658                 defaultOrientation = 180;
659             }
660             break;
661         default:
662             ALOGE("Unexpected camera orientation %d!", cameraInfo.orientation);
663             break;
664     }
665     if (defaultOrientation != 0) {
666         ALOGV("Setting default display orientation to %d", defaultOrientation);
667         rc = camera->sendCommand(CAMERA_CMD_SET_DISPLAY_ORIENTATION,
668                 defaultOrientation, 0);
669         if (rc != NO_ERROR) {
670             ALOGE("Unable to update default orientation: %s (%d)",
671                     strerror(-rc), rc);
672             return rc;
673         }
674     }
675 
676     return NO_ERROR;
677 }
678 
679 // disconnect from camera service
680 // It's okay to call this when the native camera context is already null.
681 // This handles the case where the user has called release() and the
682 // finalizer is invoked later.
android_hardware_Camera_release(JNIEnv * env,jobject thiz)683 static void android_hardware_Camera_release(JNIEnv *env, jobject thiz)
684 {
685     ALOGV("release camera");
686     JNICameraContext* context = NULL;
687     sp<Camera> camera;
688     {
689         Mutex::Autolock _l(sLock);
690         context = reinterpret_cast<JNICameraContext*>(env->GetLongField(thiz, fields.context));
691 
692         // Make sure we do not attempt to callback on a deleted Java object.
693         env->SetLongField(thiz, fields.context, 0);
694     }
695 
696     // clean up if release has not been called before
697     if (context != NULL) {
698         camera = context->getCamera();
699         context->release();
700         ALOGV("native_release: context=%p camera=%p", context, camera.get());
701 
702         // clear callbacks
703         if (camera != NULL) {
704             camera->setPreviewCallbackFlags(CAMERA_FRAME_CALLBACK_FLAG_NOOP);
705             camera->disconnect();
706         }
707 
708         // remove context to prevent further Java access
709         context->decStrong((void*)android_hardware_Camera_native_setup);
710     }
711 }
712 
android_hardware_Camera_setPreviewSurface(JNIEnv * env,jobject thiz,jobject jSurface)713 static void android_hardware_Camera_setPreviewSurface(JNIEnv *env, jobject thiz, jobject jSurface)
714 {
715     ALOGV("setPreviewSurface");
716     sp<Camera> camera = get_native_camera(env, thiz, NULL);
717     if (camera == 0) return;
718 
719     sp<Surface> surface;
720     if (jSurface) {
721         surface = android_view_Surface_getSurface(env, jSurface);
722     }
723 
724 #if WB_LIBCAMERASERVICE_WITH_DEPENDENCIES
725     if (camera->setPreviewTarget(surface) != NO_ERROR) {
726 #else
727     sp<IGraphicBufferProducer> gbp;
728     if (surface != NULL) {
729         gbp = surface->getIGraphicBufferProducer();
730     }
731     if (camera->setPreviewTarget(gbp) != NO_ERROR) {
732 #endif
733         jniThrowException(env, "java/io/IOException", "setPreviewTexture failed");
734     }
735 }
736 
737 static void android_hardware_Camera_setPreviewTexture(JNIEnv *env,
738         jobject thiz, jobject jSurfaceTexture)
739 {
740     ALOGV("setPreviewTexture");
741     sp<Camera> camera = get_native_camera(env, thiz, NULL);
742     if (camera == 0) return;
743 
744 #if WB_LIBCAMERASERVICE_WITH_DEPENDENCIES
745     sp<Surface> surface;
746 #endif
747     sp<IGraphicBufferProducer> producer = NULL;
748     if (jSurfaceTexture != NULL) {
749         producer = SurfaceTexture_getProducer(env, jSurfaceTexture);
750         if (producer == NULL) {
751             jniThrowException(env, "java/lang/IllegalArgumentException",
752                     "SurfaceTexture already released in setPreviewTexture");
753             return;
754         }
755 #if WB_LIBCAMERASERVICE_WITH_DEPENDENCIES
756         surface = new Surface(producer);
757 #endif
758     }
759 
760 #if WB_LIBCAMERASERVICE_WITH_DEPENDENCIES
761     if (camera->setPreviewTarget(surface) != NO_ERROR) {
762 #else
763     if (camera->setPreviewTarget(producer) != NO_ERROR) {
764 #endif
765         jniThrowException(env, "java/io/IOException",
766                 "setPreviewTexture failed");
767     }
768 }
769 
770 static void android_hardware_Camera_setPreviewCallbackSurface(JNIEnv *env,
771         jobject thiz, jobject jSurface)
772 {
773     ALOGV("setPreviewCallbackSurface");
774     JNICameraContext* context;
775     sp<Camera> camera = get_native_camera(env, thiz, &context);
776     if (camera == 0) return;
777 
778 #if !WB_LIBCAMERASERVICE_WITH_DEPENDENCIES
779     sp<IGraphicBufferProducer> gbp;
780 #endif
781     sp<Surface> surface;
782     if (jSurface) {
783         surface = android_view_Surface_getSurface(env, jSurface);
784         if (surface == NULL) {
785             jniThrowException(env, "java/lang/IllegalArgumentException",
786                               "android_view_Surface_getSurface failed");
787             return;
788         }
789 
790 #if !WB_LIBCAMERASERVICE_WITH_DEPENDENCIES
791         if (surface != NULL) {
792             gbp = surface->getIGraphicBufferProducer();
793         }
794 #endif
795     }
796     // Clear out normal preview callbacks
797     context->setCallbackMode(env, false, false);
798     // Then set up callback surface
799 #if WB_LIBCAMERASERVICE_WITH_DEPENDENCIES
800     if (camera->setPreviewCallbackTarget(surface) != NO_ERROR) {
801 #else
802     if (camera->setPreviewCallbackTarget(gbp) != NO_ERROR) {
803 #endif
804         jniThrowException(env, "java/io/IOException", "setPreviewCallbackTarget failed");
805     }
806 }
807 
808 static void android_hardware_Camera_startPreview(JNIEnv *env, jobject thiz)
809 {
810     ALOGV("startPreview");
811     sp<Camera> camera = get_native_camera(env, thiz, NULL);
812     if (camera == 0) return;
813 
814     if (camera->startPreview() != NO_ERROR) {
815         jniThrowRuntimeException(env, "startPreview failed");
816         return;
817     }
818 }
819 
820 static void android_hardware_Camera_stopPreview(JNIEnv *env, jobject thiz)
821 {
822     ALOGV("stopPreview");
823     sp<Camera> c = get_native_camera(env, thiz, NULL);
824     if (c == 0) return;
825 
826     c->stopPreview();
827 }
828 
829 static jboolean android_hardware_Camera_previewEnabled(JNIEnv *env, jobject thiz)
830 {
831     ALOGV("previewEnabled");
832     sp<Camera> c = get_native_camera(env, thiz, NULL);
833     if (c == 0) return JNI_FALSE;
834 
835     return c->previewEnabled() ? JNI_TRUE : JNI_FALSE;
836 }
837 
838 static void android_hardware_Camera_setHasPreviewCallback(JNIEnv *env, jobject thiz, jboolean installed, jboolean manualBuffer)
839 {
840     ALOGV("setHasPreviewCallback: installed:%d, manualBuffer:%d", (int)installed, (int)manualBuffer);
841     // Important: Only install preview_callback if the Java code has called
842     // setPreviewCallback() with a non-null value, otherwise we'd pay to memcpy
843     // each preview frame for nothing.
844     JNICameraContext* context;
845     sp<Camera> camera = get_native_camera(env, thiz, &context);
846     if (camera == 0) return;
847 
848     // setCallbackMode will take care of setting the context flags and calling
849     // camera->setPreviewCallbackFlags within a mutex for us.
850     context->setCallbackMode(env, installed, manualBuffer);
851 }
852 
853 static void android_hardware_Camera_addCallbackBuffer(JNIEnv *env, jobject thiz, jbyteArray bytes, jint msgType) {
854     ALOGV("addCallbackBuffer: 0x%x", msgType);
855 
856     JNICameraContext* context = reinterpret_cast<JNICameraContext*>(env->GetLongField(thiz, fields.context));
857 
858     if (context != NULL) {
859         context->addCallbackBuffer(env, bytes, msgType);
860     }
861 }
862 
863 static void android_hardware_Camera_autoFocus(JNIEnv *env, jobject thiz)
864 {
865     ALOGV("autoFocus");
866     JNICameraContext* context;
867     sp<Camera> c = get_native_camera(env, thiz, &context);
868     if (c == 0) return;
869 
870     if (c->autoFocus() != NO_ERROR) {
871         jniThrowRuntimeException(env, "autoFocus failed");
872     }
873 }
874 
875 static void android_hardware_Camera_cancelAutoFocus(JNIEnv *env, jobject thiz)
876 {
877     ALOGV("cancelAutoFocus");
878     JNICameraContext* context;
879     sp<Camera> c = get_native_camera(env, thiz, &context);
880     if (c == 0) return;
881 
882     if (c->cancelAutoFocus() != NO_ERROR) {
883         jniThrowRuntimeException(env, "cancelAutoFocus failed");
884     }
885 }
886 
887 static void android_hardware_Camera_takePicture(JNIEnv *env, jobject thiz, jint msgType)
888 {
889     ALOGV("takePicture");
890     JNICameraContext* context;
891     sp<Camera> camera = get_native_camera(env, thiz, &context);
892     if (camera == 0) return;
893 
894     /*
895      * When CAMERA_MSG_RAW_IMAGE is requested, if the raw image callback
896      * buffer is available, CAMERA_MSG_RAW_IMAGE is enabled to get the
897      * notification _and_ the data; otherwise, CAMERA_MSG_RAW_IMAGE_NOTIFY
898      * is enabled to receive the callback notification but no data.
899      *
900      * Note that CAMERA_MSG_RAW_IMAGE_NOTIFY is not exposed to the
901      * Java application.
902      */
903     if (msgType & CAMERA_MSG_RAW_IMAGE) {
904         ALOGV("Enable raw image callback buffer");
905         if (!context->isRawImageCallbackBufferAvailable()) {
906             ALOGV("Enable raw image notification, since no callback buffer exists");
907             msgType &= ~CAMERA_MSG_RAW_IMAGE;
908             msgType |= CAMERA_MSG_RAW_IMAGE_NOTIFY;
909         }
910     }
911 
912     if (camera->takePicture(msgType) != NO_ERROR) {
913         jniThrowRuntimeException(env, "takePicture failed");
914         return;
915     }
916 }
917 
918 static void android_hardware_Camera_setParameters(JNIEnv *env, jobject thiz, jstring params)
919 {
920     ALOGV("setParameters");
921     sp<Camera> camera = get_native_camera(env, thiz, NULL);
922     if (camera == 0) return;
923 
924     const jchar* str = env->GetStringCritical(params, 0);
925     String8 params8;
926     if (params) {
927         params8 = String8(reinterpret_cast<const char16_t*>(str),
928                           env->GetStringLength(params));
929         env->ReleaseStringCritical(params, str);
930     }
931     if (camera->setParameters(params8) != NO_ERROR) {
932         jniThrowRuntimeException(env, "setParameters failed");
933         return;
934     }
935 }
936 
937 static jstring android_hardware_Camera_getParameters(JNIEnv *env, jobject thiz)
938 {
939     ALOGV("getParameters");
940     sp<Camera> camera = get_native_camera(env, thiz, NULL);
941     if (camera == 0) return 0;
942 
943     String8 params8 = camera->getParameters();
944     if (params8.empty()) {
945         jniThrowRuntimeException(env, "getParameters failed (empty parameters)");
946         return 0;
947     }
948     return env->NewStringUTF(params8.c_str());
949 }
950 
951 static void android_hardware_Camera_reconnect(JNIEnv *env, jobject thiz)
952 {
953     ALOGV("reconnect");
954     sp<Camera> camera = get_native_camera(env, thiz, NULL);
955     if (camera == 0) return;
956 
957     if (camera->reconnect() != NO_ERROR) {
958         jniThrowException(env, "java/io/IOException", "reconnect failed");
959         return;
960     }
961 }
962 
963 static void android_hardware_Camera_lock(JNIEnv *env, jobject thiz)
964 {
965     ALOGV("lock");
966     sp<Camera> camera = get_native_camera(env, thiz, NULL);
967     if (camera == 0) return;
968 
969     if (camera->lock() != NO_ERROR) {
970         jniThrowRuntimeException(env, "lock failed");
971     }
972 }
973 
974 static void android_hardware_Camera_unlock(JNIEnv *env, jobject thiz)
975 {
976     ALOGV("unlock");
977     sp<Camera> camera = get_native_camera(env, thiz, NULL);
978     if (camera == 0) return;
979 
980     if (camera->unlock() != NO_ERROR) {
981         jniThrowRuntimeException(env, "unlock failed");
982     }
983 }
984 
985 static void android_hardware_Camera_startSmoothZoom(JNIEnv *env, jobject thiz, jint value)
986 {
987     ALOGV("startSmoothZoom");
988     sp<Camera> camera = get_native_camera(env, thiz, NULL);
989     if (camera == 0) return;
990 
991     status_t rc = camera->sendCommand(CAMERA_CMD_START_SMOOTH_ZOOM, value, 0);
992     if (rc == BAD_VALUE) {
993         char msg[64];
994         sprintf(msg, "invalid zoom value=%d", value);
995         jniThrowException(env, "java/lang/IllegalArgumentException", msg);
996     } else if (rc != NO_ERROR) {
997         jniThrowRuntimeException(env, "start smooth zoom failed");
998     }
999 }
1000 
1001 static void android_hardware_Camera_stopSmoothZoom(JNIEnv *env, jobject thiz)
1002 {
1003     ALOGV("stopSmoothZoom");
1004     sp<Camera> camera = get_native_camera(env, thiz, NULL);
1005     if (camera == 0) return;
1006 
1007     if (camera->sendCommand(CAMERA_CMD_STOP_SMOOTH_ZOOM, 0, 0) != NO_ERROR) {
1008         jniThrowRuntimeException(env, "stop smooth zoom failed");
1009     }
1010 }
1011 
1012 static void android_hardware_Camera_setDisplayOrientation(JNIEnv *env, jobject thiz,
1013         jint value)
1014 {
1015     ALOGV("setDisplayOrientation");
1016     sp<Camera> camera = get_native_camera(env, thiz, NULL);
1017     if (camera == 0) return;
1018 
1019     if (camera->sendCommand(CAMERA_CMD_SET_DISPLAY_ORIENTATION, value, 0) != NO_ERROR) {
1020         jniThrowRuntimeException(env, "set display orientation failed");
1021     }
1022 }
1023 
1024 static jboolean android_hardware_Camera_enableShutterSound(JNIEnv *env, jobject thiz,
1025         jboolean enabled)
1026 {
1027     ALOGV("enableShutterSound");
1028     sp<Camera> camera = get_native_camera(env, thiz, NULL);
1029     if (camera == 0) return JNI_FALSE;
1030 
1031     int32_t value = (enabled == JNI_TRUE) ? 1 : 0;
1032     status_t rc = camera->sendCommand(CAMERA_CMD_ENABLE_SHUTTER_SOUND, value, 0);
1033     if (rc == NO_ERROR) {
1034         return JNI_TRUE;
1035     } else if (rc == PERMISSION_DENIED) {
1036         return JNI_FALSE;
1037     } else {
1038         jniThrowRuntimeException(env, "enable shutter sound failed");
1039         return JNI_FALSE;
1040     }
1041 }
1042 
1043 static void android_hardware_Camera_startFaceDetection(JNIEnv *env, jobject thiz,
1044         jint type)
1045 {
1046     ALOGV("startFaceDetection");
1047     JNICameraContext* context;
1048     sp<Camera> camera = get_native_camera(env, thiz, &context);
1049     if (camera == 0) return;
1050 
1051     status_t rc = camera->sendCommand(CAMERA_CMD_START_FACE_DETECTION, type, 0);
1052     if (rc == BAD_VALUE) {
1053         char msg[64];
1054         snprintf(msg, sizeof(msg), "invalid face detection type=%d", type);
1055         jniThrowException(env, "java/lang/IllegalArgumentException", msg);
1056     } else if (rc != NO_ERROR) {
1057         jniThrowRuntimeException(env, "start face detection failed");
1058     }
1059 }
1060 
1061 static void android_hardware_Camera_stopFaceDetection(JNIEnv *env, jobject thiz)
1062 {
1063     ALOGV("stopFaceDetection");
1064     sp<Camera> camera = get_native_camera(env, thiz, NULL);
1065     if (camera == 0) return;
1066 
1067     if (camera->sendCommand(CAMERA_CMD_STOP_FACE_DETECTION, 0, 0) != NO_ERROR) {
1068         jniThrowRuntimeException(env, "stop face detection failed");
1069     }
1070 }
1071 
1072 static void android_hardware_Camera_enableFocusMoveCallback(JNIEnv *env, jobject thiz, jint enable)
1073 {
1074     ALOGV("enableFocusMoveCallback");
1075     sp<Camera> camera = get_native_camera(env, thiz, NULL);
1076     if (camera == 0) return;
1077 
1078     if (camera->sendCommand(CAMERA_CMD_ENABLE_FOCUS_MOVE_MSG, enable, 0) != NO_ERROR) {
1079         jniThrowRuntimeException(env, "enable focus move callback failed");
1080     }
1081 }
1082 
1083 static void android_hardware_Camera_setAudioRestriction(
1084         JNIEnv *env, jobject thiz, jint mode)
1085 {
1086     ALOGV("setAudioRestriction");
1087     sp<Camera> camera = get_native_camera(env, thiz, NULL);
1088     if (camera == 0) {
1089         jniThrowRuntimeException(env, "camera has been disconnected");
1090         return;
1091     }
1092 
1093     int32_t ret = camera->setAudioRestriction(mode);
1094     if (ret < 0) {
1095         jniThrowRuntimeException(env, "Illegal argument or low-level eror");
1096         return;
1097     }
1098 }
1099 
1100 static int32_t android_hardware_Camera_getAudioRestriction(
1101         JNIEnv *env, jobject thiz)
1102 {
1103     ALOGV("getAudioRestriction");
1104     sp<Camera> camera = get_native_camera(env, thiz, NULL);
1105     if (camera == 0) {
1106         jniThrowRuntimeException(env, "camera has been disconnected");
1107         return -1;
1108     }
1109 
1110     int32_t ret = camera->getGlobalAudioRestriction();
1111     if (ret < 0) {
1112         jniThrowRuntimeException(env, "Illegal argument or low-level eror");
1113         return -1;
1114     }
1115     return ret;
1116 }
1117 
1118 //-------------------------------------------------
1119 
1120 static const JNINativeMethod camMethods[] = {
1121         {"_getNumberOfCameras", "(Landroid/os/Parcel;I)I",
1122          (void *)android_hardware_Camera_getNumberOfCameras},
1123         {"_getCameraInfo", "(IILandroid/os/Parcel;ILandroid/hardware/Camera$CameraInfo;)V",
1124          (void *)android_hardware_Camera_getCameraInfo},
1125         {"native_setup", "(Ljava/lang/Object;IIZLandroid/os/Parcel;I)I",
1126          (void *)android_hardware_Camera_native_setup},
1127         {"native_release", "()V", (void *)android_hardware_Camera_release},
1128         {"setPreviewSurface", "(Landroid/view/Surface;)V",
1129          (void *)android_hardware_Camera_setPreviewSurface},
1130         {"setPreviewTexture", "(Landroid/graphics/SurfaceTexture;)V",
1131          (void *)android_hardware_Camera_setPreviewTexture},
1132         {"setPreviewCallbackSurface", "(Landroid/view/Surface;)V",
1133          (void *)android_hardware_Camera_setPreviewCallbackSurface},
1134         {"startPreview", "()V", (void *)android_hardware_Camera_startPreview},
1135         {"_stopPreview", "()V", (void *)android_hardware_Camera_stopPreview},
1136         {"previewEnabled", "()Z", (void *)android_hardware_Camera_previewEnabled},
1137         {"setHasPreviewCallback", "(ZZ)V", (void *)android_hardware_Camera_setHasPreviewCallback},
1138         {"_addCallbackBuffer", "([BI)V", (void *)android_hardware_Camera_addCallbackBuffer},
1139         {"native_autoFocus", "()V", (void *)android_hardware_Camera_autoFocus},
1140         {"native_cancelAutoFocus", "()V", (void *)android_hardware_Camera_cancelAutoFocus},
1141         {"native_takePicture", "(I)V", (void *)android_hardware_Camera_takePicture},
1142         {"native_setParameters", "(Ljava/lang/String;)V",
1143          (void *)android_hardware_Camera_setParameters},
1144         {"native_getParameters", "()Ljava/lang/String;",
1145          (void *)android_hardware_Camera_getParameters},
1146         {"reconnect", "()V", (void *)android_hardware_Camera_reconnect},
1147         {"lock", "()V", (void *)android_hardware_Camera_lock},
1148         {"unlock", "()V", (void *)android_hardware_Camera_unlock},
1149         {"startSmoothZoom", "(I)V", (void *)android_hardware_Camera_startSmoothZoom},
1150         {"stopSmoothZoom", "()V", (void *)android_hardware_Camera_stopSmoothZoom},
1151         {"setDisplayOrientation", "(I)V", (void *)android_hardware_Camera_setDisplayOrientation},
1152         {"_enableShutterSound", "(Z)Z", (void *)android_hardware_Camera_enableShutterSound},
1153         {"_startFaceDetection", "(I)V", (void *)android_hardware_Camera_startFaceDetection},
1154         {"_stopFaceDetection", "()V", (void *)android_hardware_Camera_stopFaceDetection},
1155         {"enableFocusMoveCallback", "(I)V",
1156          (void *)android_hardware_Camera_enableFocusMoveCallback},
1157         {"setAudioRestriction", "(I)V", (void *)android_hardware_Camera_setAudioRestriction},
1158         {"getAudioRestriction", "()I", (void *)android_hardware_Camera_getAudioRestriction},
1159 };
1160 
1161 struct field {
1162     const char *class_name;
1163     const char *field_name;
1164     const char *field_type;
1165     jfieldID   *jfield;
1166 };
1167 
1168 static void find_fields(JNIEnv *env, field *fields, int count)
1169 {
1170     for (int i = 0; i < count; i++) {
1171         field *f = &fields[i];
1172         jclass clazz = FindClassOrDie(env, f->class_name);
1173         jfieldID field = GetFieldIDOrDie(env, clazz, f->field_name, f->field_type);
1174         *(f->jfield) = field;
1175     }
1176 }
1177 
1178 // Get all the required offsets in java class and register native functions
1179 int register_android_hardware_Camera(JNIEnv *env)
1180 {
1181     field fields_to_find[] = {
1182         { "android/hardware/Camera", "mNativeContext",   "J", &fields.context },
1183         { "android/hardware/Camera$CameraInfo", "facing",   "I", &fields.facing },
1184         { "android/hardware/Camera$CameraInfo", "orientation",   "I", &fields.orientation },
1185         { "android/hardware/Camera$CameraInfo", "canDisableShutterSound",   "Z",
1186           &fields.canDisableShutterSound },
1187         { "android/hardware/Camera$Face", "rect", "Landroid/graphics/Rect;", &fields.face_rect },
1188         { "android/hardware/Camera$Face", "leftEye", "Landroid/graphics/Point;", &fields.face_left_eye},
1189         { "android/hardware/Camera$Face", "rightEye", "Landroid/graphics/Point;", &fields.face_right_eye},
1190         { "android/hardware/Camera$Face", "mouth", "Landroid/graphics/Point;", &fields.face_mouth},
1191         { "android/hardware/Camera$Face", "score", "I", &fields.face_score },
1192         { "android/hardware/Camera$Face", "id", "I", &fields.face_id},
1193         { "android/graphics/Rect", "left", "I", &fields.rect_left },
1194         { "android/graphics/Rect", "top", "I", &fields.rect_top },
1195         { "android/graphics/Rect", "right", "I", &fields.rect_right },
1196         { "android/graphics/Rect", "bottom", "I", &fields.rect_bottom },
1197         { "android/graphics/Point", "x", "I", &fields.point_x},
1198         { "android/graphics/Point", "y", "I", &fields.point_y},
1199     };
1200 
1201     find_fields(env, fields_to_find, NELEM(fields_to_find));
1202 
1203     jclass clazz = FindClassOrDie(env, "android/hardware/Camera");
1204     fields.post_event = GetStaticMethodIDOrDie(env, clazz, "postEventFromNative",
1205                                                "(Ljava/lang/Object;IIILjava/lang/Object;)V");
1206 
1207     clazz = FindClassOrDie(env, "android/graphics/Rect");
1208     fields.rect_constructor = GetMethodIDOrDie(env, clazz, "<init>", "()V");
1209 
1210     clazz = FindClassOrDie(env, "android/hardware/Camera$Face");
1211     fields.face_constructor = GetMethodIDOrDie(env, clazz, "<init>", "()V");
1212 
1213     clazz = env->FindClass("android/graphics/Point");
1214     fields.point_constructor = env->GetMethodID(clazz, "<init>", "()V");
1215     if (fields.point_constructor == NULL) {
1216         ALOGE("Can't find android/graphics/Point()");
1217         return -1;
1218     }
1219 
1220     // Register native functions
1221     return RegisterMethodsOrDie(env, "android/hardware/Camera", camMethods, NELEM(camMethods));
1222 }
1223