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