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