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