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