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