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