Camera.java revision 5b9bcda3a26e9b1f9b1eff28a2be8853d69614f0
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 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">&lt;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> &lt;uses-permission android:name="android.permission.CAMERA" />
49 * &lt;uses-feature android:name="android.hardware.camera" />
50 * &lt;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    private boolean mWithBuffer;
85
86    /**
87     * Returns a new Camera object.
88     */
89    public static Camera open() {
90        return new Camera();
91    }
92
93    Camera() {
94        mShutterCallback = null;
95        mRawImageCallback = null;
96        mJpegCallback = null;
97        mPreviewCallback = null;
98        mPostviewCallback = null;
99        mZoomCallback = null;
100
101        Looper looper;
102        if ((looper = Looper.myLooper()) != null) {
103            mEventHandler = new EventHandler(this, looper);
104        } else if ((looper = Looper.getMainLooper()) != null) {
105            mEventHandler = new EventHandler(this, looper);
106        } else {
107            mEventHandler = null;
108        }
109
110        native_setup(new WeakReference<Camera>(this));
111    }
112
113    protected void finalize() {
114        native_release();
115    }
116
117    private native final void native_setup(Object camera_this);
118    private native final void native_release();
119
120
121    /**
122     * Disconnects and releases the Camera object resources.
123     * <p>It is recommended that you call this as soon as you're done with the
124     * Camera object.</p>
125     */
126    public final void release() {
127        native_release();
128    }
129
130    /**
131     * Reconnect to the camera after passing it to MediaRecorder. To save
132     * setup/teardown time, a client of Camera can pass an initialized Camera
133     * object to a MediaRecorder to use for video recording. Once the
134     * MediaRecorder is done with the Camera, this method can be used to
135     * re-establish a connection with the camera hardware. NOTE: The Camera
136     * object must first be unlocked by the process that owns it before it
137     * can be connected to another process.
138     *
139     * @throws IOException if the method fails.
140     */
141    public native final void reconnect() throws IOException;
142
143    /**
144     * Lock the camera to prevent other processes from accessing it. To save
145     * setup/teardown time, a client of Camera can pass an initialized Camera
146     * object to another process. This method is used to re-lock the Camera
147     * object prevent other processes from accessing it. By default, the
148     * Camera object is locked. Locking it again from the same process will
149     * have no effect. Attempting to lock it from another process if it has
150     * not been unlocked will fail.
151     *
152     * @throws RuntimeException if the method fails.
153     */
154    public native final void lock();
155
156    /**
157     * Unlock the camera to allow another process to access it. To save
158     * setup/teardown time, a client of Camera can pass an initialized Camera
159     * object to another process. This method is used to unlock the Camera
160     * object before handing off the Camera object to the other process.
161     *
162     * @throws RuntimeException if the method fails.
163     */
164    public native final void unlock();
165
166    /**
167     * Sets the SurfaceHolder to be used for a picture preview. If the surface
168     * changed since the last call, the screen will blank. Nothing happens
169     * if the same surface is re-set.
170     *
171     * @param holder the SurfaceHolder upon which to place the picture preview
172     * @throws IOException if the method fails.
173     */
174    public final void setPreviewDisplay(SurfaceHolder holder) throws IOException {
175        if (holder != null) {
176            setPreviewDisplay(holder.getSurface());
177        } else {
178            setPreviewDisplay((Surface)null);
179        }
180    }
181
182    private native final void setPreviewDisplay(Surface surface);
183
184    /**
185     * Used to get a copy of each preview frame.
186     */
187    public interface PreviewCallback
188    {
189        /**
190         * The callback that delivers the preview frames.
191         *
192         * @param data The contents of the preview frame in the format defined
193         *  by {@link android.graphics.ImageFormat}, which can be queried
194         *  with {@link android.hardware.Camera.Parameters#getPreviewFormat()}.
195         *  If {@link android.hardware.Camera.Parameters#setPreviewFormat(int)}
196         *             is never called, the default will be the YCbCr_420_SP
197         *             (NV21) format.
198         * @param camera The Camera service object.
199         */
200        void onPreviewFrame(byte[] data, Camera camera);
201    };
202
203    /**
204     * Start drawing preview frames to the surface.
205     */
206    public native final void startPreview();
207
208    /**
209     * Stop drawing preview frames to the surface.
210     */
211    public native final void stopPreview();
212
213    /**
214     * Return current preview state.
215     *
216     * FIXME: Unhide before release
217     * @hide
218     */
219    public native final boolean previewEnabled();
220
221    /**
222     * Can be called at any time to instruct the camera to use a callback for
223     * each preview frame in addition to displaying it.
224     *
225     * @param cb A callback object that receives a copy of each preview frame.
226     *           Pass null to stop receiving callbacks at any time.
227     */
228    public final void setPreviewCallback(PreviewCallback cb) {
229        mPreviewCallback = cb;
230        mOneShot = false;
231        mWithBuffer = false;
232        // Always use one-shot mode. We fake camera preview mode by
233        // doing one-shot preview continuously.
234        setHasPreviewCallback(cb != null, false);
235    }
236
237    /**
238     * Installs a callback to retrieve a single preview frame, after which the
239     * callback is cleared.
240     *
241     * @param cb A callback object that receives a copy of the preview frame.
242     */
243    public final void setOneShotPreviewCallback(PreviewCallback cb) {
244        mPreviewCallback = cb;
245        mOneShot = true;
246        mWithBuffer = false;
247        setHasPreviewCallback(cb != null, false);
248    }
249
250    private native final void setHasPreviewCallback(boolean installed, boolean manualBuffer);
251
252    /**
253     * Installs a callback which will get called as long as there are buffers in the
254     * preview buffer queue, which minimizes dynamic allocation of preview buffers.
255     *
256     * Apps must call addCallbackBuffer to explicitly register the buffers to use, or no callbacks
257     * will be received. addCallbackBuffer may be safely called before or after
258     * a call to setPreviewCallbackWithBuffer with a non-null callback parameter.
259     *
260     * The buffer queue will be cleared upon any calls to setOneShotPreviewCallback,
261     * setPreviewCallback, or to this method with a null callback parameter.
262     *
263     * @param cb A callback object that receives a copy of the preview frame.  A null value will clear the queue.
264     */
265    public final void setPreviewCallbackWithBuffer(PreviewCallback cb) {
266        mPreviewCallback = cb;
267        mOneShot = false;
268        mWithBuffer = true;
269        setHasPreviewCallback(cb != null, true);
270    }
271
272    /**
273     * Adds a pre-allocated buffer to the callback buffer queue.
274     * Preview width and height can be determined from getPreviewSize, and bitsPerPixel can be
275     * found from {@link android.hardware.Camera.Parameters#getPreviewFormat()}
276     * and {@link android.graphics.ImageFormat#getBitsPerPixel(int)}.
277     *
278     * Alternatively, a buffer from a previous callback may be passed in or used
279     * to determine the size of new preview frame buffers.
280     *
281     * @param callbackBuffer The buffer to register. Size should be width * height * bitsPerPixel / 8.
282     * @see #setPreviewCallbackWithBuffer(PreviewCallback)
283     */
284    public native final void addCallbackBuffer(byte[] callbackBuffer);
285
286    private class EventHandler extends Handler
287    {
288        private Camera mCamera;
289
290        public EventHandler(Camera c, Looper looper) {
291            super(looper);
292            mCamera = c;
293        }
294
295        @Override
296        public void handleMessage(Message msg) {
297            switch(msg.what) {
298            case CAMERA_MSG_SHUTTER:
299                if (mShutterCallback != null) {
300                    mShutterCallback.onShutter();
301                }
302                return;
303
304            case CAMERA_MSG_RAW_IMAGE:
305                if (mRawImageCallback != null) {
306                    mRawImageCallback.onPictureTaken((byte[])msg.obj, mCamera);
307                }
308                return;
309
310            case CAMERA_MSG_COMPRESSED_IMAGE:
311                if (mJpegCallback != null) {
312                    mJpegCallback.onPictureTaken((byte[])msg.obj, mCamera);
313                }
314                return;
315
316            case CAMERA_MSG_PREVIEW_FRAME:
317                if (mPreviewCallback != null) {
318                    PreviewCallback cb = mPreviewCallback;
319                    if (mOneShot) {
320                        // Clear the callback variable before the callback
321                        // in case the app calls setPreviewCallback from
322                        // the callback function
323                        mPreviewCallback = null;
324                    } else if (!mWithBuffer) {
325                        // We're faking the camera preview mode to prevent
326                        // the app from being flooded with preview frames.
327                        // Set to oneshot mode again.
328                        setHasPreviewCallback(true, false);
329                    }
330                    cb.onPreviewFrame((byte[])msg.obj, mCamera);
331                }
332                return;
333
334            case CAMERA_MSG_POSTVIEW_FRAME:
335                if (mPostviewCallback != null) {
336                    mPostviewCallback.onPictureTaken((byte[])msg.obj, mCamera);
337                }
338                return;
339
340            case CAMERA_MSG_FOCUS:
341                if (mAutoFocusCallback != null) {
342                    mAutoFocusCallback.onAutoFocus(msg.arg1 == 0 ? false : true, mCamera);
343                }
344                return;
345
346            case CAMERA_MSG_ZOOM:
347                if (mZoomCallback != null) {
348                    mZoomCallback.onZoomUpdate(msg.arg1, msg.arg2 != 0, mCamera);
349                }
350                return;
351
352            case CAMERA_MSG_ERROR :
353                Log.e(TAG, "Error " + msg.arg1);
354                if (mErrorCallback != null) {
355                    mErrorCallback.onError(msg.arg1, mCamera);
356                }
357                return;
358
359            default:
360                Log.e(TAG, "Unknown message type " + msg.what);
361                return;
362            }
363        }
364    }
365
366    private static void postEventFromNative(Object camera_ref,
367                                            int what, int arg1, int arg2, Object obj)
368    {
369        Camera c = (Camera)((WeakReference)camera_ref).get();
370        if (c == null)
371            return;
372
373        if (c.mEventHandler != null) {
374            Message m = c.mEventHandler.obtainMessage(what, arg1, arg2, obj);
375            c.mEventHandler.sendMessage(m);
376        }
377    }
378
379    /**
380     * Handles the callback for the camera auto focus.
381     * <p>Devices that do not support auto-focus will receive a "fake"
382     * callback to this interface. If your application needs auto-focus and
383     * should not be installed on devices <em>without</em> auto-focus, you must
384     * declare that your app uses the
385     * {@code android.hardware.camera.autofocus} feature, in the
386     * <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html">&lt;uses-feature></a>
387     * manifest element.</p>
388     */
389    public interface AutoFocusCallback
390    {
391        /**
392         * Callback for the camera auto focus. If the camera does not support
393         * auto-focus and autoFocus is called, onAutoFocus will be called
394         * immediately with success.
395         *
396         * @param success true if focus was successful, false if otherwise
397         * @param camera  the Camera service object
398         */
399        void onAutoFocus(boolean success, Camera camera);
400    };
401
402    /**
403     * Starts auto-focus function and registers a callback function to run when
404     * camera is focused. Only valid after startPreview() has been called.
405     * Applications should call {@link
406     * android.hardware.Camera.Parameters#getFocusMode()} to determine if this
407     * method should be called. If the camera does not support auto-focus, it is
408     * a no-op and {@link AutoFocusCallback#onAutoFocus(boolean, Camera)}
409     * callback will be called immediately.
410     * <p>If your application should not be installed
411     * on devices without auto-focus, you must declare that your application
412     * uses auto-focus with the
413     * <a href="{@docRoot}guide/topics/manifest/uses-feature-element.html">&lt;uses-feature></a>
414     * manifest element.</p>
415     * <p>If the current flash mode is not
416     * {@link android.hardware.Camera.Parameters#FLASH_MODE_OFF}, flash may be
417     * fired during auto-focus depending on the driver.<p>
418     *
419     * @param cb the callback to run
420     */
421    public final void autoFocus(AutoFocusCallback cb)
422    {
423        mAutoFocusCallback = cb;
424        native_autoFocus();
425    }
426    private native final void native_autoFocus();
427
428    /**
429     * Cancels auto-focus function. If the auto-focus is still in progress,
430     * this function will cancel it. Whether the auto-focus is in progress
431     * or not, this function will return the focus position to the default.
432     * If the camera does not support auto-focus, this is a no-op.
433     */
434    public final void cancelAutoFocus()
435    {
436        mAutoFocusCallback = null;
437        native_cancelAutoFocus();
438    }
439    private native final void native_cancelAutoFocus();
440
441    /**
442     * An interface which contains a callback for the shutter closing after taking a picture.
443     */
444    public interface ShutterCallback
445    {
446        /**
447         * Can be used to play a shutter sound as soon as the image has been captured, but before
448         * the data is available.
449         */
450        void onShutter();
451    }
452
453    /**
454     * Handles the callback for when a picture is taken.
455     */
456    public interface PictureCallback {
457        /**
458         * Callback for when a picture is taken.
459         *
460         * @param data   a byte array of the picture data
461         * @param camera the Camera service object
462         */
463        void onPictureTaken(byte[] data, Camera camera);
464    };
465
466    /**
467     * Triggers an asynchronous image capture. The camera service will initiate
468     * a series of callbacks to the application as the image capture progresses.
469     * The shutter callback occurs after the image is captured. This can be used
470     * to trigger a sound to let the user know that image has been captured. The
471     * raw callback occurs when the raw image data is available (NOTE: the data
472     * may be null if the hardware does not have enough memory to make a copy).
473     * The jpeg callback occurs when the compressed image is available. If the
474     * application does not need a particular callback, a null can be passed
475     * instead of a callback method.
476     *
477     * This method will stop the preview. Applications should not call {@link
478     * #stopPreview()} before this. After jpeg callback is received,
479     * applications can call {@link #startPreview()} to restart the preview.
480     *
481     * @param shutter   callback after the image is captured, may be null
482     * @param raw       callback with raw image data, may be null
483     * @param jpeg      callback with jpeg image data, may be null
484     */
485    public final void takePicture(ShutterCallback shutter, PictureCallback raw,
486            PictureCallback jpeg) {
487        takePicture(shutter, raw, null, jpeg);
488    }
489    private native final void native_takePicture();
490
491    /**
492     * Triggers an asynchronous image capture. The camera service will initiate
493     * a series of callbacks to the application as the image capture progresses.
494     * The shutter callback occurs after the image is captured. This can be used
495     * to trigger a sound to let the user know that image has been captured. The
496     * raw callback occurs when the raw image data is available (NOTE: the data
497     * may be null if the hardware does not have enough memory to make a copy).
498     * The postview callback occurs when a scaled, fully processed postview
499     * image is available (NOTE: not all hardware supports this). The jpeg
500     * callback occurs when the compressed image is available. If the
501     * application does not need a particular callback, a null can be passed
502     * instead of a callback method.
503     *
504     * This method will stop the preview. Applications should not call {@link
505     * #stopPreview()} before this. After jpeg callback is received,
506     * applications can call {@link #startPreview()} to restart the preview.
507     *
508     * @param shutter   callback after the image is captured, may be null
509     * @param raw       callback with raw image data, may be null
510     * @param postview  callback with postview image data, may be null
511     * @param jpeg      callback with jpeg image data, may be null
512     */
513    public final void takePicture(ShutterCallback shutter, PictureCallback raw,
514            PictureCallback postview, PictureCallback jpeg) {
515        mShutterCallback = shutter;
516        mRawImageCallback = raw;
517        mPostviewCallback = postview;
518        mJpegCallback = jpeg;
519        native_takePicture();
520    }
521
522    /**
523     * Zooms to the requested value smoothly. Driver will generate {@link
524     * ZoomCallback} for the zoom value and whether zoom is stopped at the
525     * time. For example, suppose the current zoom is 0 and startSmoothZoom is
526     * called with value 3. Three ZoomCallback will be generated with zoom value
527     * 1, 2, and 3. The applications can call {@link #stopSmoothZoom} to stop
528     * the zoom earlier. The applications should not call startSmoothZoom again
529     * or change the zoom value before zoom stops. This method is supported if
530     * {@link android.hardware.Camera.Parameters#isSmoothZoomSupported} is true.
531     *
532     * @param value zoom value. The valid range is 0 to {@link
533     *              android.hardware.Camera.Parameters#getMaxZoom}.
534     */
535    public native final void startSmoothZoom(int value);
536
537    /**
538     * Stops the smooth zoom. The applications should wait for the {@link
539     * ZoomCallback} to know when the zoom is actually stopped. This method is
540     * supported if {@link
541     * android.hardware.Camera.Parameters#isSmoothZoomSupported} is true.
542     */
543    public native final void stopSmoothZoom();
544
545    /**
546     * Set the display orientation. This affects the preview frames and the
547     * picture displayed after snapshot. This method is useful for portrait
548     * mode applications.
549     *
550     * This does not affect the order of byte array passed in
551     * {@link PreviewCallback#onPreviewFrame}. This method is not allowed to
552     * be called during preview.
553     *
554     * @param degrees the angle that the picture will be rotated clockwise.
555     *                Valid values are 0, 90, 180, and 270. The starting
556     *                position is 0 (landscape).
557     */
558    public native final void setDisplayOrientation(int degrees);
559
560    /**
561     * Handles the zoom callback.
562     *
563     */
564    public interface ZoomCallback
565    {
566        /**
567         * Callback for zoom updates
568         *
569         * @param zoomValue the current zoom value. In smooth zoom mode, camera
570         *                  generates this callback for every new zoom value.
571         * @param stopped whether smooth zoom is stopped. If the value is true,
572         *                this is the last zoom update for the application.
573         *
574         * @param camera  the Camera service object
575         * @see #startSmoothZoom(int)
576         */
577        void onZoomUpdate(int zoomValue, boolean stopped, Camera camera);
578    };
579
580    /**
581     * Registers a callback to be invoked when the zoom value is updated by the
582     * camera driver during smooth zoom.
583     *
584     * @param cb the callback to run
585     * @see #startSmoothZoom(int)
586     */
587    public final void setZoomCallback(ZoomCallback cb)
588    {
589        mZoomCallback = cb;
590    }
591
592    // These match the enum in include/ui/Camera.h
593    /** Unspecified camerar error.  @see #ErrorCallback */
594    public static final int CAMERA_ERROR_UNKNOWN = 1;
595    /** Media server died. In this case, the application must release the
596     * Camera object and instantiate a new one. @see #ErrorCallback */
597    public static final int CAMERA_ERROR_SERVER_DIED = 100;
598
599    /**
600     * Handles the camera error callback.
601     */
602    public interface ErrorCallback
603    {
604        /**
605         * Callback for camera errors.
606         * @param error   error code:
607         * <ul>
608         * <li>{@link #CAMERA_ERROR_UNKNOWN}
609         * <li>{@link #CAMERA_ERROR_SERVER_DIED}
610         * </ul>
611         * @param camera  the Camera service object
612         */
613        void onError(int error, Camera camera);
614    };
615
616    /**
617     * Registers a callback to be invoked when an error occurs.
618     * @param cb the callback to run
619     */
620    public final void setErrorCallback(ErrorCallback cb)
621    {
622        mErrorCallback = cb;
623    }
624
625    private native final void native_setParameters(String params);
626    private native final String native_getParameters();
627
628    /**
629     * Sets the Parameters for pictures from this Camera service.
630     *
631     * @param params the Parameters to use for this Camera service
632     */
633    public void setParameters(Parameters params) {
634        native_setParameters(params.flatten());
635    }
636
637    /**
638     * Returns the picture Parameters for this Camera service.
639     */
640    public Parameters getParameters() {
641        Parameters p = new Parameters();
642        String s = native_getParameters();
643        p.unflatten(s);
644        return p;
645    }
646
647    /**
648     * Handles the picture size (dimensions).
649     */
650    public class Size {
651        /**
652         * Sets the dimensions for pictures.
653         *
654         * @param w the photo width (pixels)
655         * @param h the photo height (pixels)
656         */
657        public Size(int w, int h) {
658            width = w;
659            height = h;
660        }
661        /**
662         * Compares {@code obj} to this size.
663         *
664         * @param obj the object to compare this size with.
665         * @return {@code true} if the width and height of {@code obj} is the
666         *         same as those of this size. {@code false} otherwise.
667         */
668        @Override
669        public boolean equals(Object obj) {
670            if (!(obj instanceof Size)) {
671                return false;
672            }
673            Size s = (Size) obj;
674            return width == s.width && height == s.height;
675        }
676        @Override
677        public int hashCode() {
678            return width * 32713 + height;
679        }
680        /** width of the picture */
681        public int width;
682        /** height of the picture */
683        public int height;
684    };
685
686    /**
687     * Handles the parameters for pictures created by a Camera service.
688     *
689     * <p>To make camera parameters take effect, applications have to call
690     * Camera.setParameters. For example, after setWhiteBalance is called, white
691     * balance is not changed until Camera.setParameters() is called.
692     *
693     * <p>Different devices may have different camera capabilities, such as
694     * picture size or flash modes. The application should query the camera
695     * capabilities before setting parameters. For example, the application
696     * should call getSupportedColorEffects before calling setEffect. If the
697     * camera does not support color effects, getSupportedColorEffects will
698     * return null.
699     */
700    public class Parameters {
701        // Parameter keys to communicate with the camera driver.
702        private static final String KEY_PREVIEW_SIZE = "preview-size";
703        private static final String KEY_PREVIEW_FORMAT = "preview-format";
704        private static final String KEY_PREVIEW_FRAME_RATE = "preview-frame-rate";
705        private static final String KEY_PICTURE_SIZE = "picture-size";
706        private static final String KEY_PICTURE_FORMAT = "picture-format";
707        private static final String KEY_JPEG_THUMBNAIL_SIZE = "jpeg-thumbnail-size";
708        private static final String KEY_JPEG_THUMBNAIL_WIDTH = "jpeg-thumbnail-width";
709        private static final String KEY_JPEG_THUMBNAIL_HEIGHT = "jpeg-thumbnail-height";
710        private static final String KEY_JPEG_THUMBNAIL_QUALITY = "jpeg-thumbnail-quality";
711        private static final String KEY_JPEG_QUALITY = "jpeg-quality";
712        private static final String KEY_ROTATION = "rotation";
713        private static final String KEY_GPS_LATITUDE = "gps-latitude";
714        private static final String KEY_GPS_LONGITUDE = "gps-longitude";
715        private static final String KEY_GPS_ALTITUDE = "gps-altitude";
716        private static final String KEY_GPS_TIMESTAMP = "gps-timestamp";
717        private static final String KEY_GPS_PROCESSING_METHOD = "gps-processing-method";
718        private static final String KEY_WHITE_BALANCE = "whitebalance";
719        private static final String KEY_EFFECT = "effect";
720        private static final String KEY_ANTIBANDING = "antibanding";
721        private static final String KEY_SCENE_MODE = "scene-mode";
722        private static final String KEY_FLASH_MODE = "flash-mode";
723        private static final String KEY_FOCUS_MODE = "focus-mode";
724        private static final String KEY_FOCAL_LENGTH = "focal-length";
725        private static final String KEY_HORIZONTAL_VIEW_ANGLE = "horizontal-view-angle";
726        private static final String KEY_VERTICAL_VIEW_ANGLE = "vertical-view-angle";
727        private static final String KEY_EXPOSURE_COMPENSATION = "exposure-compensation";
728        private static final String KEY_MAX_EXPOSURE_COMPENSATION = "max-exposure-compensation";
729        private static final String KEY_MIN_EXPOSURE_COMPENSATION = "min-exposure-compensation";
730        private static final String KEY_EXPOSURE_COMPENSATION_STEP = "exposure-compensation-step";
731        private static final String KEY_ZOOM = "zoom";
732        private static final String KEY_MAX_ZOOM = "max-zoom";
733        private static final String KEY_ZOOM_RATIOS = "zoom-ratios";
734        private static final String KEY_ZOOM_SUPPORTED = "zoom-supported";
735        private static final String KEY_SMOOTH_ZOOM_SUPPORTED = "smooth-zoom-supported";
736        // Parameter key suffix for supported values.
737        private static final String SUPPORTED_VALUES_SUFFIX = "-values";
738
739        private static final String TRUE = "true";
740
741        // Values for white balance settings.
742        public static final String WHITE_BALANCE_AUTO = "auto";
743        public static final String WHITE_BALANCE_INCANDESCENT = "incandescent";
744        public static final String WHITE_BALANCE_FLUORESCENT = "fluorescent";
745        public static final String WHITE_BALANCE_WARM_FLUORESCENT = "warm-fluorescent";
746        public static final String WHITE_BALANCE_DAYLIGHT = "daylight";
747        public static final String WHITE_BALANCE_CLOUDY_DAYLIGHT = "cloudy-daylight";
748        public static final String WHITE_BALANCE_TWILIGHT = "twilight";
749        public static final String WHITE_BALANCE_SHADE = "shade";
750
751        // Values for color effect settings.
752        public static final String EFFECT_NONE = "none";
753        public static final String EFFECT_MONO = "mono";
754        public static final String EFFECT_NEGATIVE = "negative";
755        public static final String EFFECT_SOLARIZE = "solarize";
756        public static final String EFFECT_SEPIA = "sepia";
757        public static final String EFFECT_POSTERIZE = "posterize";
758        public static final String EFFECT_WHITEBOARD = "whiteboard";
759        public static final String EFFECT_BLACKBOARD = "blackboard";
760        public static final String EFFECT_AQUA = "aqua";
761
762        // Values for antibanding settings.
763        public static final String ANTIBANDING_AUTO = "auto";
764        public static final String ANTIBANDING_50HZ = "50hz";
765        public static final String ANTIBANDING_60HZ = "60hz";
766        public static final String ANTIBANDING_OFF = "off";
767
768        // Values for flash mode settings.
769        /**
770         * Flash will not be fired.
771         */
772        public static final String FLASH_MODE_OFF = "off";
773
774        /**
775         * Flash will be fired automatically when required. The flash may be fired
776         * during preview, auto-focus, or snapshot depending on the driver.
777         */
778        public static final String FLASH_MODE_AUTO = "auto";
779
780        /**
781         * Flash will always be fired during snapshot. The flash may also be
782         * fired during preview or auto-focus depending on the driver.
783         */
784        public static final String FLASH_MODE_ON = "on";
785
786        /**
787         * Flash will be fired in red-eye reduction mode.
788         */
789        public static final String FLASH_MODE_RED_EYE = "red-eye";
790
791        /**
792         * Constant emission of light during preview, auto-focus and snapshot.
793         * This can also be used for video recording.
794         */
795        public static final String FLASH_MODE_TORCH = "torch";
796
797        // Values for scene mode settings.
798        public static final String SCENE_MODE_AUTO = "auto";
799        public static final String SCENE_MODE_ACTION = "action";
800        public static final String SCENE_MODE_PORTRAIT = "portrait";
801        public static final String SCENE_MODE_LANDSCAPE = "landscape";
802        public static final String SCENE_MODE_NIGHT = "night";
803        public static final String SCENE_MODE_NIGHT_PORTRAIT = "night-portrait";
804        public static final String SCENE_MODE_THEATRE = "theatre";
805        public static final String SCENE_MODE_BEACH = "beach";
806        public static final String SCENE_MODE_SNOW = "snow";
807        public static final String SCENE_MODE_SUNSET = "sunset";
808        public static final String SCENE_MODE_STEADYPHOTO = "steadyphoto";
809        public static final String SCENE_MODE_FIREWORKS = "fireworks";
810        public static final String SCENE_MODE_SPORTS = "sports";
811        public static final String SCENE_MODE_PARTY = "party";
812        public static final String SCENE_MODE_CANDLELIGHT = "candlelight";
813
814        // Values for focus mode settings.
815        /**
816         * Auto-focus mode.
817         */
818        public static final String FOCUS_MODE_AUTO = "auto";
819
820        /**
821         * Focus is set at infinity. Applications should not call
822         * {@link #autoFocus(AutoFocusCallback)} in this mode.
823         */
824        public static final String FOCUS_MODE_INFINITY = "infinity";
825        public static final String FOCUS_MODE_MACRO = "macro";
826
827        /**
828         * Focus is fixed. The camera is always in this mode if the focus is not
829         * adjustable. If the camera has auto-focus, this mode can fix the
830         * focus, which is usually at hyperfocal distance. Applications should
831         * not call {@link #autoFocus(AutoFocusCallback)} in this mode.
832         */
833        public static final String FOCUS_MODE_FIXED = "fixed";
834
835        // Formats for setPreviewFormat and setPictureFormat.
836        private static final String PIXEL_FORMAT_YUV422SP = "yuv422sp";
837        private static final String PIXEL_FORMAT_YUV420SP = "yuv420sp";
838        private static final String PIXEL_FORMAT_YUV422I = "yuv422i-yuyv";
839        private static final String PIXEL_FORMAT_RGB565 = "rgb565";
840        private static final String PIXEL_FORMAT_JPEG = "jpeg";
841
842        private HashMap<String, String> mMap;
843
844        private Parameters() {
845            mMap = new HashMap<String, String>();
846        }
847
848        /**
849         * Writes the current Parameters to the log.
850         * @hide
851         * @deprecated
852         */
853        public void dump() {
854            Log.e(TAG, "dump: size=" + mMap.size());
855            for (String k : mMap.keySet()) {
856                Log.e(TAG, "dump: " + k + "=" + mMap.get(k));
857            }
858        }
859
860        /**
861         * Creates a single string with all the parameters set in
862         * this Parameters object.
863         * <p>The {@link #unflatten(String)} method does the reverse.</p>
864         *
865         * @return a String with all values from this Parameters object, in
866         *         semi-colon delimited key-value pairs
867         */
868        public String flatten() {
869            StringBuilder flattened = new StringBuilder();
870            for (String k : mMap.keySet()) {
871                flattened.append(k);
872                flattened.append("=");
873                flattened.append(mMap.get(k));
874                flattened.append(";");
875            }
876            // chop off the extra semicolon at the end
877            flattened.deleteCharAt(flattened.length()-1);
878            return flattened.toString();
879        }
880
881        /**
882         * Takes a flattened string of parameters and adds each one to
883         * this Parameters object.
884         * <p>The {@link #flatten()} method does the reverse.</p>
885         *
886         * @param flattened a String of parameters (key-value paired) that
887         *                  are semi-colon delimited
888         */
889        public void unflatten(String flattened) {
890            mMap.clear();
891
892            StringTokenizer tokenizer = new StringTokenizer(flattened, ";");
893            while (tokenizer.hasMoreElements()) {
894                String kv = tokenizer.nextToken();
895                int pos = kv.indexOf('=');
896                if (pos == -1) {
897                    continue;
898                }
899                String k = kv.substring(0, pos);
900                String v = kv.substring(pos + 1);
901                mMap.put(k, v);
902            }
903        }
904
905        public void remove(String key) {
906            mMap.remove(key);
907        }
908
909        /**
910         * Sets a String parameter.
911         *
912         * @param key   the key name for the parameter
913         * @param value the String value of the parameter
914         */
915        public void set(String key, String value) {
916            if (key.indexOf('=') != -1 || key.indexOf(';') != -1) {
917                Log.e(TAG, "Key \"" + key + "\" contains invalid character (= or ;)");
918                return;
919            }
920            if (value.indexOf('=') != -1 || value.indexOf(';') != -1) {
921                Log.e(TAG, "Value \"" + value + "\" contains invalid character (= or ;)");
922                return;
923            }
924
925            mMap.put(key, value);
926        }
927
928        /**
929         * Sets an integer parameter.
930         *
931         * @param key   the key name for the parameter
932         * @param value the int value of the parameter
933         */
934        public void set(String key, int value) {
935            mMap.put(key, Integer.toString(value));
936        }
937
938        /**
939         * Returns the value of a String parameter.
940         *
941         * @param key the key name for the parameter
942         * @return the String value of the parameter
943         */
944        public String get(String key) {
945            return mMap.get(key);
946        }
947
948        /**
949         * Returns the value of an integer parameter.
950         *
951         * @param key the key name for the parameter
952         * @return the int value of the parameter
953         */
954        public int getInt(String key) {
955            return Integer.parseInt(mMap.get(key));
956        }
957
958        /**
959         * Sets the dimensions for preview pictures.
960         *
961         * @param width  the width of the pictures, in pixels
962         * @param height the height of the pictures, in pixels
963         */
964        public void setPreviewSize(int width, int height) {
965            String v = Integer.toString(width) + "x" + Integer.toString(height);
966            set(KEY_PREVIEW_SIZE, v);
967        }
968
969        /**
970         * Returns the dimensions setting for preview pictures.
971         *
972         * @return a Size object with the height and width setting
973         *          for the preview picture
974         */
975        public Size getPreviewSize() {
976            String pair = get(KEY_PREVIEW_SIZE);
977            return strToSize(pair);
978        }
979
980        /**
981         * Gets the supported preview sizes.
982         *
983         * @return a List of Size object. This method will always return a list
984         *         with at least one element.
985         */
986        public List<Size> getSupportedPreviewSizes() {
987            String str = get(KEY_PREVIEW_SIZE + SUPPORTED_VALUES_SUFFIX);
988            return splitSize(str);
989        }
990
991        /**
992         * Sets the dimensions for EXIF thumbnail in Jpeg picture. If
993         * applications set both width and height to 0, EXIF will not contain
994         * thumbnail.
995         *
996         * @param width  the width of the thumbnail, in pixels
997         * @param height the height of the thumbnail, in pixels
998         */
999        public void setJpegThumbnailSize(int width, int height) {
1000            set(KEY_JPEG_THUMBNAIL_WIDTH, width);
1001            set(KEY_JPEG_THUMBNAIL_HEIGHT, height);
1002        }
1003
1004        /**
1005         * Returns the dimensions for EXIF thumbnail in Jpeg picture.
1006         *
1007         * @return a Size object with the height and width setting for the EXIF
1008         *         thumbnails
1009         */
1010        public Size getJpegThumbnailSize() {
1011            return new Size(getInt(KEY_JPEG_THUMBNAIL_WIDTH),
1012                            getInt(KEY_JPEG_THUMBNAIL_HEIGHT));
1013        }
1014
1015        /**
1016         * Gets the supported jpeg thumbnail sizes.
1017         *
1018         * @return a List of Size object. This method will always return a list
1019         *         with at least two elements. Size 0,0 (no thumbnail) is always
1020         *         supported.
1021         */
1022        public List<Size> getSupportedJpegThumbnailSizes() {
1023            String str = get(KEY_JPEG_THUMBNAIL_SIZE + SUPPORTED_VALUES_SUFFIX);
1024            return splitSize(str);
1025        }
1026
1027        /**
1028         * Sets the quality of the EXIF thumbnail in Jpeg picture.
1029         *
1030         * @param quality the JPEG quality of the EXIF thumbnail. The range is 1
1031         *                to 100, with 100 being the best.
1032         */
1033        public void setJpegThumbnailQuality(int quality) {
1034            set(KEY_JPEG_THUMBNAIL_QUALITY, quality);
1035        }
1036
1037        /**
1038         * Returns the quality setting for the EXIF thumbnail in Jpeg picture.
1039         *
1040         * @return the JPEG quality setting of the EXIF thumbnail.
1041         */
1042        public int getJpegThumbnailQuality() {
1043            return getInt(KEY_JPEG_THUMBNAIL_QUALITY);
1044        }
1045
1046        /**
1047         * Sets Jpeg quality of captured picture.
1048         *
1049         * @param quality the JPEG quality of captured picture. The range is 1
1050         *                to 100, with 100 being the best.
1051         */
1052        public void setJpegQuality(int quality) {
1053            set(KEY_JPEG_QUALITY, quality);
1054        }
1055
1056        /**
1057         * Returns the quality setting for the JPEG picture.
1058         *
1059         * @return the JPEG picture quality setting.
1060         */
1061        public int getJpegQuality() {
1062            return getInt(KEY_JPEG_QUALITY);
1063        }
1064
1065        /**
1066         * Sets the rate at which preview frames are received. This is the
1067         * target frame rate. The actual frame rate depends on the driver.
1068         *
1069         * @param fps the frame rate (frames per second)
1070         */
1071        public void setPreviewFrameRate(int fps) {
1072            set(KEY_PREVIEW_FRAME_RATE, fps);
1073        }
1074
1075        /**
1076         * Returns the setting for the rate at which preview frames are
1077         * received. This is the target frame rate. The actual frame rate
1078         * depends on the driver.
1079         *
1080         * @return the frame rate setting (frames per second)
1081         */
1082        public int getPreviewFrameRate() {
1083            return getInt(KEY_PREVIEW_FRAME_RATE);
1084        }
1085
1086        /**
1087         * Gets the supported preview frame rates.
1088         *
1089         * @return a List of Integer objects (preview frame rates). null if
1090         *         preview frame rate setting is not supported.
1091         */
1092        public List<Integer> getSupportedPreviewFrameRates() {
1093            String str = get(KEY_PREVIEW_FRAME_RATE + SUPPORTED_VALUES_SUFFIX);
1094            return splitInt(str);
1095        }
1096
1097        /**
1098         * Sets the image format for preview pictures.
1099         * <p>If this is never called, the default format will be
1100         * {@link android.graphics.ImageFormat#NV21}, which
1101         * uses the NV21 encoding format.</p>
1102         *
1103         * @param pixel_format the desired preview picture format, defined
1104         *   by one of the {@link android.graphics.ImageFormat} constants.
1105         *   (E.g., <var>ImageFormat.NV21</var> (default),
1106         *                      <var>ImageFormat.RGB_565</var>, or
1107         *                      <var>ImageFormat.JPEG</var>)
1108         * @see android.graphics.ImageFormat
1109         */
1110        public void setPreviewFormat(int pixel_format) {
1111            String s = cameraFormatForPixelFormat(pixel_format);
1112            if (s == null) {
1113                throw new IllegalArgumentException(
1114                        "Invalid pixel_format=" + pixel_format);
1115            }
1116
1117            set(KEY_PREVIEW_FORMAT, s);
1118        }
1119
1120        /**
1121         * Returns the image format for preview pictures got from
1122         * {@link PreviewCallback}.
1123         *
1124         * @return the {@link android.graphics.ImageFormat} int representing
1125         *         the preview picture format.
1126         */
1127        public int getPreviewFormat() {
1128            return pixelFormatForCameraFormat(get(KEY_PREVIEW_FORMAT));
1129        }
1130
1131        /**
1132         * Gets the supported preview formats.
1133         *
1134         * @return a List of Integer objects. This method will always return a
1135         *         list with at least one element.
1136         */
1137        public List<Integer> getSupportedPreviewFormats() {
1138            String str = get(KEY_PREVIEW_FORMAT + SUPPORTED_VALUES_SUFFIX);
1139            ArrayList<Integer> formats = new ArrayList<Integer>();
1140            for (String s : split(str)) {
1141                int f = pixelFormatForCameraFormat(s);
1142                if (f == ImageFormat.UNKNOWN) continue;
1143                formats.add(f);
1144            }
1145            return formats;
1146        }
1147
1148        /**
1149         * Sets the dimensions for pictures.
1150         *
1151         * @param width  the width for pictures, in pixels
1152         * @param height the height for pictures, in pixels
1153         */
1154        public void setPictureSize(int width, int height) {
1155            String v = Integer.toString(width) + "x" + Integer.toString(height);
1156            set(KEY_PICTURE_SIZE, v);
1157        }
1158
1159        /**
1160         * Returns the dimension setting for pictures.
1161         *
1162         * @return a Size object with the height and width setting
1163         *          for pictures
1164         */
1165        public Size getPictureSize() {
1166            String pair = get(KEY_PICTURE_SIZE);
1167            return strToSize(pair);
1168        }
1169
1170        /**
1171         * Gets the supported picture sizes.
1172         *
1173         * @return a List of Size objects. This method will always return a list
1174         *         with at least one element.
1175         */
1176        public List<Size> getSupportedPictureSizes() {
1177            String str = get(KEY_PICTURE_SIZE + SUPPORTED_VALUES_SUFFIX);
1178            return splitSize(str);
1179        }
1180
1181        /**
1182         * Sets the image format for pictures.
1183         *
1184         * @param pixel_format the desired picture format
1185         *                     (<var>ImageFormat.NV21</var>,
1186         *                      <var>ImageFormat.RGB_565</var>, or
1187         *                      <var>ImageFormat.JPEG</var>)
1188         * @see android.graphics.ImageFormat
1189         */
1190        public void setPictureFormat(int pixel_format) {
1191            String s = cameraFormatForPixelFormat(pixel_format);
1192            if (s == null) {
1193                throw new IllegalArgumentException(
1194                        "Invalid pixel_format=" + pixel_format);
1195            }
1196
1197            set(KEY_PICTURE_FORMAT, s);
1198        }
1199
1200        /**
1201         * Returns the image format for pictures.
1202         *
1203         * @return the ImageFormat int representing the picture format
1204         */
1205        public int getPictureFormat() {
1206            return pixelFormatForCameraFormat(get(KEY_PICTURE_FORMAT));
1207        }
1208
1209        /**
1210         * Gets the supported picture formats.
1211         *
1212         * @return a List of Integer objects (values are ImageFormat.XXX). This
1213         *         method will always return a list with at least one element.
1214         */
1215        public List<Integer> getSupportedPictureFormats() {
1216            String str = get(KEY_PICTURE_FORMAT + SUPPORTED_VALUES_SUFFIX);
1217            ArrayList<Integer> formats = new ArrayList<Integer>();
1218            for (String s : split(str)) {
1219                int f = pixelFormatForCameraFormat(s);
1220                if (f == ImageFormat.UNKNOWN) continue;
1221                formats.add(f);
1222            }
1223            return formats;
1224        }
1225
1226        private String cameraFormatForPixelFormat(int pixel_format) {
1227            switch(pixel_format) {
1228            case ImageFormat.NV16:      return PIXEL_FORMAT_YUV422SP;
1229            case ImageFormat.NV21:      return PIXEL_FORMAT_YUV420SP;
1230            case ImageFormat.YUY2:      return PIXEL_FORMAT_YUV422I;
1231            case ImageFormat.RGB_565:   return PIXEL_FORMAT_RGB565;
1232            case ImageFormat.JPEG:      return PIXEL_FORMAT_JPEG;
1233            default:                    return null;
1234            }
1235        }
1236
1237        private int pixelFormatForCameraFormat(String format) {
1238            if (format == null)
1239                return ImageFormat.UNKNOWN;
1240
1241            if (format.equals(PIXEL_FORMAT_YUV422SP))
1242                return ImageFormat.NV16;
1243
1244            if (format.equals(PIXEL_FORMAT_YUV420SP))
1245                return ImageFormat.NV21;
1246
1247            if (format.equals(PIXEL_FORMAT_YUV422I))
1248                return ImageFormat.YUY2;
1249
1250            if (format.equals(PIXEL_FORMAT_RGB565))
1251                return ImageFormat.RGB_565;
1252
1253            if (format.equals(PIXEL_FORMAT_JPEG))
1254                return ImageFormat.JPEG;
1255
1256            return ImageFormat.UNKNOWN;
1257        }
1258
1259        /**
1260         * Sets the orientation of the device in degrees. For example, suppose
1261         * the natural position of the device is landscape. If the user takes a
1262         * picture in landscape mode in 2048x1536 resolution, the rotation
1263         * should be set to 0. If the user rotates the phone 90 degrees
1264         * clockwise, the rotation should be set to 90. Applications can use
1265         * {@link android.view.OrientationEventListener} to set this parameter.
1266         *
1267         * The camera driver may set orientation in the EXIF header without
1268         * rotating the picture. Or the driver may rotate the picture and
1269         * the EXIF thumbnail. If the Jpeg picture is rotated, the orientation
1270         * in the EXIF header will be missing or 1 (row #0 is top and column #0
1271         * is left side).
1272         *
1273         * @param rotation The orientation of the device in degrees. Rotation
1274         *                 can only be 0, 90, 180 or 270.
1275         * @throws IllegalArgumentException if rotation value is invalid.
1276         * @see android.view.OrientationEventListener
1277         */
1278        public void setRotation(int rotation) {
1279            if (rotation == 0 || rotation == 90 || rotation == 180
1280                    || rotation == 270) {
1281                set(KEY_ROTATION, Integer.toString(rotation));
1282            } else {
1283                throw new IllegalArgumentException(
1284                        "Invalid rotation=" + rotation);
1285            }
1286        }
1287
1288        /**
1289         * Sets GPS latitude coordinate. This will be stored in JPEG EXIF
1290         * header.
1291         *
1292         * @param latitude GPS latitude coordinate.
1293         */
1294        public void setGpsLatitude(double latitude) {
1295            set(KEY_GPS_LATITUDE, Double.toString(latitude));
1296        }
1297
1298        /**
1299         * Sets GPS longitude coordinate. This will be stored in JPEG EXIF
1300         * header.
1301         *
1302         * @param longitude GPS longitude coordinate.
1303         */
1304        public void setGpsLongitude(double longitude) {
1305            set(KEY_GPS_LONGITUDE, Double.toString(longitude));
1306        }
1307
1308        /**
1309         * Sets GPS altitude. This will be stored in JPEG EXIF header.
1310         *
1311         * @param altitude GPS altitude in meters.
1312         */
1313        public void setGpsAltitude(double altitude) {
1314            set(KEY_GPS_ALTITUDE, Double.toString(altitude));
1315        }
1316
1317        /**
1318         * Sets GPS timestamp. This will be stored in JPEG EXIF header.
1319         *
1320         * @param timestamp GPS timestamp (UTC in seconds since January 1,
1321         *                  1970).
1322         */
1323        public void setGpsTimestamp(long timestamp) {
1324            set(KEY_GPS_TIMESTAMP, Long.toString(timestamp));
1325        }
1326
1327        /**
1328         * Sets GPS processing method. It will store up to 100 characters
1329         * in JPEG EXIF header.
1330         *
1331         * @param processing_method The processing method to get this location.
1332         */
1333        public void setGpsProcessingMethod(String processing_method) {
1334            set(KEY_GPS_PROCESSING_METHOD, processing_method);
1335        }
1336
1337        /**
1338         * Removes GPS latitude, longitude, altitude, and timestamp from the
1339         * parameters.
1340         */
1341        public void removeGpsData() {
1342            remove(KEY_GPS_LATITUDE);
1343            remove(KEY_GPS_LONGITUDE);
1344            remove(KEY_GPS_ALTITUDE);
1345            remove(KEY_GPS_TIMESTAMP);
1346            remove(KEY_GPS_PROCESSING_METHOD);
1347        }
1348
1349        /**
1350         * Gets the current white balance setting.
1351         *
1352         * @return one of WHITE_BALANCE_XXX string constant. null if white
1353         *         balance setting is not supported.
1354         */
1355        public String getWhiteBalance() {
1356            return get(KEY_WHITE_BALANCE);
1357        }
1358
1359        /**
1360         * Sets the white balance.
1361         *
1362         * @param value WHITE_BALANCE_XXX string constant.
1363         */
1364        public void setWhiteBalance(String value) {
1365            set(KEY_WHITE_BALANCE, value);
1366        }
1367
1368        /**
1369         * Gets the supported white balance.
1370         *
1371         * @return a List of WHITE_BALANCE_XXX string constants. null if white
1372         *         balance setting is not supported.
1373         */
1374        public List<String> getSupportedWhiteBalance() {
1375            String str = get(KEY_WHITE_BALANCE + SUPPORTED_VALUES_SUFFIX);
1376            return split(str);
1377        }
1378
1379        /**
1380         * Gets the current color effect setting.
1381         *
1382         * @return one of EFFECT_XXX string constant. null if color effect
1383         *         setting is not supported.
1384         */
1385        public String getColorEffect() {
1386            return get(KEY_EFFECT);
1387        }
1388
1389        /**
1390         * Sets the current color effect setting.
1391         *
1392         * @param value EFFECT_XXX string constants.
1393         */
1394        public void setColorEffect(String value) {
1395            set(KEY_EFFECT, value);
1396        }
1397
1398        /**
1399         * Gets the supported color effects.
1400         *
1401         * @return a List of EFFECT_XXX string constants. null if color effect
1402         *         setting is not supported.
1403         */
1404        public List<String> getSupportedColorEffects() {
1405            String str = get(KEY_EFFECT + SUPPORTED_VALUES_SUFFIX);
1406            return split(str);
1407        }
1408
1409
1410        /**
1411         * Gets the current antibanding setting.
1412         *
1413         * @return one of ANTIBANDING_XXX string constant. null if antibanding
1414         *         setting is not supported.
1415         */
1416        public String getAntibanding() {
1417            return get(KEY_ANTIBANDING);
1418        }
1419
1420        /**
1421         * Sets the antibanding.
1422         *
1423         * @param antibanding ANTIBANDING_XXX string constant.
1424         */
1425        public void setAntibanding(String antibanding) {
1426            set(KEY_ANTIBANDING, antibanding);
1427        }
1428
1429        /**
1430         * Gets the supported antibanding values.
1431         *
1432         * @return a List of ANTIBANDING_XXX string constants. null if
1433         *         antibanding setting is not supported.
1434         */
1435        public List<String> getSupportedAntibanding() {
1436            String str = get(KEY_ANTIBANDING + SUPPORTED_VALUES_SUFFIX);
1437            return split(str);
1438        }
1439
1440        /**
1441         * Gets the current scene mode setting.
1442         *
1443         * @return one of SCENE_MODE_XXX string constant. null if scene mode
1444         *         setting is not supported.
1445         */
1446        public String getSceneMode() {
1447            return get(KEY_SCENE_MODE);
1448        }
1449
1450        /**
1451         * Sets the scene mode. Other parameters may be changed after changing
1452         * scene mode. For example, flash and supported flash mode may be
1453         * changed to "off" in night scene mode. After setting scene mode,
1454         * applications should call getParameters to know if some parameters are
1455         * changed.
1456         *
1457         * @param value SCENE_MODE_XXX string constants.
1458         */
1459        public void setSceneMode(String value) {
1460            set(KEY_SCENE_MODE, value);
1461        }
1462
1463        /**
1464         * Gets the supported scene modes.
1465         *
1466         * @return a List of SCENE_MODE_XXX string constant. null if scene mode
1467         *         setting is not supported.
1468         */
1469        public List<String> getSupportedSceneModes() {
1470            String str = get(KEY_SCENE_MODE + SUPPORTED_VALUES_SUFFIX);
1471            return split(str);
1472        }
1473
1474        /**
1475         * Gets the current flash mode setting.
1476         *
1477         * @return one of FLASH_MODE_XXX string constant. null if flash mode
1478         *         setting is not supported.
1479         */
1480        public String getFlashMode() {
1481            return get(KEY_FLASH_MODE);
1482        }
1483
1484        /**
1485         * Sets the flash mode.
1486         *
1487         * @param value FLASH_MODE_XXX string constants.
1488         */
1489        public void setFlashMode(String value) {
1490            set(KEY_FLASH_MODE, value);
1491        }
1492
1493        /**
1494         * Gets the supported flash modes.
1495         *
1496         * @return a List of FLASH_MODE_XXX string constants. null if flash mode
1497         *         setting is not supported.
1498         */
1499        public List<String> getSupportedFlashModes() {
1500            String str = get(KEY_FLASH_MODE + SUPPORTED_VALUES_SUFFIX);
1501            return split(str);
1502        }
1503
1504        /**
1505         * Gets the current focus mode setting.
1506         *
1507         * @return one of FOCUS_MODE_XXX string constant. If the camera does not
1508         *         support auto-focus, this should return {@link
1509         *         #FOCUS_MODE_FIXED}. If the focus mode is not FOCUS_MODE_FIXED
1510         *         or {@link #FOCUS_MODE_INFINITY}, applications should call
1511         *         {@link #autoFocus(AutoFocusCallback)} to start the focus.
1512         */
1513        public String getFocusMode() {
1514            return get(KEY_FOCUS_MODE);
1515        }
1516
1517        /**
1518         * Sets the focus mode.
1519         *
1520         * @param value FOCUS_MODE_XXX string constants.
1521         */
1522        public void setFocusMode(String value) {
1523            set(KEY_FOCUS_MODE, value);
1524        }
1525
1526        /**
1527         * Gets the supported focus modes.
1528         *
1529         * @return a List of FOCUS_MODE_XXX string constants. This method will
1530         *         always return a list with at least one element.
1531         */
1532        public List<String> getSupportedFocusModes() {
1533            String str = get(KEY_FOCUS_MODE + SUPPORTED_VALUES_SUFFIX);
1534            return split(str);
1535        }
1536
1537        /**
1538         * Gets the focal length (in millimeter) of the camera.
1539         *
1540         * @return the focal length. This method will always return a valid
1541         *         value.
1542         */
1543        public float getFocalLength() {
1544            return Float.parseFloat(get(KEY_FOCAL_LENGTH));
1545        }
1546
1547        /**
1548         * Gets the horizontal angle of view in degrees.
1549         *
1550         * @return horizontal angle of view. This method will always return a
1551         *         valid value.
1552         */
1553        public float getHorizontalViewAngle() {
1554            return Float.parseFloat(get(KEY_HORIZONTAL_VIEW_ANGLE));
1555        }
1556
1557        /**
1558         * Gets the vertical angle of view in degrees.
1559         *
1560         * @return vertical angle of view. This method will always return a
1561         *         valid value.
1562         */
1563        public float getVerticalViewAngle() {
1564            return Float.parseFloat(get(KEY_VERTICAL_VIEW_ANGLE));
1565        }
1566
1567        /**
1568         * Gets the current exposure compensation index.
1569         *
1570         * @return current exposure compensation index. The range is {@link
1571         *         #getMinExposureCompensation} to {@link
1572         *         #getMaxExposureCompensation}. 0 means exposure is not
1573         *         adjusted.
1574         */
1575        public int getExposureCompensation() {
1576            return getInt(KEY_EXPOSURE_COMPENSATION, 0);
1577        }
1578
1579        /**
1580         * Sets the exposure compensation index.
1581         *
1582         * @param value exposure compensation index. The valid value range is
1583         *        from {@link #getMinExposureCompensation} (inclusive) to {@link
1584         *        #getMaxExposureCompensation} (inclusive). 0 means exposure is
1585         *        not adjusted. Application should call
1586         *        getMinExposureCompensation and getMaxExposureCompensation to
1587         *        know if exposure compensation is supported.
1588         */
1589        public void setExposureCompensation(int value) {
1590            set(KEY_EXPOSURE_COMPENSATION, value);
1591        }
1592
1593        /**
1594         * Gets the maximum exposure compensation index.
1595         *
1596         * @return maximum exposure compensation index (>=0). If both this
1597         *         method and {@link #getMinExposureCompensation} return 0,
1598         *         exposure compensation is not supported.
1599         */
1600        public int getMaxExposureCompensation() {
1601            return getInt(KEY_MAX_EXPOSURE_COMPENSATION, 0);
1602        }
1603
1604        /**
1605         * Gets the minimum exposure compensation index.
1606         *
1607         * @return minimum exposure compensation index (<=0). If both this
1608         *         method and {@link #getMaxExposureCompensation} return 0,
1609         *         exposure compensation is not supported.
1610         */
1611        public int getMinExposureCompensation() {
1612            return getInt(KEY_MIN_EXPOSURE_COMPENSATION, 0);
1613        }
1614
1615        /**
1616         * Gets the exposure compensation step.
1617         *
1618         * @return exposure compensation step. Applications can get EV by
1619         *         multiplying the exposure compensation index and step. Ex: if
1620         *         exposure compensation index is -6 and step is 0.333333333, EV
1621         *         is -2.
1622         */
1623        public float getExposureCompensationStep() {
1624            return getFloat(KEY_EXPOSURE_COMPENSATION_STEP, 0);
1625        }
1626
1627        /**
1628         * Gets current zoom value. This also works when smooth zoom is in
1629         * progress. Applications should check {@link #isZoomSupported} before
1630         * using this method.
1631         *
1632         * @return the current zoom value. The range is 0 to {@link
1633         *         #getMaxZoom}. 0 means the camera is not zoomed.
1634         */
1635        public int getZoom() {
1636            return getInt(KEY_ZOOM, 0);
1637        }
1638
1639        /**
1640         * Sets current zoom value. If the camera is zoomed (value > 0), the
1641         * actual picture size may be smaller than picture size setting.
1642         * Applications can check the actual picture size after picture is
1643         * returned from {@link PictureCallback}. The preview size remains the
1644         * same in zoom. Applications should check {@link #isZoomSupported}
1645         * before using this method.
1646         *
1647         * @param value zoom value. The valid range is 0 to {@link #getMaxZoom}.
1648         */
1649        public void setZoom(int value) {
1650            set(KEY_ZOOM, value);
1651        }
1652
1653        /**
1654         * Returns true if zoom is supported. Applications should call this
1655         * before using other zoom methods.
1656         *
1657         * @return true if zoom is supported.
1658         */
1659        public boolean isZoomSupported() {
1660            String str = get(KEY_ZOOM_SUPPORTED);
1661            return TRUE.equals(str);
1662        }
1663
1664        /**
1665         * Gets the maximum zoom value allowed for snapshot. This is the maximum
1666         * value that applications can set to {@link #setZoom(int)}.
1667         * Applications should call {@link #isZoomSupported} before using this
1668         * method. This value may change in different preview size. Applications
1669         * should call this again after setting preview size.
1670         *
1671         * @return the maximum zoom value supported by the camera.
1672         */
1673        public int getMaxZoom() {
1674            return getInt(KEY_MAX_ZOOM, 0);
1675        }
1676
1677        /**
1678         * Gets the zoom ratios of all zoom values. Applications should check
1679         * {@link #isZoomSupported} before using this method.
1680         *
1681         * @return the zoom ratios in 1/100 increments. Ex: a zoom of 3.2x is
1682         *         returned as 320. The number of elements is {@link
1683         *         #getMaxZoom} + 1. The list is sorted from small to large. The
1684         *         first element is always 100. The last element is the zoom
1685         *         ratio of the maximum zoom value.
1686         */
1687        public List<Integer> getZoomRatios() {
1688            return splitInt(get(KEY_ZOOM_RATIOS));
1689        }
1690
1691        /**
1692         * Returns true if smooth zoom is supported. Applications should call
1693         * this before using other smooth zoom methods.
1694         *
1695         * @return true if smooth zoom is supported.
1696         */
1697        public boolean isSmoothZoomSupported() {
1698            String str = get(KEY_SMOOTH_ZOOM_SUPPORTED);
1699            return TRUE.equals(str);
1700        }
1701
1702        // Splits a comma delimited string to an ArrayList of String.
1703        // Return null if the passing string is null or the size is 0.
1704        private ArrayList<String> split(String str) {
1705            if (str == null) return null;
1706
1707            // Use StringTokenizer because it is faster than split.
1708            StringTokenizer tokenizer = new StringTokenizer(str, ",");
1709            ArrayList<String> substrings = new ArrayList<String>();
1710            while (tokenizer.hasMoreElements()) {
1711                substrings.add(tokenizer.nextToken());
1712            }
1713            return substrings;
1714        }
1715
1716        // Splits a comma delimited string to an ArrayList of Integer.
1717        // Return null if the passing string is null or the size is 0.
1718        private ArrayList<Integer> splitInt(String str) {
1719            if (str == null) return null;
1720
1721            StringTokenizer tokenizer = new StringTokenizer(str, ",");
1722            ArrayList<Integer> substrings = new ArrayList<Integer>();
1723            while (tokenizer.hasMoreElements()) {
1724                String token = tokenizer.nextToken();
1725                substrings.add(Integer.parseInt(token));
1726            }
1727            if (substrings.size() == 0) return null;
1728            return substrings;
1729        }
1730
1731        // Returns the value of a float parameter.
1732        private float getFloat(String key, float defaultValue) {
1733            try {
1734                return Float.parseFloat(mMap.get(key));
1735            } catch (NumberFormatException ex) {
1736                return defaultValue;
1737            }
1738        }
1739
1740        // Returns the value of a integer parameter.
1741        private int getInt(String key, int defaultValue) {
1742            try {
1743                return Integer.parseInt(mMap.get(key));
1744            } catch (NumberFormatException ex) {
1745                return defaultValue;
1746            }
1747        }
1748
1749        // Splits a comma delimited string to an ArrayList of Size.
1750        // Return null if the passing string is null or the size is 0.
1751        private ArrayList<Size> splitSize(String str) {
1752            if (str == null) return null;
1753
1754            StringTokenizer tokenizer = new StringTokenizer(str, ",");
1755            ArrayList<Size> sizeList = new ArrayList<Size>();
1756            while (tokenizer.hasMoreElements()) {
1757                Size size = strToSize(tokenizer.nextToken());
1758                if (size != null) sizeList.add(size);
1759            }
1760            if (sizeList.size() == 0) return null;
1761            return sizeList;
1762        }
1763
1764        // Parses a string (ex: "480x320") to Size object.
1765        // Return null if the passing string is null.
1766        private Size strToSize(String str) {
1767            if (str == null) return null;
1768
1769            int pos = str.indexOf('x');
1770            if (pos != -1) {
1771                String width = str.substring(0, pos);
1772                String height = str.substring(pos + 1);
1773                return new Size(Integer.parseInt(width),
1774                                Integer.parseInt(height));
1775            }
1776            Log.e(TAG, "Invalid size parameter string=" + str);
1777            return null;
1778        }
1779    };
1780}
1781