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