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