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