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