Debian Codegraph @

core/java/android/hardware/camera2/CameraManager.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2013 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.camera2;
18
19 import android.annotation.CallbackExecutor;
20 import android.annotation.NonNull;
21 import android.annotation.Nullable;
22 import android.annotation.RequiresPermission;
23 import android.annotation.SystemApi;
24 import android.annotation.SystemService;
25 import android.annotation.TestApi;
26 import android.app.compat.CompatChanges;
27 import android.compat.annotation.ChangeId;
28 import android.compat.annotation.EnabledSince;
29 import android.compat.annotation.Overridable;
30 import android.content.Context;
31 import android.content.pm.PackageManager;
32 import android.graphics.Point;
33 import android.hardware.CameraStatus;
34 import android.hardware.ICameraService;
35 import android.hardware.ICameraServiceListener;
36 import android.hardware.camera2.impl.CameraDeviceImpl;
37 import android.hardware.camera2.impl.CameraInjectionSessionImpl;
38 import android.hardware.camera2.impl.CameraMetadataNative;
39 import android.hardware.camera2.params.ExtensionSessionConfiguration;
40 import android.hardware.camera2.params.SessionConfiguration;
41 import android.hardware.camera2.params.StreamConfiguration;
42 import android.hardware.camera2.utils.CameraIdAndSessionConfiguration;
43 import android.hardware.camera2.utils.ConcurrentCameraIdCombination;
44 import android.hardware.devicestate.DeviceStateManager;
45 import android.hardware.display.DisplayManager;
46 import android.os.Binder;
47 import android.os.DeadObjectException;
48 import android.os.Handler;
49 import android.os.HandlerExecutor;
50 import android.os.HandlerThread;
51 import android.os.IBinder;
52 import android.os.RemoteException;
53 import android.os.ServiceManager;
54 import android.os.ServiceSpecificException;
55 import android.os.SystemProperties;
56 import android.util.ArrayMap;
57 import android.util.ArraySet;
58 import android.util.Log;
59 import android.util.Size;
60 import android.view.Display;
61
62 import com.android.internal.annotations.GuardedBy;
63 import com.android.internal.util.ArrayUtils;
64
65 import java.lang.ref.WeakReference;
66 import java.util.ArrayList;
67 import java.util.Arrays;
68 import java.util.Comparator;
69 import java.util.HashMap;
70 import java.util.Map;
71 import java.util.Set;
72 import java.util.concurrent.Executor;
73 import java.util.concurrent.Executors;
74 import java.util.concurrent.RejectedExecutionException;
75 import java.util.concurrent.ScheduledExecutorService;
76 import java.util.concurrent.TimeUnit;
77
78 /**
79 * <p>A system service manager for detecting, characterizing, and connecting to
80 * {@link CameraDevice CameraDevices}.</p>
81 *
82 * <p>For more details about communicating with camera devices, read the Camera
83 * developer guide or the {@link android.hardware.camera2 camera2}
84 * package documentation.</p>
85 */
86 @SystemService(Context.CAMERA_SERVICE)
87 public final class CameraManager {
88
89 private static final String TAG = "CameraManager";
90 private final boolean DEBUG = false;
91
92 private static final int USE_CALLING_UID = -1;
93
94 @SuppressWarnings("unused")
95 private static final int API_VERSION_1 = 1;
96 private static final int API_VERSION_2 = 2;
97
98 private static final int CAMERA_TYPE_BACKWARD_COMPATIBLE = 0;
99 private static final int CAMERA_TYPE_ALL = 1;
100
101 private ArrayList<String> mDeviceIdList;
102
103 private final Context mContext;
104 private final Object mLock = new Object();
105
106 private static final String CAMERA_OPEN_CLOSE_LISTENER_PERMISSION =
107 "android.permission.CAMERA_OPEN_CLOSE_LISTENER";
108 private final boolean mHasOpenCloseListenerPermission;
109
110 /**
111 * Force camera output to be rotated to portrait orientation on landscape cameras.
112 * Many apps do not handle this situation and display stretched images otherwise.
113 * @hide
114 */
115 @ChangeId
116 @Overridable
117 @EnabledSince(targetSdkVersion = android.os.Build.VERSION_CODES.BASE)
118 @TestApi
119 public static final long OVERRIDE_FRONT_CAMERA_APP_COMPAT = 250678880L;
120
121 /**
122 * System property for allowing the above
123 * @hide
124 */
125 public static final String LANDSCAPE_TO_PORTRAIT_PROP =
126 "camera.enable_landscape_to_portrait";
127
128 /**
129 * @hide
130 */
131 public CameraManager(Context context) {
132 synchronized(mLock) {
133 mContext = context;
134 mHasOpenCloseListenerPermission =
135 mContext.checkSelfPermission(CAMERA_OPEN_CLOSE_LISTENER_PERMISSION) ==
136 PackageManager.PERMISSION_GRANTED;
137 }
138
139 mHandlerThread = new HandlerThread(TAG);
140 mHandlerThread.start();
141 mHandler = new Handler(mHandlerThread.getLooper());
142 mFoldStateListener = new FoldStateListener(context);
143 try {
144 context.getSystemService(DeviceStateManager.class)
145 .registerCallback(new HandlerExecutor(mHandler), mFoldStateListener);
146 } catch (IllegalStateException e) {
147 Log.v(TAG, "Failed to register device state listener!");
148 Log.v(TAG, "Device state dependent characteristics updates will not be functional!");
149 mHandlerThread.quitSafely();
150 mHandler = null;
151 mFoldStateListener = null;
152 }
153 }
154
155 private HandlerThread mHandlerThread;
156 private Handler mHandler;
157 private FoldStateListener mFoldStateListener;
158
159 /**
160 * @hide
161 */
162 public interface DeviceStateListener {
163 void onDeviceStateChanged(boolean folded);
164 }
165
166 private static final class FoldStateListener implements DeviceStateManager.DeviceStateCallback {
167 private final int[] mFoldedDeviceStates;
168
169 private ArrayList<WeakReference<DeviceStateListener>> mDeviceStateListeners =
170 new ArrayList<>();
171 private boolean mFoldedDeviceState;
172
173 public FoldStateListener(Context context) {
174 mFoldedDeviceStates = context.getResources().getIntArray(
175 com.android.internal.R.array.config_foldedDeviceStates);
176 }
177
178 private synchronized void handleStateChange(int state) {
179 boolean folded = ArrayUtils.contains(mFoldedDeviceStates, state);
180
181 mFoldedDeviceState = folded;
182 ArrayList<WeakReference<DeviceStateListener>> invalidListeners = new ArrayList<>();
183 for (WeakReference<DeviceStateListener> listener : mDeviceStateListeners) {
184 DeviceStateListener callback = listener.get();
185 if (callback != null) {
186 callback.onDeviceStateChanged(folded);
187 } else {
188 invalidListeners.add(listener);
189 }
190 }
191 if (!invalidListeners.isEmpty()) {
192 mDeviceStateListeners.removeAll(invalidListeners);
193 }
194 }
195
196 public synchronized void addDeviceStateListener(DeviceStateListener listener) {
197 listener.onDeviceStateChanged(mFoldedDeviceState);
198 mDeviceStateListeners.add(new WeakReference<>(listener));
199 }
200
201 @Override
202 public final void onBaseStateChanged(int state) {
203 handleStateChange(state);
204 }
205
206 @Override
207 public final void onStateChanged(int state) {
208 handleStateChange(state);
209 }
210 }
211
212 /**
213 * Register a {@link CameraCharacteristics} device state listener
214 *
215 * @param chars Camera characteristics that need to receive device state updates
216 *
217 * @hide
218 */
219 public void registerDeviceStateListener(@NonNull CameraCharacteristics chars) {
220 synchronized (mLock) {
221 DeviceStateListener listener = chars.getDeviceStateListener();
222 if (mFoldStateListener != null) {
223 mFoldStateListener.addDeviceStateListener(listener);
224 }
225 }
226 }
227
228 /**
229 * Return the list of currently connected camera devices by identifier, including
230 * cameras that may be in use by other camera API clients.
231 *
232 * <p>Non-removable cameras use integers starting at 0 for their
233 * identifiers, while removable cameras have a unique identifier for each
234 * individual device, even if they are the same model.</p>
235 *
236 * <p>This list doesn't contain physical cameras that can only be used as part of a logical
237 * multi-camera device.</p>
238 *
239 * @return The list of currently connected camera devices.
240 */
241 @NonNull
242 public String[] getCameraIdList() throws CameraAccessException {
243 return CameraManagerGlobal.get().getCameraIdList();
244 }
245
246 /**
247 * Similar to getCameraIdList(). However, getCamerIdListNoLazy() necessarily communicates with
248 * cameraserver in order to get the list of camera ids. This is to faciliate testing since some
249 * camera ids may go 'offline' without callbacks from cameraserver because of changes in
250 * SYSTEM_CAMERA permissions (though this is not a changeable permission, tests may call
251 * adopt(drop)ShellPermissionIdentity() and effectively change their permissions). This call
252 * affects the camera ids returned by getCameraIdList() as well. Tests which do adopt shell
253 * permission identity should not mix getCameraIdList() and getCameraListNoLazyCalls().
254 */
255 /** @hide */
256 @TestApi
257 public String[] getCameraIdListNoLazy() throws CameraAccessException {
258 return CameraManagerGlobal.get().getCameraIdListNoLazy();
259 }
260
261 /**
262 * Return the set of combinations of currently connected camera device identifiers, which
263 * support configuring camera device sessions concurrently.
264 *
265 * <p>The devices in these combinations can be concurrently configured by the same
266 * client camera application. Using these camera devices concurrently by two different
267 * applications is not guaranteed to be supported, however.</p>
268 *
269 * <p>For concurrent operation, in chronological order :
270 * <ul>
271 * <li> Applications must first close any open cameras that have sessions configured, using
272 * {@link CameraDevice#close}. </li>
273 * <li> All camera devices intended to be operated concurrently, must be opened using
274 * {@link #openCamera}, before configuring sessions on any of the camera devices.</li>
275 *</ul>
276 *</p>
277 * <p>Each device in a combination, is guaranteed to support stream combinations which may be
278 * obtained by querying {@link #getCameraCharacteristics} for the key
279 * {@link android.hardware.camera2.CameraCharacteristics#SCALER_MANDATORY_CONCURRENT_STREAM_COMBINATIONS}.</p>
280 *
281 * <p>For concurrent operation, if a camera device has a non null zoom ratio range as specified
282 * by
283 * {@link android.hardware.camera2.CameraCharacteristics#CONTROL_ZOOM_RATIO_RANGE},
284 * its complete zoom ratio range may not apply. Applications can use
285 * {@link android.hardware.camera2.CaptureRequest#CONTROL_ZOOM_RATIO} >=1 and <=
286 * {@link android.hardware.camera2.CameraCharacteristics#SCALER_AVAILABLE_MAX_DIGITAL_ZOOM}
287 * during concurrent operation.
288 * <p>
289 *
290 * <p>The set of combinations may include camera devices that may be in use by other camera API
291 * clients.</p>
292 *
293 * <p>Concurrent camera extension sessions {@link CameraExtensionSession} are not currently
294 * supported.</p>
295 *
296 * <p>The set of combinations doesn't contain physical cameras that can only be used as
297 * part of a logical multi-camera device.</p>
298 *
299 * <p> If a new camera id becomes available through
300 * {@link AvailabilityCallback#onCameraUnavailable(String)}, clients can call
301 * this method to check if new combinations of camera ids which can stream concurrently are
302 * available.
303 *
304 * @return The set of combinations of currently connected camera devices, that may have
305 * sessions configured concurrently. The set of combinations will be empty if no such
306 * combinations are supported by the camera subsystem.
307 *
308 * @throws CameraAccessException if the camera device has been disconnected.
309 */
310 @NonNull
311 public Set<Set<String>> getConcurrentCameraIds() throws CameraAccessException {
312 return CameraManagerGlobal.get().getConcurrentCameraIds();
313 }
314
315 /**
316 * Checks whether the provided set of camera devices and their corresponding
317 * {@link SessionConfiguration} can be configured concurrently.
318 *
319 * <p>This method performs a runtime check of the given {@link SessionConfiguration} and camera
320 * id combinations. The result confirms whether or not the passed session configurations can be
321 * successfully used to create camera capture sessions concurrently, on the given camera
322 * devices using {@link CameraDevice#createCaptureSession(SessionConfiguration)}.
323 * </p>
324 *
325 * <p>The method can be called at any point before, during and after active capture sessions.
326 * It will not impact normal camera behavior in any way and must complete significantly
327 * faster than creating a regular or constrained capture session.</p>
328 *
329 * <p>Although this method is faster than creating a new capture session, it is not intended
330 * to be used for exploring the entire space of supported concurrent stream combinations. The
331 * available mandatory concurrent stream combinations may be obtained by querying
332 * {@link #getCameraCharacteristics} for the key
333 * {@link android.hardware.camera2.CameraCharacteristics#SCALER_MANDATORY_CONCURRENT_STREAM_COMBINATIONS}. </p>
334 *
335 * <p>Note that session parameters will be ignored and calls to
336 * {@link SessionConfiguration#setSessionParameters} are not required.</p>
337 *
338 * @return {@code true} if the given combination of session configurations and corresponding
339 * camera ids are concurrently supported by the camera sub-system,
340 * {@code false} otherwise OR if the set of camera devices provided is not a subset of
341 * those returned by {@link #getConcurrentCameraIds}.
342 *
343 * @throws CameraAccessException if one of the camera devices queried is no longer connected.
344 *
345 */
346 @RequiresPermission(android.Manifest.permission.CAMERA)
347 public boolean isConcurrentSessionConfigurationSupported(
348 @NonNull Map<String, SessionConfiguration> cameraIdAndSessionConfig)
349 throws CameraAccessException {
350 return CameraManagerGlobal.get().isConcurrentSessionConfigurationSupported(
351 cameraIdAndSessionConfig, mContext.getApplicationInfo().targetSdkVersion);
352 }
353
354 /**
355 * Register a callback to be notified about camera device availability.
356 *
357 * <p>Registering the same callback again will replace the handler with the
358 * new one provided.</p>
359 *
360 * <p>The first time a callback is registered, it is immediately called
361 * with the availability status of all currently known camera devices.</p>
362 *
363 * <p>{@link AvailabilityCallback#onCameraUnavailable(String)} will be called whenever a camera
364 * device is opened by any camera API client. As of API level 23, other camera API clients may
365 * still be able to open such a camera device, evicting the existing client if they have higher
366 * priority than the existing client of a camera device. See open() for more details.</p>
367 *
368 * <p>Since this callback will be registered with the camera service, remember to unregister it
369 * once it is no longer needed; otherwise the callback will continue to receive events
370 * indefinitely and it may prevent other resources from being released. Specifically, the
371 * callbacks will be invoked independently of the general activity lifecycle and independently
372 * of the state of individual CameraManager instances.</p>
373 *
374 * @param callback the new callback to send camera availability notices to
375 * @param handler The handler on which the callback should be invoked, or {@code null} to use
376 * the current thread's {@link android.os.Looper looper}.
377 *
378 * @throws IllegalArgumentException if the handler is {@code null} but the current thread has
379 * no looper.
380 */
381 public void registerAvailabilityCallback(@NonNull AvailabilityCallback callback,
382 @Nullable Handler handler) {
383 CameraManagerGlobal.get().registerAvailabilityCallback(callback,
384 CameraDeviceImpl.checkAndWrapHandler(handler), mHasOpenCloseListenerPermission);
385 }
386
387 /**
388 * Register a callback to be notified about camera device availability.
389 *
390 * <p>The behavior of this method matches that of
391 * {@link #registerAvailabilityCallback(AvailabilityCallback, Handler)},
392 * except that it uses {@link java.util.concurrent.Executor} as an argument
393 * instead of {@link android.os.Handler}.</p>
394 *
395 * @param executor The executor which will be used to invoke the callback.
396 * @param callback the new callback to send camera availability notices to
397 *
398 * @throws IllegalArgumentException if the executor is {@code null}.
399 */
400 public void registerAvailabilityCallback(@NonNull @CallbackExecutor Executor executor,
401 @NonNull AvailabilityCallback callback) {
402 if (executor == null) {
403 throw new IllegalArgumentException("executor was null");
404 }
405 CameraManagerGlobal.get().registerAvailabilityCallback(callback, executor,
406 mHasOpenCloseListenerPermission);
407 }
408
409 /**
410 * Remove a previously-added callback; the callback will no longer receive connection and
411 * disconnection callbacks.
412 *
413 * <p>Removing a callback that isn't registered has no effect.</p>
414 *
415 * @param callback The callback to remove from the notification list
416 */
417 public void unregisterAvailabilityCallback(@NonNull AvailabilityCallback callback) {
418 CameraManagerGlobal.get().unregisterAvailabilityCallback(callback);
419 }
420
421 /**
422 * Register a callback to be notified about torch mode status.
423 *
424 * <p>Registering the same callback again will replace the handler with the
425 * new one provided.</p>
426 *
427 * <p>The first time a callback is registered, it is immediately called
428 * with the torch mode status of all currently known camera devices with a flash unit.</p>
429 *
430 * <p>Since this callback will be registered with the camera service, remember to unregister it
431 * once it is no longer needed; otherwise the callback will continue to receive events
432 * indefinitely and it may prevent other resources from being released. Specifically, the
433 * callbacks will be invoked independently of the general activity lifecycle and independently
434 * of the state of individual CameraManager instances.</p>
435 *
436 * @param callback The new callback to send torch mode status to
437 * @param handler The handler on which the callback should be invoked, or {@code null} to use
438 * the current thread's {@link android.os.Looper looper}.
439 *
440 * @throws IllegalArgumentException if the handler is {@code null} but the current thread has
441 * no looper.
442 */
443 public void registerTorchCallback(@NonNull TorchCallback callback, @Nullable Handler handler) {
444 CameraManagerGlobal.get().registerTorchCallback(callback,
445 CameraDeviceImpl.checkAndWrapHandler(handler));
446 }
447
448 /**
449 * Register a callback to be notified about torch mode status.
450 *
451 * <p>The behavior of this method matches that of
452 * {@link #registerTorchCallback(TorchCallback, Handler)},
453 * except that it uses {@link java.util.concurrent.Executor} as an argument
454 * instead of {@link android.os.Handler}.</p>
455 *
456 * @param executor The executor which will be used to invoke the callback
457 * @param callback The new callback to send torch mode status to
458 *
459 * @throws IllegalArgumentException if the executor is {@code null}.
460 */
461 public void registerTorchCallback(@NonNull @CallbackExecutor Executor executor,
462 @NonNull TorchCallback callback) {
463 if (executor == null) {
464 throw new IllegalArgumentException("executor was null");
465 }
466 CameraManagerGlobal.get().registerTorchCallback(callback, executor);
467 }
468
469 /**
470 * Remove a previously-added callback; the callback will no longer receive torch mode status
471 * callbacks.
472 *
473 * <p>Removing a callback that isn't registered has no effect.</p>
474 *
475 * @param callback The callback to remove from the notification list
476 */
477 public void unregisterTorchCallback(@NonNull TorchCallback callback) {
478 CameraManagerGlobal.get().unregisterTorchCallback(callback);
479 }
480
481 // TODO(b/147726300): Investigate how to support foldables/multi-display devices.
482 private Size getDisplaySize() {
483 Size ret = new Size(0, 0);
484
485 try {
486 DisplayManager displayManager =
487 (DisplayManager) mContext.getSystemService(Context.DISPLAY_SERVICE);
488 Display display = displayManager.getDisplay(Display.DEFAULT_DISPLAY);
489 if (display != null) {
490 Point sz = new Point();
491 display.getRealSize(sz);
492 int width = sz.x;
493 int height = sz.y;
494
495 if (height > width) {
496 height = width;
497 width = sz.y;
498 }
499
500 ret = new Size(width, height);
501 } else {
502 Log.e(TAG, "Invalid default display!");
503 }
504 } catch (Exception e) {
505 Log.e(TAG, "getDisplaySize Failed. " + e);
506 }
507
508 return ret;
509 }
510
511 /**
512 * Get all physical cameras' multi-resolution stream configuration map
513 *
514 * <p>For a logical multi-camera, query the map between physical camera id and
515 * the physical camera's multi-resolution stream configuration. This map is in turn
516 * combined to form the logical camera's multi-resolution stream configuration map.</p>
517 *
518 * <p>For an ultra high resolution camera, directly use
519 * android.scaler.physicalCameraMultiResolutionStreamConfigurations as the camera device's
520 * multi-resolution stream configuration map.</p>
521 */
522 private Map<String, StreamConfiguration[]> getPhysicalCameraMultiResolutionConfigs(
523 String cameraId, CameraMetadataNative info, ICameraService cameraService)
524 throws CameraAccessException {
525 HashMap<String, StreamConfiguration[]> multiResolutionStreamConfigurations =
526 new HashMap<String, StreamConfiguration[]>();
527
528 Boolean multiResolutionStreamSupported = info.get(
529 CameraCharacteristics.SCALER_MULTI_RESOLUTION_STREAM_SUPPORTED);
530 if (multiResolutionStreamSupported == null || !multiResolutionStreamSupported) {
531 return multiResolutionStreamConfigurations;
532 }
533
534 // Query the characteristics of all physical sub-cameras, and combine the multi-resolution
535 // stream configurations. Alternatively, for ultra-high resolution camera, direclty use
536 // its multi-resolution stream configurations. Note that framework derived formats such as
537 // HEIC and DEPTH_JPEG aren't supported as multi-resolution input or output formats.
538 Set<String> physicalCameraIds = info.getPhysicalCameraIds();
539 if (physicalCameraIds.size() == 0 && info.isUltraHighResolutionSensor()) {
540 StreamConfiguration[] configs = info.get(CameraCharacteristics.
541 SCALER_PHYSICAL_CAMERA_MULTI_RESOLUTION_STREAM_CONFIGURATIONS);
542 if (configs != null) {
543 multiResolutionStreamConfigurations.put(cameraId, configs);
544 }
545 return multiResolutionStreamConfigurations;
546 }
547 try {
548 for (String physicalCameraId : physicalCameraIds) {
549 CameraMetadataNative physicalCameraInfo =
550 cameraService.getCameraCharacteristics(physicalCameraId,
551 mContext.getApplicationInfo().targetSdkVersion,
552 /*overrideToPortrait*/false);
553 StreamConfiguration[] configs = physicalCameraInfo.get(
554 CameraCharacteristics.
555 SCALER_PHYSICAL_CAMERA_MULTI_RESOLUTION_STREAM_CONFIGURATIONS);
556 if (configs != null) {
557 multiResolutionStreamConfigurations.put(physicalCameraId, configs);
558 }
559 }
560 } catch (RemoteException e) {
561 ServiceSpecificException sse = new ServiceSpecificException(
562 ICameraService.ERROR_DISCONNECTED,
563 "Camera service is currently unavailable");
564 throwAsPublicException(sse);
565 }
566
567 return multiResolutionStreamConfigurations;
568 }
569
570 /**
571 * <p>Query the capabilities of a camera device. These capabilities are
572 * immutable for a given camera.</p>
573 *
574 * <p>From API level 29, this function can also be used to query the capabilities of physical
575 * cameras that can only be used as part of logical multi-camera. These cameras cannot be
576 * opened directly via {@link #openCamera}</p>
577 *
578 * <p>Also starting with API level 29, while most basic camera information is still available
579 * even without the CAMERA permission, some values are not available to apps that do not hold
580 * that permission. The keys not available are listed by
581 * {@link CameraCharacteristics#getKeysNeedingPermission}.</p>
582 *
583 * @param cameraId The id of the camera device to query. This could be either a standalone
584 * camera ID which can be directly opened by {@link #openCamera}, or a physical camera ID that
585 * can only used as part of a logical multi-camera.
586 * @return The properties of the given camera
587 *
588 * @throws IllegalArgumentException if the cameraId does not match any
589 * known camera device.
590 * @throws CameraAccessException if the camera device has been disconnected.
591 *
592 * @see #getCameraIdList
593 * @see android.app.admin.DevicePolicyManager#setCameraDisabled
594 */
595 @NonNull
596 public CameraCharacteristics getCameraCharacteristics(@NonNull String cameraId)
597 throws CameraAccessException {
598 CameraCharacteristics characteristics = null;
599 if (CameraManagerGlobal.sCameraServiceDisabled) {
600 throw new IllegalArgumentException("No cameras available on device");
601 }
602 synchronized (mLock) {
603 ICameraService cameraService = CameraManagerGlobal.get().getCameraService();
604 if (cameraService == null) {
605 throw new CameraAccessException(CameraAccessException.CAMERA_DISCONNECTED,
606 "Camera service is currently unavailable");
607 }
608 try {
609 Size displaySize = getDisplaySize();
610
611 boolean overrideToPortrait = shouldOverrideToPortrait();
612 CameraMetadataNative info = cameraService.getCameraCharacteristics(cameraId,
613 mContext.getApplicationInfo().targetSdkVersion, overrideToPortrait);
614 try {
615 info.setCameraId(Integer.parseInt(cameraId));
616 } catch (NumberFormatException e) {
617 Log.v(TAG, "Failed to parse camera Id " + cameraId + " to integer");
618 }
619
620 boolean hasConcurrentStreams =
621 CameraManagerGlobal.get().cameraIdHasConcurrentStreamsLocked(cameraId);
622 info.setHasMandatoryConcurrentStreams(hasConcurrentStreams);
623 info.setDisplaySize(displaySize);
624
625 Map<String, StreamConfiguration[]> multiResolutionSizeMap =
626 getPhysicalCameraMultiResolutionConfigs(cameraId, info, cameraService);
627 if (multiResolutionSizeMap.size() > 0) {
628 info.setMultiResolutionStreamConfigurationMap(multiResolutionSizeMap);
629 }
630
631 characteristics = new CameraCharacteristics(info);
632 } catch (ServiceSpecificException e) {
633 throwAsPublicException(e);
634 } catch (RemoteException e) {
635 // Camera service died - act as if the camera was disconnected
636 throw new CameraAccessException(CameraAccessException.CAMERA_DISCONNECTED,
637 "Camera service is currently unavailable", e);
638 }
639 }
640 registerDeviceStateListener(characteristics);
641 return characteristics;
642 }
643
644 /**
645 * <p>Query the camera extension capabilities of a camera device.</p>
646 *
647 * @param cameraId The id of the camera device to query. This must be a standalone
648 * camera ID which can be directly opened by {@link #openCamera}.
649 * @return The properties of the given camera
650 *
651 * @throws IllegalArgumentException if the cameraId does not match any
652 * known camera device.
653 * @throws CameraAccessException if the camera device has been disconnected.
654 *
655 * @see CameraExtensionCharacteristics
656 * @see CameraDevice#createExtensionSession(ExtensionSessionConfiguration)
657 * @see CameraExtensionSession
658 */
659 @NonNull
660 public CameraExtensionCharacteristics getCameraExtensionCharacteristics(
661 @NonNull String cameraId) throws CameraAccessException {
662 CameraCharacteristics chars = getCameraCharacteristics(cameraId);
663 return new CameraExtensionCharacteristics(mContext, cameraId, chars);
664 }
665
666 private Map<String, CameraCharacteristics> getPhysicalIdToCharsMap(
667 CameraCharacteristics chars) throws CameraAccessException {
668 HashMap<String, CameraCharacteristics> physicalIdsToChars =
669 new HashMap<String, CameraCharacteristics>();
670 Set<String> physicalCameraIds = chars.getPhysicalCameraIds();
671 for (String physicalCameraId : physicalCameraIds) {
672 CameraCharacteristics physicalChars = getCameraCharacteristics(physicalCameraId);
673 physicalIdsToChars.put(physicalCameraId, physicalChars);
674 }
675 return physicalIdsToChars;
676 }
677
678 /**
679 * Helper for opening a connection to a camera with the given ID.
680 *
681 * @param cameraId The unique identifier of the camera device to open
682 * @param callback The callback for the camera. Must not be null.
683 * @param executor The executor to invoke the callback with. Must not be null.
684 * @param uid The UID of the application actually opening the camera.
685 * Must be USE_CALLING_UID unless the caller is a service
686 * that is trusted to open the device on behalf of an
687 * application and to forward the real UID.
688 *
689 * @throws CameraAccessException if the camera is disabled by device policy,
690 * too many camera devices are already open, or the cameraId does not match
691 * any currently available camera device.
692 *
693 * @throws SecurityException if the application does not have permission to
694 * access the camera
695 * @throws IllegalArgumentException if callback or handler is null.
696 * @return A handle to the newly-created camera device.
697 *
698 * @see #getCameraIdList
699 * @see android.app.admin.DevicePolicyManager#setCameraDisabled
700 */
701 private CameraDevice openCameraDeviceUserAsync(String cameraId,
702 CameraDevice.StateCallback callback, Executor executor, final int uid,
703 final int oomScoreOffset) throws CameraAccessException {
704 CameraCharacteristics characteristics = getCameraCharacteristics(cameraId);
705 CameraDevice device = null;
706 Map<String, CameraCharacteristics> physicalIdsToChars =
707 getPhysicalIdToCharsMap(characteristics);
708 synchronized (mLock) {
709
710 ICameraDeviceUser cameraUser = null;
711 android.hardware.camera2.impl.CameraDeviceImpl deviceImpl =
712 new android.hardware.camera2.impl.CameraDeviceImpl(
713 cameraId,
714 callback,
715 executor,
716 characteristics,
717 physicalIdsToChars,
718 mContext.getApplicationInfo().targetSdkVersion,
719 mContext);
720
721 ICameraDeviceCallbacks callbacks = deviceImpl.getCallbacks();
722
723 try {
724 ICameraService cameraService = CameraManagerGlobal.get().getCameraService();
725 if (cameraService == null) {
726 throw new ServiceSpecificException(
727 ICameraService.ERROR_DISCONNECTED,
728 "Camera service is currently unavailable");
729 }
730
731 boolean overrideToPortrait = shouldOverrideToPortrait();
732 cameraUser = cameraService.connectDevice(callbacks, cameraId,
733 mContext.getOpPackageName(), mContext.getAttributionTag(), uid,
734 oomScoreOffset, mContext.getApplicationInfo().targetSdkVersion,
735 overrideToPortrait);
736 } catch (ServiceSpecificException e) {
737 if (e.errorCode == ICameraService.ERROR_DEPRECATED_HAL) {
738 throw new AssertionError("Should've gone down the shim path");
739 } else if (e.errorCode == ICameraService.ERROR_CAMERA_IN_USE ||
740 e.errorCode == ICameraService.ERROR_MAX_CAMERAS_IN_USE ||
741 e.errorCode == ICameraService.ERROR_DISABLED ||
742 e.errorCode == ICameraService.ERROR_DISCONNECTED ||
743 e.errorCode == ICameraService.ERROR_INVALID_OPERATION) {
744 // Received one of the known connection errors
745 // The remote camera device cannot be connected to, so
746 // set the local camera to the startup error state
747 deviceImpl.setRemoteFailure(e);
748
749 if (e.errorCode == ICameraService.ERROR_DISABLED ||
750 e.errorCode == ICameraService.ERROR_DISCONNECTED ||
751 e.errorCode == ICameraService.ERROR_CAMERA_IN_USE) {
752 // Per API docs, these failures call onError and throw
753 throwAsPublicException(e);
754 }
755 } else {
756 // Unexpected failure - rethrow
757 throwAsPublicException(e);
758 }
759 } catch (RemoteException e) {
760 // Camera service died - act as if it's a CAMERA_DISCONNECTED case
761 ServiceSpecificException sse = new ServiceSpecificException(
762 ICameraService.ERROR_DISCONNECTED,
763 "Camera service is currently unavailable");
764 deviceImpl.setRemoteFailure(sse);
765 throwAsPublicException(sse);
766 }
767
768 // TODO: factor out callback to be non-nested, then move setter to constructor
769 // For now, calling setRemoteDevice will fire initial
770 // onOpened/onUnconfigured callbacks.
771 // This function call may post onDisconnected and throw CAMERA_DISCONNECTED if
772 // cameraUser dies during setup.
773 deviceImpl.setRemoteDevice(cameraUser);
774 device = deviceImpl;
775 }
776
777 return device;
778 }
779
780 /**
781 * Open a connection to a camera with the given ID.
782 *
783 * <p>Use {@link #getCameraIdList} to get the list of available camera
784 * devices. Note that even if an id is listed, open may fail if the device
785 * is disconnected between the calls to {@link #getCameraIdList} and
786 * {@link #openCamera}, or if a higher-priority camera API client begins using the
787 * camera device.</p>
788 *
789 * <p>As of API level 23, devices for which the
790 * {@link AvailabilityCallback#onCameraUnavailable(String)} callback has been called due to the
791 * device being in use by a lower-priority, background camera API client can still potentially
792 * be opened by calling this method when the calling camera API client has a higher priority
793 * than the current camera API client using this device. In general, if the top, foreground
794 * activity is running within your application process, your process will be given the highest
795 * priority when accessing the camera, and this method will succeed even if the camera device is
796 * in use by another camera API client. Any lower-priority application that loses control of the
797 * camera in this way will receive an
798 * {@link android.hardware.camera2.CameraDevice.StateCallback#onDisconnected} callback.
799 * Opening the same camera ID twice in the same application will similarly cause the
800 * {@link android.hardware.camera2.CameraDevice.StateCallback#onDisconnected} callback
801 * being fired for the {@link CameraDevice} from the first open call and all ongoing tasks
802 * being droppped.</p>
803 *
804 * <p>Once the camera is successfully opened, {@link CameraDevice.StateCallback#onOpened} will
805 * be invoked with the newly opened {@link CameraDevice}. The camera device can then be set up
806 * for operation by calling {@link CameraDevice#createCaptureSession} and
807 * {@link CameraDevice#createCaptureRequest}</p>
808 *
809 * <p>Before API level 30, when the application tries to open multiple {@link CameraDevice} of
810 * different IDs and the device does not support opening such combination, either the
811 * {@link #openCamera} will fail and throw a {@link CameraAccessException} or one or more of
812 * already opened {@link CameraDevice} will be disconnected and receive
813 * {@link android.hardware.camera2.CameraDevice.StateCallback#onDisconnected} callback. Which
814 * behavior will happen depends on the device implementation and can vary on different devices.
815 * Starting in API level 30, if the device does not support the combination of cameras being
816 * opened, it is guaranteed the {@link #openCamera} call will fail and none of existing
817 * {@link CameraDevice} will be disconnected.</p>
818 *
819 * <!--
820 * <p>Since the camera device will be opened asynchronously, any asynchronous operations done
821 * on the returned CameraDevice instance will be queued up until the device startup has
822 * completed and the callback's {@link CameraDevice.StateCallback#onOpened onOpened} method is
823 * called. The pending operations are then processed in order.</p>
824 * -->
825 * <p>If the camera becomes disconnected during initialization
826 * after this function call returns,
827 * {@link CameraDevice.StateCallback#onDisconnected} with a
828 * {@link CameraDevice} in the disconnected state (and
829 * {@link CameraDevice.StateCallback#onOpened} will be skipped).</p>
830 *
831 * <p>If opening the camera device fails, then the device callback's
832 * {@link CameraDevice.StateCallback#onError onError} method will be called, and subsequent
833 * calls on the camera device will throw a {@link CameraAccessException}.</p>
834 *
835 * @param cameraId
836 * The unique identifier of the camera device to open
837 * @param callback
838 * The callback which is invoked once the camera is opened
839 * @param handler
840 * The handler on which the callback should be invoked, or
841 * {@code null} to use the current thread's {@link android.os.Looper looper}.
842 *
843 * @throws CameraAccessException if the camera is disabled by device policy,
844 * has been disconnected, is being used by a higher-priority camera API client, or the device
845 * has reached its maximal resource and cannot open this camera device.
846 *
847 * @throws IllegalArgumentException if cameraId or the callback was null,
848 * or the cameraId does not match any currently or previously available
849 * camera device returned by {@link #getCameraIdList}.
850 *
851 * @throws SecurityException if the application does not have permission to
852 * access the camera
853 *
854 * @see #getCameraIdList
855 * @see android.app.admin.DevicePolicyManager#setCameraDisabled
856 */
857 @RequiresPermission(android.Manifest.permission.CAMERA)
858 public void openCamera(@NonNull String cameraId,
859 @NonNull final CameraDevice.StateCallback callback, @Nullable Handler handler)
860 throws CameraAccessException {
861
862 openCameraForUid(cameraId, callback, CameraDeviceImpl.checkAndWrapHandler(handler),
863 USE_CALLING_UID);
864 }
865
866 /**
867 * Open a connection to a camera with the given ID.
868 *
869 * <p>The behavior of this method matches that of
870 * {@link #openCamera(String, StateCallback, Handler)}, except that it uses
871 * {@link java.util.concurrent.Executor} as an argument instead of
872 * {@link android.os.Handler}.</p>
873 *
874 * @param cameraId
875 * The unique identifier of the camera device to open
876 * @param executor
877 * The executor which will be used when invoking the callback.
878 * @param callback
879 * The callback which is invoked once the camera is opened
880 *
881 * @throws CameraAccessException if the camera is disabled by device policy,
882 * has been disconnected, or is being used by a higher-priority camera API client.
883 *
884 * @throws IllegalArgumentException if cameraId, the callback or the executor was null,
885 * or the cameraId does not match any currently or previously available
886 * camera device.
887 *
888 * @throws SecurityException if the application does not have permission to
889 * access the camera
890 *
891 * @see #getCameraIdList
892 * @see android.app.admin.DevicePolicyManager#setCameraDisabled
893 */
894 @RequiresPermission(android.Manifest.permission.CAMERA)
895 public void openCamera(@NonNull String cameraId,
896 @NonNull @CallbackExecutor Executor executor,
897 @NonNull final CameraDevice.StateCallback callback)
898 throws CameraAccessException {
899 if (executor == null) {
900 throw new IllegalArgumentException("executor was null");
901 }
902 openCameraForUid(cameraId, callback, executor, USE_CALLING_UID);
903 }
904
905 /**
906 * Open a connection to a camera with the given ID. Also specify what oom score must be offset
907 * by cameraserver for this client. This api can be useful for system
908 * components which want to assume a lower priority (for camera arbitration) than other clients
909 * which it might contend for camera devices with. Increasing the oom score of a client reduces
910 * its priority when the camera framework manages camera arbitration.
911 * Considering typical use cases:
912 *
913 * 1) oom score(apps hosting activities visible to the user) - oom score(of a foreground app)
914 * is approximately 100.
915 *
916 * 2) The oom score (process which hosts components which that are perceptible to the user /
917 * native vendor camera clients) - oom (foreground app) is approximately 200.
918 *
919 * 3) The oom score (process which is cached hosting activities not visible) - oom (foreground
920 * app) is approximately 999.
921 *
922 * <p>The behavior of this method matches that of
923 * {@link #openCamera(String, StateCallback, Handler)}, except that it uses
924 * {@link java.util.concurrent.Executor} as an argument instead of
925 * {@link android.os.Handler}.</p>
926 *
927 * @param cameraId
928 * The unique identifier of the camera device to open
929 * @param executor
930 * The executor which will be used when invoking the callback.
931 * @param callback
932 * The callback which is invoked once the camera is opened
933 * @param oomScoreOffset
934 * The value by which the oom score of this client must be offset by the camera
935 * framework in order to assist it with camera arbitration. This value must be > 0.
936 * A positive value lowers the priority of this camera client compared to what the
937 * camera framework would have originally seen.
938 *
939 * @throws CameraAccessException if the camera is disabled by device policy,
940 * has been disconnected, or is being used by a higher-priority camera API client.
941 *
942 * @throws IllegalArgumentException if cameraId, the callback or the executor was null,
943 * or the cameraId does not match any currently or previously available
944 * camera device.
945 *
946 * @throws SecurityException if the application does not have permission to
947 * access the camera
948 *
949 * @see #getCameraIdList
950 * @see android.app.admin.DevicePolicyManager#setCameraDisabled
951 *
952 * @hide
953 */
954 @SystemApi
955 @TestApi
956 @RequiresPermission(allOf = {
957 android.Manifest.permission.SYSTEM_CAMERA,
958 android.Manifest.permission.CAMERA,
959 })
960 public void openCamera(@NonNull String cameraId, int oomScoreOffset,
961 @NonNull @CallbackExecutor Executor executor,
962 @NonNull final CameraDevice.StateCallback callback) throws CameraAccessException {
963 if (executor == null) {
964 throw new IllegalArgumentException("executor was null");
965 }
966 if (oomScoreOffset < 0) {
967 throw new IllegalArgumentException(
968 "oomScoreOffset < 0, cannot increase priority of camera client");
969 }
970 openCameraForUid(cameraId, callback, executor, USE_CALLING_UID, oomScoreOffset);
971 }
972
973 /**
974 * Open a connection to a camera with the given ID, on behalf of another application
975 * specified by clientUid. Also specify the minimum oom score and process state the application
976 * should have, as seen by the cameraserver.
977 *
978 * <p>The behavior of this method matches that of {@link #openCamera}, except that it allows
979 * the caller to specify the UID to use for permission/etc verification. This can only be
980 * done by services trusted by the camera subsystem to act on behalf of applications and
981 * to forward the real UID.</p>
982 *
983 * @param clientUid
984 * The UID of the application on whose behalf the camera is being opened.
985 * Must be USE_CALLING_UID unless the caller is a trusted service.
986 * @param oomScoreOffset
987 * The minimum oom score that cameraservice must see for this client.
988 * @hide
989 */
990 public void openCameraForUid(@NonNull String cameraId,
991 @NonNull final CameraDevice.StateCallback callback, @NonNull Executor executor,
992 int clientUid, int oomScoreOffset) throws CameraAccessException {
993
994 if (cameraId == null) {
995 throw new IllegalArgumentException("cameraId was null");
996 } else if (callback == null) {
997 throw new IllegalArgumentException("callback was null");
998 }
999 if (CameraManagerGlobal.sCameraServiceDisabled) {
1000 throw new IllegalArgumentException("No cameras available on device");
1001 }
1002
1003 openCameraDeviceUserAsync(cameraId, callback, executor, clientUid, oomScoreOffset);
1004 }
1005
1006 /**
1007 * Open a connection to a camera with the given ID, on behalf of another application
1008 * specified by clientUid.
1009 *
1010 * <p>The behavior of this method matches that of {@link #openCamera}, except that it allows
1011 * the caller to specify the UID to use for permission/etc verification. This can only be
1012 * done by services trusted by the camera subsystem to act on behalf of applications and
1013 * to forward the real UID.</p>
1014 *
1015 * @param clientUid
1016 * The UID of the application on whose behalf the camera is being opened.
1017 * Must be USE_CALLING_UID unless the caller is a trusted service.
1018 *
1019 * @hide
1020 */
1021 public void openCameraForUid(@NonNull String cameraId,
1022 @NonNull final CameraDevice.StateCallback callback, @NonNull Executor executor,
1023 int clientUid) throws CameraAccessException {
1024 openCameraForUid(cameraId, callback, executor, clientUid, /*oomScoreOffset*/0);
1025 }
1026
1027 /**
1028 * Set the flash unit's torch mode of the camera of the given ID without opening the camera
1029 * device.
1030 *
1031 * <p>Use {@link #getCameraIdList} to get the list of available camera devices and use
1032 * {@link #getCameraCharacteristics} to check whether the camera device has a flash unit.
1033 * Note that even if a camera device has a flash unit, turning on the torch mode may fail
1034 * if the camera device or other camera resources needed to turn on the torch mode are in use.
1035 * </p>
1036 *
1037 * <p> If {@link #setTorchMode} is called to turn on or off the torch mode successfully,
1038 * {@link CameraManager.TorchCallback#onTorchModeChanged} will be invoked.
1039 * However, even if turning on the torch mode is successful, the application does not have the
1040 * exclusive ownership of the flash unit or the camera device. The torch mode will be turned
1041 * off and becomes unavailable when the camera device that the flash unit belongs to becomes
1042 * unavailable or when other camera resources to keep the torch on become unavailable (
1043 * {@link CameraManager.TorchCallback#onTorchModeUnavailable} will be invoked). Also,
1044 * other applications are free to call {@link #setTorchMode} to turn off the torch mode (
1045 * {@link CameraManager.TorchCallback#onTorchModeChanged} will be invoked). If the latest
1046 * application that turned on the torch mode exits, the torch mode will be turned off.
1047 *
1048 * @param cameraId
1049 * The unique identifier of the camera device that the flash unit belongs to.
1050 * @param enabled
1051 * The desired state of the torch mode for the target camera device. Set to
1052 * {@code true} to turn on the torch mode. Set to {@code false} to turn off the
1053 * torch mode.
1054 *
1055 * @throws CameraAccessException if it failed to access the flash unit.
1056 * {@link CameraAccessException#CAMERA_IN_USE} will be thrown if the camera device
1057 * is in use. {@link CameraAccessException#MAX_CAMERAS_IN_USE} will be thrown if
1058 * other camera resources needed to turn on the torch mode are in use.
1059 * {@link CameraAccessException#CAMERA_DISCONNECTED} will be thrown if camera
1060 * service is not available.
1061 *
1062 * @throws IllegalArgumentException if cameraId was null, cameraId doesn't match any currently
1063 * or previously available camera device, or the camera device doesn't have a
1064 * flash unit.
1065 */
1066 public void setTorchMode(@NonNull String cameraId, boolean enabled)
1067 throws CameraAccessException {
1068 if (CameraManagerGlobal.sCameraServiceDisabled) {
1069 throw new IllegalArgumentException("No cameras available on device");
1070 }
1071 CameraManagerGlobal.get().setTorchMode(cameraId, enabled);
1072 }
1073
1074 /**
1075 * Set the brightness level of the flashlight associated with the given cameraId in torch
1076 * mode. If the torch is OFF and torchStrength is >= 1, torch will turn ON with the
1077 * strength level specified in torchStrength.
1078 *
1079 * <p>Use
1080 * {@link android.hardware.camera2.CameraCharacteristics#FLASH_INFO_STRENGTH_MAXIMUM_LEVEL}
1081 * to check whether the camera device supports flash unit strength control or not. If this value
1082 * is greater than 1, applications can call this API to control the flashlight brightness level.
1083 * </p>
1084 *
1085 * <p>If {@link #turnOnTorchWithStrengthLevel} is called to change the brightness level of the
1086 * flash unit {@link CameraManager.TorchCallback#onTorchStrengthLevelChanged} will be invoked.
1087 * If the new desired strength level is same as previously set level, then this callback will
1088 * not be invoked.
1089 * If the torch is OFF and {@link #turnOnTorchWithStrengthLevel} is called with level >= 1,
1090 * the torch will be turned ON with that brightness level. In this case
1091 * {@link CameraManager.TorchCallback#onTorchModeChanged} will also be invoked.
1092 * </p>
1093 *
1094 * <p>When the torch is turned OFF via {@link #setTorchMode}, the flashlight brightness level
1095 * will reset to default value
1096 * {@link android.hardware.camera2.CameraCharacteristics#FLASH_INFO_STRENGTH_DEFAULT_LEVEL}
1097 * In this case the {@link CameraManager.TorchCallback#onTorchStrengthLevelChanged} will not be
1098 * invoked.
1099 * </p>
1100 *
1101 * <p>If torch is enabled via {@link #setTorchMode} after calling
1102 * {@link #turnOnTorchWithStrengthLevel} with level N then the flash unit will have the
1103 * brightness level N.
1104 * Since multiple applications are free to call {@link #setTorchMode}, when the latest
1105 * application that turned ON the torch mode exits, the torch mode will be turned OFF
1106 * and in this case the brightness level will reset to default level.
1107 * </p>
1108 *
1109 * @param cameraId
1110 * The unique identifier of the camera device that the flash unit belongs to.
1111 * @param torchStrength
1112 * The desired brightness level to be set for the flash unit in the range 1 to
1113 * {@link android.hardware.camera2.CameraCharacteristics#FLASH_INFO_STRENGTH_MAXIMUM_LEVEL}.
1114 *
1115 * @throws CameraAccessException if it failed to access the flash unit.
1116 * {@link CameraAccessException#CAMERA_IN_USE} will be thrown if the camera device
1117 * is in use. {@link CameraAccessException#MAX_CAMERAS_IN_USE} will be thrown if
1118 * other camera resources needed to turn on the torch mode are in use.
1119 * {@link CameraAccessException#CAMERA_DISCONNECTED} will be thrown if camera
1120 * service is not available.
1121 * @throws IllegalArgumentException if cameraId was null, cameraId doesn't match any currently
1122 * or previously available camera device, the camera device doesn't have a
1123 * flash unit or if torchStrength is not within the range i.e. is greater than
1124 * the maximum level
1125 * {@link android.hardware.camera2.CameraCharacteristics#FLASH_INFO_STRENGTH_MAXIMUM_LEVEL}
1126 * or <= 0.
1127 *
1128 */
1129 public void turnOnTorchWithStrengthLevel(@NonNull String cameraId, int torchStrength)
1130 throws CameraAccessException {
1131 if (CameraManagerGlobal.sCameraServiceDisabled) {
1132 throw new IllegalArgumentException("No camera available on device");
1133 }
1134 CameraManagerGlobal.get().turnOnTorchWithStrengthLevel(cameraId, torchStrength);
1135 }
1136
1137 /**
1138 * Returns the brightness level of the flash unit associated with the cameraId.
1139 *
1140 * @param cameraId
1141 * The unique identifier of the camera device that the flash unit belongs to.
1142 * @return The brightness level of the flash unit associated with cameraId.
1143 * When the torch is turned OFF, the strength level will reset to a default level
1144 * {@link android.hardware.camera2.CameraCharacteristics#FLASH_INFO_STRENGTH_DEFAULT_LEVEL}.
1145 * In this case the return value will be
1146 * {@link android.hardware.camera2.CameraCharacteristics#FLASH_INFO_STRENGTH_DEFAULT_LEVEL}
1147 * rather than 0.
1148 *
1149 * @throws CameraAccessException if it failed to access the flash unit.
1150 * @throws IllegalArgumentException if cameraId was null, cameraId doesn't match any currently
1151 * or previously available camera device, or the camera device doesn't have a
1152 * flash unit.
1153 *
1154 */
1155 public int getTorchStrengthLevel(@NonNull String cameraId)
1156 throws CameraAccessException {
1157 if (CameraManagerGlobal.sCameraServiceDisabled) {
1158 throw new IllegalArgumentException("No camera available on device.");
1159 }
1160 return CameraManagerGlobal.get().getTorchStrengthLevel(cameraId);
1161 }
1162
1163 private static boolean shouldOverrideToPortrait() {
1164 return CompatChanges.isChangeEnabled(OVERRIDE_FRONT_CAMERA_APP_COMPAT)
1165 && CameraManagerGlobal.sLandscapeToPortrait;
1166 }
1167
1168 /**
1169 * A callback for camera devices becoming available or unavailable to open.
1170 *
1171 * <p>Cameras become available when they are no longer in use, or when a new
1172 * removable camera is connected. They become unavailable when some
1173 * application or service starts using a camera, or when a removable camera
1174 * is disconnected.</p>
1175 *
1176 * <p>Extend this callback and pass an instance of the subclass to
1177 * {@link CameraManager#registerAvailabilityCallback} to be notified of such availability
1178 * changes.</p>
1179 *
1180 * @see #registerAvailabilityCallback
1181 */
1182 public static abstract class AvailabilityCallback {
1183
1184 /**
1185 * A new camera has become available to use.
1186 *
1187 * <p>The default implementation of this method does nothing.</p>
1188 *
1189 * @param cameraId The unique identifier of the new camera.
1190 */
1191 public void onCameraAvailable(@NonNull String cameraId) {
1192 // default empty implementation
1193 }
1194
1195 /**
1196 * A previously-available camera has become unavailable for use.
1197 *
1198 * <p>If an application had an active CameraDevice instance for the
1199 * now-disconnected camera, that application will receive a
1200 * {@link CameraDevice.StateCallback#onDisconnected disconnection error}.</p>
1201 *
1202 * <p>The default implementation of this method does nothing.</p>
1203 *
1204 * @param cameraId The unique identifier of the disconnected camera.
1205 */
1206 public void onCameraUnavailable(@NonNull String cameraId) {
1207 // default empty implementation
1208 }
1209
1210 /**
1211 * Called whenever camera access priorities change.
1212 *
1213 * <p>Notification that camera access priorities have changed and the camera may
1214 * now be openable. An application that was previously denied camera access due to
1215 * a higher-priority user already using the camera, or that was disconnected from an
1216 * active camera session due to a higher-priority user trying to open the camera,
1217 * should try to open the camera again if it still wants to use it. Note that
1218 * multiple applications may receive this callback at the same time, and only one of
1219 * them will succeed in opening the camera in practice, depending on exact access
1220 * priority levels and timing. This method is useful in cases where multiple
1221 * applications may be in the resumed state at the same time, and the user switches
1222 * focus between them, or if the current camera-using application moves between
1223 * full-screen and Picture-in-Picture (PiP) states. In such cases, the camera
1224 * available/unavailable callbacks will not be invoked, but another application may
1225 * now have higher priority for camera access than the current camera-using
1226 * application.</p>
1227 *
1228 * <p>The default implementation of this method does nothing.</p>
1229 *
1230 */
1231 public void onCameraAccessPrioritiesChanged() {
1232 // default empty implementation
1233 }
1234
1235 /**
1236 * A physical camera has become available for use again.
1237 *
1238 * <p>By default, all of the physical cameras of a logical multi-camera are
1239 * available, so {@link #onPhysicalCameraAvailable} is not called for any of the physical
1240 * cameras of a logical multi-camera, when {@link #onCameraAvailable} for the logical
1241 * multi-camera is invoked. However, if some specific physical cameras are unavailable
1242 * to begin with, {@link #onPhysicalCameraUnavailable} may be invoked after
1243 * {@link #onCameraAvailable}.</p>
1244 *
1245 * <p>Limitation: Opening a logical camera disables the {@link #onPhysicalCameraAvailable}
1246 * and {@link #onPhysicalCameraUnavailable} callbacks for its physical cameras. For example,
1247 * if app A opens the camera device:</p>
1248 *
1249 * <ul>
1250 *
1251 * <li>All apps subscribing to ActivityCallback get {@link #onCameraUnavailable}.</li>
1252 *
1253 * <li>No app (including app A) subscribing to ActivityCallback gets
1254 * {@link #onPhysicalCameraAvailable} or {@link #onPhysicalCameraUnavailable}, because
1255 * the logical camera is unavailable (some app is using it).</li>
1256 *
1257 * </ul>
1258 *
1259 * <p>The default implementation of this method does nothing.</p>
1260 *
1261 * @param cameraId The unique identifier of the logical multi-camera.
1262 * @param physicalCameraId The unique identifier of the physical camera.
1263 *
1264 * @see #onCameraAvailable
1265 * @see #onPhysicalCameraUnavailable
1266 */
1267 public void onPhysicalCameraAvailable(@NonNull String cameraId,
1268 @NonNull String physicalCameraId) {
1269 // default empty implementation
1270 }
1271
1272 /**
1273 * A previously-available physical camera has become unavailable for use.
1274 *
1275 * <p>By default, all of the physical cameras of a logical multi-camera are
1276 * unavailable if the logical camera itself is unavailable.
1277 * No availability callbacks will be called for any of the physical
1278 * cameras of its parent logical multi-camera, when {@link #onCameraUnavailable} for
1279 * the logical multi-camera is invoked.</p>
1280 *
1281 * <p>Limitation: Opening a logical camera disables the {@link #onPhysicalCameraAvailable}
1282 * and {@link #onPhysicalCameraUnavailable} callbacks for its physical cameras. For example,
1283 * if app A opens the camera device:</p>
1284 *
1285 * <ul>
1286 *
1287 * <li>All apps subscribing to ActivityCallback get {@link #onCameraUnavailable}.</li>
1288 *
1289 * <li>No app (including app A) subscribing to ActivityCallback gets
1290 * {@link #onPhysicalCameraAvailable} or {@link #onPhysicalCameraUnavailable}, because
1291 * the logical camera is unavailable (some app is using it).</li>
1292 *
1293 * </ul>
1294 *
1295 * <p>The default implementation of this method does nothing.</p>
1296 *
1297 * @param cameraId The unique identifier of the logical multi-camera.
1298 * @param physicalCameraId The unique identifier of the physical camera.
1299 *
1300 * @see #onCameraAvailable
1301 * @see #onPhysicalCameraAvailable
1302 */
1303 public void onPhysicalCameraUnavailable(@NonNull String cameraId,
1304 @NonNull String physicalCameraId) {
1305 // default empty implementation
1306 }
1307
1308 /**
1309 * A camera device has been opened by an application.
1310 *
1311 * <p>The default implementation of this method does nothing.</p>
1312 * android.Manifest.permission.CAMERA_OPEN_CLOSE_LISTENER is required to receive this
1313 * callback
1314 * @param cameraId The unique identifier of the camera opened.
1315 * @param packageId The package Id of the application opening the camera.
1316 *
1317 * @see #onCameraClosed
1318 * @hide
1319 */
1320 @SystemApi
1321 @TestApi
1322 @RequiresPermission(android.Manifest.permission.CAMERA_OPEN_CLOSE_LISTENER)
1323 public void onCameraOpened(@NonNull String cameraId, @NonNull String packageId) {
1324 // default empty implementation
1325 }
1326
1327 /**
1328 * A previously-opened camera has been closed.
1329 *
1330 * <p>The default implementation of this method does nothing.</p>
1331 * android.Manifest.permission.CAMERA_OPEN_CLOSE_LISTENER is required to receive this
1332 * callback.
1333 * @param cameraId The unique identifier of the closed camera.
1334 * @hide
1335 */
1336 @SystemApi
1337 @TestApi
1338 @RequiresPermission(android.Manifest.permission.CAMERA_OPEN_CLOSE_LISTENER)
1339 public void onCameraClosed(@NonNull String cameraId) {
1340 // default empty implementation
1341 }
1342 }
1343
1344 /**
1345 * A callback for camera flash torch modes becoming unavailable, disabled, or enabled.
1346 *
1347 * <p>The torch mode becomes unavailable when the camera device it belongs to becomes
1348 * unavailable or other camera resources it needs become busy due to other higher priority
1349 * camera activities. The torch mode becomes disabled when it was turned off or when the camera
1350 * device it belongs to is no longer in use and other camera resources it needs are no longer
1351 * busy. A camera's torch mode is turned off when an application calls {@link #setTorchMode} to
1352 * turn off the camera's torch mode, or when an application turns on another camera's torch mode
1353 * if keeping multiple torch modes on simultaneously is not supported. The torch mode becomes
1354 * enabled when it is turned on via {@link #setTorchMode}.</p>
1355 *
1356 * <p>The torch mode is available to set via {@link #setTorchMode} only when it's in a disabled
1357 * or enabled state.</p>
1358 *
1359 * <p>Extend this callback and pass an instance of the subclass to
1360 * {@link CameraManager#registerTorchCallback} to be notified of such status changes.
1361 * </p>
1362 *
1363 * @see #registerTorchCallback
1364 */
1365 public static abstract class TorchCallback {
1366 /**
1367 * A camera's torch mode has become unavailable to set via {@link #setTorchMode}.
1368 *
1369 * <p>If torch mode was previously turned on by calling {@link #setTorchMode}, it will be
1370 * turned off before {@link CameraManager.TorchCallback#onTorchModeUnavailable} is
1371 * invoked. {@link #setTorchMode} will fail until the torch mode has entered a disabled or
1372 * enabled state again.</p>
1373 *
1374 * <p>The default implementation of this method does nothing.</p>
1375 *
1376 * @param cameraId The unique identifier of the camera whose torch mode has become
1377 * unavailable.
1378 */
1379 public void onTorchModeUnavailable(@NonNull String cameraId) {
1380 // default empty implementation
1381 }
1382
1383 /**
1384 * A camera's torch mode has become enabled or disabled and can be changed via
1385 * {@link #setTorchMode}.
1386 *
1387 * <p>The default implementation of this method does nothing.</p>
1388 *
1389 * @param cameraId The unique identifier of the camera whose torch mode has been changed.
1390 *
1391 * @param enabled The state that the torch mode of the camera has been changed to.
1392 * {@code true} when the torch mode has become on and available to be turned
1393 * off. {@code false} when the torch mode has becomes off and available to
1394 * be turned on.
1395 */
1396 public void onTorchModeChanged(@NonNull String cameraId, boolean enabled) {
1397 // default empty implementation
1398 }
1399
1400 /**
1401 * A camera's flash unit brightness level has been changed in torch mode via
1402 * {@link #turnOnTorchWithStrengthLevel}. When the torch is turned OFF, this
1403 * callback will not be triggered even though the torch strength level resets to
1404 * default value
1405 * {@link android.hardware.camera2.CameraCharacteristics#FLASH_INFO_STRENGTH_DEFAULT_LEVEL}
1406 *
1407 * <p>The default implementation of this method does nothing.</p>
1408 *
1409 * @param cameraId The unique identifier of the camera whose flash unit brightness level has
1410 * been changed.
1411 *
1412 * @param newStrengthLevel The brightness level of the flash unit that has been changed to.
1413 */
1414 public void onTorchStrengthLevelChanged(@NonNull String cameraId, int newStrengthLevel) {
1415 // default empty implementation
1416 }
1417 }
1418
1419 /**
1420 * Convert ServiceSpecificExceptions and Binder RemoteExceptions from camera binder interfaces
1421 * into the correct public exceptions.
1422 *
1423 * @hide
1424 */
1425 public static void throwAsPublicException(Throwable t) throws CameraAccessException {
1426 if (t instanceof ServiceSpecificException) {
1427 ServiceSpecificException e = (ServiceSpecificException) t;
1428 int reason = CameraAccessException.CAMERA_ERROR;
1429 switch(e.errorCode) {
1430 case ICameraService.ERROR_DISCONNECTED:
1431 reason = CameraAccessException.CAMERA_DISCONNECTED;
1432 break;
1433 case ICameraService.ERROR_DISABLED:
1434 reason = CameraAccessException.CAMERA_DISABLED;
1435 break;
1436 case ICameraService.ERROR_CAMERA_IN_USE:
1437 reason = CameraAccessException.CAMERA_IN_USE;
1438 break;
1439 case ICameraService.ERROR_MAX_CAMERAS_IN_USE:
1440 reason = CameraAccessException.MAX_CAMERAS_IN_USE;
1441 break;
1442 case ICameraService.ERROR_DEPRECATED_HAL:
1443 reason = CameraAccessException.CAMERA_DEPRECATED_HAL;
1444 break;
1445 case ICameraService.ERROR_ILLEGAL_ARGUMENT:
1446 case ICameraService.ERROR_ALREADY_EXISTS:
1447 throw new IllegalArgumentException(e.getMessage(), e);
1448 case ICameraService.ERROR_PERMISSION_DENIED:
1449 throw new SecurityException(e.getMessage(), e);
1450 case ICameraService.ERROR_TIMED_OUT:
1451 case ICameraService.ERROR_INVALID_OPERATION:
1452 default:
1453 reason = CameraAccessException.CAMERA_ERROR;
1454 }
1455 throw new CameraAccessException(reason, e.getMessage(), e);
1456 } else if (t instanceof DeadObjectException) {
1457 throw new CameraAccessException(CameraAccessException.CAMERA_DISCONNECTED,
1458 "Camera service has died unexpectedly",
1459 t);
1460 } else if (t instanceof RemoteException) {
1461 throw new UnsupportedOperationException("An unknown RemoteException was thrown" +
1462 " which should never happen.", t);
1463 } else if (t instanceof RuntimeException) {
1464 RuntimeException e = (RuntimeException) t;
1465 throw e;
1466 }
1467 }
1468
1469 /**
1470 * Queries the camera service if a cameraId is a hidden physical camera that belongs to a
1471 * logical camera device.
1472 *
1473 * A hidden physical camera is a camera that cannot be opened by the application. But it
1474 * can be used as part of a logical camera.
1475 *
1476 * @param cameraId a non-{@code null} camera identifier
1477 * @return {@code true} if cameraId is a hidden physical camera device
1478 *
1479 * @hide
1480 */
1481 public static boolean isHiddenPhysicalCamera(String cameraId) {
1482 try {
1483 ICameraService cameraService = CameraManagerGlobal.get().getCameraService();
1484 // If no camera service, no support
1485 if (cameraService == null) return false;
1486
1487 return cameraService.isHiddenPhysicalCamera(cameraId);
1488 } catch (RemoteException e) {
1489 // Camera service is now down, no support for any API level
1490 }
1491 return false;
1492 }
1493
1494 /**
1495 * Inject the external camera to replace the internal camera session.
1496 *
1497 * <p>If injecting the external camera device fails, then the injection callback's
1498 * {@link CameraInjectionSession.InjectionStatusCallback#onInjectionError
1499 * onInjectionError} method will be called.</p>
1500 *
1501 * @param packageName It scopes the injection to a particular app.
1502 * @param internalCamId The id of one of the physical or logical cameras on the phone.
1503 * @param externalCamId The id of one of the remote cameras that are provided by the dynamic
1504 * camera HAL.
1505 * @param executor The executor which will be used when invoking the callback.
1506 * @param callback The callback which is invoked once the external camera is injected.
1507 *
1508 * @throws CameraAccessException If the camera device has been disconnected.
1509 * {@link CameraAccessException#CAMERA_DISCONNECTED} will be
1510 * thrown if camera service is not available.
1511 * @throws SecurityException If the specific application that can cast to external
1512 * devices does not have permission to inject the external
1513 * camera.
1514 * @throws IllegalArgumentException If cameraId doesn't match any currently or previously
1515 * available camera device or some camera functions might not
1516 * work properly or the injection camera runs into a fatal
1517 * error.
1518 * @hide
1519 */
1520 @RequiresPermission(android.Manifest.permission.CAMERA_INJECT_EXTERNAL_CAMERA)
1521 public void injectCamera(@NonNull String packageName, @NonNull String internalCamId,
1522 @NonNull String externalCamId, @NonNull @CallbackExecutor Executor executor,
1523 @NonNull CameraInjectionSession.InjectionStatusCallback callback)
1524 throws CameraAccessException, SecurityException,
1525 IllegalArgumentException {
1526 if (CameraManagerGlobal.sCameraServiceDisabled) {
1527 throw new IllegalArgumentException("No cameras available on device");
1528 }
1529 ICameraService cameraService = CameraManagerGlobal.get().getCameraService();
1530 if (cameraService == null) {
1531 throw new CameraAccessException(CameraAccessException.CAMERA_DISCONNECTED,
1532 "Camera service is currently unavailable");
1533 }
1534 synchronized (mLock) {
1535 try {
1536 CameraInjectionSessionImpl injectionSessionImpl =
1537 new CameraInjectionSessionImpl(callback, executor);
1538 ICameraInjectionCallback cameraInjectionCallback =
1539 injectionSessionImpl.getCallback();
1540 ICameraInjectionSession injectionSession = cameraService.injectCamera(packageName,
1541 internalCamId, externalCamId, cameraInjectionCallback);
1542 injectionSessionImpl.setRemoteInjectionSession(injectionSession);
1543 } catch (ServiceSpecificException e) {
1544 throwAsPublicException(e);
1545 } catch (RemoteException e) {
1546 // Camera service died - act as if it's a CAMERA_DISCONNECTED case
1547 ServiceSpecificException sse = new ServiceSpecificException(
1548 ICameraService.ERROR_DISCONNECTED,
1549 "Camera service is currently unavailable");
1550 throwAsPublicException(sse);
1551 }
1552 }
1553 }
1554
1555 /**
1556 * A per-process global camera manager instance, to retain a connection to the camera service,
1557 * and to distribute camera availability notices to API-registered callbacks
1558 */
1559 private static final class CameraManagerGlobal extends ICameraServiceListener.Stub
1560 implements IBinder.DeathRecipient {
1561
1562 private static final String TAG = "CameraManagerGlobal";
1563 private final boolean DEBUG = false;
1564
1565 private final int CAMERA_SERVICE_RECONNECT_DELAY_MS = 1000;
1566
1567 // Singleton instance
1568 private static final CameraManagerGlobal gCameraManager =
1569 new CameraManagerGlobal();
1570
1571 /**
1572 * This must match the ICameraService definition
1573 */
1574 private static final String CAMERA_SERVICE_BINDER_NAME = "media.camera";
1575
1576 private final ScheduledExecutorService mScheduler = Executors.newScheduledThreadPool(1);
1577 // Camera ID -> Status map
1578 private final ArrayMap<String, Integer> mDeviceStatus = new ArrayMap<String, Integer>();
1579 // Camera ID -> (physical camera ID -> Status map)
1580 private final ArrayMap<String, ArrayList<String>> mUnavailablePhysicalDevices =
1581 new ArrayMap<String, ArrayList<String>>();
1582 // Opened Camera ID -> apk name map
1583 private final ArrayMap<String, String> mOpenedDevices = new ArrayMap<String, String>();
1584
1585 private final Set<Set<String>> mConcurrentCameraIdCombinations =
1586 new ArraySet<Set<String>>();
1587
1588 // Registered availablility callbacks and their executors
1589 private final ArrayMap<AvailabilityCallback, Executor> mCallbackMap =
1590 new ArrayMap<AvailabilityCallback, Executor>();
1591
1592 // torch client binder to set the torch mode with.
1593 private Binder mTorchClientBinder = new Binder();
1594
1595 // Camera ID -> Torch status map
1596 private final ArrayMap<String, Integer> mTorchStatus = new ArrayMap<String, Integer>();
1597
1598 // Registered torch callbacks and their executors
1599 private final ArrayMap<TorchCallback, Executor> mTorchCallbackMap =
1600 new ArrayMap<TorchCallback, Executor>();
1601
1602 private final Object mLock = new Object();
1603
1604 // Access only through getCameraService to deal with binder death
1605 private ICameraService mCameraService;
1606 private boolean mHasOpenCloseListenerPermission = false;
1607
1608 // Singleton, don't allow construction
1609 private CameraManagerGlobal() { }
1610
1611 public static final boolean sCameraServiceDisabled =
1612 SystemProperties.getBoolean("config.disable_cameraservice", false);
1613
1614 public static final boolean sLandscapeToPortrait =
1615 SystemProperties.getBoolean(LANDSCAPE_TO_PORTRAIT_PROP, false);
1616
1617 public static CameraManagerGlobal get() {
1618 return gCameraManager;
1619 }
1620
1621 @Override
1622 public IBinder asBinder() {
1623 return this;
1624 }
1625
1626 /**
1627 * Return a best-effort ICameraService.
1628 *
1629 * <p>This will be null if the camera service is not currently available. If the camera
1630 * service has died since the last use of the camera service, will try to reconnect to the
1631 * service.</p>
1632 */
1633 public ICameraService getCameraService() {
1634 synchronized(mLock) {
1635 connectCameraServiceLocked();
1636 if (mCameraService == null && !sCameraServiceDisabled) {
1637 Log.e(TAG, "Camera service is unavailable");
1638 }
1639 return mCameraService;
1640 }
1641 }
1642
1643 /**
1644 * Connect to the camera service if it's available, and set up listeners.
1645 * If the service is already connected, do nothing.
1646 *
1647 * <p>Sets mCameraService to a valid pointer or null if the connection does not succeed.</p>
1648 */
1649 private void connectCameraServiceLocked() {
1650 // Only reconnect if necessary
1651 if (mCameraService != null || sCameraServiceDisabled) return;
1652
1653 Log.i(TAG, "Connecting to camera service");
1654
1655 IBinder cameraServiceBinder = ServiceManager.getService(CAMERA_SERVICE_BINDER_NAME);
1656 if (cameraServiceBinder == null) {
1657 // Camera service is now down, leave mCameraService as null
1658 return;
1659 }
1660 try {
1661 cameraServiceBinder.linkToDeath(this, /*flags*/ 0);
1662 } catch (RemoteException e) {
1663 // Camera service is now down, leave mCameraService as null
1664 return;
1665 }
1666
1667 ICameraService cameraService = ICameraService.Stub.asInterface(cameraServiceBinder);
1668
1669 try {
1670 CameraMetadataNative.setupGlobalVendorTagDescriptor();
1671 } catch (ServiceSpecificException e) {
1672 handleRecoverableSetupErrors(e);
1673 }
1674
1675 try {
1676 CameraStatus[] cameraStatuses = cameraService.addListener(this);
1677 for (CameraStatus c : cameraStatuses) {
1678 onStatusChangedLocked(c.status, c.cameraId);
1679
1680 if (c.unavailablePhysicalCameras != null) {
1681 for (String unavailPhysicalCamera : c.unavailablePhysicalCameras) {
1682 onPhysicalCameraStatusChangedLocked(
1683 ICameraServiceListener.STATUS_NOT_PRESENT,
1684 c.cameraId, unavailPhysicalCamera);
1685 }
1686 }
1687
1688 if (mHasOpenCloseListenerPermission &&
1689 c.status == ICameraServiceListener.STATUS_NOT_AVAILABLE &&
1690 !c.clientPackage.isEmpty()) {
1691 onCameraOpenedLocked(c.cameraId, c.clientPackage);
1692 }
1693 }
1694 mCameraService = cameraService;
1695 } catch(ServiceSpecificException e) {
1696 // Unexpected failure
1697 throw new IllegalStateException("Failed to register a camera service listener", e);
1698 } catch (RemoteException e) {
1699 // Camera service is now down, leave mCameraService as null
1700 }
1701
1702 try {
1703 ConcurrentCameraIdCombination[] cameraIdCombinations =
1704 cameraService.getConcurrentCameraIds();
1705 for (ConcurrentCameraIdCombination comb : cameraIdCombinations) {
1706 mConcurrentCameraIdCombinations.add(comb.getConcurrentCameraIdCombination());
1707 }
1708 } catch (ServiceSpecificException e) {
1709 // Unexpected failure
1710 throw new IllegalStateException("Failed to get concurrent camera id combinations",
1711 e);
1712 } catch (RemoteException e) {
1713 // Camera service died in all probability
1714 }
1715 }
1716
1717 private String[] extractCameraIdListLocked() {
1718 String[] cameraIds = null;
1719 int idCount = 0;
1720 for (int i = 0; i < mDeviceStatus.size(); i++) {
1721 int status = mDeviceStatus.valueAt(i);
1722 if (status == ICameraServiceListener.STATUS_NOT_PRESENT
1723 || status == ICameraServiceListener.STATUS_ENUMERATING) continue;
1724 idCount++;
1725 }
1726 cameraIds = new String[idCount];
1727 idCount = 0;
1728 for (int i = 0; i < mDeviceStatus.size(); i++) {
1729 int status = mDeviceStatus.valueAt(i);
1730 if (status == ICameraServiceListener.STATUS_NOT_PRESENT
1731 || status == ICameraServiceListener.STATUS_ENUMERATING) continue;
1732 cameraIds[idCount] = mDeviceStatus.keyAt(i);
1733 idCount++;
1734 }
1735 return cameraIds;
1736 }
1737
1738 private Set<Set<String>> extractConcurrentCameraIdListLocked() {
1739 Set<Set<String>> concurrentCameraIds = new ArraySet<Set<String>>();
1740 for (Set<String> cameraIds : mConcurrentCameraIdCombinations) {
1741 Set<String> extractedCameraIds = new ArraySet<String>();
1742 for (String cameraId : cameraIds) {
1743 // if the camera id status is NOT_PRESENT or ENUMERATING; skip the device.
1744 // TODO: Would a device status NOT_PRESENT ever be in the map ? it gets removed
1745 // in the callback anyway.
1746 Integer status = mDeviceStatus.get(cameraId);
1747 if (status == null) {
1748 // camera id not present
1749 continue;
1750 }
1751 if (status == ICameraServiceListener.STATUS_ENUMERATING
1752 || status == ICameraServiceListener.STATUS_NOT_PRESENT) {
1753 continue;
1754 }
1755 extractedCameraIds.add(cameraId);
1756 }
1757 concurrentCameraIds.add(extractedCameraIds);
1758 }
1759 return concurrentCameraIds;
1760 }
1761
1762 private static void sortCameraIds(String[] cameraIds) {
1763 // The sort logic must match the logic in
1764 // libcameraservice/common/CameraProviderManager.cpp::getAPI1CompatibleCameraDeviceIds
1765 Arrays.sort(cameraIds, new Comparator<String>() {
1766 @Override
1767 public int compare(String s1, String s2) {
1768 int s1Int = 0, s2Int = 0;
1769 try {
1770 s1Int = Integer.parseInt(s1);
1771 } catch (NumberFormatException e) {
1772 s1Int = -1;
1773 }
1774
1775 try {
1776 s2Int = Integer.parseInt(s2);
1777 } catch (NumberFormatException e) {
1778 s2Int = -1;
1779 }
1780
1781 // Uint device IDs first
1782 if (s1Int >= 0 && s2Int >= 0) {
1783 return s1Int - s2Int;
1784 } else if (s1Int >= 0) {
1785 return -1;
1786 } else if (s2Int >= 0) {
1787 return 1;
1788 } else {
1789 // Simple string compare if both id are not uint
1790 return s1.compareTo(s2);
1791 }
1792 }});
1793
1794 }
1795
1796 public static boolean cameraStatusesContains(CameraStatus[] cameraStatuses, String id) {
1797 for (CameraStatus c : cameraStatuses) {
1798 if (c.cameraId.equals(id)) {
1799 return true;
1800 }
1801 }
1802 return false;
1803 }
1804
1805 public String[] getCameraIdListNoLazy() {
1806 if (sCameraServiceDisabled) {
1807 return new String[] {};
1808 }
1809
1810 CameraStatus[] cameraStatuses;
1811 ICameraServiceListener.Stub testListener = new ICameraServiceListener.Stub() {
1812 @Override
1813 public void onStatusChanged(int status, String id) throws RemoteException {
1814 }
1815 @Override
1816 public void onPhysicalCameraStatusChanged(int status,
1817 String id, String physicalId) throws RemoteException {
1818 }
1819 @Override
1820 public void onTorchStatusChanged(int status, String id) throws RemoteException {
1821 }
1822 @Override
1823 public void onTorchStrengthLevelChanged(String id, int newStrengthLevel)
1824 throws RemoteException {
1825 }
1826 @Override
1827 public void onCameraAccessPrioritiesChanged() {
1828 }
1829 @Override
1830 public void onCameraOpened(String id, String clientPackageId) {
1831 }
1832 @Override
1833 public void onCameraClosed(String id) {
1834 }};
1835
1836 String[] cameraIds = null;
1837 synchronized (mLock) {
1838 connectCameraServiceLocked();
1839 try {
1840 // The purpose of the addListener, removeListener pair here is to get a fresh
1841 // list of camera ids from cameraserver. We do this since for in test processes,
1842 // changes can happen w.r.t non-changeable permissions (eg: SYSTEM_CAMERA
1843 // permissions can be effectively changed by calling
1844 // adopt(drop)ShellPermissionIdentity()).
1845 // Camera devices, which have their discovery affected by these permission
1846 // changes, will not have clients get callbacks informing them about these
1847 // devices going offline (in real world scenarios, these permissions aren't
1848 // changeable). Future calls to getCameraIdList() will reflect the changes in
1849 // the camera id list after getCameraIdListNoLazy() is called.
1850 // We need to remove the torch ids which may have been associated with the
1851 // devices removed as well. This is the same situation.
1852 cameraStatuses = mCameraService.addListener(testListener);
1853 mCameraService.removeListener(testListener);
1854 for (CameraStatus c : cameraStatuses) {
1855 onStatusChangedLocked(c.status, c.cameraId);
1856 }
1857 Set<String> deviceCameraIds = mDeviceStatus.keySet();
1858 ArrayList<String> deviceIdsToRemove = new ArrayList<String>();
1859 for (String deviceCameraId : deviceCameraIds) {
1860 // Its possible that a device id was removed without a callback notifying
1861 // us. This may happen in case a process 'drops' system camera permissions
1862 // (even though the permission isn't a changeable one, tests may call
1863 // adoptShellPermissionIdentity() and then dropShellPermissionIdentity().
1864 if (!cameraStatusesContains(cameraStatuses, deviceCameraId)) {
1865 deviceIdsToRemove.add(deviceCameraId);
1866 }
1867 }
1868 for (String id : deviceIdsToRemove) {
1869 onStatusChangedLocked(ICameraServiceListener.STATUS_NOT_PRESENT, id);
1870 mTorchStatus.remove(id);
1871 }
1872 } catch (ServiceSpecificException e) {
1873 // Unexpected failure
1874 throw new IllegalStateException("Failed to register a camera service listener",
1875 e);
1876 } catch (RemoteException e) {
1877 // Camera service is now down, leave mCameraService as null
1878 }
1879 cameraIds = extractCameraIdListLocked();
1880 }
1881 sortCameraIds(cameraIds);
1882 return cameraIds;
1883 }
1884
1885 /**
1886 * Get a list of all camera IDs that are at least PRESENT; ignore devices that are
1887 * NOT_PRESENT or ENUMERATING, since they cannot be used by anyone.
1888 */
1889 public String[] getCameraIdList() {
1890 String[] cameraIds = null;
1891 synchronized (mLock) {
1892 // Try to make sure we have an up-to-date list of camera devices.
1893 connectCameraServiceLocked();
1894 cameraIds = extractCameraIdListLocked();
1895 }
1896 sortCameraIds(cameraIds);
1897 return cameraIds;
1898 }
1899
1900 public @NonNull Set<Set<String>> getConcurrentCameraIds() {
1901 Set<Set<String>> concurrentStreamingCameraIds = null;
1902 synchronized (mLock) {
1903 // Try to make sure we have an up-to-date list of concurrent camera devices.
1904 connectCameraServiceLocked();
1905 concurrentStreamingCameraIds = extractConcurrentCameraIdListLocked();
1906 }
1907 // TODO: Some sort of sorting ?
1908 return concurrentStreamingCameraIds;
1909 }
1910
1911 public boolean isConcurrentSessionConfigurationSupported(
1912 @NonNull Map<String, SessionConfiguration> cameraIdsAndSessionConfigurations,
1913 int targetSdkVersion) throws CameraAccessException {
1914
1915 if (cameraIdsAndSessionConfigurations == null) {
1916 throw new IllegalArgumentException("cameraIdsAndSessionConfigurations was null");
1917 }
1918
1919 int size = cameraIdsAndSessionConfigurations.size();
1920 if (size == 0) {
1921 throw new IllegalArgumentException("camera id and session combination is empty");
1922 }
1923
1924 synchronized (mLock) {
1925 // Go through all the elements and check if the camera ids are valid at least /
1926 // belong to one of the combinations returned by getConcurrentCameraIds()
1927 boolean subsetFound = false;
1928 for (Set<String> combination : mConcurrentCameraIdCombinations) {
1929 if (combination.containsAll(cameraIdsAndSessionConfigurations.keySet())) {
1930 subsetFound = true;
1931 }
1932 }
1933 if (!subsetFound) {
1934 Log.v(TAG, "isConcurrentSessionConfigurationSupported called with a subset of"
1935 + "camera ids not returned by getConcurrentCameraIds");
1936 return false;
1937 }
1938 CameraIdAndSessionConfiguration [] cameraIdsAndConfigs =
1939 new CameraIdAndSessionConfiguration[size];
1940 int i = 0;
1941 for (Map.Entry<String, SessionConfiguration> pair :
1942 cameraIdsAndSessionConfigurations.entrySet()) {
1943 cameraIdsAndConfigs[i] =
1944 new CameraIdAndSessionConfiguration(pair.getKey(), pair.getValue());
1945 i++;
1946 }
1947 try {
1948 return mCameraService.isConcurrentSessionConfigurationSupported(
1949 cameraIdsAndConfigs, targetSdkVersion);
1950 } catch (ServiceSpecificException e) {
1951 throwAsPublicException(e);
1952 } catch (RemoteException e) {
1953 // Camera service died - act as if the camera was disconnected
1954 throw new CameraAccessException(CameraAccessException.CAMERA_DISCONNECTED,
1955 "Camera service is currently unavailable", e);
1956 }
1957 }
1958
1959 return false;
1960 }
1961
1962 /**
1963 * Helper function to find out if a camera id is in the set of combinations returned by
1964 * getConcurrentCameraIds()
1965 * @param cameraId the unique identifier of the camera device to query
1966 * @return Whether the camera device was found in the set of combinations returned by
1967 * getConcurrentCameraIds
1968 */
1969 public boolean cameraIdHasConcurrentStreamsLocked(String cameraId) {
1970 if (!mDeviceStatus.containsKey(cameraId)) {
1971 // physical camera ids aren't advertised in concurrent camera id combinations.
1972 if (DEBUG) {
1973 Log.v(TAG, " physical camera id " + cameraId + " is hidden." +
1974 " Available logical camera ids : " + mDeviceStatus.toString());
1975 }
1976 return false;
1977 }
1978 for (Set<String> comb : mConcurrentCameraIdCombinations) {
1979 if (comb.contains(cameraId)) {
1980 return true;
1981 }
1982 }
1983 return false;
1984 }
1985
1986 public void setTorchMode(String cameraId, boolean enabled) throws CameraAccessException {
1987 synchronized(mLock) {
1988
1989 if (cameraId == null) {
1990 throw new IllegalArgumentException("cameraId was null");
1991 }
1992
1993 ICameraService cameraService = getCameraService();
1994 if (cameraService == null) {
1995 throw new CameraAccessException(CameraAccessException.CAMERA_DISCONNECTED,
1996 "Camera service is currently unavailable");
1997 }
1998
1999 try {
2000 cameraService.setTorchMode(cameraId, enabled, mTorchClientBinder);
2001 } catch(ServiceSpecificException e) {
2002 throwAsPublicException(e);
2003 } catch (RemoteException e) {
2004 throw new CameraAccessException(CameraAccessException.CAMERA_DISCONNECTED,
2005 "Camera service is currently unavailable");
2006 }
2007 }
2008 }
2009
2010 public void turnOnTorchWithStrengthLevel(String cameraId, int torchStrength) throws
2011 CameraAccessException {
2012 synchronized(mLock) {
2013
2014 if (cameraId == null) {
2015 throw new IllegalArgumentException("cameraId was null");
2016 }
2017
2018 ICameraService cameraService = getCameraService();
2019 if (cameraService == null) {
2020 throw new CameraAccessException(CameraAccessException.CAMERA_DISCONNECTED,
2021 "Camera service is currently unavailable.");
2022 }
2023
2024 try {
2025 cameraService.turnOnTorchWithStrengthLevel(cameraId, torchStrength,
2026 mTorchClientBinder);
2027 } catch(ServiceSpecificException e) {
2028 throwAsPublicException(e);
2029 } catch (RemoteException e) {
2030 throw new CameraAccessException(CameraAccessException.CAMERA_DISCONNECTED,
2031 "Camera service is currently unavailable.");
2032 }
2033 }
2034 }
2035
2036 public int getTorchStrengthLevel(String cameraId) throws CameraAccessException {
2037 int torchStrength = 0;
2038 synchronized(mLock) {
2039 if (cameraId == null) {
2040 throw new IllegalArgumentException("cameraId was null");
2041 }
2042
2043 ICameraService cameraService = getCameraService();
2044 if (cameraService == null) {
2045 throw new CameraAccessException(CameraAccessException.CAMERA_DISCONNECTED,
2046 "Camera service is currently unavailable.");
2047 }
2048
2049 try {
2050 torchStrength = cameraService.getTorchStrengthLevel(cameraId);
2051 } catch(ServiceSpecificException e) {
2052 throwAsPublicException(e);
2053 } catch (RemoteException e) {
2054 throw new CameraAccessException(CameraAccessException.CAMERA_DISCONNECTED,
2055 "Camera service is currently unavailable.");
2056 }
2057 }
2058 return torchStrength;
2059 }
2060
2061 private void handleRecoverableSetupErrors(ServiceSpecificException e) {
2062 switch (e.errorCode) {
2063 case ICameraService.ERROR_DISCONNECTED:
2064 Log.w(TAG, e.getMessage());
2065 break;
2066 default:
2067 throw new IllegalStateException(e);
2068 }
2069 }
2070
2071 private boolean isAvailable(int status) {
2072 switch (status) {
2073 case ICameraServiceListener.STATUS_PRESENT:
2074 return true;
2075 default:
2076 return false;
2077 }
2078 }
2079
2080 private boolean validStatus(int status) {
2081 switch (status) {
2082 case ICameraServiceListener.STATUS_NOT_PRESENT:
2083 case ICameraServiceListener.STATUS_PRESENT:
2084 case ICameraServiceListener.STATUS_ENUMERATING:
2085 case ICameraServiceListener.STATUS_NOT_AVAILABLE:
2086 return true;
2087 default:
2088 return false;
2089 }
2090 }
2091
2092 private boolean validTorchStatus(int status) {
2093 switch (status) {
2094 case ICameraServiceListener.TORCH_STATUS_NOT_AVAILABLE:
2095 case ICameraServiceListener.TORCH_STATUS_AVAILABLE_ON:
2096 case ICameraServiceListener.TORCH_STATUS_AVAILABLE_OFF:
2097 return true;
2098 default:
2099 return false;
2100 }
2101 }
2102
2103 private void postSingleAccessPriorityChangeUpdate(final AvailabilityCallback callback,
2104 final Executor executor) {
2105 final long ident = Binder.clearCallingIdentity();
2106 try {
2107 executor.execute(
2108 new Runnable() {
2109 @Override
2110 public void run() {
2111 callback.onCameraAccessPrioritiesChanged();
2112 }
2113 });
2114 } finally {
2115 Binder.restoreCallingIdentity(ident);
2116 }
2117 }
2118
2119 private void postSingleCameraOpenedUpdate(final AvailabilityCallback callback,
2120 final Executor executor, final String id, final String packageId) {
2121 final long ident = Binder.clearCallingIdentity();
2122 try {
2123 executor.execute(
2124 new Runnable() {
2125 @Override
2126 public void run() {
2127 callback.onCameraOpened(id, packageId);
2128 }
2129 });
2130 } finally {
2131 Binder.restoreCallingIdentity(ident);
2132 }
2133 }
2134
2135 private void postSingleCameraClosedUpdate(final AvailabilityCallback callback,
2136 final Executor executor, final String id) {
2137 final long ident = Binder.clearCallingIdentity();
2138 try {
2139 executor.execute(
2140 new Runnable() {
2141 @Override
2142 public void run() {
2143 callback.onCameraClosed(id);
2144 }
2145 });
2146 } finally {
2147 Binder.restoreCallingIdentity(ident);
2148 }
2149 }
2150
2151 private void postSingleUpdate(final AvailabilityCallback callback, final Executor executor,
2152 final String id, final String physicalId, final int status) {
2153 if (isAvailable(status)) {
2154 final long ident = Binder.clearCallingIdentity();
2155 try {
2156 executor.execute(
2157 new Runnable() {
2158 @Override
2159 public void run() {
2160 if (physicalId == null) {
2161 callback.onCameraAvailable(id);
2162 } else {
2163 callback.onPhysicalCameraAvailable(id, physicalId);
2164 }
2165 }
2166 });
2167 } finally {
2168 Binder.restoreCallingIdentity(ident);
2169 }
2170 } else {
2171 final long ident = Binder.clearCallingIdentity();
2172 try {
2173 executor.execute(
2174 new Runnable() {
2175 @Override
2176 public void run() {
2177 if (physicalId == null) {
2178 callback.onCameraUnavailable(id);
2179 } else {
2180 callback.onPhysicalCameraUnavailable(id, physicalId);
2181 }
2182 }
2183 });
2184 } finally {
2185 Binder.restoreCallingIdentity(ident);
2186 }
2187 }
2188 }
2189
2190 private void postSingleTorchUpdate(final TorchCallback callback, final Executor executor,
2191 final String id, final int status) {
2192 switch(status) {
2193 case ICameraServiceListener.TORCH_STATUS_AVAILABLE_ON:
2194 case ICameraServiceListener.TORCH_STATUS_AVAILABLE_OFF: {
2195 final long ident = Binder.clearCallingIdentity();
2196 try {
2197 executor.execute(() -> {
2198 callback.onTorchModeChanged(id, status ==
2199 ICameraServiceListener.TORCH_STATUS_AVAILABLE_ON);
2200 });
2201 } finally {
2202 Binder.restoreCallingIdentity(ident);
2203 }
2204 }
2205 break;
2206 default: {
2207 final long ident = Binder.clearCallingIdentity();
2208 try {
2209 executor.execute(() -> {
2210 callback.onTorchModeUnavailable(id);
2211 });
2212 } finally {
2213 Binder.restoreCallingIdentity(ident);
2214 }
2215 }
2216 break;
2217 }
2218 }
2219
2220 private void postSingleTorchStrengthLevelUpdate(final TorchCallback callback,
2221 final Executor executor, final String id, final int newStrengthLevel) {
2222 final long ident = Binder.clearCallingIdentity();
2223 try {
2224 executor.execute(() -> {
2225 callback.onTorchStrengthLevelChanged(id, newStrengthLevel);
2226 });
2227 } finally {
2228 Binder.restoreCallingIdentity(ident);
2229 }
2230 }
2231
2232 /**
2233 * Send the state of all known cameras to the provided listener, to initialize
2234 * the listener's knowledge of camera state.
2235 */
2236 private void updateCallbackLocked(AvailabilityCallback callback, Executor executor) {
2237 for (int i = 0; i < mDeviceStatus.size(); i++) {
2238 String id = mDeviceStatus.keyAt(i);
2239 Integer status = mDeviceStatus.valueAt(i);
2240 postSingleUpdate(callback, executor, id, null /*physicalId*/, status);
2241
2242 // Send the NOT_PRESENT state for unavailable physical cameras
2243 if (isAvailable(status) && mUnavailablePhysicalDevices.containsKey(id)) {
2244 ArrayList<String> unavailableIds = mUnavailablePhysicalDevices.get(id);
2245 for (String unavailableId : unavailableIds) {
2246 postSingleUpdate(callback, executor, id, unavailableId,
2247 ICameraServiceListener.STATUS_NOT_PRESENT);
2248 }
2249 }
2250
2251 }
2252 for (int i = 0; i < mOpenedDevices.size(); i++) {
2253 String id = mOpenedDevices.keyAt(i);
2254 String clientPackageId = mOpenedDevices.valueAt(i);
2255 postSingleCameraOpenedUpdate(callback, executor, id, clientPackageId);
2256 }
2257 }
2258
2259 private void onStatusChangedLocked(int status, String id) {
2260 if (DEBUG) {
2261 Log.v(TAG,
2262 String.format("Camera id %s has status changed to 0x%x", id, status));
2263 }
2264
2265 if (!validStatus(status)) {
2266 Log.e(TAG, String.format("Ignoring invalid device %s status 0x%x", id,
2267 status));
2268 return;
2269 }
2270
2271 Integer oldStatus;
2272 if (status == ICameraServiceListener.STATUS_NOT_PRESENT) {
2273 oldStatus = mDeviceStatus.remove(id);
2274 mUnavailablePhysicalDevices.remove(id);
2275 } else {
2276 oldStatus = mDeviceStatus.put(id, status);
2277 if (oldStatus == null) {
2278 mUnavailablePhysicalDevices.put(id, new ArrayList<String>());
2279 }
2280 }
2281
2282 if (oldStatus != null && oldStatus == status) {
2283 if (DEBUG) {
2284 Log.v(TAG, String.format(
2285 "Device status changed to 0x%x, which is what it already was",
2286 status));
2287 }
2288 return;
2289 }
2290
2291 // TODO: consider abstracting out this state minimization + transition
2292 // into a separate
2293 // more easily testable class
2294 // i.e. (new State()).addState(STATE_AVAILABLE)
2295 // .addState(STATE_NOT_AVAILABLE)
2296 // .addTransition(STATUS_PRESENT, STATE_AVAILABLE),
2297 // .addTransition(STATUS_NOT_PRESENT, STATE_NOT_AVAILABLE)
2298 // .addTransition(STATUS_ENUMERATING, STATE_NOT_AVAILABLE);
2299 // .addTransition(STATUS_NOT_AVAILABLE, STATE_NOT_AVAILABLE);
2300
2301 // Translate all the statuses to either 'available' or 'not available'
2302 // available -> available => no new update
2303 // not available -> not available => no new update
2304 if (oldStatus != null && isAvailable(status) == isAvailable(oldStatus)) {
2305 if (DEBUG) {
2306 Log.v(TAG,
2307 String.format(
2308 "Device status was previously available (%b), " +
2309 " and is now again available (%b)" +
2310 "so no new client visible update will be sent",
2311 isAvailable(oldStatus), isAvailable(status)));
2312 }
2313 return;
2314 }
2315
2316 final int callbackCount = mCallbackMap.size();
2317 for (int i = 0; i < callbackCount; i++) {
2318 Executor executor = mCallbackMap.valueAt(i);
2319 final AvailabilityCallback callback = mCallbackMap.keyAt(i);
2320
2321 postSingleUpdate(callback, executor, id, null /*physicalId*/, status);
2322 }
2323 } // onStatusChangedLocked
2324
2325 private void onPhysicalCameraStatusChangedLocked(int status,
2326 String id, String physicalId) {
2327 if (DEBUG) {
2328 Log.v(TAG,
2329 String.format("Camera id %s physical camera id %s has status "
2330 + "changed to 0x%x", id, physicalId, status));
2331 }
2332
2333 if (!validStatus(status)) {
2334 Log.e(TAG, String.format(
2335 "Ignoring invalid device %s physical device %s status 0x%x", id,
2336 physicalId, status));
2337 return;
2338 }
2339
2340 //TODO: Do we need to treat this as error?
2341 if (!mDeviceStatus.containsKey(id) || !isAvailable(mDeviceStatus.get(id))
2342 || !mUnavailablePhysicalDevices.containsKey(id)) {
2343 Log.e(TAG, String.format("Camera %s is not available. Ignore physical camera "
2344 + "status change", id));
2345 return;
2346 }
2347
2348 ArrayList<String> unavailablePhysicalDevices = mUnavailablePhysicalDevices.get(id);
2349 if (!isAvailable(status)
2350 && !unavailablePhysicalDevices.contains(physicalId)) {
2351 unavailablePhysicalDevices.add(physicalId);
2352 } else if (isAvailable(status)
2353 && unavailablePhysicalDevices.contains(physicalId)) {
2354 unavailablePhysicalDevices.remove(physicalId);
2355 } else {
2356 if (DEBUG) {
2357 Log.v(TAG,
2358 String.format(
2359 "Physical camera device status was previously available (%b), "
2360 + " and is now again available (%b)"
2361 + "so no new client visible update will be sent",
2362 !unavailablePhysicalDevices.contains(physicalId),
2363 isAvailable(status)));
2364 }
2365 return;
2366 }
2367
2368 final int callbackCount = mCallbackMap.size();
2369 for (int i = 0; i < callbackCount; i++) {
2370 Executor executor = mCallbackMap.valueAt(i);
2371 final AvailabilityCallback callback = mCallbackMap.keyAt(i);
2372
2373 postSingleUpdate(callback, executor, id, physicalId, status);
2374 }
2375 } // onPhysicalCameraStatusChangedLocked
2376
2377 private void updateTorchCallbackLocked(TorchCallback callback, Executor executor) {
2378 for (int i = 0; i < mTorchStatus.size(); i++) {
2379 String id = mTorchStatus.keyAt(i);
2380 Integer status = mTorchStatus.valueAt(i);
2381 postSingleTorchUpdate(callback, executor, id, status);
2382 }
2383 }
2384
2385 private void onTorchStatusChangedLocked(int status, String id) {
2386 if (DEBUG) {
2387 Log.v(TAG,
2388 String.format("Camera id %s has torch status changed to 0x%x", id, status));
2389 }
2390
2391 if (!validTorchStatus(status)) {
2392 Log.e(TAG, String.format("Ignoring invalid device %s torch status 0x%x", id,
2393 status));
2394 return;
2395 }
2396
2397 Integer oldStatus = mTorchStatus.put(id, status);
2398 if (oldStatus != null && oldStatus == status) {
2399 if (DEBUG) {
2400 Log.v(TAG, String.format(
2401 "Torch status changed to 0x%x, which is what it already was",
2402 status));
2403 }
2404 return;
2405 }
2406
2407 final int callbackCount = mTorchCallbackMap.size();
2408 for (int i = 0; i < callbackCount; i++) {
2409 final Executor executor = mTorchCallbackMap.valueAt(i);
2410 final TorchCallback callback = mTorchCallbackMap.keyAt(i);
2411 postSingleTorchUpdate(callback, executor, id, status);
2412 }
2413 } // onTorchStatusChangedLocked
2414
2415 private void onTorchStrengthLevelChangedLocked(String cameraId, int newStrengthLevel) {
2416 if (DEBUG) {
2417
2418 Log.v(TAG,
2419 String.format("Camera id %s has torch strength level changed to %d",
2420 cameraId, newStrengthLevel));
2421 }
2422
2423 final int callbackCount = mTorchCallbackMap.size();
2424 for (int i = 0; i < callbackCount; i++) {
2425 final Executor executor = mTorchCallbackMap.valueAt(i);
2426 final TorchCallback callback = mTorchCallbackMap.keyAt(i);
2427 postSingleTorchStrengthLevelUpdate(callback, executor, cameraId, newStrengthLevel);
2428 }
2429 } // onTorchStrengthLevelChanged
2430
2431 /**
2432 * Register a callback to be notified about camera device availability with the
2433 * global listener singleton.
2434 *
2435 * @param callback the new callback to send camera availability notices to
2436 * @param executor The executor which should invoke the callback. May not be null.
2437 * @param hasOpenCloseListenerPermission whether the client has permission for
2438 * onCameraOpened/onCameraClosed callback
2439 */
2440 public void registerAvailabilityCallback(AvailabilityCallback callback, Executor executor,
2441 boolean hasOpenCloseListenerPermission) {
2442 synchronized (mLock) {
2443 // In practice, this permission doesn't change. So we don't need one flag for each
2444 // callback object.
2445 mHasOpenCloseListenerPermission = hasOpenCloseListenerPermission;
2446 connectCameraServiceLocked();
2447
2448 Executor oldExecutor = mCallbackMap.put(callback, executor);
2449 // For new callbacks, provide initial availability information
2450 if (oldExecutor == null) {
2451 updateCallbackLocked(callback, executor);
2452 }
2453
2454 // If not connected to camera service, schedule a reconnect to camera service.
2455 if (mCameraService == null) {
2456 scheduleCameraServiceReconnectionLocked();
2457 }
2458 }
2459 }
2460
2461 /**
2462 * Remove a previously-added callback; the callback will no longer receive connection and
2463 * disconnection callbacks, and is no longer referenced by the global listener singleton.
2464 *
2465 * @param callback The callback to remove from the notification list
2466 */
2467 public void unregisterAvailabilityCallback(AvailabilityCallback callback) {
2468 synchronized (mLock) {
2469 mCallbackMap.remove(callback);
2470 }
2471 }
2472
2473 public void registerTorchCallback(TorchCallback callback, Executor executor) {
2474 synchronized(mLock) {
2475 connectCameraServiceLocked();
2476
2477 Executor oldExecutor = mTorchCallbackMap.put(callback, executor);
2478 // For new callbacks, provide initial torch information
2479 if (oldExecutor == null) {
2480 updateTorchCallbackLocked(callback, executor);
2481 }
2482
2483 // If not connected to camera service, schedule a reconnect to camera service.
2484 if (mCameraService == null) {
2485 scheduleCameraServiceReconnectionLocked();
2486 }
2487 }
2488 }
2489
2490 public void unregisterTorchCallback(TorchCallback callback) {
2491 synchronized(mLock) {
2492 mTorchCallbackMap.remove(callback);
2493 }
2494 }
2495
2496 /**
2497 * Callback from camera service notifying the process about camera availability changes
2498 */
2499 @Override
2500 public void onStatusChanged(int status, String cameraId) throws RemoteException {
2501 synchronized(mLock) {
2502 onStatusChangedLocked(status, cameraId);
2503 }
2504 }
2505
2506 @Override
2507 public void onPhysicalCameraStatusChanged(int status, String cameraId,
2508 String physicalCameraId) throws RemoteException {
2509 synchronized (mLock) {
2510 onPhysicalCameraStatusChangedLocked(status, cameraId, physicalCameraId);
2511 }
2512 }
2513
2514 @Override
2515 public void onTorchStatusChanged(int status, String cameraId) throws RemoteException {
2516 synchronized (mLock) {
2517 onTorchStatusChangedLocked(status, cameraId);
2518 }
2519 }
2520
2521 @Override
2522 public void onTorchStrengthLevelChanged(String cameraId, int newStrengthLevel)
2523 throws RemoteException {
2524 synchronized (mLock) {
2525 onTorchStrengthLevelChangedLocked(cameraId, newStrengthLevel);
2526 }
2527 }
2528
2529 @Override
2530 public void onCameraAccessPrioritiesChanged() {
2531 synchronized (mLock) {
2532 final int callbackCount = mCallbackMap.size();
2533 for (int i = 0; i < callbackCount; i++) {
2534 Executor executor = mCallbackMap.valueAt(i);
2535 final AvailabilityCallback callback = mCallbackMap.keyAt(i);
2536
2537 postSingleAccessPriorityChangeUpdate(callback, executor);
2538 }
2539 }
2540 }
2541
2542 @Override
2543 public void onCameraOpened(String cameraId, String clientPackageId) {
2544 synchronized (mLock) {
2545 onCameraOpenedLocked(cameraId, clientPackageId);
2546 }
2547 }
2548
2549 private void onCameraOpenedLocked(String cameraId, String clientPackageId) {
2550 String oldApk = mOpenedDevices.put(cameraId, clientPackageId);
2551
2552 if (oldApk != null) {
2553 if (oldApk.equals(clientPackageId)) {
2554 Log.w(TAG,
2555 "onCameraOpened was previously called for " + oldApk
2556 + " and is now again called for the same package name, "
2557 + "so no new client visible update will be sent");
2558 return;
2559 } else {
2560 Log.w(TAG,
2561 "onCameraOpened was previously called for " + oldApk
2562 + " and is now called for " + clientPackageId
2563 + " without onCameraClosed being called first");
2564 }
2565 }
2566
2567 final int callbackCount = mCallbackMap.size();
2568 for (int i = 0; i < callbackCount; i++) {
2569 Executor executor = mCallbackMap.valueAt(i);
2570 final AvailabilityCallback callback = mCallbackMap.keyAt(i);
2571
2572 postSingleCameraOpenedUpdate(callback, executor, cameraId, clientPackageId);
2573 }
2574 }
2575
2576 @Override
2577 public void onCameraClosed(String cameraId) {
2578 synchronized (mLock) {
2579 onCameraClosedLocked(cameraId);
2580 }
2581 }
2582
2583 private void onCameraClosedLocked(String cameraId) {
2584 mOpenedDevices.remove(cameraId);
2585
2586 final int callbackCount = mCallbackMap.size();
2587 for (int i = 0; i < callbackCount; i++) {
2588 Executor executor = mCallbackMap.valueAt(i);
2589 final AvailabilityCallback callback = mCallbackMap.keyAt(i);
2590
2591 postSingleCameraClosedUpdate(callback, executor, cameraId);
2592 }
2593 }
2594
2595 /**
2596 * Try to connect to camera service after some delay if any client registered camera
2597 * availability callback or torch status callback.
2598 */
2599 private void scheduleCameraServiceReconnectionLocked() {
2600 if (mCallbackMap.isEmpty() && mTorchCallbackMap.isEmpty()) {
2601 // Not necessary to reconnect camera service if no client registers a callback.
2602 return;
2603 }
2604
2605 if (DEBUG) {
2606 Log.v(TAG, "Reconnecting Camera Service in " + CAMERA_SERVICE_RECONNECT_DELAY_MS +
2607 " ms");
2608 }
2609
2610 try {
2611 mScheduler.schedule(() -> {
2612 ICameraService cameraService = getCameraService();
2613 if (cameraService == null) {
2614 synchronized(mLock) {
2615 if (DEBUG) {
2616 Log.v(TAG, "Reconnecting Camera Service failed.");
2617 }
2618 scheduleCameraServiceReconnectionLocked();
2619 }
2620 }
2621 }, CAMERA_SERVICE_RECONNECT_DELAY_MS, TimeUnit.MILLISECONDS);
2622 } catch (RejectedExecutionException e) {
2623 Log.e(TAG, "Failed to schedule camera service re-connect: " + e);
2624 }
2625 }
2626
2627 /**
2628 * Listener for camera service death.
2629 *
2630 * <p>The camera service isn't supposed to die under any normal circumstances, but can be
2631 * turned off during debug, or crash due to bugs. So detect that and null out the interface
2632 * object, so that the next calls to the manager can try to reconnect.</p>
2633 */
2634 public void binderDied() {
2635 synchronized(mLock) {
2636 // Only do this once per service death
2637 if (mCameraService == null) return;
2638
2639 mCameraService = null;
2640
2641 // Tell listeners that the cameras and torch modes are unavailable and schedule a
2642 // reconnection to camera service. When camera service is reconnected, the camera
2643 // and torch statuses will be updated.
2644 // Iterate from the end to the beginning befcause onStatusChangedLocked removes
2645 // entries from the ArrayMap.
2646 for (int i = mDeviceStatus.size() - 1; i >= 0; i--) {
2647 String cameraId = mDeviceStatus.keyAt(i);
2648 onStatusChangedLocked(ICameraServiceListener.STATUS_NOT_PRESENT, cameraId);
2649
2650 if (mHasOpenCloseListenerPermission) {
2651 onCameraClosedLocked(cameraId);
2652 }
2653 }
2654 for (int i = 0; i < mTorchStatus.size(); i++) {
2655 String cameraId = mTorchStatus.keyAt(i);
2656 onTorchStatusChangedLocked(ICameraServiceListener.TORCH_STATUS_NOT_AVAILABLE,
2657 cameraId);
2658 }
2659
2660 mConcurrentCameraIdCombinations.clear();
2661
2662 scheduleCameraServiceReconnectionLocked();
2663 }
2664 }
2665
2666 } // CameraManagerGlobal
2667
2668 } // CameraManager