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