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