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