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