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