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