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