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