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