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