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