android_hardware_Camera.cpp revision f013e1afd1e68af5e3b868c26a653bbfb39538f8
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 void android_hardware_Camera_setHasPreviewCallback(JNIEnv *env, jobject thiz, jboolean installed)
229{
230    sp<Camera> c = get_native_camera(env, thiz);
231    if (c == 0)
232        return;
233
234    // Important: Only install preview_callback if the Java code has called
235    // setPreviewCallback() with a non-null value, otherwise we'd pay to memcpy
236    // each preview frame for nothing.
237    callback_cookie *cookie = (callback_cookie *)env->GetIntField(thiz, fields.listener_context);
238
239    c->setFrameCallback(installed ? preview_callback : NULL,
240            cookie,
241            installed ? FRAME_CALLBACK_FLAG_CAMERA: FRAME_CALLBACK_FLAG_NOOP);
242}
243
244static void autofocus_callback_impl(bool success, void *cookie)
245{
246    JNIEnv *env = AndroidRuntime::getJNIEnv();
247    callback_cookie *c = (callback_cookie *)cookie;
248    env->CallStaticVoidMethod(c->camera_class, fields.post_event,
249                              c->camera_ref, kAutoFocusCallback,
250                              success, 0, NULL);
251}
252
253
254
255static void android_hardware_Camera_autoFocus(JNIEnv *env, jobject thiz)
256{
257    sp<Camera> c = get_native_camera(env, thiz);
258    if (c == 0)
259        return;
260    callback_cookie *cookie = (callback_cookie *)env->GetIntField(thiz, fields.listener_context);
261    c->setAutoFocusCallback(autofocus_callback_impl, cookie);
262    if (c->autoFocus() != NO_ERROR) {
263        jniThrowException(env, "java/io/IOException", "autoFocus failed");
264    }
265}
266
267static void jpeg_callback(const sp<IMemory>& mem, void *cookie)
268{
269    JNIEnv *env = AndroidRuntime::getJNIEnv();
270    callback_cookie *c = (callback_cookie *)cookie;
271    int arg1 = 0, arg2 = 0;
272    jobject obj = NULL;
273
274    if (mem == NULL) {
275        env->CallStaticVoidMethod(c->camera_class, fields.post_event,
276                                  c->camera_ref, kJpegCallback, arg1, arg2, NULL);
277        return;
278    }
279    ssize_t offset;
280    size_t size;
281    sp<IMemoryHeap> heap = mem->getMemory(&offset, &size);
282    LOGV("jpeg_callback: mem off=%d, size=%d", offset, size);
283
284    uint8_t *heap_base = (uint8_t *)heap->base();
285    if (heap_base == NULL) {
286        LOGE("YUV heap is NULL");
287        return;
288    }
289
290    uint8_t *data = heap_base + offset;
291
292    jbyteArray array = env->NewByteArray(size);
293    if (array == NULL) {
294        LOGE("Couldn't allocate byte array for JPEG data");
295        env->ExceptionClear();
296        return;
297    }
298
299    jbyte *bytes = env->GetByteArrayElements(array, NULL);
300    memcpy(bytes, data, size);
301    env->ReleaseByteArrayElements(array, bytes, 0);
302
303    obj = array;
304
305    env->CallStaticVoidMethod(c->camera_class, fields.post_event,
306                              c->camera_ref, kJpegCallback, arg1, arg2, obj);
307    env->DeleteLocalRef(array);
308}
309
310static void shutter_callback_impl(void *cookie)
311{
312    JNIEnv *env = AndroidRuntime::getJNIEnv();
313    callback_cookie *c = (callback_cookie *)cookie;
314    env->CallStaticVoidMethod(c->camera_class, fields.post_event,
315                              c->camera_ref, kShutterCallback, 0, 0, NULL);
316}
317
318static void raw_callback(const sp<IMemory>& mem __attribute__((unused)),
319                         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, kRawCallback, 0, 0, NULL);
325}
326
327static void android_hardware_Camera_takePicture(JNIEnv *env, jobject thiz)
328{
329    sp<Camera> c = get_native_camera(env, thiz);
330    if (c == 0)
331        return;
332
333    callback_cookie *cookie =
334        (callback_cookie *)env->GetIntField(thiz, fields.listener_context);
335    c->setShutterCallback(shutter_callback_impl, cookie);
336    c->setRawCallback(raw_callback, cookie);
337    c->setJpegCallback(jpeg_callback, cookie);
338    if (c->takePicture() != NO_ERROR) {
339        jniThrowException(env, "java/io/IOException", "takePicture failed");
340        return;
341    }
342
343    return;
344}
345
346static void android_hardware_Camera_setParameters(JNIEnv *env, jobject thiz, jstring params)
347{
348    sp<Camera> c = get_native_camera(env, thiz);
349    if (c == 0)
350        return;
351
352    const jchar* str = env->GetStringCritical(params, 0);
353    String8 params8;
354    if (params) {
355        params8 = String8(str, env->GetStringLength(params));
356        env->ReleaseStringCritical(params, str);
357    }
358    if (c->setParameters(params8) != NO_ERROR) {
359        jniThrowException(env, "java/lang/IllegalArgumentException", "setParameters failed");
360        return;
361    }
362}
363
364static jstring android_hardware_Camera_getParameters(JNIEnv *env, jobject thiz)
365{
366    sp<Camera> c = get_native_camera(env, thiz);
367    if (c == 0)
368        return 0;
369
370    return env->NewStringUTF(c->getParameters().string());
371}
372
373static void android_hardware_Camera_reconnect(JNIEnv *env, jobject thiz)
374{
375    sp<Camera> c = get_native_camera(env, thiz);
376    if (c == 0)
377        return;
378
379    if (c->reconnect() != NO_ERROR) {
380        jniThrowException(env, "java/io/IOException", "reconnect failed");
381        return;
382    }
383}
384
385//-------------------------------------------------
386
387static JNINativeMethod camMethods[] = {
388  { "native_setup",
389    "(Ljava/lang/Object;)V",
390    (void*)android_hardware_Camera_native_setup },
391  { "native_release",
392    "()V",
393    (void*)android_hardware_Camera_release },
394  { "setPreviewDisplay",
395    "(Landroid/view/Surface;)V",
396    (void *)android_hardware_Camera_setPreviewDisplay },
397  { "startPreview",
398    "()V",
399    (void *)android_hardware_Camera_startPreview },
400  { "stopPreview",
401    "()V",
402    (void *)android_hardware_Camera_stopPreview },
403  { "setHasPreviewCallback",
404    "(Z)V",
405    (void *)android_hardware_Camera_setHasPreviewCallback },
406  { "native_autoFocus",
407    "()V",
408    (void *)android_hardware_Camera_autoFocus },
409  { "native_takePicture",
410    "()V",
411    (void *)android_hardware_Camera_takePicture },
412  { "native_setParameters",
413    "(Ljava/lang/String;)V",
414    (void *)android_hardware_Camera_setParameters },
415  { "native_getParameters",
416    "()Ljava/lang/String;",
417    (void *)android_hardware_Camera_getParameters },
418  { "reconnect",
419    "()V",
420    (void*)android_hardware_Camera_reconnect },
421};
422
423struct field {
424    const char *class_name;
425    const char *field_name;
426    const char *field_type;
427    jfieldID   *jfield;
428};
429
430static int find_fields(JNIEnv *env, field *fields, int count)
431{
432    for (int i = 0; i < count; i++) {
433        field *f = &fields[i];
434        jclass clazz = env->FindClass(f->class_name);
435        if (clazz == NULL) {
436            LOGE("Can't find %s", f->class_name);
437            return -1;
438        }
439
440        jfieldID field = env->GetFieldID(clazz, f->field_name, f->field_type);
441        if (field == NULL) {
442            LOGE("Can't find %s.%s", f->class_name, f->field_name);
443            return -1;
444        }
445
446        *(f->jfield) = field;
447    }
448
449    return 0;
450}
451
452// Get all the required offsets in java class and register native functions
453int register_android_hardware_Camera(JNIEnv *env)
454{
455    field fields_to_find[] = {
456        { "android/hardware/Camera", "mNativeContext",   "I", &fields.context },
457        { "android/hardware/Camera", "mListenerContext", "I", &fields.listener_context },
458        { "android/view/Surface",    "mSurface",         "I", &fields.surface }
459    };
460
461    if (find_fields(env, fields_to_find, NELEM(fields_to_find)) < 0)
462        return -1;
463
464    jclass clazz = env->FindClass("android/hardware/Camera");
465    fields.post_event = env->GetStaticMethodID(clazz, "postEventFromNative",
466                                               "(Ljava/lang/Object;IIILjava/lang/Object;)V");
467    if (fields.post_event == NULL) {
468        LOGE("Can't find android/hardware/Camera.postEventFromNative");
469        return -1;
470    }
471
472
473    // Register native functions
474    return AndroidRuntime::registerNativeMethods(env, "android/hardware/Camera",
475                                              camMethods, NELEM(camMethods));
476}
477
478