Camera.java revision 7836660f5eb45b7b7e1f5119face65c80e2ade17
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 java.lang.ref.WeakReference; 20import java.util.ArrayList; 21import java.util.HashMap; 22import java.util.List; 23import java.util.StringTokenizer; 24import java.io.IOException; 25 26import android.util.Log; 27import android.view.Surface; 28import android.view.SurfaceHolder; 29import android.graphics.ImageFormat; 30import android.os.Handler; 31import android.os.Looper; 32import android.os.Message; 33 34/** 35 * The Camera class is used to set image capture settings, start/stop preview, 36 * snap pictures, and retrieve frames for encoding for video. This class is a 37 * client for the Camera service, which manages the actual camera hardware. 38 * 39 * <p>To access the device camera, you must declare the 40 * {@link android.Manifest.permission#CAMERA} permission in your Android 41 * Manifest. Also be sure to include the 42 * <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html"><uses-feature></a> 43 * manifest element to declare camera features used by your application. 44 * For example, if you use the camera and auto-focus feature, your Manifest 45 * should include the following:</p> 46 * <pre> <uses-permission android:name="android.permission.CAMERA" /> 47 * <uses-feature android:name="android.hardware.camera" /> 48 * <uses-feature android:name="android.hardware.camera.autofocus" /></pre> 49 * 50 * <p>To take pictures with this class, use the following steps:</p> 51 * 52 * <ol> 53 * <li>Obtain an instance of Camera from {@link #open(int)}. 54 * 55 * <li>Get existing (default) settings with {@link #getParameters()}. 56 * 57 * <li>If necessary, modify the returned {@link Camera.Parameters} object and call 58 * {@link #setParameters(Camera.Parameters)}. 59 * 60 * <li>If desired, call {@link #setDisplayOrientation(int)}. 61 * 62 * <li><b>Important</b>: Pass a fully initialized {@link SurfaceHolder} to 63 * {@link #setPreviewDisplay(SurfaceHolder)}. Without a surface, the camera 64 * will be unable to start the preview. 65 * 66 * <li><b>Important</b>: Call {@link #startPreview()} to start updating the 67 * preview surface. Preview must be started before you can take a picture. 68 * 69 * <li>When you want, call {@link #takePicture(Camera.ShutterCallback, 70 * Camera.PictureCallback, Camera.PictureCallback, Camera.PictureCallback)} to 71 * capture a photo. Wait for the callbacks to provide the actual image data. 72 * 73 * <li>After taking a picture, preview display will have stopped. To take more 74 * photos, call {@link #startPreview()} again first. 75 * 76 * <li>Call {@link #stopPreview()} to stop updating the preview surface. 77 * 78 * <li><b>Important:</b> Call {@link #release()} to release the camera for 79 * use by other applications. Applications should release the camera 80 * immediately in {@link android.app.Activity#onPause()} (and re-{@link #open()} 81 * it in {@link android.app.Activity#onResume()}). 82 * </ol> 83 * 84 * <p>To quickly switch to video recording mode, use these steps:</p> 85 * 86 * <ol> 87 * <li>Obtain and initialize a Camera and start preview as described above. 88 * 89 * <li>Call {@link #unlock()} to allow the media process to access the camera. 90 * 91 * <li>Pass the camera to {@link android.media.MediaRecorder#setCamera(Camera)}. 92 * See {@link android.media.MediaRecorder} information about video recording. 93 * 94 * <li>When finished recording, call {@link #reconnect()} to re-acquire 95 * and re-lock the camera. 96 * 97 * <li>If desired, restart preview and take more photos or videos. 98 * 99 * <li>Call {@link #stopPreview()} and {@link #release()} as described above. 100 * </ol> 101 * 102 * <p>This class is not thread-safe, and is meant for use from one event thread. 103 * Most long-running operations (preview, focus, photo capture, etc) happen 104 * asynchronously and invoke callbacks as necessary. Callbacks will be invoked 105 * on the event thread {@link #open(int)} was called from. This class's methods 106 * must never be called from multiple threads at once.</p> 107 * 108 * <p class="caution"><strong>Caution:</strong> Different Android-powered devices 109 * may have different hardware specifications, such as megapixel ratings and 110 * auto-focus capabilities. In order for your application to be compatible with 111 * more devices, you should not make assumptions about the device camera 112 * specifications.</p> 113 */ 114public class Camera { 115 private static final String TAG = "Camera"; 116 117 // These match the enums in frameworks/base/include/camera/Camera.h 118 private static final int CAMERA_MSG_ERROR = 0x001; 119 private static final int CAMERA_MSG_SHUTTER = 0x002; 120 private static final int CAMERA_MSG_FOCUS = 0x004; 121 private static final int CAMERA_MSG_ZOOM = 0x008; 122 private static final int CAMERA_MSG_PREVIEW_FRAME = 0x010; 123 private static final int CAMERA_MSG_VIDEO_FRAME = 0x020; 124 private static final int CAMERA_MSG_POSTVIEW_FRAME = 0x040; 125 private static final int CAMERA_MSG_RAW_IMAGE = 0x080; 126 private static final int CAMERA_MSG_COMPRESSED_IMAGE = 0x100; 127 private static final int CAMERA_MSG_ALL_MSGS = 0x1FF; 128 129 private int mNativeContext; // accessed by native methods 130 private EventHandler mEventHandler; 131 private ShutterCallback mShutterCallback; 132 private PictureCallback mRawImageCallback; 133 private PictureCallback mJpegCallback; 134 private PreviewCallback mPreviewCallback; 135 private PictureCallback mPostviewCallback; 136 private AutoFocusCallback mAutoFocusCallback; 137 private OnZoomChangeListener mZoomListener; 138 private ErrorCallback mErrorCallback; 139 private boolean mOneShot; 140 private boolean mWithBuffer; 141 142 /** 143 * Returns the number of physical cameras available on this device. 144 */ 145 public native static int getNumberOfCameras(); 146 147 /** 148 * Returns the information about a particular camera. 149 * If {@link #getNumberOfCameras()} returns N, the valid id is 0 to N-1. 150 */ 151 public native static void getCameraInfo(int cameraId, CameraInfo cameraInfo); 152 153 /** 154 * Information about a camera 155 */ 156 public static class CameraInfo { 157 /** 158 * The facing of the camera is opposite to that of the screen. 159 */ 160 public static final int CAMERA_FACING_BACK = 0; 161 162 /** 163 * The facing of the camera is the same as that of the screen. 164 */ 165 public static final int CAMERA_FACING_FRONT = 1; 166 167 /** 168 * The direction that the camera faces to. It should be 169 * CAMERA_FACING_BACK or CAMERA_FACING_FRONT. 170 */ 171 public int facing; 172 173 /** 174 * The orientation of the camera image. The value is the angle that the 175 * camera image needs to be rotated clockwise so it shows correctly on 176 * the display in its natural orientation. It should be 0, 90, 180, or 270. 177 * 178 * For example, suppose a device has a naturally tall screen, but the camera 179 * sensor is mounted in landscape. If the top side of the camera sensor is 180 * aligned with the right edge of the display in natural orientation, the 181 * value should be 90. 182 * 183 * @see #setDisplayOrientation(int) 184 */ 185 public int orientation; 186 }; 187 188 /** 189 * Creates a new Camera object to access a particular hardware camera. 190 * 191 * <p>You must call {@link #release()} when you are done using the camera, 192 * otherwise it will remain locked and be unavailable to other applications. 193 * 194 * <p>Your application should only have one Camera object active at a time 195 * for a particular hardware camera. 196 * 197 * <p>Callbacks from other methods are delivered to the event loop of the 198 * thread which called open(). If this thread has no event loop, then 199 * callbacks are delivered to the main application event loop. If there 200 * is no main application event loop, callbacks are not delivered. 201 * 202 * <p class="caution"><b>Caution:</b> On some devices, this method may 203 * take a long time to complete. It is best to call this method from a 204 * worker thread (possibly using {@link android.os.AsyncTask}) to avoid 205 * blocking the main application UI thread. 206 * 207 * @param cameraId the hardware camera to access, between 0 and 208 * {@link #getNumberOfCameras()}-1. Use {@link #CAMERA_ID_DEFAULT} 209 * to access the default camera. 210 * @return a new Camera object, connected, locked and ready for use. 211 * @throws RuntimeException if connection to the camera service fails (for 212 * example, if the camera is in use by another process). 213 */ 214 public static Camera open(int cameraId) { 215 return new Camera(cameraId); 216 } 217 218 /** 219 * The id for the default camera. 220 * @see #open(int) 221 */ 222 public static int CAMERA_ID_DEFAULT = 0; 223 224 /** 225 * Equivalent to Camera.open(Camera.CAMERA_ID_DEFAULT). 226 * Creates a new Camera object to access the default camera. 227 * @see #open(int) 228 */ 229 public static Camera open() { 230 return new Camera(CAMERA_ID_DEFAULT); 231 } 232 233 Camera(int cameraId) { 234 mShutterCallback = null; 235 mRawImageCallback = null; 236 mJpegCallback = null; 237 mPreviewCallback = null; 238 mPostviewCallback = null; 239 mZoomListener = null; 240 241 Looper looper; 242 if ((looper = Looper.myLooper()) != null) { 243 mEventHandler = new EventHandler(this, looper); 244 } else if ((looper = Looper.getMainLooper()) != null) { 245 mEventHandler = new EventHandler(this, looper); 246 } else { 247 mEventHandler = null; 248 } 249 250 native_setup(new WeakReference<Camera>(this), cameraId); 251 } 252 253 protected void finalize() { 254 native_release(); 255 } 256 257 private native final void native_setup(Object camera_this, int cameraId); 258 private native final void native_release(); 259 260 261 /** 262 * Disconnects and releases the Camera object resources. 263 * 264 * <p>You must call this as soon as you're done with the Camera object.</p> 265 */ 266 public final void release() { 267 native_release(); 268 } 269 270 /** 271 * Unlocks the camera to allow another process to access it. 272 * Normally, the camera is locked to the process with an active Camera 273 * object until {@link #release()} is called. To allow rapid handoff 274 * between processes, you can call this method to release the camera 275 * temporarily for another process to use; once the other process is done 276 * you can call {@link #reconnect()} to reclaim the camera. 277 * 278 * <p>This must be done before calling 279 * {@link android.media.MediaRecorder#setCamera(Camera)}. 280 * 281 * <p>If you are not recording video, you probably do not need this method. 282 * 283 * @throws RuntimeException if the camera cannot be unlocked. 284 */ 285 public native final void unlock(); 286 287 /** 288 * Re-locks the camera to prevent other processes from accessing it. 289 * Camera objects are locked by default unless {@link #unlock()} is 290 * called. Normally {@link #reconnect()} is used instead. 291 * 292 * <p>If you are not recording video, you probably do not need this method. 293 * 294 * @throws RuntimeException if the camera cannot be re-locked (for 295 * example, if the camera is still in use by another process). 296 */ 297 public native final void lock(); 298 299 /** 300 * Reconnects to the camera service after another process used it. 301 * After {@link #unlock()} is called, another process may use the 302 * camera; when the process is done, you must reconnect to the camera, 303 * which will re-acquire the lock and allow you to continue using the 304 * camera. 305 * 306 * <p>This must be done after {@link android.media.MediaRecorder} is 307 * done recording if {@link android.media.MediaRecorder#setCamera(Camera)} 308 * was used. 309 * 310 * <p>If you are not recording video, you probably do not need this method. 311 * 312 * @throws IOException if a connection cannot be re-established (for 313 * example, if the camera is still in use by another process). 314 */ 315 public native final void reconnect() throws IOException; 316 317 /** 318 * Sets the {@link Surface} to be used for live preview. 319 * A surface is necessary for preview, and preview is necessary to take 320 * pictures. The same surface can be re-set without harm. 321 * 322 * <p>The {@link SurfaceHolder} must already contain a surface when this 323 * method is called. If you are using {@link android.view.SurfaceView}, 324 * you will need to register a {@link SurfaceHolder.Callback} with 325 * {@link SurfaceHolder#addCallback(SurfaceHolder.Callback)} and wait for 326 * {@link SurfaceHolder.Callback#surfaceCreated(SurfaceHolder)} before 327 * calling setPreviewDisplay() or starting preview. 328 * 329 * <p>This method must be called before {@link #startPreview()}. The 330 * one exception is that if the preview surface is not set (or set to null) 331 * before startPreview() is called, then this method may be called once 332 * with a non-null parameter to set the preview surface. (This allows 333 * camera setup and surface creation to happen in parallel, saving time.) 334 * The preview surface may not otherwise change while preview is running. 335 * 336 * @param holder containing the Surface on which to place the preview, 337 * or null to remove the preview surface 338 * @throws IOException if the method fails (for example, if the surface 339 * is unavailable or unsuitable). 340 */ 341 public final void setPreviewDisplay(SurfaceHolder holder) throws IOException { 342 if (holder != null) { 343 setPreviewDisplay(holder.getSurface()); 344 } else { 345 setPreviewDisplay((Surface)null); 346 } 347 } 348 349 private native final void setPreviewDisplay(Surface surface); 350 351 /** 352 * Callback interface used to deliver copies of preview frames as 353 * they are displayed. 354 * 355 * @see #setPreviewCallback(Camera.PreviewCallback) 356 * @see #setOneShotPreviewCallback(Camera.PreviewCallback) 357 * @see #setPreviewCallbackWithBuffer(Camera.PreviewCallback) 358 * @see #startPreview() 359 */ 360 public interface PreviewCallback 361 { 362 /** 363 * Called as preview frames are displayed. This callback is invoked 364 * on the event thread {@link #open(int)} was called from. 365 * 366 * @param data the contents of the preview frame in the format defined 367 * by {@link android.graphics.ImageFormat}, which can be queried 368 * with {@link android.hardware.Camera.Parameters#getPreviewFormat()}. 369 * If {@link android.hardware.Camera.Parameters#setPreviewFormat(int)} 370 * is never called, the default will be the YCbCr_420_SP 371 * (NV21) format. 372 * @param camera the Camera service object. 373 */ 374 void onPreviewFrame(byte[] data, Camera camera); 375 }; 376 377 /** 378 * Starts capturing and drawing preview frames to the screen. 379 * Preview will not actually start until a surface is supplied with 380 * {@link #setPreviewDisplay(SurfaceHolder)}. 381 * 382 * <p>If {@link #setPreviewCallback(Camera.PreviewCallback)}, 383 * {@link #setOneShotPreviewCallback(Camera.PreviewCallback)}, or 384 * {@link #setPreviewCallbackWithBuffer(Camera.PreviewCallback)} were 385 * called, {@link Camera.PreviewCallback#onPreviewFrame(byte[], Camera)} 386 * will be called when preview data becomes available. 387 */ 388 public native final void startPreview(); 389 390 /** 391 * Stops capturing and drawing preview frames to the surface, and 392 * resets the camera for a future call to {@link #startPreview()}. 393 */ 394 public native final void stopPreview(); 395 396 /** 397 * Return current preview state. 398 * 399 * FIXME: Unhide before release 400 * @hide 401 */ 402 public native final boolean previewEnabled(); 403 404 /** 405 * Installs a callback to be invoked for every preview frame in addition 406 * to displaying them on the screen. The callback will be repeatedly called 407 * for as long as preview is active. This method can be called at any time, 408 * even while preview is live. Any other preview callbacks are overridden. 409 * 410 * @param cb a callback object that receives a copy of each preview frame, 411 * or null to stop receiving callbacks. 412 */ 413 public final void setPreviewCallback(PreviewCallback cb) { 414 mPreviewCallback = cb; 415 mOneShot = false; 416 mWithBuffer = false; 417 // Always use one-shot mode. We fake camera preview mode by 418 // doing one-shot preview continuously. 419 setHasPreviewCallback(cb != null, false); 420 } 421 422 /** 423 * Installs a callback to be invoked for the next preview frame in addition 424 * to displaying it on the screen. After one invocation, the callback is 425 * cleared. This method can be called any time, even when preview is live. 426 * Any other preview callbacks are overridden. 427 * 428 * @param cb a callback object that receives a copy of the next preview frame, 429 * or null to stop receiving callbacks. 430 */ 431 public final void setOneShotPreviewCallback(PreviewCallback cb) { 432 mPreviewCallback = cb; 433 mOneShot = true; 434 mWithBuffer = false; 435 setHasPreviewCallback(cb != null, false); 436 } 437 438 private native final void setHasPreviewCallback(boolean installed, boolean manualBuffer); 439 440 /** 441 * Installs a callback to be invoked for every preview frame, using buffers 442 * supplied with {@link #addCallbackBuffer(byte[])}, in addition to 443 * displaying them on the screen. The callback will be repeatedly called 444 * for as long as preview is active and buffers are available. 445 * Any other preview callbacks are overridden. 446 * 447 * <p>The purpose of this method is to improve preview efficiency and frame 448 * rate by allowing preview frame memory reuse. You must call 449 * {@link #addCallbackBuffer(byte[])} at some point -- before or after 450 * calling this method -- or no callbacks will received. 451 * 452 * The buffer queue will be cleared if this method is called with a null 453 * callback, {@link #setPreviewCallback(Camera.PreviewCallback)} is called, 454 * or {@link #setOneShotPreviewCallback(Camera.PreviewCallback)} is called. 455 * 456 * @param cb a callback object that receives a copy of the preview frame, 457 * or null to stop receiving callbacks and clear the buffer queue. 458 * @see #addCallbackBuffer(byte[]) 459 */ 460 public final void setPreviewCallbackWithBuffer(PreviewCallback cb) { 461 mPreviewCallback = cb; 462 mOneShot = false; 463 mWithBuffer = true; 464 setHasPreviewCallback(cb != null, true); 465 } 466 467 /** 468 * Adds a pre-allocated buffer to the preview callback buffer queue. 469 * Applications can add one or more buffers to the queue. When a preview 470 * frame arrives and there is still at least one available buffer, the 471 * buffer will be used and removed from the queue. Then preview callback is 472 * invoked with the buffer. If a frame arrives and there is no buffer left, 473 * the frame is discarded. Applications should add buffers back when they 474 * finish processing the data in them. 475 * 476 * <p>The size of the buffer is determined by multiplying the preview 477 * image width, height, and bytes per pixel. The width and height can be 478 * read from {@link Camera.Parameters#getPreviewSize()}. Bytes per pixel 479 * can be computed from 480 * {@link android.graphics.ImageFormat#getBitsPerPixel(int)} / 8, 481 * using the image format from {@link Camera.Parameters#getPreviewFormat()}. 482 * 483 * <p>This method is only necessary when 484 * {@link #setPreviewCallbackWithBuffer(PreviewCallback)} is used. When 485 * {@link #setPreviewCallback(PreviewCallback)} or 486 * {@link #setOneShotPreviewCallback(PreviewCallback)} are used, buffers 487 * are automatically allocated. 488 * 489 * @param callbackBuffer the buffer to add to the queue. 490 * The size should be width * height * bits_per_pixel / 8. 491 * @see #setPreviewCallbackWithBuffer(PreviewCallback) 492 */ 493 public native final void addCallbackBuffer(byte[] callbackBuffer); 494 495 private class EventHandler extends Handler 496 { 497 private Camera mCamera; 498 499 public EventHandler(Camera c, Looper looper) { 500 super(looper); 501 mCamera = c; 502 } 503 504 @Override 505 public void handleMessage(Message msg) { 506 switch(msg.what) { 507 case CAMERA_MSG_SHUTTER: 508 if (mShutterCallback != null) { 509 mShutterCallback.onShutter(); 510 } 511 return; 512 513 case CAMERA_MSG_RAW_IMAGE: 514 if (mRawImageCallback != null) { 515 mRawImageCallback.onPictureTaken((byte[])msg.obj, mCamera); 516 } 517 return; 518 519 case CAMERA_MSG_COMPRESSED_IMAGE: 520 if (mJpegCallback != null) { 521 mJpegCallback.onPictureTaken((byte[])msg.obj, mCamera); 522 } 523 return; 524 525 case CAMERA_MSG_PREVIEW_FRAME: 526 if (mPreviewCallback != null) { 527 PreviewCallback cb = mPreviewCallback; 528 if (mOneShot) { 529 // Clear the callback variable before the callback 530 // in case the app calls setPreviewCallback from 531 // the callback function 532 mPreviewCallback = null; 533 } else if (!mWithBuffer) { 534 // We're faking the camera preview mode to prevent 535 // the app from being flooded with preview frames. 536 // Set to oneshot mode again. 537 setHasPreviewCallback(true, false); 538 } 539 cb.onPreviewFrame((byte[])msg.obj, mCamera); 540 } 541 return; 542 543 case CAMERA_MSG_POSTVIEW_FRAME: 544 if (mPostviewCallback != null) { 545 mPostviewCallback.onPictureTaken((byte[])msg.obj, mCamera); 546 } 547 return; 548 549 case CAMERA_MSG_FOCUS: 550 if (mAutoFocusCallback != null) { 551 mAutoFocusCallback.onAutoFocus(msg.arg1 == 0 ? false : true, mCamera); 552 } 553 return; 554 555 case CAMERA_MSG_ZOOM: 556 if (mZoomListener != null) { 557 mZoomListener.onZoomChange(msg.arg1, msg.arg2 != 0, mCamera); 558 } 559 return; 560 561 case CAMERA_MSG_ERROR : 562 Log.e(TAG, "Error " + msg.arg1); 563 if (mErrorCallback != null) { 564 mErrorCallback.onError(msg.arg1, mCamera); 565 } 566 return; 567 568 default: 569 Log.e(TAG, "Unknown message type " + msg.what); 570 return; 571 } 572 } 573 } 574 575 private static void postEventFromNative(Object camera_ref, 576 int what, int arg1, int arg2, Object obj) 577 { 578 Camera c = (Camera)((WeakReference)camera_ref).get(); 579 if (c == null) 580 return; 581 582 if (c.mEventHandler != null) { 583 Message m = c.mEventHandler.obtainMessage(what, arg1, arg2, obj); 584 c.mEventHandler.sendMessage(m); 585 } 586 } 587 588 /** 589 * Callback interface used to notify on completion of camera auto focus. 590 * 591 * <p>Devices that do not support auto-focus will receive a "fake" 592 * callback to this interface. If your application needs auto-focus and 593 * should not be installed on devices <em>without</em> auto-focus, you must 594 * declare that your app uses the 595 * {@code android.hardware.camera.autofocus} feature, in the 596 * <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html"><uses-feature></a> 597 * manifest element.</p> 598 * 599 * @see #autoFocus(AutoFocusCallback) 600 */ 601 public interface AutoFocusCallback 602 { 603 /** 604 * Called when the camera auto focus completes. If the camera does not 605 * support auto-focus and autoFocus is called, onAutoFocus will be 606 * called immediately with success. 607 * 608 * @param success true if focus was successful, false if otherwise 609 * @param camera the Camera service object 610 */ 611 void onAutoFocus(boolean success, Camera camera); 612 }; 613 614 /** 615 * Starts camera auto-focus and registers a callback function to run when 616 * the camera is focused. This method is only valid when preview is active 617 * (between {@link #startPreview()} and before {@link #stopPreview()}). 618 * 619 * <p>Callers should check 620 * {@link android.hardware.Camera.Parameters#getFocusMode()} to determine if 621 * this method should be called. If the camera does not support auto-focus, 622 * it is a no-op and {@link AutoFocusCallback#onAutoFocus(boolean, Camera)} 623 * callback will be called immediately. 624 * 625 * <p>If your application should not be installed 626 * on devices without auto-focus, you must declare that your application 627 * uses auto-focus with the 628 * <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html"><uses-feature></a> 629 * manifest element.</p> 630 * 631 * <p>If the current flash mode is not 632 * {@link android.hardware.Camera.Parameters#FLASH_MODE_OFF}, flash may be 633 * fired during auto-focus, depending on the driver and camera hardware.<p> 634 * 635 * @param cb the callback to run 636 * @see #cancelAutoFocus() 637 */ 638 public final void autoFocus(AutoFocusCallback cb) 639 { 640 mAutoFocusCallback = cb; 641 native_autoFocus(); 642 } 643 private native final void native_autoFocus(); 644 645 /** 646 * Cancels any auto-focus function in progress. 647 * Whether or not auto-focus is currently in progress, 648 * this function will return the focus position to the default. 649 * If the camera does not support auto-focus, this is a no-op. 650 * 651 * @see #autoFocus(Camera.AutoFocusCallback) 652 */ 653 public final void cancelAutoFocus() 654 { 655 mAutoFocusCallback = null; 656 native_cancelAutoFocus(); 657 } 658 private native final void native_cancelAutoFocus(); 659 660 /** 661 * Callback interface used to signal the moment of actual image capture. 662 * 663 * @see #takePicture(ShutterCallback, PictureCallback, PictureCallback, PictureCallback) 664 */ 665 public interface ShutterCallback 666 { 667 /** 668 * Called as near as possible to the moment when a photo is captured 669 * from the sensor. This is a good opportunity to play a shutter sound 670 * or give other feedback of camera operation. This may be some time 671 * after the photo was triggered, but some time before the actual data 672 * is available. 673 */ 674 void onShutter(); 675 } 676 677 /** 678 * Callback interface used to supply image data from a photo capture. 679 * 680 * @see #takePicture(ShutterCallback, PictureCallback, PictureCallback, PictureCallback) 681 */ 682 public interface PictureCallback { 683 /** 684 * Called when image data is available after a picture is taken. 685 * The format of the data depends on the context of the callback 686 * and {@link Camera.Parameters} settings. 687 * 688 * @param data a byte array of the picture data 689 * @param camera the Camera service object 690 */ 691 void onPictureTaken(byte[] data, Camera camera); 692 }; 693 694 /** 695 * Equivalent to takePicture(shutter, raw, null, jpeg). 696 * 697 * @see #takePicture(ShutterCallback, PictureCallback, PictureCallback, PictureCallback) 698 */ 699 public final void takePicture(ShutterCallback shutter, PictureCallback raw, 700 PictureCallback jpeg) { 701 takePicture(shutter, raw, null, jpeg); 702 } 703 private native final void native_takePicture(); 704 705 /** 706 * Triggers an asynchronous image capture. The camera service will initiate 707 * a series of callbacks to the application as the image capture progresses. 708 * The shutter callback occurs after the image is captured. This can be used 709 * to trigger a sound to let the user know that image has been captured. The 710 * raw callback occurs when the raw image data is available (NOTE: the data 711 * may be null if the hardware does not have enough memory to make a copy). 712 * The postview callback occurs when a scaled, fully processed postview 713 * image is available (NOTE: not all hardware supports this). The jpeg 714 * callback occurs when the compressed image is available. If the 715 * application does not need a particular callback, a null can be passed 716 * instead of a callback method. 717 * 718 * <p>This method is only valid when preview is active (after 719 * {@link #startPreview()}). Preview will be stopped after the image is 720 * taken; callers must call {@link #startPreview()} again if they want to 721 * re-start preview or take more pictures. 722 * 723 * <p>After calling this method, you must not call {@link #startPreview()} 724 * or take another picture until the JPEG callback has returned. 725 * 726 * @param shutter the callback for image capture moment, or null 727 * @param raw the callback for raw (uncompressed) image data, or null 728 * @param postview callback with postview image data, may be null 729 * @param jpeg the callback for JPEG image data, or null 730 */ 731 public final void takePicture(ShutterCallback shutter, PictureCallback raw, 732 PictureCallback postview, PictureCallback jpeg) { 733 mShutterCallback = shutter; 734 mRawImageCallback = raw; 735 mPostviewCallback = postview; 736 mJpegCallback = jpeg; 737 native_takePicture(); 738 } 739 740 /** 741 * Zooms to the requested value smoothly. The driver will notify {@link 742 * OnZoomChangeListener} of the zoom value and whether zoom is stopped at 743 * the time. For example, suppose the current zoom is 0 and startSmoothZoom 744 * is called with value 3. The 745 * {@link Camera.OnZoomChangeListener#onZoomChange(int, boolean, Camera)} 746 * method will be called three times with zoom values 1, 2, and 3. 747 * Applications can call {@link #stopSmoothZoom} to stop the zoom earlier. 748 * Applications should not call startSmoothZoom again or change the zoom 749 * value before zoom stops. If the supplied zoom value equals to the current 750 * zoom value, no zoom callback will be generated. This method is supported 751 * if {@link android.hardware.Camera.Parameters#isSmoothZoomSupported} 752 * returns true. 753 * 754 * @param value zoom value. The valid range is 0 to {@link 755 * android.hardware.Camera.Parameters#getMaxZoom}. 756 * @throws IllegalArgumentException if the zoom value is invalid. 757 * @throws RuntimeException if the method fails. 758 * @see #setZoomChangeListener(OnZoomChangeListener) 759 */ 760 public native final void startSmoothZoom(int value); 761 762 /** 763 * Stops the smooth zoom. Applications should wait for the {@link 764 * OnZoomChangeListener} to know when the zoom is actually stopped. This 765 * method is supported if {@link 766 * android.hardware.Camera.Parameters#isSmoothZoomSupported} is true. 767 * 768 * @throws RuntimeException if the method fails. 769 */ 770 public native final void stopSmoothZoom(); 771 772 /** 773 * Set the display orientation. This affects the preview frames and the 774 * picture displayed after snapshot. This method is useful for portrait 775 * mode applications. 776 * 777 * This does not affect the order of byte array passed in 778 * {@link PreviewCallback#onPreviewFrame}. This method is not allowed to 779 * be called during preview. 780 * 781 * If you want to make the camera image show in the same orientation as 782 * the display, you can use the following code.<p> 783 * <pre> 784 * public static void setCameraDisplayOrientation(Activity activity, 785 * int cameraId, android.hardware.Camera camera) { 786 * android.hardware.Camera.CameraInfo info = 787 * new android.hardware.Camera.CameraInfo(); 788 * android.hardware.Camera.getCameraInfo(cameraId, info); 789 * int rotation = activity.getWindowManager().getDefaultDisplay() 790 * .getRotation(); 791 * int degrees = 0; 792 * switch (rotation) { 793 * case Surface.ROTATION_0: degrees = 0; break; 794 * case Surface.ROTATION_90: degrees = 90; break; 795 * case Surface.ROTATION_180: degrees = 180; break; 796 * case Surface.ROTATION_270: degrees = 270; break; 797 * } 798 * 799 * int result = (info.orientation - degrees + 360) % 360; 800 * camera.setDisplayOrientation(result); 801 * } 802 * </pre> 803 * @param degrees the angle that the picture will be rotated clockwise. 804 * Valid values are 0, 90, 180, and 270. The starting 805 * position is 0 (landscape). 806 */ 807 public native final void setDisplayOrientation(int degrees); 808 809 /** 810 * Callback interface for zoom changes during a smooth zoom operation. 811 * 812 * @see #setZoomChangeListener(OnZoomChangeListener) 813 * @see #startSmoothZoom(int) 814 */ 815 public interface OnZoomChangeListener 816 { 817 /** 818 * Called when the zoom value has changed during a smooth zoom. 819 * 820 * @param zoomValue the current zoom value. In smooth zoom mode, camera 821 * calls this for every new zoom value. 822 * @param stopped whether smooth zoom is stopped. If the value is true, 823 * this is the last zoom update for the application. 824 * @param camera the Camera service object 825 */ 826 void onZoomChange(int zoomValue, boolean stopped, Camera camera); 827 }; 828 829 /** 830 * Registers a listener to be notified when the zoom value is updated by the 831 * camera driver during smooth zoom. 832 * 833 * @param listener the listener to notify 834 * @see #startSmoothZoom(int) 835 */ 836 public final void setZoomChangeListener(OnZoomChangeListener listener) 837 { 838 mZoomListener = listener; 839 } 840 841 // Error codes match the enum in include/ui/Camera.h 842 843 /** 844 * Unspecified camera error. 845 * @see Camera.ErrorCallback 846 */ 847 public static final int CAMERA_ERROR_UNKNOWN = 1; 848 849 /** 850 * Media server died. In this case, the application must release the 851 * Camera object and instantiate a new one. 852 * @see Camera.ErrorCallback 853 */ 854 public static final int CAMERA_ERROR_SERVER_DIED = 100; 855 856 /** 857 * Callback interface for camera error notification. 858 * 859 * @see #setErrorCallback(ErrorCallback) 860 */ 861 public interface ErrorCallback 862 { 863 /** 864 * Callback for camera errors. 865 * @param error error code: 866 * <ul> 867 * <li>{@link #CAMERA_ERROR_UNKNOWN} 868 * <li>{@link #CAMERA_ERROR_SERVER_DIED} 869 * </ul> 870 * @param camera the Camera service object 871 */ 872 void onError(int error, Camera camera); 873 }; 874 875 /** 876 * Registers a callback to be invoked when an error occurs. 877 * @param cb The callback to run 878 */ 879 public final void setErrorCallback(ErrorCallback cb) 880 { 881 mErrorCallback = cb; 882 } 883 884 private native final void native_setParameters(String params); 885 private native final String native_getParameters(); 886 887 /** 888 * Changes the settings for this Camera service. 889 * 890 * @param params the Parameters to use for this Camera service 891 * @see #getParameters() 892 */ 893 public void setParameters(Parameters params) { 894 native_setParameters(params.flatten()); 895 } 896 897 /** 898 * Returns the current settings for this Camera service. 899 * If modifications are made to the returned Parameters, they must be passed 900 * to {@link #setParameters(Camera.Parameters)} to take effect. 901 * 902 * @see #setParameters(Camera.Parameters) 903 */ 904 public Parameters getParameters() { 905 Parameters p = new Parameters(); 906 String s = native_getParameters(); 907 p.unflatten(s); 908 return p; 909 } 910 911 /** 912 * Image size (width and height dimensions). 913 */ 914 public class Size { 915 /** 916 * Sets the dimensions for pictures. 917 * 918 * @param w the photo width (pixels) 919 * @param h the photo height (pixels) 920 */ 921 public Size(int w, int h) { 922 width = w; 923 height = h; 924 } 925 /** 926 * Compares {@code obj} to this size. 927 * 928 * @param obj the object to compare this size with. 929 * @return {@code true} if the width and height of {@code obj} is the 930 * same as those of this size. {@code false} otherwise. 931 */ 932 @Override 933 public boolean equals(Object obj) { 934 if (!(obj instanceof Size)) { 935 return false; 936 } 937 Size s = (Size) obj; 938 return width == s.width && height == s.height; 939 } 940 @Override 941 public int hashCode() { 942 return width * 32713 + height; 943 } 944 /** width of the picture */ 945 public int width; 946 /** height of the picture */ 947 public int height; 948 }; 949 950 /** 951 * Camera service settings. 952 * 953 * <p>To make camera parameters take effect, applications have to call 954 * {@link Camera#setParameters(Camera.Parameters)}. For example, after 955 * {@link Camera.Parameters#setWhiteBalance} is called, white balance is not 956 * actually changed until {@link Camera#setParameters(Camera.Parameters)} 957 * is called with the changed parameters object. 958 * 959 * <p>Different devices may have different camera capabilities, such as 960 * picture size or flash modes. The application should query the camera 961 * capabilities before setting parameters. For example, the application 962 * should call {@link Camera.Parameters#getSupportedColorEffects()} before 963 * calling {@link Camera.Parameters#setColorEffect(String)}. If the 964 * camera does not support color effects, 965 * {@link Camera.Parameters#getSupportedColorEffects()} will return null. 966 */ 967 public class Parameters { 968 // Parameter keys to communicate with the camera driver. 969 private static final String KEY_PREVIEW_SIZE = "preview-size"; 970 private static final String KEY_PREVIEW_FORMAT = "preview-format"; 971 private static final String KEY_PREVIEW_FRAME_RATE = "preview-frame-rate"; 972 private static final String KEY_PREVIEW_FPS_RANGE = "preview-fps-range"; 973 private static final String KEY_PICTURE_SIZE = "picture-size"; 974 private static final String KEY_PICTURE_FORMAT = "picture-format"; 975 private static final String KEY_JPEG_THUMBNAIL_SIZE = "jpeg-thumbnail-size"; 976 private static final String KEY_JPEG_THUMBNAIL_WIDTH = "jpeg-thumbnail-width"; 977 private static final String KEY_JPEG_THUMBNAIL_HEIGHT = "jpeg-thumbnail-height"; 978 private static final String KEY_JPEG_THUMBNAIL_QUALITY = "jpeg-thumbnail-quality"; 979 private static final String KEY_JPEG_QUALITY = "jpeg-quality"; 980 private static final String KEY_ROTATION = "rotation"; 981 private static final String KEY_GPS_LATITUDE = "gps-latitude"; 982 private static final String KEY_GPS_LONGITUDE = "gps-longitude"; 983 private static final String KEY_GPS_ALTITUDE = "gps-altitude"; 984 private static final String KEY_GPS_TIMESTAMP = "gps-timestamp"; 985 private static final String KEY_GPS_PROCESSING_METHOD = "gps-processing-method"; 986 private static final String KEY_WHITE_BALANCE = "whitebalance"; 987 private static final String KEY_EFFECT = "effect"; 988 private static final String KEY_ANTIBANDING = "antibanding"; 989 private static final String KEY_SCENE_MODE = "scene-mode"; 990 private static final String KEY_FLASH_MODE = "flash-mode"; 991 private static final String KEY_FOCUS_MODE = "focus-mode"; 992 private static final String KEY_FOCAL_LENGTH = "focal-length"; 993 private static final String KEY_HORIZONTAL_VIEW_ANGLE = "horizontal-view-angle"; 994 private static final String KEY_VERTICAL_VIEW_ANGLE = "vertical-view-angle"; 995 private static final String KEY_EXPOSURE_COMPENSATION = "exposure-compensation"; 996 private static final String KEY_MAX_EXPOSURE_COMPENSATION = "max-exposure-compensation"; 997 private static final String KEY_MIN_EXPOSURE_COMPENSATION = "min-exposure-compensation"; 998 private static final String KEY_EXPOSURE_COMPENSATION_STEP = "exposure-compensation-step"; 999 private static final String KEY_ZOOM = "zoom"; 1000 private static final String KEY_MAX_ZOOM = "max-zoom"; 1001 private static final String KEY_ZOOM_RATIOS = "zoom-ratios"; 1002 private static final String KEY_ZOOM_SUPPORTED = "zoom-supported"; 1003 private static final String KEY_SMOOTH_ZOOM_SUPPORTED = "smooth-zoom-supported"; 1004 private static final String KEY_FOCUS_DISTANCES = "focus-distances"; 1005 1006 // Parameter key suffix for supported values. 1007 private static final String SUPPORTED_VALUES_SUFFIX = "-values"; 1008 1009 private static final String TRUE = "true"; 1010 1011 // Values for white balance settings. 1012 public static final String WHITE_BALANCE_AUTO = "auto"; 1013 public static final String WHITE_BALANCE_INCANDESCENT = "incandescent"; 1014 public static final String WHITE_BALANCE_FLUORESCENT = "fluorescent"; 1015 public static final String WHITE_BALANCE_WARM_FLUORESCENT = "warm-fluorescent"; 1016 public static final String WHITE_BALANCE_DAYLIGHT = "daylight"; 1017 public static final String WHITE_BALANCE_CLOUDY_DAYLIGHT = "cloudy-daylight"; 1018 public static final String WHITE_BALANCE_TWILIGHT = "twilight"; 1019 public static final String WHITE_BALANCE_SHADE = "shade"; 1020 1021 // Values for color effect settings. 1022 public static final String EFFECT_NONE = "none"; 1023 public static final String EFFECT_MONO = "mono"; 1024 public static final String EFFECT_NEGATIVE = "negative"; 1025 public static final String EFFECT_SOLARIZE = "solarize"; 1026 public static final String EFFECT_SEPIA = "sepia"; 1027 public static final String EFFECT_POSTERIZE = "posterize"; 1028 public static final String EFFECT_WHITEBOARD = "whiteboard"; 1029 public static final String EFFECT_BLACKBOARD = "blackboard"; 1030 public static final String EFFECT_AQUA = "aqua"; 1031 1032 // Values for antibanding settings. 1033 public static final String ANTIBANDING_AUTO = "auto"; 1034 public static final String ANTIBANDING_50HZ = "50hz"; 1035 public static final String ANTIBANDING_60HZ = "60hz"; 1036 public static final String ANTIBANDING_OFF = "off"; 1037 1038 // Values for flash mode settings. 1039 /** 1040 * Flash will not be fired. 1041 */ 1042 public static final String FLASH_MODE_OFF = "off"; 1043 1044 /** 1045 * Flash will be fired automatically when required. The flash may be fired 1046 * during preview, auto-focus, or snapshot depending on the driver. 1047 */ 1048 public static final String FLASH_MODE_AUTO = "auto"; 1049 1050 /** 1051 * Flash will always be fired during snapshot. The flash may also be 1052 * fired during preview or auto-focus depending on the driver. 1053 */ 1054 public static final String FLASH_MODE_ON = "on"; 1055 1056 /** 1057 * Flash will be fired in red-eye reduction mode. 1058 */ 1059 public static final String FLASH_MODE_RED_EYE = "red-eye"; 1060 1061 /** 1062 * Constant emission of light during preview, auto-focus and snapshot. 1063 * This can also be used for video recording. 1064 */ 1065 public static final String FLASH_MODE_TORCH = "torch"; 1066 1067 /** 1068 * Scene mode is off. 1069 */ 1070 public static final String SCENE_MODE_AUTO = "auto"; 1071 1072 /** 1073 * Take photos of fast moving objects. Same as {@link 1074 * #SCENE_MODE_SPORTS}. 1075 */ 1076 public static final String SCENE_MODE_ACTION = "action"; 1077 1078 /** 1079 * Take people pictures. 1080 */ 1081 public static final String SCENE_MODE_PORTRAIT = "portrait"; 1082 1083 /** 1084 * Take pictures on distant objects. 1085 */ 1086 public static final String SCENE_MODE_LANDSCAPE = "landscape"; 1087 1088 /** 1089 * Take photos at night. 1090 */ 1091 public static final String SCENE_MODE_NIGHT = "night"; 1092 1093 /** 1094 * Take people pictures at night. 1095 */ 1096 public static final String SCENE_MODE_NIGHT_PORTRAIT = "night-portrait"; 1097 1098 /** 1099 * Take photos in a theater. Flash light is off. 1100 */ 1101 public static final String SCENE_MODE_THEATRE = "theatre"; 1102 1103 /** 1104 * Take pictures on the beach. 1105 */ 1106 public static final String SCENE_MODE_BEACH = "beach"; 1107 1108 /** 1109 * Take pictures on the snow. 1110 */ 1111 public static final String SCENE_MODE_SNOW = "snow"; 1112 1113 /** 1114 * Take sunset photos. 1115 */ 1116 public static final String SCENE_MODE_SUNSET = "sunset"; 1117 1118 /** 1119 * Avoid blurry pictures (for example, due to hand shake). 1120 */ 1121 public static final String SCENE_MODE_STEADYPHOTO = "steadyphoto"; 1122 1123 /** 1124 * For shooting firework displays. 1125 */ 1126 public static final String SCENE_MODE_FIREWORKS = "fireworks"; 1127 1128 /** 1129 * Take photos of fast moving objects. Same as {@link 1130 * #SCENE_MODE_ACTION}. 1131 */ 1132 public static final String SCENE_MODE_SPORTS = "sports"; 1133 1134 /** 1135 * Take indoor low-light shot. 1136 */ 1137 public static final String SCENE_MODE_PARTY = "party"; 1138 1139 /** 1140 * Capture the naturally warm color of scenes lit by candles. 1141 */ 1142 public static final String SCENE_MODE_CANDLELIGHT = "candlelight"; 1143 1144 /** 1145 * Applications are looking for a barcode. Camera driver will be 1146 * optimized for barcode reading. 1147 */ 1148 public static final String SCENE_MODE_BARCODE = "barcode"; 1149 1150 /** 1151 * Auto-focus mode. Applications should call {@link 1152 * #autoFocus(AutoFocusCallback)} to start the focus in this mode. 1153 */ 1154 public static final String FOCUS_MODE_AUTO = "auto"; 1155 1156 /** 1157 * Focus is set at infinity. Applications should not call 1158 * {@link #autoFocus(AutoFocusCallback)} in this mode. 1159 */ 1160 public static final String FOCUS_MODE_INFINITY = "infinity"; 1161 1162 /** 1163 * Macro (close-up) focus mode. Applications should call 1164 * {@link #autoFocus(AutoFocusCallback)} to start the focus in this 1165 * mode. 1166 */ 1167 public static final String FOCUS_MODE_MACRO = "macro"; 1168 1169 /** 1170 * Focus is fixed. The camera is always in this mode if the focus is not 1171 * adjustable. If the camera has auto-focus, this mode can fix the 1172 * focus, which is usually at hyperfocal distance. Applications should 1173 * not call {@link #autoFocus(AutoFocusCallback)} in this mode. 1174 */ 1175 public static final String FOCUS_MODE_FIXED = "fixed"; 1176 1177 /** 1178 * Extended depth of field (EDOF). Focusing is done digitally and 1179 * continuously. Applications should not call {@link 1180 * #autoFocus(AutoFocusCallback)} in this mode. 1181 */ 1182 public static final String FOCUS_MODE_EDOF = "edof"; 1183 1184 /** 1185 * Continuous auto focus mode. The camera continuously tries to focus. 1186 * This is ideal for shooting video or shooting photo of moving object. 1187 * Auto focus starts when the parameter is set. Applications should not 1188 * call {@link #autoFocus(AutoFocusCallback)} in this mode. To stop 1189 * continuous focus, applications should change the focus mode to other 1190 * modes. 1191 */ 1192 public static final String FOCUS_MODE_CONTINUOUS = "continuous"; 1193 1194 // Indices for focus distance array. 1195 /** 1196 * The array index of near focus distance for use with 1197 * {@link #getFocusDistances(float[])}. 1198 */ 1199 public static final int FOCUS_DISTANCE_NEAR_INDEX = 0; 1200 1201 /** 1202 * The array index of optimal focus distance for use with 1203 * {@link #getFocusDistances(float[])}. 1204 */ 1205 public static final int FOCUS_DISTANCE_OPTIMAL_INDEX = 1; 1206 1207 /** 1208 * The array index of far focus distance for use with 1209 * {@link #getFocusDistances(float[])}. 1210 */ 1211 public static final int FOCUS_DISTANCE_FAR_INDEX = 2; 1212 1213 /** 1214 * The array index of minimum preview fps for use with {@link 1215 * #getPreviewFpsRange(int[])} or {@link 1216 * #getSupportedPreviewFpsRange()}. 1217 */ 1218 public static final int PREVIEW_FPS_MIN_INDEX = 0; 1219 1220 /** 1221 * The array index of maximum preview fps for use with {@link 1222 * #getPreviewFpsRange(int[])} or {@link 1223 * #getSupportedPreviewFpsRange()}. 1224 */ 1225 public static final int PREVIEW_FPS_MAX_INDEX = 1; 1226 1227 // Formats for setPreviewFormat and setPictureFormat. 1228 private static final String PIXEL_FORMAT_YUV422SP = "yuv422sp"; 1229 private static final String PIXEL_FORMAT_YUV420SP = "yuv420sp"; 1230 private static final String PIXEL_FORMAT_YUV422I = "yuv422i-yuyv"; 1231 private static final String PIXEL_FORMAT_RGB565 = "rgb565"; 1232 private static final String PIXEL_FORMAT_JPEG = "jpeg"; 1233 1234 private HashMap<String, String> mMap; 1235 1236 private Parameters() { 1237 mMap = new HashMap<String, String>(); 1238 } 1239 1240 /** 1241 * Writes the current Parameters to the log. 1242 * @hide 1243 * @deprecated 1244 */ 1245 public void dump() { 1246 Log.e(TAG, "dump: size=" + mMap.size()); 1247 for (String k : mMap.keySet()) { 1248 Log.e(TAG, "dump: " + k + "=" + mMap.get(k)); 1249 } 1250 } 1251 1252 /** 1253 * Creates a single string with all the parameters set in 1254 * this Parameters object. 1255 * <p>The {@link #unflatten(String)} method does the reverse.</p> 1256 * 1257 * @return a String with all values from this Parameters object, in 1258 * semi-colon delimited key-value pairs 1259 */ 1260 public String flatten() { 1261 StringBuilder flattened = new StringBuilder(); 1262 for (String k : mMap.keySet()) { 1263 flattened.append(k); 1264 flattened.append("="); 1265 flattened.append(mMap.get(k)); 1266 flattened.append(";"); 1267 } 1268 // chop off the extra semicolon at the end 1269 flattened.deleteCharAt(flattened.length()-1); 1270 return flattened.toString(); 1271 } 1272 1273 /** 1274 * Takes a flattened string of parameters and adds each one to 1275 * this Parameters object. 1276 * <p>The {@link #flatten()} method does the reverse.</p> 1277 * 1278 * @param flattened a String of parameters (key-value paired) that 1279 * are semi-colon delimited 1280 */ 1281 public void unflatten(String flattened) { 1282 mMap.clear(); 1283 1284 StringTokenizer tokenizer = new StringTokenizer(flattened, ";"); 1285 while (tokenizer.hasMoreElements()) { 1286 String kv = tokenizer.nextToken(); 1287 int pos = kv.indexOf('='); 1288 if (pos == -1) { 1289 continue; 1290 } 1291 String k = kv.substring(0, pos); 1292 String v = kv.substring(pos + 1); 1293 mMap.put(k, v); 1294 } 1295 } 1296 1297 public void remove(String key) { 1298 mMap.remove(key); 1299 } 1300 1301 /** 1302 * Sets a String parameter. 1303 * 1304 * @param key the key name for the parameter 1305 * @param value the String value of the parameter 1306 */ 1307 public void set(String key, String value) { 1308 if (key.indexOf('=') != -1 || key.indexOf(';') != -1) { 1309 Log.e(TAG, "Key \"" + key + "\" contains invalid character (= or ;)"); 1310 return; 1311 } 1312 if (value.indexOf('=') != -1 || value.indexOf(';') != -1) { 1313 Log.e(TAG, "Value \"" + value + "\" contains invalid character (= or ;)"); 1314 return; 1315 } 1316 1317 mMap.put(key, value); 1318 } 1319 1320 /** 1321 * Sets an integer parameter. 1322 * 1323 * @param key the key name for the parameter 1324 * @param value the int value of the parameter 1325 */ 1326 public void set(String key, int value) { 1327 mMap.put(key, Integer.toString(value)); 1328 } 1329 1330 /** 1331 * Returns the value of a String parameter. 1332 * 1333 * @param key the key name for the parameter 1334 * @return the String value of the parameter 1335 */ 1336 public String get(String key) { 1337 return mMap.get(key); 1338 } 1339 1340 /** 1341 * Returns the value of an integer parameter. 1342 * 1343 * @param key the key name for the parameter 1344 * @return the int value of the parameter 1345 */ 1346 public int getInt(String key) { 1347 return Integer.parseInt(mMap.get(key)); 1348 } 1349 1350 /** 1351 * Sets the dimensions for preview pictures. 1352 * 1353 * @param width the width of the pictures, in pixels 1354 * @param height the height of the pictures, in pixels 1355 */ 1356 public void setPreviewSize(int width, int height) { 1357 String v = Integer.toString(width) + "x" + Integer.toString(height); 1358 set(KEY_PREVIEW_SIZE, v); 1359 } 1360 1361 /** 1362 * Returns the dimensions setting for preview pictures. 1363 * 1364 * @return a Size object with the height and width setting 1365 * for the preview picture 1366 */ 1367 public Size getPreviewSize() { 1368 String pair = get(KEY_PREVIEW_SIZE); 1369 return strToSize(pair); 1370 } 1371 1372 /** 1373 * Gets the supported preview sizes. 1374 * 1375 * @return a list of Size object. This method will always return a list 1376 * with at least one element. 1377 */ 1378 public List<Size> getSupportedPreviewSizes() { 1379 String str = get(KEY_PREVIEW_SIZE + SUPPORTED_VALUES_SUFFIX); 1380 return splitSize(str); 1381 } 1382 1383 /** 1384 * Sets the dimensions for EXIF thumbnail in Jpeg picture. If 1385 * applications set both width and height to 0, EXIF will not contain 1386 * thumbnail. 1387 * 1388 * @param width the width of the thumbnail, in pixels 1389 * @param height the height of the thumbnail, in pixels 1390 */ 1391 public void setJpegThumbnailSize(int width, int height) { 1392 set(KEY_JPEG_THUMBNAIL_WIDTH, width); 1393 set(KEY_JPEG_THUMBNAIL_HEIGHT, height); 1394 } 1395 1396 /** 1397 * Returns the dimensions for EXIF thumbnail in Jpeg picture. 1398 * 1399 * @return a Size object with the height and width setting for the EXIF 1400 * thumbnails 1401 */ 1402 public Size getJpegThumbnailSize() { 1403 return new Size(getInt(KEY_JPEG_THUMBNAIL_WIDTH), 1404 getInt(KEY_JPEG_THUMBNAIL_HEIGHT)); 1405 } 1406 1407 /** 1408 * Gets the supported jpeg thumbnail sizes. 1409 * 1410 * @return a list of Size object. This method will always return a list 1411 * with at least two elements. Size 0,0 (no thumbnail) is always 1412 * supported. 1413 */ 1414 public List<Size> getSupportedJpegThumbnailSizes() { 1415 String str = get(KEY_JPEG_THUMBNAIL_SIZE + SUPPORTED_VALUES_SUFFIX); 1416 return splitSize(str); 1417 } 1418 1419 /** 1420 * Sets the quality of the EXIF thumbnail in Jpeg picture. 1421 * 1422 * @param quality the JPEG quality of the EXIF thumbnail. The range is 1 1423 * to 100, with 100 being the best. 1424 */ 1425 public void setJpegThumbnailQuality(int quality) { 1426 set(KEY_JPEG_THUMBNAIL_QUALITY, quality); 1427 } 1428 1429 /** 1430 * Returns the quality setting for the EXIF thumbnail in Jpeg picture. 1431 * 1432 * @return the JPEG quality setting of the EXIF thumbnail. 1433 */ 1434 public int getJpegThumbnailQuality() { 1435 return getInt(KEY_JPEG_THUMBNAIL_QUALITY); 1436 } 1437 1438 /** 1439 * Sets Jpeg quality of captured picture. 1440 * 1441 * @param quality the JPEG quality of captured picture. The range is 1 1442 * to 100, with 100 being the best. 1443 */ 1444 public void setJpegQuality(int quality) { 1445 set(KEY_JPEG_QUALITY, quality); 1446 } 1447 1448 /** 1449 * Returns the quality setting for the JPEG picture. 1450 * 1451 * @return the JPEG picture quality setting. 1452 */ 1453 public int getJpegQuality() { 1454 return getInt(KEY_JPEG_QUALITY); 1455 } 1456 1457 /** 1458 * Sets the rate at which preview frames are received. This is the 1459 * target frame rate. The actual frame rate depends on the driver. 1460 * 1461 * @param fps the frame rate (frames per second) 1462 * @deprecated replaced by {@link #setPreviewFpsRange(int,int)} 1463 */ 1464 @Deprecated 1465 public void setPreviewFrameRate(int fps) { 1466 set(KEY_PREVIEW_FRAME_RATE, fps); 1467 } 1468 1469 /** 1470 * Returns the setting for the rate at which preview frames are 1471 * received. This is the target frame rate. The actual frame rate 1472 * depends on the driver. 1473 * 1474 * @return the frame rate setting (frames per second) 1475 * @deprecated replaced by {@link #getPreviewFpsRange(int[])} 1476 */ 1477 @Deprecated 1478 public int getPreviewFrameRate() { 1479 return getInt(KEY_PREVIEW_FRAME_RATE); 1480 } 1481 1482 /** 1483 * Gets the supported preview frame rates. 1484 * 1485 * @return a list of supported preview frame rates. null if preview 1486 * frame rate setting is not supported. 1487 * @deprecated replaced by {@link #getSupportedPreviewFpsRange()} 1488 */ 1489 @Deprecated 1490 public List<Integer> getSupportedPreviewFrameRates() { 1491 String str = get(KEY_PREVIEW_FRAME_RATE + SUPPORTED_VALUES_SUFFIX); 1492 return splitInt(str); 1493 } 1494 1495 /** 1496 * Sets the maximum and maximum preview fps. This controls the rate of 1497 * preview frames received in {@link PreviewCallback}. The minimum and 1498 * maximum preview fps must be one of the elements from {@link 1499 * #getSupportedPreviewFpsRange}. 1500 * 1501 * @param min the minimum preview fps (scaled by 1000). 1502 * @param max the maximum preview fps (scaled by 1000). 1503 * @throws RuntimeException if fps range is invalid. 1504 * @see #setPreviewCallbackWithBuffer(Camera.PreviewCallback) 1505 * @see #getSupportedPreviewFpsRange() 1506 */ 1507 public void setPreviewFpsRange(int min, int max) { 1508 set(KEY_PREVIEW_FPS_RANGE, "" + min + "," + max); 1509 } 1510 1511 /** 1512 * Returns the current minimum and maximum preview fps. The values are 1513 * one of the elements returned by {@link #getSupportedPreviewFpsRange}. 1514 * 1515 * @return range the minimum and maximum preview fps (scaled by 1000). 1516 * @see #PREVIEW_FPS_MIN_INDEX 1517 * @see #PREVIEW_FPS_MAX_INDEX 1518 * @see #getSupportedPreviewFpsRange() 1519 */ 1520 public void getPreviewFpsRange(int[] range) { 1521 if (range == null || range.length != 2) { 1522 throw new IllegalArgumentException( 1523 "range must be an array with two elements."); 1524 } 1525 splitInt(get(KEY_PREVIEW_FPS_RANGE), range); 1526 } 1527 1528 /** 1529 * Gets the supported preview fps (frame-per-second) ranges. Each range 1530 * contains a minimum fps and maximum fps. If minimum fps equals to 1531 * maximum fps, the camera outputs frames in fixed frame rate. If not, 1532 * the camera outputs frames in auto frame rate. The actual frame rate 1533 * fluctuates between the minimum and the maximum. The values are 1534 * multiplied by 1000 and represented in integers. For example, if frame 1535 * rate is 26.623 frames per second, the value is 26623. 1536 * 1537 * @return a list of supported preview fps ranges. This method returns a 1538 * list with at least one element. Every element is an int array 1539 * of two values - minimum fps and maximum fps. The list is 1540 * sorted from small to large (first by maximum fps and then 1541 * minimum fps). 1542 * @see #PREVIEW_FPS_MIN_INDEX 1543 * @see #PREVIEW_FPS_MAX_INDEX 1544 */ 1545 public List<int[]> getSupportedPreviewFpsRange() { 1546 String str = get(KEY_PREVIEW_FPS_RANGE + SUPPORTED_VALUES_SUFFIX); 1547 return splitRange(str); 1548 } 1549 1550 /** 1551 * Sets the image format for preview pictures. 1552 * <p>If this is never called, the default format will be 1553 * {@link android.graphics.ImageFormat#NV21}, which 1554 * uses the NV21 encoding format.</p> 1555 * 1556 * @param pixel_format the desired preview picture format, defined 1557 * by one of the {@link android.graphics.ImageFormat} constants. 1558 * (E.g., <var>ImageFormat.NV21</var> (default), 1559 * <var>ImageFormat.RGB_565</var>, or 1560 * <var>ImageFormat.JPEG</var>) 1561 * @see android.graphics.ImageFormat 1562 */ 1563 public void setPreviewFormat(int pixel_format) { 1564 String s = cameraFormatForPixelFormat(pixel_format); 1565 if (s == null) { 1566 throw new IllegalArgumentException( 1567 "Invalid pixel_format=" + pixel_format); 1568 } 1569 1570 set(KEY_PREVIEW_FORMAT, s); 1571 } 1572 1573 /** 1574 * Returns the image format for preview frames got from 1575 * {@link PreviewCallback}. 1576 * 1577 * @return the preview format. 1578 * @see android.graphics.ImageFormat 1579 */ 1580 public int getPreviewFormat() { 1581 return pixelFormatForCameraFormat(get(KEY_PREVIEW_FORMAT)); 1582 } 1583 1584 /** 1585 * Gets the supported preview formats. 1586 * 1587 * @return a list of supported preview formats. This method will always 1588 * return a list with at least one element. 1589 * @see android.graphics.ImageFormat 1590 */ 1591 public List<Integer> getSupportedPreviewFormats() { 1592 String str = get(KEY_PREVIEW_FORMAT + SUPPORTED_VALUES_SUFFIX); 1593 ArrayList<Integer> formats = new ArrayList<Integer>(); 1594 for (String s : split(str)) { 1595 int f = pixelFormatForCameraFormat(s); 1596 if (f == ImageFormat.UNKNOWN) continue; 1597 formats.add(f); 1598 } 1599 return formats; 1600 } 1601 1602 /** 1603 * Sets the dimensions for pictures. 1604 * 1605 * @param width the width for pictures, in pixels 1606 * @param height the height for pictures, in pixels 1607 */ 1608 public void setPictureSize(int width, int height) { 1609 String v = Integer.toString(width) + "x" + Integer.toString(height); 1610 set(KEY_PICTURE_SIZE, v); 1611 } 1612 1613 /** 1614 * Returns the dimension setting for pictures. 1615 * 1616 * @return a Size object with the height and width setting 1617 * for pictures 1618 */ 1619 public Size getPictureSize() { 1620 String pair = get(KEY_PICTURE_SIZE); 1621 return strToSize(pair); 1622 } 1623 1624 /** 1625 * Gets the supported picture sizes. 1626 * 1627 * @return a list of supported picture sizes. This method will always 1628 * return a list with at least one element. 1629 */ 1630 public List<Size> getSupportedPictureSizes() { 1631 String str = get(KEY_PICTURE_SIZE + SUPPORTED_VALUES_SUFFIX); 1632 return splitSize(str); 1633 } 1634 1635 /** 1636 * Sets the image format for pictures. 1637 * 1638 * @param pixel_format the desired picture format 1639 * (<var>ImageFormat.NV21</var>, 1640 * <var>ImageFormat.RGB_565</var>, or 1641 * <var>ImageFormat.JPEG</var>) 1642 * @see android.graphics.ImageFormat 1643 */ 1644 public void setPictureFormat(int pixel_format) { 1645 String s = cameraFormatForPixelFormat(pixel_format); 1646 if (s == null) { 1647 throw new IllegalArgumentException( 1648 "Invalid pixel_format=" + pixel_format); 1649 } 1650 1651 set(KEY_PICTURE_FORMAT, s); 1652 } 1653 1654 /** 1655 * Returns the image format for pictures. 1656 * 1657 * @return the picture format 1658 * @see android.graphics.ImageFormat 1659 */ 1660 public int getPictureFormat() { 1661 return pixelFormatForCameraFormat(get(KEY_PICTURE_FORMAT)); 1662 } 1663 1664 /** 1665 * Gets the supported picture formats. 1666 * 1667 * @return supported picture formats. This method will always return a 1668 * list with at least one element. 1669 * @see android.graphics.ImageFormat 1670 */ 1671 public List<Integer> getSupportedPictureFormats() { 1672 String str = get(KEY_PICTURE_FORMAT + SUPPORTED_VALUES_SUFFIX); 1673 ArrayList<Integer> formats = new ArrayList<Integer>(); 1674 for (String s : split(str)) { 1675 int f = pixelFormatForCameraFormat(s); 1676 if (f == ImageFormat.UNKNOWN) continue; 1677 formats.add(f); 1678 } 1679 return formats; 1680 } 1681 1682 private String cameraFormatForPixelFormat(int pixel_format) { 1683 switch(pixel_format) { 1684 case ImageFormat.NV16: return PIXEL_FORMAT_YUV422SP; 1685 case ImageFormat.NV21: return PIXEL_FORMAT_YUV420SP; 1686 case ImageFormat.YUY2: return PIXEL_FORMAT_YUV422I; 1687 case ImageFormat.RGB_565: return PIXEL_FORMAT_RGB565; 1688 case ImageFormat.JPEG: return PIXEL_FORMAT_JPEG; 1689 default: return null; 1690 } 1691 } 1692 1693 private int pixelFormatForCameraFormat(String format) { 1694 if (format == null) 1695 return ImageFormat.UNKNOWN; 1696 1697 if (format.equals(PIXEL_FORMAT_YUV422SP)) 1698 return ImageFormat.NV16; 1699 1700 if (format.equals(PIXEL_FORMAT_YUV420SP)) 1701 return ImageFormat.NV21; 1702 1703 if (format.equals(PIXEL_FORMAT_YUV422I)) 1704 return ImageFormat.YUY2; 1705 1706 if (format.equals(PIXEL_FORMAT_RGB565)) 1707 return ImageFormat.RGB_565; 1708 1709 if (format.equals(PIXEL_FORMAT_JPEG)) 1710 return ImageFormat.JPEG; 1711 1712 return ImageFormat.UNKNOWN; 1713 } 1714 1715 /** 1716 * Sets the orientation of the device in degrees. For example, suppose 1717 * the natural position of the device is landscape. If the user takes a 1718 * picture in landscape mode in 2048x1536 resolution, the rotation 1719 * should be set to 0. If the user rotates the phone 90 degrees 1720 * clockwise, the rotation should be set to 90. Applications can use 1721 * {@link android.view.OrientationEventListener} to set this parameter. 1722 * 1723 * The camera driver may set orientation in the EXIF header without 1724 * rotating the picture. Or the driver may rotate the picture and 1725 * the EXIF thumbnail. If the Jpeg picture is rotated, the orientation 1726 * in the EXIF header will be missing or 1 (row #0 is top and column #0 1727 * is left side). 1728 * 1729 * @param rotation The orientation of the device in degrees. Rotation 1730 * can only be 0, 90, 180 or 270. 1731 * @throws IllegalArgumentException if rotation value is invalid. 1732 * @see android.view.OrientationEventListener 1733 */ 1734 public void setRotation(int rotation) { 1735 if (rotation == 0 || rotation == 90 || rotation == 180 1736 || rotation == 270) { 1737 set(KEY_ROTATION, Integer.toString(rotation)); 1738 } else { 1739 throw new IllegalArgumentException( 1740 "Invalid rotation=" + rotation); 1741 } 1742 } 1743 1744 /** 1745 * Sets GPS latitude coordinate. This will be stored in JPEG EXIF 1746 * header. 1747 * 1748 * @param latitude GPS latitude coordinate. 1749 */ 1750 public void setGpsLatitude(double latitude) { 1751 set(KEY_GPS_LATITUDE, Double.toString(latitude)); 1752 } 1753 1754 /** 1755 * Sets GPS longitude coordinate. This will be stored in JPEG EXIF 1756 * header. 1757 * 1758 * @param longitude GPS longitude coordinate. 1759 */ 1760 public void setGpsLongitude(double longitude) { 1761 set(KEY_GPS_LONGITUDE, Double.toString(longitude)); 1762 } 1763 1764 /** 1765 * Sets GPS altitude. This will be stored in JPEG EXIF header. 1766 * 1767 * @param altitude GPS altitude in meters. 1768 */ 1769 public void setGpsAltitude(double altitude) { 1770 set(KEY_GPS_ALTITUDE, Double.toString(altitude)); 1771 } 1772 1773 /** 1774 * Sets GPS timestamp. This will be stored in JPEG EXIF header. 1775 * 1776 * @param timestamp GPS timestamp (UTC in seconds since January 1, 1777 * 1970). 1778 */ 1779 public void setGpsTimestamp(long timestamp) { 1780 set(KEY_GPS_TIMESTAMP, Long.toString(timestamp)); 1781 } 1782 1783 /** 1784 * Sets GPS processing method. It will store up to 32 characters 1785 * in JPEG EXIF header. 1786 * 1787 * @param processing_method The processing method to get this location. 1788 */ 1789 public void setGpsProcessingMethod(String processing_method) { 1790 set(KEY_GPS_PROCESSING_METHOD, processing_method); 1791 } 1792 1793 /** 1794 * Removes GPS latitude, longitude, altitude, and timestamp from the 1795 * parameters. 1796 */ 1797 public void removeGpsData() { 1798 remove(KEY_GPS_LATITUDE); 1799 remove(KEY_GPS_LONGITUDE); 1800 remove(KEY_GPS_ALTITUDE); 1801 remove(KEY_GPS_TIMESTAMP); 1802 remove(KEY_GPS_PROCESSING_METHOD); 1803 } 1804 1805 /** 1806 * Gets the current white balance setting. 1807 * 1808 * @return current white balance. null if white balance setting is not 1809 * supported. 1810 * @see #WHITE_BALANCE_AUTO 1811 * @see #WHITE_BALANCE_INCANDESCENT 1812 * @see #WHITE_BALANCE_FLUORESCENT 1813 * @see #WHITE_BALANCE_WARM_FLUORESCENT 1814 * @see #WHITE_BALANCE_DAYLIGHT 1815 * @see #WHITE_BALANCE_CLOUDY_DAYLIGHT 1816 * @see #WHITE_BALANCE_TWILIGHT 1817 * @see #WHITE_BALANCE_SHADE 1818 * 1819 */ 1820 public String getWhiteBalance() { 1821 return get(KEY_WHITE_BALANCE); 1822 } 1823 1824 /** 1825 * Sets the white balance. 1826 * 1827 * @param value new white balance. 1828 * @see #getWhiteBalance() 1829 */ 1830 public void setWhiteBalance(String value) { 1831 set(KEY_WHITE_BALANCE, value); 1832 } 1833 1834 /** 1835 * Gets the supported white balance. 1836 * 1837 * @return a list of supported white balance. null if white balance 1838 * setting is not supported. 1839 * @see #getWhiteBalance() 1840 */ 1841 public List<String> getSupportedWhiteBalance() { 1842 String str = get(KEY_WHITE_BALANCE + SUPPORTED_VALUES_SUFFIX); 1843 return split(str); 1844 } 1845 1846 /** 1847 * Gets the current color effect setting. 1848 * 1849 * @return current color effect. null if color effect 1850 * setting is not supported. 1851 * @see #EFFECT_NONE 1852 * @see #EFFECT_MONO 1853 * @see #EFFECT_NEGATIVE 1854 * @see #EFFECT_SOLARIZE 1855 * @see #EFFECT_SEPIA 1856 * @see #EFFECT_POSTERIZE 1857 * @see #EFFECT_WHITEBOARD 1858 * @see #EFFECT_BLACKBOARD 1859 * @see #EFFECT_AQUA 1860 */ 1861 public String getColorEffect() { 1862 return get(KEY_EFFECT); 1863 } 1864 1865 /** 1866 * Sets the current color effect setting. 1867 * 1868 * @param value new color effect. 1869 * @see #getColorEffect() 1870 */ 1871 public void setColorEffect(String value) { 1872 set(KEY_EFFECT, value); 1873 } 1874 1875 /** 1876 * Gets the supported color effects. 1877 * 1878 * @return a list of supported color effects. null if color effect 1879 * setting is not supported. 1880 * @see #getColorEffect() 1881 */ 1882 public List<String> getSupportedColorEffects() { 1883 String str = get(KEY_EFFECT + SUPPORTED_VALUES_SUFFIX); 1884 return split(str); 1885 } 1886 1887 1888 /** 1889 * Gets the current antibanding setting. 1890 * 1891 * @return current antibanding. null if antibanding setting is not 1892 * supported. 1893 * @see #ANTIBANDING_AUTO 1894 * @see #ANTIBANDING_50HZ 1895 * @see #ANTIBANDING_60HZ 1896 * @see #ANTIBANDING_OFF 1897 */ 1898 public String getAntibanding() { 1899 return get(KEY_ANTIBANDING); 1900 } 1901 1902 /** 1903 * Sets the antibanding. 1904 * 1905 * @param antibanding new antibanding value. 1906 * @see #getAntibanding() 1907 */ 1908 public void setAntibanding(String antibanding) { 1909 set(KEY_ANTIBANDING, antibanding); 1910 } 1911 1912 /** 1913 * Gets the supported antibanding values. 1914 * 1915 * @return a list of supported antibanding values. null if antibanding 1916 * setting is not supported. 1917 * @see #getAntibanding() 1918 */ 1919 public List<String> getSupportedAntibanding() { 1920 String str = get(KEY_ANTIBANDING + SUPPORTED_VALUES_SUFFIX); 1921 return split(str); 1922 } 1923 1924 /** 1925 * Gets the current scene mode setting. 1926 * 1927 * @return one of SCENE_MODE_XXX string constant. null if scene mode 1928 * setting is not supported. 1929 * @see #SCENE_MODE_AUTO 1930 * @see #SCENE_MODE_ACTION 1931 * @see #SCENE_MODE_PORTRAIT 1932 * @see #SCENE_MODE_LANDSCAPE 1933 * @see #SCENE_MODE_NIGHT 1934 * @see #SCENE_MODE_NIGHT_PORTRAIT 1935 * @see #SCENE_MODE_THEATRE 1936 * @see #SCENE_MODE_BEACH 1937 * @see #SCENE_MODE_SNOW 1938 * @see #SCENE_MODE_SUNSET 1939 * @see #SCENE_MODE_STEADYPHOTO 1940 * @see #SCENE_MODE_FIREWORKS 1941 * @see #SCENE_MODE_SPORTS 1942 * @see #SCENE_MODE_PARTY 1943 * @see #SCENE_MODE_CANDLELIGHT 1944 */ 1945 public String getSceneMode() { 1946 return get(KEY_SCENE_MODE); 1947 } 1948 1949 /** 1950 * Sets the scene mode. Changing scene mode may override other 1951 * parameters (such as flash mode, focus mode, white balance). For 1952 * example, suppose originally flash mode is on and supported flash 1953 * modes are on/off. In night scene mode, both flash mode and supported 1954 * flash mode may be changed to off. After setting scene mode, 1955 * applications should call getParameters to know if some parameters are 1956 * changed. 1957 * 1958 * @param value scene mode. 1959 * @see #getSceneMode() 1960 */ 1961 public void setSceneMode(String value) { 1962 set(KEY_SCENE_MODE, value); 1963 } 1964 1965 /** 1966 * Gets the supported scene modes. 1967 * 1968 * @return a list of supported scene modes. null if scene mode setting 1969 * is not supported. 1970 * @see #getSceneMode() 1971 */ 1972 public List<String> getSupportedSceneModes() { 1973 String str = get(KEY_SCENE_MODE + SUPPORTED_VALUES_SUFFIX); 1974 return split(str); 1975 } 1976 1977 /** 1978 * Gets the current flash mode setting. 1979 * 1980 * @return current flash mode. null if flash mode setting is not 1981 * supported. 1982 * @see #FLASH_MODE_OFF 1983 * @see #FLASH_MODE_AUTO 1984 * @see #FLASH_MODE_ON 1985 * @see #FLASH_MODE_RED_EYE 1986 * @see #FLASH_MODE_TORCH 1987 */ 1988 public String getFlashMode() { 1989 return get(KEY_FLASH_MODE); 1990 } 1991 1992 /** 1993 * Sets the flash mode. 1994 * 1995 * @param value flash mode. 1996 * @see #getFlashMode() 1997 */ 1998 public void setFlashMode(String value) { 1999 set(KEY_FLASH_MODE, value); 2000 } 2001 2002 /** 2003 * Gets the supported flash modes. 2004 * 2005 * @return a list of supported flash modes. null if flash mode setting 2006 * is not supported. 2007 * @see #getFlashMode() 2008 */ 2009 public List<String> getSupportedFlashModes() { 2010 String str = get(KEY_FLASH_MODE + SUPPORTED_VALUES_SUFFIX); 2011 return split(str); 2012 } 2013 2014 /** 2015 * Gets the current focus mode setting. 2016 * 2017 * @return current focus mode. This method will always return a non-null 2018 * value. Applications should call {@link 2019 * #autoFocus(AutoFocusCallback)} to start the focus if focus 2020 * mode is FOCUS_MODE_AUTO or FOCUS_MODE_MACRO. 2021 * @see #FOCUS_MODE_AUTO 2022 * @see #FOCUS_MODE_INFINITY 2023 * @see #FOCUS_MODE_MACRO 2024 * @see #FOCUS_MODE_FIXED 2025 * @see #FOCUS_MODE_EDOF 2026 * @see #FOCUS_MODE_CONTINUOUS 2027 */ 2028 public String getFocusMode() { 2029 return get(KEY_FOCUS_MODE); 2030 } 2031 2032 /** 2033 * Sets the focus mode. 2034 * 2035 * @param value focus mode. 2036 * @see #getFocusMode() 2037 */ 2038 public void setFocusMode(String value) { 2039 set(KEY_FOCUS_MODE, value); 2040 } 2041 2042 /** 2043 * Gets the supported focus modes. 2044 * 2045 * @return a list of supported focus modes. This method will always 2046 * return a list with at least one element. 2047 * @see #getFocusMode() 2048 */ 2049 public List<String> getSupportedFocusModes() { 2050 String str = get(KEY_FOCUS_MODE + SUPPORTED_VALUES_SUFFIX); 2051 return split(str); 2052 } 2053 2054 /** 2055 * Gets the focal length (in millimeter) of the camera. 2056 * 2057 * @return the focal length. This method will always return a valid 2058 * value. 2059 */ 2060 public float getFocalLength() { 2061 return Float.parseFloat(get(KEY_FOCAL_LENGTH)); 2062 } 2063 2064 /** 2065 * Gets the horizontal angle of view in degrees. 2066 * 2067 * @return horizontal angle of view. This method will always return a 2068 * valid value. 2069 */ 2070 public float getHorizontalViewAngle() { 2071 return Float.parseFloat(get(KEY_HORIZONTAL_VIEW_ANGLE)); 2072 } 2073 2074 /** 2075 * Gets the vertical angle of view in degrees. 2076 * 2077 * @return vertical angle of view. This method will always return a 2078 * valid value. 2079 */ 2080 public float getVerticalViewAngle() { 2081 return Float.parseFloat(get(KEY_VERTICAL_VIEW_ANGLE)); 2082 } 2083 2084 /** 2085 * Gets the current exposure compensation index. 2086 * 2087 * @return current exposure compensation index. The range is {@link 2088 * #getMinExposureCompensation} to {@link 2089 * #getMaxExposureCompensation}. 0 means exposure is not 2090 * adjusted. 2091 */ 2092 public int getExposureCompensation() { 2093 return getInt(KEY_EXPOSURE_COMPENSATION, 0); 2094 } 2095 2096 /** 2097 * Sets the exposure compensation index. 2098 * 2099 * @param value exposure compensation index. The valid value range is 2100 * from {@link #getMinExposureCompensation} (inclusive) to {@link 2101 * #getMaxExposureCompensation} (inclusive). 0 means exposure is 2102 * not adjusted. Application should call 2103 * getMinExposureCompensation and getMaxExposureCompensation to 2104 * know if exposure compensation is supported. 2105 */ 2106 public void setExposureCompensation(int value) { 2107 set(KEY_EXPOSURE_COMPENSATION, value); 2108 } 2109 2110 /** 2111 * Gets the maximum exposure compensation index. 2112 * 2113 * @return maximum exposure compensation index (>=0). If both this 2114 * method and {@link #getMinExposureCompensation} return 0, 2115 * exposure compensation is not supported. 2116 */ 2117 public int getMaxExposureCompensation() { 2118 return getInt(KEY_MAX_EXPOSURE_COMPENSATION, 0); 2119 } 2120 2121 /** 2122 * Gets the minimum exposure compensation index. 2123 * 2124 * @return minimum exposure compensation index (<=0). If both this 2125 * method and {@link #getMaxExposureCompensation} return 0, 2126 * exposure compensation is not supported. 2127 */ 2128 public int getMinExposureCompensation() { 2129 return getInt(KEY_MIN_EXPOSURE_COMPENSATION, 0); 2130 } 2131 2132 /** 2133 * Gets the exposure compensation step. 2134 * 2135 * @return exposure compensation step. Applications can get EV by 2136 * multiplying the exposure compensation index and step. Ex: if 2137 * exposure compensation index is -6 and step is 0.333333333, EV 2138 * is -2. 2139 */ 2140 public float getExposureCompensationStep() { 2141 return getFloat(KEY_EXPOSURE_COMPENSATION_STEP, 0); 2142 } 2143 2144 /** 2145 * Gets current zoom value. This also works when smooth zoom is in 2146 * progress. Applications should check {@link #isZoomSupported} before 2147 * using this method. 2148 * 2149 * @return the current zoom value. The range is 0 to {@link 2150 * #getMaxZoom}. 0 means the camera is not zoomed. 2151 */ 2152 public int getZoom() { 2153 return getInt(KEY_ZOOM, 0); 2154 } 2155 2156 /** 2157 * Sets current zoom value. If the camera is zoomed (value > 0), the 2158 * actual picture size may be smaller than picture size setting. 2159 * Applications can check the actual picture size after picture is 2160 * returned from {@link PictureCallback}. The preview size remains the 2161 * same in zoom. Applications should check {@link #isZoomSupported} 2162 * before using this method. 2163 * 2164 * @param value zoom value. The valid range is 0 to {@link #getMaxZoom}. 2165 */ 2166 public void setZoom(int value) { 2167 set(KEY_ZOOM, value); 2168 } 2169 2170 /** 2171 * Returns true if zoom is supported. Applications should call this 2172 * before using other zoom methods. 2173 * 2174 * @return true if zoom is supported. 2175 */ 2176 public boolean isZoomSupported() { 2177 String str = get(KEY_ZOOM_SUPPORTED); 2178 return TRUE.equals(str); 2179 } 2180 2181 /** 2182 * Gets the maximum zoom value allowed for snapshot. This is the maximum 2183 * value that applications can set to {@link #setZoom(int)}. 2184 * Applications should call {@link #isZoomSupported} before using this 2185 * method. This value may change in different preview size. Applications 2186 * should call this again after setting preview size. 2187 * 2188 * @return the maximum zoom value supported by the camera. 2189 */ 2190 public int getMaxZoom() { 2191 return getInt(KEY_MAX_ZOOM, 0); 2192 } 2193 2194 /** 2195 * Gets the zoom ratios of all zoom values. Applications should check 2196 * {@link #isZoomSupported} before using this method. 2197 * 2198 * @return the zoom ratios in 1/100 increments. Ex: a zoom of 3.2x is 2199 * returned as 320. The number of elements is {@link 2200 * #getMaxZoom} + 1. The list is sorted from small to large. The 2201 * first element is always 100. The last element is the zoom 2202 * ratio of the maximum zoom value. 2203 */ 2204 public List<Integer> getZoomRatios() { 2205 return splitInt(get(KEY_ZOOM_RATIOS)); 2206 } 2207 2208 /** 2209 * Returns true if smooth zoom is supported. Applications should call 2210 * this before using other smooth zoom methods. 2211 * 2212 * @return true if smooth zoom is supported. 2213 */ 2214 public boolean isSmoothZoomSupported() { 2215 String str = get(KEY_SMOOTH_ZOOM_SUPPORTED); 2216 return TRUE.equals(str); 2217 } 2218 2219 /** 2220 * Gets the distances from the camera to where an object appears to be 2221 * in focus. The object is sharpest at the optimal focus distance. The 2222 * depth of field is the far focus distance minus near focus distance. 2223 * 2224 * Focus distances may change after calling {@link 2225 * #autoFocus(AutoFocusCallback)}, {@link #cancelAutoFocus}, or {@link 2226 * #startPreview()}. Applications can call {@link #getParameters()} 2227 * and this method anytime to get the latest focus distances. If the 2228 * focus mode is FOCUS_MODE_CONTINUOUS, focus distances may change from 2229 * time to time. 2230 * 2231 * This method is intended to estimate the distance between the camera 2232 * and the subject. After autofocus, the subject distance may be within 2233 * near and far focus distance. However, the precision depends on the 2234 * camera hardware, autofocus algorithm, the focus area, and the scene. 2235 * The error can be large and it should be only used as a reference. 2236 * 2237 * Far focus distance >= optimal focus distance >= near focus distance. 2238 * If the focus distance is infinity, the value will be 2239 * Float.POSITIVE_INFINITY. 2240 * 2241 * @param output focus distances in meters. output must be a float 2242 * array with three elements. Near focus distance, optimal focus 2243 * distance, and far focus distance will be filled in the array. 2244 * @see #FOCUS_DISTANCE_NEAR_INDEX 2245 * @see #FOCUS_DISTANCE_OPTIMAL_INDEX 2246 * @see #FOCUS_DISTANCE_FAR_INDEX 2247 */ 2248 public void getFocusDistances(float[] output) { 2249 if (output == null || output.length != 3) { 2250 throw new IllegalArgumentException( 2251 "output must be an float array with three elements."); 2252 } 2253 splitFloat(get(KEY_FOCUS_DISTANCES), output); 2254 } 2255 2256 // Splits a comma delimited string to an ArrayList of String. 2257 // Return null if the passing string is null or the size is 0. 2258 private ArrayList<String> split(String str) { 2259 if (str == null) return null; 2260 2261 // Use StringTokenizer because it is faster than split. 2262 StringTokenizer tokenizer = new StringTokenizer(str, ","); 2263 ArrayList<String> substrings = new ArrayList<String>(); 2264 while (tokenizer.hasMoreElements()) { 2265 substrings.add(tokenizer.nextToken()); 2266 } 2267 return substrings; 2268 } 2269 2270 // Splits a comma delimited string to an ArrayList of Integer. 2271 // Return null if the passing string is null or the size is 0. 2272 private ArrayList<Integer> splitInt(String str) { 2273 if (str == null) return null; 2274 2275 StringTokenizer tokenizer = new StringTokenizer(str, ","); 2276 ArrayList<Integer> substrings = new ArrayList<Integer>(); 2277 while (tokenizer.hasMoreElements()) { 2278 String token = tokenizer.nextToken(); 2279 substrings.add(Integer.parseInt(token)); 2280 } 2281 if (substrings.size() == 0) return null; 2282 return substrings; 2283 } 2284 2285 private void splitInt(String str, int[] output) { 2286 if (str == null) return; 2287 2288 StringTokenizer tokenizer = new StringTokenizer(str, ","); 2289 int index = 0; 2290 while (tokenizer.hasMoreElements()) { 2291 String token = tokenizer.nextToken(); 2292 output[index++] = Integer.parseInt(token); 2293 } 2294 } 2295 2296 // Splits a comma delimited string to an ArrayList of Float. 2297 private void splitFloat(String str, float[] output) { 2298 if (str == null) return; 2299 2300 StringTokenizer tokenizer = new StringTokenizer(str, ","); 2301 int index = 0; 2302 while (tokenizer.hasMoreElements()) { 2303 String token = tokenizer.nextToken(); 2304 output[index++] = Float.parseFloat(token); 2305 } 2306 } 2307 2308 // Returns the value of a float parameter. 2309 private float getFloat(String key, float defaultValue) { 2310 try { 2311 return Float.parseFloat(mMap.get(key)); 2312 } catch (NumberFormatException ex) { 2313 return defaultValue; 2314 } 2315 } 2316 2317 // Returns the value of a integer parameter. 2318 private int getInt(String key, int defaultValue) { 2319 try { 2320 return Integer.parseInt(mMap.get(key)); 2321 } catch (NumberFormatException ex) { 2322 return defaultValue; 2323 } 2324 } 2325 2326 // Splits a comma delimited string to an ArrayList of Size. 2327 // Return null if the passing string is null or the size is 0. 2328 private ArrayList<Size> splitSize(String str) { 2329 if (str == null) return null; 2330 2331 StringTokenizer tokenizer = new StringTokenizer(str, ","); 2332 ArrayList<Size> sizeList = new ArrayList<Size>(); 2333 while (tokenizer.hasMoreElements()) { 2334 Size size = strToSize(tokenizer.nextToken()); 2335 if (size != null) sizeList.add(size); 2336 } 2337 if (sizeList.size() == 0) return null; 2338 return sizeList; 2339 } 2340 2341 // Parses a string (ex: "480x320") to Size object. 2342 // Return null if the passing string is null. 2343 private Size strToSize(String str) { 2344 if (str == null) return null; 2345 2346 int pos = str.indexOf('x'); 2347 if (pos != -1) { 2348 String width = str.substring(0, pos); 2349 String height = str.substring(pos + 1); 2350 return new Size(Integer.parseInt(width), 2351 Integer.parseInt(height)); 2352 } 2353 Log.e(TAG, "Invalid size parameter string=" + str); 2354 return null; 2355 } 2356 2357 // Splits a comma delimited string to an ArrayList of int array. 2358 // Example string: "(10000,26623),(10000,30000)". Return null if the 2359 // passing string is null or the size is 0. 2360 private ArrayList<int[]> splitRange(String str) { 2361 if (str == null || str.charAt(0) != '(' 2362 || str.charAt(str.length() - 1) != ')') { 2363 Log.e(TAG, "Invalid range list string=" + str); 2364 return null; 2365 } 2366 2367 ArrayList<int[]> rangeList = new ArrayList<int[]>(); 2368 int endIndex, fromIndex = 1; 2369 do { 2370 int[] range = new int[2]; 2371 endIndex = str.indexOf("),(", fromIndex); 2372 if (endIndex == -1) endIndex = str.length() - 1; 2373 splitInt(str.substring(fromIndex, endIndex), range); 2374 rangeList.add(range); 2375 fromIndex = endIndex + 3; 2376 } while (endIndex != str.length() - 1); 2377 2378 if (rangeList.size() == 0) return null; 2379 return rangeList; 2380 } 2381 }; 2382} 2383