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