Camera.java revision eb68c46a40c773eb56ef7bcf8e7ece5c6a5a8d23
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.PixelFormat; 30import android.os.Handler; 31import android.os.Looper; 32import android.os.Message; 33 34/** 35 * The Camera class is used to connect/disconnect with the camera service, 36 * set capture settings, start/stop preview, snap a picture, and retrieve 37 * frames for encoding for video. 38 * <p>There is no default constructor for this class. Use {@link #open()} to 39 * get a Camera object.</p> 40 * 41 * <p>In order to use the device camera, you must declare the 42 * {@link android.Manifest.permission#CAMERA} permission in your Android 43 * Manifest. Also be sure to include the 44 * <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html"><uses-feature></a> 45 * manifest element in order to declare camera features used by your application. 46 * For example, if you use the camera and auto-focus feature, your Manifest 47 * should include the following:</p> 48 * <pre> <uses-permission android:name="android.permission.CAMERA" /> 49 * <uses-feature android:name="android.hardware.camera" /> 50 * <uses-feature android:name="android.hardware.camera.autofocus" /></pre> 51 * 52 * <p class="caution"><strong>Caution:</strong> Different Android-powered devices 53 * may have different hardware specifications, such as megapixel ratings and 54 * auto-focus capabilities. In order for your application to be compatible with 55 * more devices, you should not make assumptions about the device camera 56 * specifications.</p> 57 */ 58public class Camera { 59 private static final String TAG = "Camera"; 60 61 // These match the enums in frameworks/base/include/ui/Camera.h 62 private static final int CAMERA_MSG_ERROR = 0x001; 63 private static final int CAMERA_MSG_SHUTTER = 0x002; 64 private static final int CAMERA_MSG_FOCUS = 0x004; 65 private static final int CAMERA_MSG_ZOOM = 0x008; 66 private static final int CAMERA_MSG_PREVIEW_FRAME = 0x010; 67 private static final int CAMERA_MSG_VIDEO_FRAME = 0x020; 68 private static final int CAMERA_MSG_POSTVIEW_FRAME = 0x040; 69 private static final int CAMERA_MSG_RAW_IMAGE = 0x080; 70 private static final int CAMERA_MSG_COMPRESSED_IMAGE = 0x100; 71 private static final int CAMERA_MSG_ALL_MSGS = 0x1FF; 72 73 private int mNativeContext; // accessed by native methods 74 private EventHandler mEventHandler; 75 private ShutterCallback mShutterCallback; 76 private PictureCallback mRawImageCallback; 77 private PictureCallback mJpegCallback; 78 private PreviewCallback mPreviewCallback; 79 private PictureCallback mPostviewCallback; 80 private AutoFocusCallback mAutoFocusCallback; 81 private ZoomCallback mZoomCallback; 82 private ErrorCallback mErrorCallback; 83 private boolean mOneShot; 84 85 /** 86 * Returns a new Camera object. 87 */ 88 public static Camera open() { 89 return new Camera(); 90 } 91 92 Camera() { 93 mShutterCallback = null; 94 mRawImageCallback = null; 95 mJpegCallback = null; 96 mPreviewCallback = null; 97 mPostviewCallback = null; 98 mZoomCallback = null; 99 100 Looper looper; 101 if ((looper = Looper.myLooper()) != null) { 102 mEventHandler = new EventHandler(this, looper); 103 } else if ((looper = Looper.getMainLooper()) != null) { 104 mEventHandler = new EventHandler(this, looper); 105 } else { 106 mEventHandler = null; 107 } 108 109 native_setup(new WeakReference<Camera>(this)); 110 } 111 112 protected void finalize() { 113 native_release(); 114 } 115 116 private native final void native_setup(Object camera_this); 117 private native final void native_release(); 118 119 120 /** 121 * Disconnects and releases the Camera object resources. 122 * <p>It is recommended that you call this as soon as you're done with the 123 * Camera object.</p> 124 */ 125 public final void release() { 126 native_release(); 127 } 128 129 /** 130 * Reconnect to the camera after passing it to MediaRecorder. To save 131 * setup/teardown time, a client of Camera can pass an initialized Camera 132 * object to a MediaRecorder to use for video recording. Once the 133 * MediaRecorder is done with the Camera, this method can be used to 134 * re-establish a connection with the camera hardware. NOTE: The Camera 135 * object must first be unlocked by the process that owns it before it 136 * can be connected to another process. 137 * 138 * @throws IOException if the method fails. 139 * 140 * FIXME: Unhide after approval 141 * @hide 142 */ 143 public native final void reconnect() throws IOException; 144 145 /** 146 * Lock the camera to prevent other processes from accessing it. To save 147 * setup/teardown time, a client of Camera can pass an initialized Camera 148 * object to another process. This method is used to re-lock the Camera 149 * object prevent other processes from accessing it. By default, the 150 * Camera object is locked. Locking it again from the same process will 151 * have no effect. Attempting to lock it from another process if it has 152 * not been unlocked will fail. 153 * Returns 0 if lock was successful. 154 * 155 * FIXME: Unhide after approval 156 * @hide 157 */ 158 public native final int lock(); 159 160 /** 161 * Unlock the camera to allow another process to access it. To save 162 * setup/teardown time, a client of Camera can pass an initialized Camera 163 * object to another process. This method is used to unlock the Camera 164 * object before handing off the Camera object to the other process. 165 166 * Returns 0 if unlock was successful. 167 * 168 * FIXME: Unhide after approval 169 * @hide 170 */ 171 public native final int unlock(); 172 173 /** 174 * Sets the SurfaceHolder to be used for a picture preview. If the surface 175 * changed since the last call, the screen will blank. Nothing happens 176 * if the same surface is re-set. 177 * 178 * @param holder the SurfaceHolder upon which to place the picture preview 179 * @throws IOException if the method fails. 180 */ 181 public final void setPreviewDisplay(SurfaceHolder holder) throws IOException { 182 if (holder != null) { 183 setPreviewDisplay(holder.getSurface()); 184 } else { 185 setPreviewDisplay((Surface)null); 186 } 187 } 188 189 private native final void setPreviewDisplay(Surface surface); 190 191 /** 192 * Used to get a copy of each preview frame. 193 */ 194 public interface PreviewCallback 195 { 196 /** 197 * The callback that delivers the preview frames. 198 * 199 * @param data The contents of the preview frame in the format defined 200 * by {@link android.graphics.PixelFormat}, which can be queried 201 * with {@link android.hardware.Camera.Parameters#getPreviewFormat()}. 202 * If {@link android.hardware.Camera.Parameters#setPreviewFormat(int)} 203 * is never called, the default will be the YCbCr_420_SP 204 * (NV21) format. 205 * @param camera The Camera service object. 206 */ 207 void onPreviewFrame(byte[] data, Camera camera); 208 }; 209 210 /** 211 * Start drawing preview frames to the surface. 212 */ 213 public native final void startPreview(); 214 215 /** 216 * Stop drawing preview frames to the surface. 217 */ 218 public native final void stopPreview(); 219 220 /** 221 * Return current preview state. 222 * 223 * FIXME: Unhide before release 224 * @hide 225 */ 226 public native final boolean previewEnabled(); 227 228 /** 229 * Can be called at any time to instruct the camera to use a callback for 230 * each preview frame in addition to displaying it. 231 * 232 * @param cb A callback object that receives a copy of each preview frame. 233 * Pass null to stop receiving callbacks at any time. 234 */ 235 public final void setPreviewCallback(PreviewCallback cb) { 236 mPreviewCallback = cb; 237 mOneShot = false; 238 setHasPreviewCallback(cb != null, false); 239 } 240 241 /** 242 * Installs a callback to retrieve a single preview frame, after which the 243 * callback is cleared. 244 * 245 * @param cb A callback object that receives a copy of the preview frame. 246 */ 247 public final void setOneShotPreviewCallback(PreviewCallback cb) { 248 if (cb != null) { 249 mPreviewCallback = cb; 250 mOneShot = true; 251 setHasPreviewCallback(true, true); 252 } 253 } 254 255 private native final void setHasPreviewCallback(boolean installed, boolean oneshot); 256 257 private class EventHandler extends Handler 258 { 259 private Camera mCamera; 260 261 public EventHandler(Camera c, Looper looper) { 262 super(looper); 263 mCamera = c; 264 } 265 266 @Override 267 public void handleMessage(Message msg) { 268 switch(msg.what) { 269 case CAMERA_MSG_SHUTTER: 270 if (mShutterCallback != null) { 271 mShutterCallback.onShutter(); 272 } 273 return; 274 275 case CAMERA_MSG_RAW_IMAGE: 276 if (mRawImageCallback != null) { 277 mRawImageCallback.onPictureTaken((byte[])msg.obj, mCamera); 278 } 279 return; 280 281 case CAMERA_MSG_COMPRESSED_IMAGE: 282 if (mJpegCallback != null) { 283 mJpegCallback.onPictureTaken((byte[])msg.obj, mCamera); 284 } 285 return; 286 287 case CAMERA_MSG_PREVIEW_FRAME: 288 if (mPreviewCallback != null) { 289 mPreviewCallback.onPreviewFrame((byte[])msg.obj, mCamera); 290 if (mOneShot) { 291 mPreviewCallback = null; 292 } 293 } 294 return; 295 296 case CAMERA_MSG_POSTVIEW_FRAME: 297 if (mPostviewCallback != null) { 298 mPostviewCallback.onPictureTaken((byte[])msg.obj, mCamera); 299 } 300 return; 301 302 case CAMERA_MSG_FOCUS: 303 if (mAutoFocusCallback != null) { 304 mAutoFocusCallback.onAutoFocus(msg.arg1 == 0 ? false : true, mCamera); 305 } 306 return; 307 308 case CAMERA_MSG_ZOOM: 309 if (mZoomCallback != null) { 310 mZoomCallback.onZoomUpdate(msg.arg1, mCamera); 311 } 312 return; 313 314 case CAMERA_MSG_ERROR : 315 Log.e(TAG, "Error " + msg.arg1); 316 if (mErrorCallback != null) { 317 mErrorCallback.onError(msg.arg1, mCamera); 318 } 319 return; 320 321 default: 322 Log.e(TAG, "Unknown message type " + msg.what); 323 return; 324 } 325 } 326 } 327 328 private static void postEventFromNative(Object camera_ref, 329 int what, int arg1, int arg2, Object obj) 330 { 331 Camera c = (Camera)((WeakReference)camera_ref).get(); 332 if (c == null) 333 return; 334 335 if (c.mEventHandler != null) { 336 Message m = c.mEventHandler.obtainMessage(what, arg1, arg2, obj); 337 c.mEventHandler.sendMessage(m); 338 } 339 } 340 341 /** 342 * Handles the callback for the camera auto focus. 343 * <p>Devices that do not support auto-focus will receive a "fake" 344 * callback to this interface. If your application needs auto-focus and 345 * should not be installed on devices <em>without</em> auto-focus, you must 346 * declare that your app uses the 347 * {@code android.hardware.camera.autofocus} feature, in the 348 * <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html"><uses-feature></a> 349 * manifest element.</p> 350 */ 351 public interface AutoFocusCallback 352 { 353 /** 354 * Callback for the camera auto focus. If the camera does not support 355 * auto-focus and autoFocus is called, onAutoFocus will be called 356 * immediately with success. 357 * 358 * @param success true if focus was successful, false if otherwise 359 * @param camera the Camera service object 360 */ 361 void onAutoFocus(boolean success, Camera camera); 362 }; 363 364 /** 365 * Starts auto-focus function and registers a callback function to run when 366 * camera is focused. Only valid after startPreview() has been called. If 367 * the camera does not support auto-focus, it is a no-op and {@link 368 * AutoFocusCallback#onAutoFocus(boolean, Camera)} callback will be called 369 * immediately. 370 * <p>If your application should not be installed 371 * on devices without auto-focus, you must declare that your application 372 * uses auto-focus with the 373 * <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html"><uses-feature></a> 374 * manifest element.</p> 375 * 376 * @param cb the callback to run 377 */ 378 public final void autoFocus(AutoFocusCallback cb) 379 { 380 mAutoFocusCallback = cb; 381 native_autoFocus(); 382 } 383 private native final void native_autoFocus(); 384 385 /** 386 * Cancels auto-focus function. If the auto-focus is still in progress, 387 * this function will cancel it. Whether the auto-focus is in progress 388 * or not, this function will return the focus position to the default. 389 * If the camera does not support auto-focus, this is a no-op. 390 */ 391 public final void cancelAutoFocus() 392 { 393 mAutoFocusCallback = null; 394 native_cancelAutoFocus(); 395 } 396 private native final void native_cancelAutoFocus(); 397 398 /** 399 * An interface which contains a callback for the shutter closing after taking a picture. 400 */ 401 public interface ShutterCallback 402 { 403 /** 404 * Can be used to play a shutter sound as soon as the image has been captured, but before 405 * the data is available. 406 */ 407 void onShutter(); 408 } 409 410 /** 411 * Handles the callback for when a picture is taken. 412 */ 413 public interface PictureCallback { 414 /** 415 * Callback for when a picture is taken. 416 * 417 * @param data a byte array of the picture data 418 * @param camera the Camera service object 419 */ 420 void onPictureTaken(byte[] data, Camera camera); 421 }; 422 423 /** 424 * Triggers an asynchronous image capture. The camera service will initiate 425 * a series of callbacks to the application as the image capture progresses. 426 * The shutter callback occurs after the image is captured. This can be used 427 * to trigger a sound to let the user know that image has been captured. The 428 * raw callback occurs when the raw image data is available (NOTE: the data 429 * may be null if the hardware does not have enough memory to make a copy). 430 * The jpeg callback occurs when the compressed image is available. If the 431 * application does not need a particular callback, a null can be passed 432 * instead of a callback method. 433 * 434 * @param shutter callback after the image is captured, may be null 435 * @param raw callback with raw image data, may be null 436 * @param jpeg callback with jpeg image data, may be null 437 */ 438 public final void takePicture(ShutterCallback shutter, PictureCallback raw, 439 PictureCallback jpeg) { 440 takePicture(shutter, raw, null, jpeg); 441 } 442 private native final void native_takePicture(); 443 444 /** 445 * Triggers an asynchronous image capture. The camera service will initiate 446 * a series of callbacks to the application as the image capture progresses. 447 * The shutter callback occurs after the image is captured. This can be used 448 * to trigger a sound to let the user know that image has been captured. The 449 * raw callback occurs when the raw image data is available (NOTE: the data 450 * may be null if the hardware does not have enough memory to make a copy). 451 * The postview callback occurs when a scaled, fully processed postview 452 * image is available (NOTE: not all hardware supports this). The jpeg 453 * callback occurs when the compressed image is available. If the 454 * application does not need a particular callback, a null can be passed 455 * instead of a callback method. 456 * 457 * @param shutter callback after the image is captured, may be null 458 * @param raw callback with raw image data, may be null 459 * @param postview callback with postview image data, may be null 460 * @param jpeg callback with jpeg image data, may be null 461 */ 462 public final void takePicture(ShutterCallback shutter, PictureCallback raw, 463 PictureCallback postview, PictureCallback jpeg) { 464 mShutterCallback = shutter; 465 mRawImageCallback = raw; 466 mPostviewCallback = postview; 467 mJpegCallback = jpeg; 468 native_takePicture(); 469 } 470 471 /** 472 * Handles the zoom callback. 473 */ 474 public interface ZoomCallback 475 { 476 /** 477 * Callback for zoom updates 478 * @param zoomLevel new zoom level in 1/1000 increments, 479 * e.g. a zoom of 3.2x is stored as 3200. Accuracy of the 480 * value is dependent on the hardware implementation. Not 481 * all devices will generate this callback. 482 * @param camera the Camera service object 483 */ 484 void onZoomUpdate(int zoomLevel, Camera camera); 485 }; 486 487 /** 488 * Registers a callback to be invoked when the zoom 489 * level is updated by the camera driver. 490 * @param cb the callback to run 491 */ 492 public final void setZoomCallback(ZoomCallback cb) 493 { 494 mZoomCallback = cb; 495 } 496 497 // These match the enum in include/ui/Camera.h 498 /** Unspecified camerar error. @see #ErrorCallback */ 499 public static final int CAMERA_ERROR_UNKNOWN = 1; 500 /** Media server died. In this case, the application must release the 501 * Camera object and instantiate a new one. @see #ErrorCallback */ 502 public static final int CAMERA_ERROR_SERVER_DIED = 100; 503 504 /** 505 * Handles the camera error callback. 506 */ 507 public interface ErrorCallback 508 { 509 /** 510 * Callback for camera errors. 511 * @param error error code: 512 * <ul> 513 * <li>{@link #CAMERA_ERROR_UNKNOWN} 514 * <li>{@link #CAMERA_ERROR_SERVER_DIED} 515 * </ul> 516 * @param camera the Camera service object 517 */ 518 void onError(int error, Camera camera); 519 }; 520 521 /** 522 * Registers a callback to be invoked when an error occurs. 523 * @param cb the callback to run 524 */ 525 public final void setErrorCallback(ErrorCallback cb) 526 { 527 mErrorCallback = cb; 528 } 529 530 private native final void native_setParameters(String params); 531 private native final String native_getParameters(); 532 533 /** 534 * Sets the Parameters for pictures from this Camera service. 535 * 536 * @param params the Parameters to use for this Camera service 537 */ 538 public void setParameters(Parameters params) { 539 native_setParameters(params.flatten()); 540 } 541 542 /** 543 * Returns the picture Parameters for this Camera service. 544 */ 545 public Parameters getParameters() { 546 Parameters p = new Parameters(); 547 String s = native_getParameters(); 548 p.unflatten(s); 549 return p; 550 } 551 552 /** 553 * Handles the picture size (dimensions). 554 */ 555 public class Size { 556 /** 557 * Sets the dimensions for pictures. 558 * 559 * @param w the photo width (pixels) 560 * @param h the photo height (pixels) 561 */ 562 public Size(int w, int h) { 563 width = w; 564 height = h; 565 } 566 /** width of the picture */ 567 public int width; 568 /** height of the picture */ 569 public int height; 570 }; 571 572 /** 573 * Handles the parameters for pictures created by a Camera service. 574 * 575 * <p>To make camera parameters take effect, applications have to call 576 * Camera.setParameters. For example, after setWhiteBalance is called, white 577 * balance is not changed until Camera.setParameters() is called. 578 * 579 * <p>Different devices may have different camera capabilities, such as 580 * picture size or flash modes. The application should query the camera 581 * capabilities before setting parameters. For example, the application 582 * should call getSupportedColorEffects before calling setEffect. If the 583 * camera does not support color effects, getSupportedColorEffects will 584 * return null. 585 */ 586 public class Parameters { 587 // Parameter keys to communicate with the camera driver. 588 private static final String KEY_PREVIEW_SIZE = "preview-size"; 589 private static final String KEY_PREVIEW_FORMAT = "preview-format"; 590 private static final String KEY_PREVIEW_FRAME_RATE = "preview-frame-rate"; 591 private static final String KEY_PICTURE_SIZE = "picture-size"; 592 private static final String KEY_PICTURE_FORMAT = "picture-format"; 593 private static final String KEY_JPEG_THUMBNAIL_WIDTH = "jpeg-thumbnail-width"; 594 private static final String KEY_JPEG_THUMBNAIL_HEIGHT = "jpeg-thumbnail-height"; 595 private static final String KEY_JPEG_THUMBNAIL_QUALITY = "jpeg-thumbnail-quality"; 596 private static final String KEY_JPEG_QUALITY = "jpeg-quality"; 597 private static final String KEY_ROTATION = "rotation"; 598 private static final String KEY_GPS_LATITUDE = "gps-latitude"; 599 private static final String KEY_GPS_LONGITUDE = "gps-longitude"; 600 private static final String KEY_GPS_ALTITUDE = "gps-altitude"; 601 private static final String KEY_GPS_TIMESTAMP = "gps-timestamp"; 602 private static final String KEY_WHITE_BALANCE = "whitebalance"; 603 private static final String KEY_EFFECT = "effect"; 604 private static final String KEY_ANTIBANDING = "antibanding"; 605 private static final String KEY_SCENE_MODE = "scene-mode"; 606 private static final String KEY_FLASH_MODE = "flash-mode"; 607 // Parameter key suffix for supported values. 608 private static final String SUPPORTED_VALUES_SUFFIX = "-values"; 609 610 // Values for white balance settings. 611 public static final String WHITE_BALANCE_AUTO = "auto"; 612 public static final String WHITE_BALANCE_INCANDESCENT = "incandescent"; 613 public static final String WHITE_BALANCE_FLUORESCENT = "fluorescent"; 614 public static final String WHITE_BALANCE_WARM_FLUORESCENT = "warm-fluorescent"; 615 public static final String WHITE_BALANCE_DAYLIGHT = "daylight"; 616 public static final String WHITE_BALANCE_CLOUDY_DAYLIGHT = "cloudy-daylight"; 617 public static final String WHITE_BALANCE_TWILIGHT = "twilight"; 618 public static final String WHITE_BALANCE_SHADE = "shade"; 619 620 // Values for color effect settings. 621 public static final String EFFECT_NONE = "none"; 622 public static final String EFFECT_MONO = "mono"; 623 public static final String EFFECT_NEGATIVE = "negative"; 624 public static final String EFFECT_SOLARIZE = "solarize"; 625 public static final String EFFECT_SEPIA = "sepia"; 626 public static final String EFFECT_POSTERIZE = "posterize"; 627 public static final String EFFECT_WHITEBOARD = "whiteboard"; 628 public static final String EFFECT_BLACKBOARD = "blackboard"; 629 public static final String EFFECT_AQUA = "aqua"; 630 631 // Values for antibanding settings. 632 public static final String ANTIBANDING_AUTO = "auto"; 633 public static final String ANTIBANDING_50HZ = "50hz"; 634 public static final String ANTIBANDING_60HZ = "60hz"; 635 public static final String ANTIBANDING_OFF = "off"; 636 637 // Values for flash mode settings. 638 /** 639 * Flash will not be fired. 640 */ 641 public static final String FLASH_MODE_OFF = "off"; 642 /** 643 * Flash will be fired automatically when required. The timing is 644 * decided by camera driver. 645 */ 646 public static final String FLASH_MODE_AUTO = "auto"; 647 /** 648 * Flash will always be fired. The timing is decided by camera driver. 649 */ 650 public static final String FLASH_MODE_ON = "on"; 651 /** 652 * Flash will be fired in red-eye reduction mode. 653 */ 654 public static final String FLASH_MODE_RED_EYE = "red-eye"; 655 656 // Values for scene mode settings. 657 public static final String SCENE_MODE_AUTO = "auto"; 658 public static final String SCENE_MODE_ACTION = "action"; 659 public static final String SCENE_MODE_PORTRAIT = "portrait"; 660 public static final String SCENE_MODE_LANDSCAPE = "landscape"; 661 public static final String SCENE_MODE_NIGHT = "night"; 662 public static final String SCENE_MODE_NIGHT_PORTRAIT = "night-portrait"; 663 public static final String SCENE_MODE_THEATRE = "theatre"; 664 public static final String SCENE_MODE_BEACH = "beach"; 665 public static final String SCENE_MODE_SNOW = "snow"; 666 public static final String SCENE_MODE_SUNSET = "sunset"; 667 public static final String SCENE_MODE_STEADYPHOTO = "steadyphoto"; 668 public static final String SCENE_MODE_FIREWORKS = "fireworks"; 669 public static final String SCENE_MODE_SPORTS = "sports"; 670 public static final String SCENE_MODE_PARTY = "party"; 671 public static final String SCENE_MODE_CANDLELIGHT = "candlelight"; 672 673 // Formats for setPreviewFormat and setPictureFormat. 674 private static final String PIXEL_FORMAT_YUV422SP = "yuv422sp"; 675 private static final String PIXEL_FORMAT_YUV420SP = "yuv420sp"; 676 private static final String PIXEL_FORMAT_YUV422I = "yuv422i-yuyv"; 677 private static final String PIXEL_FORMAT_RGB565 = "rgb565"; 678 private static final String PIXEL_FORMAT_JPEG = "jpeg"; 679 680 private HashMap<String, String> mMap; 681 682 private Parameters() { 683 mMap = new HashMap<String, String>(); 684 } 685 686 /** 687 * Writes the current Parameters to the log. 688 * @hide 689 * @deprecated 690 */ 691 public void dump() { 692 Log.e(TAG, "dump: size=" + mMap.size()); 693 for (String k : mMap.keySet()) { 694 Log.e(TAG, "dump: " + k + "=" + mMap.get(k)); 695 } 696 } 697 698 /** 699 * Creates a single string with all the parameters set in 700 * this Parameters object. 701 * <p>The {@link #unflatten(String)} method does the reverse.</p> 702 * 703 * @return a String with all values from this Parameters object, in 704 * semi-colon delimited key-value pairs 705 */ 706 public String flatten() { 707 StringBuilder flattened = new StringBuilder(); 708 for (String k : mMap.keySet()) { 709 flattened.append(k); 710 flattened.append("="); 711 flattened.append(mMap.get(k)); 712 flattened.append(";"); 713 } 714 // chop off the extra semicolon at the end 715 flattened.deleteCharAt(flattened.length()-1); 716 return flattened.toString(); 717 } 718 719 /** 720 * Takes a flattened string of parameters and adds each one to 721 * this Parameters object. 722 * <p>The {@link #flatten()} method does the reverse.</p> 723 * 724 * @param flattened a String of parameters (key-value paired) that 725 * are semi-colon delimited 726 */ 727 public void unflatten(String flattened) { 728 mMap.clear(); 729 730 StringTokenizer tokenizer = new StringTokenizer(flattened, ";"); 731 while (tokenizer.hasMoreElements()) { 732 String kv = tokenizer.nextToken(); 733 int pos = kv.indexOf('='); 734 if (pos == -1) { 735 continue; 736 } 737 String k = kv.substring(0, pos); 738 String v = kv.substring(pos + 1); 739 mMap.put(k, v); 740 } 741 } 742 743 public void remove(String key) { 744 mMap.remove(key); 745 } 746 747 /** 748 * Sets a String parameter. 749 * 750 * @param key the key name for the parameter 751 * @param value the String value of the parameter 752 */ 753 public void set(String key, String value) { 754 if (key.indexOf('=') != -1 || key.indexOf(';') != -1) { 755 Log.e(TAG, "Key \"" + key + "\" contains invalid character (= or ;)"); 756 return; 757 } 758 if (value.indexOf('=') != -1 || value.indexOf(';') != -1) { 759 Log.e(TAG, "Value \"" + value + "\" contains invalid character (= or ;)"); 760 return; 761 } 762 763 mMap.put(key, value); 764 } 765 766 /** 767 * Sets an integer parameter. 768 * 769 * @param key the key name for the parameter 770 * @param value the int value of the parameter 771 */ 772 public void set(String key, int value) { 773 mMap.put(key, Integer.toString(value)); 774 } 775 776 /** 777 * Returns the value of a String parameter. 778 * 779 * @param key the key name for the parameter 780 * @return the String value of the parameter 781 */ 782 public String get(String key) { 783 return mMap.get(key); 784 } 785 786 /** 787 * Returns the value of an integer parameter. 788 * 789 * @param key the key name for the parameter 790 * @return the int value of the parameter 791 */ 792 public int getInt(String key) { 793 return Integer.parseInt(mMap.get(key)); 794 } 795 796 /** 797 * Sets the dimensions for preview pictures. 798 * 799 * @param width the width of the pictures, in pixels 800 * @param height the height of the pictures, in pixels 801 */ 802 public void setPreviewSize(int width, int height) { 803 String v = Integer.toString(width) + "x" + Integer.toString(height); 804 set(KEY_PREVIEW_SIZE, v); 805 } 806 807 /** 808 * Returns the dimensions setting for preview pictures. 809 * 810 * @return a Size object with the height and width setting 811 * for the preview picture 812 */ 813 public Size getPreviewSize() { 814 String pair = get(KEY_PREVIEW_SIZE); 815 return strToSize(pair); 816 } 817 818 /** 819 * Gets the supported preview sizes. 820 * 821 * @return a List of Size object. null if preview size setting is not 822 * supported. 823 */ 824 public List<Size> getSupportedPreviewSizes() { 825 String str = get(KEY_PREVIEW_SIZE + SUPPORTED_VALUES_SUFFIX); 826 return splitSize(str); 827 } 828 829 /** 830 * Sets the dimensions for EXIF thumbnail in Jpeg picture. 831 * 832 * @param width the width of the thumbnail, in pixels 833 * @param height the height of the thumbnail, in pixels 834 */ 835 public void setJpegThumbnailSize(int width, int height) { 836 set(KEY_JPEG_THUMBNAIL_WIDTH, width); 837 set(KEY_JPEG_THUMBNAIL_HEIGHT, height); 838 } 839 840 /** 841 * Returns the dimensions for EXIF thumbnail in Jpeg picture. 842 * 843 * @return a Size object with the height and width setting for the EXIF 844 * thumbnails 845 */ 846 public Size getJpegThumbnailSize() { 847 return new Size(getInt(KEY_JPEG_THUMBNAIL_WIDTH), 848 getInt(KEY_JPEG_THUMBNAIL_HEIGHT)); 849 } 850 851 /** 852 * Sets the quality of the EXIF thumbnail in Jpeg picture. 853 * 854 * @param quality the JPEG quality of the EXIF thumbnail. The range is 1 855 * to 100, with 100 being the best. 856 */ 857 public void setJpegThumbnailQuality(int quality) { 858 set(KEY_JPEG_THUMBNAIL_QUALITY, quality); 859 } 860 861 /** 862 * Returns the quality setting for the EXIF thumbnail in Jpeg picture. 863 * 864 * @return the JPEG quality setting of the EXIF thumbnail. 865 */ 866 public int getJpegThumbnailQuality() { 867 return getInt(KEY_JPEG_THUMBNAIL_QUALITY); 868 } 869 870 /** 871 * Sets Jpeg quality of captured picture. 872 * 873 * @param quality the JPEG quality of captured picture. The range is 1 874 * to 100, with 100 being the best. 875 */ 876 public void setJpegQuality(int quality) { 877 set(KEY_JPEG_QUALITY, quality); 878 } 879 880 /** 881 * Returns the quality setting for the JPEG picture. 882 * 883 * @return the JPEG picture quality setting. 884 */ 885 public int getJpegQuality() { 886 return getInt(KEY_JPEG_QUALITY); 887 } 888 889 /** 890 * Sets the rate at which preview frames are received. 891 * 892 * @param fps the frame rate (frames per second) 893 */ 894 public void setPreviewFrameRate(int fps) { 895 set(KEY_PREVIEW_FRAME_RATE, fps); 896 } 897 898 /** 899 * Returns the setting for the rate at which preview frames 900 * are received. 901 * 902 * @return the frame rate setting (frames per second) 903 */ 904 public int getPreviewFrameRate() { 905 return getInt(KEY_PREVIEW_FRAME_RATE); 906 } 907 908 /** 909 * Gets the supported preview frame rates. 910 * 911 * @return a List of Integer objects (preview frame rates). null if 912 * preview frame rate setting is not supported. 913 */ 914 public List<Integer> getSupportedPreviewFrameRates() { 915 String str = get(KEY_PREVIEW_FRAME_RATE + SUPPORTED_VALUES_SUFFIX); 916 return splitInt(str); 917 } 918 919 /** 920 * Sets the image format for preview pictures. 921 * <p>If this is never called, the default format will be 922 * {@link android.graphics.PixelFormat#YCbCr_420_SP}, which 923 * uses the NV21 encoding format.</p> 924 * 925 * @param pixel_format the desired preview picture format, defined 926 * by one of the {@link android.graphics.PixelFormat} constants. 927 * (E.g., <var>PixelFormat.YCbCr_420_SP</var> (default), 928 * <var>PixelFormat.RGB_565</var>, or 929 * <var>PixelFormat.JPEG</var>) 930 * @see android.graphics.PixelFormat 931 */ 932 public void setPreviewFormat(int pixel_format) { 933 String s = cameraFormatForPixelFormat(pixel_format); 934 if (s == null) { 935 throw new IllegalArgumentException( 936 "Invalid pixel_format=" + pixel_format); 937 } 938 939 set(KEY_PREVIEW_FORMAT, s); 940 } 941 942 /** 943 * Returns the image format for preview pictures got from 944 * {@link PreviewCallback}. 945 * 946 * @return the {@link android.graphics.PixelFormat} int representing 947 * the preview picture format. 948 */ 949 public int getPreviewFormat() { 950 return pixelFormatForCameraFormat(get(KEY_PREVIEW_FORMAT)); 951 } 952 953 /** 954 * Gets the supported preview formats. 955 * 956 * @return a List of Integer objects. null if preview format setting is 957 * not supported. 958 */ 959 public List<Integer> getSupportedPreviewFormats() { 960 String str = get(KEY_PREVIEW_FORMAT + SUPPORTED_VALUES_SUFFIX); 961 ArrayList<Integer> formats = new ArrayList<Integer>(); 962 for (String s : split(str)) { 963 int f = pixelFormatForCameraFormat(s); 964 if (f == PixelFormat.UNKNOWN) continue; 965 formats.add(f); 966 } 967 return formats; 968 } 969 970 /** 971 * Sets the dimensions for pictures. 972 * 973 * @param width the width for pictures, in pixels 974 * @param height the height for pictures, in pixels 975 */ 976 public void setPictureSize(int width, int height) { 977 String v = Integer.toString(width) + "x" + Integer.toString(height); 978 set(KEY_PICTURE_SIZE, v); 979 } 980 981 /** 982 * Returns the dimension setting for pictures. 983 * 984 * @return a Size object with the height and width setting 985 * for pictures 986 */ 987 public Size getPictureSize() { 988 String pair = get(KEY_PICTURE_SIZE); 989 return strToSize(pair); 990 } 991 992 /** 993 * Gets the supported picture sizes. 994 * 995 * @return a List of Size objects. null if picture size setting is not 996 * supported. 997 */ 998 public List<Size> getSupportedPictureSizes() { 999 String str = get(KEY_PICTURE_SIZE + SUPPORTED_VALUES_SUFFIX); 1000 return splitSize(str); 1001 } 1002 1003 /** 1004 * Sets the image format for pictures. 1005 * 1006 * @param pixel_format the desired picture format 1007 * (<var>PixelFormat.YCbCr_420_SP (NV21)</var>, 1008 * <var>PixelFormat.RGB_565</var>, or 1009 * <var>PixelFormat.JPEG</var>) 1010 * @see android.graphics.PixelFormat 1011 */ 1012 public void setPictureFormat(int pixel_format) { 1013 String s = cameraFormatForPixelFormat(pixel_format); 1014 if (s == null) { 1015 throw new IllegalArgumentException( 1016 "Invalid pixel_format=" + pixel_format); 1017 } 1018 1019 set(KEY_PICTURE_FORMAT, s); 1020 } 1021 1022 /** 1023 * Returns the image format for pictures. 1024 * 1025 * @return the PixelFormat int representing the picture format 1026 */ 1027 public int getPictureFormat() { 1028 return pixelFormatForCameraFormat(get(KEY_PICTURE_FORMAT)); 1029 } 1030 1031 /** 1032 * Gets the supported picture formats. 1033 * 1034 * @return a List of Integer objects (values are PixelFormat.XXX). null 1035 * if picture setting is not supported. 1036 */ 1037 public List<Integer> getSupportedPictureFormats() { 1038 String str = get(KEY_PICTURE_SIZE + SUPPORTED_VALUES_SUFFIX); 1039 return splitInt(str); 1040 } 1041 1042 private String cameraFormatForPixelFormat(int pixel_format) { 1043 switch(pixel_format) { 1044 case PixelFormat.YCbCr_422_SP: return PIXEL_FORMAT_YUV422SP; 1045 case PixelFormat.YCbCr_420_SP: return PIXEL_FORMAT_YUV420SP; 1046 case PixelFormat.YCbCr_422_I: return PIXEL_FORMAT_YUV422I; 1047 case PixelFormat.RGB_565: return PIXEL_FORMAT_RGB565; 1048 case PixelFormat.JPEG: return PIXEL_FORMAT_JPEG; 1049 default: return null; 1050 } 1051 } 1052 1053 private int pixelFormatForCameraFormat(String format) { 1054 if (format == null) 1055 return PixelFormat.UNKNOWN; 1056 1057 if (format.equals(PIXEL_FORMAT_YUV422SP)) 1058 return PixelFormat.YCbCr_422_SP; 1059 1060 if (format.equals(PIXEL_FORMAT_YUV420SP)) 1061 return PixelFormat.YCbCr_420_SP; 1062 1063 if (format.equals(PIXEL_FORMAT_YUV422I)) 1064 return PixelFormat.YCbCr_422_I; 1065 1066 if (format.equals(PIXEL_FORMAT_RGB565)) 1067 return PixelFormat.RGB_565; 1068 1069 if (format.equals(PIXEL_FORMAT_JPEG)) 1070 return PixelFormat.JPEG; 1071 1072 return PixelFormat.UNKNOWN; 1073 } 1074 1075 /** 1076 * Sets the orientation of the device in degrees, which instructs the 1077 * camera driver to rotate the picture and thumbnail, in order to match 1078 * what the user sees from the viewfinder. For example, suppose the 1079 * natural position of the device is landscape. If the user takes a 1080 * picture in landscape mode in 2048x1536 resolution, the rotation 1081 * should be set to 0. If the user rotates the phone 90 degrees 1082 * clockwise, the rotation should be set to 90. Applications can use 1083 * {@link android.view.OrientationEventListener} to set this parameter. 1084 * 1085 * Since the picture is rotated, the orientation in the EXIF header is 1086 * missing or always 1 (row #0 is top and column #0 is left side). 1087 * 1088 * @param rotation The orientation of the device in degrees. Rotation 1089 * can only be 0, 90, 180 or 270. 1090 * @throws IllegalArgumentException if rotation value is invalid. 1091 * @see android.view.OrientationEventListener 1092 */ 1093 public void setRotation(int rotation) { 1094 if (rotation == 0 || rotation == 90 || rotation == 180 1095 || rotation == 270) { 1096 set(KEY_ROTATION, Integer.toString(rotation)); 1097 } else { 1098 throw new IllegalArgumentException( 1099 "Invalid rotation=" + rotation); 1100 } 1101 } 1102 1103 /** 1104 * Sets GPS latitude coordinate. This will be stored in JPEG EXIF 1105 * header. 1106 * 1107 * @param latitude GPS latitude coordinate. 1108 */ 1109 public void setGpsLatitude(double latitude) { 1110 set(KEY_GPS_LATITUDE, Double.toString(latitude)); 1111 } 1112 1113 /** 1114 * Sets GPS longitude coordinate. This will be stored in JPEG EXIF 1115 * header. 1116 * 1117 * @param longitude GPS longitude coordinate. 1118 */ 1119 public void setGpsLongitude(double longitude) { 1120 set(KEY_GPS_LONGITUDE, Double.toString(longitude)); 1121 } 1122 1123 /** 1124 * Sets GPS altitude. This will be stored in JPEG EXIF header. 1125 * 1126 * @param altitude GPS altitude in meters. 1127 */ 1128 public void setGpsAltitude(double altitude) { 1129 set(KEY_GPS_ALTITUDE, Double.toString(altitude)); 1130 } 1131 1132 /** 1133 * Sets GPS timestamp. This will be stored in JPEG EXIF header. 1134 * 1135 * @param timestamp GPS timestamp (UTC in seconds since January 1, 1136 * 1970). 1137 */ 1138 public void setGpsTimestamp(long timestamp) { 1139 set(KEY_GPS_TIMESTAMP, Long.toString(timestamp)); 1140 } 1141 1142 /** 1143 * Removes GPS latitude, longitude, altitude, and timestamp from the 1144 * parameters. 1145 */ 1146 public void removeGpsData() { 1147 remove(KEY_GPS_LATITUDE); 1148 remove(KEY_GPS_LONGITUDE); 1149 remove(KEY_GPS_ALTITUDE); 1150 remove(KEY_GPS_TIMESTAMP); 1151 } 1152 1153 /** 1154 * Gets the current white balance setting. 1155 * 1156 * @return one of WHITE_BALANCE_XXX string constant. null if white 1157 * balance setting is not supported. 1158 */ 1159 public String getWhiteBalance() { 1160 return get(KEY_WHITE_BALANCE); 1161 } 1162 1163 /** 1164 * Sets the white balance. 1165 * 1166 * @param value WHITE_BALANCE_XXX string constant. 1167 */ 1168 public void setWhiteBalance(String value) { 1169 set(KEY_WHITE_BALANCE, value); 1170 } 1171 1172 /** 1173 * Gets the supported white balance. 1174 * 1175 * @return a List of WHITE_BALANCE_XXX string constants. null if white 1176 * balance setting is not supported. 1177 */ 1178 public List<String> getSupportedWhiteBalance() { 1179 String str = get(KEY_WHITE_BALANCE + SUPPORTED_VALUES_SUFFIX); 1180 return split(str); 1181 } 1182 1183 /** 1184 * Gets the current color effect setting. 1185 * 1186 * @return one of EFFECT_XXX string constant. null if color effect 1187 * setting is not supported. 1188 */ 1189 public String getColorEffect() { 1190 return get(KEY_EFFECT); 1191 } 1192 1193 /** 1194 * Sets the current color effect setting. 1195 * 1196 * @param value EFFECT_XXX string constants. 1197 */ 1198 public void setColorEffect(String value) { 1199 set(KEY_EFFECT, value); 1200 } 1201 1202 /** 1203 * Gets the supported color effects. 1204 * 1205 * @return a List of EFFECT_XXX string constants. null if color effect 1206 * setting is not supported. 1207 */ 1208 public List<String> getSupportedColorEffects() { 1209 String str = get(KEY_EFFECT + SUPPORTED_VALUES_SUFFIX); 1210 return split(str); 1211 } 1212 1213 1214 /** 1215 * Gets the current antibanding setting. 1216 * 1217 * @return one of ANTIBANDING_XXX string constant. null if antibanding 1218 * setting is not supported. 1219 */ 1220 public String getAntibanding() { 1221 return get(KEY_ANTIBANDING); 1222 } 1223 1224 /** 1225 * Sets the antibanding. 1226 * 1227 * @param antibanding ANTIBANDING_XXX string constant. 1228 */ 1229 public void setAntibanding(String antibanding) { 1230 set(KEY_ANTIBANDING, antibanding); 1231 } 1232 1233 /** 1234 * Gets the supported antibanding values. 1235 * 1236 * @return a List of ANTIBANDING_XXX string constants. null if 1237 * antibanding setting is not supported. 1238 */ 1239 public List<String> getSupportedAntibanding() { 1240 String str = get(KEY_ANTIBANDING + SUPPORTED_VALUES_SUFFIX); 1241 return split(str); 1242 } 1243 1244 /** 1245 * Gets the current scene mode setting. 1246 * 1247 * @return one of SCENE_MODE_XXX string constant. null if scene mode 1248 * setting is not supported. 1249 */ 1250 public String getSceneMode() { 1251 return get(KEY_SCENE_MODE); 1252 } 1253 1254 /** 1255 * Sets the scene mode. 1256 * 1257 * @param value SCENE_MODE_XXX string constants. 1258 */ 1259 public void setSceneMode(String value) { 1260 set(KEY_SCENE_MODE, value); 1261 } 1262 1263 /** 1264 * Gets the supported scene modes. 1265 * 1266 * @return a List of SCENE_MODE_XXX string constant. null if scene mode 1267 * setting is not supported. 1268 */ 1269 public List<String> getSupportedSceneModes() { 1270 String str = get(KEY_SCENE_MODE + SUPPORTED_VALUES_SUFFIX); 1271 return split(str); 1272 } 1273 1274 /** 1275 * Gets the current flash mode setting. 1276 * 1277 * @return one of FLASH_MODE_XXX string constant. null if flash mode 1278 * setting is not supported. 1279 */ 1280 public String getFlashMode() { 1281 return get(KEY_FLASH_MODE); 1282 } 1283 1284 /** 1285 * Sets the flash mode. 1286 * 1287 * @param value FLASH_MODE_XXX string constants. 1288 */ 1289 public void setFlashMode(String value) { 1290 set(KEY_FLASH_MODE, value); 1291 } 1292 1293 /** 1294 * Gets the supported flash modes. 1295 * 1296 * @return a List of FLASH_MODE_XXX string constants. null if flash mode 1297 * setting is not supported. 1298 */ 1299 public List<String> getSupportedFlashModes() { 1300 String str = get(KEY_FLASH_MODE + SUPPORTED_VALUES_SUFFIX); 1301 return split(str); 1302 } 1303 1304 // Splits a comma delimited string to an ArrayList of String. 1305 // Return null if the passing string is null or the size is 0. 1306 private ArrayList<String> split(String str) { 1307 if (str == null) return null; 1308 1309 // Use StringTokenizer because it is faster than split. 1310 StringTokenizer tokenizer = new StringTokenizer(str, ","); 1311 ArrayList<String> substrings = new ArrayList<String>(); 1312 while (tokenizer.hasMoreElements()) { 1313 substrings.add(tokenizer.nextToken()); 1314 } 1315 return substrings; 1316 } 1317 1318 // Splits a comma delimited string to an ArrayList of Integer. 1319 // Return null if the passing string is null or the size is 0. 1320 private ArrayList<Integer> splitInt(String str) { 1321 if (str == null) return null; 1322 1323 StringTokenizer tokenizer = new StringTokenizer(str, ","); 1324 ArrayList<Integer> substrings = new ArrayList<Integer>(); 1325 while (tokenizer.hasMoreElements()) { 1326 String token = tokenizer.nextToken(); 1327 substrings.add(Integer.parseInt(token)); 1328 } 1329 if (substrings.size() == 0) return null; 1330 return substrings; 1331 } 1332 1333 // Splits a comma delimited string to an ArrayList of Size. 1334 // Return null if the passing string is null or the size is 0. 1335 private ArrayList<Size> splitSize(String str) { 1336 if (str == null) return null; 1337 1338 StringTokenizer tokenizer = new StringTokenizer(str, ","); 1339 ArrayList<Size> sizeList = new ArrayList<Size>(); 1340 while (tokenizer.hasMoreElements()) { 1341 Size size = strToSize(tokenizer.nextToken()); 1342 if (size != null) sizeList.add(size); 1343 } 1344 if (sizeList.size() == 0) return null; 1345 return sizeList; 1346 } 1347 1348 // Parses a string (ex: "480x320") to Size object. 1349 // Return null if the passing string is null. 1350 private Size strToSize(String str) { 1351 if (str == null) return null; 1352 1353 int pos = str.indexOf('x'); 1354 if (pos != -1) { 1355 String width = str.substring(0, pos); 1356 String height = str.substring(pos + 1); 1357 return new Size(Integer.parseInt(width), 1358 Integer.parseInt(height)); 1359 } 1360 Log.e(TAG, "Invalid size parameter string=" + str); 1361 return null; 1362 } 1363 }; 1364} 1365