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