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