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