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