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