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