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