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