PhotoModule.java revision ba6994d8834db0cb2df60893ccb9af091b23bfce
1/* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.camera; 18 19import android.annotation.TargetApi; 20import android.app.Activity; 21import android.content.ContentResolver; 22import android.content.Context; 23import android.content.Intent; 24import android.graphics.Bitmap; 25import android.graphics.Rect; 26import android.graphics.SurfaceTexture; 27import android.hardware.Camera.CameraInfo; 28import android.hardware.Camera.Parameters; 29import android.hardware.Camera.Size; 30import android.hardware.Sensor; 31import android.hardware.SensorEvent; 32import android.hardware.SensorEventListener; 33import android.hardware.SensorManager; 34import android.location.Location; 35import android.media.CameraProfile; 36import android.net.Uri; 37import android.os.Build; 38import android.os.Bundle; 39import android.os.Handler; 40import android.os.Looper; 41import android.os.Message; 42import android.os.MessageQueue; 43import android.os.SystemClock; 44import android.provider.MediaStore; 45import android.util.Log; 46import android.view.KeyEvent; 47import android.view.OrientationEventListener; 48import android.view.View; 49import android.view.ViewGroup; 50 51import com.android.camera.PhotoModule.NamedImages.NamedEntity; 52import com.android.camera.app.AppController; 53import com.android.camera.app.CameraManager.CameraAFCallback; 54import com.android.camera.app.CameraManager.CameraAFMoveCallback; 55import com.android.camera.app.CameraManager.CameraPictureCallback; 56import com.android.camera.app.CameraManager.CameraProxy; 57import com.android.camera.app.CameraManager.CameraShutterCallback; 58import com.android.camera.app.MediaSaver; 59import com.android.camera.app.MemoryManager; 60import com.android.camera.app.MemoryManager.MemoryListener; 61import com.android.camera.exif.ExifInterface; 62import com.android.camera.exif.ExifTag; 63import com.android.camera.exif.Rational; 64import com.android.camera.module.ModuleController; 65import com.android.camera.settings.SettingsManager; 66import com.android.camera.ui.ModeListView; 67import com.android.camera.ui.RotateTextToast; 68import com.android.camera.util.ApiHelper; 69import com.android.camera.util.CameraUtil; 70import com.android.camera.util.GcamHelper; 71import com.android.camera.util.SmartCameraHelper; 72import com.android.camera.util.UsageStatistics; 73import com.android.camera2.R; 74 75import java.io.File; 76import java.io.FileNotFoundException; 77import java.io.FileOutputStream; 78import java.io.IOException; 79import java.io.OutputStream; 80import java.util.List; 81import java.util.Vector; 82 83public class PhotoModule 84 extends CameraModule 85 implements PhotoController, 86 ModuleController, 87 MemoryListener, 88 FocusOverlayManager.Listener, 89 ShutterButton.OnShutterButtonListener, 90 SensorEventListener { 91 92 private static final String TAG = "CAM_PhotoModule"; 93 94 // We number the request code from 1000 to avoid collision with Gallery. 95 private static final int REQUEST_CROP = 1000; 96 97 // Messages defined for the UI thread handler. 98 private static final int MSG_SETUP_PREVIEW = 1; 99 private static final int MSG_FIRST_TIME_INIT = 2; 100 private static final int MSG_SET_CAMERA_PARAMETERS_WHEN_IDLE = 3; 101 private static final int MSG_SHOW_TAP_TO_FOCUS_TOAST = 4; 102 private static final int MSG_SWITCH_CAMERA = 5; 103 private static final int MSG_SWITCH_CAMERA_START_ANIMATION = 6; 104 private static final int MSG_CAMERA_OPEN_DONE = 7; 105 private static final int MSG_OPEN_CAMERA_FAIL = 8; 106 private static final int MSG_CAMERA_DISABLED = 9; 107 private static final int MSG_SWITCH_TO_GCAM_MODULE = 10; 108 109 // The subset of parameters we need to update in setCameraParameters(). 110 private static final int UPDATE_PARAM_INITIALIZE = 1; 111 private static final int UPDATE_PARAM_ZOOM = 2; 112 private static final int UPDATE_PARAM_PREFERENCE = 4; 113 private static final int UPDATE_PARAM_ALL = -1; 114 115 // This is the delay before we execute onResume tasks when coming 116 // from the lock screen, to allow time for onPause to execute. 117 private static final int ON_RESUME_TASKS_DELAY_MSEC = 20; 118 119 private static final String DEBUG_IMAGE_PREFIX = "DEBUG_"; 120 121 // copied from Camera hierarchy 122 private CameraActivity mActivity; 123 private CameraProxy mCameraDevice; 124 private int mCameraId; 125 private Parameters mParameters; 126 private boolean mPaused; 127 128 private PhotoUI mUI; 129 130 // The activity is going to switch to the specified camera id. This is 131 // needed because texture copy is done in GL thread. -1 means camera is not 132 // switching. 133 protected int mPendingSwitchCameraId = -1; 134 private boolean mOpenCameraFail; 135 private boolean mCameraDisabled; 136 137 // When setCameraParametersWhenIdle() is called, we accumulate the subsets 138 // needed to be updated in mUpdateSet. 139 private int mUpdateSet; 140 141 private static final int SCREEN_DELAY = 2 * 60 * 1000; 142 143 private int mZoomValue; // The current zoom value. 144 145 private Parameters mInitialParams; 146 private boolean mFocusAreaSupported; 147 private boolean mMeteringAreaSupported; 148 private boolean mAeLockSupported; 149 private boolean mAwbLockSupported; 150 private boolean mContinuousFocusSupported; 151 152 // The degrees of the device rotated clockwise from its natural orientation. 153 private int mOrientation = OrientationEventListener.ORIENTATION_UNKNOWN; 154 155 private static final String sTempCropFilename = "crop-temp"; 156 157 private boolean mFaceDetectionStarted = false; 158 159 // mCropValue and mSaveUri are used only if isImageCaptureIntent() is true. 160 private String mCropValue; 161 private Uri mSaveUri; 162 163 private Uri mDebugUri; 164 165 // We use a queue to generated names of the images to be used later 166 // when the image is ready to be saved. 167 private NamedImages mNamedImages; 168 169 private final Runnable mDoSnapRunnable = new Runnable() { 170 @Override 171 public void run() { 172 onShutterButtonClick(); 173 } 174 }; 175 176 /** 177 * An unpublished intent flag requesting to return as soon as capturing is 178 * completed. TODO: consider publishing by moving into MediaStore. 179 */ 180 private static final String EXTRA_QUICK_CAPTURE = 181 "android.intent.extra.quickCapture"; 182 183 // The display rotation in degrees. This is only valid when mCameraState is 184 // not PREVIEW_STOPPED. 185 private int mDisplayRotation; 186 // The value for android.hardware.Camera.setDisplayOrientation. 187 private int mCameraDisplayOrientation; 188 // The value for UI components like indicators. 189 private int mDisplayOrientation; 190 // The value for android.hardware.Camera.Parameters.setRotation. 191 private int mJpegRotation; 192 // Indicates whether we are using front camera 193 private boolean mMirror; 194 private boolean mFirstTimeInitialized; 195 private boolean mIsImageCaptureIntent; 196 197 private int mCameraState = PREVIEW_STOPPED; 198 private boolean mSnapshotOnIdle = false; 199 200 private ContentResolver mContentResolver; 201 202 private LocationManager mLocationManager; 203 private AppController mAppController; 204 205 private final PostViewPictureCallback mPostViewPictureCallback = 206 new PostViewPictureCallback(); 207 private final RawPictureCallback mRawPictureCallback = 208 new RawPictureCallback(); 209 private final AutoFocusCallback mAutoFocusCallback = 210 new AutoFocusCallback(); 211 private final Object mAutoFocusMoveCallback = 212 ApiHelper.HAS_AUTO_FOCUS_MOVE_CALLBACK 213 ? new AutoFocusMoveCallback() 214 : null; 215 216 private final CameraErrorCallback mErrorCallback = new CameraErrorCallback(); 217 218 private long mFocusStartTime; 219 private long mShutterCallbackTime; 220 private long mPostViewPictureCallbackTime; 221 private long mRawPictureCallbackTime; 222 private long mJpegPictureCallbackTime; 223 private long mOnResumeTime; 224 private byte[] mJpegImageData; 225 226 // These latency time are for the CameraLatency test. 227 public long mAutoFocusTime; 228 public long mShutterLag; 229 public long mShutterToPictureDisplayedTime; 230 public long mPictureDisplayedToJpegCallbackTime; 231 public long mJpegCallbackFinishTime; 232 public long mCaptureStartTime; 233 234 // This handles everything about focus. 235 private FocusOverlayManager mFocusManager; 236 237 private String mSceneMode; 238 239 private final Handler mHandler = new MainHandler(); 240 241 private boolean mQuickCapture; 242 private SensorManager mSensorManager; 243 private final float[] mGData = new float[3]; 244 private final float[] mMData = new float[3]; 245 private final float[] mR = new float[16]; 246 private int mHeading = -1; 247 248 /** Whether shutter is enabled. */ 249 private boolean mShutterEnabled = true; 250 251 /** True if all the parameters needed to start preview is ready. */ 252 private boolean mCameraPreviewParamsReady = false; 253 254 private final MediaSaver.OnMediaSavedListener mOnMediaSavedListener = 255 new MediaSaver.OnMediaSavedListener() { 256 @Override 257 public void onMediaSaved(Uri uri) { 258 if (uri != null) { 259 mActivity.notifyNewMedia(uri); 260 } 261 } 262 }; 263 264 private void checkDisplayRotation() { 265 // Set the display orientation if display rotation has changed. 266 // Sometimes this happens when the device is held upside 267 // down and camera app is opened. Rotation animation will 268 // take some time and the rotation value we have got may be 269 // wrong. Framework does not have a callback for this now. 270 if (CameraUtil.getDisplayRotation(mActivity) != mDisplayRotation) { 271 setDisplayOrientation(); 272 } 273 if (SystemClock.uptimeMillis() - mOnResumeTime < 5000) { 274 mHandler.postDelayed(new Runnable() { 275 @Override 276 public void run() { 277 checkDisplayRotation(); 278 } 279 }, 100); 280 } 281 } 282 283 /** 284 * This Handler is used to post message back onto the main thread of the 285 * application 286 */ 287 private class MainHandler extends Handler { 288 public MainHandler() { 289 super(Looper.getMainLooper()); 290 } 291 292 @Override 293 public void handleMessage(Message msg) { 294 switch (msg.what) { 295 case MSG_SETUP_PREVIEW: { 296 setupPreview(); 297 break; 298 } 299 300 case MSG_FIRST_TIME_INIT: { 301 initializeFirstTime(); 302 break; 303 } 304 305 case MSG_SET_CAMERA_PARAMETERS_WHEN_IDLE: { 306 setCameraParametersWhenIdle(0); 307 break; 308 } 309 310 case MSG_SHOW_TAP_TO_FOCUS_TOAST: { 311 showTapToFocusToast(); 312 break; 313 } 314 315 case MSG_SWITCH_CAMERA: { 316 switchCamera(); 317 break; 318 } 319 320 case MSG_SWITCH_CAMERA_START_ANIMATION: { 321 // TODO: Need to revisit 322 // ((CameraScreenNail) 323 // mActivity.mCameraScreenNail).animateSwitchCamera(); 324 break; 325 } 326 327 case MSG_CAMERA_OPEN_DONE: { 328 onCameraOpened(); 329 break; 330 } 331 332 case MSG_OPEN_CAMERA_FAIL: { 333 mOpenCameraFail = true; 334 CameraUtil.showErrorAndFinish(mActivity, 335 R.string.cannot_connect_camera); 336 break; 337 } 338 339 case MSG_CAMERA_DISABLED: { 340 mCameraDisabled = true; 341 CameraUtil.showErrorAndFinish(mActivity, 342 R.string.camera_disabled); 343 break; 344 } 345 346 case MSG_SWITCH_TO_GCAM_MODULE: { 347 mActivity.onModeSelected(ModeListView.MODE_GCAM); 348 } 349 } 350 } 351 } 352 353 /** 354 * Constructs a new photo module. 355 */ 356 public PhotoModule(AppController app) { 357 super(app); 358 } 359 360 361 @Override 362 public void init(AppController app, boolean isSecureCamera, boolean isCaptureIntent) { 363 mActivity = (CameraActivity) app.getAndroidContext(); 364 mUI = new PhotoUI(mActivity, this, app.getModuleLayoutRoot()); 365 app.setPreviewStatusListener(mUI); 366 367 SettingsManager settingsManager = mActivity.getSettingsManager(); 368 mCameraId = Integer.parseInt(settingsManager.get(SettingsManager.SETTING_CAMERA_ID)); 369 370 mContentResolver = mActivity.getContentResolver(); 371 372 // Surface texture is from camera screen nail and startPreview needs it. 373 // This must be done before startPreview. 374 mIsImageCaptureIntent = isImageCaptureIntent(); 375 376 mActivity.getCameraProvider().requestCamera(mCameraId); 377 378 initializeControlByIntent(); 379 mQuickCapture = mActivity.getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false); 380 mLocationManager = mActivity.getLocationManager(); 381 mSensorManager = (SensorManager) (mActivity.getSystemService(Context.SENSOR_SERVICE)); 382 mAppController = app; 383 } 384 385 private void initializeControlByIntent() { 386 mUI.initializeControlByIntent(); 387 if (mIsImageCaptureIntent) { 388 setupCaptureParams(); 389 } 390 } 391 392 private void onPreviewStarted() { 393 mAppController.onPreviewStarted(); 394 setCameraState(IDLE); 395 startFaceDetection(); 396 startSmartCamera(); 397 locationFirstRun(); 398 } 399 400 // Prompt the user to pick to record location for the very first run of 401 // camera only 402 private void locationFirstRun() { 403 SettingsManager settingsManager = mActivity.getSettingsManager(); 404 if (settingsManager.isSet(SettingsManager.SETTING_RECORD_LOCATION)) { 405 return; 406 } 407 if (mActivity.isSecureCamera()) { 408 return; 409 } 410 // Check if the back camera exists 411 int backCameraId = CameraHolder.instance().getBackCameraId(); 412 if (backCameraId == -1) { 413 // If there is no back camera, do not show the prompt. 414 return; 415 } 416 mUI.showLocationDialog(); 417 } 418 419 @Override 420 public void onPreviewUIReady() { 421 startPreview(); 422 } 423 424 @Override 425 public void onPreviewUIDestroyed() { 426 if (mCameraDevice == null) { 427 return; 428 } 429 mCameraDevice.setPreviewTexture(null); 430 stopPreview(); 431 } 432 433 private void onCameraOpened() { 434 View root = mUI.getRootView(); 435 // These depend on camera parameters. 436 437 int width = root.getWidth(); 438 int height = root.getHeight(); 439 mFocusManager.setPreviewSize(width, height); 440 openCameraCommon(); 441 } 442 443 private void switchCamera() { 444 if (mPaused) { 445 return; 446 } 447 SettingsManager settingsManager = mActivity.getSettingsManager(); 448 449 Log.v(TAG, "Start to switch camera. id=" + mPendingSwitchCameraId); 450 mCameraId = mPendingSwitchCameraId; 451 mPendingSwitchCameraId = -1; 452 settingsManager.set(SettingsManager.SETTING_CAMERA_ID, "" + mCameraId); 453 mActivity.getCameraProvider().requestCamera(mCameraId); 454 mUI.clearFaces(); 455 if (mFocusManager != null) { 456 mFocusManager.removeMessages(); 457 } 458 459 // TODO: this needs to be brought into onCameraAvailable(); 460 CameraInfo info = mActivity.getCameraProvider().getCameraInfo()[mCameraId]; 461 mMirror = (info.facing == CameraInfo.CAMERA_FACING_FRONT); 462 mFocusManager.setMirror(mMirror); 463 // Start switch camera animation. Post a message because 464 // onFrameAvailable from the old camera may already exist. 465 mHandler.sendEmptyMessage(MSG_SWITCH_CAMERA_START_ANIMATION); 466 } 467 468 private final ButtonManager.ButtonCallback mCameraButtonCallback = 469 new ButtonManager.ButtonCallback() { 470 @Override 471 public void onStateChanged(int state) { 472 if (mPaused || mPendingSwitchCameraId != -1) { 473 return; 474 } 475 mPendingSwitchCameraId = state; 476 477 Log.v(TAG, "Start to switch camera. cameraId=" + state); 478 // We need to keep a preview frame for the animation before 479 // releasing the camera. This will trigger onPreviewTextureCopied. 480 //TODO: Need to animate the camera switch 481 switchCamera(); 482 } 483 }; 484 485 private final ButtonManager.ButtonCallback mHdrPlusButtonCallback = 486 new ButtonManager.ButtonCallback() { 487 @Override 488 public void onStateChanged(int state) { 489 if (GcamHelper.hasGcamCapture()) { 490 mHandler.sendEmptyMessage(MSG_SWITCH_TO_GCAM_MODULE); 491 } else { 492 mSceneMode = CameraUtil.SCENE_MODE_HDR; 493 updateParametersSceneMode(); 494 } 495 } 496 }; 497 498 // either open a new camera or switch cameras 499 private void openCameraCommon() { 500 mUI.onCameraOpened(mParameters, mCameraButtonCallback, mHdrPlusButtonCallback); 501 if (mIsImageCaptureIntent) { 502 // Set hdr plus to default: off. 503 SettingsManager settingsManager = mActivity.getSettingsManager(); 504 settingsManager.setDefault(SettingsManager.SETTING_CAMERA_HDR_PLUS); 505 } 506 updateSceneMode(); 507 } 508 509 @Override 510 public void onPreviewRectChanged(Rect previewRect) { 511 if (mFocusManager != null) 512 mFocusManager.setPreviewRect(previewRect); 513 } 514 515 private void resetExposureCompensation() { 516 SettingsManager settingsManager = mActivity.getSettingsManager(); 517 if (settingsManager == null) { 518 Log.e(TAG, "Settings manager is null!"); 519 return; 520 } 521 settingsManager.setDefault(SettingsManager.SETTING_EXPOSURE); 522 } 523 524 // Snapshots can only be taken after this is called. It should be called 525 // once only. We could have done these things in onCreate() but we want to 526 // make preview screen appear as soon as possible. 527 private void initializeFirstTime() { 528 if (mFirstTimeInitialized || mPaused) { 529 return; 530 } 531 532 // Initialize location service. 533 SettingsController settingsController = mActivity.getSettingsController(); 534 settingsController.syncLocationManager(); 535 536 mUI.initializeFirstTime(); 537 538 // We set the listener only when both service and shutterbutton 539 // are initialized. 540 getServices().getMemoryManager().addListener(this); 541 542 mNamedImages = new NamedImages(); 543 544 mFirstTimeInitialized = true; 545 addIdleHandler(); 546 547 mActivity.updateStorageSpaceAndHint(); 548 } 549 550 // If the activity is paused and resumed, this method will be called in 551 // onResume. 552 private void initializeSecondTime() { 553 // Start location update if needed. 554 SettingsController settingsController = mActivity.getSettingsController(); 555 settingsController.syncLocationManager(); 556 557 getServices().getMemoryManager().addListener(this); 558 mNamedImages = new NamedImages(); 559 mUI.initializeSecondTime(mParameters); 560 } 561 562 private void addIdleHandler() { 563 MessageQueue queue = Looper.myQueue(); 564 queue.addIdleHandler(new MessageQueue.IdleHandler() { 565 @Override 566 public boolean queueIdle() { 567 Storage.ensureOSXCompatible(); 568 return false; 569 } 570 }); 571 } 572 573 private void startSmartCamera() { 574 SmartCameraHelper.register(mCameraDevice, mParameters.getPreviewSize(), mActivity, 575 (ViewGroup) mActivity.findViewById(R.id.camera_app_root)); 576 } 577 578 private void stopSmartCamera() { 579 SmartCameraHelper.tearDown(); 580 } 581 582 @Override 583 public void startFaceDetection() { 584 if (mFaceDetectionStarted) { 585 return; 586 } 587 if (mParameters.getMaxNumDetectedFaces() > 0) { 588 mFaceDetectionStarted = true; 589 CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId]; 590 mUI.onStartFaceDetection(mDisplayOrientation, 591 (info.facing == CameraInfo.CAMERA_FACING_FRONT)); 592 mCameraDevice.setFaceDetectionCallback(mHandler, mUI); 593 mCameraDevice.startFaceDetection(); 594 } 595 } 596 597 @Override 598 public void stopFaceDetection() { 599 if (!mFaceDetectionStarted) { 600 return; 601 } 602 if (mParameters.getMaxNumDetectedFaces() > 0) { 603 mFaceDetectionStarted = false; 604 mCameraDevice.setFaceDetectionCallback(null, null); 605 mCameraDevice.stopFaceDetection(); 606 mUI.clearFaces(); 607 } 608 } 609 610 private final class ShutterCallback 611 implements CameraShutterCallback { 612 613 private final boolean mNeedsAnimation; 614 615 public ShutterCallback(boolean needsAnimation) { 616 mNeedsAnimation = needsAnimation; 617 } 618 619 @Override 620 public void onShutter(CameraProxy camera) { 621 mShutterCallbackTime = System.currentTimeMillis(); 622 mShutterLag = mShutterCallbackTime - mCaptureStartTime; 623 Log.v(TAG, "mShutterLag = " + mShutterLag + "ms"); 624 if (mNeedsAnimation) { 625 mActivity.runOnUiThread(new Runnable() { 626 @Override 627 public void run() { 628 animateAfterShutter(); 629 } 630 }); 631 } 632 } 633 } 634 635 private final class PostViewPictureCallback 636 implements CameraPictureCallback { 637 @Override 638 public void onPictureTaken(byte[] data, CameraProxy camera) { 639 mPostViewPictureCallbackTime = System.currentTimeMillis(); 640 Log.v(TAG, "mShutterToPostViewCallbackTime = " 641 + (mPostViewPictureCallbackTime - mShutterCallbackTime) 642 + "ms"); 643 } 644 } 645 646 private final class RawPictureCallback 647 implements CameraPictureCallback { 648 @Override 649 public void onPictureTaken(byte[] rawData, CameraProxy camera) { 650 mRawPictureCallbackTime = System.currentTimeMillis(); 651 Log.v(TAG, "mShutterToRawCallbackTime = " 652 + (mRawPictureCallbackTime - mShutterCallbackTime) + "ms"); 653 } 654 } 655 656 private final class JpegPictureCallback 657 implements CameraPictureCallback { 658 Location mLocation; 659 660 public JpegPictureCallback(Location loc) { 661 mLocation = loc; 662 } 663 664 @Override 665 public void onPictureTaken(final byte[] jpegData, CameraProxy camera) { 666 setShutterEnabled(true); 667 if (mPaused) { 668 return; 669 } 670 if (mIsImageCaptureIntent) { 671 stopPreview(); 672 } 673 if (mSceneMode == CameraUtil.SCENE_MODE_HDR) { 674 mUI.setSwipingEnabled(true); 675 } 676 677 mJpegPictureCallbackTime = System.currentTimeMillis(); 678 // If postview callback has arrived, the captured image is displayed 679 // in postview callback. If not, the captured image is displayed in 680 // raw picture callback. 681 if (mPostViewPictureCallbackTime != 0) { 682 mShutterToPictureDisplayedTime = 683 mPostViewPictureCallbackTime - mShutterCallbackTime; 684 mPictureDisplayedToJpegCallbackTime = 685 mJpegPictureCallbackTime - mPostViewPictureCallbackTime; 686 } else { 687 mShutterToPictureDisplayedTime = 688 mRawPictureCallbackTime - mShutterCallbackTime; 689 mPictureDisplayedToJpegCallbackTime = 690 mJpegPictureCallbackTime - mRawPictureCallbackTime; 691 } 692 Log.v(TAG, "mPictureDisplayedToJpegCallbackTime = " 693 + mPictureDisplayedToJpegCallbackTime + "ms"); 694 695 mFocusManager.updateFocusUI(); // Ensure focus indicator is hidden. 696 if (!mIsImageCaptureIntent) { 697 setupPreview(); 698 } 699 700 ExifInterface exif = Exif.getExif(jpegData); 701 int orientation = Exif.getOrientation(exif); 702 703 if (!mIsImageCaptureIntent) { 704 // Calculate the width and the height of the jpeg. 705 Size s = mParameters.getPictureSize(); 706 int width, height; 707 if ((mJpegRotation + orientation) % 180 == 0) { 708 width = s.width; 709 height = s.height; 710 } else { 711 width = s.height; 712 height = s.width; 713 } 714 NamedEntity name = mNamedImages.getNextNameEntity(); 715 String title = (name == null) ? null : name.title; 716 long date = (name == null) ? -1 : name.date; 717 718 // Handle debug mode outputs 719 if (mDebugUri != null) { 720 // If using a debug uri, save jpeg there. 721 saveToDebugUri(jpegData); 722 723 // Adjust the title of the debug image shown in mediastore. 724 if (title != null) { 725 title = DEBUG_IMAGE_PREFIX + title; 726 } 727 } 728 729 if (title == null) { 730 Log.e(TAG, "Unbalanced name/data pair"); 731 } else { 732 if (date == -1) 733 date = mCaptureStartTime; 734 if (mHeading >= 0) { 735 // heading direction has been updated by the sensor. 736 ExifTag directionRefTag = exif.buildTag( 737 ExifInterface.TAG_GPS_IMG_DIRECTION_REF, 738 ExifInterface.GpsTrackRef.MAGNETIC_DIRECTION); 739 ExifTag directionTag = exif.buildTag( 740 ExifInterface.TAG_GPS_IMG_DIRECTION, 741 new Rational(mHeading, 1)); 742 exif.setTag(directionRefTag); 743 exif.setTag(directionTag); 744 } 745 getServices().getMediaSaver().addImage( 746 jpegData, title, date, mLocation, width, height, 747 orientation, exif, mOnMediaSavedListener, mContentResolver); 748 } 749 // Animate capture with real jpeg data instead of a preview 750 // frame. 751 mUI.animateCapture(jpegData, orientation, mMirror); 752 } else { 753 mJpegImageData = jpegData; 754 if (!mQuickCapture) { 755 mUI.showCapturedImageForReview(jpegData, orientation, mMirror); 756 } else { 757 onCaptureDone(); 758 } 759 } 760 761 // Check this in advance of each shot so we don't add to shutter 762 // latency. It's true that someone else could write to the SD card 763 // in the mean time and fill it, but that could have happened 764 // between the shutter press and saving the JPEG too. 765 mActivity.updateStorageSpaceAndHint(); 766 767 long now = System.currentTimeMillis(); 768 mJpegCallbackFinishTime = now - mJpegPictureCallbackTime; 769 Log.v(TAG, "mJpegCallbackFinishTime = " 770 + mJpegCallbackFinishTime + "ms"); 771 mJpegPictureCallbackTime = 0; 772 } 773 } 774 775 private final class AutoFocusCallback implements CameraAFCallback { 776 @Override 777 public void onAutoFocus( 778 boolean focused, CameraProxy camera) { 779 if (mPaused) { 780 return; 781 } 782 783 mAutoFocusTime = System.currentTimeMillis() - mFocusStartTime; 784 Log.v(TAG, "mAutoFocusTime = " + mAutoFocusTime + "ms"); 785 setCameraState(IDLE); 786 mFocusManager.onAutoFocus(focused, mUI.isShutterPressed()); 787 } 788 } 789 790 @TargetApi(Build.VERSION_CODES.JELLY_BEAN) 791 private final class AutoFocusMoveCallback 792 implements CameraAFMoveCallback { 793 @Override 794 public void onAutoFocusMoving( 795 boolean moving, CameraProxy camera) { 796 mFocusManager.onAutoFocusMoving(moving); 797 } 798 } 799 800 /** 801 * This class is just a thread-safe queue for name,date holder objects. 802 */ 803 public static class NamedImages { 804 private final Vector<NamedEntity> mQueue; 805 806 public NamedImages() { 807 mQueue = new Vector<NamedEntity>(); 808 } 809 810 public void nameNewImage(long date) { 811 NamedEntity r = new NamedEntity(); 812 r.title = CameraUtil.createJpegName(date); 813 r.date = date; 814 mQueue.add(r); 815 } 816 817 public NamedEntity getNextNameEntity() { 818 synchronized (mQueue) { 819 if (!mQueue.isEmpty()) { 820 return mQueue.remove(0); 821 } 822 } 823 return null; 824 } 825 826 public static class NamedEntity { 827 public String title; 828 public long date; 829 } 830 } 831 832 private void setCameraState(int state) { 833 mCameraState = state; 834 switch (state) { 835 case PhotoController.PREVIEW_STOPPED: 836 case PhotoController.SNAPSHOT_IN_PROGRESS: 837 case PhotoController.SWITCHING_CAMERA: 838 // TODO: Tell app UI to disable swipe 839 break; 840 case PhotoController.IDLE: 841 // TODO: Tell app UI to enable swipe 842 break; 843 } 844 } 845 846 private void animateAfterShutter() { 847 // Only animate when in full screen capture mode 848 // i.e. If monkey/a user swipes to the gallery during picture taking, 849 // don't show animation 850 if (!mIsImageCaptureIntent) { 851 mUI.animateFlash(); 852 } 853 } 854 855 @Override 856 public boolean capture() { 857 // If we are already in the middle of taking a snapshot or the image 858 // save request is full then ignore. 859 if (mCameraDevice == null || mCameraState == SNAPSHOT_IN_PROGRESS 860 || mCameraState == SWITCHING_CAMERA || !mShutterEnabled) { 861 return false; 862 } 863 mCaptureStartTime = System.currentTimeMillis(); 864 mPostViewPictureCallbackTime = 0; 865 mJpegImageData = null; 866 867 final boolean animateBefore = (mSceneMode == CameraUtil.SCENE_MODE_HDR); 868 869 if (animateBefore) { 870 animateAfterShutter(); 871 } 872 873 // Set rotation and gps data. 874 int orientation; 875 876 // We need to be consistent with the framework orientation (i.e. the 877 // orientation of the UI.) when the auto-rotate screen setting is on. 878 if (mActivity.isAutoRotateScreen()) { 879 orientation = (360 - mDisplayRotation) % 360; 880 } else { 881 orientation = mOrientation; 882 } 883 mJpegRotation = CameraUtil.getJpegRotation(mActivity, mCameraId, orientation); 884 mParameters.setRotation(mJpegRotation); 885 Location loc = mActivity.getLocationManager().getCurrentLocation(); 886 CameraUtil.setGpsParameters(mParameters, loc); 887 mCameraDevice.setParameters(mParameters); 888 889 // We don't want user to press the button again while taking a 890 // multi-second HDR photo. 891 setShutterEnabled(false); 892 mCameraDevice.takePicture(mHandler, 893 new ShutterCallback(!animateBefore), 894 mRawPictureCallback, mPostViewPictureCallback, 895 new JpegPictureCallback(loc)); 896 897 mNamedImages.nameNewImage(mCaptureStartTime); 898 899 mFaceDetectionStarted = false; 900 setCameraState(SNAPSHOT_IN_PROGRESS); 901 UsageStatistics.onEvent(UsageStatistics.COMPONENT_CAMERA, 902 UsageStatistics.ACTION_CAPTURE_DONE, "Photo", 0, 903 UsageStatistics.hashFileName(mNamedImages.mQueue.lastElement().title + ".jpg")); 904 return true; 905 } 906 907 @Override 908 public void setFocusParameters() { 909 setCameraParameters(UPDATE_PARAM_PREFERENCE); 910 } 911 912 private void updateSceneMode() { 913 // If scene mode is set, we cannot set flash mode, white balance, and 914 // focus mode, instead, we read it from driver 915 if (!Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) { 916 overrideCameraSettings(mParameters.getFlashMode(), 917 mParameters.getWhiteBalance(), mParameters.getFocusMode()); 918 } else { 919 overrideCameraSettings(null, null, null); 920 } 921 } 922 923 private void overrideCameraSettings(final String flashMode, 924 final String whiteBalance, final String focusMode) { 925 SettingsManager settingsManager = mActivity.getSettingsManager(); 926 settingsManager.set(SettingsManager.SETTING_FLASH_MODE, flashMode); 927 settingsManager.set(SettingsManager.SETTING_WHITE_BALANCE, whiteBalance); 928 settingsManager.set(SettingsManager.SETTING_FOCUS_MODE, focusMode); 929 } 930 931 @Override 932 public void onOrientationChanged(int orientation) { 933 // We keep the last known orientation. So if the user first orient 934 // the camera then point the camera to floor or sky, we still have 935 // the correct orientation. 936 if (orientation == OrientationEventListener.ORIENTATION_UNKNOWN) { 937 return; 938 } 939 mOrientation = CameraUtil.roundOrientation(orientation, mOrientation); 940 941 // Show the toast after getting the first orientation changed. 942 if (mHandler.hasMessages(MSG_SHOW_TAP_TO_FOCUS_TOAST)) { 943 mHandler.removeMessages(MSG_SHOW_TAP_TO_FOCUS_TOAST); 944 showTapToFocusToast(); 945 } 946 } 947 948 @Override 949 public void onCameraAvailable(CameraProxy cameraProxy) { 950 if (mPaused) { 951 return; 952 } 953 mCameraDevice = cameraProxy; 954 955 resetExposureCompensation(); 956 initializeCapabilities(); 957 958 // Reset zoom value index. 959 mZoomValue = 0; 960 if (mFocusManager == null) { 961 initializeFocusManager(); 962 } 963 mFocusManager.setParameters(mInitialParams); 964 965 mParameters = mCameraDevice.getParameters(); 966 setCameraParameters(UPDATE_PARAM_ALL); 967 mCameraPreviewParamsReady = true; 968 startPreview(); 969 970 onCameraOpened(); 971 } 972 973 @Override 974 public void onCaptureCancelled() { 975 mActivity.setResultEx(Activity.RESULT_CANCELED, new Intent()); 976 mActivity.finish(); 977 } 978 979 @Override 980 public void onCaptureRetake() { 981 if (mPaused) 982 return; 983 mUI.hidePostCaptureAlert(); 984 setupPreview(); 985 } 986 987 @Override 988 public void onCaptureDone() { 989 if (mPaused) { 990 return; 991 } 992 993 byte[] data = mJpegImageData; 994 995 if (mCropValue == null) { 996 // First handle the no crop case -- just return the value. If the 997 // caller specifies a "save uri" then write the data to its 998 // stream. Otherwise, pass back a scaled down version of the bitmap 999 // directly in the extras. 1000 if (mSaveUri != null) { 1001 OutputStream outputStream = null; 1002 try { 1003 outputStream = mContentResolver.openOutputStream(mSaveUri); 1004 outputStream.write(data); 1005 outputStream.close(); 1006 1007 mActivity.setResultEx(Activity.RESULT_OK); 1008 mActivity.finish(); 1009 } catch (IOException ex) { 1010 // ignore exception 1011 } finally { 1012 CameraUtil.closeSilently(outputStream); 1013 } 1014 } else { 1015 ExifInterface exif = Exif.getExif(data); 1016 int orientation = Exif.getOrientation(exif); 1017 Bitmap bitmap = CameraUtil.makeBitmap(data, 50 * 1024); 1018 bitmap = CameraUtil.rotate(bitmap, orientation); 1019 mActivity.setResultEx(Activity.RESULT_OK, 1020 new Intent("inline-data").putExtra("data", bitmap)); 1021 mActivity.finish(); 1022 } 1023 } else { 1024 // Save the image to a temp file and invoke the cropper 1025 Uri tempUri = null; 1026 FileOutputStream tempStream = null; 1027 try { 1028 File path = mActivity.getFileStreamPath(sTempCropFilename); 1029 path.delete(); 1030 tempStream = mActivity.openFileOutput(sTempCropFilename, 0); 1031 tempStream.write(data); 1032 tempStream.close(); 1033 tempUri = Uri.fromFile(path); 1034 } catch (FileNotFoundException ex) { 1035 mActivity.setResultEx(Activity.RESULT_CANCELED); 1036 mActivity.finish(); 1037 return; 1038 } catch (IOException ex) { 1039 mActivity.setResultEx(Activity.RESULT_CANCELED); 1040 mActivity.finish(); 1041 return; 1042 } finally { 1043 CameraUtil.closeSilently(tempStream); 1044 } 1045 1046 Bundle newExtras = new Bundle(); 1047 if (mCropValue.equals("circle")) { 1048 newExtras.putString("circleCrop", "true"); 1049 } 1050 if (mSaveUri != null) { 1051 newExtras.putParcelable(MediaStore.EXTRA_OUTPUT, mSaveUri); 1052 } else { 1053 newExtras.putBoolean(CameraUtil.KEY_RETURN_DATA, true); 1054 } 1055 if (mActivity.isSecureCamera()) { 1056 newExtras.putBoolean(CameraUtil.KEY_SHOW_WHEN_LOCKED, true); 1057 } 1058 1059 // TODO: Share this constant. 1060 final String CROP_ACTION = "com.android.camera.action.CROP"; 1061 Intent cropIntent = new Intent(CROP_ACTION); 1062 1063 cropIntent.setData(tempUri); 1064 cropIntent.putExtras(newExtras); 1065 1066 mActivity.startActivityForResult(cropIntent, REQUEST_CROP); 1067 } 1068 } 1069 1070 @Override 1071 public void onShutterButtonFocus(boolean pressed) { 1072 if (mPaused || (mCameraState == SNAPSHOT_IN_PROGRESS) 1073 || (mCameraState == PREVIEW_STOPPED)) { 1074 return; 1075 } 1076 1077 // Do not do focus if there is not enough storage. 1078 if (pressed && !canTakePicture()) { 1079 return; 1080 } 1081 1082 if (pressed) { 1083 mFocusManager.onShutterDown(); 1084 } else { 1085 mFocusManager.onShutterUp(); 1086 } 1087 } 1088 1089 @Override 1090 public void onShutterButtonClick() { 1091 if (mPaused || (mCameraState == SWITCHING_CAMERA) 1092 || (mCameraState == PREVIEW_STOPPED)) { 1093 return; 1094 } 1095 1096 // Do not take the picture if there is not enough storage. 1097 if (mActivity.getStorageSpaceBytes() <= Storage.LOW_STORAGE_THRESHOLD_BYTES) { 1098 Log.i(TAG, "Not enough space or storage not ready. remaining=" 1099 + mActivity.getStorageSpaceBytes()); 1100 return; 1101 } 1102 Log.v(TAG, "onShutterButtonClick: mCameraState=" + mCameraState); 1103 1104 if (mSceneMode == CameraUtil.SCENE_MODE_HDR) { 1105 mUI.setSwipingEnabled(false); 1106 } 1107 // If the user wants to do a snapshot while the previous one is still 1108 // in progress, remember the fact and do it after we finish the previous 1109 // one and re-start the preview. Snapshot in progress also includes the 1110 // state that autofocus is focusing and a picture will be taken when 1111 // focus callback arrives. 1112 if ((mFocusManager.isFocusingSnapOnFinish() || mCameraState == SNAPSHOT_IN_PROGRESS) 1113 && !mIsImageCaptureIntent) { 1114 mSnapshotOnIdle = true; 1115 return; 1116 } 1117 1118 mSnapshotOnIdle = false; 1119 mFocusManager.doSnap(); 1120 } 1121 1122 private void onResumeTasks() { 1123 Log.v(TAG, "Executing onResumeTasks."); 1124 if (mOpenCameraFail || mCameraDisabled) { 1125 return; 1126 } 1127 1128 mActivity.getCameraProvider().requestCamera(mCameraId); 1129 1130 mJpegPictureCallbackTime = 0; 1131 mZoomValue = 0; 1132 1133 mOnResumeTime = SystemClock.uptimeMillis(); 1134 checkDisplayRotation(); 1135 1136 // If first time initialization is not finished, put it in the 1137 // message queue. 1138 if (!mFirstTimeInitialized) { 1139 mHandler.sendEmptyMessage(MSG_FIRST_TIME_INIT); 1140 } else { 1141 initializeSecondTime(); 1142 } 1143 1144 UsageStatistics.onContentViewChanged( 1145 UsageStatistics.COMPONENT_CAMERA, "PhotoModule"); 1146 1147 Sensor gsensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); 1148 if (gsensor != null) { 1149 mSensorManager.registerListener(this, gsensor, SensorManager.SENSOR_DELAY_NORMAL); 1150 } 1151 1152 Sensor msensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); 1153 if (msensor != null) { 1154 mSensorManager.registerListener(this, msensor, SensorManager.SENSOR_DELAY_NORMAL); 1155 } 1156 } 1157 1158 /** 1159 * The focus manager is the first UI related element to get initialized, 1160 * and it requires the RenderOverlay, so initialize it here 1161 */ 1162 private void initializeFocusManager() { 1163 // Create FocusManager object. startPreview needs it. 1164 // if mFocusManager not null, reuse it 1165 // otherwise create a new instance 1166 if (mFocusManager != null) { 1167 mFocusManager.removeMessages(); 1168 } else { 1169 CameraInfo info = CameraHolder.instance().getCameraInfo()[mCameraId]; 1170 mMirror = (info.facing == CameraInfo.CAMERA_FACING_FRONT); 1171 String[] defaultFocusModes = mActivity.getResources().getStringArray( 1172 R.array.pref_camera_focusmode_default_array); 1173 mFocusManager = new FocusOverlayManager(mActivity.getSettingsManager(), 1174 defaultFocusModes, 1175 mInitialParams, this, mMirror, 1176 mActivity.getMainLooper(), mUI); 1177 } 1178 } 1179 1180 @Override 1181 public void resume() { 1182 mPaused = false; 1183 // Add delay on resume from lock screen only, in order to to speed up 1184 // the onResume --> onPause --> onResume cycle from lock screen. 1185 // Don't do always because letting go of thread can cause delay. 1186 String action = mActivity.getIntent().getAction(); 1187 if (MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA.equals(action) 1188 || MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE.equals(action)) { 1189 Log.v(TAG, "On resume, from lock screen."); 1190 // Note: onPauseAfterSuper() will delete this runnable, so we will 1191 // at most have 1 copy queued up. 1192 mHandler.postDelayed(new Runnable() { 1193 @Override 1194 public void run() { 1195 onResumeTasks(); 1196 } 1197 }, ON_RESUME_TASKS_DELAY_MSEC); 1198 } else { 1199 Log.v(TAG, "On resume."); 1200 onResumeTasks(); 1201 } 1202 } 1203 1204 @Override 1205 public void pause() { 1206 mPaused = true; 1207 Sensor gsensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); 1208 if (gsensor != null) { 1209 mSensorManager.unregisterListener(this, gsensor); 1210 } 1211 1212 Sensor msensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD); 1213 if (msensor != null) { 1214 mSensorManager.unregisterListener(this, msensor); 1215 } 1216 1217 // Reset the focus first. Camera CTS does not guarantee that 1218 // cancelAutoFocus is allowed after preview stops. 1219 if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) { 1220 mCameraDevice.cancelAutoFocus(); 1221 } 1222 1223 // If the camera has not been opened asynchronously yet, 1224 // and startPreview hasn't been called, then this is a no-op. 1225 // (e.g. onResume -> onPause -> onResume). 1226 stopPreview(); 1227 1228 mNamedImages = null; 1229 1230 if (mLocationManager != null) { 1231 mLocationManager.recordLocation(false); 1232 } 1233 1234 // If we are in an image capture intent and has taken 1235 // a picture, we just clear it in onPause. 1236 mJpegImageData = null; 1237 1238 // Remove the messages and runnables in the queue. 1239 mHandler.removeCallbacksAndMessages(null); 1240 1241 closeCamera(); 1242 mActivity.enableKeepScreenOn(false); 1243 mUI.onPause(); 1244 1245 mPendingSwitchCameraId = -1; 1246 if (mFocusManager != null) { 1247 mFocusManager.removeMessages(); 1248 } 1249 getServices().getMemoryManager().removeListener(this); 1250 } 1251 1252 @Override 1253 public void destroy() { 1254 // TODO: implement this. 1255 } 1256 1257 @Override 1258 public void onPreviewSizeChanged(int width, int height) { 1259 // TODO: implement this. 1260 } 1261 1262 @Override 1263 public void onLayoutOrientationChanged(boolean isLandscape) { 1264 setDisplayOrientation(); 1265 } 1266 1267 @Override 1268 public void updateCameraOrientation() { 1269 if (mDisplayRotation != CameraUtil.getDisplayRotation(mActivity)) { 1270 setDisplayOrientation(); 1271 } 1272 } 1273 1274 private boolean canTakePicture() { 1275 return isCameraIdle() 1276 && (mActivity.getStorageSpaceBytes() > Storage.LOW_STORAGE_THRESHOLD_BYTES); 1277 } 1278 1279 @Override 1280 public void autoFocus() { 1281 mFocusStartTime = System.currentTimeMillis(); 1282 mCameraDevice.autoFocus(mHandler, mAutoFocusCallback); 1283 setCameraState(FOCUSING); 1284 } 1285 1286 @Override 1287 public void cancelAutoFocus() { 1288 mCameraDevice.cancelAutoFocus(); 1289 setCameraState(IDLE); 1290 setCameraParameters(UPDATE_PARAM_PREFERENCE); 1291 } 1292 1293 // Preview area is touched. 1294 @Override 1295 public void onSingleTapUp(View view, int x, int y) { 1296 if (mUI.isImmediateCapture()) { 1297 cancelAutoFocus(); 1298 onShutterButtonClick(); 1299 } else { 1300 onShutterButtonFocus(true); 1301 onShutterButtonClick(); 1302 } 1303 } 1304 1305 @Override 1306 public boolean onBackPressed() { 1307 return mUI.onBackPressed(); 1308 } 1309 1310 @Override 1311 public boolean onKeyDown(int keyCode, KeyEvent event) { 1312 switch (keyCode) { 1313 case KeyEvent.KEYCODE_VOLUME_UP: 1314 case KeyEvent.KEYCODE_VOLUME_DOWN: 1315 case KeyEvent.KEYCODE_FOCUS: 1316 if (/* TODO: mActivity.isInCameraApp() && */mFirstTimeInitialized) { 1317 if (event.getRepeatCount() == 0) { 1318 onShutterButtonFocus(true); 1319 } 1320 return true; 1321 } 1322 return false; 1323 case KeyEvent.KEYCODE_CAMERA: 1324 if (mFirstTimeInitialized && event.getRepeatCount() == 0) { 1325 onShutterButtonClick(); 1326 } 1327 return true; 1328 case KeyEvent.KEYCODE_DPAD_CENTER: 1329 // If we get a dpad center event without any focused view, move 1330 // the focus to the shutter button and press it. 1331 if (mFirstTimeInitialized && event.getRepeatCount() == 0) { 1332 // Start auto-focus immediately to reduce shutter lag. After 1333 // the shutter button gets the focus, onShutterButtonFocus() 1334 // will be called again but it is fine. 1335 onShutterButtonFocus(true); 1336 mUI.pressShutterButton(); 1337 } 1338 return true; 1339 } 1340 return false; 1341 } 1342 1343 @Override 1344 public boolean onKeyUp(int keyCode, KeyEvent event) { 1345 switch (keyCode) { 1346 case KeyEvent.KEYCODE_VOLUME_UP: 1347 case KeyEvent.KEYCODE_VOLUME_DOWN: 1348 if (/* mActivity.isInCameraApp() && */mFirstTimeInitialized) { 1349 onShutterButtonClick(); 1350 return true; 1351 } 1352 return false; 1353 case KeyEvent.KEYCODE_FOCUS: 1354 if (mFirstTimeInitialized) { 1355 onShutterButtonFocus(false); 1356 } 1357 return true; 1358 } 1359 return false; 1360 } 1361 1362 private void closeCamera() { 1363 if (mCameraDevice != null) { 1364 mCameraDevice.setZoomChangeListener(null); 1365 mCameraDevice.setFaceDetectionCallback(null, null); 1366 mCameraDevice.setErrorCallback(null); 1367 1368 mFaceDetectionStarted = false; 1369 mActivity.getCameraProvider().releaseCamera(mCameraDevice.getCameraId()); 1370 mCameraDevice = null; 1371 setCameraState(PREVIEW_STOPPED); 1372 mFocusManager.onCameraReleased(); 1373 } 1374 } 1375 1376 private void setDisplayOrientation() { 1377 mDisplayRotation = CameraUtil.getDisplayRotation(mActivity); 1378 mDisplayOrientation = CameraUtil.getDisplayOrientation(mDisplayRotation, mCameraId); 1379 mCameraDisplayOrientation = mDisplayOrientation; 1380 mUI.setDisplayOrientation(mDisplayOrientation); 1381 if (mFocusManager != null) { 1382 mFocusManager.setDisplayOrientation(mDisplayOrientation); 1383 } 1384 // Change the camera display orientation 1385 if (mCameraDevice != null) { 1386 mCameraDevice.setDisplayOrientation(mCameraDisplayOrientation); 1387 } 1388 } 1389 1390 /** Only called by UI thread. */ 1391 private void setupPreview() { 1392 mFocusManager.resetTouchFocus(); 1393 startPreview(); 1394 } 1395 1396 /** 1397 * Returns whether we can/should start the preview or not. 1398 */ 1399 private boolean checkPreviewPreconditions() { 1400 if (mPaused) { 1401 return false; 1402 } 1403 1404 if (mCameraDevice == null) { 1405 Log.w(TAG, "startPreview: camera device not ready yet."); 1406 return false; 1407 } 1408 1409 SurfaceTexture st = mUI.getSurfaceTexture(); 1410 if (st == null) { 1411 Log.w(TAG, "startPreview: surfaceTexture is not ready."); 1412 return false; 1413 } 1414 1415 if (!mCameraPreviewParamsReady) { 1416 Log.w(TAG, "startPreview: parameters for preview is not ready."); 1417 return false; 1418 } 1419 return true; 1420 } 1421 1422 /** 1423 * The start/stop preview should only run on the UI thread. 1424 */ 1425 private void startPreview() { 1426 if (!checkPreviewPreconditions()) { 1427 return; 1428 } 1429 1430 mCameraDevice.setErrorCallback(mErrorCallback); 1431 // ICS camera frameworks has a bug. Face detection state is not cleared 1432 // after taking a picture. Stop the preview to work around it. The bug 1433 // was fixed in JB. 1434 if (mCameraState != PREVIEW_STOPPED) { 1435 stopPreview(); 1436 } 1437 1438 setDisplayOrientation(); 1439 1440 if (!mSnapshotOnIdle) { 1441 // If the focus mode is continuous autofocus, call cancelAutoFocus 1442 // to resume it because it may have been paused by autoFocus call. 1443 String focusMode = mFocusManager.getFocusMode(); 1444 if (CameraUtil.FOCUS_MODE_CONTINUOUS_PICTURE.equals(focusMode)) { 1445 mCameraDevice.cancelAutoFocus(); 1446 } 1447 mFocusManager.setAeAwbLock(false); // Unlock AE and AWB. 1448 } 1449 setCameraParameters(UPDATE_PARAM_ALL); 1450 // Let UI set its expected aspect ratio 1451 mCameraDevice.setPreviewTexture(mUI.getSurfaceTexture()); 1452 1453 Log.v(TAG, "startPreview"); 1454 mCameraDevice.startPreview(); 1455 1456 mFocusManager.onPreviewStarted(); 1457 onPreviewStarted(); 1458 1459 if (mSnapshotOnIdle) { 1460 mHandler.post(mDoSnapRunnable); 1461 } 1462 } 1463 1464 @Override 1465 public void stopPreview() { 1466 if (mCameraDevice != null && mCameraState != PREVIEW_STOPPED) { 1467 Log.v(TAG, "stopPreview"); 1468 mCameraDevice.stopPreview(); 1469 mFaceDetectionStarted = false; 1470 } 1471 setCameraState(PREVIEW_STOPPED); 1472 if (mFocusManager != null) { 1473 mFocusManager.onPreviewStopped(); 1474 } 1475 stopSmartCamera(); 1476 } 1477 1478 private void updateCameraParametersInitialize() { 1479 // Reset preview frame rate to the maximum because it may be lowered by 1480 // video camera application. 1481 int[] fpsRange = CameraUtil.getPhotoPreviewFpsRange(mParameters); 1482 if (fpsRange != null && fpsRange.length > 0) { 1483 mParameters.setPreviewFpsRange( 1484 fpsRange[Parameters.PREVIEW_FPS_MIN_INDEX], 1485 fpsRange[Parameters.PREVIEW_FPS_MAX_INDEX]); 1486 } 1487 1488 mParameters.set(CameraUtil.RECORDING_HINT, CameraUtil.FALSE); 1489 1490 // Disable video stabilization. Convenience methods not available in API 1491 // level <= 14 1492 String vstabSupported = mParameters.get("video-stabilization-supported"); 1493 if ("true".equals(vstabSupported)) { 1494 mParameters.set("video-stabilization", "false"); 1495 } 1496 } 1497 1498 private void updateCameraParametersZoom() { 1499 // Set zoom. 1500 if (mParameters.isZoomSupported()) { 1501 mParameters.setZoom(mZoomValue); 1502 } 1503 } 1504 1505 @TargetApi(Build.VERSION_CODES.JELLY_BEAN) 1506 private void setAutoExposureLockIfSupported() { 1507 if (mAeLockSupported) { 1508 mParameters.setAutoExposureLock(mFocusManager.getAeAwbLock()); 1509 } 1510 } 1511 1512 @TargetApi(Build.VERSION_CODES.JELLY_BEAN) 1513 private void setAutoWhiteBalanceLockIfSupported() { 1514 if (mAwbLockSupported) { 1515 mParameters.setAutoWhiteBalanceLock(mFocusManager.getAeAwbLock()); 1516 } 1517 } 1518 1519 private void setFocusAreasIfSupported() { 1520 if (mFocusAreaSupported) { 1521 mParameters.setFocusAreas(mFocusManager.getFocusAreas()); 1522 } 1523 } 1524 1525 private void setMeteringAreasIfSupported() { 1526 if (mMeteringAreaSupported) { 1527 mParameters.setMeteringAreas(mFocusManager.getMeteringAreas()); 1528 } 1529 } 1530 1531 private void updateCameraParametersPreference() { 1532 SettingsManager settingsManager = mActivity.getSettingsManager(); 1533 1534 setAutoExposureLockIfSupported(); 1535 setAutoWhiteBalanceLockIfSupported(); 1536 setFocusAreasIfSupported(); 1537 setMeteringAreasIfSupported(); 1538 1539 // Initialize focus mode. 1540 mFocusManager.overrideFocusMode(null); 1541 mParameters.setFocusMode(mFocusManager.getFocusMode()); 1542 1543 // Set picture size. 1544 String pictureSize = settingsManager.get(SettingsManager.SETTING_PICTURE_SIZE); 1545 if (pictureSize == null) { 1546 //TODO: deprecate CameraSettings. 1547 CameraSettings.initialCameraPictureSize( 1548 mActivity, mParameters, settingsManager); 1549 } else { 1550 List<Size> supported = mParameters.getSupportedPictureSizes(); 1551 CameraSettings.setCameraPictureSize( 1552 pictureSize, supported, mParameters); 1553 } 1554 Size size = mParameters.getPictureSize(); 1555 1556 // Set a preview size that is closest to the viewfinder height and has 1557 // the right aspect ratio. 1558 List<Size> sizes = mParameters.getSupportedPreviewSizes(); 1559 Size optimalSize = CameraUtil.getOptimalPreviewSize(mActivity, sizes, 1560 (double) size.width / size.height); 1561 Size original = mParameters.getPreviewSize(); 1562 if (!original.equals(optimalSize)) { 1563 mParameters.setPreviewSize(optimalSize.width, optimalSize.height); 1564 1565 // Zoom related settings will be changed for different preview 1566 // sizes, so set and read the parameters to get latest values 1567 if (mHandler.getLooper() == Looper.myLooper()) { 1568 // On UI thread only, not when camera starts up 1569 setupPreview(); 1570 } else { 1571 mCameraDevice.setParameters(mParameters); 1572 } 1573 mParameters = mCameraDevice.getParameters(); 1574 } 1575 1576 if (optimalSize.width != 0 && optimalSize.height != 0) { 1577 mUI.updatePreviewAspectRatio((float) optimalSize.width 1578 / (float) optimalSize.height); 1579 } 1580 Log.v(TAG, "Preview size is " + optimalSize.width + "x" + optimalSize.height); 1581 1582 // Set JPEG quality. 1583 int jpegQuality = CameraProfile.getJpegEncodingQualityParameter(mCameraId, 1584 CameraProfile.QUALITY_HIGH); 1585 mParameters.setJpegQuality(jpegQuality); 1586 1587 // For the following settings, we need to check if the settings are 1588 // still supported by latest driver, if not, ignore the settings. 1589 1590 // Set exposure compensation 1591 int value = Integer.parseInt(settingsManager.get(SettingsManager.SETTING_EXPOSURE)); 1592 int max = mParameters.getMaxExposureCompensation(); 1593 int min = mParameters.getMinExposureCompensation(); 1594 if (value >= min && value <= max) { 1595 mParameters.setExposureCompensation(value); 1596 } else { 1597 Log.w(TAG, "invalid exposure range: " + value); 1598 } 1599 1600 mSceneMode = settingsManager.get(SettingsManager.SETTING_SCENE_MODE); 1601 updateParametersSceneMode(); 1602 1603 if (mContinuousFocusSupported && ApiHelper.HAS_AUTO_FOCUS_MOVE_CALLBACK) { 1604 updateAutoFocusMoveCallback(); 1605 } 1606 } 1607 1608 public void updateParametersSceneMode() { 1609 SettingsManager settingsManager = mActivity.getSettingsManager(); 1610 1611 if (CameraUtil.isSupported(mSceneMode, mParameters.getSupportedSceneModes())) { 1612 if (!mParameters.getSceneMode().equals(mSceneMode)) { 1613 mParameters.setSceneMode(mSceneMode); 1614 1615 // Setting scene mode will change the settings of flash mode, 1616 // white balance, and focus mode. Here we read back the 1617 // parameters, so we can know those settings. 1618 mCameraDevice.setParameters(mParameters); 1619 mParameters = mCameraDevice.getParameters(); 1620 } 1621 } else { 1622 mSceneMode = mParameters.getSceneMode(); 1623 if (mSceneMode == null) { 1624 mSceneMode = Parameters.SCENE_MODE_AUTO; 1625 } 1626 } 1627 1628 if (Parameters.SCENE_MODE_AUTO.equals(mSceneMode)) { 1629 // Set flash mode. 1630 String flashMode = settingsManager.get(SettingsManager.SETTING_FLASH_MODE); 1631 List<String> supportedFlash = mParameters.getSupportedFlashModes(); 1632 if (CameraUtil.isSupported(flashMode, supportedFlash)) { 1633 mParameters.setFlashMode(flashMode); 1634 } else { 1635 flashMode = mParameters.getFlashMode(); 1636 if (flashMode == null) { 1637 flashMode = mActivity.getString( 1638 R.string.pref_camera_flashmode_no_flash); 1639 } 1640 } 1641 1642 // Set white balance parameter. 1643 String whiteBalance = settingsManager.get(SettingsManager.SETTING_WHITE_BALANCE); 1644 if (CameraUtil.isSupported(whiteBalance, 1645 mParameters.getSupportedWhiteBalance())) { 1646 mParameters.setWhiteBalance(whiteBalance); 1647 } else { 1648 whiteBalance = mParameters.getWhiteBalance(); 1649 if (whiteBalance == null) { 1650 whiteBalance = Parameters.WHITE_BALANCE_AUTO; 1651 } 1652 } 1653 1654 // Set focus mode. 1655 mFocusManager.overrideFocusMode(null); 1656 mParameters.setFocusMode(mFocusManager.getFocusMode()); 1657 } else { 1658 mFocusManager.overrideFocusMode(mParameters.getFocusMode()); 1659 } 1660 } 1661 1662 @TargetApi(Build.VERSION_CODES.JELLY_BEAN) 1663 private void updateAutoFocusMoveCallback() { 1664 if (mParameters.getFocusMode().equals(CameraUtil.FOCUS_MODE_CONTINUOUS_PICTURE)) { 1665 mCameraDevice.setAutoFocusMoveCallback(mHandler, 1666 (CameraAFMoveCallback) mAutoFocusMoveCallback); 1667 } else { 1668 mCameraDevice.setAutoFocusMoveCallback(null, null); 1669 } 1670 } 1671 1672 // We separate the parameters into several subsets, so we can update only 1673 // the subsets actually need updating. The PREFERENCE set needs extra 1674 // locking because the preference can be changed from GLThread as well. 1675 private void setCameraParameters(int updateSet) { 1676 if ((updateSet & UPDATE_PARAM_INITIALIZE) != 0) { 1677 updateCameraParametersInitialize(); 1678 } 1679 1680 if ((updateSet & UPDATE_PARAM_ZOOM) != 0) { 1681 updateCameraParametersZoom(); 1682 } 1683 1684 if ((updateSet & UPDATE_PARAM_PREFERENCE) != 0) { 1685 updateCameraParametersPreference(); 1686 } 1687 1688 mCameraDevice.setParameters(mParameters); 1689 } 1690 1691 // If the Camera is idle, update the parameters immediately, otherwise 1692 // accumulate them in mUpdateSet and update later. 1693 private void setCameraParametersWhenIdle(int additionalUpdateSet) { 1694 mUpdateSet |= additionalUpdateSet; 1695 if (mCameraDevice == null) { 1696 // We will update all the parameters when we open the device, so 1697 // we don't need to do anything now. 1698 mUpdateSet = 0; 1699 return; 1700 } else if (isCameraIdle()) { 1701 setCameraParameters(mUpdateSet); 1702 updateSceneMode(); 1703 mUpdateSet = 0; 1704 } else { 1705 if (!mHandler.hasMessages(MSG_SET_CAMERA_PARAMETERS_WHEN_IDLE)) { 1706 mHandler.sendEmptyMessageDelayed(MSG_SET_CAMERA_PARAMETERS_WHEN_IDLE, 1000); 1707 } 1708 } 1709 } 1710 1711 @Override 1712 public boolean isCameraIdle() { 1713 return (mCameraState == IDLE) || 1714 (mCameraState == PREVIEW_STOPPED) || 1715 ((mFocusManager != null) && mFocusManager.isFocusCompleted() 1716 && (mCameraState != SWITCHING_CAMERA)); 1717 } 1718 1719 @Override 1720 public boolean isImageCaptureIntent() { 1721 String action = mActivity.getIntent().getAction(); 1722 return (MediaStore.ACTION_IMAGE_CAPTURE.equals(action) 1723 || CameraActivity.ACTION_IMAGE_CAPTURE_SECURE.equals(action)); 1724 } 1725 1726 private void setupCaptureParams() { 1727 Bundle myExtras = mActivity.getIntent().getExtras(); 1728 if (myExtras != null) { 1729 mSaveUri = (Uri) myExtras.getParcelable(MediaStore.EXTRA_OUTPUT); 1730 mCropValue = myExtras.getString("crop"); 1731 } 1732 } 1733 1734 public void onSharedPreferenceChanged() { 1735 // ignore the events after "onPause()" 1736 if (mPaused) { 1737 return; 1738 } 1739 1740 SettingsController settingsController = mActivity.getSettingsController(); 1741 settingsController.syncLocationManager(); 1742 1743 setCameraParametersWhenIdle(UPDATE_PARAM_PREFERENCE); 1744 } 1745 1746 private void showTapToFocusToast() { 1747 // TODO: Use a toast? 1748 new RotateTextToast(mActivity, R.string.tap_to_focus, 0).show(); 1749 // Clear the preference. 1750 SettingsManager settingsManager = mActivity.getSettingsManager(); 1751 settingsManager.setBoolean( 1752 SettingsManager.SETTING_CAMERA_FIRST_USE_HINT_SHOWN, false); 1753 } 1754 1755 private void initializeCapabilities() { 1756 mInitialParams = mCameraDevice.getParameters(); 1757 mFocusAreaSupported = CameraUtil.isFocusAreaSupported(mInitialParams); 1758 mMeteringAreaSupported = CameraUtil.isMeteringAreaSupported(mInitialParams); 1759 mAeLockSupported = CameraUtil.isAutoExposureLockSupported(mInitialParams); 1760 mAwbLockSupported = CameraUtil.isAutoWhiteBalanceLockSupported(mInitialParams); 1761 mContinuousFocusSupported = mInitialParams.getSupportedFocusModes().contains( 1762 CameraUtil.FOCUS_MODE_CONTINUOUS_PICTURE); 1763 } 1764 1765 private void setShutterEnabled(boolean enabled) { 1766 mShutterEnabled = enabled; 1767 mUI.enableShutter(enabled); 1768 } 1769 1770 // TODO: Remove this 1771 @Override 1772 public int onZoomChanged(int index) { 1773 // Not useful to change zoom value when the activity is paused. 1774 if (mPaused) { 1775 return index; 1776 } 1777 mZoomValue = index; 1778 if (mParameters == null || mCameraDevice == null) { 1779 return index; 1780 } 1781 // Set zoom parameters asynchronously 1782 mParameters.setZoom(mZoomValue); 1783 mCameraDevice.setParameters(mParameters); 1784 Parameters p = mCameraDevice.getParameters(); 1785 if (p != null) { 1786 return p.getZoom(); 1787 } 1788 return index; 1789 } 1790 1791 @Override 1792 public int getCameraState() { 1793 return mCameraState; 1794 } 1795 1796 @Override 1797 public void onMemoryStateChanged(int state) { 1798 setShutterEnabled(state == MemoryManager.STATE_OK); 1799 } 1800 1801 @Override 1802 public void onLowMemory() { 1803 // Not much we can do in the photo module. 1804 } 1805 1806 @Override 1807 public void onAccuracyChanged(Sensor sensor, int accuracy) { 1808 } 1809 1810 @Override 1811 public void onSensorChanged(SensorEvent event) { 1812 int type = event.sensor.getType(); 1813 float[] data; 1814 if (type == Sensor.TYPE_ACCELEROMETER) { 1815 data = mGData; 1816 } else if (type == Sensor.TYPE_MAGNETIC_FIELD) { 1817 data = mMData; 1818 } else { 1819 // we should not be here. 1820 return; 1821 } 1822 for (int i = 0; i < 3; i++) { 1823 data[i] = event.values[i]; 1824 } 1825 float[] orientation = new float[3]; 1826 SensorManager.getRotationMatrix(mR, null, mGData, mMData); 1827 SensorManager.getOrientation(mR, orientation); 1828 mHeading = (int) (orientation[0] * 180f / Math.PI) % 360; 1829 if (mHeading < 0) { 1830 mHeading += 360; 1831 } 1832 } 1833 1834 // For debugging only. 1835 public void setDebugUri(Uri uri) { 1836 mDebugUri = uri; 1837 } 1838 1839 // For debugging only. 1840 private void saveToDebugUri(byte[] data) { 1841 if (mDebugUri != null) { 1842 OutputStream outputStream = null; 1843 try { 1844 outputStream = mContentResolver.openOutputStream(mDebugUri); 1845 outputStream.write(data); 1846 outputStream.close(); 1847 } catch (IOException e) { 1848 Log.e(TAG, "Exception while writing debug jpeg file", e); 1849 } finally { 1850 CameraUtil.closeSilently(outputStream); 1851 } 1852 } 1853 } 1854} 1855