OSDN Git Service

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