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