Debian Codegraph @

core/java/android/hardware/Camera.java

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