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