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