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