1 /* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef ANDROID_SERVERS_CAMERA_CAMERASERVICE_H 18 #define ANDROID_SERVERS_CAMERA_CAMERASERVICE_H 19 20 #include <android/hardware/BnCameraService.h> 21 #include <android/hardware/BnSensorPrivacyListener.h> 22 #include <android/hardware/ICameraServiceListener.h> 23 #include <android/hardware/CameraIdRemapping.h> 24 #include <android/hardware/camera2/BnCameraInjectionSession.h> 25 #include <android/hardware/camera2/ICameraInjectionCallback.h> 26 27 #include <cutils/multiuser.h> 28 #include <utils/Vector.h> 29 #include <utils/KeyedVector.h> 30 #include <binder/ActivityManager.h> 31 #include <binder/AppOpsManager.h> 32 #include <binder/BinderService.h> 33 #include <binder/IServiceManager.h> 34 #include <binder/IActivityManager.h> 35 #include <binder/IAppOpsCallback.h> 36 #include <binder/IUidObserver.h> 37 #include <hardware/camera.h> 38 #include <sensorprivacy/SensorPrivacyManager.h> 39 40 #include <android/hardware/camera/common/1.0/types.h> 41 42 #include <camera/VendorTagDescriptor.h> 43 #include <camera/CaptureResult.h> 44 #include <camera/CameraParameters.h> 45 #include <camera/camera2/ConcurrentCamera.h> 46 47 #include "CameraFlashlight.h" 48 49 #include "common/CameraProviderManager.h" 50 #include "media/RingBuffer.h" 51 #include "utils/AutoConditionLock.h" 52 #include "utils/ClientManager.h" 53 #include "utils/IPCTransport.h" 54 #include "utils/CameraServiceProxyWrapper.h" 55 56 #include <set> 57 #include <string> 58 #include <list> 59 #include <map> 60 #include <memory> 61 #include <optional> 62 #include <utility> 63 #include <unordered_map> 64 #include <unordered_set> 65 #include <vector> 66 67 namespace android { 68 69 extern volatile int32_t gLogLevel; 70 71 class MemoryHeapBase; 72 class MediaPlayer; 73 74 class CameraService : 75 public BinderService<CameraService>, 76 public virtual ::android::hardware::BnCameraService, 77 public virtual IBinder::DeathRecipient, 78 public virtual CameraProviderManager::StatusListener, 79 public virtual IServiceManager::LocalRegistrationCallback 80 { 81 friend class BinderService<CameraService>; 82 friend class CameraOfflineSessionClient; 83 public: 84 class Client; 85 class BasicClient; 86 class OfflineClient; 87 88 // The effective API level. The Camera2 API running in LEGACY mode counts as API_1. 89 enum apiLevel { 90 API_1 = 1, 91 API_2 = 2 92 }; 93 94 // 3 second busy timeout when other clients are connecting 95 static const nsecs_t DEFAULT_CONNECT_TIMEOUT_NS = 3000000000; 96 97 // 1 second busy timeout when other clients are disconnecting 98 static const nsecs_t DEFAULT_DISCONNECT_TIMEOUT_NS = 1000000000; 99 100 // Default number of messages to store in eviction log 101 static const size_t DEFAULT_EVENT_LOG_LENGTH = 100; 102 103 // Event log ID 104 static const int SN_EVENT_LOG_ID = 0x534e4554; 105 106 // Register camera service 107 static void instantiate(); 108 109 // Implementation of BinderService<T> getServiceName()110 static char const* getServiceName() { return "media.camera"; } 111 112 // Implementation of IServiceManager::LocalRegistrationCallback 113 virtual void onServiceRegistration(const String16& name, const sp<IBinder>& binder) override; 114 115 // Non-null arguments for cameraServiceProxyWrapper should be provided for 116 // testing purposes only. 117 CameraService(std::shared_ptr<CameraServiceProxyWrapper> 118 cameraServiceProxyWrapper = nullptr); 119 virtual ~CameraService(); 120 121 ///////////////////////////////////////////////////////////////////// 122 // HAL Callbacks - implements CameraProviderManager::StatusListener 123 124 virtual void onDeviceStatusChanged(const String8 &cameraId, 125 CameraDeviceStatus newHalStatus) override; 126 virtual void onDeviceStatusChanged(const String8 &cameraId, 127 const String8 &physicalCameraId, 128 CameraDeviceStatus newHalStatus) override; 129 // This method may hold CameraProviderManager::mInterfaceMutex as a part 130 // of calling getSystemCameraKind() internally. Care should be taken not to 131 // directly / indirectly call this from callers who also hold 132 // mInterfaceMutex. 133 virtual void onTorchStatusChanged(const String8& cameraId, 134 TorchModeStatus newStatus) override; 135 // Does not hold CameraProviderManager::mInterfaceMutex. 136 virtual void onTorchStatusChanged(const String8& cameraId, 137 TorchModeStatus newStatus, 138 SystemCameraKind kind) override; 139 virtual void onNewProviderRegistered() override; 140 141 ///////////////////////////////////////////////////////////////////// 142 // ICameraService 143 // IMPORTANT: All binder calls that deal with logicalCameraId should use 144 // resolveCameraId(logicalCameraId) to arrive at the correct cameraId to 145 // perform the operation on (in case of Id Remapping). 146 virtual binder::Status getNumberOfCameras(int32_t type, int32_t* numCameras); 147 148 virtual binder::Status getCameraInfo(int cameraId, bool overrideToPortrait, 149 hardware::CameraInfo* cameraInfo) override; 150 virtual binder::Status getCameraCharacteristics(const String16& cameraId, 151 int targetSdkVersion, bool overrideToPortrait, CameraMetadata* cameraInfo) override; 152 virtual binder::Status getCameraVendorTagDescriptor( 153 /*out*/ 154 hardware::camera2::params::VendorTagDescriptor* desc); 155 virtual binder::Status getCameraVendorTagCache( 156 /*out*/ 157 hardware::camera2::params::VendorTagDescriptorCache* cache); 158 159 virtual binder::Status connect(const sp<hardware::ICameraClient>& cameraClient, 160 int32_t cameraId, const String16& clientPackageName, 161 int32_t clientUid, int clientPid, int targetSdkVersion, 162 bool overrideToPortrait, bool forceSlowJpegMode, 163 /*out*/ 164 sp<hardware::ICamera>* device) override; 165 166 virtual binder::Status connectDevice( 167 const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb, const String16& cameraId, 168 const String16& clientPackageName, const std::optional<String16>& clientFeatureId, 169 int32_t clientUid, int scoreOffset, int targetSdkVersion, bool overrideToPortrait, 170 /*out*/ 171 sp<hardware::camera2::ICameraDeviceUser>* device); 172 173 virtual binder::Status addListener(const sp<hardware::ICameraServiceListener>& listener, 174 /*out*/ 175 std::vector<hardware::CameraStatus>* cameraStatuses); 176 virtual binder::Status removeListener( 177 const sp<hardware::ICameraServiceListener>& listener); 178 179 virtual binder::Status getConcurrentCameraIds( 180 /*out*/ 181 std::vector<hardware::camera2::utils::ConcurrentCameraIdCombination>* concurrentCameraIds); 182 183 virtual binder::Status isConcurrentSessionConfigurationSupported( 184 const std::vector<hardware::camera2::utils::CameraIdAndSessionConfiguration>& sessions, 185 int targetSdkVersion, /*out*/bool* supported); 186 187 virtual binder::Status getLegacyParameters( 188 int32_t cameraId, 189 /*out*/ 190 String16* parameters); 191 192 virtual binder::Status setTorchMode(const String16& cameraId, bool enabled, 193 const sp<IBinder>& clientBinder); 194 195 virtual binder::Status turnOnTorchWithStrengthLevel(const String16& cameraId, 196 int32_t torchStrength, const sp<IBinder>& clientBinder); 197 198 virtual binder::Status getTorchStrengthLevel(const String16& cameraId, 199 int32_t* torchStrength); 200 201 virtual binder::Status notifySystemEvent(int32_t eventId, 202 const std::vector<int32_t>& args); 203 204 virtual binder::Status notifyDeviceStateChange(int64_t newState); 205 206 virtual binder::Status notifyDisplayConfigurationChange(); 207 208 // OK = supports api of that version, -EOPNOTSUPP = does not support 209 virtual binder::Status supportsCameraApi( 210 const String16& cameraId, int32_t apiVersion, 211 /*out*/ 212 bool *isSupported); 213 214 virtual binder::Status isHiddenPhysicalCamera( 215 const String16& cameraId, 216 /*out*/ 217 bool *isSupported); 218 219 virtual binder::Status injectCamera( 220 const String16& packageName, const String16& internalCamId, 221 const String16& externalCamId, 222 const sp<hardware::camera2::ICameraInjectionCallback>& callback, 223 /*out*/ 224 sp<hardware::camera2::ICameraInjectionSession>* cameraInjectionSession); 225 226 virtual binder::Status reportExtensionSessionStats( 227 const hardware::CameraExtensionSessionStats& stats, String16* sessionKey /*out*/); 228 229 virtual binder::Status remapCameraIds(const hardware::CameraIdRemapping& 230 cameraIdRemapping); 231 232 // Extra permissions checks 233 virtual status_t onTransact(uint32_t code, const Parcel& data, 234 Parcel* reply, uint32_t flags); 235 236 virtual status_t dump(int fd, const Vector<String16>& args); 237 238 virtual status_t shellCommand(int in, int out, int err, const Vector<String16>& args); 239 240 binder::Status addListenerHelper(const sp<hardware::ICameraServiceListener>& listener, 241 /*out*/ 242 std::vector<hardware::CameraStatus>* cameraStatuses, bool isVendor = false, 243 bool isProcessLocalTest = false); 244 245 // Monitored UIDs availability notification 246 void notifyMonitoredUids(); 247 void notifyMonitoredUids(const std::unordered_set<uid_t> ¬ifyUidSet); 248 249 // Stores current open session device info in temp file. 250 void cacheDump(); 251 252 // Register an offline client for a given active camera id 253 status_t addOfflineClient(String8 cameraId, sp<BasicClient> offlineClient); 254 255 ///////////////////////////////////////////////////////////////////// 256 // Client functionality 257 258 enum sound_kind { 259 SOUND_SHUTTER = 0, 260 SOUND_RECORDING_START = 1, 261 SOUND_RECORDING_STOP = 2, 262 NUM_SOUNDS 263 }; 264 265 void playSound(sound_kind kind); 266 void loadSoundLocked(sound_kind kind); 267 void decreaseSoundRef(); 268 void increaseSoundRef(); 269 270 ///////////////////////////////////////////////////////////////////// 271 // CameraDeviceFactory functionality 272 std::pair<int, IPCTransport> getDeviceVersion(const String8& cameraId, 273 bool overrideToPortrait, int* portraitRotation, 274 int* facing = nullptr, int* orientation = nullptr); 275 276 ///////////////////////////////////////////////////////////////////// 277 // Methods to be used in CameraService class tests only 278 // 279 // CameraService class test method only - clear static variables in the 280 // cameraserver process, which otherwise might affect multiple test runs. 281 void clearCachedVariables(); 282 283 // Add test listener, linkToDeath won't be called since this is for process 284 // local testing. 285 binder::Status addListenerTest(const sp<hardware::ICameraServiceListener>& listener, 286 /*out*/ 287 std::vector<hardware::CameraStatus>* cameraStatuses); 288 289 ///////////////////////////////////////////////////////////////////// 290 // Shared utilities 291 static binder::Status filterGetInfoErrorCode(status_t err); 292 293 ///////////////////////////////////////////////////////////////////// 294 // CameraClient functionality 295 296 class BasicClient : public virtual RefBase { 297 friend class CameraService; 298 public: 299 virtual status_t initialize(sp<CameraProviderManager> manager, 300 const String8& monitorTags) = 0; 301 virtual binder::Status disconnect(); 302 303 // because we can't virtually inherit IInterface, which breaks 304 // virtual inheritance 305 virtual sp<IBinder> asBinderWrapper() = 0; 306 307 // Return the remote callback binder object (e.g. ICameraDeviceCallbacks) getRemote()308 sp<IBinder> getRemote() { 309 return mRemoteBinder; 310 } 311 getOverrideToPortrait()312 bool getOverrideToPortrait() const { 313 return mOverrideToPortrait; 314 } 315 316 // Disallows dumping over binder interface 317 virtual status_t dump(int fd, const Vector<String16>& args); 318 // Internal dump method to be called by CameraService 319 virtual status_t dumpClient(int fd, const Vector<String16>& args) = 0; 320 321 virtual status_t startWatchingTags(const String8 &tags, int outFd); 322 virtual status_t stopWatchingTags(int outFd); 323 virtual status_t dumpWatchedEventsToVector(std::vector<std::string> &out); 324 325 // Return the package name for this client 326 virtual String16 getPackageName() const; 327 328 // Return the camera facing for this client 329 virtual int getCameraFacing() const; 330 331 // Return the camera orientation for this client 332 virtual int getCameraOrientation() const; 333 334 // Notify client about a fatal error 335 virtual void notifyError(int32_t errorCode, 336 const CaptureResultExtras& resultExtras) = 0; 337 338 // Get the UID of the application client using this 339 virtual uid_t getClientUid() const; 340 341 // Get the PID of the application client using this 342 virtual int getClientPid() const; 343 344 // Check what API level is used for this client. This is used to determine which 345 // superclass this can be cast to. 346 virtual bool canCastToApiClient(apiLevel level) const; 347 348 // Block the client form using the camera 349 virtual void block(); 350 351 // set audio restriction from client 352 // Will call into camera service and hold mServiceLock 353 virtual status_t setAudioRestriction(int32_t mode); 354 355 // Get current global audio restriction setting 356 // Will call into camera service and hold mServiceLock 357 virtual int32_t getServiceAudioRestriction() const; 358 359 // Get current audio restriction setting for this client 360 virtual int32_t getAudioRestriction() const; 361 362 static bool isValidAudioRestriction(int32_t mode); 363 364 // Override rotate-and-crop AUTO behavior 365 virtual status_t setRotateAndCropOverride(uint8_t rotateAndCrop, bool fromHal = false) = 0; 366 367 // Override autoframing AUTO behaviour 368 virtual status_t setAutoframingOverride(uint8_t autoframingValue) = 0; 369 370 // Whether the client supports camera muting (black only output) 371 virtual bool supportsCameraMute() = 0; 372 373 // Set/reset camera mute 374 virtual status_t setCameraMute(bool enabled) = 0; 375 376 // Set Camera service watchdog 377 virtual status_t setCameraServiceWatchdog(bool enabled) = 0; 378 379 // Set stream use case overrides 380 virtual void setStreamUseCaseOverrides( 381 const std::vector<int64_t>& useCaseOverrides) = 0; 382 383 // Clear stream use case overrides 384 virtual void clearStreamUseCaseOverrides() = 0; 385 386 // Whether the client supports camera zoom override 387 virtual bool supportsZoomOverride() = 0; 388 389 // Set/reset zoom override 390 virtual status_t setZoomOverride(int32_t zoomOverride) = 0; 391 392 // The injection camera session to replace the internal camera 393 // session. 394 virtual status_t injectCamera(const String8& injectedCamId, 395 sp<CameraProviderManager> manager) = 0; 396 397 // Stop the injection camera and restore to internal camera session. 398 virtual status_t stopInjection() = 0; 399 400 protected: 401 BasicClient(const sp<CameraService>& cameraService, 402 const sp<IBinder>& remoteCallback, 403 const String16& clientPackageName, 404 bool nativeClient, 405 const std::optional<String16>& clientFeatureId, 406 const String8& cameraIdStr, 407 int cameraFacing, 408 int sensorOrientation, 409 int clientPid, 410 uid_t clientUid, 411 int servicePid, 412 bool overrideToPortrait); 413 414 virtual ~BasicClient(); 415 416 // the instance is in the middle of destruction. When this is set, 417 // the instance should not be accessed from callback. 418 // CameraService's mClientLock should be acquired to access this. 419 // - subclasses should set this to true in their destructors. 420 bool mDestructionStarted; 421 422 // these are initialized in the constructor. 423 static sp<CameraService> sCameraService; 424 const String8 mCameraIdStr; 425 const int mCameraFacing; 426 const int mOrientation; 427 String16 mClientPackageName; 428 bool mSystemNativeClient; 429 std::optional<String16> mClientFeatureId; 430 pid_t mClientPid; 431 const uid_t mClientUid; 432 const pid_t mServicePid; 433 bool mDisconnected; 434 bool mUidIsTrusted; 435 bool mOverrideToPortrait; 436 437 mutable Mutex mAudioRestrictionLock; 438 int32_t mAudioRestriction; 439 440 // - The app-side Binder interface to receive callbacks from us 441 sp<IBinder> mRemoteBinder; // immutable after constructor 442 443 // Permissions management methods for camera lifecycle 444 445 // Notify rest of system/apps about camera opening, and check appops 446 virtual status_t startCameraOps(); 447 // Notify rest of system/apps about camera starting to stream data, and confirm appops 448 virtual status_t startCameraStreamingOps(); 449 // Notify rest of system/apps about camera stopping streaming data 450 virtual status_t finishCameraStreamingOps(); 451 // Notify rest of system/apps about camera closing 452 virtual status_t finishCameraOps(); 453 // Handle errors for start/checkOps 454 virtual status_t handleAppOpMode(int32_t mode); 455 // Just notify camera appops to trigger unblocking dialog if sensor 456 // privacy is enabled and camera mute is not supported 457 virtual status_t noteAppOp(); 458 459 std::unique_ptr<AppOpsManager> mAppOpsManager = nullptr; 460 461 class OpsCallback : public BnAppOpsCallback { 462 public: 463 explicit OpsCallback(wp<BasicClient> client); 464 virtual void opChanged(int32_t op, const String16& packageName); 465 466 private: 467 wp<BasicClient> mClient; 468 469 }; // class OpsCallback 470 471 sp<OpsCallback> mOpsCallback; 472 // Track whether checkOps was called successfully, to avoid 473 // finishing what we didn't start, on camera open. 474 bool mOpsActive; 475 // Track whether startOps was called successfully on start of 476 // camera streaming. 477 bool mOpsStreaming; 478 479 // IAppOpsCallback interface, indirected through opListener 480 virtual void opChanged(int32_t op, const String16& packageName); 481 }; // class BasicClient 482 483 class Client : public hardware::BnCamera, public BasicClient 484 { 485 public: 486 typedef hardware::ICameraClient TCamCallbacks; 487 488 // ICamera interface (see ICamera for details) 489 virtual binder::Status disconnect(); 490 virtual status_t connect(const sp<hardware::ICameraClient>& client) = 0; 491 virtual status_t lock() = 0; 492 virtual status_t unlock() = 0; 493 virtual status_t setPreviewTarget(const sp<IGraphicBufferProducer>& bufferProducer)=0; 494 virtual void setPreviewCallbackFlag(int flag) = 0; 495 virtual status_t setPreviewCallbackTarget( 496 const sp<IGraphicBufferProducer>& callbackProducer) = 0; 497 virtual status_t startPreview() = 0; 498 virtual void stopPreview() = 0; 499 virtual bool previewEnabled() = 0; 500 virtual status_t setVideoBufferMode(int32_t videoBufferMode) = 0; 501 virtual status_t startRecording() = 0; 502 virtual void stopRecording() = 0; 503 virtual bool recordingEnabled() = 0; 504 virtual void releaseRecordingFrame(const sp<IMemory>& mem) = 0; 505 virtual status_t autoFocus() = 0; 506 virtual status_t cancelAutoFocus() = 0; 507 virtual status_t takePicture(int msgType) = 0; 508 virtual status_t setParameters(const String8& params) = 0; 509 virtual String8 getParameters() const = 0; 510 virtual status_t sendCommand(int32_t cmd, int32_t arg1, int32_t arg2) = 0; 511 virtual status_t setVideoTarget(const sp<IGraphicBufferProducer>& bufferProducer) = 0; 512 513 // Interface used by CameraService 514 Client(const sp<CameraService>& cameraService, 515 const sp<hardware::ICameraClient>& cameraClient, 516 const String16& clientPackageName, 517 bool systemNativeClient, 518 const std::optional<String16>& clientFeatureId, 519 const String8& cameraIdStr, 520 int api1CameraId, 521 int cameraFacing, 522 int sensorOrientation, 523 int clientPid, 524 uid_t clientUid, 525 int servicePid, 526 bool overrideToPortrait); 527 ~Client(); 528 529 // return our camera client getRemoteCallback()530 const sp<hardware::ICameraClient>& getRemoteCallback() { 531 return mRemoteCallback; 532 } 533 asBinderWrapper()534 virtual sp<IBinder> asBinderWrapper() { 535 return asBinder(this); 536 } 537 538 virtual void notifyError(int32_t errorCode, 539 const CaptureResultExtras& resultExtras); 540 541 // Check what API level is used for this client. This is used to determine which 542 // superclass this can be cast to. 543 virtual bool canCastToApiClient(apiLevel level) const; 544 setImageDumpMask(int)545 void setImageDumpMask(int /*mask*/) { } 546 protected: 547 // Initialized in constructor 548 549 // - The app-side Binder interface to receive callbacks from us 550 sp<hardware::ICameraClient> mRemoteCallback; 551 552 int mCameraId; // All API1 clients use integer camera IDs 553 }; // class Client 554 555 /** 556 * A listener class that implements the LISTENER interface for use with a ClientManager, and 557 * implements the following methods: 558 * void onClientRemoved(const ClientDescriptor<KEY, VALUE>& descriptor); 559 * void onClientAdded(const ClientDescriptor<KEY, VALUE>& descriptor); 560 */ 561 class ClientEventListener { 562 public: 563 void onClientAdded(const resource_policy::ClientDescriptor<String8, 564 sp<CameraService::BasicClient>>& descriptor); 565 void onClientRemoved(const resource_policy::ClientDescriptor<String8, 566 sp<CameraService::BasicClient>>& descriptor); 567 }; // class ClientEventListener 568 569 typedef std::shared_ptr<resource_policy::ClientDescriptor<String8, 570 sp<CameraService::BasicClient>>> DescriptorPtr; 571 572 /** 573 * A container class for managing active camera clients that are using HAL devices. Active 574 * clients are represented by ClientDescriptor objects that contain strong pointers to the 575 * actual BasicClient subclass binder interface implementation. 576 * 577 * This class manages the eviction behavior for the camera clients. See the parent class 578 * implementation in utils/ClientManager for the specifics of this behavior. 579 */ 580 class CameraClientManager : public resource_policy::ClientManager<String8, 581 sp<CameraService::BasicClient>, ClientEventListener> { 582 public: 583 CameraClientManager(); 584 virtual ~CameraClientManager(); 585 586 /** 587 * Return a strong pointer to the active BasicClient for this camera ID, or an empty 588 * if none exists. 589 */ 590 sp<CameraService::BasicClient> getCameraClient(const String8& id) const; 591 592 /** 593 * Return a string describing the current state. 594 */ 595 String8 toString() const; 596 597 /** 598 * Make a ClientDescriptor object wrapping the given BasicClient strong pointer. 599 */ 600 static DescriptorPtr makeClientDescriptor(const String8& key, const sp<BasicClient>& value, 601 int32_t cost, const std::set<String8>& conflictingKeys, int32_t score, 602 int32_t ownerId, int32_t state, int oomScoreOffset, bool systemNativeClient); 603 604 /** 605 * Make a ClientDescriptor object wrapping the given BasicClient strong pointer with 606 * values intialized from a prior ClientDescriptor. 607 */ 608 static DescriptorPtr makeClientDescriptor(const sp<BasicClient>& value, 609 const CameraService::DescriptorPtr& partial, int oomScoreOffset, 610 bool systemNativeClient); 611 612 }; // class CameraClientManager 613 614 int32_t updateAudioRestriction(); 615 int32_t updateAudioRestrictionLocked(); 616 617 private: 618 619 // TODO: b/263304156 update this to make use of a death callback for more 620 // robust/fault tolerant logging getActivityManager()621 static const sp<IActivityManager>& getActivityManager() { 622 static const char* kActivityService = "activity"; 623 static const auto activityManager = []() -> sp<IActivityManager> { 624 const sp<IServiceManager> sm(defaultServiceManager()); 625 if (sm != nullptr) { 626 return interface_cast<IActivityManager>(sm->checkService(String16(kActivityService))); 627 } 628 return nullptr; 629 }(); 630 return activityManager; 631 } 632 633 /** 634 * Typesafe version of device status, containing both the HAL-layer and the service interface- 635 * layer values. 636 */ 637 enum class StatusInternal : int32_t { 638 NOT_PRESENT = static_cast<int32_t>(CameraDeviceStatus::NOT_PRESENT), 639 PRESENT = static_cast<int32_t>(CameraDeviceStatus::PRESENT), 640 ENUMERATING = static_cast<int32_t>(CameraDeviceStatus::ENUMERATING), 641 NOT_AVAILABLE = static_cast<int32_t>(hardware::ICameraServiceListener::STATUS_NOT_AVAILABLE), 642 UNKNOWN = static_cast<int32_t>(hardware::ICameraServiceListener::STATUS_UNKNOWN) 643 }; 644 645 /** 646 * Container class for the state of each logical camera device, including: ID, status, and 647 * dependencies on other devices. The mapping of camera ID -> state saved in mCameraStates 648 * represents the camera devices advertised by the HAL (and any USB devices, when we add 649 * those). 650 * 651 * This container does NOT represent an active camera client. These are represented using 652 * the ClientDescriptors stored in mActiveClientManager. 653 */ 654 class CameraState { 655 public: 656 657 /** 658 * Make a new CameraState and set the ID, cost, and conflicting devices using the values 659 * returned in the HAL's camera_info struct for each device. 660 */ 661 CameraState(const String8& id, int cost, const std::set<String8>& conflicting, 662 SystemCameraKind deviceKind, const std::vector<std::string>& physicalCameras); 663 virtual ~CameraState(); 664 665 /** 666 * Return the status for this device. 667 * 668 * This method acquires mStatusLock. 669 */ 670 StatusInternal getStatus() const; 671 672 /** 673 * This function updates the status for this camera device, unless the given status 674 * is in the given list of rejected status states, and execute the function passed in 675 * with a signature onStatusUpdateLocked(const String8&, int32_t) 676 * if the status has changed. 677 * 678 * This method is idempotent, and will not result in the function passed to 679 * onStatusUpdateLocked being called more than once for the same arguments. 680 * This method aquires mStatusLock. 681 */ 682 template<class Func> 683 void updateStatus(StatusInternal status, 684 const String8& cameraId, 685 std::initializer_list<StatusInternal> rejectSourceStates, 686 Func onStatusUpdatedLocked); 687 688 /** 689 * Return the last set CameraParameters object generated from the information returned by 690 * the HAL for this device (or an empty CameraParameters object if none has been set). 691 */ 692 CameraParameters getShimParams() const; 693 694 /** 695 * Set the CameraParameters for this device. 696 */ 697 void setShimParams(const CameraParameters& params); 698 699 /** 700 * Return the resource_cost advertised by the HAL for this device. 701 */ 702 int getCost() const; 703 704 /** 705 * Return a set of the IDs of conflicting devices advertised by the HAL for this device. 706 */ 707 std::set<String8> getConflicting() const; 708 709 /** 710 * Return the ID of this camera device. 711 */ 712 String8 getId() const; 713 714 /** 715 * Return the kind (SystemCameraKind) of this camera device. 716 */ 717 SystemCameraKind getSystemCameraKind() const; 718 719 /** 720 * Return whether this camera is a logical multi-camera and has a 721 * particular physical sub-camera. 722 */ 723 bool containsPhysicalCamera(const std::string& physicalCameraId) const; 724 725 /** 726 * Add/Remove the unavailable physical camera ID. 727 */ 728 bool addUnavailablePhysicalId(const String8& physicalId); 729 bool removeUnavailablePhysicalId(const String8& physicalId); 730 731 /** 732 * Set and get client package name. 733 */ 734 void setClientPackage(const String8& clientPackage); 735 String8 getClientPackage() const; 736 737 /** 738 * Return the unavailable physical ids for this device. 739 * 740 * This method acquires mStatusLock. 741 */ 742 std::vector<String8> getUnavailablePhysicalIds() const; 743 private: 744 const String8 mId; 745 StatusInternal mStatus; // protected by mStatusLock 746 const int mCost; 747 std::set<String8> mConflicting; 748 std::set<String8> mUnavailablePhysicalIds; 749 String8 mClientPackage; 750 mutable Mutex mStatusLock; 751 CameraParameters mShimParams; 752 const SystemCameraKind mSystemCameraKind; 753 const std::vector<std::string> mPhysicalCameras; // Empty if not a logical multi-camera 754 }; // class CameraState 755 756 // Observer for UID lifecycle enforcing that UIDs in idle 757 // state cannot use the camera to protect user privacy. 758 class UidPolicy : 759 public BnUidObserver, 760 public virtual IBinder::DeathRecipient, 761 public virtual IServiceManager::LocalRegistrationCallback { 762 public: UidPolicy(sp<CameraService> service)763 explicit UidPolicy(sp<CameraService> service) 764 : mRegistered(false), mService(service) {} 765 766 void registerSelf(); 767 void unregisterSelf(); 768 769 bool isUidActive(uid_t uid, String16 callingPackage); 770 int32_t getProcState(uid_t uid); 771 772 // IUidObserver 773 void onUidGone(uid_t uid, bool disabled) override; 774 void onUidActive(uid_t uid) override; 775 void onUidIdle(uid_t uid, bool disabled) override; 776 void onUidStateChanged(uid_t uid, int32_t procState, int64_t procStateSeq, 777 int32_t capability) override; 778 void onUidProcAdjChanged(uid_t uid, int adj) override; 779 780 void addOverrideUid(uid_t uid, String16 callingPackage, bool active); 781 void removeOverrideUid(uid_t uid, String16 callingPackage); 782 783 void registerMonitorUid(uid_t uid, bool openCamera); 784 void unregisterMonitorUid(uid_t uid, bool closeCamera); 785 786 // Implementation of IServiceManager::LocalRegistrationCallback 787 virtual void onServiceRegistration(const String16& name, 788 const sp<IBinder>& binder) override; 789 // IBinder::DeathRecipient implementation 790 virtual void binderDied(const wp<IBinder> &who); 791 private: 792 bool isUidActiveLocked(uid_t uid, String16 callingPackage); 793 int32_t getProcStateLocked(uid_t uid); 794 void updateOverrideUid(uid_t uid, String16 callingPackage, bool active, bool insert); 795 void registerWithActivityManager(); 796 797 struct MonitoredUid { 798 int32_t procState; 799 int32_t procAdj; 800 bool hasCamera; 801 size_t refCount; 802 }; 803 804 Mutex mUidLock; 805 bool mRegistered; 806 ActivityManager mAm; 807 wp<CameraService> mService; 808 std::unordered_set<uid_t> mActiveUids; 809 // Monitored uid map 810 std::unordered_map<uid_t, MonitoredUid> mMonitoredUids; 811 std::unordered_map<uid_t, bool> mOverrideUids; 812 sp<IBinder> mObserverToken; 813 }; // class UidPolicy 814 815 // If sensor privacy is enabled then all apps, including those that are active, should be 816 // prevented from accessing the camera. 817 class SensorPrivacyPolicy : public hardware::BnSensorPrivacyListener, 818 public virtual IBinder::DeathRecipient, 819 public virtual IServiceManager::LocalRegistrationCallback { 820 public: SensorPrivacyPolicy(wp<CameraService> service)821 explicit SensorPrivacyPolicy(wp<CameraService> service) 822 : mService(service), mSensorPrivacyEnabled(false), mRegistered(false) {} 823 824 void registerSelf(); 825 void unregisterSelf(); 826 827 bool isSensorPrivacyEnabled(); 828 bool isCameraPrivacyEnabled(); 829 830 binder::Status onSensorPrivacyChanged(int toggleType, int sensor, 831 bool enabled); 832 833 // Implementation of IServiceManager::LocalRegistrationCallback 834 virtual void onServiceRegistration(const String16& name, 835 const sp<IBinder>& binder) override; 836 // IBinder::DeathRecipient implementation 837 virtual void binderDied(const wp<IBinder> &who); 838 839 private: 840 SensorPrivacyManager mSpm; 841 wp<CameraService> mService; 842 Mutex mSensorPrivacyLock; 843 bool mSensorPrivacyEnabled; 844 bool mRegistered; 845 846 bool hasCameraPrivacyFeature(); 847 void registerWithSensorPrivacyManager(); 848 }; 849 850 sp<UidPolicy> mUidPolicy; 851 852 sp<SensorPrivacyPolicy> mSensorPrivacyPolicy; 853 854 std::shared_ptr<CameraServiceProxyWrapper> mCameraServiceProxyWrapper; 855 856 // Delay-load the Camera HAL module 857 virtual void onFirstRef(); 858 859 // Eumerate all camera providers in the system 860 status_t enumerateProviders(); 861 862 // Add/remove a new camera to camera and torch state lists or remove an unplugged one 863 // Caller must not hold mServiceLock 864 void addStates(const String8 id); 865 void removeStates(const String8 id); 866 867 // Check if we can connect, before we acquire the service lock. 868 // The returned originalClientPid is the PID of the original process that wants to connect to 869 // camera. 870 // The returned clientPid is the PID of the client that directly connects to camera. 871 // originalClientPid and clientPid are usually the same except when the application uses 872 // mediaserver to connect to camera (using MediaRecorder to connect to camera). In that case, 873 // clientPid is the PID of mediaserver and originalClientPid is the PID of the application. 874 binder::Status validateConnectLocked(const String8& cameraId, const String8& clientName8, 875 /*inout*/int& clientUid, /*inout*/int& clientPid, /*out*/int& originalClientPid) const; 876 binder::Status validateClientPermissionsLocked(const String8& cameraId, const String8& clientName8, 877 /*inout*/int& clientUid, /*inout*/int& clientPid, /*out*/int& originalClientPid) const; 878 879 // Handle active client evictions, and update service state. 880 // Only call with with mServiceLock held. 881 status_t handleEvictionsLocked(const String8& cameraId, int clientPid, 882 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName, 883 int scoreOffset, bool systemNativeClient, 884 /*out*/ 885 sp<BasicClient>* client, 886 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial); 887 888 // Should an operation attempt on a cameraId be rejected ? (this can happen 889 // under various conditions. For example if a camera device is advertised as 890 // system only or hidden secure camera, amongst possible others. 891 bool shouldRejectSystemCameraConnection(const String8 & cameraId) const; 892 893 // Should a device status update be skipped for a particular camera device ? (this can happen 894 // under various conditions. For example if a camera device is advertised as 895 // system only or hidden secure camera, amongst possible others. 896 static bool shouldSkipStatusUpdates(SystemCameraKind systemCameraKind, bool isVendorListener, 897 int clientPid, int clientUid); 898 899 // Gets the kind of camera device (i.e public, hidden secure or system only) 900 // getSystemCameraKind() needs mInterfaceMutex which might lead to deadlocks 901 // if held along with mStatusListenerLock (depending on lock ordering, b/141756275), it is 902 // recommended that we don't call this function with mStatusListenerLock held. 903 status_t getSystemCameraKind(const String8& cameraId, SystemCameraKind *kind) const; 904 905 // Update the set of API1Compatible camera devices without including system 906 // cameras and secure cameras. This is used for hiding system only cameras 907 // from clients using camera1 api and not having android.permission.SYSTEM_CAMERA. 908 // This function expects @param normalDeviceIds, to have normalDeviceIds 909 // sorted in alpha-numeric order. 910 void filterAPI1SystemCameraLocked(const std::vector<std::string> &normalDeviceIds); 911 912 // In some cases the calling code has no access to the package it runs under. 913 // For example, NDK camera API. 914 // In this case we will get the packages for the calling UID and pick the first one 915 // for attributing the app op. This will work correctly for runtime permissions 916 // as for legacy apps we will toggle the app op for all packages in the UID. 917 // The caveat is that the operation may be attributed to the wrong package and 918 // stats based on app ops may be slightly off. 919 String16 getPackageNameFromUid(int clientUid); 920 921 // Single implementation shared between the various connect calls 922 template<class CALLBACK, class CLIENT> 923 binder::Status connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId, 924 int api1CameraId, const String16& clientPackageNameMaybe, bool systemNativeClient, 925 const std::optional<String16>& clientFeatureId, int clientUid, int clientPid, 926 apiLevel effectiveApiLevel, bool shimUpdateOnly, int scoreOffset, int targetSdkVersion, 927 bool overrideToPortrait, bool forceSlowJpegMode, const String8& originalCameraId, 928 /*out*/sp<CLIENT>& device); 929 930 // Lock guarding camera service state 931 Mutex mServiceLock; 932 933 // Condition to use with mServiceLock, used to handle simultaneous connect calls from clients 934 std::shared_ptr<WaitableMutexWrapper> mServiceLockWrapper; 935 936 // Return NO_ERROR if the device with a give ID can be connected to 937 status_t checkIfDeviceIsUsable(const String8& cameraId) const; 938 939 // Container for managing currently active application-layer clients 940 CameraClientManager mActiveClientManager; 941 942 // Adds client logs during open session to the file pointed by fd. 943 void dumpOpenSessionClientLogs(int fd, const Vector<String16>& args, const String8& cameraId); 944 945 // Adds client logs during closed session to the file pointed by fd. 946 void dumpClosedSessionClientLogs(int fd, const String8& cameraId); 947 948 // Mapping from camera ID -> state for each device, map is protected by mCameraStatesLock 949 std::map<String8, std::shared_ptr<CameraState>> mCameraStates; 950 951 // Mutex guarding mCameraStates map 952 mutable Mutex mCameraStatesLock; 953 954 /** 955 * Mapping from packageName -> {cameraIdToReplace -> newCameraIdtoUse}. 956 * 957 * This specifies that for packageName, for every binder operation targeting 958 * cameraIdToReplace, use newCameraIdToUse instead. 959 */ 960 typedef std::map<String16, std::map<String8, String8>> TCameraIdRemapping; 961 TCameraIdRemapping mCameraIdRemapping{}; 962 /** Mutex guarding mCameraIdRemapping. */ 963 Mutex mCameraIdRemappingLock; 964 965 /** Parses cameraIdRemapping parcelable into the native cameraIdRemappingMap. */ 966 binder::Status parseCameraIdRemapping( 967 const hardware::CameraIdRemapping& cameraIdRemapping, 968 /* out */ TCameraIdRemapping* cameraIdRemappingMap); 969 970 /** 971 * Resolve the (potentially remapped) camera Id to use for packageName. 972 * 973 * This returns the Camera Id to use in case inputCameraId was remapped to a 974 * different Id for the given packageName. Otherwise, it returns the inputCameraId. 975 * 976 * If the packageName is not provided, it will be inferred from the clientUid. 977 */ 978 String8 resolveCameraId( 979 const String8& inputCameraId, 980 int clientUid, 981 const String16& packageName = String16("")); 982 983 /** 984 * Updates the state of mCameraIdRemapping, while disconnecting active clients as necessary. 985 */ 986 void remapCameraIds(const TCameraIdRemapping& cameraIdRemapping); 987 988 /** 989 * Finds the Camera Ids that were remapped to the inputCameraId for the given client. 990 */ 991 std::vector<String8> findOriginalIdsForRemappedCameraId( 992 const String8& inputCameraId, int clientUid); 993 994 // Circular buffer for storing event logging for dumps 995 RingBuffer<String8> mEventLog; 996 Mutex mLogLock; 997 998 // set of client package names to watch. if this set contains 'all', then all clients will 999 // be watched. Access should be guarded by mLogLock 1000 std::set<String16> mWatchedClientPackages; 1001 // cache of last monitored tags dump immediately before the client disconnects. If a client 1002 // re-connects, its entry is not updated until it disconnects again. Access should be guarded 1003 // by mLogLock 1004 std::map<String16, std::string> mWatchedClientsDumpCache; 1005 1006 // The last monitored tags set by client 1007 String8 mMonitorTags; 1008 1009 // Currently allowed user IDs 1010 std::set<userid_t> mAllowedUsers; 1011 1012 /** 1013 * Get the camera state for a given camera id. 1014 * 1015 * This acquires mCameraStatesLock. 1016 */ 1017 std::shared_ptr<CameraService::CameraState> getCameraState(const String8& cameraId) const; 1018 1019 /** 1020 * Evict client who's remote binder has died. Returns true if this client was in the active 1021 * list and was disconnected. 1022 * 1023 * This method acquires mServiceLock. 1024 */ 1025 bool evictClientIdByRemote(const wp<IBinder>& cameraClient); 1026 1027 /** 1028 * Remove the given client from the active clients list; does not disconnect the client. 1029 * 1030 * This method acquires mServiceLock. 1031 */ 1032 void removeByClient(const BasicClient* client); 1033 1034 /** 1035 * Add new client to active clients list after conflicting clients have disconnected using the 1036 * values set in the partial descriptor passed in to construct the actual client descriptor. 1037 * This is typically called at the end of a connect call. 1038 * 1039 * This method must be called with mServiceLock held. 1040 */ 1041 void finishConnectLocked(const sp<BasicClient>& client, const DescriptorPtr& desc, 1042 int oomScoreOffset, bool systemNativeClient); 1043 1044 /** 1045 * Returns the underlying camera Id string mapped to a camera id int 1046 * Empty string is returned when the cameraIdInt is invalid. 1047 */ 1048 String8 cameraIdIntToStr(int cameraIdInt); 1049 1050 /** 1051 * Returns the underlying camera Id string mapped to a camera id int 1052 * Empty string is returned when the cameraIdInt is invalid. 1053 */ 1054 std::string cameraIdIntToStrLocked(int cameraIdInt); 1055 1056 /** 1057 * Remove a single client corresponding to the given camera id from the list of active clients. 1058 * If none exists, return an empty strongpointer. 1059 * 1060 * This method must be called with mServiceLock held. 1061 */ 1062 sp<CameraService::BasicClient> removeClientLocked(const String8& cameraId); 1063 1064 /** 1065 * Handle a notification that the current device user has changed. 1066 */ 1067 void doUserSwitch(const std::vector<int32_t>& newUserIds); 1068 1069 /** 1070 * Add an event log message. 1071 */ 1072 void logEvent(const char* event); 1073 1074 /** 1075 * Add an event log message that a client has been disconnected. 1076 */ 1077 void logDisconnected(const char* cameraId, int clientPid, const char* clientPackage); 1078 1079 /** 1080 * Add an event log message that a client has been disconnected from offline device. 1081 */ 1082 void logDisconnectedOffline(const char* cameraId, int clientPid, const char* clientPackage); 1083 1084 /** 1085 * Add an event log message that an offline client has been connected. 1086 */ 1087 void logConnectedOffline(const char* cameraId, int clientPid, 1088 const char* clientPackage); 1089 1090 /** 1091 * Add an event log message that a client has been connected. 1092 */ 1093 void logConnected(const char* cameraId, int clientPid, const char* clientPackage); 1094 1095 /** 1096 * Add an event log message that a client's connect attempt has been rejected. 1097 */ 1098 void logRejected(const char* cameraId, int clientPid, const char* clientPackage, 1099 const char* reason); 1100 1101 /** 1102 * Add an event log message when a client calls setTorchMode succesfully. 1103 */ 1104 void logTorchEvent(const char* cameraId, const char *torchState, int clientPid); 1105 1106 /** 1107 * Add an event log message that the current device user has been switched. 1108 */ 1109 void logUserSwitch(const std::set<userid_t>& oldUserIds, 1110 const std::set<userid_t>& newUserIds); 1111 1112 /** 1113 * Add an event log message that a device has been removed by the HAL 1114 */ 1115 void logDeviceRemoved(const char* cameraId, const char* reason); 1116 1117 /** 1118 * Add an event log message that a device has been added by the HAL 1119 */ 1120 void logDeviceAdded(const char* cameraId, const char* reason); 1121 1122 /** 1123 * Add an event log message that a client has unexpectedly died. 1124 */ 1125 void logClientDied(int clientPid, const char* reason); 1126 1127 /** 1128 * Add a event log message that a serious service-level error has occured 1129 * The errorCode should be one of the Android Errors 1130 */ 1131 void logServiceError(const char* msg, int errorCode); 1132 1133 /** 1134 * Dump the event log to an FD 1135 */ 1136 void dumpEventLog(int fd); 1137 1138 void cacheClientTagDumpIfNeeded(const char *cameraId, BasicClient *client); 1139 1140 /** 1141 * This method will acquire mServiceLock 1142 */ 1143 void updateCameraNumAndIds(); 1144 1145 /** 1146 * Filter camera characteristics for S Performance class primary cameras. 1147 * mServiceLock should be locked. 1148 */ 1149 void filterSPerfClassCharacteristicsLocked(); 1150 1151 // File descriptor to temp file used for caching previous open 1152 // session dumpsys info. 1153 int mMemFd; 1154 1155 // Number of camera devices (excluding hidden secure cameras) 1156 int mNumberOfCameras; 1157 // Number of camera devices (excluding hidden secure cameras and 1158 // system cameras) 1159 int mNumberOfCamerasWithoutSystemCamera; 1160 1161 std::vector<std::string> mNormalDeviceIds; 1162 std::vector<std::string> mNormalDeviceIdsWithoutSystemCamera; 1163 std::set<std::string> mPerfClassPrimaryCameraIds; 1164 1165 // sounds 1166 sp<MediaPlayer> newMediaPlayer(const char *file); 1167 1168 Mutex mSoundLock; 1169 sp<MediaPlayer> mSoundPlayer[NUM_SOUNDS]; 1170 int mSoundRef; // reference count (release all MediaPlayer when 0) 1171 1172 // Basic flag on whether the camera subsystem is in a usable state 1173 bool mInitialized; 1174 1175 sp<CameraProviderManager> mCameraProviderManager; 1176 1177 class ServiceListener : public virtual IBinder::DeathRecipient { 1178 public: ServiceListener(sp<CameraService> parent,sp<hardware::ICameraServiceListener> listener,int uid,int pid,bool isVendorClient,bool openCloseCallbackAllowed)1179 ServiceListener(sp<CameraService> parent, sp<hardware::ICameraServiceListener> listener, 1180 int uid, int pid, bool isVendorClient, bool openCloseCallbackAllowed) 1181 : mParent(parent), mListener(listener), mListenerUid(uid), mListenerPid(pid), 1182 mIsVendorListener(isVendorClient), 1183 mOpenCloseCallbackAllowed(openCloseCallbackAllowed) { } 1184 initialize(bool isProcessLocalTest)1185 status_t initialize(bool isProcessLocalTest) { 1186 if (isProcessLocalTest) { 1187 return OK; 1188 } 1189 return IInterface::asBinder(mListener)->linkToDeath(this); 1190 } 1191 1192 template<typename... args_t> handleBinderStatus(const binder::Status & ret,const char * logOnError,args_t...args)1193 void handleBinderStatus(const binder::Status &ret, const char *logOnError, 1194 args_t... args) { 1195 if (!ret.isOk() && 1196 (ret.exceptionCode() != binder::Status::Exception::EX_TRANSACTION_FAILED 1197 || !mLastTransactFailed)) { 1198 ALOGE(logOnError, args...); 1199 } 1200 1201 // If the transaction failed, the process may have died (or other things, see 1202 // b/28321379). Mute consecutive errors from this listener to avoid log spam. 1203 if (ret.exceptionCode() == binder::Status::Exception::EX_TRANSACTION_FAILED) { 1204 if (!mLastTransactFailed) { 1205 ALOGE("%s: Muting similar errors from listener %d:%d", __FUNCTION__, 1206 mListenerUid, mListenerPid); 1207 } 1208 mLastTransactFailed = true; 1209 } else { 1210 // Reset mLastTransactFailed when binder becomes healthy again. 1211 mLastTransactFailed = false; 1212 } 1213 } 1214 binderDied(const wp<IBinder> &)1215 virtual void binderDied(const wp<IBinder> &/*who*/) { 1216 auto parent = mParent.promote(); 1217 if (parent.get() != nullptr) { 1218 parent->removeListener(mListener); 1219 } 1220 } 1221 getListenerUid()1222 int getListenerUid() { return mListenerUid; } getListenerPid()1223 int getListenerPid() { return mListenerPid; } getListener()1224 sp<hardware::ICameraServiceListener> getListener() { return mListener; } isVendorListener()1225 bool isVendorListener() { return mIsVendorListener; } isOpenCloseCallbackAllowed()1226 bool isOpenCloseCallbackAllowed() { return mOpenCloseCallbackAllowed; } 1227 1228 private: 1229 wp<CameraService> mParent; 1230 sp<hardware::ICameraServiceListener> mListener; 1231 int mListenerUid = -1; 1232 int mListenerPid = -1; 1233 bool mIsVendorListener = false; 1234 bool mOpenCloseCallbackAllowed = false; 1235 1236 // Flag for preventing log spam when binder becomes unhealthy 1237 bool mLastTransactFailed = false; 1238 }; 1239 1240 // Guarded by mStatusListenerMutex 1241 std::vector<sp<ServiceListener>> mListenerList; 1242 1243 Mutex mStatusListenerLock; 1244 1245 /** 1246 * Update the status for the given camera id (if that device exists), and broadcast the 1247 * status update to all current ICameraServiceListeners if the status has changed. Any 1248 * statuses in rejectedSourceStates will be ignored. 1249 * 1250 * This method must be idempotent. 1251 * This method acquires mStatusLock and mStatusListenerLock. 1252 */ 1253 void updateStatus(StatusInternal status, 1254 const String8& cameraId, 1255 std::initializer_list<StatusInternal> 1256 rejectedSourceStates); 1257 void updateStatus(StatusInternal status, 1258 const String8& cameraId); 1259 1260 /** 1261 * Update the opened/closed status of the given camera id. 1262 * 1263 * This method acqiures mStatusListenerLock. 1264 */ 1265 void updateOpenCloseStatus(const String8& cameraId, bool open, const String16& packageName); 1266 1267 // flashlight control 1268 sp<CameraFlashlight> mFlashlight; 1269 // guard mTorchStatusMap 1270 Mutex mTorchStatusMutex; 1271 // guard mTorchClientMap 1272 Mutex mTorchClientMapMutex; 1273 // guard mTorchUidMap 1274 Mutex mTorchUidMapMutex; 1275 // camera id -> torch status 1276 KeyedVector<String8, TorchModeStatus> 1277 mTorchStatusMap; 1278 // camera id -> torch client binder 1279 // only store the last client that turns on each camera's torch mode 1280 KeyedVector<String8, sp<IBinder>> mTorchClientMap; 1281 // camera id -> [incoming uid, current uid] pair 1282 std::map<String8, std::pair<int, int>> mTorchUidMap; 1283 1284 // check and handle if torch client's process has died 1285 void handleTorchClientBinderDied(const wp<IBinder> &who); 1286 1287 // handle torch mode status change and invoke callbacks. mTorchStatusMutex 1288 // should be locked. 1289 void onTorchStatusChangedLocked(const String8& cameraId, 1290 TorchModeStatus newStatus, 1291 SystemCameraKind systemCameraKind); 1292 1293 // get a camera's torch status. mTorchStatusMutex should be locked. 1294 status_t getTorchStatusLocked(const String8 &cameraId, 1295 TorchModeStatus *status) const; 1296 1297 // set a camera's torch status. mTorchStatusMutex should be locked. 1298 status_t setTorchStatusLocked(const String8 &cameraId, 1299 TorchModeStatus status); 1300 1301 // notify physical camera status when the physical camera is public. 1302 // Expects mStatusListenerLock to be locked. 1303 void notifyPhysicalCameraStatusLocked(int32_t status, const String16& physicalCameraId, 1304 const std::list<String16>& logicalCameraIds, SystemCameraKind deviceKind); 1305 1306 // get list of logical cameras which are backed by physicalCameraId 1307 std::list<String16> getLogicalCameras(const String8& physicalCameraId); 1308 1309 1310 // IBinder::DeathRecipient implementation 1311 virtual void binderDied(const wp<IBinder> &who); 1312 1313 /** 1314 * Initialize and cache the metadata used by the HAL1 shim for a given cameraId. 1315 * 1316 * Sets Status to a service-specific error on failure 1317 */ 1318 binder::Status initializeShimMetadata(int cameraId); 1319 1320 /** 1321 * Get the cached CameraParameters for the camera. If they haven't been 1322 * cached yet, then initialize them for the first time. 1323 * 1324 * Sets Status to a service-specific error on failure 1325 */ 1326 binder::Status getLegacyParametersLazy(int cameraId, /*out*/CameraParameters* parameters); 1327 1328 // Blocks all clients from the UID 1329 void blockClientsForUid(uid_t uid); 1330 1331 // Blocks all active clients. 1332 void blockAllClients(); 1333 1334 // Overrides the UID state as if it is idle 1335 status_t handleSetUidState(const Vector<String16>& args, int err); 1336 1337 // Clears the override for the UID state 1338 status_t handleResetUidState(const Vector<String16>& args, int err); 1339 1340 // Gets the UID state 1341 status_t handleGetUidState(const Vector<String16>& args, int out, int err); 1342 1343 // Set the rotate-and-crop AUTO override behavior 1344 status_t handleSetRotateAndCrop(const Vector<String16>& args); 1345 1346 // Get the rotate-and-crop AUTO override behavior 1347 status_t handleGetRotateAndCrop(int out); 1348 1349 // Set the autoframing AUTO override behaviour. 1350 status_t handleSetAutoframing(const Vector<String16>& args); 1351 1352 // Get the autoframing AUTO override behaviour 1353 status_t handleGetAutoframing(int out); 1354 1355 // Set the mask for image dump to disk 1356 status_t handleSetImageDumpMask(const Vector<String16>& args); 1357 1358 // Get the mask for image dump to disk 1359 status_t handleGetImageDumpMask(int out); 1360 1361 // Set the camera mute state 1362 status_t handleSetCameraMute(const Vector<String16>& args); 1363 1364 // Set the stream use case overrides 1365 status_t handleSetStreamUseCaseOverrides(const Vector<String16>& args); 1366 1367 // Clear the stream use case overrides 1368 void handleClearStreamUseCaseOverrides(); 1369 1370 // Set or clear the zoom override flag 1371 status_t handleSetZoomOverride(const Vector<String16>& args); 1372 1373 // Set Camera Id remapping using 'cmd' 1374 status_t handleCameraIdRemapping(const Vector<String16>& args, int errFd); 1375 1376 // Handle 'watch' command as passed through 'cmd' 1377 status_t handleWatchCommand(const Vector<String16> &args, int inFd, int outFd); 1378 1379 // Set the camera service watchdog 1380 status_t handleSetCameraServiceWatchdog(const Vector<String16>& args); 1381 1382 // Enable tag monitoring of the given tags in provided clients 1383 status_t startWatchingTags(const Vector<String16> &args, int outFd); 1384 1385 // Disable tag monitoring 1386 status_t stopWatchingTags(int outFd); 1387 1388 // Clears mWatchedClientsDumpCache 1389 status_t clearCachedMonitoredTagDumps(int outFd); 1390 1391 // Print events of monitored tags in all cached and attached clients 1392 status_t printWatchedTags(int outFd); 1393 1394 // Print events of monitored tags in all attached clients as they are captured. New events are 1395 // fetched every `refreshMillis` ms 1396 // NOTE: This function does not terminate until user passes '\n' to inFd. 1397 status_t printWatchedTagsUntilInterrupt(const Vector<String16> &args, int inFd, int outFd); 1398 1399 // Parses comma separated clients list and adds them to mWatchedClientPackages. 1400 // Does not acquire mLogLock before modifying mWatchedClientPackages. It is the caller's 1401 // responsibility to acquire mLogLock before calling this function. 1402 void parseClientsToWatchLocked(String8 clients); 1403 1404 // Prints the shell command help 1405 status_t printHelp(int out); 1406 1407 // Returns true if client should monitor tags based on the contents of mWatchedClientPackages. 1408 // Acquires mLogLock before querying mWatchedClientPackages. 1409 bool isClientWatched(const BasicClient *client); 1410 1411 // Returns true if client should monitor tags based on the contents of mWatchedClientPackages. 1412 // Does not acquire mLogLock before querying mWatchedClientPackages. It is the caller's 1413 // responsibility to acquire mLogLock before calling this functions. 1414 bool isClientWatchedLocked(const BasicClient *client); 1415 1416 /** 1417 * Get the current system time as a formatted string. 1418 */ 1419 static String8 getFormattedCurrentTime(); 1420 1421 static binder::Status makeClient( 1422 const sp<CameraService>& cameraService, const sp<IInterface>& cameraCb, 1423 const String16& packageName, bool systemNativeClient, 1424 const std::optional<String16>& featureId, const String8& cameraId, int api1CameraId, 1425 int facing, int sensorOrientation, int clientPid, uid_t clientUid, int servicePid, 1426 std::pair<int, IPCTransport> deviceVersionAndIPCTransport, apiLevel effectiveApiLevel, 1427 bool overrideForPerfClass, bool overrideToPortrait, bool forceSlowJpegMode, 1428 const String8& originalCameraId, 1429 /*out*/ sp<BasicClient>* client); 1430 1431 status_t checkCameraAccess(const String16& opPackageName); 1432 1433 static String8 toString(std::set<userid_t> intSet); 1434 static int32_t mapToInterface(TorchModeStatus status); 1435 static StatusInternal mapToInternal(CameraDeviceStatus status); 1436 static int32_t mapToInterface(StatusInternal status); 1437 1438 1439 void broadcastTorchModeStatus(const String8& cameraId, 1440 TorchModeStatus status, SystemCameraKind systemCameraKind); 1441 1442 void broadcastTorchStrengthLevel(const String8& cameraId, int32_t newTorchStrengthLevel); 1443 1444 void disconnectClient(const String8& id, sp<BasicClient> clientToDisconnect); 1445 1446 // Regular online and offline devices must not be in conflict at camera service layer. 1447 // Use separate keys for offline devices. 1448 static const String8 kOfflineDevice; 1449 1450 // Sentinel value to be stored in `mWatchedClientsPackages` to indicate that all clients should 1451 // be watched. 1452 static const String16 kWatchAllClientsFlag; 1453 1454 // TODO: right now each BasicClient holds one AppOpsManager instance. 1455 // We can refactor the code so all of clients share this instance 1456 AppOpsManager mAppOps; 1457 1458 // Aggreated audio restriction mode for all camera clients 1459 int32_t mAudioRestriction; 1460 1461 // Current override cmd rotate-and-crop mode; AUTO means no override 1462 uint8_t mOverrideRotateAndCropMode = ANDROID_SCALER_ROTATE_AND_CROP_AUTO; 1463 1464 // Current autoframing mode 1465 uint8_t mOverrideAutoframingMode = ANDROID_CONTROL_AUTOFRAMING_AUTO; 1466 1467 // Current image dump mask 1468 uint8_t mImageDumpMask = 0; 1469 1470 // Current camera mute mode 1471 bool mOverrideCameraMuteMode = false; 1472 1473 // Camera Service watchdog flag 1474 bool mCameraServiceWatchdogEnabled = true; 1475 1476 // Current stream use case overrides 1477 std::vector<int64_t> mStreamUseCaseOverrides; 1478 1479 // Current zoom override value 1480 int32_t mZoomOverrideValue = -1; 1481 1482 /** 1483 * A listener class that implements the IBinder::DeathRecipient interface 1484 * for use to call back the error state injected by the external camera, and 1485 * camera service can kill the injection when binder signals process death. 1486 */ 1487 class InjectionStatusListener : public virtual IBinder::DeathRecipient { 1488 public: InjectionStatusListener(sp<CameraService> parent)1489 InjectionStatusListener(sp<CameraService> parent) : mParent(parent) {} 1490 1491 void addListener(const sp<hardware::camera2::ICameraInjectionCallback>& callback); 1492 void removeListener(); 1493 void notifyInjectionError(String8 injectedCamId, status_t err); 1494 1495 // IBinder::DeathRecipient implementation 1496 virtual void binderDied(const wp<IBinder>& who); 1497 1498 private: 1499 Mutex mListenerLock; 1500 wp<CameraService> mParent; 1501 sp<hardware::camera2::ICameraInjectionCallback> mCameraInjectionCallback; 1502 }; 1503 1504 sp<InjectionStatusListener> mInjectionStatusListener; 1505 1506 /** 1507 * A class that implements the hardware::camera2::BnCameraInjectionSession interface 1508 */ 1509 class CameraInjectionSession : public hardware::camera2::BnCameraInjectionSession { 1510 public: CameraInjectionSession(sp<CameraService> parent)1511 CameraInjectionSession(sp<CameraService> parent) : mParent(parent) {} ~CameraInjectionSession()1512 virtual ~CameraInjectionSession() {} 1513 binder::Status stopInjection() override; 1514 1515 private: 1516 Mutex mInjectionSessionLock; 1517 wp<CameraService> mParent; 1518 }; 1519 1520 // When injecting the camera, it will check whether the injecting camera status is unavailable. 1521 // If it is, the disconnect function will be called to to prevent camera access on the device. 1522 status_t checkIfInjectionCameraIsPresent(const String8& externalCamId, 1523 sp<BasicClient> clientSp); 1524 1525 void clearInjectionParameters(); 1526 1527 // This is the existing camera id being replaced. 1528 String8 mInjectionInternalCamId; 1529 // This is the external camera Id replacing the internalId. 1530 String8 mInjectionExternalCamId; 1531 bool mInjectionInitPending = false; 1532 // Guard mInjectionInternalCamId and mInjectionInitPending. 1533 Mutex mInjectionParametersLock; 1534 1535 // Track the folded/unfoled device state. 0 == UNFOLDED, 4 == FOLDED 1536 int64_t mDeviceState; 1537 1538 void updateTorchUidMapLocked(const String16& cameraId, int uid); 1539 }; 1540 1541 } // namespace android 1542 1543 #endif 1544