Camera.java revision 244f8c26365a303d9dd861bd48a29a4b48578da1
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 * @hide 391 */ 392 public final void cancelAutoFocus() 393 { 394 mAutoFocusCallback = null; 395 native_cancelAutoFocus(); 396 } 397 private native final void native_cancelAutoFocus(); 398 399 /** 400 * An interface which contains a callback for the shutter closing after taking a picture. 401 */ 402 public interface ShutterCallback 403 { 404 /** 405 * Can be used to play a shutter sound as soon as the image has been captured, but before 406 * the data is available. 407 */ 408 void onShutter(); 409 } 410 411 /** 412 * Handles the callback for when a picture is taken. 413 */ 414 public interface PictureCallback { 415 /** 416 * Callback for when a picture is taken. 417 * 418 * @param data a byte array of the picture data 419 * @param camera the Camera service object 420 */ 421 void onPictureTaken(byte[] data, Camera camera); 422 }; 423 424 /** 425 * Triggers an asynchronous image capture. The camera service will initiate 426 * a series of callbacks to the application as the image capture progresses. 427 * The shutter callback occurs after the image is captured. This can be used 428 * to trigger a sound to let the user know that image has been captured. The 429 * raw callback occurs when the raw image data is available (NOTE: the data 430 * may be null if the hardware does not have enough memory to make a copy). 431 * The jpeg callback occurs when the compressed image is available. If the 432 * application does not need a particular callback, a null can be passed 433 * instead of a callback method. 434 * 435 * @param shutter callback after the image is captured, may be null 436 * @param raw callback with raw image data, may be null 437 * @param jpeg callback with jpeg image data, may be null 438 */ 439 public final void takePicture(ShutterCallback shutter, PictureCallback raw, 440 PictureCallback jpeg) { 441 takePicture(shutter, raw, null, jpeg); 442 } 443 private native final void native_takePicture(); 444 445 /** 446 * Triggers an asynchronous image capture. The camera service will initiate 447 * a series of callbacks to the application as the image capture progresses. 448 * The shutter callback occurs after the image is captured. This can be used 449 * to trigger a sound to let the user know that image has been captured. The 450 * raw callback occurs when the raw image data is available (NOTE: the data 451 * may be null if the hardware does not have enough memory to make a copy). 452 * The postview callback occurs when a scaled, fully processed postview 453 * image is available (NOTE: not all hardware supports this). The jpeg 454 * callback occurs when the compressed image is available. If the 455 * application does not need a particular callback, a null can be passed 456 * instead of a callback method. 457 * 458 * @param shutter callback after the image is captured, may be null 459 * @param raw callback with raw image data, may be null 460 * @param postview callback with postview image data, may be null 461 * @param jpeg callback with jpeg image data, may be null 462 */ 463 public final void takePicture(ShutterCallback shutter, PictureCallback raw, 464 PictureCallback postview, PictureCallback jpeg) { 465 mShutterCallback = shutter; 466 mRawImageCallback = raw; 467 mPostviewCallback = postview; 468 mJpegCallback = jpeg; 469 native_takePicture(); 470 } 471 472 /** 473 * Handles the zoom callback. 474 */ 475 public interface ZoomCallback 476 { 477 /** 478 * Callback for zoom updates 479 * @param zoomLevel new zoom level in 1/1000 increments, 480 * e.g. a zoom of 3.2x is stored as 3200. Accuracy of the 481 * value is dependent on the hardware implementation. Not 482 * all devices will generate this callback. 483 * @param camera the Camera service object 484 */ 485 void onZoomUpdate(int zoomLevel, Camera camera); 486 }; 487 488 /** 489 * Registers a callback to be invoked when the zoom 490 * level is updated by the camera driver. 491 * @param cb the callback to run 492 */ 493 public final void setZoomCallback(ZoomCallback cb) 494 { 495 mZoomCallback = cb; 496 } 497 498 // These match the enum in include/ui/Camera.h 499 /** Unspecified camerar error. @see #ErrorCallback */ 500 public static final int CAMERA_ERROR_UNKNOWN = 1; 501 /** Media server died. In this case, the application must release the 502 * Camera object and instantiate a new one. @see #ErrorCallback */ 503 public static final int CAMERA_ERROR_SERVER_DIED = 100; 504 505 /** 506 * Handles the camera error callback. 507 */ 508 public interface ErrorCallback 509 { 510 /** 511 * Callback for camera errors. 512 * @param error error code: 513 * <ul> 514 * <li>{@link #CAMERA_ERROR_UNKNOWN} 515 * <li>{@link #CAMERA_ERROR_SERVER_DIED} 516 * </ul> 517 * @param camera the Camera service object 518 */ 519 void onError(int error, Camera camera); 520 }; 521 522 /** 523 * Registers a callback to be invoked when an error occurs. 524 * @param cb the callback to run 525 */ 526 public final void setErrorCallback(ErrorCallback cb) 527 { 528 mErrorCallback = cb; 529 } 530 531 private native final void native_setParameters(String params); 532 private native final String native_getParameters(); 533 534 /** 535 * Sets the Parameters for pictures from this Camera service. 536 * 537 * @param params the Parameters to use for this Camera service 538 */ 539 public void setParameters(Parameters params) { 540 native_setParameters(params.flatten()); 541 } 542 543 /** 544 * Returns the picture Parameters for this Camera service. 545 */ 546 public Parameters getParameters() { 547 Parameters p = new Parameters(); 548 String s = native_getParameters(); 549 p.unflatten(s); 550 return p; 551 } 552 553 /** 554 * Handles the picture size (dimensions). 555 */ 556 public class Size { 557 /** 558 * Sets the dimensions for pictures. 559 * 560 * @param w the photo width (pixels) 561 * @param h the photo height (pixels) 562 */ 563 public Size(int w, int h) { 564 width = w; 565 height = h; 566 } 567 /** width of the picture */ 568 public int width; 569 /** height of the picture */ 570 public int height; 571 }; 572 573 /** 574 * Handles the parameters for pictures created by a Camera service. 575 * 576 * <p>To make camera parameters take effect, applications have to call 577 * Camera.setParameters. For example, after setWhiteBalance is called, white 578 * balance is not changed until Camera.setParameters() is called. 579 * 580 * <p>Different devices may have different camera capabilities, such as 581 * picture size or flash modes. The application should query the camera 582 * capabilities before setting parameters. For example, the application 583 * should call getSupportedColorEffects before calling setEffect. If the 584 * camera does not support color effects, getSupportedColorEffects will 585 * return null. 586 */ 587 public class Parameters { 588 // Parameter keys to communicate with the camera driver. 589 private static final String KEY_PREVIEW_SIZE = "preview-size"; 590 private static final String KEY_PREVIEW_FORMAT = "preview-format"; 591 private static final String KEY_PREVIEW_FRAME_RATE = "preview-frame-rate"; 592 private static final String KEY_PICTURE_SIZE = "picture-size"; 593 private static final String KEY_PICTURE_FORMAT = "picture-format"; 594 private static final String KEY_JPEG_THUMBNAIL_WIDTH = "jpeg-thumbnail-width"; 595 private static final String KEY_JPEG_THUMBNAIL_HEIGHT = "jpeg-thumbnail-height"; 596 private static final String KEY_JPEG_THUMBNAIL_QUALITY = "jpeg-thumbnail-quality"; 597 private static final String KEY_JPEG_QUALITY = "jpeg-quality"; 598 private static final String KEY_ROTATION = "rotation"; 599 private static final String KEY_GPS_LATITUDE = "gps-latitude"; 600 private static final String KEY_GPS_LONGITUDE = "gps-longitude"; 601 private static final String KEY_GPS_ALTITUDE = "gps-altitude"; 602 private static final String KEY_GPS_TIMESTAMP = "gps-timestamp"; 603 private static final String KEY_WHITE_BALANCE = "whitebalance"; 604 private static final String KEY_EFFECT = "effect"; 605 private static final String KEY_ANTIBANDING = "antibanding"; 606 private static final String KEY_SCENE_MODE = "scene-mode"; 607 private static final String KEY_FLASH_MODE = "flash-mode"; 608 // Parameter key suffix for supported values. 609 private static final String SUPPORTED_VALUES_SUFFIX = "-values"; 610 611 // Values for white balance settings. 612 public static final String WHITE_BALANCE_AUTO = "auto"; 613 public static final String WHITE_BALANCE_INCANDESCENT = "incandescent"; 614 public static final String WHITE_BALANCE_FLUORESCENT = "fluorescent"; 615 public static final String WHITE_BALANCE_WARM_FLUORESCENT = "warm-fluorescent"; 616 public static final String WHITE_BALANCE_DAYLIGHT = "daylight"; 617 public static final String WHITE_BALANCE_CLOUDY_DAYLIGHT = "cloudy-daylight"; 618 public static final String WHITE_BALANCE_TWILIGHT = "twilight"; 619 public static final String WHITE_BALANCE_SHADE = "shade"; 620 621 // Values for color effect settings. 622 public static final String EFFECT_NONE = "none"; 623 public static final String EFFECT_MONO = "mono"; 624 public static final String EFFECT_NEGATIVE = "negative"; 625 public static final String EFFECT_SOLARIZE = "solarize"; 626 public static final String EFFECT_SEPIA = "sepia"; 627 public static final String EFFECT_POSTERIZE = "posterize"; 628 public static final String EFFECT_WHITEBOARD = "whiteboard"; 629 public static final String EFFECT_BLACKBOARD = "blackboard"; 630 public static final String EFFECT_AQUA = "aqua"; 631 632 // Values for antibanding settings. 633 public static final String ANTIBANDING_AUTO = "auto"; 634 public static final String ANTIBANDING_50HZ = "50hz"; 635 public static final String ANTIBANDING_60HZ = "60hz"; 636 public static final String ANTIBANDING_OFF = "off"; 637 638 // Values for flash mode settings. 639 /** 640 * Flash will not be fired. 641 */ 642 public static final String FLASH_MODE_OFF = "off"; 643 /** 644 * Flash will be fired automatically when required. The timing is 645 * decided by camera driver. 646 */ 647 public static final String FLASH_MODE_AUTO = "auto"; 648 /** 649 * Flash will always be fired. The timing is decided by camera driver. 650 */ 651 public static final String FLASH_MODE_ON = "on"; 652 /** 653 * Flash will be fired in red-eye reduction mode. 654 */ 655 public static final String FLASH_MODE_RED_EYE = "red-eye"; 656 657 // Values for scene mode settings. 658 public static final String SCENE_MODE_AUTO = "auto"; 659 public static final String SCENE_MODE_ACTION = "action"; 660 public static final String SCENE_MODE_PORTRAIT = "portrait"; 661 public static final String SCENE_MODE_LANDSCAPE = "landscape"; 662 public static final String SCENE_MODE_NIGHT = "night"; 663 public static final String SCENE_MODE_NIGHT_PORTRAIT = "night-portrait"; 664 public static final String SCENE_MODE_THEATRE = "theatre"; 665 public static final String SCENE_MODE_BEACH = "beach"; 666 public static final String SCENE_MODE_SNOW = "snow"; 667 public static final String SCENE_MODE_SUNSET = "sunset"; 668 public static final String SCENE_MODE_STEADYPHOTO = "steadyphoto"; 669 public static final String SCENE_MODE_FIREWORKS = "fireworks"; 670 public static final String SCENE_MODE_SPORTS = "sports"; 671 public static final String SCENE_MODE_PARTY = "party"; 672 public static final String SCENE_MODE_CANDLELIGHT = "candlelight"; 673 674 // Formats for setPreviewFormat and setPictureFormat. 675 private static final String PIXEL_FORMAT_YUV422SP = "yuv422sp"; 676 private static final String PIXEL_FORMAT_YUV420SP = "yuv420sp"; 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 return splitInt(str); 962 } 963 964 /** 965 * Sets the dimensions for pictures. 966 * 967 * @param width the width for pictures, in pixels 968 * @param height the height for pictures, in pixels 969 */ 970 public void setPictureSize(int width, int height) { 971 String v = Integer.toString(width) + "x" + Integer.toString(height); 972 set(KEY_PICTURE_SIZE, v); 973 } 974 975 /** 976 * Returns the dimension setting for pictures. 977 * 978 * @return a Size object with the height and width setting 979 * for pictures 980 */ 981 public Size getPictureSize() { 982 String pair = get(KEY_PICTURE_SIZE); 983 return strToSize(pair); 984 } 985 986 /** 987 * Gets the supported picture sizes. 988 * 989 * @return a List of Size objects. null if picture size setting is not 990 * supported. 991 */ 992 public List<Size> getSupportedPictureSizes() { 993 String str = get(KEY_PICTURE_SIZE + SUPPORTED_VALUES_SUFFIX); 994 return splitSize(str); 995 } 996 997 /** 998 * Sets the image format for pictures. 999 * 1000 * @param pixel_format the desired picture format 1001 * (<var>PixelFormat.YCbCr_420_SP (NV21)</var>, 1002 * <var>PixelFormat.RGB_565</var>, or 1003 * <var>PixelFormat.JPEG</var>) 1004 * @see android.graphics.PixelFormat 1005 */ 1006 public void setPictureFormat(int pixel_format) { 1007 String s = cameraFormatForPixelFormat(pixel_format); 1008 if (s == null) { 1009 throw new IllegalArgumentException( 1010 "Invalid pixel_format=" + pixel_format); 1011 } 1012 1013 set(KEY_PICTURE_FORMAT, s); 1014 } 1015 1016 /** 1017 * Returns the image format for pictures. 1018 * 1019 * @return the PixelFormat int representing the picture format 1020 */ 1021 public int getPictureFormat() { 1022 return pixelFormatForCameraFormat(get(KEY_PICTURE_FORMAT)); 1023 } 1024 1025 /** 1026 * Gets the supported picture formats. 1027 * 1028 * @return a List of Integer objects (values are PixelFormat.XXX). null 1029 * if picture setting is not supported. 1030 */ 1031 public List<Integer> getSupportedPictureFormats() { 1032 String str = get(KEY_PICTURE_SIZE + SUPPORTED_VALUES_SUFFIX); 1033 return splitInt(str); 1034 } 1035 1036 private String cameraFormatForPixelFormat(int pixel_format) { 1037 switch(pixel_format) { 1038 case PixelFormat.YCbCr_422_SP: return PIXEL_FORMAT_YUV422SP; 1039 case PixelFormat.YCbCr_420_SP: return PIXEL_FORMAT_YUV420SP; 1040 case PixelFormat.RGB_565: return PIXEL_FORMAT_RGB565; 1041 case PixelFormat.JPEG: return PIXEL_FORMAT_JPEG; 1042 default: return null; 1043 } 1044 } 1045 1046 private int pixelFormatForCameraFormat(String format) { 1047 if (format == null) 1048 return PixelFormat.UNKNOWN; 1049 1050 if (format.equals(PIXEL_FORMAT_YUV422SP)) 1051 return PixelFormat.YCbCr_422_SP; 1052 1053 if (format.equals(PIXEL_FORMAT_YUV420SP)) 1054 return PixelFormat.YCbCr_420_SP; 1055 1056 if (format.equals(PIXEL_FORMAT_RGB565)) 1057 return PixelFormat.RGB_565; 1058 1059 if (format.equals(PIXEL_FORMAT_JPEG)) 1060 return PixelFormat.JPEG; 1061 1062 return PixelFormat.UNKNOWN; 1063 } 1064 1065 /** 1066 * Sets the orientation of the device in degrees, which instructs the 1067 * camera driver to rotate the picture and thumbnail, in order to match 1068 * what the user sees from the viewfinder. For example, suppose the 1069 * natural position of the device is landscape. If the user takes a 1070 * picture in landscape mode in 2048x1536 resolution, the rotation 1071 * should be set to 0. If the user rotates the phone 90 degrees 1072 * clockwise, the rotation should be set to 90. Applications can use 1073 * {@link android.view.OrientationEventListener} to set this parameter. 1074 * 1075 * Since the picture is rotated, the orientation in the EXIF header is 1076 * missing or always 1 (row #0 is top and column #0 is left side). 1077 * 1078 * @param rotation The orientation of the device in degrees. Rotation 1079 * can only be 0, 90, 180 or 270. 1080 * @throws IllegalArgumentException if rotation value is invalid. 1081 * @see android.view.OrientationEventListener 1082 */ 1083 public void setRotation(int rotation) { 1084 if (rotation == 0 || rotation == 90 || rotation == 180 1085 || rotation == 270) { 1086 set(KEY_ROTATION, Integer.toString(rotation)); 1087 } else { 1088 throw new IllegalArgumentException( 1089 "Invalid rotation=" + rotation); 1090 } 1091 } 1092 1093 /** 1094 * Sets GPS latitude coordinate. This will be stored in JPEG EXIF 1095 * header. 1096 * 1097 * @param latitude GPS latitude coordinate. 1098 */ 1099 public void setGpsLatitude(double latitude) { 1100 set(KEY_GPS_LATITUDE, Double.toString(latitude)); 1101 } 1102 1103 /** 1104 * Sets GPS longitude coordinate. This will be stored in JPEG EXIF 1105 * header. 1106 * 1107 * @param longitude GPS longitude coordinate. 1108 */ 1109 public void setGpsLongitude(double longitude) { 1110 set(KEY_GPS_LONGITUDE, Double.toString(longitude)); 1111 } 1112 1113 /** 1114 * Sets GPS altitude. This will be stored in JPEG EXIF header. 1115 * 1116 * @param altitude GPS altitude in meters. 1117 */ 1118 public void setGpsAltitude(double altitude) { 1119 set(KEY_GPS_ALTITUDE, Double.toString(altitude)); 1120 } 1121 1122 /** 1123 * Sets GPS timestamp. This will be stored in JPEG EXIF header. 1124 * 1125 * @param timestamp GPS timestamp (UTC in seconds since January 1, 1126 * 1970). 1127 */ 1128 public void setGpsTimestamp(long timestamp) { 1129 set(KEY_GPS_TIMESTAMP, Long.toString(timestamp)); 1130 } 1131 1132 /** 1133 * Removes GPS latitude, longitude, altitude, and timestamp from the 1134 * parameters. 1135 */ 1136 public void removeGpsData() { 1137 remove(KEY_GPS_LATITUDE); 1138 remove(KEY_GPS_LONGITUDE); 1139 remove(KEY_GPS_ALTITUDE); 1140 remove(KEY_GPS_TIMESTAMP); 1141 } 1142 1143 /** 1144 * Gets the current white balance setting. 1145 * 1146 * @return one of WHITE_BALANCE_XXX string constant. null if white 1147 * balance setting is not supported. 1148 */ 1149 public String getWhiteBalance() { 1150 return get(KEY_WHITE_BALANCE); 1151 } 1152 1153 /** 1154 * Sets the white balance. 1155 * 1156 * @param value WHITE_BALANCE_XXX string constant. 1157 */ 1158 public void setWhiteBalance(String value) { 1159 set(KEY_WHITE_BALANCE, value); 1160 } 1161 1162 /** 1163 * Gets the supported white balance. 1164 * 1165 * @return a List of WHITE_BALANCE_XXX string constants. null if white 1166 * balance setting is not supported. 1167 */ 1168 public List<String> getSupportedWhiteBalance() { 1169 String str = get(KEY_WHITE_BALANCE + SUPPORTED_VALUES_SUFFIX); 1170 return split(str); 1171 } 1172 1173 /** 1174 * Gets the current color effect setting. 1175 * 1176 * @return one of EFFECT_XXX string constant. null if color effect 1177 * setting is not supported. 1178 */ 1179 public String getColorEffect() { 1180 return get(KEY_EFFECT); 1181 } 1182 1183 /** 1184 * Sets the current color effect setting. 1185 * 1186 * @param value EFFECT_XXX string constants. 1187 */ 1188 public void setColorEffect(String value) { 1189 set(KEY_EFFECT, value); 1190 } 1191 1192 /** 1193 * Gets the supported color effects. 1194 * 1195 * @return a List of EFFECT_XXX string constants. null if color effect 1196 * setting is not supported. 1197 */ 1198 public List<String> getSupportedColorEffects() { 1199 String str = get(KEY_EFFECT + SUPPORTED_VALUES_SUFFIX); 1200 return split(str); 1201 } 1202 1203 1204 /** 1205 * Gets the current antibanding setting. 1206 * 1207 * @return one of ANTIBANDING_XXX string constant. null if antibanding 1208 * setting is not supported. 1209 */ 1210 public String getAntibanding() { 1211 return get(KEY_ANTIBANDING); 1212 } 1213 1214 /** 1215 * Sets the antibanding. 1216 * 1217 * @param antibanding ANTIBANDING_XXX string constant. 1218 */ 1219 public void setAntibanding(String antibanding) { 1220 set(KEY_ANTIBANDING, antibanding); 1221 } 1222 1223 /** 1224 * Gets the supported antibanding values. 1225 * 1226 * @return a List of ANTIBANDING_XXX string constants. null if 1227 * antibanding setting is not supported. 1228 */ 1229 public List<String> getSupportedAntibanding() { 1230 String str = get(KEY_ANTIBANDING + SUPPORTED_VALUES_SUFFIX); 1231 return split(str); 1232 } 1233 1234 /** 1235 * Gets the current scene mode setting. 1236 * 1237 * @return one of SCENE_MODE_XXX string constant. null if scene mode 1238 * setting is not supported. 1239 */ 1240 public String getSceneMode() { 1241 return get(KEY_SCENE_MODE); 1242 } 1243 1244 /** 1245 * Sets the scene mode. 1246 * 1247 * @param value SCENE_MODE_XXX string constants. 1248 */ 1249 public void setSceneMode(String value) { 1250 set(KEY_SCENE_MODE, value); 1251 } 1252 1253 /** 1254 * Gets the supported scene modes. 1255 * 1256 * @return a List of SCENE_MODE_XXX string constant. null if scene mode 1257 * setting is not supported. 1258 */ 1259 public List<String> getSupportedSceneModes() { 1260 String str = get(KEY_SCENE_MODE + SUPPORTED_VALUES_SUFFIX); 1261 return split(str); 1262 } 1263 1264 /** 1265 * Gets the current flash mode setting. 1266 * 1267 * @return one of FLASH_MODE_XXX string constant. null if flash mode 1268 * setting is not supported. 1269 */ 1270 public String getFlashMode() { 1271 return get(KEY_FLASH_MODE); 1272 } 1273 1274 /** 1275 * Sets the flash mode. 1276 * 1277 * @param value FLASH_MODE_XXX string constants. 1278 */ 1279 public void setFlashMode(String value) { 1280 set(KEY_FLASH_MODE, value); 1281 } 1282 1283 /** 1284 * Gets the supported flash modes. 1285 * 1286 * @return a List of FLASH_MODE_XXX string constants. null if flash mode 1287 * setting is not supported. 1288 */ 1289 public List<String> getSupportedFlashModes() { 1290 String str = get(KEY_FLASH_MODE + SUPPORTED_VALUES_SUFFIX); 1291 return split(str); 1292 } 1293 1294 // Splits a comma delimited string to an ArrayList of String. 1295 // Return null if the passing string is null or the size is 0. 1296 private ArrayList<String> split(String str) { 1297 if (str == null) return null; 1298 1299 // Use StringTokenizer because it is faster than split. 1300 StringTokenizer tokenizer = new StringTokenizer(str, ","); 1301 ArrayList<String> substrings = new ArrayList<String>(); 1302 while (tokenizer.hasMoreElements()) { 1303 substrings.add(tokenizer.nextToken()); 1304 } 1305 return substrings; 1306 } 1307 1308 // Splits a comma delimited string to an ArrayList of Integer. 1309 // Return null if the passing string is null or the size is 0. 1310 private ArrayList<Integer> splitInt(String str) { 1311 if (str == null) return null; 1312 1313 StringTokenizer tokenizer = new StringTokenizer(str, ","); 1314 ArrayList<Integer> substrings = new ArrayList<Integer>(); 1315 while (tokenizer.hasMoreElements()) { 1316 String token = tokenizer.nextToken(); 1317 substrings.add(Integer.parseInt(token)); 1318 } 1319 if (substrings.size() == 0) return null; 1320 return substrings; 1321 } 1322 1323 // Splits a comma delimited string to an ArrayList of Size. 1324 // Return null if the passing string is null or the size is 0. 1325 private ArrayList<Size> splitSize(String str) { 1326 if (str == null) return null; 1327 1328 StringTokenizer tokenizer = new StringTokenizer(str, ","); 1329 ArrayList<Size> sizeList = new ArrayList<Size>(); 1330 while (tokenizer.hasMoreElements()) { 1331 Size size = strToSize(tokenizer.nextToken()); 1332 if (size != null) sizeList.add(size); 1333 } 1334 if (sizeList.size() == 0) return null; 1335 return sizeList; 1336 } 1337 1338 // Parses a string (ex: "480x320") to Size object. 1339 // Return null if the passing string is null. 1340 private Size strToSize(String str) { 1341 if (str == null) return null; 1342 1343 int pos = str.indexOf('x'); 1344 if (pos != -1) { 1345 String width = str.substring(0, pos); 1346 String height = str.substring(pos + 1); 1347 return new Size(Integer.parseInt(width), 1348 Integer.parseInt(height)); 1349 } 1350 Log.e(TAG, "Invalid size parameter string=" + str); 1351 return null; 1352 } 1353 }; 1354} 1355