1 /* 2 * Copyright (C) 2008 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 17 package android.hardware; 18 19 import static android.system.OsConstants.EACCES; 20 import static android.system.OsConstants.EBUSY; 21 import static android.system.OsConstants.EINVAL; 22 import static android.system.OsConstants.ENODEV; 23 import static android.system.OsConstants.ENOSYS; 24 import static android.system.OsConstants.EOPNOTSUPP; 25 import static android.system.OsConstants.EUSERS; 26 27 import android.annotation.Nullable; 28 import android.annotation.SdkConstant; 29 import android.annotation.SdkConstant.SdkConstantType; 30 import android.app.ActivityThread; 31 import android.app.AppOpsManager; 32 import android.compat.annotation.UnsupportedAppUsage; 33 import android.content.Context; 34 import android.graphics.ImageFormat; 35 import android.graphics.Point; 36 import android.graphics.Rect; 37 import android.graphics.SurfaceTexture; 38 import android.media.AudioAttributes; 39 import android.media.IAudioService; 40 import android.os.Build; 41 import android.os.Handler; 42 import android.os.IBinder; 43 import android.os.Looper; 44 import android.os.Message; 45 import android.os.Process; 46 import android.os.RemoteException; 47 import android.os.ServiceManager; 48 import android.renderscript.Allocation; 49 import android.renderscript.Element; 50 import android.renderscript.RSIllegalArgumentException; 51 import android.renderscript.RenderScript; 52 import android.renderscript.Type; 53 import android.text.TextUtils; 54 import android.util.Log; 55 import android.view.Surface; 56 import android.view.SurfaceHolder; 57 58 import com.android.internal.annotations.GuardedBy; 59 import com.android.internal.app.IAppOpsCallback; 60 import com.android.internal.app.IAppOpsService; 61 62 import java.io.IOException; 63 import java.lang.ref.WeakReference; 64 import java.util.ArrayList; 65 import java.util.LinkedHashMap; 66 import java.util.List; 67 68 /** 69 * The Camera class is used to set image capture settings, start/stop preview, 70 * snap pictures, and retrieve frames for encoding for video. This class is a 71 * client for the Camera service, which manages the actual camera hardware. 72 * 73 * <p>To access the device camera, you must declare the 74 * {@link android.Manifest.permission#CAMERA} permission in your Android 75 * Manifest. Also be sure to include the 76 * <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html"><uses-feature></a> 77 * manifest element to declare camera features used by your application. 78 * For example, if you use the camera and auto-focus feature, your Manifest 79 * should include the following:</p> 80 * <pre> <uses-permission android:name="android.permission.CAMERA" /> 81 * <uses-feature android:name="android.hardware.camera" /> 82 * <uses-feature android:name="android.hardware.camera.autofocus" /></pre> 83 * 84 * <p>To take pictures with this class, use the following steps:</p> 85 * 86 * <ol> 87 * <li>Obtain an instance of Camera from {@link #open(int)}. 88 * 89 * <li>Get existing (default) settings with {@link #getParameters()}. 90 * 91 * <li>If necessary, modify the returned {@link Camera.Parameters} object and call 92 * {@link #setParameters(Camera.Parameters)}. 93 * 94 * <li>Call {@link #setDisplayOrientation(int)} to ensure correct orientation of preview. 95 * 96 * <li><b>Important</b>: Pass a fully initialized {@link SurfaceHolder} to 97 * {@link #setPreviewDisplay(SurfaceHolder)}. Without a surface, the camera 98 * will be unable to start the preview. 99 * 100 * <li><b>Important</b>: Call {@link #startPreview()} to start updating the 101 * preview surface. Preview must be started before you can take a picture. 102 * 103 * <li>When you want, call {@link #takePicture(Camera.ShutterCallback, 104 * Camera.PictureCallback, Camera.PictureCallback, Camera.PictureCallback)} to 105 * capture a photo. Wait for the callbacks to provide the actual image data. 106 * 107 * <li>After taking a picture, preview display will have stopped. To take more 108 * photos, call {@link #startPreview()} again first. 109 * 110 * <li>Call {@link #stopPreview()} to stop updating the preview surface. 111 * 112 * <li><b>Important:</b> Call {@link #release()} to release the camera for 113 * use by other applications. Applications should release the camera 114 * immediately in {@link android.app.Activity#onPause()} (and re-{@link #open()} 115 * it in {@link android.app.Activity#onResume()}). 116 * </ol> 117 * 118 * <p>To quickly switch to video recording mode, use these steps:</p> 119 * 120 * <ol> 121 * <li>Obtain and initialize a Camera and start preview as described above. 122 * 123 * <li>Call {@link #unlock()} to allow the media process to access the camera. 124 * 125 * <li>Pass the camera to {@link android.media.MediaRecorder#setCamera(Camera)}. 126 * See {@link android.media.MediaRecorder} information about video recording. 127 * 128 * <li>When finished recording, call {@link #reconnect()} to re-acquire 129 * and re-lock the camera. 130 * 131 * <li>If desired, restart preview and take more photos or videos. 132 * 133 * <li>Call {@link #stopPreview()} and {@link #release()} as described above. 134 * </ol> 135 * 136 * <p>This class is not thread-safe, and is meant for use from one event thread. 137 * Most long-running operations (preview, focus, photo capture, etc) happen 138 * asynchronously and invoke callbacks as necessary. Callbacks will be invoked 139 * on the event thread {@link #open(int)} was called from. This class's methods 140 * must never be called from multiple threads at once.</p> 141 * 142 * <p class="caution"><strong>Caution:</strong> Different Android-powered devices 143 * may have different hardware specifications, such as megapixel ratings and 144 * auto-focus capabilities. In order for your application to be compatible with 145 * more devices, you should not make assumptions about the device camera 146 * specifications.</p> 147 * 148 * <div class="special reference"> 149 * <h3>Developer Guides</h3> 150 * <p>For more information about using cameras, read the 151 * <a href="{@docRoot}guide/topics/media/camera.html">Camera</a> developer guide.</p> 152 * </div> 153 * 154 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 155 * applications. 156 */ 157 @Deprecated 158 public class Camera { 159 private static final String TAG = "Camera"; 160 161 // These match the enums in frameworks/base/include/camera/Camera.h 162 private static final int CAMERA_MSG_ERROR = 0x001; 163 private static final int CAMERA_MSG_SHUTTER = 0x002; 164 private static final int CAMERA_MSG_FOCUS = 0x004; 165 private static final int CAMERA_MSG_ZOOM = 0x008; 166 private static final int CAMERA_MSG_PREVIEW_FRAME = 0x010; 167 private static final int CAMERA_MSG_VIDEO_FRAME = 0x020; 168 private static final int CAMERA_MSG_POSTVIEW_FRAME = 0x040; 169 private static final int CAMERA_MSG_RAW_IMAGE = 0x080; 170 private static final int CAMERA_MSG_COMPRESSED_IMAGE = 0x100; 171 private static final int CAMERA_MSG_RAW_IMAGE_NOTIFY = 0x200; 172 private static final int CAMERA_MSG_PREVIEW_METADATA = 0x400; 173 private static final int CAMERA_MSG_FOCUS_MOVE = 0x800; 174 175 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) 176 private long mNativeContext; // accessed by native methods 177 private EventHandler mEventHandler; 178 private ShutterCallback mShutterCallback; 179 private PictureCallback mRawImageCallback; 180 private PictureCallback mJpegCallback; 181 private PreviewCallback mPreviewCallback; 182 private boolean mUsingPreviewAllocation; 183 private PictureCallback mPostviewCallback; 184 private AutoFocusCallback mAutoFocusCallback; 185 private AutoFocusMoveCallback mAutoFocusMoveCallback; 186 private OnZoomChangeListener mZoomListener; 187 private FaceDetectionListener mFaceListener; 188 private ErrorCallback mErrorCallback; 189 private ErrorCallback mDetailedErrorCallback; 190 private boolean mOneShot; 191 private boolean mWithBuffer; 192 private boolean mFaceDetectionRunning = false; 193 private final Object mAutoFocusCallbackLock = new Object(); 194 195 private final Object mShutterSoundLock = new Object(); 196 // for AppOps 197 private @Nullable IAppOpsService mAppOps; 198 private IAppOpsCallback mAppOpsCallback; 199 @GuardedBy("mShutterSoundLock") 200 private boolean mHasAppOpsPlayAudio = true; 201 @GuardedBy("mShutterSoundLock") 202 private boolean mShutterSoundEnabledFromApp = true; 203 204 private static final int NO_ERROR = 0; 205 206 /** 207 * Broadcast Action: A new picture is taken by the camera, and the entry of 208 * the picture has been added to the media store. 209 * {@link android.content.Intent#getData} is URI of the picture. 210 * 211 * <p>In {@link android.os.Build.VERSION_CODES#N Android N} this broadcast was removed, and 212 * applications are recommended to use 213 * {@link android.app.job.JobInfo.Builder JobInfo.Builder}.{@link android.app.job.JobInfo.Builder#addTriggerContentUri} 214 * instead.</p> 215 * 216 * <p>In {@link android.os.Build.VERSION_CODES#O Android O} this broadcast has been brought 217 * back, but only for <em>registered</em> receivers. Apps that are actively running can 218 * again listen to the broadcast if they want an immediate clear signal about a picture 219 * being taken, however anything doing heavy work (or needing to be launched) as a result of 220 * this should still use JobScheduler.</p> 221 */ 222 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 223 public static final String ACTION_NEW_PICTURE = "android.hardware.action.NEW_PICTURE"; 224 225 /** 226 * Broadcast Action: A new video is recorded by the camera, and the entry 227 * of the video has been added to the media store. 228 * {@link android.content.Intent#getData} is URI of the video. 229 * 230 * <p>In {@link android.os.Build.VERSION_CODES#N Android N} this broadcast was removed, and 231 * applications are recommended to use 232 * {@link android.app.job.JobInfo.Builder JobInfo.Builder}.{@link android.app.job.JobInfo.Builder#addTriggerContentUri} 233 * instead.</p> 234 * 235 * <p>In {@link android.os.Build.VERSION_CODES#O Android O} this broadcast has been brought 236 * back, but only for <em>registered</em> receivers. Apps that are actively running can 237 * again listen to the broadcast if they want an immediate clear signal about a video 238 * being taken, however anything doing heavy work (or needing to be launched) as a result of 239 * this should still use JobScheduler.</p> 240 */ 241 @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) 242 public static final String ACTION_NEW_VIDEO = "android.hardware.action.NEW_VIDEO"; 243 244 /** 245 * Camera HAL device API version 1.0 246 * @hide 247 */ 248 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) 249 public static final int CAMERA_HAL_API_VERSION_1_0 = 0x100; 250 251 /** 252 * Camera HAL device API version 3.0 253 * @hide 254 */ 255 public static final int CAMERA_HAL_API_VERSION_3_0 = 0x300; 256 257 /** 258 * Hardware face detection. It does not use much CPU. 259 */ 260 private static final int CAMERA_FACE_DETECTION_HW = 0; 261 262 /** 263 * Software face detection. It uses some CPU. 264 */ 265 private static final int CAMERA_FACE_DETECTION_SW = 1; 266 267 /** 268 * Returns the number of physical cameras available on this device. 269 * The return value of this method might change dynamically if the device 270 * supports external cameras and an external camera is connected or 271 * disconnected. 272 * 273 * If there is a 274 * {@link android.hardware.camera2.CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES_LOGICAL_MULTI_CAMERA 275 * logical multi-camera} in the system, to maintain app backward compatibility, this method will 276 * only expose one camera per facing for all logical camera and physical camera groups. 277 * Use camera2 API to see all cameras. 278 * 279 * @return total number of accessible camera devices, or 0 if there are no 280 * cameras or an error was encountered enumerating them. 281 */ getNumberOfCameras()282 public native static int getNumberOfCameras(); 283 284 /** 285 * Returns the information about a particular camera. 286 * If {@link #getNumberOfCameras()} returns N, the valid id is 0 to N-1. 287 * 288 * @throws RuntimeException if an invalid ID is provided, or if there is an 289 * error retrieving the information (generally due to a hardware or other 290 * low-level failure). 291 */ getCameraInfo(int cameraId, CameraInfo cameraInfo)292 public static void getCameraInfo(int cameraId, CameraInfo cameraInfo) { 293 _getCameraInfo(cameraId, cameraInfo); 294 IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE); 295 IAudioService audioService = IAudioService.Stub.asInterface(b); 296 try { 297 if (audioService.isCameraSoundForced()) { 298 // Only set this when sound is forced; otherwise let native code 299 // decide. 300 cameraInfo.canDisableShutterSound = false; 301 } 302 } catch (RemoteException e) { 303 Log.e(TAG, "Audio service is unavailable for queries"); 304 } 305 } _getCameraInfo(int cameraId, CameraInfo cameraInfo)306 private native static void _getCameraInfo(int cameraId, CameraInfo cameraInfo); 307 308 /** 309 * Information about a camera 310 * 311 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 312 * applications. 313 */ 314 @Deprecated 315 public static class CameraInfo { 316 /** 317 * The facing of the camera is opposite to that of the screen. 318 */ 319 public static final int CAMERA_FACING_BACK = 0; 320 321 /** 322 * The facing of the camera is the same as that of the screen. 323 */ 324 public static final int CAMERA_FACING_FRONT = 1; 325 326 /** 327 * The direction that the camera faces. It should be 328 * CAMERA_FACING_BACK or CAMERA_FACING_FRONT. 329 */ 330 public int facing; 331 332 /** 333 * <p>The orientation of the camera image. The value is the angle that the 334 * camera image needs to be rotated clockwise so it shows correctly on 335 * the display in its natural orientation. It should be 0, 90, 180, or 270.</p> 336 * 337 * <p>For example, suppose a device has a naturally tall screen. The 338 * back-facing camera sensor is mounted in landscape. You are looking at 339 * the screen. If the top side of the camera sensor is aligned with the 340 * right edge of the screen in natural orientation, the value should be 341 * 90. If the top side of a front-facing camera sensor is aligned with 342 * the right of the screen, the value should be 270.</p> 343 * 344 * @see #setDisplayOrientation(int) 345 * @see Parameters#setRotation(int) 346 * @see Parameters#setPreviewSize(int, int) 347 * @see Parameters#setPictureSize(int, int) 348 * @see Parameters#setJpegThumbnailSize(int, int) 349 */ 350 public int orientation; 351 352 /** 353 * <p>Whether the shutter sound can be disabled.</p> 354 * 355 * <p>On some devices, the camera shutter sound cannot be turned off 356 * through {@link #enableShutterSound enableShutterSound}. This field 357 * can be used to determine whether a call to disable the shutter sound 358 * will succeed.</p> 359 * 360 * <p>If this field is set to true, then a call of 361 * {@code enableShutterSound(false)} will be successful. If set to 362 * false, then that call will fail, and the shutter sound will be played 363 * when {@link Camera#takePicture takePicture} is called.</p> 364 */ 365 public boolean canDisableShutterSound; 366 }; 367 368 /** 369 * Creates a new Camera object to access a particular hardware camera. If 370 * the same camera is opened by other applications, this will throw a 371 * RuntimeException. 372 * 373 * <p>You must call {@link #release()} when you are done using the camera, 374 * otherwise it will remain locked and be unavailable to other applications. 375 * 376 * <p>Your application should only have one Camera object active at a time 377 * for a particular hardware camera. 378 * 379 * <p>Callbacks from other methods are delivered to the event loop of the 380 * thread which called open(). If this thread has no event loop, then 381 * callbacks are delivered to the main application event loop. If there 382 * is no main application event loop, callbacks are not delivered. 383 * 384 * <p class="caution"><b>Caution:</b> On some devices, this method may 385 * take a long time to complete. It is best to call this method from a 386 * worker thread (possibly using {@link android.os.AsyncTask}) to avoid 387 * blocking the main application UI thread. 388 * 389 * @param cameraId the hardware camera to access, between 0 and 390 * {@link #getNumberOfCameras()}-1. 391 * @return a new Camera object, connected, locked and ready for use. 392 * @throws RuntimeException if opening the camera fails (for example, if the 393 * camera is in use by another process or device policy manager has 394 * disabled the camera). 395 * @see android.app.admin.DevicePolicyManager#getCameraDisabled(android.content.ComponentName) 396 */ open(int cameraId)397 public static Camera open(int cameraId) { 398 return new Camera(cameraId); 399 } 400 401 /** 402 * Creates a new Camera object to access the first back-facing camera on the 403 * device. If the device does not have a back-facing camera, this returns 404 * null. Otherwise acts like the {@link #open(int)} call. 405 * 406 * @return a new Camera object for the first back-facing camera, or null if there is no 407 * backfacing camera 408 * @see #open(int) 409 */ open()410 public static Camera open() { 411 int numberOfCameras = getNumberOfCameras(); 412 CameraInfo cameraInfo = new CameraInfo(); 413 for (int i = 0; i < numberOfCameras; i++) { 414 getCameraInfo(i, cameraInfo); 415 if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) { 416 return new Camera(i); 417 } 418 } 419 return null; 420 } 421 422 /** 423 * Creates a new Camera object to access a particular hardware camera with 424 * given hal API version. If the same camera is opened by other applications 425 * or the hal API version is not supported by this device, this will throw a 426 * RuntimeException. As of Android 12, HAL version 1 is no longer supported. 427 * <p> 428 * You must call {@link #release()} when you are done using the camera, 429 * otherwise it will remain locked and be unavailable to other applications. 430 * <p> 431 * Your application should only have one Camera object active at a time for 432 * a particular hardware camera. 433 * <p> 434 * Callbacks from other methods are delivered to the event loop of the 435 * thread which called open(). If this thread has no event loop, then 436 * callbacks are delivered to the main application event loop. If there is 437 * no main application event loop, callbacks are not delivered. 438 * <p class="caution"> 439 * <b>Caution:</b> On some devices, this method may take a long time to 440 * complete. It is best to call this method from a worker thread (possibly 441 * using {@link android.os.AsyncTask}) to avoid blocking the main 442 * application UI thread. 443 * 444 * @param cameraId The hardware camera to access, between 0 and 445 * {@link #getNumberOfCameras()}-1. 446 * @param halVersion The HAL API version this camera device to be opened as. 447 * @return a new Camera object, connected, locked and ready for use. 448 * 449 * @throws IllegalArgumentException if the {@code halVersion} is invalid 450 * 451 * @throws RuntimeException if opening the camera fails (for example, if the 452 * camera is in use by another process or device policy manager has disabled 453 * the camera). 454 * 455 * @see android.app.admin.DevicePolicyManager#getCameraDisabled(android.content.ComponentName) 456 * @see #CAMERA_HAL_API_VERSION_1_0 457 * 458 * @hide 459 */ 460 @UnsupportedAppUsage openLegacy(int cameraId, int halVersion)461 public static Camera openLegacy(int cameraId, int halVersion) { 462 if (halVersion < CAMERA_HAL_API_VERSION_3_0) { 463 throw new IllegalArgumentException("Unsupported HAL version " + halVersion); 464 } 465 466 return new Camera(cameraId); 467 } 468 cameraInit(int cameraId)469 private int cameraInit(int cameraId) { 470 mShutterCallback = null; 471 mRawImageCallback = null; 472 mJpegCallback = null; 473 mPreviewCallback = null; 474 mPostviewCallback = null; 475 mUsingPreviewAllocation = false; 476 mZoomListener = null; 477 478 Looper looper; 479 if ((looper = Looper.myLooper()) != null) { 480 mEventHandler = new EventHandler(this, looper); 481 } else if ((looper = Looper.getMainLooper()) != null) { 482 mEventHandler = new EventHandler(this, looper); 483 } else { 484 mEventHandler = null; 485 } 486 487 return native_setup(new WeakReference<Camera>(this), cameraId, 488 ActivityThread.currentOpPackageName()); 489 } 490 491 /** used by Camera#open, Camera#open(int) */ Camera(int cameraId)492 Camera(int cameraId) { 493 int err = cameraInit(cameraId); 494 if (checkInitErrors(err)) { 495 if (err == -EACCES) { 496 throw new RuntimeException("Fail to connect to camera service"); 497 } else if (err == -ENODEV) { 498 throw new RuntimeException("Camera initialization failed"); 499 } 500 // Should never hit this. 501 throw new RuntimeException("Unknown camera error"); 502 } 503 initAppOps(); 504 } 505 506 507 /** 508 * @hide 509 */ checkInitErrors(int err)510 public static boolean checkInitErrors(int err) { 511 return err != NO_ERROR; 512 } 513 514 /** 515 * @hide 516 */ openUninitialized()517 public static Camera openUninitialized() { 518 return new Camera(); 519 } 520 521 /** 522 * An empty Camera for testing purpose. 523 */ Camera()524 Camera() {} 525 initAppOps()526 private void initAppOps() { 527 IBinder b = ServiceManager.getService(Context.APP_OPS_SERVICE); 528 mAppOps = IAppOpsService.Stub.asInterface(b); 529 // initialize mHasAppOpsPlayAudio 530 updateAppOpsPlayAudio(); 531 // register a callback to monitor whether the OP_PLAY_AUDIO is still allowed 532 mAppOpsCallback = new IAppOpsCallbackWrapper(this); 533 try { 534 mAppOps.startWatchingMode(AppOpsManager.OP_PLAY_AUDIO, 535 ActivityThread.currentPackageName(), mAppOpsCallback); 536 } catch (RemoteException e) { 537 Log.e(TAG, "Error registering appOps callback", e); 538 mHasAppOpsPlayAudio = false; 539 } 540 } 541 releaseAppOps()542 private void releaseAppOps() { 543 try { 544 if (mAppOps != null) { 545 mAppOps.stopWatchingMode(mAppOpsCallback); 546 } 547 } catch (Exception e) { 548 // nothing to do here, the object is supposed to be released anyway 549 } 550 } 551 552 @Override finalize()553 protected void finalize() { 554 release(); 555 } 556 557 @UnsupportedAppUsage native_setup(Object cameraThis, int cameraId, String packageName)558 private native int native_setup(Object cameraThis, int cameraId, String packageName); 559 native_release()560 private native final void native_release(); 561 562 563 /** 564 * Disconnects and releases the Camera object resources. 565 * 566 * <p>You must call this as soon as you're done with the Camera object.</p> 567 */ release()568 public final void release() { 569 native_release(); 570 mFaceDetectionRunning = false; 571 releaseAppOps(); 572 } 573 574 /** 575 * Unlocks the camera to allow another process to access it. 576 * Normally, the camera is locked to the process with an active Camera 577 * object until {@link #release()} is called. To allow rapid handoff 578 * between processes, you can call this method to release the camera 579 * temporarily for another process to use; once the other process is done 580 * you can call {@link #reconnect()} to reclaim the camera. 581 * 582 * <p>This must be done before calling 583 * {@link android.media.MediaRecorder#setCamera(Camera)}. This cannot be 584 * called after recording starts. 585 * 586 * <p>If you are not recording video, you probably do not need this method. 587 * 588 * @throws RuntimeException if the camera cannot be unlocked. 589 */ unlock()590 public native final void unlock(); 591 592 /** 593 * Re-locks the camera to prevent other processes from accessing it. 594 * Camera objects are locked by default unless {@link #unlock()} is 595 * called. Normally {@link #reconnect()} is used instead. 596 * 597 * <p>Since API level 14, camera is automatically locked for applications in 598 * {@link android.media.MediaRecorder#start()}. Applications can use the 599 * camera (ex: zoom) after recording starts. There is no need to call this 600 * after recording starts or stops. 601 * 602 * <p>If you are not recording video, you probably do not need this method. 603 * 604 * @throws RuntimeException if the camera cannot be re-locked (for 605 * example, if the camera is still in use by another process). 606 */ lock()607 public native final void lock(); 608 609 /** 610 * Reconnects to the camera service after another process used it. 611 * After {@link #unlock()} is called, another process may use the 612 * camera; when the process is done, you must reconnect to the camera, 613 * which will re-acquire the lock and allow you to continue using the 614 * camera. 615 * 616 * <p>Since API level 14, camera is automatically locked for applications in 617 * {@link android.media.MediaRecorder#start()}. Applications can use the 618 * camera (ex: zoom) after recording starts. There is no need to call this 619 * after recording starts or stops. 620 * 621 * <p>If you are not recording video, you probably do not need this method. 622 * 623 * @throws IOException if a connection cannot be re-established (for 624 * example, if the camera is still in use by another process). 625 * @throws RuntimeException if release() has been called on this Camera 626 * instance. 627 */ reconnect()628 public native final void reconnect() throws IOException; 629 630 /** 631 * Sets the {@link Surface} to be used for live preview. 632 * Either a surface or surface texture is necessary for preview, and 633 * preview is necessary to take pictures. The same surface can be re-set 634 * without harm. Setting a preview surface will un-set any preview surface 635 * texture that was set via {@link #setPreviewTexture}. 636 * 637 * <p>The {@link SurfaceHolder} must already contain a surface when this 638 * method is called. If you are using {@link android.view.SurfaceView}, 639 * you will need to register a {@link SurfaceHolder.Callback} with 640 * {@link SurfaceHolder#addCallback(SurfaceHolder.Callback)} and wait for 641 * {@link SurfaceHolder.Callback#surfaceCreated(SurfaceHolder)} before 642 * calling setPreviewDisplay() or starting preview. 643 * 644 * <p>This method must be called before {@link #startPreview()}. The 645 * one exception is that if the preview surface is not set (or set to null) 646 * before startPreview() is called, then this method may be called once 647 * with a non-null parameter to set the preview surface. (This allows 648 * camera setup and surface creation to happen in parallel, saving time.) 649 * The preview surface may not otherwise change while preview is running. 650 * 651 * @param holder containing the Surface on which to place the preview, 652 * or null to remove the preview surface 653 * @throws IOException if the method fails (for example, if the surface 654 * is unavailable or unsuitable). 655 * @throws RuntimeException if release() has been called on this Camera 656 * instance. 657 */ setPreviewDisplay(SurfaceHolder holder)658 public final void setPreviewDisplay(SurfaceHolder holder) throws IOException { 659 if (holder != null) { 660 setPreviewSurface(holder.getSurface()); 661 } else { 662 setPreviewSurface((Surface)null); 663 } 664 } 665 666 /** 667 * @hide 668 */ 669 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) setPreviewSurface(Surface surface)670 public native final void setPreviewSurface(Surface surface) throws IOException; 671 672 /** 673 * Sets the {@link SurfaceTexture} to be used for live preview. 674 * Either a surface or surface texture is necessary for preview, and 675 * preview is necessary to take pictures. The same surface texture can be 676 * re-set without harm. Setting a preview surface texture will un-set any 677 * preview surface that was set via {@link #setPreviewDisplay}. 678 * 679 * <p>This method must be called before {@link #startPreview()}. The 680 * one exception is that if the preview surface texture is not set (or set 681 * to null) before startPreview() is called, then this method may be called 682 * once with a non-null parameter to set the preview surface. (This allows 683 * camera setup and surface creation to happen in parallel, saving time.) 684 * The preview surface texture may not otherwise change while preview is 685 * running. 686 * 687 * <p>The timestamps provided by {@link SurfaceTexture#getTimestamp()} for a 688 * SurfaceTexture set as the preview texture have an unspecified zero point, 689 * and cannot be directly compared between different cameras or different 690 * instances of the same camera, or across multiple runs of the same 691 * program. 692 * 693 * <p>If you are using the preview data to create video or still images, 694 * strongly consider using {@link android.media.MediaActionSound} to 695 * properly indicate image capture or recording start/stop to the user.</p> 696 * 697 * @see android.media.MediaActionSound 698 * @see android.graphics.SurfaceTexture 699 * @see android.view.TextureView 700 * @param surfaceTexture the {@link SurfaceTexture} to which the preview 701 * images are to be sent or null to remove the current preview surface 702 * texture 703 * @throws IOException if the method fails (for example, if the surface 704 * texture is unavailable or unsuitable). 705 * @throws RuntimeException if release() has been called on this Camera 706 * instance. 707 */ setPreviewTexture(SurfaceTexture surfaceTexture)708 public native final void setPreviewTexture(SurfaceTexture surfaceTexture) throws IOException; 709 710 /** 711 * Callback interface used to deliver copies of preview frames as 712 * they are displayed. 713 * 714 * @see #setPreviewCallback(Camera.PreviewCallback) 715 * @see #setOneShotPreviewCallback(Camera.PreviewCallback) 716 * @see #setPreviewCallbackWithBuffer(Camera.PreviewCallback) 717 * @see #startPreview() 718 * 719 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 720 * applications. 721 */ 722 @Deprecated 723 public interface PreviewCallback 724 { 725 /** 726 * Called as preview frames are displayed. This callback is invoked 727 * on the event thread {@link #open(int)} was called from. 728 * 729 * <p>If using the {@link android.graphics.ImageFormat#YV12} format, 730 * refer to the equations in {@link Camera.Parameters#setPreviewFormat} 731 * for the arrangement of the pixel data in the preview callback 732 * buffers. 733 * 734 * @param data the contents of the preview frame in the format defined 735 * by {@link android.graphics.ImageFormat}, which can be queried 736 * with {@link android.hardware.Camera.Parameters#getPreviewFormat()}. 737 * If {@link android.hardware.Camera.Parameters#setPreviewFormat(int)} 738 * is never called, the default will be the YCbCr_420_SP 739 * (NV21) format. 740 * @param camera the Camera service object. 741 */ onPreviewFrame(byte[] data, Camera camera)742 void onPreviewFrame(byte[] data, Camera camera); 743 }; 744 745 /** 746 * Starts capturing and drawing preview frames to the screen. 747 * Preview will not actually start until a surface is supplied 748 * with {@link #setPreviewDisplay(SurfaceHolder)} or 749 * {@link #setPreviewTexture(SurfaceTexture)}. 750 * 751 * <p>If {@link #setPreviewCallback(Camera.PreviewCallback)}, 752 * {@link #setOneShotPreviewCallback(Camera.PreviewCallback)}, or 753 * {@link #setPreviewCallbackWithBuffer(Camera.PreviewCallback)} were 754 * called, {@link Camera.PreviewCallback#onPreviewFrame(byte[], Camera)} 755 * will be called when preview data becomes available. 756 * 757 * @throws RuntimeException if starting preview fails; usually this would be 758 * because of a hardware or other low-level error, or because release() 759 * has been called on this Camera instance. The QCIF (176x144) exception 760 * mentioned in {@link Parameters#setPreviewSize setPreviewSize} and 761 * {@link Parameters#setPictureSize setPictureSize} can also cause this 762 * exception be thrown. 763 */ startPreview()764 public native final void startPreview(); 765 766 /** 767 * Stops capturing and drawing preview frames to the surface, and 768 * resets the camera for a future call to {@link #startPreview()}. 769 * 770 * @throws RuntimeException if stopping preview fails; usually this would be 771 * because of a hardware or other low-level error, or because release() 772 * has been called on this Camera instance. 773 */ stopPreview()774 public final void stopPreview() { 775 _stopPreview(); 776 mFaceDetectionRunning = false; 777 778 mShutterCallback = null; 779 mRawImageCallback = null; 780 mPostviewCallback = null; 781 mJpegCallback = null; 782 synchronized (mAutoFocusCallbackLock) { 783 mAutoFocusCallback = null; 784 } 785 mAutoFocusMoveCallback = null; 786 } 787 _stopPreview()788 private native final void _stopPreview(); 789 790 /** 791 * Return current preview state. 792 * 793 * FIXME: Unhide before release 794 * @hide 795 */ 796 @UnsupportedAppUsage previewEnabled()797 public native final boolean previewEnabled(); 798 799 /** 800 * <p>Installs a callback to be invoked for every preview frame in addition 801 * to displaying them on the screen. The callback will be repeatedly called 802 * for as long as preview is active. This method can be called at any time, 803 * even while preview is live. Any other preview callbacks are 804 * overridden.</p> 805 * 806 * <p>If you are using the preview data to create video or still images, 807 * strongly consider using {@link android.media.MediaActionSound} to 808 * properly indicate image capture or recording start/stop to the user.</p> 809 * 810 * @param cb a callback object that receives a copy of each preview frame, 811 * or null to stop receiving callbacks. 812 * @throws RuntimeException if release() has been called on this Camera 813 * instance. 814 * @see android.media.MediaActionSound 815 */ setPreviewCallback(PreviewCallback cb)816 public final void setPreviewCallback(PreviewCallback cb) { 817 mPreviewCallback = cb; 818 mOneShot = false; 819 mWithBuffer = false; 820 if (cb != null) { 821 mUsingPreviewAllocation = false; 822 } 823 // Always use one-shot mode. We fake camera preview mode by 824 // doing one-shot preview continuously. 825 setHasPreviewCallback(cb != null, false); 826 } 827 828 /** 829 * <p>Installs a callback to be invoked for the next preview frame in 830 * addition to displaying it on the screen. After one invocation, the 831 * callback is cleared. This method can be called any time, even when 832 * preview is live. Any other preview callbacks are overridden.</p> 833 * 834 * <p>If you are using the preview data to create video or still images, 835 * strongly consider using {@link android.media.MediaActionSound} to 836 * properly indicate image capture or recording start/stop to the user.</p> 837 * 838 * @param cb a callback object that receives a copy of the next preview frame, 839 * or null to stop receiving callbacks. 840 * @throws RuntimeException if release() has been called on this Camera 841 * instance. 842 * @see android.media.MediaActionSound 843 */ setOneShotPreviewCallback(PreviewCallback cb)844 public final void setOneShotPreviewCallback(PreviewCallback cb) { 845 mPreviewCallback = cb; 846 mOneShot = true; 847 mWithBuffer = false; 848 if (cb != null) { 849 mUsingPreviewAllocation = false; 850 } 851 setHasPreviewCallback(cb != null, false); 852 } 853 setHasPreviewCallback(boolean installed, boolean manualBuffer)854 private native final void setHasPreviewCallback(boolean installed, boolean manualBuffer); 855 856 /** 857 * <p>Installs a callback to be invoked for every preview frame, using 858 * buffers supplied with {@link #addCallbackBuffer(byte[])}, in addition to 859 * displaying them on the screen. The callback will be repeatedly called 860 * for as long as preview is active and buffers are available. Any other 861 * preview callbacks are overridden.</p> 862 * 863 * <p>The purpose of this method is to improve preview efficiency and frame 864 * rate by allowing preview frame memory reuse. You must call 865 * {@link #addCallbackBuffer(byte[])} at some point -- before or after 866 * calling this method -- or no callbacks will received.</p> 867 * 868 * <p>The buffer queue will be cleared if this method is called with a null 869 * callback, {@link #setPreviewCallback(Camera.PreviewCallback)} is called, 870 * or {@link #setOneShotPreviewCallback(Camera.PreviewCallback)} is 871 * called.</p> 872 * 873 * <p>If you are using the preview data to create video or still images, 874 * strongly consider using {@link android.media.MediaActionSound} to 875 * properly indicate image capture or recording start/stop to the user.</p> 876 * 877 * @param cb a callback object that receives a copy of the preview frame, 878 * or null to stop receiving callbacks and clear the buffer queue. 879 * @throws RuntimeException if release() has been called on this Camera 880 * instance. 881 * @see #addCallbackBuffer(byte[]) 882 * @see android.media.MediaActionSound 883 */ setPreviewCallbackWithBuffer(PreviewCallback cb)884 public final void setPreviewCallbackWithBuffer(PreviewCallback cb) { 885 mPreviewCallback = cb; 886 mOneShot = false; 887 mWithBuffer = true; 888 if (cb != null) { 889 mUsingPreviewAllocation = false; 890 } 891 setHasPreviewCallback(cb != null, true); 892 } 893 894 /** 895 * Adds a pre-allocated buffer to the preview callback buffer queue. 896 * Applications can add one or more buffers to the queue. When a preview 897 * frame arrives and there is still at least one available buffer, the 898 * buffer will be used and removed from the queue. Then preview callback is 899 * invoked with the buffer. If a frame arrives and there is no buffer left, 900 * the frame is discarded. Applications should add buffers back when they 901 * finish processing the data in them. 902 * 903 * <p>For formats besides YV12, the size of the buffer is determined by 904 * multiplying the preview image width, height, and bytes per pixel. The 905 * width and height can be read from 906 * {@link Camera.Parameters#getPreviewSize()}. Bytes per pixel can be 907 * computed from {@link android.graphics.ImageFormat#getBitsPerPixel(int)} / 908 * 8, using the image format from 909 * {@link Camera.Parameters#getPreviewFormat()}. 910 * 911 * <p>If using the {@link android.graphics.ImageFormat#YV12} format, the 912 * size can be calculated using the equations listed in 913 * {@link Camera.Parameters#setPreviewFormat}. 914 * 915 * <p>This method is only necessary when 916 * {@link #setPreviewCallbackWithBuffer(PreviewCallback)} is used. When 917 * {@link #setPreviewCallback(PreviewCallback)} or 918 * {@link #setOneShotPreviewCallback(PreviewCallback)} are used, buffers 919 * are automatically allocated. When a supplied buffer is too small to 920 * hold the preview frame data, preview callback will return null and 921 * the buffer will be removed from the buffer queue. 922 * 923 * @param callbackBuffer the buffer to add to the queue. The size of the 924 * buffer must match the values described above. 925 * @see #setPreviewCallbackWithBuffer(PreviewCallback) 926 */ addCallbackBuffer(byte[] callbackBuffer)927 public final void addCallbackBuffer(byte[] callbackBuffer) 928 { 929 _addCallbackBuffer(callbackBuffer, CAMERA_MSG_PREVIEW_FRAME); 930 } 931 932 /** 933 * Adds a pre-allocated buffer to the raw image callback buffer queue. 934 * Applications can add one or more buffers to the queue. When a raw image 935 * frame arrives and there is still at least one available buffer, the 936 * buffer will be used to hold the raw image data and removed from the 937 * queue. Then raw image callback is invoked with the buffer. If a raw 938 * image frame arrives but there is no buffer left, the frame is 939 * discarded. Applications should add buffers back when they finish 940 * processing the data in them by calling this method again in order 941 * to avoid running out of raw image callback buffers. 942 * 943 * <p>The size of the buffer is determined by multiplying the raw image 944 * width, height, and bytes per pixel. The width and height can be 945 * read from {@link Camera.Parameters#getPictureSize()}. Bytes per pixel 946 * can be computed from 947 * {@link android.graphics.ImageFormat#getBitsPerPixel(int)} / 8, 948 * using the image format from {@link Camera.Parameters#getPreviewFormat()}. 949 * 950 * <p>This method is only necessary when the PictureCallbck for raw image 951 * is used while calling {@link #takePicture(Camera.ShutterCallback, 952 * Camera.PictureCallback, Camera.PictureCallback, Camera.PictureCallback)}. 953 * 954 * <p>Please note that by calling this method, the mode for 955 * application-managed callback buffers is triggered. If this method has 956 * never been called, null will be returned by the raw image callback since 957 * there is no image callback buffer available. Furthermore, When a supplied 958 * buffer is too small to hold the raw image data, raw image callback will 959 * return null and the buffer will be removed from the buffer queue. 960 * 961 * @param callbackBuffer the buffer to add to the raw image callback buffer 962 * queue. The size should be width * height * (bits per pixel) / 8. An 963 * null callbackBuffer will be ignored and won't be added to the queue. 964 * 965 * @see #takePicture(Camera.ShutterCallback, 966 * Camera.PictureCallback, Camera.PictureCallback, Camera.PictureCallback)}. 967 * 968 * {@hide} 969 */ 970 @UnsupportedAppUsage addRawImageCallbackBuffer(byte[] callbackBuffer)971 public final void addRawImageCallbackBuffer(byte[] callbackBuffer) 972 { 973 addCallbackBuffer(callbackBuffer, CAMERA_MSG_RAW_IMAGE); 974 } 975 976 @UnsupportedAppUsage addCallbackBuffer(byte[] callbackBuffer, int msgType)977 private final void addCallbackBuffer(byte[] callbackBuffer, int msgType) 978 { 979 // CAMERA_MSG_VIDEO_FRAME may be allowed in the future. 980 if (msgType != CAMERA_MSG_PREVIEW_FRAME && 981 msgType != CAMERA_MSG_RAW_IMAGE) { 982 throw new IllegalArgumentException( 983 "Unsupported message type: " + msgType); 984 } 985 986 _addCallbackBuffer(callbackBuffer, msgType); 987 } 988 _addCallbackBuffer( byte[] callbackBuffer, int msgType)989 private native final void _addCallbackBuffer( 990 byte[] callbackBuffer, int msgType); 991 992 /** 993 * <p>Create a {@link android.renderscript RenderScript} 994 * {@link android.renderscript.Allocation Allocation} to use as a 995 * destination of preview callback frames. Use 996 * {@link #setPreviewCallbackAllocation setPreviewCallbackAllocation} to use 997 * the created Allocation as a destination for camera preview frames.</p> 998 * 999 * <p>The Allocation will be created with a YUV type, and its contents must 1000 * be accessed within Renderscript with the {@code rsGetElementAtYuv_*} 1001 * accessor methods. Its size will be based on the current 1002 * {@link Parameters#getPreviewSize preview size} configured for this 1003 * camera.</p> 1004 * 1005 * @param rs the RenderScript context for this Allocation. 1006 * @param usage additional usage flags to set for the Allocation. The usage 1007 * flag {@link android.renderscript.Allocation#USAGE_IO_INPUT} will always 1008 * be set on the created Allocation, but additional flags may be provided 1009 * here. 1010 * @return a new YUV-type Allocation with dimensions equal to the current 1011 * preview size. 1012 * @throws RSIllegalArgumentException if the usage flags are not compatible 1013 * with an YUV Allocation. 1014 * @see #setPreviewCallbackAllocation 1015 * @hide 1016 */ createPreviewAllocation(RenderScript rs, int usage)1017 public final Allocation createPreviewAllocation(RenderScript rs, int usage) 1018 throws RSIllegalArgumentException { 1019 Parameters p = getParameters(); 1020 Size previewSize = p.getPreviewSize(); 1021 Type.Builder yuvBuilder = new Type.Builder(rs, 1022 Element.createPixel(rs, 1023 Element.DataType.UNSIGNED_8, 1024 Element.DataKind.PIXEL_YUV)); 1025 // Use YV12 for wide compatibility. Changing this requires also 1026 // adjusting camera service's format selection. 1027 yuvBuilder.setYuvFormat(ImageFormat.YV12); 1028 yuvBuilder.setX(previewSize.width); 1029 yuvBuilder.setY(previewSize.height); 1030 1031 Allocation a = Allocation.createTyped(rs, yuvBuilder.create(), 1032 usage | Allocation.USAGE_IO_INPUT); 1033 1034 return a; 1035 } 1036 1037 /** 1038 * <p>Set an {@link android.renderscript.Allocation Allocation} as the 1039 * target of preview callback data. Use this method for efficient processing 1040 * of camera preview data with RenderScript. The Allocation must be created 1041 * with the {@link #createPreviewAllocation createPreviewAllocation } 1042 * method.</p> 1043 * 1044 * <p>Setting a preview allocation will disable any active preview callbacks 1045 * set by {@link #setPreviewCallback setPreviewCallback} or 1046 * {@link #setPreviewCallbackWithBuffer setPreviewCallbackWithBuffer}, and 1047 * vice versa. Using a preview allocation still requires an active standard 1048 * preview target to be set, either with 1049 * {@link #setPreviewTexture setPreviewTexture} or 1050 * {@link #setPreviewDisplay setPreviewDisplay}.</p> 1051 * 1052 * <p>To be notified when new frames are available to the Allocation, use 1053 * {@link android.renderscript.Allocation#setIoInputNotificationHandler Allocation.setIoInputNotificationHandler}. To 1054 * update the frame currently accessible from the Allocation to the latest 1055 * preview frame, call 1056 * {@link android.renderscript.Allocation#ioReceive Allocation.ioReceive}.</p> 1057 * 1058 * <p>To disable preview into the Allocation, call this method with a 1059 * {@code null} parameter.</p> 1060 * 1061 * <p>Once a preview allocation is set, the preview size set by 1062 * {@link Parameters#setPreviewSize setPreviewSize} cannot be changed. If 1063 * you wish to change the preview size, first remove the preview allocation 1064 * by calling {@code setPreviewCallbackAllocation(null)}, then change the 1065 * preview size, create a new preview Allocation with 1066 * {@link #createPreviewAllocation createPreviewAllocation}, and set it as 1067 * the new preview callback allocation target.</p> 1068 * 1069 * <p>If you are using the preview data to create video or still images, 1070 * strongly consider using {@link android.media.MediaActionSound} to 1071 * properly indicate image capture or recording start/stop to the user.</p> 1072 * 1073 * @param previewAllocation the allocation to use as destination for preview 1074 * @throws IOException if configuring the camera to use the Allocation for 1075 * preview fails. 1076 * @throws IllegalArgumentException if the Allocation's dimensions or other 1077 * parameters don't meet the requirements. 1078 * @see #createPreviewAllocation 1079 * @see #setPreviewCallback 1080 * @see #setPreviewCallbackWithBuffer 1081 * @hide 1082 */ setPreviewCallbackAllocation(Allocation previewAllocation)1083 public final void setPreviewCallbackAllocation(Allocation previewAllocation) 1084 throws IOException { 1085 Surface previewSurface = null; 1086 if (previewAllocation != null) { 1087 Parameters p = getParameters(); 1088 Size previewSize = p.getPreviewSize(); 1089 if (previewSize.width != previewAllocation.getType().getX() || 1090 previewSize.height != previewAllocation.getType().getY()) { 1091 throw new IllegalArgumentException( 1092 "Allocation dimensions don't match preview dimensions: " + 1093 "Allocation is " + 1094 previewAllocation.getType().getX() + 1095 ", " + 1096 previewAllocation.getType().getY() + 1097 ". Preview is " + previewSize.width + ", " + 1098 previewSize.height); 1099 } 1100 if ((previewAllocation.getUsage() & 1101 Allocation.USAGE_IO_INPUT) == 0) { 1102 throw new IllegalArgumentException( 1103 "Allocation usage does not include USAGE_IO_INPUT"); 1104 } 1105 if (previewAllocation.getType().getElement().getDataKind() != 1106 Element.DataKind.PIXEL_YUV) { 1107 throw new IllegalArgumentException( 1108 "Allocation is not of a YUV type"); 1109 } 1110 previewSurface = previewAllocation.getSurface(); 1111 mUsingPreviewAllocation = true; 1112 } else { 1113 mUsingPreviewAllocation = false; 1114 } 1115 setPreviewCallbackSurface(previewSurface); 1116 } 1117 setPreviewCallbackSurface(Surface s)1118 private native final void setPreviewCallbackSurface(Surface s); 1119 1120 private class EventHandler extends Handler 1121 { 1122 private final Camera mCamera; 1123 1124 @UnsupportedAppUsage EventHandler(Camera c, Looper looper)1125 public EventHandler(Camera c, Looper looper) { 1126 super(looper); 1127 mCamera = c; 1128 } 1129 1130 @Override handleMessage(Message msg)1131 public void handleMessage(Message msg) { 1132 switch(msg.what) { 1133 case CAMERA_MSG_SHUTTER: 1134 if (mShutterCallback != null) { 1135 mShutterCallback.onShutter(); 1136 } 1137 return; 1138 1139 case CAMERA_MSG_RAW_IMAGE: 1140 if (mRawImageCallback != null) { 1141 mRawImageCallback.onPictureTaken((byte[])msg.obj, mCamera); 1142 } 1143 return; 1144 1145 case CAMERA_MSG_COMPRESSED_IMAGE: 1146 if (mJpegCallback != null) { 1147 mJpegCallback.onPictureTaken((byte[])msg.obj, mCamera); 1148 } 1149 return; 1150 1151 case CAMERA_MSG_PREVIEW_FRAME: 1152 PreviewCallback pCb = mPreviewCallback; 1153 if (pCb != null) { 1154 if (mOneShot) { 1155 // Clear the callback variable before the callback 1156 // in case the app calls setPreviewCallback from 1157 // the callback function 1158 mPreviewCallback = null; 1159 } else if (!mWithBuffer) { 1160 // We're faking the camera preview mode to prevent 1161 // the app from being flooded with preview frames. 1162 // Set to oneshot mode again. 1163 setHasPreviewCallback(true, false); 1164 } 1165 pCb.onPreviewFrame((byte[])msg.obj, mCamera); 1166 } 1167 return; 1168 1169 case CAMERA_MSG_POSTVIEW_FRAME: 1170 if (mPostviewCallback != null) { 1171 mPostviewCallback.onPictureTaken((byte[])msg.obj, mCamera); 1172 } 1173 return; 1174 1175 case CAMERA_MSG_FOCUS: 1176 AutoFocusCallback cb = null; 1177 synchronized (mAutoFocusCallbackLock) { 1178 cb = mAutoFocusCallback; 1179 } 1180 if (cb != null) { 1181 boolean success = msg.arg1 == 0 ? false : true; 1182 cb.onAutoFocus(success, mCamera); 1183 } 1184 return; 1185 1186 case CAMERA_MSG_ZOOM: 1187 if (mZoomListener != null) { 1188 mZoomListener.onZoomChange(msg.arg1, msg.arg2 != 0, mCamera); 1189 } 1190 return; 1191 1192 case CAMERA_MSG_PREVIEW_METADATA: 1193 if (mFaceListener != null) { 1194 mFaceListener.onFaceDetection((Face[])msg.obj, mCamera); 1195 } 1196 return; 1197 1198 case CAMERA_MSG_ERROR : 1199 Log.e(TAG, "Error " + msg.arg1); 1200 if (mDetailedErrorCallback != null) { 1201 mDetailedErrorCallback.onError(msg.arg1, mCamera); 1202 } else if (mErrorCallback != null) { 1203 if (msg.arg1 == CAMERA_ERROR_DISABLED) { 1204 mErrorCallback.onError(CAMERA_ERROR_EVICTED, mCamera); 1205 } else { 1206 mErrorCallback.onError(msg.arg1, mCamera); 1207 } 1208 } 1209 return; 1210 1211 case CAMERA_MSG_FOCUS_MOVE: 1212 if (mAutoFocusMoveCallback != null) { 1213 mAutoFocusMoveCallback.onAutoFocusMoving(msg.arg1 == 0 ? false : true, mCamera); 1214 } 1215 return; 1216 1217 default: 1218 Log.e(TAG, "Unknown message type " + msg.what); 1219 return; 1220 } 1221 } 1222 } 1223 1224 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) postEventFromNative(Object camera_ref, int what, int arg1, int arg2, Object obj)1225 private static void postEventFromNative(Object camera_ref, 1226 int what, int arg1, int arg2, Object obj) 1227 { 1228 Camera c = (Camera)((WeakReference)camera_ref).get(); 1229 if (c == null) 1230 return; 1231 1232 if (c.mEventHandler != null) { 1233 Message m = c.mEventHandler.obtainMessage(what, arg1, arg2, obj); 1234 c.mEventHandler.sendMessage(m); 1235 } 1236 } 1237 1238 /** 1239 * Callback interface used to notify on completion of camera auto focus. 1240 * 1241 * <p>Devices that do not support auto-focus will receive a "fake" 1242 * callback to this interface. If your application needs auto-focus and 1243 * should not be installed on devices <em>without</em> auto-focus, you must 1244 * declare that your app uses the 1245 * {@code android.hardware.camera.autofocus} feature, in the 1246 * <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html"><uses-feature></a> 1247 * manifest element.</p> 1248 * 1249 * @see #autoFocus(AutoFocusCallback) 1250 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 1251 * applications. 1252 */ 1253 @Deprecated 1254 public interface AutoFocusCallback 1255 { 1256 /** 1257 * Called when the camera auto focus completes. If the camera 1258 * does not support auto-focus and autoFocus is called, 1259 * onAutoFocus will be called immediately with a fake value of 1260 * <code>success</code> set to <code>true</code>. 1261 * 1262 * The auto-focus routine does not lock auto-exposure and auto-white 1263 * balance after it completes. 1264 * 1265 * @param success true if focus was successful, false if otherwise 1266 * @param camera the Camera service object 1267 * @see android.hardware.Camera.Parameters#setAutoExposureLock(boolean) 1268 * @see android.hardware.Camera.Parameters#setAutoWhiteBalanceLock(boolean) 1269 */ onAutoFocus(boolean success, Camera camera)1270 void onAutoFocus(boolean success, Camera camera); 1271 } 1272 1273 /** 1274 * Starts camera auto-focus and registers a callback function to run when 1275 * the camera is focused. This method is only valid when preview is active 1276 * (between {@link #startPreview()} and before {@link #stopPreview()}). 1277 * 1278 * <p>Callers should check 1279 * {@link android.hardware.Camera.Parameters#getFocusMode()} to determine if 1280 * this method should be called. If the camera does not support auto-focus, 1281 * it is a no-op and {@link AutoFocusCallback#onAutoFocus(boolean, Camera)} 1282 * callback will be called immediately. 1283 * 1284 * <p>If your application should not be installed 1285 * on devices without auto-focus, you must declare that your application 1286 * uses auto-focus with the 1287 * <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html"><uses-feature></a> 1288 * manifest element.</p> 1289 * 1290 * <p>If the current flash mode is not 1291 * {@link android.hardware.Camera.Parameters#FLASH_MODE_OFF}, flash may be 1292 * fired during auto-focus, depending on the driver and camera hardware.<p> 1293 * 1294 * <p>Auto-exposure lock {@link android.hardware.Camera.Parameters#getAutoExposureLock()} 1295 * and auto-white balance locks {@link android.hardware.Camera.Parameters#getAutoWhiteBalanceLock()} 1296 * do not change during and after autofocus. But auto-focus routine may stop 1297 * auto-exposure and auto-white balance transiently during focusing. 1298 * 1299 * <p>Stopping preview with {@link #stopPreview()}, or triggering still 1300 * image capture with {@link #takePicture(Camera.ShutterCallback, 1301 * Camera.PictureCallback, Camera.PictureCallback)}, will not change the 1302 * the focus position. Applications must call cancelAutoFocus to reset the 1303 * focus.</p> 1304 * 1305 * <p>If autofocus is successful, consider using 1306 * {@link android.media.MediaActionSound} to properly play back an autofocus 1307 * success sound to the user.</p> 1308 * 1309 * @param cb the callback to run 1310 * @throws RuntimeException if starting autofocus fails; usually this would 1311 * be because of a hardware or other low-level error, or because 1312 * release() has been called on this Camera instance. 1313 * @see #cancelAutoFocus() 1314 * @see android.hardware.Camera.Parameters#setAutoExposureLock(boolean) 1315 * @see android.hardware.Camera.Parameters#setAutoWhiteBalanceLock(boolean) 1316 * @see android.media.MediaActionSound 1317 */ autoFocus(AutoFocusCallback cb)1318 public final void autoFocus(AutoFocusCallback cb) 1319 { 1320 synchronized (mAutoFocusCallbackLock) { 1321 mAutoFocusCallback = cb; 1322 } 1323 native_autoFocus(); 1324 } native_autoFocus()1325 private native final void native_autoFocus(); 1326 1327 /** 1328 * Cancels any auto-focus function in progress. 1329 * Whether or not auto-focus is currently in progress, 1330 * this function will return the focus position to the default. 1331 * If the camera does not support auto-focus, this is a no-op. 1332 * 1333 * @throws RuntimeException if canceling autofocus fails; usually this would 1334 * be because of a hardware or other low-level error, or because 1335 * release() has been called on this Camera instance. 1336 * @see #autoFocus(Camera.AutoFocusCallback) 1337 */ cancelAutoFocus()1338 public final void cancelAutoFocus() 1339 { 1340 synchronized (mAutoFocusCallbackLock) { 1341 mAutoFocusCallback = null; 1342 } 1343 native_cancelAutoFocus(); 1344 // CAMERA_MSG_FOCUS should be removed here because the following 1345 // scenario can happen: 1346 // - An application uses the same thread for autoFocus, cancelAutoFocus 1347 // and looper thread. 1348 // - The application calls autoFocus. 1349 // - HAL sends CAMERA_MSG_FOCUS, which enters the looper message queue. 1350 // Before event handler's handleMessage() is invoked, the application 1351 // calls cancelAutoFocus and autoFocus. 1352 // - The application gets the old CAMERA_MSG_FOCUS and thinks autofocus 1353 // has been completed. But in fact it is not. 1354 // 1355 // As documented in the beginning of the file, apps should not use 1356 // multiple threads to call autoFocus and cancelAutoFocus at the same 1357 // time. It is HAL's responsibility not to send a CAMERA_MSG_FOCUS 1358 // message after native_cancelAutoFocus is called. 1359 mEventHandler.removeMessages(CAMERA_MSG_FOCUS); 1360 } native_cancelAutoFocus()1361 private native final void native_cancelAutoFocus(); 1362 1363 /** 1364 * Callback interface used to notify on auto focus start and stop. 1365 * 1366 * <p>This is only supported in continuous autofocus modes -- {@link 1367 * Parameters#FOCUS_MODE_CONTINUOUS_VIDEO} and {@link 1368 * Parameters#FOCUS_MODE_CONTINUOUS_PICTURE}. Applications can show 1369 * autofocus animation based on this.</p> 1370 * 1371 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 1372 * applications. 1373 */ 1374 @Deprecated 1375 public interface AutoFocusMoveCallback 1376 { 1377 /** 1378 * Called when the camera auto focus starts or stops. 1379 * 1380 * @param start true if focus starts to move, false if focus stops to move 1381 * @param camera the Camera service object 1382 */ onAutoFocusMoving(boolean start, Camera camera)1383 void onAutoFocusMoving(boolean start, Camera camera); 1384 } 1385 1386 /** 1387 * Sets camera auto-focus move callback. 1388 * 1389 * @param cb the callback to run 1390 * @throws RuntimeException if enabling the focus move callback fails; 1391 * usually this would be because of a hardware or other low-level error, 1392 * or because release() has been called on this Camera instance. 1393 */ setAutoFocusMoveCallback(AutoFocusMoveCallback cb)1394 public void setAutoFocusMoveCallback(AutoFocusMoveCallback cb) { 1395 mAutoFocusMoveCallback = cb; 1396 enableFocusMoveCallback((mAutoFocusMoveCallback != null) ? 1 : 0); 1397 } 1398 enableFocusMoveCallback(int enable)1399 private native void enableFocusMoveCallback(int enable); 1400 1401 /** 1402 * Callback interface used to signal the moment of actual image capture. 1403 * 1404 * @see #takePicture(ShutterCallback, PictureCallback, PictureCallback, PictureCallback) 1405 * 1406 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 1407 * applications. 1408 */ 1409 @Deprecated 1410 public interface ShutterCallback 1411 { 1412 /** 1413 * Called as near as possible to the moment when a photo is captured 1414 * from the sensor. This is a good opportunity to play a shutter sound 1415 * or give other feedback of camera operation. This may be some time 1416 * after the photo was triggered, but some time before the actual data 1417 * is available. 1418 */ onShutter()1419 void onShutter(); 1420 } 1421 1422 /** 1423 * Callback interface used to supply image data from a photo capture. 1424 * 1425 * @see #takePicture(ShutterCallback, PictureCallback, PictureCallback, PictureCallback) 1426 * 1427 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 1428 * applications. 1429 */ 1430 @Deprecated 1431 public interface PictureCallback { 1432 /** 1433 * Called when image data is available after a picture is taken. 1434 * The format of the data depends on the context of the callback 1435 * and {@link Camera.Parameters} settings. 1436 * 1437 * @param data a byte array of the picture data 1438 * @param camera the Camera service object 1439 */ onPictureTaken(byte[] data, Camera camera)1440 void onPictureTaken(byte[] data, Camera camera); 1441 }; 1442 1443 /** 1444 * Equivalent to <pre>takePicture(Shutter, raw, null, jpeg)</pre>. 1445 * 1446 * @see #takePicture(ShutterCallback, PictureCallback, PictureCallback, PictureCallback) 1447 */ takePicture(ShutterCallback shutter, PictureCallback raw, PictureCallback jpeg)1448 public final void takePicture(ShutterCallback shutter, PictureCallback raw, 1449 PictureCallback jpeg) { 1450 takePicture(shutter, raw, null, jpeg); 1451 } native_takePicture(int msgType)1452 private native final void native_takePicture(int msgType); 1453 1454 /** 1455 * Triggers an asynchronous image capture. The camera service will initiate 1456 * a series of callbacks to the application as the image capture progresses. 1457 * The shutter callback occurs after the image is captured. This can be used 1458 * to trigger a sound to let the user know that image has been captured. The 1459 * raw callback occurs when the raw image data is available (NOTE: the data 1460 * will be null if there is no raw image callback buffer available or the 1461 * raw image callback buffer is not large enough to hold the raw image). 1462 * The postview callback occurs when a scaled, fully processed postview 1463 * image is available (NOTE: not all hardware supports this). The jpeg 1464 * callback occurs when the compressed image is available. If the 1465 * application does not need a particular callback, a null can be passed 1466 * instead of a callback method. 1467 * 1468 * <p>This method is only valid when preview is active (after 1469 * {@link #startPreview()}). Preview will be stopped after the image is 1470 * taken; callers must call {@link #startPreview()} again if they want to 1471 * re-start preview or take more pictures. This should not be called between 1472 * {@link android.media.MediaRecorder#start()} and 1473 * {@link android.media.MediaRecorder#stop()}. 1474 * 1475 * <p>After calling this method, you must not call {@link #startPreview()} 1476 * or take another picture until the JPEG callback has returned. 1477 * 1478 * @param shutter the callback for image capture moment, or null 1479 * @param raw the callback for raw (uncompressed) image data, or null 1480 * @param postview callback with postview image data, may be null 1481 * @param jpeg the callback for JPEG image data, or null 1482 * @throws RuntimeException if starting picture capture fails; usually this 1483 * would be because of a hardware or other low-level error, or because 1484 * release() has been called on this Camera instance. 1485 */ takePicture(ShutterCallback shutter, PictureCallback raw, PictureCallback postview, PictureCallback jpeg)1486 public final void takePicture(ShutterCallback shutter, PictureCallback raw, 1487 PictureCallback postview, PictureCallback jpeg) { 1488 mShutterCallback = shutter; 1489 mRawImageCallback = raw; 1490 mPostviewCallback = postview; 1491 mJpegCallback = jpeg; 1492 1493 // If callback is not set, do not send me callbacks. 1494 int msgType = 0; 1495 if (mShutterCallback != null) { 1496 msgType |= CAMERA_MSG_SHUTTER; 1497 } 1498 if (mRawImageCallback != null) { 1499 msgType |= CAMERA_MSG_RAW_IMAGE; 1500 } 1501 if (mPostviewCallback != null) { 1502 msgType |= CAMERA_MSG_POSTVIEW_FRAME; 1503 } 1504 if (mJpegCallback != null) { 1505 msgType |= CAMERA_MSG_COMPRESSED_IMAGE; 1506 } 1507 1508 native_takePicture(msgType); 1509 mFaceDetectionRunning = false; 1510 } 1511 1512 /** 1513 * Zooms to the requested value smoothly. The driver will notify {@link 1514 * OnZoomChangeListener} of the zoom value and whether zoom is stopped at 1515 * the time. For example, suppose the current zoom is 0 and startSmoothZoom 1516 * is called with value 3. The 1517 * {@link Camera.OnZoomChangeListener#onZoomChange(int, boolean, Camera)} 1518 * method will be called three times with zoom values 1, 2, and 3. 1519 * Applications can call {@link #stopSmoothZoom} to stop the zoom earlier. 1520 * Applications should not call startSmoothZoom again or change the zoom 1521 * value before zoom stops. If the supplied zoom value equals to the current 1522 * zoom value, no zoom callback will be generated. This method is supported 1523 * if {@link android.hardware.Camera.Parameters#isSmoothZoomSupported} 1524 * returns true. 1525 * 1526 * @param value zoom value. The valid range is 0 to {@link 1527 * android.hardware.Camera.Parameters#getMaxZoom}. 1528 * @throws IllegalArgumentException if the zoom value is invalid. 1529 * @throws RuntimeException if the method fails. 1530 * @see #setZoomChangeListener(OnZoomChangeListener) 1531 */ startSmoothZoom(int value)1532 public native final void startSmoothZoom(int value); 1533 1534 /** 1535 * Stops the smooth zoom. Applications should wait for the {@link 1536 * OnZoomChangeListener} to know when the zoom is actually stopped. This 1537 * method is supported if {@link 1538 * android.hardware.Camera.Parameters#isSmoothZoomSupported} is true. 1539 * 1540 * @throws RuntimeException if the method fails. 1541 */ stopSmoothZoom()1542 public native final void stopSmoothZoom(); 1543 1544 /** 1545 * Set the clockwise rotation of preview display in degrees. This affects 1546 * the preview frames and the picture displayed after snapshot. This method 1547 * is useful for portrait mode applications. Note that preview display of 1548 * front-facing cameras is flipped horizontally before the rotation, that 1549 * is, the image is reflected along the central vertical axis of the camera 1550 * sensor. So the users can see themselves as looking into a mirror. 1551 * 1552 * <p>This does not affect the order of byte array passed in {@link 1553 * PreviewCallback#onPreviewFrame}, JPEG pictures, or recorded videos. This 1554 * method is not allowed to be called during preview. 1555 * 1556 * <p>If you want to make the camera image show in the same orientation as 1557 * the display, you can use the following code. 1558 * <pre> 1559 * public static void setCameraDisplayOrientation(Activity activity, 1560 * int cameraId, android.hardware.Camera camera) { 1561 * android.hardware.Camera.CameraInfo info = 1562 * new android.hardware.Camera.CameraInfo(); 1563 * android.hardware.Camera.getCameraInfo(cameraId, info); 1564 * int rotation = activity.getWindowManager().getDefaultDisplay() 1565 * .getRotation(); 1566 * int degrees = 0; 1567 * switch (rotation) { 1568 * case Surface.ROTATION_0: degrees = 0; break; 1569 * case Surface.ROTATION_90: degrees = 90; break; 1570 * case Surface.ROTATION_180: degrees = 180; break; 1571 * case Surface.ROTATION_270: degrees = 270; break; 1572 * } 1573 * 1574 * int result; 1575 * if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { 1576 * result = (info.orientation + degrees) % 360; 1577 * result = (360 - result) % 360; // compensate the mirror 1578 * } else { // back-facing 1579 * result = (info.orientation - degrees + 360) % 360; 1580 * } 1581 * camera.setDisplayOrientation(result); 1582 * } 1583 * </pre> 1584 * 1585 * <p>Starting from API level 14, this method can be called when preview is 1586 * active. 1587 * 1588 * <p><b>Note: </b>Before API level 24, the default value for orientation is 0. Starting in 1589 * API level 24, the default orientation will be such that applications in forced-landscape mode 1590 * will have correct preview orientation, which may be either a default of 0 or 1591 * 180. Applications that operate in portrait mode or allow for changing orientation must still 1592 * call this method after each orientation change to ensure correct preview display in all 1593 * cases.</p> 1594 * 1595 * @param degrees the angle that the picture will be rotated clockwise. 1596 * Valid values are 0, 90, 180, and 270. 1597 * @throws RuntimeException if setting orientation fails; usually this would 1598 * be because of a hardware or other low-level error, or because 1599 * release() has been called on this Camera instance. 1600 * @see #setPreviewDisplay(SurfaceHolder) 1601 */ setDisplayOrientation(int degrees)1602 public native final void setDisplayOrientation(int degrees); 1603 1604 /** 1605 * <p>Enable or disable the default shutter sound when taking a picture.</p> 1606 * 1607 * <p>By default, the camera plays the system-defined camera shutter sound 1608 * when {@link #takePicture} is called. Using this method, the shutter sound 1609 * can be disabled. It is strongly recommended that an alternative shutter 1610 * sound is played in the {@link ShutterCallback} when the system shutter 1611 * sound is disabled.</p> 1612 * 1613 * <p>Note that devices may not always allow disabling the camera shutter 1614 * sound. If the shutter sound state cannot be set to the desired value, 1615 * this method will return false. {@link CameraInfo#canDisableShutterSound} 1616 * can be used to determine whether the device will allow the shutter sound 1617 * to be disabled.</p> 1618 * 1619 * @param enabled whether the camera should play the system shutter sound 1620 * when {@link #takePicture takePicture} is called. 1621 * @return {@code true} if the shutter sound state was successfully 1622 * changed. {@code false} if the shutter sound state could not be 1623 * changed. {@code true} is also returned if shutter sound playback 1624 * is already set to the requested state. 1625 * @throws RuntimeException if the call fails; usually this would be because 1626 * of a hardware or other low-level error, or because release() has been 1627 * called on this Camera instance. 1628 * @see #takePicture 1629 * @see CameraInfo#canDisableShutterSound 1630 * @see ShutterCallback 1631 */ enableShutterSound(boolean enabled)1632 public final boolean enableShutterSound(boolean enabled) { 1633 boolean canDisableShutterSound = true; 1634 IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE); 1635 IAudioService audioService = IAudioService.Stub.asInterface(b); 1636 try { 1637 if (audioService.isCameraSoundForced()) { 1638 canDisableShutterSound = false; 1639 } 1640 } catch (RemoteException e) { 1641 Log.e(TAG, "Audio service is unavailable for queries"); 1642 } 1643 if (!enabled && !canDisableShutterSound) { 1644 return false; 1645 } 1646 synchronized (mShutterSoundLock) { 1647 mShutterSoundEnabledFromApp = enabled; 1648 // Return the result of _enableShutterSound(enabled) in all cases. 1649 // If the shutter sound can be disabled, disable it when the device is in DnD mode. 1650 boolean ret = _enableShutterSound(enabled); 1651 if (enabled && !mHasAppOpsPlayAudio) { 1652 Log.i(TAG, "Shutter sound is not allowed by AppOpsManager"); 1653 if (canDisableShutterSound) { 1654 _enableShutterSound(false); 1655 } 1656 } 1657 return ret; 1658 } 1659 } 1660 1661 /** 1662 * Disable the shutter sound unconditionally. 1663 * 1664 * <p> 1665 * This is only guaranteed to work for legacy cameras 1666 * (i.e. initialized with {@link #cameraInitUnspecified}). Trying to call this on 1667 * a regular camera will force a conditional check in the camera service. 1668 * </p> 1669 * 1670 * @return {@code true} if the shutter sound state was successfully 1671 * changed. {@code false} if the shutter sound state could not be 1672 * changed. {@code true} is also returned if shutter sound playback 1673 * is already set to the requested state. 1674 * 1675 * @hide 1676 */ disableShutterSound()1677 public final boolean disableShutterSound() { 1678 return _enableShutterSound(/*enabled*/false); 1679 } 1680 _enableShutterSound(boolean enabled)1681 private native final boolean _enableShutterSound(boolean enabled); 1682 1683 private static class IAppOpsCallbackWrapper extends IAppOpsCallback.Stub { 1684 private final WeakReference<Camera> mWeakCamera; 1685 IAppOpsCallbackWrapper(Camera camera)1686 IAppOpsCallbackWrapper(Camera camera) { 1687 mWeakCamera = new WeakReference<Camera>(camera); 1688 } 1689 1690 @Override opChanged(int op, int uid, String packageName)1691 public void opChanged(int op, int uid, String packageName) { 1692 if (op == AppOpsManager.OP_PLAY_AUDIO) { 1693 final Camera camera = mWeakCamera.get(); 1694 if (camera != null) { 1695 camera.updateAppOpsPlayAudio(); 1696 } 1697 } 1698 } 1699 } 1700 updateAppOpsPlayAudio()1701 private void updateAppOpsPlayAudio() { 1702 synchronized (mShutterSoundLock) { 1703 boolean oldHasAppOpsPlayAudio = mHasAppOpsPlayAudio; 1704 try { 1705 int mode = AppOpsManager.MODE_IGNORED; 1706 if (mAppOps != null) { 1707 mode = mAppOps.checkAudioOperation(AppOpsManager.OP_PLAY_AUDIO, 1708 AudioAttributes.USAGE_ASSISTANCE_SONIFICATION, 1709 Process.myUid(), ActivityThread.currentPackageName()); 1710 } 1711 mHasAppOpsPlayAudio = mode == AppOpsManager.MODE_ALLOWED; 1712 } catch (RemoteException e) { 1713 Log.e(TAG, "AppOpsService check audio operation failed"); 1714 mHasAppOpsPlayAudio = false; 1715 } 1716 if (oldHasAppOpsPlayAudio != mHasAppOpsPlayAudio) { 1717 if (!mHasAppOpsPlayAudio) { 1718 IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE); 1719 IAudioService audioService = IAudioService.Stub.asInterface(b); 1720 try { 1721 if (audioService.isCameraSoundForced()) { 1722 return; 1723 } 1724 } catch (RemoteException e) { 1725 Log.e(TAG, "Audio service is unavailable for queries"); 1726 } 1727 _enableShutterSound(false); 1728 } else { 1729 enableShutterSound(mShutterSoundEnabledFromApp); 1730 } 1731 } 1732 } 1733 } 1734 1735 /** 1736 * Callback interface for zoom changes during a smooth zoom operation. 1737 * 1738 * @see #setZoomChangeListener(OnZoomChangeListener) 1739 * @see #startSmoothZoom(int) 1740 * 1741 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 1742 * applications. 1743 */ 1744 @Deprecated 1745 public interface OnZoomChangeListener 1746 { 1747 /** 1748 * Called when the zoom value has changed during a smooth zoom. 1749 * 1750 * @param zoomValue the current zoom value. In smooth zoom mode, camera 1751 * calls this for every new zoom value. 1752 * @param stopped whether smooth zoom is stopped. If the value is true, 1753 * this is the last zoom update for the application. 1754 * @param camera the Camera service object 1755 */ onZoomChange(int zoomValue, boolean stopped, Camera camera)1756 void onZoomChange(int zoomValue, boolean stopped, Camera camera); 1757 }; 1758 1759 /** 1760 * Registers a listener to be notified when the zoom value is updated by the 1761 * camera driver during smooth zoom. 1762 * 1763 * @param listener the listener to notify 1764 * @see #startSmoothZoom(int) 1765 */ setZoomChangeListener(OnZoomChangeListener listener)1766 public final void setZoomChangeListener(OnZoomChangeListener listener) 1767 { 1768 mZoomListener = listener; 1769 } 1770 1771 /** 1772 * Callback interface for face detected in the preview frame. 1773 * 1774 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 1775 * applications. 1776 */ 1777 @Deprecated 1778 public interface FaceDetectionListener 1779 { 1780 /** 1781 * Notify the listener of the detected faces in the preview frame. 1782 * 1783 * @param faces The detected faces in a list 1784 * @param camera The {@link Camera} service object 1785 */ onFaceDetection(Face[] faces, Camera camera)1786 void onFaceDetection(Face[] faces, Camera camera); 1787 } 1788 1789 /** 1790 * Registers a listener to be notified about the faces detected in the 1791 * preview frame. 1792 * 1793 * @param listener the listener to notify 1794 * @see #startFaceDetection() 1795 */ setFaceDetectionListener(FaceDetectionListener listener)1796 public final void setFaceDetectionListener(FaceDetectionListener listener) 1797 { 1798 mFaceListener = listener; 1799 } 1800 1801 /** 1802 * Starts the face detection. This should be called after preview is started. 1803 * The camera will notify {@link FaceDetectionListener} of the detected 1804 * faces in the preview frame. The detected faces may be the same as the 1805 * previous ones. Applications should call {@link #stopFaceDetection} to 1806 * stop the face detection. This method is supported if {@link 1807 * Parameters#getMaxNumDetectedFaces()} returns a number larger than 0. 1808 * If the face detection has started, apps should not call this again. 1809 * 1810 * <p>When the face detection is running, {@link Parameters#setWhiteBalance(String)}, 1811 * {@link Parameters#setFocusAreas(List)}, and {@link Parameters#setMeteringAreas(List)} 1812 * have no effect. The camera uses the detected faces to do auto-white balance, 1813 * auto exposure, and autofocus. 1814 * 1815 * <p>If the apps call {@link #autoFocus(AutoFocusCallback)}, the camera 1816 * will stop sending face callbacks. The last face callback indicates the 1817 * areas used to do autofocus. After focus completes, face detection will 1818 * resume sending face callbacks. If the apps call {@link 1819 * #cancelAutoFocus()}, the face callbacks will also resume.</p> 1820 * 1821 * <p>After calling {@link #takePicture(Camera.ShutterCallback, Camera.PictureCallback, 1822 * Camera.PictureCallback)} or {@link #stopPreview()}, and then resuming 1823 * preview with {@link #startPreview()}, the apps should call this method 1824 * again to resume face detection.</p> 1825 * 1826 * @throws IllegalArgumentException if the face detection is unsupported. 1827 * @throws RuntimeException if the method fails or the face detection is 1828 * already running. 1829 * @see FaceDetectionListener 1830 * @see #stopFaceDetection() 1831 * @see Parameters#getMaxNumDetectedFaces() 1832 */ startFaceDetection()1833 public final void startFaceDetection() { 1834 if (mFaceDetectionRunning) { 1835 throw new RuntimeException("Face detection is already running"); 1836 } 1837 _startFaceDetection(CAMERA_FACE_DETECTION_HW); 1838 mFaceDetectionRunning = true; 1839 } 1840 1841 /** 1842 * Stops the face detection. 1843 * 1844 * @see #startFaceDetection() 1845 */ stopFaceDetection()1846 public final void stopFaceDetection() { 1847 _stopFaceDetection(); 1848 mFaceDetectionRunning = false; 1849 } 1850 _startFaceDetection(int type)1851 private native final void _startFaceDetection(int type); _stopFaceDetection()1852 private native final void _stopFaceDetection(); 1853 1854 /** 1855 * Information about a face identified through camera face detection. 1856 * 1857 * <p>When face detection is used with a camera, the {@link FaceDetectionListener} returns a 1858 * list of face objects for use in focusing and metering.</p> 1859 * 1860 * @see FaceDetectionListener 1861 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 1862 * applications. 1863 */ 1864 @Deprecated 1865 public static class Face { 1866 /** 1867 * Create an empty face. 1868 */ Face()1869 public Face() { 1870 } 1871 1872 /** 1873 * Bounds of the face. (-1000, -1000) represents the top-left of the 1874 * camera field of view, and (1000, 1000) represents the bottom-right of 1875 * the field of view. For example, suppose the size of the viewfinder UI 1876 * is 800x480. The rect passed from the driver is (-1000, -1000, 0, 0). 1877 * The corresponding viewfinder rect should be (0, 0, 400, 240). It is 1878 * guaranteed left < right and top < bottom. The coordinates can be 1879 * smaller than -1000 or bigger than 1000. But at least one vertex will 1880 * be within (-1000, -1000) and (1000, 1000). 1881 * 1882 * <p>The direction is relative to the sensor orientation, that is, what 1883 * the sensor sees. The direction is not affected by the rotation or 1884 * mirroring of {@link #setDisplayOrientation(int)}. The face bounding 1885 * rectangle does not provide any information about face orientation.</p> 1886 * 1887 * <p>Here is the matrix to convert driver coordinates to View coordinates 1888 * in pixels.</p> 1889 * <pre> 1890 * Matrix matrix = new Matrix(); 1891 * CameraInfo info = CameraHolder.instance().getCameraInfo()[cameraId]; 1892 * // Need mirror for front camera. 1893 * boolean mirror = (info.facing == CameraInfo.CAMERA_FACING_FRONT); 1894 * matrix.setScale(mirror ? -1 : 1, 1); 1895 * // This is the value for android.hardware.Camera.setDisplayOrientation. 1896 * matrix.postRotate(displayOrientation); 1897 * // Camera driver coordinates range from (-1000, -1000) to (1000, 1000). 1898 * // UI coordinates range from (0, 0) to (width, height). 1899 * matrix.postScale(view.getWidth() / 2000f, view.getHeight() / 2000f); 1900 * matrix.postTranslate(view.getWidth() / 2f, view.getHeight() / 2f); 1901 * </pre> 1902 * 1903 * @see #startFaceDetection() 1904 */ 1905 public Rect rect; 1906 1907 /** 1908 * <p>The confidence level for the detection of the face. The range is 1 to 1909 * 100. 100 is the highest confidence.</p> 1910 * 1911 * <p>Depending on the device, even very low-confidence faces may be 1912 * listed, so applications should filter out faces with low confidence, 1913 * depending on the use case. For a typical point-and-shoot camera 1914 * application that wishes to display rectangles around detected faces, 1915 * filtering out faces with confidence less than 50 is recommended.</p> 1916 * 1917 * @see #startFaceDetection() 1918 */ 1919 public int score; 1920 1921 /** 1922 * An unique id per face while the face is visible to the tracker. If 1923 * the face leaves the field-of-view and comes back, it will get a new 1924 * id. This is an optional field, may not be supported on all devices. 1925 * If not supported, id will always be set to -1. The optional fields 1926 * are supported as a set. Either they are all valid, or none of them 1927 * are. 1928 */ 1929 public int id = -1; 1930 1931 /** 1932 * The coordinates of the center of the left eye. The coordinates are in 1933 * the same space as the ones for {@link #rect}. This is an optional 1934 * field, may not be supported on all devices. If not supported, the 1935 * value will always be set to null. The optional fields are supported 1936 * as a set. Either they are all valid, or none of them are. 1937 */ 1938 public Point leftEye = null; 1939 1940 /** 1941 * The coordinates of the center of the right eye. The coordinates are 1942 * in the same space as the ones for {@link #rect}.This is an optional 1943 * field, may not be supported on all devices. If not supported, the 1944 * value will always be set to null. The optional fields are supported 1945 * as a set. Either they are all valid, or none of them are. 1946 */ 1947 public Point rightEye = null; 1948 1949 /** 1950 * The coordinates of the center of the mouth. The coordinates are in 1951 * the same space as the ones for {@link #rect}. This is an optional 1952 * field, may not be supported on all devices. If not supported, the 1953 * value will always be set to null. The optional fields are supported 1954 * as a set. Either they are all valid, or none of them are. 1955 */ 1956 public Point mouth = null; 1957 } 1958 1959 /** 1960 * Unspecified camera error. 1961 * @see Camera.ErrorCallback 1962 */ 1963 public static final int CAMERA_ERROR_UNKNOWN = 1; 1964 1965 /** 1966 * Camera was disconnected due to use by higher priority user. 1967 * @see Camera.ErrorCallback 1968 */ 1969 public static final int CAMERA_ERROR_EVICTED = 2; 1970 1971 /** 1972 * Camera was disconnected due to device policy change or client 1973 * application going to background. 1974 * @see Camera.ErrorCallback 1975 * 1976 * @hide 1977 */ 1978 public static final int CAMERA_ERROR_DISABLED = 3; 1979 1980 /** 1981 * Media server died. In this case, the application must release the 1982 * Camera object and instantiate a new one. 1983 * @see Camera.ErrorCallback 1984 */ 1985 public static final int CAMERA_ERROR_SERVER_DIED = 100; 1986 1987 /** 1988 * Callback interface for camera error notification. 1989 * 1990 * @see #setErrorCallback(ErrorCallback) 1991 * 1992 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 1993 * applications. 1994 */ 1995 @Deprecated 1996 public interface ErrorCallback 1997 { 1998 /** 1999 * Callback for camera errors. 2000 * @param error error code: 2001 * <ul> 2002 * <li>{@link #CAMERA_ERROR_UNKNOWN} 2003 * <li>{@link #CAMERA_ERROR_SERVER_DIED} 2004 * </ul> 2005 * @param camera the Camera service object 2006 */ onError(int error, Camera camera)2007 void onError(int error, Camera camera); 2008 }; 2009 2010 /** 2011 * Registers a callback to be invoked when an error occurs. 2012 * @param cb The callback to run 2013 */ setErrorCallback(ErrorCallback cb)2014 public final void setErrorCallback(ErrorCallback cb) 2015 { 2016 mErrorCallback = cb; 2017 } 2018 2019 /** 2020 * Registers a callback to be invoked when an error occurs. 2021 * The detailed error callback may contain error code that 2022 * gives more detailed information about the error. 2023 * 2024 * When a detailed callback is set, the callback set via 2025 * #setErrorCallback(ErrorCallback) will stop receiving 2026 * onError call. 2027 * 2028 * @param cb The callback to run 2029 * 2030 * @hide 2031 */ setDetailedErrorCallback(ErrorCallback cb)2032 public final void setDetailedErrorCallback(ErrorCallback cb) 2033 { 2034 mDetailedErrorCallback = cb; 2035 } 2036 2037 @UnsupportedAppUsage native_setParameters(String params)2038 private native final void native_setParameters(String params); 2039 @UnsupportedAppUsage native_getParameters()2040 private native final String native_getParameters(); 2041 2042 /** 2043 * Changes the settings for this Camera service. 2044 * 2045 * @param params the Parameters to use for this Camera service 2046 * @throws RuntimeException if any parameter is invalid or not supported. 2047 * @see #getParameters() 2048 */ setParameters(Parameters params)2049 public void setParameters(Parameters params) { 2050 // If using preview allocations, don't allow preview size changes 2051 if (mUsingPreviewAllocation) { 2052 Size newPreviewSize = params.getPreviewSize(); 2053 Size currentPreviewSize = getParameters().getPreviewSize(); 2054 if (newPreviewSize.width != currentPreviewSize.width || 2055 newPreviewSize.height != currentPreviewSize.height) { 2056 throw new IllegalStateException("Cannot change preview size" + 2057 " while a preview allocation is configured."); 2058 } 2059 } 2060 2061 native_setParameters(params.flatten()); 2062 } 2063 2064 /** 2065 * Returns the current settings for this Camera service. 2066 * If modifications are made to the returned Parameters, they must be passed 2067 * to {@link #setParameters(Camera.Parameters)} to take effect. 2068 * 2069 * @throws RuntimeException if reading parameters fails; usually this would 2070 * be because of a hardware or other low-level error, or because 2071 * release() has been called on this Camera instance. 2072 * @see #setParameters(Camera.Parameters) 2073 */ getParameters()2074 public Parameters getParameters() { 2075 Parameters p = new Parameters(); 2076 String s = native_getParameters(); 2077 p.unflatten(s); 2078 return p; 2079 } 2080 2081 /** 2082 * Returns an empty {@link Parameters} for testing purpose. 2083 * 2084 * @return a Parameter object. 2085 * 2086 * @hide 2087 */ 2088 @UnsupportedAppUsage getEmptyParameters()2089 public static Parameters getEmptyParameters() { 2090 Camera camera = new Camera(); 2091 return camera.new Parameters(); 2092 } 2093 2094 /** 2095 * Returns a copied {@link Parameters}; for shim use only. 2096 * 2097 * @param parameters a non-{@code null} parameters 2098 * @return a Parameter object, with all the parameters copied from {@code parameters}. 2099 * 2100 * @throws NullPointerException if {@code parameters} was {@code null} 2101 * @hide 2102 */ getParametersCopy(Camera.Parameters parameters)2103 public static Parameters getParametersCopy(Camera.Parameters parameters) { 2104 if (parameters == null) { 2105 throw new NullPointerException("parameters must not be null"); 2106 } 2107 2108 Camera camera = parameters.getOuter(); 2109 Parameters p = camera.new Parameters(); 2110 p.copyFrom(parameters); 2111 2112 return p; 2113 } 2114 2115 /** 2116 * Set camera audio restriction mode. 2117 * 2118 * @hide 2119 */ setAudioRestriction(int mode)2120 public native final void setAudioRestriction(int mode); 2121 2122 /** 2123 * Get currently applied camera audio restriction mode. 2124 * 2125 * @hide 2126 */ getAudioRestriction()2127 public native final int getAudioRestriction(); 2128 2129 /** 2130 * Image size (width and height dimensions). 2131 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 2132 * applications. 2133 */ 2134 @Deprecated 2135 public class Size { 2136 /** 2137 * Sets the dimensions for pictures. 2138 * 2139 * @param w the photo width (pixels) 2140 * @param h the photo height (pixels) 2141 */ Size(int w, int h)2142 public Size(int w, int h) { 2143 width = w; 2144 height = h; 2145 } 2146 /** 2147 * Compares {@code obj} to this size. 2148 * 2149 * @param obj the object to compare this size with. 2150 * @return {@code true} if the width and height of {@code obj} is the 2151 * same as those of this size. {@code false} otherwise. 2152 */ 2153 @Override equals(@ullable Object obj)2154 public boolean equals(@Nullable Object obj) { 2155 if (!(obj instanceof Size)) { 2156 return false; 2157 } 2158 Size s = (Size) obj; 2159 return width == s.width && height == s.height; 2160 } 2161 @Override hashCode()2162 public int hashCode() { 2163 return width * 32713 + height; 2164 } 2165 /** width of the picture */ 2166 public int width; 2167 /** height of the picture */ 2168 public int height; 2169 }; 2170 2171 /** 2172 * <p>The Area class is used for choosing specific metering and focus areas for 2173 * the camera to use when calculating auto-exposure, auto-white balance, and 2174 * auto-focus.</p> 2175 * 2176 * <p>To find out how many simultaneous areas a given camera supports, use 2177 * {@link Parameters#getMaxNumMeteringAreas()} and 2178 * {@link Parameters#getMaxNumFocusAreas()}. If metering or focusing area 2179 * selection is unsupported, these methods will return 0.</p> 2180 * 2181 * <p>Each Area consists of a rectangle specifying its bounds, and a weight 2182 * that determines its importance. The bounds are relative to the camera's 2183 * current field of view. The coordinates are mapped so that (-1000, -1000) 2184 * is always the top-left corner of the current field of view, and (1000, 2185 * 1000) is always the bottom-right corner of the current field of 2186 * view. Setting Areas with bounds outside that range is not allowed. Areas 2187 * with zero or negative width or height are not allowed.</p> 2188 * 2189 * <p>The weight must range from 1 to 1000, and represents a weight for 2190 * every pixel in the area. This means that a large metering area with 2191 * the same weight as a smaller area will have more effect in the 2192 * metering result. Metering areas can overlap and the driver 2193 * will add the weights in the overlap region.</p> 2194 * 2195 * @see Parameters#setFocusAreas(List) 2196 * @see Parameters#getFocusAreas() 2197 * @see Parameters#getMaxNumFocusAreas() 2198 * @see Parameters#setMeteringAreas(List) 2199 * @see Parameters#getMeteringAreas() 2200 * @see Parameters#getMaxNumMeteringAreas() 2201 * 2202 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 2203 * applications. 2204 */ 2205 @Deprecated 2206 public static class Area { 2207 /** 2208 * Create an area with specified rectangle and weight. 2209 * 2210 * @param rect the bounds of the area. 2211 * @param weight the weight of the area. 2212 */ Area(Rect rect, int weight)2213 public Area(Rect rect, int weight) { 2214 this.rect = rect; 2215 this.weight = weight; 2216 } 2217 /** 2218 * Compares {@code obj} to this area. 2219 * 2220 * @param obj the object to compare this area with. 2221 * @return {@code true} if the rectangle and weight of {@code obj} is 2222 * the same as those of this area. {@code false} otherwise. 2223 */ 2224 @Override equals(@ullable Object obj)2225 public boolean equals(@Nullable Object obj) { 2226 if (!(obj instanceof Area)) { 2227 return false; 2228 } 2229 Area a = (Area) obj; 2230 if (rect == null) { 2231 if (a.rect != null) return false; 2232 } else { 2233 if (!rect.equals(a.rect)) return false; 2234 } 2235 return weight == a.weight; 2236 } 2237 2238 /** 2239 * Bounds of the area. (-1000, -1000) represents the top-left of the 2240 * camera field of view, and (1000, 1000) represents the bottom-right of 2241 * the field of view. Setting bounds outside that range is not 2242 * allowed. Bounds with zero or negative width or height are not 2243 * allowed. 2244 * 2245 * @see Parameters#getFocusAreas() 2246 * @see Parameters#getMeteringAreas() 2247 */ 2248 public Rect rect; 2249 2250 /** 2251 * Weight of the area. The weight must range from 1 to 1000, and 2252 * represents a weight for every pixel in the area. This means that a 2253 * large metering area with the same weight as a smaller area will have 2254 * more effect in the metering result. Metering areas can overlap and 2255 * the driver will add the weights in the overlap region. 2256 * 2257 * @see Parameters#getFocusAreas() 2258 * @see Parameters#getMeteringAreas() 2259 */ 2260 public int weight; 2261 } 2262 2263 /** 2264 * Camera service settings. 2265 * 2266 * <p>To make camera parameters take effect, applications have to call 2267 * {@link Camera#setParameters(Camera.Parameters)}. For example, after 2268 * {@link Camera.Parameters#setWhiteBalance} is called, white balance is not 2269 * actually changed until {@link Camera#setParameters(Camera.Parameters)} 2270 * is called with the changed parameters object. 2271 * 2272 * <p>Different devices may have different camera capabilities, such as 2273 * picture size or flash modes. The application should query the camera 2274 * capabilities before setting parameters. For example, the application 2275 * should call {@link Camera.Parameters#getSupportedColorEffects()} before 2276 * calling {@link Camera.Parameters#setColorEffect(String)}. If the 2277 * camera does not support color effects, 2278 * {@link Camera.Parameters#getSupportedColorEffects()} will return null. 2279 * 2280 * @deprecated We recommend using the new {@link android.hardware.camera2} API for new 2281 * applications. 2282 */ 2283 @Deprecated 2284 public class Parameters { 2285 // Parameter keys to communicate with the camera driver. 2286 private static final String KEY_PREVIEW_SIZE = "preview-size"; 2287 private static final String KEY_PREVIEW_FORMAT = "preview-format"; 2288 private static final String KEY_PREVIEW_FRAME_RATE = "preview-frame-rate"; 2289 private static final String KEY_PREVIEW_FPS_RANGE = "preview-fps-range"; 2290 private static final String KEY_PICTURE_SIZE = "picture-size"; 2291 private static final String KEY_PICTURE_FORMAT = "picture-format"; 2292 private static final String KEY_JPEG_THUMBNAIL_SIZE = "jpeg-thumbnail-size"; 2293 private static final String KEY_JPEG_THUMBNAIL_WIDTH = "jpeg-thumbnail-width"; 2294 private static final String KEY_JPEG_THUMBNAIL_HEIGHT = "jpeg-thumbnail-height"; 2295 private static final String KEY_JPEG_THUMBNAIL_QUALITY = "jpeg-thumbnail-quality"; 2296 private static final String KEY_JPEG_QUALITY = "jpeg-quality"; 2297 private static final String KEY_ROTATION = "rotation"; 2298 private static final String KEY_GPS_LATITUDE = "gps-latitude"; 2299 private static final String KEY_GPS_LONGITUDE = "gps-longitude"; 2300 private static final String KEY_GPS_ALTITUDE = "gps-altitude"; 2301 private static final String KEY_GPS_TIMESTAMP = "gps-timestamp"; 2302 private static final String KEY_GPS_PROCESSING_METHOD = "gps-processing-method"; 2303 private static final String KEY_WHITE_BALANCE = "whitebalance"; 2304 private static final String KEY_EFFECT = "effect"; 2305 private static final String KEY_ANTIBANDING = "antibanding"; 2306 private static final String KEY_SCENE_MODE = "scene-mode"; 2307 private static final String KEY_FLASH_MODE = "flash-mode"; 2308 private static final String KEY_FOCUS_MODE = "focus-mode"; 2309 private static final String KEY_FOCUS_AREAS = "focus-areas"; 2310 private static final String KEY_MAX_NUM_FOCUS_AREAS = "max-num-focus-areas"; 2311 private static final String KEY_FOCAL_LENGTH = "focal-length"; 2312 private static final String KEY_HORIZONTAL_VIEW_ANGLE = "horizontal-view-angle"; 2313 private static final String KEY_VERTICAL_VIEW_ANGLE = "vertical-view-angle"; 2314 private static final String KEY_EXPOSURE_COMPENSATION = "exposure-compensation"; 2315 private static final String KEY_MAX_EXPOSURE_COMPENSATION = "max-exposure-compensation"; 2316 private static final String KEY_MIN_EXPOSURE_COMPENSATION = "min-exposure-compensation"; 2317 private static final String KEY_EXPOSURE_COMPENSATION_STEP = "exposure-compensation-step"; 2318 private static final String KEY_AUTO_EXPOSURE_LOCK = "auto-exposure-lock"; 2319 private static final String KEY_AUTO_EXPOSURE_LOCK_SUPPORTED = "auto-exposure-lock-supported"; 2320 private static final String KEY_AUTO_WHITEBALANCE_LOCK = "auto-whitebalance-lock"; 2321 private static final String KEY_AUTO_WHITEBALANCE_LOCK_SUPPORTED = "auto-whitebalance-lock-supported"; 2322 private static final String KEY_METERING_AREAS = "metering-areas"; 2323 private static final String KEY_MAX_NUM_METERING_AREAS = "max-num-metering-areas"; 2324 private static final String KEY_ZOOM = "zoom"; 2325 private static final String KEY_MAX_ZOOM = "max-zoom"; 2326 private static final String KEY_ZOOM_RATIOS = "zoom-ratios"; 2327 private static final String KEY_ZOOM_SUPPORTED = "zoom-supported"; 2328 private static final String KEY_SMOOTH_ZOOM_SUPPORTED = "smooth-zoom-supported"; 2329 private static final String KEY_FOCUS_DISTANCES = "focus-distances"; 2330 private static final String KEY_VIDEO_SIZE = "video-size"; 2331 private static final String KEY_PREFERRED_PREVIEW_SIZE_FOR_VIDEO = 2332 "preferred-preview-size-for-video"; 2333 private static final String KEY_MAX_NUM_DETECTED_FACES_HW = "max-num-detected-faces-hw"; 2334 private static final String KEY_MAX_NUM_DETECTED_FACES_SW = "max-num-detected-faces-sw"; 2335 private static final String KEY_RECORDING_HINT = "recording-hint"; 2336 private static final String KEY_VIDEO_SNAPSHOT_SUPPORTED = "video-snapshot-supported"; 2337 private static final String KEY_VIDEO_STABILIZATION = "video-stabilization"; 2338 private static final String KEY_VIDEO_STABILIZATION_SUPPORTED = "video-stabilization-supported"; 2339 2340 // Parameter key suffix for supported values. 2341 private static final String SUPPORTED_VALUES_SUFFIX = "-values"; 2342 2343 private static final String TRUE = "true"; 2344 private static final String FALSE = "false"; 2345 2346 // Values for white balance settings. 2347 public static final String WHITE_BALANCE_AUTO = "auto"; 2348 public static final String WHITE_BALANCE_INCANDESCENT = "incandescent"; 2349 public static final String WHITE_BALANCE_FLUORESCENT = "fluorescent"; 2350 public static final String WHITE_BALANCE_WARM_FLUORESCENT = "warm-fluorescent"; 2351 public static final String WHITE_BALANCE_DAYLIGHT = "daylight"; 2352 public static final String WHITE_BALANCE_CLOUDY_DAYLIGHT = "cloudy-daylight"; 2353 public static final String WHITE_BALANCE_TWILIGHT = "twilight"; 2354 public static final String WHITE_BALANCE_SHADE = "shade"; 2355 2356 // Values for color effect settings. 2357 public static final String EFFECT_NONE = "none"; 2358 public static final String EFFECT_MONO = "mono"; 2359 public static final String EFFECT_NEGATIVE = "negative"; 2360 public static final String EFFECT_SOLARIZE = "solarize"; 2361 public static final String EFFECT_SEPIA = "sepia"; 2362 public static final String EFFECT_POSTERIZE = "posterize"; 2363 public static final String EFFECT_WHITEBOARD = "whiteboard"; 2364 public static final String EFFECT_BLACKBOARD = "blackboard"; 2365 public static final String EFFECT_AQUA = "aqua"; 2366 2367 // Values for antibanding settings. 2368 public static final String ANTIBANDING_AUTO = "auto"; 2369 public static final String ANTIBANDING_50HZ = "50hz"; 2370 public static final String ANTIBANDING_60HZ = "60hz"; 2371 public static final String ANTIBANDING_OFF = "off"; 2372 2373 // Values for flash mode settings. 2374 /** 2375 * Flash will not be fired. 2376 */ 2377 public static final String FLASH_MODE_OFF = "off"; 2378 2379 /** 2380 * Flash will be fired automatically when required. The flash may be fired 2381 * during preview, auto-focus, or snapshot depending on the driver. 2382 */ 2383 public static final String FLASH_MODE_AUTO = "auto"; 2384 2385 /** 2386 * Flash will always be fired during snapshot. The flash may also be 2387 * fired during preview or auto-focus depending on the driver. 2388 */ 2389 public static final String FLASH_MODE_ON = "on"; 2390 2391 /** 2392 * Flash will be fired in red-eye reduction mode. 2393 */ 2394 public static final String FLASH_MODE_RED_EYE = "red-eye"; 2395 2396 /** 2397 * Constant emission of light during preview, auto-focus and snapshot. 2398 * This can also be used for video recording. 2399 */ 2400 public static final String FLASH_MODE_TORCH = "torch"; 2401 2402 /** 2403 * Scene mode is off. 2404 */ 2405 public static final String SCENE_MODE_AUTO = "auto"; 2406 2407 /** 2408 * Take photos of fast moving objects. Same as {@link 2409 * #SCENE_MODE_SPORTS}. 2410 */ 2411 public static final String SCENE_MODE_ACTION = "action"; 2412 2413 /** 2414 * Take people pictures. 2415 */ 2416 public static final String SCENE_MODE_PORTRAIT = "portrait"; 2417 2418 /** 2419 * Take pictures on distant objects. 2420 */ 2421 public static final String SCENE_MODE_LANDSCAPE = "landscape"; 2422 2423 /** 2424 * Take photos at night. 2425 */ 2426 public static final String SCENE_MODE_NIGHT = "night"; 2427 2428 /** 2429 * Take people pictures at night. 2430 */ 2431 public static final String SCENE_MODE_NIGHT_PORTRAIT = "night-portrait"; 2432 2433 /** 2434 * Take photos in a theater. Flash light is off. 2435 */ 2436 public static final String SCENE_MODE_THEATRE = "theatre"; 2437 2438 /** 2439 * Take pictures on the beach. 2440 */ 2441 public static final String SCENE_MODE_BEACH = "beach"; 2442 2443 /** 2444 * Take pictures on the snow. 2445 */ 2446 public static final String SCENE_MODE_SNOW = "snow"; 2447 2448 /** 2449 * Take sunset photos. 2450 */ 2451 public static final String SCENE_MODE_SUNSET = "sunset"; 2452 2453 /** 2454 * Avoid blurry pictures (for example, due to hand shake). 2455 */ 2456 public static final String SCENE_MODE_STEADYPHOTO = "steadyphoto"; 2457 2458 /** 2459 * For shooting firework displays. 2460 */ 2461 public static final String SCENE_MODE_FIREWORKS = "fireworks"; 2462 2463 /** 2464 * Take photos of fast moving objects. Same as {@link 2465 * #SCENE_MODE_ACTION}. 2466 */ 2467 public static final String SCENE_MODE_SPORTS = "sports"; 2468 2469 /** 2470 * Take indoor low-light shot. 2471 */ 2472 public static final String SCENE_MODE_PARTY = "party"; 2473 2474 /** 2475 * Capture the naturally warm color of scenes lit by candles. 2476 */ 2477 public static final String SCENE_MODE_CANDLELIGHT = "candlelight"; 2478 2479 /** 2480 * Applications are looking for a barcode. Camera driver will be 2481 * optimized for barcode reading. 2482 */ 2483 public static final String SCENE_MODE_BARCODE = "barcode"; 2484 2485 /** 2486 * Capture a scene using high dynamic range imaging techniques. The 2487 * camera will return an image that has an extended dynamic range 2488 * compared to a regular capture. Capturing such an image may take 2489 * longer than a regular capture. 2490 */ 2491 public static final String SCENE_MODE_HDR = "hdr"; 2492 2493 /** 2494 * Auto-focus mode. Applications should call {@link 2495 * #autoFocus(AutoFocusCallback)} to start the focus in this mode. 2496 */ 2497 public static final String FOCUS_MODE_AUTO = "auto"; 2498 2499 /** 2500 * Focus is set at infinity. Applications should not call 2501 * {@link #autoFocus(AutoFocusCallback)} in this mode. 2502 */ 2503 public static final String FOCUS_MODE_INFINITY = "infinity"; 2504 2505 /** 2506 * Macro (close-up) focus mode. Applications should call 2507 * {@link #autoFocus(AutoFocusCallback)} to start the focus in this 2508 * mode. 2509 */ 2510 public static final String FOCUS_MODE_MACRO = "macro"; 2511 2512 /** 2513 * Focus is fixed. The camera is always in this mode if the focus is not 2514 * adjustable. If the camera has auto-focus, this mode can fix the 2515 * focus, which is usually at hyperfocal distance. Applications should 2516 * not call {@link #autoFocus(AutoFocusCallback)} in this mode. 2517 */ 2518 public static final String FOCUS_MODE_FIXED = "fixed"; 2519 2520 /** 2521 * Extended depth of field (EDOF). Focusing is done digitally and 2522 * continuously. Applications should not call {@link 2523 * #autoFocus(AutoFocusCallback)} in this mode. 2524 */ 2525 public static final String FOCUS_MODE_EDOF = "edof"; 2526 2527 /** 2528 * Continuous auto focus mode intended for video recording. The camera 2529 * continuously tries to focus. This is the best choice for video 2530 * recording because the focus changes smoothly . Applications still can 2531 * call {@link #takePicture(Camera.ShutterCallback, 2532 * Camera.PictureCallback, Camera.PictureCallback)} in this mode but the 2533 * subject may not be in focus. Auto focus starts when the parameter is 2534 * set. 2535 * 2536 * <p>Since API level 14, applications can call {@link 2537 * #autoFocus(AutoFocusCallback)} in this mode. The focus callback will 2538 * immediately return with a boolean that indicates whether the focus is 2539 * sharp or not. The focus position is locked after autoFocus call. If 2540 * applications want to resume the continuous focus, cancelAutoFocus 2541 * must be called. Restarting the preview will not resume the continuous 2542 * autofocus. To stop continuous focus, applications should change the 2543 * focus mode to other modes. 2544 * 2545 * @see #FOCUS_MODE_CONTINUOUS_PICTURE 2546 */ 2547 public static final String FOCUS_MODE_CONTINUOUS_VIDEO = "continuous-video"; 2548 2549 /** 2550 * Continuous auto focus mode intended for taking pictures. The camera 2551 * continuously tries to focus. The speed of focus change is more 2552 * aggressive than {@link #FOCUS_MODE_CONTINUOUS_VIDEO}. Auto focus 2553 * starts when the parameter is set. 2554 * 2555 * <p>Applications can call {@link #autoFocus(AutoFocusCallback)} in 2556 * this mode. If the autofocus is in the middle of scanning, the focus 2557 * callback will return when it completes. If the autofocus is not 2558 * scanning, the focus callback will immediately return with a boolean 2559 * that indicates whether the focus is sharp or not. The apps can then 2560 * decide if they want to take a picture immediately or to change the 2561 * focus mode to auto, and run a full autofocus cycle. The focus 2562 * position is locked after autoFocus call. If applications want to 2563 * resume the continuous focus, cancelAutoFocus must be called. 2564 * Restarting the preview will not resume the continuous autofocus. To 2565 * stop continuous focus, applications should change the focus mode to 2566 * other modes. 2567 * 2568 * @see #FOCUS_MODE_CONTINUOUS_VIDEO 2569 */ 2570 public static final String FOCUS_MODE_CONTINUOUS_PICTURE = "continuous-picture"; 2571 2572 // Indices for focus distance array. 2573 /** 2574 * The array index of near focus distance for use with 2575 * {@link #getFocusDistances(float[])}. 2576 */ 2577 public static final int FOCUS_DISTANCE_NEAR_INDEX = 0; 2578 2579 /** 2580 * The array index of optimal focus distance for use with 2581 * {@link #getFocusDistances(float[])}. 2582 */ 2583 public static final int FOCUS_DISTANCE_OPTIMAL_INDEX = 1; 2584 2585 /** 2586 * The array index of far focus distance for use with 2587 * {@link #getFocusDistances(float[])}. 2588 */ 2589 public static final int FOCUS_DISTANCE_FAR_INDEX = 2; 2590 2591 /** 2592 * The array index of minimum preview fps for use with {@link 2593 * #getPreviewFpsRange(int[])} or {@link 2594 * #getSupportedPreviewFpsRange()}. 2595 */ 2596 public static final int PREVIEW_FPS_MIN_INDEX = 0; 2597 2598 /** 2599 * The array index of maximum preview fps for use with {@link 2600 * #getPreviewFpsRange(int[])} or {@link 2601 * #getSupportedPreviewFpsRange()}. 2602 */ 2603 public static final int PREVIEW_FPS_MAX_INDEX = 1; 2604 2605 // Formats for setPreviewFormat and setPictureFormat. 2606 private static final String PIXEL_FORMAT_YUV422SP = "yuv422sp"; 2607 private static final String PIXEL_FORMAT_YUV420SP = "yuv420sp"; 2608 private static final String PIXEL_FORMAT_YUV422I = "yuv422i-yuyv"; 2609 private static final String PIXEL_FORMAT_YUV420P = "yuv420p"; 2610 private static final String PIXEL_FORMAT_RGB565 = "rgb565"; 2611 private static final String PIXEL_FORMAT_JPEG = "jpeg"; 2612 private static final String PIXEL_FORMAT_BAYER_RGGB = "bayer-rggb"; 2613 2614 /** 2615 * Order matters: Keys that are {@link #set(String, String) set} later 2616 * will take precedence over keys that are set earlier (if the two keys 2617 * conflict with each other). 2618 * 2619 * <p>One example is {@link #setPreviewFpsRange(int, int)} , since it 2620 * conflicts with {@link #setPreviewFrameRate(int)} whichever key is set later 2621 * is the one that will take precedence. 2622 * </p> 2623 */ 2624 private final LinkedHashMap<String, String> mMap; 2625 Parameters()2626 private Parameters() { 2627 mMap = new LinkedHashMap<String, String>(/*initialCapacity*/64); 2628 } 2629 2630 /** 2631 * Overwrite existing parameters with a copy of the ones from {@code other}. 2632 * 2633 * <b>For use by the legacy shim only.</b> 2634 * 2635 * @hide 2636 */ 2637 @UnsupportedAppUsage copyFrom(Parameters other)2638 public void copyFrom(Parameters other) { 2639 if (other == null) { 2640 throw new NullPointerException("other must not be null"); 2641 } 2642 2643 mMap.putAll(other.mMap); 2644 } 2645 getOuter()2646 private Camera getOuter() { 2647 return Camera.this; 2648 } 2649 2650 2651 /** 2652 * Value equality check. 2653 * 2654 * @hide 2655 */ same(Parameters other)2656 public boolean same(Parameters other) { 2657 if (this == other) { 2658 return true; 2659 } 2660 return other != null && Parameters.this.mMap.equals(other.mMap); 2661 } 2662 2663 /** 2664 * Writes the current Parameters to the log. 2665 * @hide 2666 * @deprecated 2667 */ 2668 @Deprecated 2669 @UnsupportedAppUsage dump()2670 public void dump() { 2671 Log.e(TAG, "dump: size=" + mMap.size()); 2672 for (String k : mMap.keySet()) { 2673 Log.e(TAG, "dump: " + k + "=" + mMap.get(k)); 2674 } 2675 } 2676 2677 /** 2678 * Creates a single string with all the parameters set in 2679 * this Parameters object. 2680 * <p>The {@link #unflatten(String)} method does the reverse.</p> 2681 * 2682 * @return a String with all values from this Parameters object, in 2683 * semi-colon delimited key-value pairs 2684 */ flatten()2685 public String flatten() { 2686 StringBuilder flattened = new StringBuilder(128); 2687 for (String k : mMap.keySet()) { 2688 flattened.append(k); 2689 flattened.append("="); 2690 flattened.append(mMap.get(k)); 2691 flattened.append(";"); 2692 } 2693 // chop off the extra semicolon at the end 2694 flattened.deleteCharAt(flattened.length()-1); 2695 return flattened.toString(); 2696 } 2697 2698 /** 2699 * Takes a flattened string of parameters and adds each one to 2700 * this Parameters object. 2701 * <p>The {@link #flatten()} method does the reverse.</p> 2702 * 2703 * @param flattened a String of parameters (key-value paired) that 2704 * are semi-colon delimited 2705 */ unflatten(String flattened)2706 public void unflatten(String flattened) { 2707 mMap.clear(); 2708 2709 TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter(';'); 2710 splitter.setString(flattened); 2711 for (String kv : splitter) { 2712 int pos = kv.indexOf('='); 2713 if (pos == -1) { 2714 continue; 2715 } 2716 String k = kv.substring(0, pos); 2717 String v = kv.substring(pos + 1); 2718 mMap.put(k, v); 2719 } 2720 } 2721 remove(String key)2722 public void remove(String key) { 2723 mMap.remove(key); 2724 } 2725 2726 /** 2727 * Sets a String parameter. 2728 * 2729 * @param key the key name for the parameter 2730 * @param value the String value of the parameter 2731 */ set(String key, String value)2732 public void set(String key, String value) { 2733 if (key.indexOf('=') != -1 || key.indexOf(';') != -1 || key.indexOf(0) != -1) { 2734 Log.e(TAG, "Key \"" + key + "\" contains invalid character (= or ; or \\0)"); 2735 return; 2736 } 2737 if (value.indexOf('=') != -1 || value.indexOf(';') != -1 || value.indexOf(0) != -1) { 2738 Log.e(TAG, "Value \"" + value + "\" contains invalid character (= or ; or \\0)"); 2739 return; 2740 } 2741 2742 put(key, value); 2743 } 2744 2745 /** 2746 * Sets an integer parameter. 2747 * 2748 * @param key the key name for the parameter 2749 * @param value the int value of the parameter 2750 */ set(String key, int value)2751 public void set(String key, int value) { 2752 put(key, Integer.toString(value)); 2753 } 2754 put(String key, String value)2755 private void put(String key, String value) { 2756 /* 2757 * Remove the key if it already exists. 2758 * 2759 * This way setting a new value for an already existing key will always move 2760 * that key to be ordered the latest in the map. 2761 */ 2762 mMap.remove(key); 2763 mMap.put(key, value); 2764 } 2765 set(String key, List<Area> areas)2766 private void set(String key, List<Area> areas) { 2767 if (areas == null) { 2768 set(key, "(0,0,0,0,0)"); 2769 } else { 2770 StringBuilder buffer = new StringBuilder(); 2771 for (int i = 0; i < areas.size(); i++) { 2772 Area area = areas.get(i); 2773 Rect rect = area.rect; 2774 buffer.append('('); 2775 buffer.append(rect.left); 2776 buffer.append(','); 2777 buffer.append(rect.top); 2778 buffer.append(','); 2779 buffer.append(rect.right); 2780 buffer.append(','); 2781 buffer.append(rect.bottom); 2782 buffer.append(','); 2783 buffer.append(area.weight); 2784 buffer.append(')'); 2785 if (i != areas.size() - 1) buffer.append(','); 2786 } 2787 set(key, buffer.toString()); 2788 } 2789 } 2790 2791 /** 2792 * Returns the value of a String parameter. 2793 * 2794 * @param key the key name for the parameter 2795 * @return the String value of the parameter 2796 */ get(String key)2797 public String get(String key) { 2798 return mMap.get(key); 2799 } 2800 2801 /** 2802 * Returns the value of an integer parameter. 2803 * 2804 * @param key the key name for the parameter 2805 * @return the int value of the parameter 2806 */ getInt(String key)2807 public int getInt(String key) { 2808 return Integer.parseInt(mMap.get(key)); 2809 } 2810 2811 /** 2812 * Sets the dimensions for preview pictures. If the preview has already 2813 * started, applications should stop the preview first before changing 2814 * preview size. 2815 * 2816 * The sides of width and height are based on camera orientation. That 2817 * is, the preview size is the size before it is rotated by display 2818 * orientation. So applications need to consider the display orientation 2819 * while setting preview size. For example, suppose the camera supports 2820 * both 480x320 and 320x480 preview sizes. The application wants a 3:2 2821 * preview ratio. If the display orientation is set to 0 or 180, preview 2822 * size should be set to 480x320. If the display orientation is set to 2823 * 90 or 270, preview size should be set to 320x480. The display 2824 * orientation should also be considered while setting picture size and 2825 * thumbnail size. 2826 * 2827 * Exception on 176x144 (QCIF) resolution: 2828 * Camera devices usually have a fixed capability for downscaling from 2829 * larger resolution to smaller, and the QCIF resolution sometimes 2830 * is not fully supported due to this limitation on devices with 2831 * high-resolution image sensors. Therefore, trying to configure a QCIF 2832 * preview size with any picture or video size larger than 1920x1080 2833 * (either width or height) might not be supported, and 2834 * {@link #setParameters(Camera.Parameters)} might throw a 2835 * RuntimeException if it is not. 2836 * 2837 * @param width the width of the pictures, in pixels 2838 * @param height the height of the pictures, in pixels 2839 * @see #setDisplayOrientation(int) 2840 * @see #getCameraInfo(int, CameraInfo) 2841 * @see #setPictureSize(int, int) 2842 * @see #setJpegThumbnailSize(int, int) 2843 */ setPreviewSize(int width, int height)2844 public void setPreviewSize(int width, int height) { 2845 String v = Integer.toString(width) + "x" + Integer.toString(height); 2846 set(KEY_PREVIEW_SIZE, v); 2847 } 2848 2849 /** 2850 * Returns the dimensions setting for preview pictures. 2851 * 2852 * @return a Size object with the width and height setting 2853 * for the preview picture 2854 */ getPreviewSize()2855 public Size getPreviewSize() { 2856 String pair = get(KEY_PREVIEW_SIZE); 2857 return strToSize(pair); 2858 } 2859 2860 /** 2861 * Gets the supported preview sizes. 2862 * 2863 * @return a list of Size object. This method will always return a list 2864 * with at least one element. 2865 */ getSupportedPreviewSizes()2866 public List<Size> getSupportedPreviewSizes() { 2867 String str = get(KEY_PREVIEW_SIZE + SUPPORTED_VALUES_SUFFIX); 2868 return splitSize(str); 2869 } 2870 2871 /** 2872 * <p>Gets the supported video frame sizes that can be used by 2873 * MediaRecorder.</p> 2874 * 2875 * <p>If the returned list is not null, the returned list will contain at 2876 * least one Size and one of the sizes in the returned list must be 2877 * passed to MediaRecorder.setVideoSize() for camcorder application if 2878 * camera is used as the video source. In this case, the size of the 2879 * preview can be different from the resolution of the recorded video 2880 * during video recording.</p> 2881 * 2882 * <p>Exception on 176x144 (QCIF) resolution: 2883 * Camera devices usually have a fixed capability for downscaling from 2884 * larger resolution to smaller, and the QCIF resolution sometimes 2885 * is not fully supported due to this limitation on devices with 2886 * high-resolution image sensors. Therefore, trying to configure a QCIF 2887 * video resolution with any preview or picture size larger than 2888 * 1920x1080 (either width or height) might not be supported, and 2889 * {@link #setParameters(Camera.Parameters)} will throw a 2890 * RuntimeException if it is not.</p> 2891 * 2892 * @return a list of Size object if camera has separate preview and 2893 * video output; otherwise, null is returned. 2894 * @see #getPreferredPreviewSizeForVideo() 2895 */ getSupportedVideoSizes()2896 public List<Size> getSupportedVideoSizes() { 2897 String str = get(KEY_VIDEO_SIZE + SUPPORTED_VALUES_SUFFIX); 2898 return splitSize(str); 2899 } 2900 2901 /** 2902 * Returns the preferred or recommended preview size (width and height) 2903 * in pixels for video recording. Camcorder applications should 2904 * set the preview size to a value that is not larger than the 2905 * preferred preview size. In other words, the product of the width 2906 * and height of the preview size should not be larger than that of 2907 * the preferred preview size. In addition, we recommend to choose a 2908 * preview size that has the same aspect ratio as the resolution of 2909 * video to be recorded. 2910 * 2911 * @return the preferred preview size (width and height) in pixels for 2912 * video recording if getSupportedVideoSizes() does not return 2913 * null; otherwise, null is returned. 2914 * @see #getSupportedVideoSizes() 2915 */ getPreferredPreviewSizeForVideo()2916 public Size getPreferredPreviewSizeForVideo() { 2917 String pair = get(KEY_PREFERRED_PREVIEW_SIZE_FOR_VIDEO); 2918 return strToSize(pair); 2919 } 2920 2921 /** 2922 * <p>Sets the dimensions for EXIF thumbnail in Jpeg picture. If 2923 * applications set both width and height to 0, EXIF will not contain 2924 * thumbnail.</p> 2925 * 2926 * <p>Applications need to consider the display orientation. See {@link 2927 * #setPreviewSize(int,int)} for reference.</p> 2928 * 2929 * @param width the width of the thumbnail, in pixels 2930 * @param height the height of the thumbnail, in pixels 2931 * @see #setPreviewSize(int,int) 2932 */ setJpegThumbnailSize(int width, int height)2933 public void setJpegThumbnailSize(int width, int height) { 2934 set(KEY_JPEG_THUMBNAIL_WIDTH, width); 2935 set(KEY_JPEG_THUMBNAIL_HEIGHT, height); 2936 } 2937 2938 /** 2939 * Returns the dimensions for EXIF thumbnail in Jpeg picture. 2940 * 2941 * @return a Size object with the height and width setting for the EXIF 2942 * thumbnails 2943 */ getJpegThumbnailSize()2944 public Size getJpegThumbnailSize() { 2945 return new Size(getInt(KEY_JPEG_THUMBNAIL_WIDTH), 2946 getInt(KEY_JPEG_THUMBNAIL_HEIGHT)); 2947 } 2948 2949 /** 2950 * Gets the supported jpeg thumbnail sizes. 2951 * 2952 * @return a list of Size object. This method will always return a list 2953 * with at least two elements. Size 0,0 (no thumbnail) is always 2954 * supported. 2955 */ getSupportedJpegThumbnailSizes()2956 public List<Size> getSupportedJpegThumbnailSizes() { 2957 String str = get(KEY_JPEG_THUMBNAIL_SIZE + SUPPORTED_VALUES_SUFFIX); 2958 return splitSize(str); 2959 } 2960 2961 /** 2962 * Sets the quality of the EXIF thumbnail in Jpeg picture. 2963 * 2964 * @param quality the JPEG quality of the EXIF thumbnail. The range is 1 2965 * to 100, with 100 being the best. 2966 */ setJpegThumbnailQuality(int quality)2967 public void setJpegThumbnailQuality(int quality) { 2968 set(KEY_JPEG_THUMBNAIL_QUALITY, quality); 2969 } 2970 2971 /** 2972 * Returns the quality setting for the EXIF thumbnail in Jpeg picture. 2973 * 2974 * @return the JPEG quality setting of the EXIF thumbnail. 2975 */ getJpegThumbnailQuality()2976 public int getJpegThumbnailQuality() { 2977 return getInt(KEY_JPEG_THUMBNAIL_QUALITY); 2978 } 2979 2980 /** 2981 * Sets Jpeg quality of captured picture. 2982 * 2983 * @param quality the JPEG quality of captured picture. The range is 1 2984 * to 100, with 100 being the best. 2985 */ setJpegQuality(int quality)2986 public void setJpegQuality(int quality) { 2987 set(KEY_JPEG_QUALITY, quality); 2988 } 2989 2990 /** 2991 * Returns the quality setting for the JPEG picture. 2992 * 2993 * @return the JPEG picture quality setting. 2994 */ getJpegQuality()2995 public int getJpegQuality() { 2996 return getInt(KEY_JPEG_QUALITY); 2997 } 2998 2999 /** 3000 * Sets the rate at which preview frames are received. This is the 3001 * target frame rate. The actual frame rate depends on the driver. 3002 * 3003 * @param fps the frame rate (frames per second) 3004 * @deprecated replaced by {@link #setPreviewFpsRange(int,int)} 3005 */ 3006 @Deprecated setPreviewFrameRate(int fps)3007 public void setPreviewFrameRate(int fps) { 3008 set(KEY_PREVIEW_FRAME_RATE, fps); 3009 } 3010 3011 /** 3012 * Returns the setting for the rate at which preview frames are 3013 * received. This is the target frame rate. The actual frame rate 3014 * depends on the driver. 3015 * 3016 * @return the frame rate setting (frames per second) 3017 * @deprecated replaced by {@link #getPreviewFpsRange(int[])} 3018 */ 3019 @Deprecated getPreviewFrameRate()3020 public int getPreviewFrameRate() { 3021 return getInt(KEY_PREVIEW_FRAME_RATE); 3022 } 3023 3024 /** 3025 * Gets the supported preview frame rates. 3026 * 3027 * @return a list of supported preview frame rates. null if preview 3028 * frame rate setting is not supported. 3029 * @deprecated replaced by {@link #getSupportedPreviewFpsRange()} 3030 */ 3031 @Deprecated getSupportedPreviewFrameRates()3032 public List<Integer> getSupportedPreviewFrameRates() { 3033 String str = get(KEY_PREVIEW_FRAME_RATE + SUPPORTED_VALUES_SUFFIX); 3034 return splitInt(str); 3035 } 3036 3037 /** 3038 * Sets the minimum and maximum preview fps. This controls the rate of 3039 * preview frames received in {@link PreviewCallback}. The minimum and 3040 * maximum preview fps must be one of the elements from {@link 3041 * #getSupportedPreviewFpsRange}. 3042 * 3043 * @param min the minimum preview fps (scaled by 1000). 3044 * @param max the maximum preview fps (scaled by 1000). 3045 * @throws RuntimeException if fps range is invalid. 3046 * @see #setPreviewCallbackWithBuffer(Camera.PreviewCallback) 3047 * @see #getSupportedPreviewFpsRange() 3048 */ setPreviewFpsRange(int min, int max)3049 public void setPreviewFpsRange(int min, int max) { 3050 set(KEY_PREVIEW_FPS_RANGE, "" + min + "," + max); 3051 } 3052 3053 /** 3054 * Returns the current minimum and maximum preview fps. The values are 3055 * one of the elements returned by {@link #getSupportedPreviewFpsRange}. 3056 * 3057 * @return range the minimum and maximum preview fps (scaled by 1000). 3058 * @see #PREVIEW_FPS_MIN_INDEX 3059 * @see #PREVIEW_FPS_MAX_INDEX 3060 * @see #getSupportedPreviewFpsRange() 3061 */ getPreviewFpsRange(int[] range)3062 public void getPreviewFpsRange(int[] range) { 3063 if (range == null || range.length != 2) { 3064 throw new IllegalArgumentException( 3065 "range must be an array with two elements."); 3066 } 3067 splitInt(get(KEY_PREVIEW_FPS_RANGE), range); 3068 } 3069 3070 /** 3071 * Gets the supported preview fps (frame-per-second) ranges. Each range 3072 * contains a minimum fps and maximum fps. If minimum fps equals to 3073 * maximum fps, the camera outputs frames in fixed frame rate. If not, 3074 * the camera outputs frames in auto frame rate. The actual frame rate 3075 * fluctuates between the minimum and the maximum. The values are 3076 * multiplied by 1000 and represented in integers. For example, if frame 3077 * rate is 26.623 frames per second, the value is 26623. 3078 * 3079 * @return a list of supported preview fps ranges. This method returns a 3080 * list with at least one element. Every element is an int array 3081 * of two values - minimum fps and maximum fps. The list is 3082 * sorted from small to large (first by maximum fps and then 3083 * minimum fps). 3084 * @see #PREVIEW_FPS_MIN_INDEX 3085 * @see #PREVIEW_FPS_MAX_INDEX 3086 */ getSupportedPreviewFpsRange()3087 public List<int[]> getSupportedPreviewFpsRange() { 3088 String str = get(KEY_PREVIEW_FPS_RANGE + SUPPORTED_VALUES_SUFFIX); 3089 return splitRange(str); 3090 } 3091 3092 /** 3093 * Sets the image format for preview pictures. 3094 * <p>If this is never called, the default format will be 3095 * {@link android.graphics.ImageFormat#NV21}, which 3096 * uses the NV21 encoding format.</p> 3097 * 3098 * <p>Use {@link Parameters#getSupportedPreviewFormats} to get a list of 3099 * the available preview formats. 3100 * 3101 * <p>It is strongly recommended that either 3102 * {@link android.graphics.ImageFormat#NV21} or 3103 * {@link android.graphics.ImageFormat#YV12} is used, since 3104 * they are supported by all camera devices.</p> 3105 * 3106 * <p>For YV12, the image buffer that is received is not necessarily 3107 * tightly packed, as there may be padding at the end of each row of 3108 * pixel data, as described in 3109 * {@link android.graphics.ImageFormat#YV12}. For camera callback data, 3110 * it can be assumed that the stride of the Y and UV data is the 3111 * smallest possible that meets the alignment requirements. That is, if 3112 * the preview size is <var>width x height</var>, then the following 3113 * equations describe the buffer index for the beginning of row 3114 * <var>y</var> for the Y plane and row <var>c</var> for the U and V 3115 * planes: 3116 * 3117 * <pre>{@code 3118 * yStride = (int) ceil(width / 16.0) * 16; 3119 * uvStride = (int) ceil( (yStride / 2) / 16.0) * 16; 3120 * ySize = yStride * height; 3121 * uvSize = uvStride * height / 2; 3122 * yRowIndex = yStride * y; 3123 * uRowIndex = ySize + uvSize + uvStride * c; 3124 * vRowIndex = ySize + uvStride * c; 3125 * size = ySize + uvSize * 2; 3126 * } 3127 *</pre> 3128 * 3129 * @param pixel_format the desired preview picture format, defined by 3130 * one of the {@link android.graphics.ImageFormat} constants. (E.g., 3131 * <var>ImageFormat.NV21</var> (default), or 3132 * <var>ImageFormat.YV12</var>) 3133 * 3134 * @see android.graphics.ImageFormat 3135 * @see android.hardware.Camera.Parameters#getSupportedPreviewFormats 3136 */ setPreviewFormat(int pixel_format)3137 public void setPreviewFormat(int pixel_format) { 3138 String s = cameraFormatForPixelFormat(pixel_format); 3139 if (s == null) { 3140 throw new IllegalArgumentException( 3141 "Invalid pixel_format=" + pixel_format); 3142 } 3143 3144 set(KEY_PREVIEW_FORMAT, s); 3145 } 3146 3147 /** 3148 * Returns the image format for preview frames got from 3149 * {@link PreviewCallback}. 3150 * 3151 * @return the preview format. 3152 * @see android.graphics.ImageFormat 3153 * @see #setPreviewFormat 3154 */ getPreviewFormat()3155 public int getPreviewFormat() { 3156 return pixelFormatForCameraFormat(get(KEY_PREVIEW_FORMAT)); 3157 } 3158 3159 /** 3160 * Gets the supported preview formats. {@link android.graphics.ImageFormat#NV21} 3161 * is always supported. {@link android.graphics.ImageFormat#YV12} 3162 * is always supported since API level 12. 3163 * 3164 * @return a list of supported preview formats. This method will always 3165 * return a list with at least one element. 3166 * @see android.graphics.ImageFormat 3167 * @see #setPreviewFormat 3168 */ getSupportedPreviewFormats()3169 public List<Integer> getSupportedPreviewFormats() { 3170 String str = get(KEY_PREVIEW_FORMAT + SUPPORTED_VALUES_SUFFIX); 3171 ArrayList<Integer> formats = new ArrayList<Integer>(); 3172 for (String s : split(str)) { 3173 int f = pixelFormatForCameraFormat(s); 3174 if (f == ImageFormat.UNKNOWN) continue; 3175 formats.add(f); 3176 } 3177 return formats; 3178 } 3179 3180 /** 3181 * <p>Sets the dimensions for pictures.</p> 3182 * 3183 * <p>Applications need to consider the display orientation. See {@link 3184 * #setPreviewSize(int,int)} for reference.</p> 3185 * 3186 * <p>Exception on 176x144 (QCIF) resolution: 3187 * Camera devices usually have a fixed capability for downscaling from 3188 * larger resolution to smaller, and the QCIF resolution sometimes 3189 * is not fully supported due to this limitation on devices with 3190 * high-resolution image sensors. Therefore, trying to configure a QCIF 3191 * picture size with any preview or video size larger than 1920x1080 3192 * (either width or height) might not be supported, and 3193 * {@link #setParameters(Camera.Parameters)} might throw a 3194 * RuntimeException if it is not.</p> 3195 * 3196 * @param width the width for pictures, in pixels 3197 * @param height the height for pictures, in pixels 3198 * @see #setPreviewSize(int,int) 3199 * 3200 */ setPictureSize(int width, int height)3201 public void setPictureSize(int width, int height) { 3202 String v = Integer.toString(width) + "x" + Integer.toString(height); 3203 set(KEY_PICTURE_SIZE, v); 3204 } 3205 3206 /** 3207 * Returns the dimension setting for pictures. 3208 * 3209 * @return a Size object with the height and width setting 3210 * for pictures 3211 */ getPictureSize()3212 public Size getPictureSize() { 3213 String pair = get(KEY_PICTURE_SIZE); 3214 return strToSize(pair); 3215 } 3216 3217 /** 3218 * Gets the supported picture sizes. 3219 * 3220 * @return a list of supported picture sizes. This method will always 3221 * return a list with at least one element. 3222 */ getSupportedPictureSizes()3223 public List<Size> getSupportedPictureSizes() { 3224 String str = get(KEY_PICTURE_SIZE + SUPPORTED_VALUES_SUFFIX); 3225 return splitSize(str); 3226 } 3227 3228 /** 3229 * Sets the image format for pictures. 3230 * 3231 * @param pixel_format the desired picture format 3232 * (<var>ImageFormat.NV21</var>, 3233 * <var>ImageFormat.RGB_565</var>, or 3234 * <var>ImageFormat.JPEG</var>) 3235 * @see android.graphics.ImageFormat 3236 */ setPictureFormat(int pixel_format)3237 public void setPictureFormat(int pixel_format) { 3238 String s = cameraFormatForPixelFormat(pixel_format); 3239 if (s == null) { 3240 throw new IllegalArgumentException( 3241 "Invalid pixel_format=" + pixel_format); 3242 } 3243 3244 set(KEY_PICTURE_FORMAT, s); 3245 } 3246 3247 /** 3248 * Returns the image format for pictures. 3249 * 3250 * @return the picture format 3251 * @see android.graphics.ImageFormat 3252 */ getPictureFormat()3253 public int getPictureFormat() { 3254 return pixelFormatForCameraFormat(get(KEY_PICTURE_FORMAT)); 3255 } 3256 3257 /** 3258 * Gets the supported picture formats. 3259 * 3260 * @return supported picture formats. This method will always return a 3261 * list with at least one element. 3262 * @see android.graphics.ImageFormat 3263 */ getSupportedPictureFormats()3264 public List<Integer> getSupportedPictureFormats() { 3265 String str = get(KEY_PICTURE_FORMAT + SUPPORTED_VALUES_SUFFIX); 3266 ArrayList<Integer> formats = new ArrayList<Integer>(); 3267 for (String s : split(str)) { 3268 int f = pixelFormatForCameraFormat(s); 3269 if (f == ImageFormat.UNKNOWN) continue; 3270 formats.add(f); 3271 } 3272 return formats; 3273 } 3274 cameraFormatForPixelFormat(int pixel_format)3275 private String cameraFormatForPixelFormat(int pixel_format) { 3276 switch(pixel_format) { 3277 case ImageFormat.NV16: return PIXEL_FORMAT_YUV422SP; 3278 case ImageFormat.NV21: return PIXEL_FORMAT_YUV420SP; 3279 case ImageFormat.YUY2: return PIXEL_FORMAT_YUV422I; 3280 case ImageFormat.YV12: return PIXEL_FORMAT_YUV420P; 3281 case ImageFormat.RGB_565: return PIXEL_FORMAT_RGB565; 3282 case ImageFormat.JPEG: return PIXEL_FORMAT_JPEG; 3283 default: return null; 3284 } 3285 } 3286 pixelFormatForCameraFormat(String format)3287 private int pixelFormatForCameraFormat(String format) { 3288 if (format == null) 3289 return ImageFormat.UNKNOWN; 3290 3291 if (format.equals(PIXEL_FORMAT_YUV422SP)) 3292 return ImageFormat.NV16; 3293 3294 if (format.equals(PIXEL_FORMAT_YUV420SP)) 3295 return ImageFormat.NV21; 3296 3297 if (format.equals(PIXEL_FORMAT_YUV422I)) 3298 return ImageFormat.YUY2; 3299 3300 if (format.equals(PIXEL_FORMAT_YUV420P)) 3301 return ImageFormat.YV12; 3302 3303 if (format.equals(PIXEL_FORMAT_RGB565)) 3304 return ImageFormat.RGB_565; 3305 3306 if (format.equals(PIXEL_FORMAT_JPEG)) 3307 return ImageFormat.JPEG; 3308 3309 return ImageFormat.UNKNOWN; 3310 } 3311 3312 /** 3313 * Sets the clockwise rotation angle in degrees relative to the 3314 * orientation of the camera. This affects the pictures returned from 3315 * JPEG {@link PictureCallback}. The camera driver may set orientation 3316 * in the EXIF header without rotating the picture. Or the driver may 3317 * rotate the picture and the EXIF thumbnail. If the Jpeg picture is 3318 * rotated, the orientation in the EXIF header will be missing or 1 (row 3319 * #0 is top and column #0 is left side). 3320 * 3321 * <p> 3322 * If applications want to rotate the picture to match the orientation 3323 * of what users see, apps should use 3324 * {@link android.view.OrientationEventListener} and 3325 * {@link android.hardware.Camera.CameraInfo}. The value from 3326 * OrientationEventListener is relative to the natural orientation of 3327 * the device. CameraInfo.orientation is the angle between camera 3328 * orientation and natural device orientation. The sum of the two is the 3329 * rotation angle for back-facing camera. The difference of the two is 3330 * the rotation angle for front-facing camera. Note that the JPEG 3331 * pictures of front-facing cameras are not mirrored as in preview 3332 * display. 3333 * 3334 * <p> 3335 * For example, suppose the natural orientation of the device is 3336 * portrait. The device is rotated 270 degrees clockwise, so the device 3337 * orientation is 270. Suppose a back-facing camera sensor is mounted in 3338 * landscape and the top side of the camera sensor is aligned with the 3339 * right edge of the display in natural orientation. So the camera 3340 * orientation is 90. The rotation should be set to 0 (270 + 90). 3341 * 3342 * <p>The reference code is as follows. 3343 * 3344 * <pre> 3345 * public void onOrientationChanged(int orientation) { 3346 * if (orientation == ORIENTATION_UNKNOWN) return; 3347 * android.hardware.Camera.CameraInfo info = 3348 * new android.hardware.Camera.CameraInfo(); 3349 * android.hardware.Camera.getCameraInfo(cameraId, info); 3350 * orientation = (orientation + 45) / 90 * 90; 3351 * int rotation = 0; 3352 * if (info.facing == CameraInfo.CAMERA_FACING_FRONT) { 3353 * rotation = (info.orientation - orientation + 360) % 360; 3354 * } else { // back-facing camera 3355 * rotation = (info.orientation + orientation) % 360; 3356 * } 3357 * mParameters.setRotation(rotation); 3358 * } 3359 * </pre> 3360 * 3361 * @param rotation The rotation angle in degrees relative to the 3362 * orientation of the camera. Rotation can only be 0, 3363 * 90, 180 or 270. 3364 * @throws IllegalArgumentException if rotation value is invalid. 3365 * @see android.view.OrientationEventListener 3366 * @see #getCameraInfo(int, CameraInfo) 3367 */ setRotation(int rotation)3368 public void setRotation(int rotation) { 3369 if (rotation == 0 || rotation == 90 || rotation == 180 3370 || rotation == 270) { 3371 set(KEY_ROTATION, Integer.toString(rotation)); 3372 } else { 3373 throw new IllegalArgumentException( 3374 "Invalid rotation=" + rotation); 3375 } 3376 } 3377 3378 /** 3379 * Sets GPS latitude coordinate. This will be stored in JPEG EXIF 3380 * header. 3381 * 3382 * @param latitude GPS latitude coordinate. 3383 */ setGpsLatitude(double latitude)3384 public void setGpsLatitude(double latitude) { 3385 set(KEY_GPS_LATITUDE, Double.toString(latitude)); 3386 } 3387 3388 /** 3389 * Sets GPS longitude coordinate. This will be stored in JPEG EXIF 3390 * header. 3391 * 3392 * @param longitude GPS longitude coordinate. 3393 */ setGpsLongitude(double longitude)3394 public void setGpsLongitude(double longitude) { 3395 set(KEY_GPS_LONGITUDE, Double.toString(longitude)); 3396 } 3397 3398 /** 3399 * Sets GPS altitude. This will be stored in JPEG EXIF header. 3400 * 3401 * @param altitude GPS altitude in meters. 3402 */ setGpsAltitude(double altitude)3403 public void setGpsAltitude(double altitude) { 3404 set(KEY_GPS_ALTITUDE, Double.toString(altitude)); 3405 } 3406 3407 /** 3408 * Sets GPS timestamp. This will be stored in JPEG EXIF header. 3409 * 3410 * @param timestamp GPS timestamp (UTC in seconds since January 1, 3411 * 1970). 3412 */ setGpsTimestamp(long timestamp)3413 public void setGpsTimestamp(long timestamp) { 3414 set(KEY_GPS_TIMESTAMP, Long.toString(timestamp)); 3415 } 3416 3417 /** 3418 * Sets GPS processing method. The method will be stored in a UTF-8 string up to 31 bytes 3419 * long, in the JPEG EXIF header. 3420 * 3421 * @param processing_method The processing method to get this location. 3422 */ setGpsProcessingMethod(String processing_method)3423 public void setGpsProcessingMethod(String processing_method) { 3424 set(KEY_GPS_PROCESSING_METHOD, processing_method); 3425 } 3426 3427 /** 3428 * Removes GPS latitude, longitude, altitude, and timestamp from the 3429 * parameters. 3430 */ removeGpsData()3431 public void removeGpsData() { 3432 remove(KEY_GPS_LATITUDE); 3433 remove(KEY_GPS_LONGITUDE); 3434 remove(KEY_GPS_ALTITUDE); 3435 remove(KEY_GPS_TIMESTAMP); 3436 remove(KEY_GPS_PROCESSING_METHOD); 3437 } 3438 3439 /** 3440 * Gets the current white balance setting. 3441 * 3442 * @return current white balance. null if white balance setting is not 3443 * supported. 3444 * @see #WHITE_BALANCE_AUTO 3445 * @see #WHITE_BALANCE_INCANDESCENT 3446 * @see #WHITE_BALANCE_FLUORESCENT 3447 * @see #WHITE_BALANCE_WARM_FLUORESCENT 3448 * @see #WHITE_BALANCE_DAYLIGHT 3449 * @see #WHITE_BALANCE_CLOUDY_DAYLIGHT 3450 * @see #WHITE_BALANCE_TWILIGHT 3451 * @see #WHITE_BALANCE_SHADE 3452 * 3453 */ getWhiteBalance()3454 public String getWhiteBalance() { 3455 return get(KEY_WHITE_BALANCE); 3456 } 3457 3458 /** 3459 * Sets the white balance. Changing the setting will release the 3460 * auto-white balance lock. It is recommended not to change white 3461 * balance and AWB lock at the same time. 3462 * 3463 * @param value new white balance. 3464 * @see #getWhiteBalance() 3465 * @see #setAutoWhiteBalanceLock(boolean) 3466 */ setWhiteBalance(String value)3467 public void setWhiteBalance(String value) { 3468 String oldValue = get(KEY_WHITE_BALANCE); 3469 if (same(value, oldValue)) return; 3470 set(KEY_WHITE_BALANCE, value); 3471 set(KEY_AUTO_WHITEBALANCE_LOCK, FALSE); 3472 } 3473 3474 /** 3475 * Gets the supported white balance. 3476 * 3477 * @return a list of supported white balance. null if white balance 3478 * setting is not supported. 3479 * @see #getWhiteBalance() 3480 */ getSupportedWhiteBalance()3481 public List<String> getSupportedWhiteBalance() { 3482 String str = get(KEY_WHITE_BALANCE + SUPPORTED_VALUES_SUFFIX); 3483 return split(str); 3484 } 3485 3486 /** 3487 * Gets the current color effect setting. 3488 * 3489 * @return current color effect. null if color effect 3490 * setting is not supported. 3491 * @see #EFFECT_NONE 3492 * @see #EFFECT_MONO 3493 * @see #EFFECT_NEGATIVE 3494 * @see #EFFECT_SOLARIZE 3495 * @see #EFFECT_SEPIA 3496 * @see #EFFECT_POSTERIZE 3497 * @see #EFFECT_WHITEBOARD 3498 * @see #EFFECT_BLACKBOARD 3499 * @see #EFFECT_AQUA 3500 */ getColorEffect()3501 public String getColorEffect() { 3502 return get(KEY_EFFECT); 3503 } 3504 3505 /** 3506 * Sets the current color effect setting. 3507 * 3508 * @param value new color effect. 3509 * @see #getColorEffect() 3510 */ setColorEffect(String value)3511 public void setColorEffect(String value) { 3512 set(KEY_EFFECT, value); 3513 } 3514 3515 /** 3516 * Gets the supported color effects. 3517 * 3518 * @return a list of supported color effects. null if color effect 3519 * setting is not supported. 3520 * @see #getColorEffect() 3521 */ getSupportedColorEffects()3522 public List<String> getSupportedColorEffects() { 3523 String str = get(KEY_EFFECT + SUPPORTED_VALUES_SUFFIX); 3524 return split(str); 3525 } 3526 3527 3528 /** 3529 * Gets the current antibanding setting. 3530 * 3531 * @return current antibanding. null if antibanding setting is not 3532 * supported. 3533 * @see #ANTIBANDING_AUTO 3534 * @see #ANTIBANDING_50HZ 3535 * @see #ANTIBANDING_60HZ 3536 * @see #ANTIBANDING_OFF 3537 */ getAntibanding()3538 public String getAntibanding() { 3539 return get(KEY_ANTIBANDING); 3540 } 3541 3542 /** 3543 * Sets the antibanding. 3544 * 3545 * @param antibanding new antibanding value. 3546 * @see #getAntibanding() 3547 */ setAntibanding(String antibanding)3548 public void setAntibanding(String antibanding) { 3549 set(KEY_ANTIBANDING, antibanding); 3550 } 3551 3552 /** 3553 * Gets the supported antibanding values. 3554 * 3555 * @return a list of supported antibanding values. null if antibanding 3556 * setting is not supported. 3557 * @see #getAntibanding() 3558 */ getSupportedAntibanding()3559 public List<String> getSupportedAntibanding() { 3560 String str = get(KEY_ANTIBANDING + SUPPORTED_VALUES_SUFFIX); 3561 return split(str); 3562 } 3563 3564 /** 3565 * Gets the current scene mode setting. 3566 * 3567 * @return one of SCENE_MODE_XXX string constant. null if scene mode 3568 * setting is not supported. 3569 * @see #SCENE_MODE_AUTO 3570 * @see #SCENE_MODE_ACTION 3571 * @see #SCENE_MODE_PORTRAIT 3572 * @see #SCENE_MODE_LANDSCAPE 3573 * @see #SCENE_MODE_NIGHT 3574 * @see #SCENE_MODE_NIGHT_PORTRAIT 3575 * @see #SCENE_MODE_THEATRE 3576 * @see #SCENE_MODE_BEACH 3577 * @see #SCENE_MODE_SNOW 3578 * @see #SCENE_MODE_SUNSET 3579 * @see #SCENE_MODE_STEADYPHOTO 3580 * @see #SCENE_MODE_FIREWORKS 3581 * @see #SCENE_MODE_SPORTS 3582 * @see #SCENE_MODE_PARTY 3583 * @see #SCENE_MODE_CANDLELIGHT 3584 * @see #SCENE_MODE_BARCODE 3585 */ getSceneMode()3586 public String getSceneMode() { 3587 return get(KEY_SCENE_MODE); 3588 } 3589 3590 /** 3591 * Sets the scene mode. Changing scene mode may override other 3592 * parameters (such as flash mode, focus mode, white balance). For 3593 * example, suppose originally flash mode is on and supported flash 3594 * modes are on/off. In night scene mode, both flash mode and supported 3595 * flash mode may be changed to off. After setting scene mode, 3596 * applications should call getParameters to know if some parameters are 3597 * changed. 3598 * 3599 * @param value scene mode. 3600 * @see #getSceneMode() 3601 */ setSceneMode(String value)3602 public void setSceneMode(String value) { 3603 set(KEY_SCENE_MODE, value); 3604 } 3605 3606 /** 3607 * Gets the supported scene modes. 3608 * 3609 * @return a list of supported scene modes. null if scene mode setting 3610 * is not supported. 3611 * @see #getSceneMode() 3612 */ getSupportedSceneModes()3613 public List<String> getSupportedSceneModes() { 3614 String str = get(KEY_SCENE_MODE + SUPPORTED_VALUES_SUFFIX); 3615 return split(str); 3616 } 3617 3618 /** 3619 * Gets the current flash mode setting. 3620 * 3621 * @return current flash mode. null if flash mode setting is not 3622 * supported. 3623 * @see #FLASH_MODE_OFF 3624 * @see #FLASH_MODE_AUTO 3625 * @see #FLASH_MODE_ON 3626 * @see #FLASH_MODE_RED_EYE 3627 * @see #FLASH_MODE_TORCH 3628 */ getFlashMode()3629 public String getFlashMode() { 3630 return get(KEY_FLASH_MODE); 3631 } 3632 3633 /** 3634 * Sets the flash mode. 3635 * 3636 * @param value flash mode. 3637 * @see #getFlashMode() 3638 */ setFlashMode(String value)3639 public void setFlashMode(String value) { 3640 set(KEY_FLASH_MODE, value); 3641 } 3642 3643 /** 3644 * Gets the supported flash modes. 3645 * 3646 * @return a list of supported flash modes. null if flash mode setting 3647 * is not supported. 3648 * @see #getFlashMode() 3649 */ getSupportedFlashModes()3650 public List<String> getSupportedFlashModes() { 3651 String str = get(KEY_FLASH_MODE + SUPPORTED_VALUES_SUFFIX); 3652 return split(str); 3653 } 3654 3655 /** 3656 * Gets the current focus mode setting. 3657 * 3658 * @return current focus mode. This method will always return a non-null 3659 * value. Applications should call {@link 3660 * #autoFocus(AutoFocusCallback)} to start the focus if focus 3661 * mode is FOCUS_MODE_AUTO or FOCUS_MODE_MACRO. 3662 * @see #FOCUS_MODE_AUTO 3663 * @see #FOCUS_MODE_INFINITY 3664 * @see #FOCUS_MODE_MACRO 3665 * @see #FOCUS_MODE_FIXED 3666 * @see #FOCUS_MODE_EDOF 3667 * @see #FOCUS_MODE_CONTINUOUS_VIDEO 3668 */ getFocusMode()3669 public String getFocusMode() { 3670 return get(KEY_FOCUS_MODE); 3671 } 3672 3673 /** 3674 * Sets the focus mode. 3675 * 3676 * @param value focus mode. 3677 * @see #getFocusMode() 3678 */ setFocusMode(String value)3679 public void setFocusMode(String value) { 3680 set(KEY_FOCUS_MODE, value); 3681 } 3682 3683 /** 3684 * Gets the supported focus modes. 3685 * 3686 * @return a list of supported focus modes. This method will always 3687 * return a list with at least one element. 3688 * @see #getFocusMode() 3689 */ getSupportedFocusModes()3690 public List<String> getSupportedFocusModes() { 3691 String str = get(KEY_FOCUS_MODE + SUPPORTED_VALUES_SUFFIX); 3692 return split(str); 3693 } 3694 3695 /** 3696 * Gets the focal length (in millimeter) of the camera. 3697 * 3698 * @return the focal length. Returns -1.0 when the device 3699 * doesn't report focal length information. 3700 */ getFocalLength()3701 public float getFocalLength() { 3702 return Float.parseFloat(get(KEY_FOCAL_LENGTH)); 3703 } 3704 3705 /** 3706 * Gets the horizontal angle of view in degrees. 3707 * 3708 * @return horizontal angle of view. Returns -1.0 when the device 3709 * doesn't report view angle information. 3710 */ getHorizontalViewAngle()3711 public float getHorizontalViewAngle() { 3712 return Float.parseFloat(get(KEY_HORIZONTAL_VIEW_ANGLE)); 3713 } 3714 3715 /** 3716 * Gets the vertical angle of view in degrees. 3717 * 3718 * @return vertical angle of view. Returns -1.0 when the device 3719 * doesn't report view angle information. 3720 */ getVerticalViewAngle()3721 public float getVerticalViewAngle() { 3722 return Float.parseFloat(get(KEY_VERTICAL_VIEW_ANGLE)); 3723 } 3724 3725 /** 3726 * Gets the current exposure compensation index. 3727 * 3728 * @return current exposure compensation index. The range is {@link 3729 * #getMinExposureCompensation} to {@link 3730 * #getMaxExposureCompensation}. 0 means exposure is not 3731 * adjusted. 3732 */ getExposureCompensation()3733 public int getExposureCompensation() { 3734 return getInt(KEY_EXPOSURE_COMPENSATION, 0); 3735 } 3736 3737 /** 3738 * Sets the exposure compensation index. 3739 * 3740 * @param value exposure compensation index. The valid value range is 3741 * from {@link #getMinExposureCompensation} (inclusive) to {@link 3742 * #getMaxExposureCompensation} (inclusive). 0 means exposure is 3743 * not adjusted. Application should call 3744 * getMinExposureCompensation and getMaxExposureCompensation to 3745 * know if exposure compensation is supported. 3746 */ setExposureCompensation(int value)3747 public void setExposureCompensation(int value) { 3748 set(KEY_EXPOSURE_COMPENSATION, value); 3749 } 3750 3751 /** 3752 * Gets the maximum exposure compensation index. 3753 * 3754 * @return maximum exposure compensation index (>=0). If both this 3755 * method and {@link #getMinExposureCompensation} return 0, 3756 * exposure compensation is not supported. 3757 */ getMaxExposureCompensation()3758 public int getMaxExposureCompensation() { 3759 return getInt(KEY_MAX_EXPOSURE_COMPENSATION, 0); 3760 } 3761 3762 /** 3763 * Gets the minimum exposure compensation index. 3764 * 3765 * @return minimum exposure compensation index (<=0). If both this 3766 * method and {@link #getMaxExposureCompensation} return 0, 3767 * exposure compensation is not supported. 3768 */ getMinExposureCompensation()3769 public int getMinExposureCompensation() { 3770 return getInt(KEY_MIN_EXPOSURE_COMPENSATION, 0); 3771 } 3772 3773 /** 3774 * Gets the exposure compensation step. 3775 * 3776 * @return exposure compensation step. Applications can get EV by 3777 * multiplying the exposure compensation index and step. Ex: if 3778 * exposure compensation index is -6 and step is 0.333333333, EV 3779 * is -2. 3780 */ getExposureCompensationStep()3781 public float getExposureCompensationStep() { 3782 return getFloat(KEY_EXPOSURE_COMPENSATION_STEP, 0); 3783 } 3784 3785 /** 3786 * <p>Sets the auto-exposure lock state. Applications should check 3787 * {@link #isAutoExposureLockSupported} before using this method.</p> 3788 * 3789 * <p>If set to true, the camera auto-exposure routine will immediately 3790 * pause until the lock is set to false. Exposure compensation settings 3791 * changes will still take effect while auto-exposure is locked.</p> 3792 * 3793 * <p>If auto-exposure is already locked, setting this to true again has 3794 * no effect (the driver will not recalculate exposure values).</p> 3795 * 3796 * <p>Stopping preview with {@link #stopPreview()}, or triggering still 3797 * image capture with {@link #takePicture(Camera.ShutterCallback, 3798 * Camera.PictureCallback, Camera.PictureCallback)}, will not change the 3799 * lock.</p> 3800 * 3801 * <p>Exposure compensation, auto-exposure lock, and auto-white balance 3802 * lock can be used to capture an exposure-bracketed burst of images, 3803 * for example.</p> 3804 * 3805 * <p>Auto-exposure state, including the lock state, will not be 3806 * maintained after camera {@link #release()} is called. Locking 3807 * auto-exposure after {@link #open()} but before the first call to 3808 * {@link #startPreview()} will not allow the auto-exposure routine to 3809 * run at all, and may result in severely over- or under-exposed 3810 * images.</p> 3811 * 3812 * @param toggle new state of the auto-exposure lock. True means that 3813 * auto-exposure is locked, false means that the auto-exposure 3814 * routine is free to run normally. 3815 * 3816 * @see #getAutoExposureLock() 3817 */ setAutoExposureLock(boolean toggle)3818 public void setAutoExposureLock(boolean toggle) { 3819 set(KEY_AUTO_EXPOSURE_LOCK, toggle ? TRUE : FALSE); 3820 } 3821 3822 /** 3823 * Gets the state of the auto-exposure lock. Applications should check 3824 * {@link #isAutoExposureLockSupported} before using this method. See 3825 * {@link #setAutoExposureLock} for details about the lock. 3826 * 3827 * @return State of the auto-exposure lock. Returns true if 3828 * auto-exposure is currently locked, and false otherwise. 3829 * 3830 * @see #setAutoExposureLock(boolean) 3831 * 3832 */ getAutoExposureLock()3833 public boolean getAutoExposureLock() { 3834 String str = get(KEY_AUTO_EXPOSURE_LOCK); 3835 return TRUE.equals(str); 3836 } 3837 3838 /** 3839 * Returns true if auto-exposure locking is supported. Applications 3840 * should call this before trying to lock auto-exposure. See 3841 * {@link #setAutoExposureLock} for details about the lock. 3842 * 3843 * @return true if auto-exposure lock is supported. 3844 * @see #setAutoExposureLock(boolean) 3845 * 3846 */ isAutoExposureLockSupported()3847 public boolean isAutoExposureLockSupported() { 3848 String str = get(KEY_AUTO_EXPOSURE_LOCK_SUPPORTED); 3849 return TRUE.equals(str); 3850 } 3851 3852 /** 3853 * <p>Sets the auto-white balance lock state. Applications should check 3854 * {@link #isAutoWhiteBalanceLockSupported} before using this 3855 * method.</p> 3856 * 3857 * <p>If set to true, the camera auto-white balance routine will 3858 * immediately pause until the lock is set to false.</p> 3859 * 3860 * <p>If auto-white balance is already locked, setting this to true 3861 * again has no effect (the driver will not recalculate white balance 3862 * values).</p> 3863 * 3864 * <p>Stopping preview with {@link #stopPreview()}, or triggering still 3865 * image capture with {@link #takePicture(Camera.ShutterCallback, 3866 * Camera.PictureCallback, Camera.PictureCallback)}, will not change the 3867 * the lock.</p> 3868 * 3869 * <p> Changing the white balance mode with {@link #setWhiteBalance} 3870 * will release the auto-white balance lock if it is set.</p> 3871 * 3872 * <p>Exposure compensation, AE lock, and AWB lock can be used to 3873 * capture an exposure-bracketed burst of images, for example. 3874 * Auto-white balance state, including the lock state, will not be 3875 * maintained after camera {@link #release()} is called. Locking 3876 * auto-white balance after {@link #open()} but before the first call to 3877 * {@link #startPreview()} will not allow the auto-white balance routine 3878 * to run at all, and may result in severely incorrect color in captured 3879 * images.</p> 3880 * 3881 * @param toggle new state of the auto-white balance lock. True means 3882 * that auto-white balance is locked, false means that the 3883 * auto-white balance routine is free to run normally. 3884 * 3885 * @see #getAutoWhiteBalanceLock() 3886 * @see #setWhiteBalance(String) 3887 */ setAutoWhiteBalanceLock(boolean toggle)3888 public void setAutoWhiteBalanceLock(boolean toggle) { 3889 set(KEY_AUTO_WHITEBALANCE_LOCK, toggle ? TRUE : FALSE); 3890 } 3891 3892 /** 3893 * Gets the state of the auto-white balance lock. Applications should 3894 * check {@link #isAutoWhiteBalanceLockSupported} before using this 3895 * method. See {@link #setAutoWhiteBalanceLock} for details about the 3896 * lock. 3897 * 3898 * @return State of the auto-white balance lock. Returns true if 3899 * auto-white balance is currently locked, and false 3900 * otherwise. 3901 * 3902 * @see #setAutoWhiteBalanceLock(boolean) 3903 * 3904 */ getAutoWhiteBalanceLock()3905 public boolean getAutoWhiteBalanceLock() { 3906 String str = get(KEY_AUTO_WHITEBALANCE_LOCK); 3907 return TRUE.equals(str); 3908 } 3909 3910 /** 3911 * Returns true if auto-white balance locking is supported. Applications 3912 * should call this before trying to lock auto-white balance. See 3913 * {@link #setAutoWhiteBalanceLock} for details about the lock. 3914 * 3915 * @return true if auto-white balance lock is supported. 3916 * @see #setAutoWhiteBalanceLock(boolean) 3917 * 3918 */ isAutoWhiteBalanceLockSupported()3919 public boolean isAutoWhiteBalanceLockSupported() { 3920 String str = get(KEY_AUTO_WHITEBALANCE_LOCK_SUPPORTED); 3921 return TRUE.equals(str); 3922 } 3923 3924 /** 3925 * Gets current zoom value. This also works when smooth zoom is in 3926 * progress. Applications should check {@link #isZoomSupported} before 3927 * using this method. 3928 * 3929 * @return the current zoom value. The range is 0 to {@link 3930 * #getMaxZoom}. 0 means the camera is not zoomed. 3931 */ getZoom()3932 public int getZoom() { 3933 return getInt(KEY_ZOOM, 0); 3934 } 3935 3936 /** 3937 * Sets current zoom value. If the camera is zoomed (value > 0), the 3938 * actual picture size may be smaller than picture size setting. 3939 * Applications can check the actual picture size after picture is 3940 * returned from {@link PictureCallback}. The preview size remains the 3941 * same in zoom. Applications should check {@link #isZoomSupported} 3942 * before using this method. 3943 * 3944 * @param value zoom value. The valid range is 0 to {@link #getMaxZoom}. 3945 */ setZoom(int value)3946 public void setZoom(int value) { 3947 set(KEY_ZOOM, value); 3948 } 3949 3950 /** 3951 * Returns true if zoom is supported. Applications should call this 3952 * before using other zoom methods. 3953 * 3954 * @return true if zoom is supported. 3955 */ isZoomSupported()3956 public boolean isZoomSupported() { 3957 String str = get(KEY_ZOOM_SUPPORTED); 3958 return TRUE.equals(str); 3959 } 3960 3961 /** 3962 * Gets the maximum zoom value allowed for snapshot. This is the maximum 3963 * value that applications can set to {@link #setZoom(int)}. 3964 * Applications should call {@link #isZoomSupported} before using this 3965 * method. This value may change in different preview size. Applications 3966 * should call this again after setting preview size. 3967 * 3968 * @return the maximum zoom value supported by the camera. 3969 */ getMaxZoom()3970 public int getMaxZoom() { 3971 return getInt(KEY_MAX_ZOOM, 0); 3972 } 3973 3974 /** 3975 * Gets the zoom ratios of all zoom values. Applications should check 3976 * {@link #isZoomSupported} before using this method. 3977 * 3978 * @return the zoom ratios in 1/100 increments. Ex: a zoom of 3.2x is 3979 * returned as 320. The number of elements is {@link 3980 * #getMaxZoom} + 1. The list is sorted from small to large. The 3981 * first element is always 100. The last element is the zoom 3982 * ratio of the maximum zoom value. 3983 */ getZoomRatios()3984 public List<Integer> getZoomRatios() { 3985 return splitInt(get(KEY_ZOOM_RATIOS)); 3986 } 3987 3988 /** 3989 * Returns true if smooth zoom is supported. Applications should call 3990 * this before using other smooth zoom methods. 3991 * 3992 * @return true if smooth zoom is supported. 3993 */ isSmoothZoomSupported()3994 public boolean isSmoothZoomSupported() { 3995 String str = get(KEY_SMOOTH_ZOOM_SUPPORTED); 3996 return TRUE.equals(str); 3997 } 3998 3999 /** 4000 * <p>Gets the distances from the camera to where an object appears to be 4001 * in focus. The object is sharpest at the optimal focus distance. The 4002 * depth of field is the far focus distance minus near focus distance.</p> 4003 * 4004 * <p>Focus distances may change after calling {@link 4005 * #autoFocus(AutoFocusCallback)}, {@link #cancelAutoFocus}, or {@link 4006 * #startPreview()}. Applications can call {@link #getParameters()} 4007 * and this method anytime to get the latest focus distances. If the 4008 * focus mode is FOCUS_MODE_CONTINUOUS_VIDEO, focus distances may change 4009 * from time to time.</p> 4010 * 4011 * <p>This method is intended to estimate the distance between the camera 4012 * and the subject. After autofocus, the subject distance may be within 4013 * near and far focus distance. However, the precision depends on the 4014 * camera hardware, autofocus algorithm, the focus area, and the scene. 4015 * The error can be large and it should be only used as a reference.</p> 4016 * 4017 * <p>Far focus distance >= optimal focus distance >= near focus distance. 4018 * If the focus distance is infinity, the value will be 4019 * {@code Float.POSITIVE_INFINITY}.</p> 4020 * 4021 * @param output focus distances in meters. output must be a float 4022 * array with three elements. Near focus distance, optimal focus 4023 * distance, and far focus distance will be filled in the array. 4024 * @see #FOCUS_DISTANCE_NEAR_INDEX 4025 * @see #FOCUS_DISTANCE_OPTIMAL_INDEX 4026 * @see #FOCUS_DISTANCE_FAR_INDEX 4027 */ getFocusDistances(float[] output)4028 public void getFocusDistances(float[] output) { 4029 if (output == null || output.length != 3) { 4030 throw new IllegalArgumentException( 4031 "output must be a float array with three elements."); 4032 } 4033 splitFloat(get(KEY_FOCUS_DISTANCES), output); 4034 } 4035 4036 /** 4037 * Gets the maximum number of focus areas supported. This is the maximum 4038 * length of the list in {@link #setFocusAreas(List)} and 4039 * {@link #getFocusAreas()}. 4040 * 4041 * @return the maximum number of focus areas supported by the camera. 4042 * @see #getFocusAreas() 4043 */ getMaxNumFocusAreas()4044 public int getMaxNumFocusAreas() { 4045 return getInt(KEY_MAX_NUM_FOCUS_AREAS, 0); 4046 } 4047 4048 /** 4049 * <p>Gets the current focus areas. Camera driver uses the areas to decide 4050 * focus.</p> 4051 * 4052 * <p>Before using this API or {@link #setFocusAreas(List)}, apps should 4053 * call {@link #getMaxNumFocusAreas()} to know the maximum number of 4054 * focus areas first. If the value is 0, focus area is not supported.</p> 4055 * 4056 * <p>Each focus area is a rectangle with specified weight. The direction 4057 * is relative to the sensor orientation, that is, what the sensor sees. 4058 * The direction is not affected by the rotation or mirroring of 4059 * {@link #setDisplayOrientation(int)}. Coordinates of the rectangle 4060 * range from -1000 to 1000. (-1000, -1000) is the upper left point. 4061 * (1000, 1000) is the lower right point. The width and height of focus 4062 * areas cannot be 0 or negative.</p> 4063 * 4064 * <p>The weight must range from 1 to 1000. The weight should be 4065 * interpreted as a per-pixel weight - all pixels in the area have the 4066 * specified weight. This means a small area with the same weight as a 4067 * larger area will have less influence on the focusing than the larger 4068 * area. Focus areas can partially overlap and the driver will add the 4069 * weights in the overlap region.</p> 4070 * 4071 * <p>A special case of a {@code null} focus area list means the driver is 4072 * free to select focus targets as it wants. For example, the driver may 4073 * use more signals to select focus areas and change them 4074 * dynamically. Apps can set the focus area list to {@code null} if they 4075 * want the driver to completely control focusing.</p> 4076 * 4077 * <p>Focus areas are relative to the current field of view 4078 * ({@link #getZoom()}). No matter what the zoom level is, (-1000,-1000) 4079 * represents the top of the currently visible camera frame. The focus 4080 * area cannot be set to be outside the current field of view, even 4081 * when using zoom.</p> 4082 * 4083 * <p>Focus area only has effect if the current focus mode is 4084 * {@link #FOCUS_MODE_AUTO}, {@link #FOCUS_MODE_MACRO}, 4085 * {@link #FOCUS_MODE_CONTINUOUS_VIDEO}, or 4086 * {@link #FOCUS_MODE_CONTINUOUS_PICTURE}.</p> 4087 * 4088 * @return a list of current focus areas 4089 */ getFocusAreas()4090 public List<Area> getFocusAreas() { 4091 return splitArea(get(KEY_FOCUS_AREAS)); 4092 } 4093 4094 /** 4095 * Sets focus areas. See {@link #getFocusAreas()} for documentation. 4096 * 4097 * @param focusAreas the focus areas 4098 * @see #getFocusAreas() 4099 */ setFocusAreas(List<Area> focusAreas)4100 public void setFocusAreas(List<Area> focusAreas) { 4101 set(KEY_FOCUS_AREAS, focusAreas); 4102 } 4103 4104 /** 4105 * Gets the maximum number of metering areas supported. This is the 4106 * maximum length of the list in {@link #setMeteringAreas(List)} and 4107 * {@link #getMeteringAreas()}. 4108 * 4109 * @return the maximum number of metering areas supported by the camera. 4110 * @see #getMeteringAreas() 4111 */ getMaxNumMeteringAreas()4112 public int getMaxNumMeteringAreas() { 4113 return getInt(KEY_MAX_NUM_METERING_AREAS, 0); 4114 } 4115 4116 /** 4117 * <p>Gets the current metering areas. Camera driver uses these areas to 4118 * decide exposure.</p> 4119 * 4120 * <p>Before using this API or {@link #setMeteringAreas(List)}, apps should 4121 * call {@link #getMaxNumMeteringAreas()} to know the maximum number of 4122 * metering areas first. If the value is 0, metering area is not 4123 * supported.</p> 4124 * 4125 * <p>Each metering area is a rectangle with specified weight. The 4126 * direction is relative to the sensor orientation, that is, what the 4127 * sensor sees. The direction is not affected by the rotation or 4128 * mirroring of {@link #setDisplayOrientation(int)}. Coordinates of the 4129 * rectangle range from -1000 to 1000. (-1000, -1000) is the upper left 4130 * point. (1000, 1000) is the lower right point. The width and height of 4131 * metering areas cannot be 0 or negative.</p> 4132 * 4133 * <p>The weight must range from 1 to 1000, and represents a weight for 4134 * every pixel in the area. This means that a large metering area with 4135 * the same weight as a smaller area will have more effect in the 4136 * metering result. Metering areas can partially overlap and the driver 4137 * will add the weights in the overlap region.</p> 4138 * 4139 * <p>A special case of a {@code null} metering area list means the driver 4140 * is free to meter as it chooses. For example, the driver may use more 4141 * signals to select metering areas and change them dynamically. Apps 4142 * can set the metering area list to {@code null} if they want the 4143 * driver to completely control metering.</p> 4144 * 4145 * <p>Metering areas are relative to the current field of view 4146 * ({@link #getZoom()}). No matter what the zoom level is, (-1000,-1000) 4147 * represents the top of the currently visible camera frame. The 4148 * metering area cannot be set to be outside the current field of view, 4149 * even when using zoom.</p> 4150 * 4151 * <p>No matter what metering areas are, the final exposure are compensated 4152 * by {@link #setExposureCompensation(int)}.</p> 4153 * 4154 * @return a list of current metering areas 4155 */ getMeteringAreas()4156 public List<Area> getMeteringAreas() { 4157 return splitArea(get(KEY_METERING_AREAS)); 4158 } 4159 4160 /** 4161 * Sets metering areas. See {@link #getMeteringAreas()} for 4162 * documentation. 4163 * 4164 * @param meteringAreas the metering areas 4165 * @see #getMeteringAreas() 4166 */ setMeteringAreas(List<Area> meteringAreas)4167 public void setMeteringAreas(List<Area> meteringAreas) { 4168 set(KEY_METERING_AREAS, meteringAreas); 4169 } 4170 4171 /** 4172 * Gets the maximum number of detected faces supported. This is the 4173 * maximum length of the list returned from {@link FaceDetectionListener}. 4174 * If the return value is 0, face detection of the specified type is not 4175 * supported. 4176 * 4177 * @return the maximum number of detected face supported by the camera. 4178 * @see #startFaceDetection() 4179 */ getMaxNumDetectedFaces()4180 public int getMaxNumDetectedFaces() { 4181 return getInt(KEY_MAX_NUM_DETECTED_FACES_HW, 0); 4182 } 4183 4184 /** 4185 * Sets recording mode hint. This tells the camera that the intent of 4186 * the application is to record videos {@link 4187 * android.media.MediaRecorder#start()}, not to take still pictures 4188 * {@link #takePicture(Camera.ShutterCallback, Camera.PictureCallback, 4189 * Camera.PictureCallback, Camera.PictureCallback)}. Using this hint can 4190 * allow MediaRecorder.start() to start faster or with fewer glitches on 4191 * output. This should be called before starting preview for the best 4192 * result, but can be changed while the preview is active. The default 4193 * value is false. 4194 * 4195 * The app can still call takePicture() when the hint is true or call 4196 * MediaRecorder.start() when the hint is false. But the performance may 4197 * be worse. 4198 * 4199 * @param hint true if the apps intend to record videos using 4200 * {@link android.media.MediaRecorder}. 4201 */ setRecordingHint(boolean hint)4202 public void setRecordingHint(boolean hint) { 4203 set(KEY_RECORDING_HINT, hint ? TRUE : FALSE); 4204 } 4205 4206 /** 4207 * <p>Returns true if video snapshot is supported. That is, applications 4208 * can call {@link #takePicture(Camera.ShutterCallback, 4209 * Camera.PictureCallback, Camera.PictureCallback, 4210 * Camera.PictureCallback)} during recording. Applications do not need 4211 * to call {@link #startPreview()} after taking a picture. The preview 4212 * will be still active. Other than that, taking a picture during 4213 * recording is identical to taking a picture normally. All settings and 4214 * methods related to takePicture work identically. Ex: 4215 * {@link #getPictureSize()}, {@link #getSupportedPictureSizes()}, 4216 * {@link #setJpegQuality(int)}, {@link #setRotation(int)}, and etc. The 4217 * picture will have an EXIF header. {@link #FLASH_MODE_AUTO} and 4218 * {@link #FLASH_MODE_ON} also still work, but the video will record the 4219 * flash.</p> 4220 * 4221 * <p>Applications can set shutter callback as null to avoid the shutter 4222 * sound. It is also recommended to set raw picture and post view 4223 * callbacks to null to avoid the interrupt of preview display.</p> 4224 * 4225 * <p>Field-of-view of the recorded video may be different from that of the 4226 * captured pictures. The maximum size of a video snapshot may be 4227 * smaller than that for regular still captures. If the current picture 4228 * size is set higher than can be supported by video snapshot, the 4229 * picture will be captured at the maximum supported size instead.</p> 4230 * 4231 * @return true if video snapshot is supported. 4232 */ isVideoSnapshotSupported()4233 public boolean isVideoSnapshotSupported() { 4234 String str = get(KEY_VIDEO_SNAPSHOT_SUPPORTED); 4235 return TRUE.equals(str); 4236 } 4237 4238 /** 4239 * <p>Enables and disables video stabilization. Use 4240 * {@link #isVideoStabilizationSupported} to determine if calling this 4241 * method is valid.</p> 4242 * 4243 * <p>Video stabilization reduces the shaking due to the motion of the 4244 * camera in both the preview stream and in recorded videos, including 4245 * data received from the preview callback. It does not reduce motion 4246 * blur in images captured with 4247 * {@link Camera#takePicture takePicture}.</p> 4248 * 4249 * <p>Video stabilization can be enabled and disabled while preview or 4250 * recording is active, but toggling it may cause a jump in the video 4251 * stream that may be undesirable in a recorded video.</p> 4252 * 4253 * @param toggle Set to true to enable video stabilization, and false to 4254 * disable video stabilization. 4255 * @see #isVideoStabilizationSupported() 4256 * @see #getVideoStabilization() 4257 */ setVideoStabilization(boolean toggle)4258 public void setVideoStabilization(boolean toggle) { 4259 set(KEY_VIDEO_STABILIZATION, toggle ? TRUE : FALSE); 4260 } 4261 4262 /** 4263 * Get the current state of video stabilization. See 4264 * {@link #setVideoStabilization} for details of video stabilization. 4265 * 4266 * @return true if video stabilization is enabled 4267 * @see #isVideoStabilizationSupported() 4268 * @see #setVideoStabilization(boolean) 4269 */ getVideoStabilization()4270 public boolean getVideoStabilization() { 4271 String str = get(KEY_VIDEO_STABILIZATION); 4272 return TRUE.equals(str); 4273 } 4274 4275 /** 4276 * Returns true if video stabilization is supported. See 4277 * {@link #setVideoStabilization} for details of video stabilization. 4278 * 4279 * @return true if video stabilization is supported 4280 * @see #setVideoStabilization(boolean) 4281 * @see #getVideoStabilization() 4282 */ isVideoStabilizationSupported()4283 public boolean isVideoStabilizationSupported() { 4284 String str = get(KEY_VIDEO_STABILIZATION_SUPPORTED); 4285 return TRUE.equals(str); 4286 } 4287 4288 // Splits a comma delimited string to an ArrayList of String. 4289 // Return null if the passing string is null or the size is 0. split(String str)4290 private ArrayList<String> split(String str) { 4291 if (str == null) return null; 4292 4293 TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter(','); 4294 splitter.setString(str); 4295 ArrayList<String> substrings = new ArrayList<String>(); 4296 for (String s : splitter) { 4297 substrings.add(s); 4298 } 4299 return substrings; 4300 } 4301 4302 // Splits a comma delimited string to an ArrayList of Integer. 4303 // Return null if the passing string is null or the size is 0. splitInt(String str)4304 private ArrayList<Integer> splitInt(String str) { 4305 if (str == null) return null; 4306 4307 TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter(','); 4308 splitter.setString(str); 4309 ArrayList<Integer> substrings = new ArrayList<Integer>(); 4310 for (String s : splitter) { 4311 substrings.add(Integer.parseInt(s)); 4312 } 4313 if (substrings.size() == 0) return null; 4314 return substrings; 4315 } 4316 splitInt(String str, int[] output)4317 private void splitInt(String str, int[] output) { 4318 if (str == null) return; 4319 4320 TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter(','); 4321 splitter.setString(str); 4322 int index = 0; 4323 for (String s : splitter) { 4324 output[index++] = Integer.parseInt(s); 4325 } 4326 } 4327 4328 // Splits a comma delimited string to an ArrayList of Float. splitFloat(String str, float[] output)4329 private void splitFloat(String str, float[] output) { 4330 if (str == null) return; 4331 4332 TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter(','); 4333 splitter.setString(str); 4334 int index = 0; 4335 for (String s : splitter) { 4336 output[index++] = Float.parseFloat(s); 4337 } 4338 } 4339 4340 // Returns the value of a float parameter. getFloat(String key, float defaultValue)4341 private float getFloat(String key, float defaultValue) { 4342 try { 4343 return Float.parseFloat(mMap.get(key)); 4344 } catch (NumberFormatException ex) { 4345 return defaultValue; 4346 } 4347 } 4348 4349 // Returns the value of a integer parameter. getInt(String key, int defaultValue)4350 private int getInt(String key, int defaultValue) { 4351 try { 4352 return Integer.parseInt(mMap.get(key)); 4353 } catch (NumberFormatException ex) { 4354 return defaultValue; 4355 } 4356 } 4357 4358 // Splits a comma delimited string to an ArrayList of Size. 4359 // Return null if the passing string is null or the size is 0. splitSize(String str)4360 private ArrayList<Size> splitSize(String str) { 4361 if (str == null) return null; 4362 4363 TextUtils.StringSplitter splitter = new TextUtils.SimpleStringSplitter(','); 4364 splitter.setString(str); 4365 ArrayList<Size> sizeList = new ArrayList<Size>(); 4366 for (String s : splitter) { 4367 Size size = strToSize(s); 4368 if (size != null) sizeList.add(size); 4369 } 4370 if (sizeList.size() == 0) return null; 4371 return sizeList; 4372 } 4373 4374 // Parses a string (ex: "480x320") to Size object. 4375 // Return null if the passing string is null. strToSize(String str)4376 private Size strToSize(String str) { 4377 if (str == null) return null; 4378 4379 int pos = str.indexOf('x'); 4380 if (pos != -1) { 4381 String width = str.substring(0, pos); 4382 String height = str.substring(pos + 1); 4383 return new Size(Integer.parseInt(width), 4384 Integer.parseInt(height)); 4385 } 4386 Log.e(TAG, "Invalid size parameter string=" + str); 4387 return null; 4388 } 4389 4390 // Splits a comma delimited string to an ArrayList of int array. 4391 // Example string: "(10000,26623),(10000,30000)". Return null if the 4392 // passing string is null or the size is 0. splitRange(String str)4393 private ArrayList<int[]> splitRange(String str) { 4394 if (str == null || str.charAt(0) != '(' 4395 || str.charAt(str.length() - 1) != ')') { 4396 Log.e(TAG, "Invalid range list string=" + str); 4397 return null; 4398 } 4399 4400 ArrayList<int[]> rangeList = new ArrayList<int[]>(); 4401 int endIndex, fromIndex = 1; 4402 do { 4403 int[] range = new int[2]; 4404 endIndex = str.indexOf("),(", fromIndex); 4405 if (endIndex == -1) endIndex = str.length() - 1; 4406 splitInt(str.substring(fromIndex, endIndex), range); 4407 rangeList.add(range); 4408 fromIndex = endIndex + 3; 4409 } while (endIndex != str.length() - 1); 4410 4411 if (rangeList.size() == 0) return null; 4412 return rangeList; 4413 } 4414 4415 // Splits a comma delimited string to an ArrayList of Area objects. 4416 // Example string: "(-10,-10,0,0,300),(0,0,10,10,700)". Return null if 4417 // the passing string is null or the size is 0 or (0,0,0,0,0). 4418 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553) splitArea(String str)4419 private ArrayList<Area> splitArea(String str) { 4420 if (str == null || str.charAt(0) != '(' 4421 || str.charAt(str.length() - 1) != ')') { 4422 Log.e(TAG, "Invalid area string=" + str); 4423 return null; 4424 } 4425 4426 ArrayList<Area> result = new ArrayList<Area>(); 4427 int endIndex, fromIndex = 1; 4428 int[] array = new int[5]; 4429 do { 4430 endIndex = str.indexOf("),(", fromIndex); 4431 if (endIndex == -1) endIndex = str.length() - 1; 4432 splitInt(str.substring(fromIndex, endIndex), array); 4433 Rect rect = new Rect(array[0], array[1], array[2], array[3]); 4434 result.add(new Area(rect, array[4])); 4435 fromIndex = endIndex + 3; 4436 } while (endIndex != str.length() - 1); 4437 4438 if (result.size() == 0) return null; 4439 4440 if (result.size() == 1) { 4441 Area area = result.get(0); 4442 Rect rect = area.rect; 4443 if (rect.left == 0 && rect.top == 0 && rect.right == 0 4444 && rect.bottom == 0 && area.weight == 0) { 4445 return null; 4446 } 4447 } 4448 4449 return result; 4450 } 4451 same(String s1, String s2)4452 private boolean same(String s1, String s2) { 4453 if (s1 == null && s2 == null) return true; 4454 if (s1 != null && s1.equals(s2)) return true; 4455 return false; 4456 } 4457 }; 4458 } 4459