android_hardware_Camera.cpp revision f0d6a48c6ad852b84687127f14b1ffde02416dc4
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 <utils/Log.h>
21
22#include "jni.h"
23#include "JNIHelp.h"
24#include "android_runtime/AndroidRuntime.h"
25
26#include <utils/Vector.h>
27
28#include <gui/SurfaceTexture.h>
29#include <surfaceflinger/Surface.h>
30#include <camera/Camera.h>
31#include <binder/IMemory.h>
32
33using namespace android;
34
35struct fields_t {
36    jfieldID    context;
37    jfieldID    surface;
38    jfieldID    surfaceTexture;
39    jfieldID    facing;
40    jfieldID    orientation;
41    jfieldID    face_rect;
42    jfieldID    face_score;
43    jfieldID    rect_left;
44    jfieldID    rect_top;
45    jfieldID    rect_right;
46    jfieldID    rect_bottom;
47    jmethodID   post_event;
48};
49
50static fields_t fields;
51static Mutex sLock;
52
53// provides persistent context for calls from native code to Java
54class JNICameraContext: public CameraListener
55{
56public:
57    JNICameraContext(JNIEnv* env, jobject weak_this, jclass clazz, const sp<Camera>& camera);
58    ~JNICameraContext() { release(); }
59    virtual void notify(int32_t msgType, int32_t ext1, int32_t ext2);
60    virtual void postData(int32_t msgType, const sp<IMemory>& dataPtr);
61    virtual void postDataTimestamp(nsecs_t timestamp, int32_t msgType, const sp<IMemory>& dataPtr);
62    void addCallbackBuffer(JNIEnv *env, jbyteArray cbb, int msgType);
63    void setCallbackMode(JNIEnv *env, bool installed, bool manualMode);
64    sp<Camera> getCamera() { Mutex::Autolock _l(mLock); return mCamera; }
65    bool isRawImageCallbackBufferAvailable() const;
66    void release();
67
68private:
69    void copyAndPost(JNIEnv* env, const sp<IMemory>& dataPtr, int msgType);
70    void clearCallbackBuffers_l(JNIEnv *env, Vector<jbyteArray> *buffers);
71    void clearCallbackBuffers_l(JNIEnv *env);
72    jbyteArray getCallbackBuffer(JNIEnv *env, Vector<jbyteArray> *buffers, size_t bufferSize);
73
74    jobject     mCameraJObjectWeak;     // weak reference to java object
75    jclass      mCameraJClass;          // strong reference to java class
76    sp<Camera>  mCamera;                // strong reference to native object
77    Mutex       mLock;
78
79    /*
80     * Global reference application-managed raw image buffer queue.
81     *
82     * Manual-only mode is supported for raw image callbacks, which is
83     * set whenever method addCallbackBuffer() with msgType =
84     * CAMERA_MSG_RAW_IMAGE is called; otherwise, null is returned
85     * with raw image callbacks.
86     */
87    Vector<jbyteArray> mRawImageCallbackBuffers;
88
89    /*
90     * Application-managed preview buffer queue and the flags
91     * associated with the usage of the preview buffer callback.
92     */
93    Vector<jbyteArray> mCallbackBuffers; // Global reference application managed byte[]
94    bool mManualBufferMode;              // Whether to use application managed buffers.
95    bool mManualCameraCallbackSet;       // Whether the callback has been set, used to
96                                         // reduce unnecessary calls to set the callback.
97};
98
99bool JNICameraContext::isRawImageCallbackBufferAvailable() const
100{
101    return !mRawImageCallbackBuffers.isEmpty();
102}
103
104sp<Camera> get_native_camera(JNIEnv *env, jobject thiz, JNICameraContext** pContext)
105{
106    sp<Camera> camera;
107    Mutex::Autolock _l(sLock);
108    JNICameraContext* context = reinterpret_cast<JNICameraContext*>(env->GetIntField(thiz, fields.context));
109    if (context != NULL) {
110        camera = context->getCamera();
111    }
112    LOGV("get_native_camera: context=%p, camera=%p", context, camera.get());
113    if (camera == 0) {
114        jniThrowRuntimeException(env, "Method called after release()");
115    }
116
117    if (pContext != NULL) *pContext = context;
118    return camera;
119}
120
121JNICameraContext::JNICameraContext(JNIEnv* env, jobject weak_this, jclass clazz, const sp<Camera>& camera)
122{
123    mCameraJObjectWeak = env->NewGlobalRef(weak_this);
124    mCameraJClass = (jclass)env->NewGlobalRef(clazz);
125    mCamera = camera;
126
127    mManualBufferMode = false;
128    mManualCameraCallbackSet = false;
129}
130
131void JNICameraContext::release()
132{
133    LOGV("release");
134    Mutex::Autolock _l(mLock);
135    JNIEnv *env = AndroidRuntime::getJNIEnv();
136
137    if (mCameraJObjectWeak != NULL) {
138        env->DeleteGlobalRef(mCameraJObjectWeak);
139        mCameraJObjectWeak = NULL;
140    }
141    if (mCameraJClass != NULL) {
142        env->DeleteGlobalRef(mCameraJClass);
143        mCameraJClass = NULL;
144    }
145    clearCallbackBuffers_l(env);
146    mCamera.clear();
147}
148
149void JNICameraContext::notify(int32_t msgType, int32_t ext1, int32_t ext2)
150{
151    LOGV("notify");
152
153    // VM pointer will be NULL if object is released
154    Mutex::Autolock _l(mLock);
155    if (mCameraJObjectWeak == NULL) {
156        LOGW("callback on dead camera object");
157        return;
158    }
159    JNIEnv *env = AndroidRuntime::getJNIEnv();
160
161    /*
162     * If the notification or msgType is CAMERA_MSG_RAW_IMAGE_NOTIFY, change it
163     * to CAMERA_MSG_RAW_IMAGE since CAMERA_MSG_RAW_IMAGE_NOTIFY is not exposed
164     * to the Java app.
165     */
166    if (msgType == CAMERA_MSG_RAW_IMAGE_NOTIFY) {
167        msgType = CAMERA_MSG_RAW_IMAGE;
168    }
169
170    env->CallStaticVoidMethod(mCameraJClass, fields.post_event,
171            mCameraJObjectWeak, msgType, ext1, ext2, NULL);
172}
173
174jbyteArray JNICameraContext::getCallbackBuffer(
175        JNIEnv* env, Vector<jbyteArray>* buffers, size_t bufferSize)
176{
177    jbyteArray obj = NULL;
178
179    // Vector access should be protected by lock in postData()
180    if (!buffers->isEmpty()) {
181        LOGV("Using callback buffer from queue of length %d", buffers->size());
182        jbyteArray globalBuffer = buffers->itemAt(0);
183        buffers->removeAt(0);
184
185        obj = (jbyteArray)env->NewLocalRef(globalBuffer);
186        env->DeleteGlobalRef(globalBuffer);
187
188        if (obj != NULL) {
189            jsize bufferLength = env->GetArrayLength(obj);
190            if ((int)bufferLength < (int)bufferSize) {
191                LOGE("Callback buffer was too small! Expected %d bytes, but got %d bytes!",
192                    bufferSize, bufferLength);
193                env->DeleteLocalRef(obj);
194                return NULL;
195            }
196        }
197    }
198
199    return obj;
200}
201
202void JNICameraContext::copyAndPost(JNIEnv* env, const sp<IMemory>& dataPtr, int msgType)
203{
204    jbyteArray obj = NULL;
205
206    // allocate Java byte array and copy data
207    if (dataPtr != NULL) {
208        ssize_t offset;
209        size_t size;
210        sp<IMemoryHeap> heap = dataPtr->getMemory(&offset, &size);
211        LOGV("copyAndPost: off=%ld, size=%d", offset, size);
212        uint8_t *heapBase = (uint8_t*)heap->base();
213
214        if (heapBase != NULL) {
215            const jbyte* data = reinterpret_cast<const jbyte*>(heapBase + offset);
216
217            if (!mManualBufferMode) {
218                LOGV("Allocating callback buffer");
219                obj = env->NewByteArray(size);
220            } else {
221                switch (msgType) {
222                    case CAMERA_MSG_PREVIEW_FRAME: {
223                        obj = getCallbackBuffer(env, &mCallbackBuffers, size);
224
225                        if (mCallbackBuffers.isEmpty()) {
226                            LOGV("Out of buffers, clearing callback!");
227                            mCamera->setPreviewCallbackFlags(CAMERA_FRAME_CALLBACK_FLAG_NOOP);
228                            mManualCameraCallbackSet = false;
229
230                            if (obj == NULL) {
231                                return;
232                            }
233                        }
234                        break;
235                    }
236                    case CAMERA_MSG_RAW_IMAGE: {
237                        obj = getCallbackBuffer(env, &mRawImageCallbackBuffers, size);
238                        break;
239                    }
240                    default: {
241                        jniThrowRuntimeException(env, "Unsupported message type");
242                        return;
243                    }
244                }
245            }
246
247            if (obj == NULL) {
248                LOGE("Couldn't allocate byte array for JPEG data");
249                env->ExceptionClear();
250            } else {
251                env->SetByteArrayRegion(obj, 0, size, data);
252            }
253        } else {
254            LOGE("image heap is NULL");
255        }
256    }
257
258    // post image data to Java
259    env->CallStaticVoidMethod(mCameraJClass, fields.post_event,
260            mCameraJObjectWeak, msgType, 0, 0, obj);
261    if (obj) {
262        env->DeleteLocalRef(obj);
263    }
264}
265
266void JNICameraContext::postData(int32_t msgType, const sp<IMemory>& dataPtr)
267{
268    // VM pointer will be NULL if object is released
269    Mutex::Autolock _l(mLock);
270    JNIEnv *env = AndroidRuntime::getJNIEnv();
271    if (mCameraJObjectWeak == NULL) {
272        LOGW("callback on dead camera object");
273        return;
274    }
275
276    // return data based on callback type
277    switch (msgType) {
278        case CAMERA_MSG_VIDEO_FRAME:
279            // should never happen
280            break;
281
282        // For backward-compatibility purpose, if there is no callback
283        // buffer for raw image, the callback returns null.
284        case CAMERA_MSG_RAW_IMAGE:
285            LOGV("rawCallback");
286            if (mRawImageCallbackBuffers.isEmpty()) {
287                env->CallStaticVoidMethod(mCameraJClass, fields.post_event,
288                        mCameraJObjectWeak, msgType, 0, 0, NULL);
289            } else {
290                copyAndPost(env, dataPtr, msgType);
291            }
292            break;
293
294        default:
295            LOGV("dataCallback(%d, %p)", msgType, dataPtr.get());
296            copyAndPost(env, dataPtr, msgType);
297            break;
298    }
299}
300
301void JNICameraContext::postDataTimestamp(nsecs_t timestamp, int32_t msgType, const sp<IMemory>& dataPtr)
302{
303    // TODO: plumb up to Java. For now, just drop the timestamp
304    postData(msgType, dataPtr);
305}
306
307void JNICameraContext::setCallbackMode(JNIEnv *env, bool installed, bool manualMode)
308{
309    Mutex::Autolock _l(mLock);
310    mManualBufferMode = manualMode;
311    mManualCameraCallbackSet = false;
312
313    // In order to limit the over usage of binder threads, all non-manual buffer
314    // callbacks use CAMERA_FRAME_CALLBACK_FLAG_BARCODE_SCANNER mode now.
315    //
316    // Continuous callbacks will have the callback re-registered from handleMessage.
317    // Manual buffer mode will operate as fast as possible, relying on the finite supply
318    // of buffers for throttling.
319
320    if (!installed) {
321        mCamera->setPreviewCallbackFlags(CAMERA_FRAME_CALLBACK_FLAG_NOOP);
322        clearCallbackBuffers_l(env, &mCallbackBuffers);
323    } else if (mManualBufferMode) {
324        if (!mCallbackBuffers.isEmpty()) {
325            mCamera->setPreviewCallbackFlags(CAMERA_FRAME_CALLBACK_FLAG_CAMERA);
326            mManualCameraCallbackSet = true;
327        }
328    } else {
329        mCamera->setPreviewCallbackFlags(CAMERA_FRAME_CALLBACK_FLAG_BARCODE_SCANNER);
330        clearCallbackBuffers_l(env, &mCallbackBuffers);
331    }
332}
333
334void JNICameraContext::addCallbackBuffer(
335        JNIEnv *env, jbyteArray cbb, int msgType)
336{
337    LOGV("addCallbackBuffer: 0x%x", msgType);
338    if (cbb != NULL) {
339        Mutex::Autolock _l(mLock);
340        switch (msgType) {
341            case CAMERA_MSG_PREVIEW_FRAME: {
342                jbyteArray callbackBuffer = (jbyteArray)env->NewGlobalRef(cbb);
343                mCallbackBuffers.push(callbackBuffer);
344
345                LOGV("Adding callback buffer to queue, %d total",
346                        mCallbackBuffers.size());
347
348                // We want to make sure the camera knows we're ready for the
349                // next frame. This may have come unset had we not had a
350                // callbackbuffer ready for it last time.
351                if (mManualBufferMode && !mManualCameraCallbackSet) {
352                    mCamera->setPreviewCallbackFlags(CAMERA_FRAME_CALLBACK_FLAG_CAMERA);
353                    mManualCameraCallbackSet = true;
354                }
355                break;
356            }
357            case CAMERA_MSG_RAW_IMAGE: {
358                jbyteArray callbackBuffer = (jbyteArray)env->NewGlobalRef(cbb);
359                mRawImageCallbackBuffers.push(callbackBuffer);
360                break;
361            }
362            default: {
363                jniThrowException(env,
364                        "java/lang/IllegalArgumentException",
365                        "Unsupported message type");
366                return;
367            }
368        }
369    } else {
370       LOGE("Null byte array!");
371    }
372}
373
374void JNICameraContext::clearCallbackBuffers_l(JNIEnv *env)
375{
376    clearCallbackBuffers_l(env, &mCallbackBuffers);
377    clearCallbackBuffers_l(env, &mRawImageCallbackBuffers);
378}
379
380void JNICameraContext::clearCallbackBuffers_l(JNIEnv *env, Vector<jbyteArray> *buffers) {
381    LOGV("Clearing callback buffers, %d remained", buffers->size());
382    while (!buffers->isEmpty()) {
383        env->DeleteGlobalRef(buffers->top());
384        buffers->pop();
385    }
386}
387
388static jint android_hardware_Camera_getNumberOfCameras(JNIEnv *env, jobject thiz)
389{
390    return Camera::getNumberOfCameras();
391}
392
393static void android_hardware_Camera_getCameraInfo(JNIEnv *env, jobject thiz,
394    jint cameraId, jobject info_obj)
395{
396    CameraInfo cameraInfo;
397    status_t rc = Camera::getCameraInfo(cameraId, &cameraInfo);
398    if (rc != NO_ERROR) {
399        jniThrowRuntimeException(env, "Fail to get camera info");
400        return;
401    }
402    env->SetIntField(info_obj, fields.facing, cameraInfo.facing);
403    env->SetIntField(info_obj, fields.orientation, cameraInfo.orientation);
404}
405
406// connect to camera service
407static void android_hardware_Camera_native_setup(JNIEnv *env, jobject thiz,
408    jobject weak_this, jint cameraId)
409{
410    sp<Camera> camera = Camera::connect(cameraId);
411
412    if (camera == NULL) {
413        jniThrowRuntimeException(env, "Fail to connect to camera service");
414        return;
415    }
416
417    // make sure camera hardware is alive
418    if (camera->getStatus() != NO_ERROR) {
419        jniThrowRuntimeException(env, "Camera initialization failed");
420        return;
421    }
422
423    jclass clazz = env->GetObjectClass(thiz);
424    if (clazz == NULL) {
425        jniThrowRuntimeException(env, "Can't find android/hardware/Camera");
426        return;
427    }
428
429    // We use a weak reference so the Camera object can be garbage collected.
430    // The reference is only used as a proxy for callbacks.
431    sp<JNICameraContext> context = new JNICameraContext(env, weak_this, clazz, camera);
432    context->incStrong(thiz);
433    camera->setListener(context);
434
435    // save context in opaque field
436    env->SetIntField(thiz, fields.context, (int)context.get());
437}
438
439// disconnect from camera service
440// It's okay to call this when the native camera context is already null.
441// This handles the case where the user has called release() and the
442// finalizer is invoked later.
443static void android_hardware_Camera_release(JNIEnv *env, jobject thiz)
444{
445    // TODO: Change to LOGV
446    LOGV("release camera");
447    JNICameraContext* context = NULL;
448    sp<Camera> camera;
449    {
450        Mutex::Autolock _l(sLock);
451        context = reinterpret_cast<JNICameraContext*>(env->GetIntField(thiz, fields.context));
452
453        // Make sure we do not attempt to callback on a deleted Java object.
454        env->SetIntField(thiz, fields.context, 0);
455    }
456
457    // clean up if release has not been called before
458    if (context != NULL) {
459        camera = context->getCamera();
460        context->release();
461        LOGV("native_release: context=%p camera=%p", context, camera.get());
462
463        // clear callbacks
464        if (camera != NULL) {
465            camera->setPreviewCallbackFlags(CAMERA_FRAME_CALLBACK_FLAG_NOOP);
466            camera->disconnect();
467        }
468
469        // remove context to prevent further Java access
470        context->decStrong(thiz);
471    }
472}
473
474static void android_hardware_Camera_setPreviewDisplay(JNIEnv *env, jobject thiz, jobject jSurface)
475{
476    LOGV("setPreviewDisplay");
477    sp<Camera> camera = get_native_camera(env, thiz, NULL);
478    if (camera == 0) return;
479
480    sp<Surface> surface = NULL;
481    if (jSurface != NULL) {
482        surface = reinterpret_cast<Surface*>(env->GetIntField(jSurface, fields.surface));
483    }
484    if (camera->setPreviewDisplay(surface) != NO_ERROR) {
485        jniThrowException(env, "java/io/IOException", "setPreviewDisplay failed");
486    }
487}
488
489static void android_hardware_Camera_setPreviewTexture(JNIEnv *env,
490        jobject thiz, jobject jSurfaceTexture)
491{
492    LOGV("setPreviewTexture");
493    sp<Camera> camera = get_native_camera(env, thiz, NULL);
494    if (camera == 0) return;
495
496    sp<SurfaceTexture> surfaceTexture = NULL;
497    if (jSurfaceTexture != NULL) {
498        surfaceTexture = reinterpret_cast<SurfaceTexture*>(env->GetIntField(
499                jSurfaceTexture, fields.surfaceTexture));
500    }
501    if (camera->setPreviewTexture(surfaceTexture) != NO_ERROR) {
502        jniThrowException(env, "java/io/IOException",
503                "setPreviewTexture failed");
504    }
505}
506
507static void android_hardware_Camera_startPreview(JNIEnv *env, jobject thiz)
508{
509    LOGV("startPreview");
510    sp<Camera> camera = get_native_camera(env, thiz, NULL);
511    if (camera == 0) return;
512
513    if (camera->startPreview() != NO_ERROR) {
514        jniThrowRuntimeException(env, "startPreview failed");
515        return;
516    }
517}
518
519static void android_hardware_Camera_stopPreview(JNIEnv *env, jobject thiz)
520{
521    LOGV("stopPreview");
522    sp<Camera> c = get_native_camera(env, thiz, NULL);
523    if (c == 0) return;
524
525    c->stopPreview();
526}
527
528static bool android_hardware_Camera_previewEnabled(JNIEnv *env, jobject thiz)
529{
530    LOGV("previewEnabled");
531    sp<Camera> c = get_native_camera(env, thiz, NULL);
532    if (c == 0) return false;
533
534    return c->previewEnabled();
535}
536
537static void android_hardware_Camera_setHasPreviewCallback(JNIEnv *env, jobject thiz, jboolean installed, jboolean manualBuffer)
538{
539    LOGV("setHasPreviewCallback: installed:%d, manualBuffer:%d", (int)installed, (int)manualBuffer);
540    // Important: Only install preview_callback if the Java code has called
541    // setPreviewCallback() with a non-null value, otherwise we'd pay to memcpy
542    // each preview frame for nothing.
543    JNICameraContext* context;
544    sp<Camera> camera = get_native_camera(env, thiz, &context);
545    if (camera == 0) return;
546
547    // setCallbackMode will take care of setting the context flags and calling
548    // camera->setPreviewCallbackFlags within a mutex for us.
549    context->setCallbackMode(env, installed, manualBuffer);
550}
551
552static void android_hardware_Camera_addCallbackBuffer(JNIEnv *env, jobject thiz, jbyteArray bytes, int msgType) {
553    LOGV("addCallbackBuffer: 0x%x", msgType);
554
555    JNICameraContext* context = reinterpret_cast<JNICameraContext*>(env->GetIntField(thiz, fields.context));
556
557    if (context != NULL) {
558        context->addCallbackBuffer(env, bytes, msgType);
559    }
560}
561
562static void android_hardware_Camera_autoFocus(JNIEnv *env, jobject thiz)
563{
564    LOGV("autoFocus");
565    JNICameraContext* context;
566    sp<Camera> c = get_native_camera(env, thiz, &context);
567    if (c == 0) return;
568
569    if (c->autoFocus() != NO_ERROR) {
570        jniThrowRuntimeException(env, "autoFocus failed");
571    }
572}
573
574static void android_hardware_Camera_cancelAutoFocus(JNIEnv *env, jobject thiz)
575{
576    LOGV("cancelAutoFocus");
577    JNICameraContext* context;
578    sp<Camera> c = get_native_camera(env, thiz, &context);
579    if (c == 0) return;
580
581    if (c->cancelAutoFocus() != NO_ERROR) {
582        jniThrowRuntimeException(env, "cancelAutoFocus failed");
583    }
584}
585
586static void android_hardware_Camera_takePicture(JNIEnv *env, jobject thiz, int msgType)
587{
588    LOGV("takePicture");
589    JNICameraContext* context;
590    sp<Camera> camera = get_native_camera(env, thiz, &context);
591    if (camera == 0) return;
592
593    /*
594     * When CAMERA_MSG_RAW_IMAGE is requested, if the raw image callback
595     * buffer is available, CAMERA_MSG_RAW_IMAGE is enabled to get the
596     * notification _and_ the data; otherwise, CAMERA_MSG_RAW_IMAGE_NOTIFY
597     * is enabled to receive the callback notification but no data.
598     *
599     * Note that CAMERA_MSG_RAW_IMAGE_NOTIFY is not exposed to the
600     * Java application.
601     */
602    if (msgType & CAMERA_MSG_RAW_IMAGE) {
603        LOGV("Enable raw image callback buffer");
604        if (!context->isRawImageCallbackBufferAvailable()) {
605            LOGV("Enable raw image notification, since no callback buffer exists");
606            msgType &= ~CAMERA_MSG_RAW_IMAGE;
607            msgType |= CAMERA_MSG_RAW_IMAGE_NOTIFY;
608        }
609    }
610
611    if (camera->takePicture(msgType) != NO_ERROR) {
612        jniThrowRuntimeException(env, "takePicture failed");
613        return;
614    }
615}
616
617static void android_hardware_Camera_setParameters(JNIEnv *env, jobject thiz, jstring params)
618{
619    LOGV("setParameters");
620    sp<Camera> camera = get_native_camera(env, thiz, NULL);
621    if (camera == 0) return;
622
623    const jchar* str = env->GetStringCritical(params, 0);
624    String8 params8;
625    if (params) {
626        params8 = String8(str, env->GetStringLength(params));
627        env->ReleaseStringCritical(params, str);
628    }
629    if (camera->setParameters(params8) != NO_ERROR) {
630        jniThrowRuntimeException(env, "setParameters failed");
631        return;
632    }
633}
634
635static jstring android_hardware_Camera_getParameters(JNIEnv *env, jobject thiz)
636{
637    LOGV("getParameters");
638    sp<Camera> camera = get_native_camera(env, thiz, NULL);
639    if (camera == 0) return 0;
640
641    return env->NewStringUTF(camera->getParameters().string());
642}
643
644static void android_hardware_Camera_reconnect(JNIEnv *env, jobject thiz)
645{
646    LOGV("reconnect");
647    sp<Camera> camera = get_native_camera(env, thiz, NULL);
648    if (camera == 0) return;
649
650    if (camera->reconnect() != NO_ERROR) {
651        jniThrowException(env, "java/io/IOException", "reconnect failed");
652        return;
653    }
654}
655
656static void android_hardware_Camera_lock(JNIEnv *env, jobject thiz)
657{
658    LOGV("lock");
659    sp<Camera> camera = get_native_camera(env, thiz, NULL);
660    if (camera == 0) return;
661
662    if (camera->lock() != NO_ERROR) {
663        jniThrowRuntimeException(env, "lock failed");
664    }
665}
666
667static void android_hardware_Camera_unlock(JNIEnv *env, jobject thiz)
668{
669    LOGV("unlock");
670    sp<Camera> camera = get_native_camera(env, thiz, NULL);
671    if (camera == 0) return;
672
673    if (camera->unlock() != NO_ERROR) {
674        jniThrowRuntimeException(env, "unlock failed");
675    }
676}
677
678static void android_hardware_Camera_startSmoothZoom(JNIEnv *env, jobject thiz, jint value)
679{
680    LOGV("startSmoothZoom");
681    sp<Camera> camera = get_native_camera(env, thiz, NULL);
682    if (camera == 0) return;
683
684    status_t rc = camera->sendCommand(CAMERA_CMD_START_SMOOTH_ZOOM, value, 0);
685    if (rc == BAD_VALUE) {
686        char msg[64];
687        sprintf(msg, "invalid zoom value=%d", value);
688        jniThrowException(env, "java/lang/IllegalArgumentException", msg);
689    } else if (rc != NO_ERROR) {
690        jniThrowRuntimeException(env, "start smooth zoom failed");
691    }
692}
693
694static void android_hardware_Camera_stopSmoothZoom(JNIEnv *env, jobject thiz)
695{
696    LOGV("stopSmoothZoom");
697    sp<Camera> camera = get_native_camera(env, thiz, NULL);
698    if (camera == 0) return;
699
700    if (camera->sendCommand(CAMERA_CMD_STOP_SMOOTH_ZOOM, 0, 0) != NO_ERROR) {
701        jniThrowRuntimeException(env, "stop smooth zoom failed");
702    }
703}
704
705static void android_hardware_Camera_setDisplayOrientation(JNIEnv *env, jobject thiz,
706        jint value)
707{
708    LOGV("setDisplayOrientation");
709    sp<Camera> camera = get_native_camera(env, thiz, NULL);
710    if (camera == 0) return;
711
712    if (camera->sendCommand(CAMERA_CMD_SET_DISPLAY_ORIENTATION, value, 0) != NO_ERROR) {
713        jniThrowRuntimeException(env, "set display orientation failed");
714    }
715}
716
717static void android_hardware_Camera_startFaceDetection(JNIEnv *env, jobject thiz,
718        jint type, jobjectArray face)
719{
720    LOGV("startFaceDetection");
721    JNICameraContext* context;
722    sp<Camera> camera = get_native_camera(env, thiz, &context);
723    if (camera == 0) return;
724
725    status_t rc = camera->sendCommand(CAMERA_CMD_START_FACE_DETECTION, type, 0);
726    if (rc == BAD_VALUE) {
727        char msg[64];
728        snprintf(msg, sizeof(msg), "invalid face detection type=%d", type);
729        jniThrowException(env, "java/lang/IllegalArgumentException", msg);
730    } else if (rc != NO_ERROR) {
731        jniThrowRuntimeException(env, "start face detection failed");
732    }
733}
734
735static void android_hardware_Camera_stopFaceDetection(JNIEnv *env, jobject thiz)
736{
737    LOGV("stopFaceDetection");
738    sp<Camera> camera = get_native_camera(env, thiz, NULL);
739    if (camera == 0) return;
740
741    if (camera->sendCommand(CAMERA_CMD_STOP_FACE_DETECTION, 0, 0) != NO_ERROR) {
742        jniThrowRuntimeException(env, "stop face detection failed");
743    }
744}
745
746//-------------------------------------------------
747
748static JNINativeMethod camMethods[] = {
749  { "getNumberOfCameras",
750    "()I",
751    (void *)android_hardware_Camera_getNumberOfCameras },
752  { "getCameraInfo",
753    "(ILandroid/hardware/Camera$CameraInfo;)V",
754    (void*)android_hardware_Camera_getCameraInfo },
755  { "native_setup",
756    "(Ljava/lang/Object;I)V",
757    (void*)android_hardware_Camera_native_setup },
758  { "native_release",
759    "()V",
760    (void*)android_hardware_Camera_release },
761  { "setPreviewDisplay",
762    "(Landroid/view/Surface;)V",
763    (void *)android_hardware_Camera_setPreviewDisplay },
764  { "setPreviewTexture",
765    "(Landroid/graphics/SurfaceTexture;)V",
766    (void *)android_hardware_Camera_setPreviewTexture },
767  { "startPreview",
768    "()V",
769    (void *)android_hardware_Camera_startPreview },
770  { "_stopPreview",
771    "()V",
772    (void *)android_hardware_Camera_stopPreview },
773  { "previewEnabled",
774    "()Z",
775    (void *)android_hardware_Camera_previewEnabled },
776  { "setHasPreviewCallback",
777    "(ZZ)V",
778    (void *)android_hardware_Camera_setHasPreviewCallback },
779  { "_addCallbackBuffer",
780    "([BI)V",
781    (void *)android_hardware_Camera_addCallbackBuffer },
782  { "native_autoFocus",
783    "()V",
784    (void *)android_hardware_Camera_autoFocus },
785  { "native_cancelAutoFocus",
786    "()V",
787    (void *)android_hardware_Camera_cancelAutoFocus },
788  { "native_takePicture",
789    "(I)V",
790    (void *)android_hardware_Camera_takePicture },
791  { "native_setParameters",
792    "(Ljava/lang/String;)V",
793    (void *)android_hardware_Camera_setParameters },
794  { "native_getParameters",
795    "()Ljava/lang/String;",
796    (void *)android_hardware_Camera_getParameters },
797  { "reconnect",
798    "()V",
799    (void*)android_hardware_Camera_reconnect },
800  { "lock",
801    "()V",
802    (void*)android_hardware_Camera_lock },
803  { "unlock",
804    "()V",
805    (void*)android_hardware_Camera_unlock },
806  { "startSmoothZoom",
807    "(I)V",
808    (void *)android_hardware_Camera_startSmoothZoom },
809  { "stopSmoothZoom",
810    "()V",
811    (void *)android_hardware_Camera_stopSmoothZoom },
812  { "setDisplayOrientation",
813    "(I)V",
814    (void *)android_hardware_Camera_setDisplayOrientation },
815  { "_startFaceDetection",
816    "(I)V",
817    (void *)android_hardware_Camera_startFaceDetection },
818  { "_stopFaceDetection",
819    "()V",
820    (void *)android_hardware_Camera_stopFaceDetection},
821};
822
823struct field {
824    const char *class_name;
825    const char *field_name;
826    const char *field_type;
827    jfieldID   *jfield;
828};
829
830static int find_fields(JNIEnv *env, field *fields, int count)
831{
832    for (int i = 0; i < count; i++) {
833        field *f = &fields[i];
834        jclass clazz = env->FindClass(f->class_name);
835        if (clazz == NULL) {
836            LOGE("Can't find %s", f->class_name);
837            return -1;
838        }
839
840        jfieldID field = env->GetFieldID(clazz, f->field_name, f->field_type);
841        if (field == NULL) {
842            LOGE("Can't find %s.%s", f->class_name, f->field_name);
843            return -1;
844        }
845
846        *(f->jfield) = field;
847    }
848
849    return 0;
850}
851
852// Get all the required offsets in java class and register native functions
853int register_android_hardware_Camera(JNIEnv *env)
854{
855    field fields_to_find[] = {
856        { "android/hardware/Camera", "mNativeContext",   "I", &fields.context },
857        { "android/view/Surface",    ANDROID_VIEW_SURFACE_JNI_ID, "I", &fields.surface },
858        { "android/graphics/SurfaceTexture",
859          ANDROID_GRAPHICS_SURFACETEXTURE_JNI_ID, "I", &fields.surfaceTexture },
860        { "android/hardware/Camera$CameraInfo", "facing",   "I", &fields.facing },
861        { "android/hardware/Camera$CameraInfo", "orientation",   "I", &fields.orientation },
862        { "android/hardware/Camera$Face", "rect", "Landroid/graphics/Rect;", &fields.face_rect },
863        { "android/hardware/Camera$Face", "score", "I", &fields.face_score },
864        { "android/graphics/Rect", "left", "I", &fields.rect_left },
865        { "android/graphics/Rect", "top", "I", &fields.rect_top },
866        { "android/graphics/Rect", "right", "I", &fields.rect_right },
867        { "android/graphics/Rect", "bottom", "I", &fields.rect_bottom },
868    };
869
870    if (find_fields(env, fields_to_find, NELEM(fields_to_find)) < 0)
871        return -1;
872
873    jclass clazz = env->FindClass("android/hardware/Camera");
874    fields.post_event = env->GetStaticMethodID(clazz, "postEventFromNative",
875                                               "(Ljava/lang/Object;IIILjava/lang/Object;)V");
876    if (fields.post_event == NULL) {
877        LOGE("Can't find android/hardware/Camera.postEventFromNative");
878        return -1;
879    }
880
881
882    // Register native functions
883    return AndroidRuntime::registerNativeMethods(env, "android/hardware/Camera",
884                                              camMethods, NELEM(camMethods));
885}
886