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