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