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