Camera.java revision 1620d118a49dc6df7b0e83d7343f8a8bb6e23b12
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_PREVIEW_FPS_RANGE = "preview-fps-range";
964        private static final String KEY_PICTURE_SIZE = "picture-size";
965        private static final String KEY_PICTURE_FORMAT = "picture-format";
966        private static final String KEY_JPEG_THUMBNAIL_SIZE = "jpeg-thumbnail-size";
967        private static final String KEY_JPEG_THUMBNAIL_WIDTH = "jpeg-thumbnail-width";
968        private static final String KEY_JPEG_THUMBNAIL_HEIGHT = "jpeg-thumbnail-height";
969        private static final String KEY_JPEG_THUMBNAIL_QUALITY = "jpeg-thumbnail-quality";
970        private static final String KEY_JPEG_QUALITY = "jpeg-quality";
971        private static final String KEY_ROTATION = "rotation";
972        private static final String KEY_GPS_LATITUDE = "gps-latitude";
973        private static final String KEY_GPS_LONGITUDE = "gps-longitude";
974        private static final String KEY_GPS_ALTITUDE = "gps-altitude";
975        private static final String KEY_GPS_TIMESTAMP = "gps-timestamp";
976        private static final String KEY_GPS_PROCESSING_METHOD = "gps-processing-method";
977        private static final String KEY_WHITE_BALANCE = "whitebalance";
978        private static final String KEY_EFFECT = "effect";
979        private static final String KEY_ANTIBANDING = "antibanding";
980        private static final String KEY_SCENE_MODE = "scene-mode";
981        private static final String KEY_FLASH_MODE = "flash-mode";
982        private static final String KEY_FOCUS_MODE = "focus-mode";
983        private static final String KEY_FOCAL_LENGTH = "focal-length";
984        private static final String KEY_HORIZONTAL_VIEW_ANGLE = "horizontal-view-angle";
985        private static final String KEY_VERTICAL_VIEW_ANGLE = "vertical-view-angle";
986        private static final String KEY_EXPOSURE_COMPENSATION = "exposure-compensation";
987        private static final String KEY_MAX_EXPOSURE_COMPENSATION = "max-exposure-compensation";
988        private static final String KEY_MIN_EXPOSURE_COMPENSATION = "min-exposure-compensation";
989        private static final String KEY_EXPOSURE_COMPENSATION_STEP = "exposure-compensation-step";
990        private static final String KEY_ZOOM = "zoom";
991        private static final String KEY_MAX_ZOOM = "max-zoom";
992        private static final String KEY_ZOOM_RATIOS = "zoom-ratios";
993        private static final String KEY_ZOOM_SUPPORTED = "zoom-supported";
994        private static final String KEY_SMOOTH_ZOOM_SUPPORTED = "smooth-zoom-supported";
995        private static final String KEY_FOCUS_DISTANCES = "focus-distances";
996        private static final String KEY_METERING_MODE = "metering-mode";
997
998        // Parameter key suffix for supported values.
999        private static final String SUPPORTED_VALUES_SUFFIX = "-values";
1000
1001        private static final String TRUE = "true";
1002
1003        // Values for white balance settings.
1004        public static final String WHITE_BALANCE_AUTO = "auto";
1005        public static final String WHITE_BALANCE_INCANDESCENT = "incandescent";
1006        public static final String WHITE_BALANCE_FLUORESCENT = "fluorescent";
1007        public static final String WHITE_BALANCE_WARM_FLUORESCENT = "warm-fluorescent";
1008        public static final String WHITE_BALANCE_DAYLIGHT = "daylight";
1009        public static final String WHITE_BALANCE_CLOUDY_DAYLIGHT = "cloudy-daylight";
1010        public static final String WHITE_BALANCE_TWILIGHT = "twilight";
1011        public static final String WHITE_BALANCE_SHADE = "shade";
1012
1013        // Values for color effect settings.
1014        public static final String EFFECT_NONE = "none";
1015        public static final String EFFECT_MONO = "mono";
1016        public static final String EFFECT_NEGATIVE = "negative";
1017        public static final String EFFECT_SOLARIZE = "solarize";
1018        public static final String EFFECT_SEPIA = "sepia";
1019        public static final String EFFECT_POSTERIZE = "posterize";
1020        public static final String EFFECT_WHITEBOARD = "whiteboard";
1021        public static final String EFFECT_BLACKBOARD = "blackboard";
1022        public static final String EFFECT_AQUA = "aqua";
1023
1024        // Values for antibanding settings.
1025        public static final String ANTIBANDING_AUTO = "auto";
1026        public static final String ANTIBANDING_50HZ = "50hz";
1027        public static final String ANTIBANDING_60HZ = "60hz";
1028        public static final String ANTIBANDING_OFF = "off";
1029
1030        // Values for flash mode settings.
1031        /**
1032         * Flash will not be fired.
1033         */
1034        public static final String FLASH_MODE_OFF = "off";
1035
1036        /**
1037         * Flash will be fired automatically when required. The flash may be fired
1038         * during preview, auto-focus, or snapshot depending on the driver.
1039         */
1040        public static final String FLASH_MODE_AUTO = "auto";
1041
1042        /**
1043         * Flash will always be fired during snapshot. The flash may also be
1044         * fired during preview or auto-focus depending on the driver.
1045         */
1046        public static final String FLASH_MODE_ON = "on";
1047
1048        /**
1049         * Flash will be fired in red-eye reduction mode.
1050         */
1051        public static final String FLASH_MODE_RED_EYE = "red-eye";
1052
1053        /**
1054         * Constant emission of light during preview, auto-focus and snapshot.
1055         * This can also be used for video recording.
1056         */
1057        public static final String FLASH_MODE_TORCH = "torch";
1058
1059        /**
1060         * Scene mode is off.
1061         */
1062        public static final String SCENE_MODE_AUTO = "auto";
1063
1064        /**
1065         * Take photos of fast moving objects. Same as {@link
1066         * #SCENE_MODE_SPORTS}.
1067         */
1068        public static final String SCENE_MODE_ACTION = "action";
1069
1070        /**
1071         * Take people pictures.
1072         */
1073        public static final String SCENE_MODE_PORTRAIT = "portrait";
1074
1075        /**
1076         * Take pictures on distant objects.
1077         */
1078        public static final String SCENE_MODE_LANDSCAPE = "landscape";
1079
1080        /**
1081         * Take photos at night.
1082         */
1083        public static final String SCENE_MODE_NIGHT = "night";
1084
1085        /**
1086         * Take people pictures at night.
1087         */
1088        public static final String SCENE_MODE_NIGHT_PORTRAIT = "night-portrait";
1089
1090        /**
1091         * Take photos in a theater. Flash light is off.
1092         */
1093        public static final String SCENE_MODE_THEATRE = "theatre";
1094
1095        /**
1096         * Take pictures on the beach.
1097         */
1098        public static final String SCENE_MODE_BEACH = "beach";
1099
1100        /**
1101         * Take pictures on the snow.
1102         */
1103        public static final String SCENE_MODE_SNOW = "snow";
1104
1105        /**
1106         * Take sunset photos.
1107         */
1108        public static final String SCENE_MODE_SUNSET = "sunset";
1109
1110        /**
1111         * Avoid blurry pictures (for example, due to hand shake).
1112         */
1113        public static final String SCENE_MODE_STEADYPHOTO = "steadyphoto";
1114
1115        /**
1116         * For shooting firework displays.
1117         */
1118        public static final String SCENE_MODE_FIREWORKS = "fireworks";
1119
1120        /**
1121         * Take photos of fast moving objects. Same as {@link
1122         * #SCENE_MODE_ACTION}.
1123         */
1124        public static final String SCENE_MODE_SPORTS = "sports";
1125
1126        /**
1127         * Take indoor low-light shot.
1128         */
1129        public static final String SCENE_MODE_PARTY = "party";
1130
1131        /**
1132         * Capture the naturally warm color of scenes lit by candles.
1133         */
1134        public static final String SCENE_MODE_CANDLELIGHT = "candlelight";
1135
1136        /**
1137         * Applications are looking for a barcode. Camera driver will be
1138         * optimized for barcode reading.
1139         */
1140        public static final String SCENE_MODE_BARCODE = "barcode";
1141
1142        /**
1143         * Auto-focus mode. Applications should call {@link
1144         * #autoFocus(AutoFocusCallback)} to start the focus in this mode.
1145         */
1146        public static final String FOCUS_MODE_AUTO = "auto";
1147
1148        /**
1149         * Focus is set at infinity. Applications should not call
1150         * {@link #autoFocus(AutoFocusCallback)} in this mode.
1151         */
1152        public static final String FOCUS_MODE_INFINITY = "infinity";
1153
1154        /**
1155         * Macro (close-up) focus mode. Applications should call
1156         * {@link #autoFocus(AutoFocusCallback)} to start the focus in this
1157         * mode.
1158         */
1159        public static final String FOCUS_MODE_MACRO = "macro";
1160
1161        /**
1162         * Focus is fixed. The camera is always in this mode if the focus is not
1163         * adjustable. If the camera has auto-focus, this mode can fix the
1164         * focus, which is usually at hyperfocal distance. Applications should
1165         * not call {@link #autoFocus(AutoFocusCallback)} in this mode.
1166         */
1167        public static final String FOCUS_MODE_FIXED = "fixed";
1168
1169        /**
1170         * Extended depth of field (EDOF). Focusing is done digitally and
1171         * continuously. Applications should not call {@link
1172         * #autoFocus(AutoFocusCallback)} in this mode.
1173         */
1174        public static final String FOCUS_MODE_EDOF = "edof";
1175
1176        /**
1177         * Continuous auto focus mode. The camera continuously tries to focus.
1178         * This is ideal for shooting video or shooting photo of moving object.
1179         * Auto focus starts when the parameter is set. Applications should not
1180         * call {@link #autoFocus(AutoFocusCallback)} in this mode. To stop
1181         * continuous focus, applications should change the focus mode to other
1182         * modes.
1183         */
1184        public static final String FOCUS_MODE_CONTINUOUS = "continuous";
1185
1186        // Indices for focus distance array.
1187        /**
1188         * The array index of near focus distance for use with
1189         * {@link #getFocusDistances(float[])}.
1190         */
1191        public static final int FOCUS_DISTANCE_NEAR_INDEX = 0;
1192
1193        /**
1194         * The array index of optimal focus distance for use with
1195         * {@link #getFocusDistances(float[])}.
1196         */
1197        public static final int FOCUS_DISTANCE_OPTIMAL_INDEX = 1;
1198
1199        /**
1200         * The array index of far focus distance for use with
1201         * {@link #getFocusDistances(float[])}.
1202         */
1203        public static final int FOCUS_DISTANCE_FAR_INDEX = 2;
1204
1205        /**
1206         * The camera determines the exposure by giving more weight to the
1207         * central part of the scene.
1208         */
1209        public static final String METERING_MODE_CENTER_WEIGHTED = "center-weighted";
1210
1211        /**
1212         * The camera determines the exposure by averaging the entire scene,
1213         * giving no weighting to any particular area.
1214         */
1215        public static final String METERING_MODE_FRAME_AVERAGE = "frame-average";
1216
1217        /**
1218         * The camera determines the exposure by a very small area of the scene,
1219         * typically the center.
1220         */
1221        public static final String METERING_MODE_SPOT = "spot";
1222
1223        /**
1224         * The array index of minimum preview fps for use with {@link
1225         * #getPreviewFpsRange(int[])} or {@link
1226         * #getSupportedPreviewFpsRange()}.
1227         */
1228        public static final int PREVIEW_FPS_MIN_INDEX = 0;
1229
1230        /**
1231         * The array index of maximum preview fps for use with {@link
1232         * #getPreviewFpsRange(int[])} or {@link
1233         * #getSupportedPreviewFpsRange()}.
1234         */
1235        public static final int PREVIEW_FPS_MAX_INDEX = 1;
1236
1237        // Formats for setPreviewFormat and setPictureFormat.
1238        private static final String PIXEL_FORMAT_YUV422SP = "yuv422sp";
1239        private static final String PIXEL_FORMAT_YUV420SP = "yuv420sp";
1240        private static final String PIXEL_FORMAT_YUV422I = "yuv422i-yuyv";
1241        private static final String PIXEL_FORMAT_RGB565 = "rgb565";
1242        private static final String PIXEL_FORMAT_JPEG = "jpeg";
1243
1244        private HashMap<String, String> mMap;
1245
1246        private Parameters() {
1247            mMap = new HashMap<String, String>();
1248        }
1249
1250        /**
1251         * Writes the current Parameters to the log.
1252         * @hide
1253         * @deprecated
1254         */
1255        public void dump() {
1256            Log.e(TAG, "dump: size=" + mMap.size());
1257            for (String k : mMap.keySet()) {
1258                Log.e(TAG, "dump: " + k + "=" + mMap.get(k));
1259            }
1260        }
1261
1262        /**
1263         * Creates a single string with all the parameters set in
1264         * this Parameters object.
1265         * <p>The {@link #unflatten(String)} method does the reverse.</p>
1266         *
1267         * @return a String with all values from this Parameters object, in
1268         *         semi-colon delimited key-value pairs
1269         */
1270        public String flatten() {
1271            StringBuilder flattened = new StringBuilder();
1272            for (String k : mMap.keySet()) {
1273                flattened.append(k);
1274                flattened.append("=");
1275                flattened.append(mMap.get(k));
1276                flattened.append(";");
1277            }
1278            // chop off the extra semicolon at the end
1279            flattened.deleteCharAt(flattened.length()-1);
1280            return flattened.toString();
1281        }
1282
1283        /**
1284         * Takes a flattened string of parameters and adds each one to
1285         * this Parameters object.
1286         * <p>The {@link #flatten()} method does the reverse.</p>
1287         *
1288         * @param flattened a String of parameters (key-value paired) that
1289         *                  are semi-colon delimited
1290         */
1291        public void unflatten(String flattened) {
1292            mMap.clear();
1293
1294            StringTokenizer tokenizer = new StringTokenizer(flattened, ";");
1295            while (tokenizer.hasMoreElements()) {
1296                String kv = tokenizer.nextToken();
1297                int pos = kv.indexOf('=');
1298                if (pos == -1) {
1299                    continue;
1300                }
1301                String k = kv.substring(0, pos);
1302                String v = kv.substring(pos + 1);
1303                mMap.put(k, v);
1304            }
1305        }
1306
1307        public void remove(String key) {
1308            mMap.remove(key);
1309        }
1310
1311        /**
1312         * Sets a String parameter.
1313         *
1314         * @param key   the key name for the parameter
1315         * @param value the String value of the parameter
1316         */
1317        public void set(String key, String value) {
1318            if (key.indexOf('=') != -1 || key.indexOf(';') != -1) {
1319                Log.e(TAG, "Key \"" + key + "\" contains invalid character (= or ;)");
1320                return;
1321            }
1322            if (value.indexOf('=') != -1 || value.indexOf(';') != -1) {
1323                Log.e(TAG, "Value \"" + value + "\" contains invalid character (= or ;)");
1324                return;
1325            }
1326
1327            mMap.put(key, value);
1328        }
1329
1330        /**
1331         * Sets an integer parameter.
1332         *
1333         * @param key   the key name for the parameter
1334         * @param value the int value of the parameter
1335         */
1336        public void set(String key, int value) {
1337            mMap.put(key, Integer.toString(value));
1338        }
1339
1340        /**
1341         * Returns the value of a String parameter.
1342         *
1343         * @param key the key name for the parameter
1344         * @return the String value of the parameter
1345         */
1346        public String get(String key) {
1347            return mMap.get(key);
1348        }
1349
1350        /**
1351         * Returns the value of an integer parameter.
1352         *
1353         * @param key the key name for the parameter
1354         * @return the int value of the parameter
1355         */
1356        public int getInt(String key) {
1357            return Integer.parseInt(mMap.get(key));
1358        }
1359
1360        /**
1361         * Sets the dimensions for preview pictures.
1362         *
1363         * @param width  the width of the pictures, in pixels
1364         * @param height the height of the pictures, in pixels
1365         */
1366        public void setPreviewSize(int width, int height) {
1367            String v = Integer.toString(width) + "x" + Integer.toString(height);
1368            set(KEY_PREVIEW_SIZE, v);
1369        }
1370
1371        /**
1372         * Returns the dimensions setting for preview pictures.
1373         *
1374         * @return a Size object with the height and width setting
1375         *          for the preview picture
1376         */
1377        public Size getPreviewSize() {
1378            String pair = get(KEY_PREVIEW_SIZE);
1379            return strToSize(pair);
1380        }
1381
1382        /**
1383         * Gets the supported preview sizes.
1384         *
1385         * @return a list of Size object. This method will always return a list
1386         *         with at least one element.
1387         */
1388        public List<Size> getSupportedPreviewSizes() {
1389            String str = get(KEY_PREVIEW_SIZE + SUPPORTED_VALUES_SUFFIX);
1390            return splitSize(str);
1391        }
1392
1393        /**
1394         * Sets the dimensions for EXIF thumbnail in Jpeg picture. If
1395         * applications set both width and height to 0, EXIF will not contain
1396         * thumbnail.
1397         *
1398         * @param width  the width of the thumbnail, in pixels
1399         * @param height the height of the thumbnail, in pixels
1400         */
1401        public void setJpegThumbnailSize(int width, int height) {
1402            set(KEY_JPEG_THUMBNAIL_WIDTH, width);
1403            set(KEY_JPEG_THUMBNAIL_HEIGHT, height);
1404        }
1405
1406        /**
1407         * Returns the dimensions for EXIF thumbnail in Jpeg picture.
1408         *
1409         * @return a Size object with the height and width setting for the EXIF
1410         *         thumbnails
1411         */
1412        public Size getJpegThumbnailSize() {
1413            return new Size(getInt(KEY_JPEG_THUMBNAIL_WIDTH),
1414                            getInt(KEY_JPEG_THUMBNAIL_HEIGHT));
1415        }
1416
1417        /**
1418         * Gets the supported jpeg thumbnail sizes.
1419         *
1420         * @return a list of Size object. This method will always return a list
1421         *         with at least two elements. Size 0,0 (no thumbnail) is always
1422         *         supported.
1423         */
1424        public List<Size> getSupportedJpegThumbnailSizes() {
1425            String str = get(KEY_JPEG_THUMBNAIL_SIZE + SUPPORTED_VALUES_SUFFIX);
1426            return splitSize(str);
1427        }
1428
1429        /**
1430         * Sets the quality of the EXIF thumbnail in Jpeg picture.
1431         *
1432         * @param quality the JPEG quality of the EXIF thumbnail. The range is 1
1433         *                to 100, with 100 being the best.
1434         */
1435        public void setJpegThumbnailQuality(int quality) {
1436            set(KEY_JPEG_THUMBNAIL_QUALITY, quality);
1437        }
1438
1439        /**
1440         * Returns the quality setting for the EXIF thumbnail in Jpeg picture.
1441         *
1442         * @return the JPEG quality setting of the EXIF thumbnail.
1443         */
1444        public int getJpegThumbnailQuality() {
1445            return getInt(KEY_JPEG_THUMBNAIL_QUALITY);
1446        }
1447
1448        /**
1449         * Sets Jpeg quality of captured picture.
1450         *
1451         * @param quality the JPEG quality of captured picture. The range is 1
1452         *                to 100, with 100 being the best.
1453         */
1454        public void setJpegQuality(int quality) {
1455            set(KEY_JPEG_QUALITY, quality);
1456        }
1457
1458        /**
1459         * Returns the quality setting for the JPEG picture.
1460         *
1461         * @return the JPEG picture quality setting.
1462         */
1463        public int getJpegQuality() {
1464            return getInt(KEY_JPEG_QUALITY);
1465        }
1466
1467        /**
1468         * Sets the rate at which preview frames are received. This is the
1469         * target frame rate. The actual frame rate depends on the driver.
1470         *
1471         * @param fps the frame rate (frames per second)
1472         * @deprecated replaced by {@link #setPreviewFpsRange(int,int)}
1473         */
1474        @Deprecated
1475        public void setPreviewFrameRate(int fps) {
1476            set(KEY_PREVIEW_FRAME_RATE, fps);
1477        }
1478
1479        /**
1480         * Returns the setting for the rate at which preview frames are
1481         * received. This is the target frame rate. The actual frame rate
1482         * depends on the driver.
1483         *
1484         * @return the frame rate setting (frames per second)
1485         * @deprecated replaced by {@link #getPreviewFpsRange(int[])}
1486         */
1487        @Deprecated
1488        public int getPreviewFrameRate() {
1489            return getInt(KEY_PREVIEW_FRAME_RATE);
1490        }
1491
1492        /**
1493         * Gets the supported preview frame rates.
1494         *
1495         * @return a list of supported preview frame rates. null if preview
1496         *         frame rate setting is not supported.
1497         * @deprecated replaced by {@link #getSupportedPreviewFpsRange()}
1498         */
1499        @Deprecated
1500        public List<Integer> getSupportedPreviewFrameRates() {
1501            String str = get(KEY_PREVIEW_FRAME_RATE + SUPPORTED_VALUES_SUFFIX);
1502            return splitInt(str);
1503        }
1504
1505        /**
1506         * Sets the maximum and maximum preview fps. This controls the rate of
1507         * preview frames received in {@link PreviewCallback}. The minimum and
1508         * maximum preview fps must be one of the elements from {@link
1509         * #getSupportedPreviewFpsRange}.
1510         *
1511         * @param min the minimum preview fps (scaled by 1000).
1512         * @param max the maximum preview fps (scaled by 1000).
1513         * @throws RuntimeException if fps range is invalid.
1514         * @see #setPreviewCallbackWithBuffer(Camera.PreviewCallback)
1515         * @see #getSupportedPreviewFpsRange()
1516         */
1517        public void setPreviewFpsRange(int min, int max) {
1518            set(KEY_PREVIEW_FPS_RANGE, "" + min + "," + max);
1519        }
1520
1521        /**
1522         * Returns the current minimum and maximum preview fps. The values are
1523         * one of the elements returned by {@link #getSupportedPreviewFpsRange}.
1524         *
1525         * @return range the minimum and maximum preview fps (scaled by 1000).
1526         * @see #PREVIEW_FPS_MIN_INDEX
1527         * @see #PREVIEW_FPS_MAX_INDEX
1528         * @see #getSupportedPreviewFpsRange()
1529         */
1530        public void getPreviewFpsRange(int[] range) {
1531            if (range == null || range.length != 2) {
1532                throw new IllegalArgumentException(
1533                        "range must be an array with two elements.");
1534            }
1535            splitInt(get(KEY_PREVIEW_FPS_RANGE), range);
1536        }
1537
1538        /**
1539         * Gets the supported preview fps (frame-per-second) ranges. Each range
1540         * contains a minimum fps and maximum fps. If minimum fps equals to
1541         * maximum fps, the camera outputs frames in fixed frame rate. If not,
1542         * the camera outputs frames in auto frame rate. The actual frame rate
1543         * fluctuates between the minimum and the maximum. The values are
1544         * multiplied by 1000 and represented in integers. For example, if frame
1545         * rate is 26.623 frames per second, the value is 26623.
1546         *
1547         * @return a list of supported preview fps ranges. This method returns a
1548         *         list with at least one element. Every element is an int array
1549         *         of two values - minimum fps and maximum fps. The list is
1550         *         sorted from small to large (first by maximum fps and then
1551         *         minimum fps).
1552         * @see #PREVIEW_FPS_MIN_INDEX
1553         * @see #PREVIEW_FPS_MAX_INDEX
1554         */
1555        public List<int[]> getSupportedPreviewFpsRange() {
1556            String str = get(KEY_PREVIEW_FPS_RANGE + SUPPORTED_VALUES_SUFFIX);
1557            return splitRange(str);
1558        }
1559
1560        /**
1561         * Sets the image format for preview pictures.
1562         * <p>If this is never called, the default format will be
1563         * {@link android.graphics.ImageFormat#NV21}, which
1564         * uses the NV21 encoding format.</p>
1565         *
1566         * @param pixel_format the desired preview picture format, defined
1567         *   by one of the {@link android.graphics.ImageFormat} constants.
1568         *   (E.g., <var>ImageFormat.NV21</var> (default),
1569         *                      <var>ImageFormat.RGB_565</var>, or
1570         *                      <var>ImageFormat.JPEG</var>)
1571         * @see android.graphics.ImageFormat
1572         */
1573        public void setPreviewFormat(int pixel_format) {
1574            String s = cameraFormatForPixelFormat(pixel_format);
1575            if (s == null) {
1576                throw new IllegalArgumentException(
1577                        "Invalid pixel_format=" + pixel_format);
1578            }
1579
1580            set(KEY_PREVIEW_FORMAT, s);
1581        }
1582
1583        /**
1584         * Returns the image format for preview frames got from
1585         * {@link PreviewCallback}.
1586         *
1587         * @return the preview format.
1588         * @see android.graphics.ImageFormat
1589         */
1590        public int getPreviewFormat() {
1591            return pixelFormatForCameraFormat(get(KEY_PREVIEW_FORMAT));
1592        }
1593
1594        /**
1595         * Gets the supported preview formats.
1596         *
1597         * @return a list of supported preview formats. This method will always
1598         *         return a list with at least one element.
1599         * @see android.graphics.ImageFormat
1600         */
1601        public List<Integer> getSupportedPreviewFormats() {
1602            String str = get(KEY_PREVIEW_FORMAT + SUPPORTED_VALUES_SUFFIX);
1603            ArrayList<Integer> formats = new ArrayList<Integer>();
1604            for (String s : split(str)) {
1605                int f = pixelFormatForCameraFormat(s);
1606                if (f == ImageFormat.UNKNOWN) continue;
1607                formats.add(f);
1608            }
1609            return formats;
1610        }
1611
1612        /**
1613         * Sets the dimensions for pictures.
1614         *
1615         * @param width  the width for pictures, in pixels
1616         * @param height the height for pictures, in pixels
1617         */
1618        public void setPictureSize(int width, int height) {
1619            String v = Integer.toString(width) + "x" + Integer.toString(height);
1620            set(KEY_PICTURE_SIZE, v);
1621        }
1622
1623        /**
1624         * Returns the dimension setting for pictures.
1625         *
1626         * @return a Size object with the height and width setting
1627         *          for pictures
1628         */
1629        public Size getPictureSize() {
1630            String pair = get(KEY_PICTURE_SIZE);
1631            return strToSize(pair);
1632        }
1633
1634        /**
1635         * Gets the supported picture sizes.
1636         *
1637         * @return a list of supported picture sizes. This method will always
1638         *         return a list with at least one element.
1639         */
1640        public List<Size> getSupportedPictureSizes() {
1641            String str = get(KEY_PICTURE_SIZE + SUPPORTED_VALUES_SUFFIX);
1642            return splitSize(str);
1643        }
1644
1645        /**
1646         * Sets the image format for pictures.
1647         *
1648         * @param pixel_format the desired picture format
1649         *                     (<var>ImageFormat.NV21</var>,
1650         *                      <var>ImageFormat.RGB_565</var>, or
1651         *                      <var>ImageFormat.JPEG</var>)
1652         * @see android.graphics.ImageFormat
1653         */
1654        public void setPictureFormat(int pixel_format) {
1655            String s = cameraFormatForPixelFormat(pixel_format);
1656            if (s == null) {
1657                throw new IllegalArgumentException(
1658                        "Invalid pixel_format=" + pixel_format);
1659            }
1660
1661            set(KEY_PICTURE_FORMAT, s);
1662        }
1663
1664        /**
1665         * Returns the image format for pictures.
1666         *
1667         * @return the picture format
1668         * @see android.graphics.ImageFormat
1669         */
1670        public int getPictureFormat() {
1671            return pixelFormatForCameraFormat(get(KEY_PICTURE_FORMAT));
1672        }
1673
1674        /**
1675         * Gets the supported picture formats.
1676         *
1677         * @return supported picture formats. This method will always return a
1678         *         list with at least one element.
1679         * @see android.graphics.ImageFormat
1680         */
1681        public List<Integer> getSupportedPictureFormats() {
1682            String str = get(KEY_PICTURE_FORMAT + SUPPORTED_VALUES_SUFFIX);
1683            ArrayList<Integer> formats = new ArrayList<Integer>();
1684            for (String s : split(str)) {
1685                int f = pixelFormatForCameraFormat(s);
1686                if (f == ImageFormat.UNKNOWN) continue;
1687                formats.add(f);
1688            }
1689            return formats;
1690        }
1691
1692        private String cameraFormatForPixelFormat(int pixel_format) {
1693            switch(pixel_format) {
1694            case ImageFormat.NV16:      return PIXEL_FORMAT_YUV422SP;
1695            case ImageFormat.NV21:      return PIXEL_FORMAT_YUV420SP;
1696            case ImageFormat.YUY2:      return PIXEL_FORMAT_YUV422I;
1697            case ImageFormat.RGB_565:   return PIXEL_FORMAT_RGB565;
1698            case ImageFormat.JPEG:      return PIXEL_FORMAT_JPEG;
1699            default:                    return null;
1700            }
1701        }
1702
1703        private int pixelFormatForCameraFormat(String format) {
1704            if (format == null)
1705                return ImageFormat.UNKNOWN;
1706
1707            if (format.equals(PIXEL_FORMAT_YUV422SP))
1708                return ImageFormat.NV16;
1709
1710            if (format.equals(PIXEL_FORMAT_YUV420SP))
1711                return ImageFormat.NV21;
1712
1713            if (format.equals(PIXEL_FORMAT_YUV422I))
1714                return ImageFormat.YUY2;
1715
1716            if (format.equals(PIXEL_FORMAT_RGB565))
1717                return ImageFormat.RGB_565;
1718
1719            if (format.equals(PIXEL_FORMAT_JPEG))
1720                return ImageFormat.JPEG;
1721
1722            return ImageFormat.UNKNOWN;
1723        }
1724
1725        /**
1726         * Sets the orientation of the device in degrees. For example, suppose
1727         * the natural position of the device is landscape. If the user takes a
1728         * picture in landscape mode in 2048x1536 resolution, the rotation
1729         * should be set to 0. If the user rotates the phone 90 degrees
1730         * clockwise, the rotation should be set to 90. Applications can use
1731         * {@link android.view.OrientationEventListener} to set this parameter.
1732         *
1733         * The camera driver may set orientation in the EXIF header without
1734         * rotating the picture. Or the driver may rotate the picture and
1735         * the EXIF thumbnail. If the Jpeg picture is rotated, the orientation
1736         * in the EXIF header will be missing or 1 (row #0 is top and column #0
1737         * is left side).
1738         *
1739         * @param rotation The orientation of the device in degrees. Rotation
1740         *                 can only be 0, 90, 180 or 270.
1741         * @throws IllegalArgumentException if rotation value is invalid.
1742         * @see android.view.OrientationEventListener
1743         */
1744        public void setRotation(int rotation) {
1745            if (rotation == 0 || rotation == 90 || rotation == 180
1746                    || rotation == 270) {
1747                set(KEY_ROTATION, Integer.toString(rotation));
1748            } else {
1749                throw new IllegalArgumentException(
1750                        "Invalid rotation=" + rotation);
1751            }
1752        }
1753
1754        /**
1755         * Sets GPS latitude coordinate. This will be stored in JPEG EXIF
1756         * header.
1757         *
1758         * @param latitude GPS latitude coordinate.
1759         */
1760        public void setGpsLatitude(double latitude) {
1761            set(KEY_GPS_LATITUDE, Double.toString(latitude));
1762        }
1763
1764        /**
1765         * Sets GPS longitude coordinate. This will be stored in JPEG EXIF
1766         * header.
1767         *
1768         * @param longitude GPS longitude coordinate.
1769         */
1770        public void setGpsLongitude(double longitude) {
1771            set(KEY_GPS_LONGITUDE, Double.toString(longitude));
1772        }
1773
1774        /**
1775         * Sets GPS altitude. This will be stored in JPEG EXIF header.
1776         *
1777         * @param altitude GPS altitude in meters.
1778         */
1779        public void setGpsAltitude(double altitude) {
1780            set(KEY_GPS_ALTITUDE, Double.toString(altitude));
1781        }
1782
1783        /**
1784         * Sets GPS timestamp. This will be stored in JPEG EXIF header.
1785         *
1786         * @param timestamp GPS timestamp (UTC in seconds since January 1,
1787         *                  1970).
1788         */
1789        public void setGpsTimestamp(long timestamp) {
1790            set(KEY_GPS_TIMESTAMP, Long.toString(timestamp));
1791        }
1792
1793        /**
1794         * Sets GPS processing method. It will store up to 32 characters
1795         * in JPEG EXIF header.
1796         *
1797         * @param processing_method The processing method to get this location.
1798         */
1799        public void setGpsProcessingMethod(String processing_method) {
1800            set(KEY_GPS_PROCESSING_METHOD, processing_method);
1801        }
1802
1803        /**
1804         * Removes GPS latitude, longitude, altitude, and timestamp from the
1805         * parameters.
1806         */
1807        public void removeGpsData() {
1808            remove(KEY_GPS_LATITUDE);
1809            remove(KEY_GPS_LONGITUDE);
1810            remove(KEY_GPS_ALTITUDE);
1811            remove(KEY_GPS_TIMESTAMP);
1812            remove(KEY_GPS_PROCESSING_METHOD);
1813        }
1814
1815        /**
1816         * Gets the current white balance setting.
1817         *
1818         * @return current white balance. null if white balance setting is not
1819         *         supported.
1820         * @see #WHITE_BALANCE_AUTO
1821         * @see #WHITE_BALANCE_INCANDESCENT
1822         * @see #WHITE_BALANCE_FLUORESCENT
1823         * @see #WHITE_BALANCE_WARM_FLUORESCENT
1824         * @see #WHITE_BALANCE_DAYLIGHT
1825         * @see #WHITE_BALANCE_CLOUDY_DAYLIGHT
1826         * @see #WHITE_BALANCE_TWILIGHT
1827         * @see #WHITE_BALANCE_SHADE
1828         *
1829         */
1830        public String getWhiteBalance() {
1831            return get(KEY_WHITE_BALANCE);
1832        }
1833
1834        /**
1835         * Sets the white balance.
1836         *
1837         * @param value new white balance.
1838         * @see #getWhiteBalance()
1839         */
1840        public void setWhiteBalance(String value) {
1841            set(KEY_WHITE_BALANCE, value);
1842        }
1843
1844        /**
1845         * Gets the supported white balance.
1846         *
1847         * @return a list of supported white balance. null if white balance
1848         *         setting is not supported.
1849         * @see #getWhiteBalance()
1850         */
1851        public List<String> getSupportedWhiteBalance() {
1852            String str = get(KEY_WHITE_BALANCE + SUPPORTED_VALUES_SUFFIX);
1853            return split(str);
1854        }
1855
1856        /**
1857         * Gets the current color effect setting.
1858         *
1859         * @return current color effect. null if color effect
1860         *         setting is not supported.
1861         * @see #EFFECT_NONE
1862         * @see #EFFECT_MONO
1863         * @see #EFFECT_NEGATIVE
1864         * @see #EFFECT_SOLARIZE
1865         * @see #EFFECT_SEPIA
1866         * @see #EFFECT_POSTERIZE
1867         * @see #EFFECT_WHITEBOARD
1868         * @see #EFFECT_BLACKBOARD
1869         * @see #EFFECT_AQUA
1870         */
1871        public String getColorEffect() {
1872            return get(KEY_EFFECT);
1873        }
1874
1875        /**
1876         * Sets the current color effect setting.
1877         *
1878         * @param value new color effect.
1879         * @see #getColorEffect()
1880         */
1881        public void setColorEffect(String value) {
1882            set(KEY_EFFECT, value);
1883        }
1884
1885        /**
1886         * Gets the supported color effects.
1887         *
1888         * @return a list of supported color effects. null if color effect
1889         *         setting is not supported.
1890         * @see #getColorEffect()
1891         */
1892        public List<String> getSupportedColorEffects() {
1893            String str = get(KEY_EFFECT + SUPPORTED_VALUES_SUFFIX);
1894            return split(str);
1895        }
1896
1897
1898        /**
1899         * Gets the current antibanding setting.
1900         *
1901         * @return current antibanding. null if antibanding setting is not
1902         *         supported.
1903         * @see #ANTIBANDING_AUTO
1904         * @see #ANTIBANDING_50HZ
1905         * @see #ANTIBANDING_60HZ
1906         * @see #ANTIBANDING_OFF
1907         */
1908        public String getAntibanding() {
1909            return get(KEY_ANTIBANDING);
1910        }
1911
1912        /**
1913         * Sets the antibanding.
1914         *
1915         * @param antibanding new antibanding value.
1916         * @see #getAntibanding()
1917         */
1918        public void setAntibanding(String antibanding) {
1919            set(KEY_ANTIBANDING, antibanding);
1920        }
1921
1922        /**
1923         * Gets the supported antibanding values.
1924         *
1925         * @return a list of supported antibanding values. null if antibanding
1926         *         setting is not supported.
1927         * @see #getAntibanding()
1928         */
1929        public List<String> getSupportedAntibanding() {
1930            String str = get(KEY_ANTIBANDING + SUPPORTED_VALUES_SUFFIX);
1931            return split(str);
1932        }
1933
1934        /**
1935         * Gets the current scene mode setting.
1936         *
1937         * @return one of SCENE_MODE_XXX string constant. null if scene mode
1938         *         setting is not supported.
1939         * @see #SCENE_MODE_AUTO
1940         * @see #SCENE_MODE_ACTION
1941         * @see #SCENE_MODE_PORTRAIT
1942         * @see #SCENE_MODE_LANDSCAPE
1943         * @see #SCENE_MODE_NIGHT
1944         * @see #SCENE_MODE_NIGHT_PORTRAIT
1945         * @see #SCENE_MODE_THEATRE
1946         * @see #SCENE_MODE_BEACH
1947         * @see #SCENE_MODE_SNOW
1948         * @see #SCENE_MODE_SUNSET
1949         * @see #SCENE_MODE_STEADYPHOTO
1950         * @see #SCENE_MODE_FIREWORKS
1951         * @see #SCENE_MODE_SPORTS
1952         * @see #SCENE_MODE_PARTY
1953         * @see #SCENE_MODE_CANDLELIGHT
1954         */
1955        public String getSceneMode() {
1956            return get(KEY_SCENE_MODE);
1957        }
1958
1959        /**
1960         * Sets the scene mode. Changing scene mode may override other
1961         * parameters (such as flash mode, focus mode, white balance). For
1962         * example, suppose originally flash mode is on and supported flash
1963         * modes are on/off. In night scene mode, both flash mode and supported
1964         * flash mode may be changed to off. After setting scene mode,
1965         * applications should call getParameters to know if some parameters are
1966         * changed.
1967         *
1968         * @param value scene mode.
1969         * @see #getSceneMode()
1970         */
1971        public void setSceneMode(String value) {
1972            set(KEY_SCENE_MODE, value);
1973        }
1974
1975        /**
1976         * Gets the supported scene modes.
1977         *
1978         * @return a list of supported scene modes. null if scene mode setting
1979         *         is not supported.
1980         * @see #getSceneMode()
1981         */
1982        public List<String> getSupportedSceneModes() {
1983            String str = get(KEY_SCENE_MODE + SUPPORTED_VALUES_SUFFIX);
1984            return split(str);
1985        }
1986
1987        /**
1988         * Gets the current flash mode setting.
1989         *
1990         * @return current flash mode. null if flash mode setting is not
1991         *         supported.
1992         * @see #FLASH_MODE_OFF
1993         * @see #FLASH_MODE_AUTO
1994         * @see #FLASH_MODE_ON
1995         * @see #FLASH_MODE_RED_EYE
1996         * @see #FLASH_MODE_TORCH
1997         */
1998        public String getFlashMode() {
1999            return get(KEY_FLASH_MODE);
2000        }
2001
2002        /**
2003         * Sets the flash mode.
2004         *
2005         * @param value flash mode.
2006         * @see #getFlashMode()
2007         */
2008        public void setFlashMode(String value) {
2009            set(KEY_FLASH_MODE, value);
2010        }
2011
2012        /**
2013         * Gets the supported flash modes.
2014         *
2015         * @return a list of supported flash modes. null if flash mode setting
2016         *         is not supported.
2017         * @see #getFlashMode()
2018         */
2019        public List<String> getSupportedFlashModes() {
2020            String str = get(KEY_FLASH_MODE + SUPPORTED_VALUES_SUFFIX);
2021            return split(str);
2022        }
2023
2024        /**
2025         * Gets the current focus mode setting.
2026         *
2027         * @return current focus mode. This method will always return a non-null
2028         *         value. Applications should call {@link
2029         *         #autoFocus(AutoFocusCallback)} to start the focus if focus
2030         *         mode is FOCUS_MODE_AUTO or FOCUS_MODE_MACRO.
2031         * @see #FOCUS_MODE_AUTO
2032         * @see #FOCUS_MODE_INFINITY
2033         * @see #FOCUS_MODE_MACRO
2034         * @see #FOCUS_MODE_FIXED
2035         * @see #FOCUS_MODE_EDOF
2036         * @see #FOCUS_MODE_CONTINUOUS
2037         */
2038        public String getFocusMode() {
2039            return get(KEY_FOCUS_MODE);
2040        }
2041
2042        /**
2043         * Sets the focus mode.
2044         *
2045         * @param value focus mode.
2046         * @see #getFocusMode()
2047         */
2048        public void setFocusMode(String value) {
2049            set(KEY_FOCUS_MODE, value);
2050        }
2051
2052        /**
2053         * Gets the supported focus modes.
2054         *
2055         * @return a list of supported focus modes. This method will always
2056         *         return a list with at least one element.
2057         * @see #getFocusMode()
2058         */
2059        public List<String> getSupportedFocusModes() {
2060            String str = get(KEY_FOCUS_MODE + SUPPORTED_VALUES_SUFFIX);
2061            return split(str);
2062        }
2063
2064        /**
2065         * Gets the focal length (in millimeter) of the camera.
2066         *
2067         * @return the focal length. This method will always return a valid
2068         *         value.
2069         */
2070        public float getFocalLength() {
2071            return Float.parseFloat(get(KEY_FOCAL_LENGTH));
2072        }
2073
2074        /**
2075         * Gets the horizontal angle of view in degrees.
2076         *
2077         * @return horizontal angle of view. This method will always return a
2078         *         valid value.
2079         */
2080        public float getHorizontalViewAngle() {
2081            return Float.parseFloat(get(KEY_HORIZONTAL_VIEW_ANGLE));
2082        }
2083
2084        /**
2085         * Gets the vertical angle of view in degrees.
2086         *
2087         * @return vertical angle of view. This method will always return a
2088         *         valid value.
2089         */
2090        public float getVerticalViewAngle() {
2091            return Float.parseFloat(get(KEY_VERTICAL_VIEW_ANGLE));
2092        }
2093
2094        /**
2095         * Gets the current exposure compensation index.
2096         *
2097         * @return current exposure compensation index. The range is {@link
2098         *         #getMinExposureCompensation} to {@link
2099         *         #getMaxExposureCompensation}. 0 means exposure is not
2100         *         adjusted.
2101         */
2102        public int getExposureCompensation() {
2103            return getInt(KEY_EXPOSURE_COMPENSATION, 0);
2104        }
2105
2106        /**
2107         * Sets the exposure compensation index.
2108         *
2109         * @param value exposure compensation index. The valid value range is
2110         *        from {@link #getMinExposureCompensation} (inclusive) to {@link
2111         *        #getMaxExposureCompensation} (inclusive). 0 means exposure is
2112         *        not adjusted. Application should call
2113         *        getMinExposureCompensation and getMaxExposureCompensation to
2114         *        know if exposure compensation is supported.
2115         */
2116        public void setExposureCompensation(int value) {
2117            set(KEY_EXPOSURE_COMPENSATION, value);
2118        }
2119
2120        /**
2121         * Gets the maximum exposure compensation index.
2122         *
2123         * @return maximum exposure compensation index (>=0). If both this
2124         *         method and {@link #getMinExposureCompensation} return 0,
2125         *         exposure compensation is not supported.
2126         */
2127        public int getMaxExposureCompensation() {
2128            return getInt(KEY_MAX_EXPOSURE_COMPENSATION, 0);
2129        }
2130
2131        /**
2132         * Gets the minimum exposure compensation index.
2133         *
2134         * @return minimum exposure compensation index (<=0). If both this
2135         *         method and {@link #getMaxExposureCompensation} return 0,
2136         *         exposure compensation is not supported.
2137         */
2138        public int getMinExposureCompensation() {
2139            return getInt(KEY_MIN_EXPOSURE_COMPENSATION, 0);
2140        }
2141
2142        /**
2143         * Gets the exposure compensation step.
2144         *
2145         * @return exposure compensation step. Applications can get EV by
2146         *         multiplying the exposure compensation index and step. Ex: if
2147         *         exposure compensation index is -6 and step is 0.333333333, EV
2148         *         is -2.
2149         */
2150        public float getExposureCompensationStep() {
2151            return getFloat(KEY_EXPOSURE_COMPENSATION_STEP, 0);
2152        }
2153
2154        /**
2155         * Gets current zoom value. This also works when smooth zoom is in
2156         * progress. Applications should check {@link #isZoomSupported} before
2157         * using this method.
2158         *
2159         * @return the current zoom value. The range is 0 to {@link
2160         *         #getMaxZoom}. 0 means the camera is not zoomed.
2161         */
2162        public int getZoom() {
2163            return getInt(KEY_ZOOM, 0);
2164        }
2165
2166        /**
2167         * Sets current zoom value. If the camera is zoomed (value > 0), the
2168         * actual picture size may be smaller than picture size setting.
2169         * Applications can check the actual picture size after picture is
2170         * returned from {@link PictureCallback}. The preview size remains the
2171         * same in zoom. Applications should check {@link #isZoomSupported}
2172         * before using this method.
2173         *
2174         * @param value zoom value. The valid range is 0 to {@link #getMaxZoom}.
2175         */
2176        public void setZoom(int value) {
2177            set(KEY_ZOOM, value);
2178        }
2179
2180        /**
2181         * Returns true if zoom is supported. Applications should call this
2182         * before using other zoom methods.
2183         *
2184         * @return true if zoom is supported.
2185         */
2186        public boolean isZoomSupported() {
2187            String str = get(KEY_ZOOM_SUPPORTED);
2188            return TRUE.equals(str);
2189        }
2190
2191        /**
2192         * Gets the maximum zoom value allowed for snapshot. This is the maximum
2193         * value that applications can set to {@link #setZoom(int)}.
2194         * Applications should call {@link #isZoomSupported} before using this
2195         * method. This value may change in different preview size. Applications
2196         * should call this again after setting preview size.
2197         *
2198         * @return the maximum zoom value supported by the camera.
2199         */
2200        public int getMaxZoom() {
2201            return getInt(KEY_MAX_ZOOM, 0);
2202        }
2203
2204        /**
2205         * Gets the zoom ratios of all zoom values. Applications should check
2206         * {@link #isZoomSupported} before using this method.
2207         *
2208         * @return the zoom ratios in 1/100 increments. Ex: a zoom of 3.2x is
2209         *         returned as 320. The number of elements is {@link
2210         *         #getMaxZoom} + 1. The list is sorted from small to large. The
2211         *         first element is always 100. The last element is the zoom
2212         *         ratio of the maximum zoom value.
2213         */
2214        public List<Integer> getZoomRatios() {
2215            return splitInt(get(KEY_ZOOM_RATIOS));
2216        }
2217
2218        /**
2219         * Returns true if smooth zoom is supported. Applications should call
2220         * this before using other smooth zoom methods.
2221         *
2222         * @return true if smooth zoom is supported.
2223         */
2224        public boolean isSmoothZoomSupported() {
2225            String str = get(KEY_SMOOTH_ZOOM_SUPPORTED);
2226            return TRUE.equals(str);
2227        }
2228
2229        /**
2230         * Gets the distances from the camera to where an object appears to be
2231         * in focus. The object is sharpest at the optimal focus distance. The
2232         * depth of field is the far focus distance minus near focus distance.
2233         *
2234         * Focus distances may change after calling {@link
2235         * #autoFocus(AutoFocusCallback)}, {@link #cancelAutoFocus}, or {@link
2236         * #startPreview()}. Applications can call {@link #getParameters()}
2237         * and this method anytime to get the latest focus distances. If the
2238         * focus mode is FOCUS_MODE_CONTINUOUS, focus distances may change from
2239         * time to time.
2240         *
2241         * This method is intended to estimate the distance between the camera
2242         * and the subject. After autofocus, the subject distance may be within
2243         * near and far focus distance. However, the precision depends on the
2244         * camera hardware, autofocus algorithm, the focus area, and the scene.
2245         * The error can be large and it should be only used as a reference.
2246         *
2247         * Far focus distance >= optimal focus distance >= near focus distance.
2248         * If the focus distance is infinity, the value will be
2249         * Float.POSITIVE_INFINITY.
2250         *
2251         * @param output focus distances in meters. output must be a float
2252         *        array with three elements. Near focus distance, optimal focus
2253         *        distance, and far focus distance will be filled in the array.
2254         * @see #FOCUS_DISTANCE_NEAR_INDEX
2255         * @see #FOCUS_DISTANCE_OPTIMAL_INDEX
2256         * @see #FOCUS_DISTANCE_FAR_INDEX
2257         */
2258        public void getFocusDistances(float[] output) {
2259            if (output == null || output.length != 3) {
2260                throw new IllegalArgumentException(
2261                        "output must be an float array with three elements.");
2262            }
2263            splitFloat(get(KEY_FOCUS_DISTANCES), output);
2264        }
2265
2266        /**
2267         * Gets the supported metering modes.
2268         *
2269         * @return a list of supported metering modes. null if metering mode
2270         *         setting is not supported.
2271         * @see #getMeteringMode()
2272         */
2273        public List<String> getSupportedMeteringModes() {
2274            String str = get(KEY_METERING_MODE + SUPPORTED_VALUES_SUFFIX);
2275            return split(str);
2276        }
2277
2278        /**
2279         * Gets the current metering mode, which affects how camera determines
2280         * exposure.
2281         *
2282         * @return current metering mode. If the camera does not support
2283         *         metering setting, this should return null.
2284         * @see #METERING_MODE_CENTER_WEIGHTED
2285         * @see #METERING_MODE_FRAME_AVERAGE
2286         * @see #METERING_MODE_SPOT
2287         */
2288        public String getMeteringMode() {
2289            return get(KEY_METERING_MODE);
2290        }
2291
2292        /**
2293         * Sets the metering mode.
2294         *
2295         * @param value metering mode.
2296         * @see #getMeteringMode()
2297         */
2298        public void setMeteringMode(String value) {
2299            set(KEY_METERING_MODE, value);
2300        }
2301
2302        // Splits a comma delimited string to an ArrayList of String.
2303        // Return null if the passing string is null or the size is 0.
2304        private ArrayList<String> split(String str) {
2305            if (str == null) return null;
2306
2307            // Use StringTokenizer because it is faster than split.
2308            StringTokenizer tokenizer = new StringTokenizer(str, ",");
2309            ArrayList<String> substrings = new ArrayList<String>();
2310            while (tokenizer.hasMoreElements()) {
2311                substrings.add(tokenizer.nextToken());
2312            }
2313            return substrings;
2314        }
2315
2316        // Splits a comma delimited string to an ArrayList of Integer.
2317        // Return null if the passing string is null or the size is 0.
2318        private ArrayList<Integer> splitInt(String str) {
2319            if (str == null) return null;
2320
2321            StringTokenizer tokenizer = new StringTokenizer(str, ",");
2322            ArrayList<Integer> substrings = new ArrayList<Integer>();
2323            while (tokenizer.hasMoreElements()) {
2324                String token = tokenizer.nextToken();
2325                substrings.add(Integer.parseInt(token));
2326            }
2327            if (substrings.size() == 0) return null;
2328            return substrings;
2329        }
2330
2331        private void splitInt(String str, int[] output) {
2332            if (str == null) return;
2333
2334            StringTokenizer tokenizer = new StringTokenizer(str, ",");
2335            int index = 0;
2336            while (tokenizer.hasMoreElements()) {
2337                String token = tokenizer.nextToken();
2338                output[index++] = Integer.parseInt(token);
2339            }
2340        }
2341
2342        // Splits a comma delimited string to an ArrayList of Float.
2343        private void splitFloat(String str, float[] output) {
2344            if (str == null) return;
2345
2346            StringTokenizer tokenizer = new StringTokenizer(str, ",");
2347            int index = 0;
2348            while (tokenizer.hasMoreElements()) {
2349                String token = tokenizer.nextToken();
2350                output[index++] = Float.parseFloat(token);
2351            }
2352        }
2353
2354        // Returns the value of a float parameter.
2355        private float getFloat(String key, float defaultValue) {
2356            try {
2357                return Float.parseFloat(mMap.get(key));
2358            } catch (NumberFormatException ex) {
2359                return defaultValue;
2360            }
2361        }
2362
2363        // Returns the value of a integer parameter.
2364        private int getInt(String key, int defaultValue) {
2365            try {
2366                return Integer.parseInt(mMap.get(key));
2367            } catch (NumberFormatException ex) {
2368                return defaultValue;
2369            }
2370        }
2371
2372        // Splits a comma delimited string to an ArrayList of Size.
2373        // Return null if the passing string is null or the size is 0.
2374        private ArrayList<Size> splitSize(String str) {
2375            if (str == null) return null;
2376
2377            StringTokenizer tokenizer = new StringTokenizer(str, ",");
2378            ArrayList<Size> sizeList = new ArrayList<Size>();
2379            while (tokenizer.hasMoreElements()) {
2380                Size size = strToSize(tokenizer.nextToken());
2381                if (size != null) sizeList.add(size);
2382            }
2383            if (sizeList.size() == 0) return null;
2384            return sizeList;
2385        }
2386
2387        // Parses a string (ex: "480x320") to Size object.
2388        // Return null if the passing string is null.
2389        private Size strToSize(String str) {
2390            if (str == null) return null;
2391
2392            int pos = str.indexOf('x');
2393            if (pos != -1) {
2394                String width = str.substring(0, pos);
2395                String height = str.substring(pos + 1);
2396                return new Size(Integer.parseInt(width),
2397                                Integer.parseInt(height));
2398            }
2399            Log.e(TAG, "Invalid size parameter string=" + str);
2400            return null;
2401        }
2402
2403        // Splits a comma delimited string to an ArrayList of int array.
2404        // Example string: "(10000,26623),(10000,30000)". Return null if the
2405        // passing string is null or the size is 0.
2406        private ArrayList<int[]> splitRange(String str) {
2407            if (str == null || str.charAt(0) != '('
2408                    || str.charAt(str.length() - 1) != ')') {
2409                Log.e(TAG, "Invalid range list string=" + str);
2410                return null;
2411            }
2412
2413            ArrayList<int[]> rangeList = new ArrayList<int[]>();
2414            int endIndex, fromIndex = 1;
2415            do {
2416                int[] range = new int[2];
2417                endIndex = str.indexOf("),(", fromIndex);
2418                if (endIndex == -1) endIndex = str.length() - 1;
2419                splitInt(str.substring(fromIndex, endIndex), range);
2420                rangeList.add(range);
2421                fromIndex = endIndex + 3;
2422            } while (endIndex != str.length() - 1);
2423
2424            if (rangeList.size() == 0) return null;
2425            return rangeList;
2426        }
2427    };
2428}
2429