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