android_hardware_Camera.cpp revision b798689749c64baba81f02e10cf2157c747d6b46
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_TAG "Camera-JNI"
19
20#include "jni.h"
21#include "JNIHelp.h"
22#include "android_runtime/AndroidRuntime.h"
23
24#include <ui/Surface.h>
25#include <ui/Camera.h>
26#include <utils/IMemory.h>
27
28using namespace android;
29
30enum CallbackMessageID {
31    kShutterCallback = 0,
32    kRawCallback = 1,
33    kJpegCallback = 2,
34    kPreviewCallback = 3,
35    kAutoFocusCallback = 4,
36    kErrorCallback = 5
37};
38
39enum CameraError {
40    kCameraErrorUnknown = 1,
41    kCameraErrorMediaServer = 100
42};
43
44
45struct fields_t {
46    jfieldID    context;
47    jfieldID    surface;
48    jfieldID    listener_context;
49    jmethodID   post_event;
50};
51
52static fields_t fields;
53static Mutex sLock;
54
55struct callback_cookie {
56    jclass      camera_class;
57    jobject     camera_ref;
58};
59
60sp<Camera> get_native_camera(JNIEnv *env, jobject thiz)
61{
62    Mutex::Autolock _l(sLock);
63    sp<Camera> c = reinterpret_cast<Camera*>(env->GetIntField(thiz, fields.context));
64    if (c == 0)
65        jniThrowException(env, "java/lang/RuntimeException", "Method called after release()");
66
67    return c;
68}
69
70static void err_callback(status_t err, void *cookie)
71{
72    JNIEnv *env = AndroidRuntime::getJNIEnv();
73    callback_cookie *c = (callback_cookie *)cookie;
74    int error;
75
76    switch (err) {
77    case DEAD_OBJECT:
78        error = kCameraErrorMediaServer;
79        break;
80    default:
81        error = kCameraErrorUnknown;
82        break;
83    }
84    LOGV("err_callback: camera_ref=%x, cookie=%x", (int)c->camera_ref, (int)cookie);
85
86    env->CallStaticVoidMethod(c->camera_class, fields.post_event,
87                              c->camera_ref, kErrorCallback, error, 0, NULL);
88}
89
90// connect to camera service
91static void android_hardware_Camera_native_setup(JNIEnv *env, jobject thiz, jobject weak_this)
92{
93    sp<Camera> c = Camera::connect();
94
95    if (c == NULL) {
96        jniThrowException(env, "java/lang/RuntimeException", "Out of memory");
97        return;
98    }
99
100    // make sure camera hardware is alive
101    if (c->getStatus() != NO_ERROR) {
102        jniThrowException(env, "java/io/IOException", "Camera initialization failed");
103        return;
104    }
105
106    callback_cookie *cookie = new callback_cookie;
107    jclass clazz = env->GetObjectClass(thiz);
108    if (clazz == NULL) {
109        LOGE("Can't find android/hardware/Camera");
110        // XXX no idea what to throw here, can this even happen?
111        jniThrowException(env, "java/lang/Exception", NULL);
112        return;
113    }
114    cookie->camera_class = (jclass)env->NewGlobalRef(clazz);
115
116    // We use a weak reference so the Camera object can be garbage collected.
117    // The reference is only used as a proxy for callbacks.
118    cookie->camera_ref = env->NewGlobalRef(weak_this);
119    env->SetIntField(thiz, fields.listener_context, (int)cookie);
120
121    LOGV("native_setup: camera_ref=%x, camera_obj=%x, cookie=%x", (int)cookie->camera_ref, (int)thiz, (int)cookie);
122
123    // save camera object in opaque field
124    env->SetIntField(thiz, fields.context, reinterpret_cast<int>(c.get()));
125
126    c->setErrorCallback(err_callback, cookie);
127
128    // hold a strong reference so the camera doesn't go away while the app is still running
129    c->incStrong(thiz);
130}
131
132// disconnect from camera service
133static void android_hardware_Camera_release(JNIEnv *env, jobject thiz)
134{
135    Mutex::Autolock _l(sLock);
136    sp<Camera> c = reinterpret_cast<Camera*>(env->GetIntField(thiz, fields.context));
137    // It's okay to call this when the native camera context is already null.
138    // This handles the case where the user has called release() and the
139    // finalizer is invoked later.
140    if (c != 0) {
141        // Make sure that we do not attempt to deliver an eror callback on a deleted
142        // Java object.
143        c->setErrorCallback(NULL, NULL);
144        c->disconnect();
145
146        // remove our strong reference created in native setup
147        c->decStrong(thiz);
148        env->SetIntField(thiz, fields.context, 0);
149
150        callback_cookie *cookie = (callback_cookie *)env->GetIntField(thiz, fields.listener_context);
151
152        LOGV("release: camera_ref=%x, camera_obj=%x, cookie=%x", (int)cookie->camera_ref, (int)thiz, (int)cookie);
153
154        if (cookie) {
155            env->DeleteGlobalRef(cookie->camera_ref);
156            env->DeleteGlobalRef(cookie->camera_class);
157            delete cookie;
158            env->SetIntField(thiz, fields.listener_context, 0);
159        }
160    }
161}
162
163static void android_hardware_Camera_setPreviewDisplay(JNIEnv *env, jobject thiz, jobject surface)
164{
165    sp<Camera> c = get_native_camera(env, thiz);
166    if (c == 0)
167        return;
168
169    sp<Surface> s = (Surface *)env->GetIntField(surface, fields.surface);
170    if (c->setPreviewDisplay(s) != NO_ERROR) {
171        jniThrowException(env, "java/io/IOException", "setPreviewDisplay failed");
172        return;
173    }
174}
175
176static void preview_callback(const sp<IMemory>& mem, void *cookie)
177{
178    JNIEnv *env = AndroidRuntime::getJNIEnv();
179    callback_cookie *c = (callback_cookie *)cookie;
180    int arg1 = 0, arg2 = 0;
181    jobject obj = NULL;
182
183    ssize_t offset;
184    size_t size;
185    sp<IMemoryHeap> heap = mem->getMemory(&offset, &size);
186
187    uint8_t *data = ((uint8_t *)heap->base()) + offset;
188
189    jbyteArray array = env->NewByteArray(size);
190    if (array == NULL) {
191        LOGE("Couldn't allocate byte array for YUV data");
192        env->ExceptionClear();
193        return;
194    }
195
196    jbyte *bytes = env->GetByteArrayElements(array, NULL);
197    memcpy(bytes, data, size);
198    env->ReleaseByteArrayElements(array, bytes, 0);
199
200    obj = array;
201
202    env->CallStaticVoidMethod(c->camera_class, fields.post_event,
203                              c->camera_ref, kPreviewCallback, arg1, arg2, obj);
204    env->DeleteLocalRef(array);
205}
206
207static void android_hardware_Camera_startPreview(JNIEnv *env, jobject thiz)
208{
209    sp<Camera> c = get_native_camera(env, thiz);
210    if (c == 0)
211        return;
212
213    if (c->startPreview() != NO_ERROR) {
214        jniThrowException(env, "java/io/IOException", "startPreview failed");
215        return;
216    }
217}
218
219static void android_hardware_Camera_stopPreview(JNIEnv *env, jobject thiz)
220{
221    sp<Camera> c = get_native_camera(env, thiz);
222    if (c == 0)
223        return;
224
225    c->stopPreview();
226}
227
228static bool android_hardware_Camera_previewEnabled(JNIEnv *env, jobject thiz)
229{
230    sp<Camera> c = get_native_camera(env, thiz);
231    if (c == 0)
232        return false;
233
234    return c->previewEnabled();
235}
236
237static void android_hardware_Camera_setHasPreviewCallback(JNIEnv *env, jobject thiz, jboolean installed)
238{
239    sp<Camera> c = get_native_camera(env, thiz);
240    if (c == 0)
241        return;
242
243    // Important: Only install preview_callback if the Java code has called
244    // setPreviewCallback() with a non-null value, otherwise we'd pay to memcpy
245    // each preview frame for nothing.
246    callback_cookie *cookie = (callback_cookie *)env->GetIntField(thiz, fields.listener_context);
247
248    c->setFrameCallback(installed ? preview_callback : NULL,
249            cookie,
250            installed ? FRAME_CALLBACK_FLAG_CAMERA: FRAME_CALLBACK_FLAG_NOOP);
251}
252
253static void autofocus_callback_impl(bool success, void *cookie)
254{
255    JNIEnv *env = AndroidRuntime::getJNIEnv();
256    callback_cookie *c = (callback_cookie *)cookie;
257    env->CallStaticVoidMethod(c->camera_class, fields.post_event,
258                              c->camera_ref, kAutoFocusCallback,
259                              success, 0, NULL);
260}
261
262
263
264static void android_hardware_Camera_autoFocus(JNIEnv *env, jobject thiz)
265{
266    sp<Camera> c = get_native_camera(env, thiz);
267    if (c == 0)
268        return;
269    callback_cookie *cookie = (callback_cookie *)env->GetIntField(thiz, fields.listener_context);
270    c->setAutoFocusCallback(autofocus_callback_impl, cookie);
271    if (c->autoFocus() != NO_ERROR) {
272        jniThrowException(env, "java/io/IOException", "autoFocus failed");
273    }
274}
275
276static void jpeg_callback(const sp<IMemory>& mem, void *cookie)
277{
278    JNIEnv *env = AndroidRuntime::getJNIEnv();
279    callback_cookie *c = (callback_cookie *)cookie;
280    int arg1 = 0, arg2 = 0;
281    jobject obj = NULL;
282
283    if (mem == NULL) {
284        env->CallStaticVoidMethod(c->camera_class, fields.post_event,
285                                  c->camera_ref, kJpegCallback, arg1, arg2, NULL);
286        return;
287    }
288    ssize_t offset;
289    size_t size;
290    sp<IMemoryHeap> heap = mem->getMemory(&offset, &size);
291    LOGV("jpeg_callback: mem off=%d, size=%d", offset, size);
292
293    uint8_t *heap_base = (uint8_t *)heap->base();
294    if (heap_base == NULL) {
295        LOGE("YUV heap is NULL");
296        return;
297    }
298
299    uint8_t *data = heap_base + offset;
300
301    jbyteArray array = env->NewByteArray(size);
302    if (array == NULL) {
303        LOGE("Couldn't allocate byte array for JPEG data");
304        env->ExceptionClear();
305        return;
306    }
307
308    jbyte *bytes = env->GetByteArrayElements(array, NULL);
309    memcpy(bytes, data, size);
310    env->ReleaseByteArrayElements(array, bytes, 0);
311
312    obj = array;
313
314    env->CallStaticVoidMethod(c->camera_class, fields.post_event,
315                              c->camera_ref, kJpegCallback, arg1, arg2, obj);
316    env->DeleteLocalRef(array);
317}
318
319static void shutter_callback_impl(void *cookie)
320{
321    JNIEnv *env = AndroidRuntime::getJNIEnv();
322    callback_cookie *c = (callback_cookie *)cookie;
323    env->CallStaticVoidMethod(c->camera_class, fields.post_event,
324                              c->camera_ref, kShutterCallback, 0, 0, NULL);
325}
326
327static void raw_callback(const sp<IMemory>& mem __attribute__((unused)),
328                         void *cookie)
329{
330    JNIEnv *env = AndroidRuntime::getJNIEnv();
331    callback_cookie *c = (callback_cookie *)cookie;
332    env->CallStaticVoidMethod(c->camera_class, fields.post_event,
333                              c->camera_ref, kRawCallback, 0, 0, NULL);
334}
335
336static void android_hardware_Camera_takePicture(JNIEnv *env, jobject thiz)
337{
338    sp<Camera> c = get_native_camera(env, thiz);
339    if (c == 0)
340        return;
341
342    callback_cookie *cookie =
343        (callback_cookie *)env->GetIntField(thiz, fields.listener_context);
344    c->setShutterCallback(shutter_callback_impl, cookie);
345    c->setRawCallback(raw_callback, cookie);
346    c->setJpegCallback(jpeg_callback, cookie);
347    if (c->takePicture() != NO_ERROR) {
348        jniThrowException(env, "java/io/IOException", "takePicture failed");
349        return;
350    }
351
352    return;
353}
354
355static void android_hardware_Camera_setParameters(JNIEnv *env, jobject thiz, jstring params)
356{
357    sp<Camera> c = get_native_camera(env, thiz);
358    if (c == 0)
359        return;
360
361    const jchar* str = env->GetStringCritical(params, 0);
362    String8 params8;
363    if (params) {
364        params8 = String8(str, env->GetStringLength(params));
365        env->ReleaseStringCritical(params, str);
366    }
367    if (c->setParameters(params8) != NO_ERROR) {
368        jniThrowException(env, "java/lang/IllegalArgumentException", "setParameters failed");
369        return;
370    }
371}
372
373static jstring android_hardware_Camera_getParameters(JNIEnv *env, jobject thiz)
374{
375    sp<Camera> c = get_native_camera(env, thiz);
376    if (c == 0)
377        return 0;
378
379    return env->NewStringUTF(c->getParameters().string());
380}
381
382static void android_hardware_Camera_reconnect(JNIEnv *env, jobject thiz)
383{
384    sp<Camera> c = get_native_camera(env, thiz);
385    if (c == 0)
386        return;
387
388    if (c->reconnect() != NO_ERROR) {
389        jniThrowException(env, "java/io/IOException", "reconnect failed");
390        return;
391    }
392}
393
394static jint android_hardware_Camera_lock(JNIEnv *env, jobject thiz)
395{
396    sp<Camera> c = get_native_camera(env, thiz);
397    if (c == 0)
398        return INVALID_OPERATION;
399    return (jint) c->lock();
400}
401
402static jint android_hardware_Camera_unlock(JNIEnv *env, jobject thiz)
403{
404    sp<Camera> c = get_native_camera(env, thiz);
405    if (c == 0)
406        return INVALID_OPERATION;
407    return (jint) c->lock();
408}
409
410//-------------------------------------------------
411
412static JNINativeMethod camMethods[] = {
413  { "native_setup",
414    "(Ljava/lang/Object;)V",
415    (void*)android_hardware_Camera_native_setup },
416  { "native_release",
417    "()V",
418    (void*)android_hardware_Camera_release },
419  { "setPreviewDisplay",
420    "(Landroid/view/Surface;)V",
421    (void *)android_hardware_Camera_setPreviewDisplay },
422  { "startPreview",
423    "()V",
424    (void *)android_hardware_Camera_startPreview },
425  { "stopPreview",
426    "()V",
427    (void *)android_hardware_Camera_stopPreview },
428  { "previewEnabled",
429    "()Z",
430    (void *)android_hardware_Camera_previewEnabled },
431  { "setHasPreviewCallback",
432    "(Z)V",
433    (void *)android_hardware_Camera_setHasPreviewCallback },
434  { "native_autoFocus",
435    "()V",
436    (void *)android_hardware_Camera_autoFocus },
437  { "native_takePicture",
438    "()V",
439    (void *)android_hardware_Camera_takePicture },
440  { "native_setParameters",
441    "(Ljava/lang/String;)V",
442    (void *)android_hardware_Camera_setParameters },
443  { "native_getParameters",
444    "()Ljava/lang/String;",
445    (void *)android_hardware_Camera_getParameters },
446  { "reconnect",
447    "()V",
448    (void*)android_hardware_Camera_reconnect },
449  { "lock",
450    "()I",
451    (void*)android_hardware_Camera_lock },
452  { "unlock",
453    "()I",
454    (void*)android_hardware_Camera_unlock },
455};
456
457struct field {
458    const char *class_name;
459    const char *field_name;
460    const char *field_type;
461    jfieldID   *jfield;
462};
463
464static int find_fields(JNIEnv *env, field *fields, int count)
465{
466    for (int i = 0; i < count; i++) {
467        field *f = &fields[i];
468        jclass clazz = env->FindClass(f->class_name);
469        if (clazz == NULL) {
470            LOGE("Can't find %s", f->class_name);
471            return -1;
472        }
473
474        jfieldID field = env->GetFieldID(clazz, f->field_name, f->field_type);
475        if (field == NULL) {
476            LOGE("Can't find %s.%s", f->class_name, f->field_name);
477            return -1;
478        }
479
480        *(f->jfield) = field;
481    }
482
483    return 0;
484}
485
486// Get all the required offsets in java class and register native functions
487int register_android_hardware_Camera(JNIEnv *env)
488{
489    field fields_to_find[] = {
490        { "android/hardware/Camera", "mNativeContext",   "I", &fields.context },
491        { "android/hardware/Camera", "mListenerContext", "I", &fields.listener_context },
492        { "android/view/Surface",    "mSurface",         "I", &fields.surface }
493    };
494
495    if (find_fields(env, fields_to_find, NELEM(fields_to_find)) < 0)
496        return -1;
497
498    jclass clazz = env->FindClass("android/hardware/Camera");
499    fields.post_event = env->GetStaticMethodID(clazz, "postEventFromNative",
500                                               "(Ljava/lang/Object;IIILjava/lang/Object;)V");
501    if (fields.post_event == NULL) {
502        LOGE("Can't find android/hardware/Camera.postEventFromNative");
503        return -1;
504    }
505
506
507    // Register native functions
508    return AndroidRuntime::registerNativeMethods(env, "android/hardware/Camera",
509                                              camMethods, NELEM(camMethods));
510}
511
512