1 /* 2 * Copyright (c) 2022-2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef OHOS_AVSESSION_SERVICE_H 17 #define OHOS_AVSESSION_SERVICE_H 18 19 #include <atomic> 20 #include <mutex> 21 #include <map> 22 23 #include "iremote_stub.h" 24 #include "system_ability.h" 25 #include "audio_info.h" 26 #include "avsession_service_stub.h" 27 #include "avsession_item.h" 28 #include "avcontroller_item.h" 29 #include "session_container.h" 30 #include "iclient_death.h" 31 #include "isession_listener.h" 32 #include "focus_session_strategy.h" 33 #include "background_audio_controller.h" 34 #include "ability_manager_adapter.h" 35 #include "device_manager.h" 36 #include "dm_device_info.h" 37 #include "audio_adapter.h" 38 #include "remote_session_command_process.h" 39 #include "i_avsession_service_listener.h" 40 #include "avqueue_info.h" 41 #include "migrate/migrate_avsession_server.h" 42 43 #include "common_event_manager.h" 44 #include "common_event_subscribe_info.h" 45 #include "common_event_subscriber.h" 46 #include "common_event_support.h" 47 #include "matching_skills.h" 48 49 #include "avsession_users_manager.h" 50 51 #ifdef BLUETOOTH_ENABLE 52 #include "bluetooth_host.h" 53 #endif 54 55 namespace OHOS::AVSession { 56 class AVSessionDumper; 57 58 class ClientDeathRecipient : public IRemoteObject::DeathRecipient { 59 public: 60 explicit ClientDeathRecipient(const std::function<void()>& callback); 61 62 void OnRemoteDied(const wptr<IRemoteObject>& object) override; 63 64 private: 65 std::function<void()> callback_; 66 }; 67 68 class AVSessionInitDMCallback : public OHOS::DistributedHardware::DmInitCallback { 69 public: 70 AVSessionInitDMCallback() = default; 71 ~AVSessionInitDMCallback() override = default; 72 void OnRemoteDied() override {}; 73 }; 74 75 #ifdef BLUETOOTH_ENABLE 76 class DetectBluetoothHostObserver : public OHOS::Bluetooth::BluetoothHostObserver { 77 public: 78 DetectBluetoothHostObserver(AVSessionService *ptr); 79 virtual ~DetectBluetoothHostObserver() = default; 80 void OnStateChanged(const int transport, const int status) override; 81 void OnDiscoveryStateChanged(int status) override 82 { 83 return; 84 } 85 86 void OnDiscoveryResult(const OHOS::Bluetooth::BluetoothRemoteDevice &device, int rssi, 87 const std::string deviceName, int deviceClass) override 88 { 89 return; 90 } 91 92 void OnPairRequested(const OHOS::Bluetooth::BluetoothRemoteDevice &device) override 93 { 94 return; 95 } 96 97 void OnPairConfirmed(const OHOS::Bluetooth::BluetoothRemoteDevice &device, int reqType, int number) override 98 { 99 return; 100 } 101 102 void OnScanModeChanged(int mode) override 103 { 104 return; 105 } 106 107 void OnDeviceNameChanged(const std::string &deviceName) override 108 { 109 return; 110 } 111 112 void OnDeviceAddrChanged(const std::string &address) override 113 { 114 return; 115 } 116 117 private: 118 bool is2in1_ = false; 119 bool lastEnabled_ = false; 120 AVSessionService *servicePtr_ = nullptr; 121 }; 122 #endif 123 124 class EventSubscriber : public EventFwk::CommonEventSubscriber { 125 public: 126 EventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscriberInfo, AVSessionService *ptr); 127 virtual ~EventSubscriber() = default; 128 void OnReceiveEvent(const EventFwk::CommonEventData &eventData) override; 129 private: 130 AVSessionService *servicePtr_ = nullptr; 131 }; 132 133 class AVSessionService : public SystemAbility, public AVSessionServiceStub, public IAVSessionServiceListener { 134 DECLARE_SYSTEM_ABILITY(AVSessionService); 135 136 public: 137 DISALLOW_COPY_AND_MOVE(AVSessionService); 138 139 explicit AVSessionService(int32_t systemAbilityId, bool runOnCreate = true); 140 141 ~AVSessionService() override; 142 143 void OnDump() override; 144 145 void OnStart() override; 146 147 void OnStop() override; 148 149 void PullMigrateStub(); 150 151 void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; 152 153 void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; 154 155 sptr<IRemoteObject> CreateSessionInner(const std::string& tag, int32_t type, 156 const AppExecFwk::ElementName& elementName) override; 157 158 int32_t CreateSessionInner(const std::string& tag, int32_t type, const AppExecFwk::ElementName& elementName, 159 sptr<IRemoteObject>& object) override; 160 161 int32_t GetAllSessionDescriptors(std::vector<AVSessionDescriptor>& descriptors) override; 162 163 int32_t GetSessionDescriptorsBySessionId(const std::string& sessionId, AVSessionDescriptor& descriptor) override; 164 165 int32_t GetHistoricalSessionDescriptors(int32_t maxSize, std::vector<AVSessionDescriptor>& descriptors) override; 166 167 int32_t GetHistoricalAVQueueInfos(int32_t maxSize, int32_t maxAppSize, 168 std::vector<AVQueueInfo>& avQueueInfos) override; 169 170 int32_t StartAVPlayback(const std::string& bundleName, const std::string& assetId) override; 171 172 int32_t CreateControllerInner(const std::string& sessionId, sptr<IRemoteObject>& object) override; 173 174 bool IsAudioPlaybackAllowed(const int32_t uid, const int32_t pid) override; 175 176 #ifdef CASTPLUS_CAST_ENGINE_ENABLE 177 int32_t GetAVCastControllerInner(const std::string& sessionId, sptr<IRemoteObject>& object) override; 178 #endif 179 180 int32_t RegisterSessionListener(const sptr<ISessionListener>& listener) override; 181 182 int32_t RegisterSessionListenerForAllUsers(const sptr<ISessionListener>& listener) override; 183 184 int32_t SendSystemAVKeyEvent(const MMI::KeyEvent& keyEvent) override; 185 186 int32_t SendSystemControlCommand(const AVControlCommand& command) override; 187 188 int32_t RegisterClientDeathObserver(const sptr<IClientDeath>& observer) override; 189 190 void OnClientDied(pid_t pid); 191 192 void HandleSessionRelease(std::string sessionId); 193 194 void HandleCallStartEvent(); 195 196 #ifdef CASTPLUS_CAST_ENGINE_ENABLE 197 __attribute__((no_sanitize("cfi"))) int32_t MirrorToStreamCast(sptr<AVSessionItem>& session); 198 199 void SplitExtraInfo(std::string info); 200 #endif 201 202 void HandleControllerRelease(AVControllerItem& controller); 203 204 std::int32_t Dump(std::int32_t fd, const std::vector<std::u16string>& args) override; 205 206 int32_t CastAudio(const SessionToken& token, 207 const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkAudioDescriptors) override; 208 209 int32_t CastAudioForAll(const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkAudioDescriptors) override; 210 NotifyAudioSessionCheckTrigger(const int32_t uid)211 void NotifyAudioSessionCheckTrigger(const int32_t uid) 212 { 213 return NotifyAudioSessionCheck(uid); 214 } 215 216 void SuperLauncher(std::string deviceId, std::string serviceName, 217 std::string extraInfo, const std::string& state); 218 219 #ifdef CASTPLUS_CAST_ENGINE_ENABLE 220 void ReleaseCastSession() override; 221 222 void CreateSessionByCast(const int64_t castHandle) override; 223 224 void NotifyDeviceAvailable(const OutputDeviceInfo& castOutputDeviceInfo) override; 225 226 void NotifyDeviceLogEvent(const DeviceLogEventCode eventId, const int64_t param) override; 227 228 void NotifyDeviceOffline(const std::string& deviceId) override; 229 230 void NotifyMirrorToStreamCast(); 231 232 int32_t StartCast(const SessionToken& sessionToken, const OutputDeviceInfo& outputDeviceInfo) override; 233 234 int32_t StopCast(const SessionToken& sessionToken) override; 235 236 int32_t checkEnableCast(bool enable) override; 237 #endif 238 239 int32_t Close(void) override; 240 241 void AddAvQueueInfoToFile(AVSessionItem& session); 242 243 void SetScreenOn(bool on); 244 245 bool GetScreenOn(); 246 247 void SetScreenLocked(bool isLocked); 248 249 bool GetScreenLocked(); 250 251 std::string GetAVQueueDir(int32_t userId = 0); 252 253 std::string GetAVSortDir(int32_t userId = 0); 254 255 void HandleUserEvent(const std::string &type, const int &userId); 256 257 void HandleScreenStatusChange(std::string event); 258 259 void RegisterBundleDeleteEventForHistory(int32_t userId = 0); 260 261 private: 262 void CheckBrEnable(); 263 264 void NotifyProcessStatus(bool isStart); 265 266 static SessionContainer& GetContainer(); 267 static AVSessionUsersManager& GetUsersManager(); 268 269 std::string AllocSessionId(); 270 271 bool AbilityHasSession(pid_t pid); 272 273 sptr<AVControllerItem> GetPresentController(pid_t pid, const std::string& sessionId); 274 275 void NotifySessionCreate(const AVSessionDescriptor& descriptor); 276 void NotifySessionRelease(const AVSessionDescriptor& descriptor); 277 void NotifyTopSessionChanged(const AVSessionDescriptor& descriptor); 278 void NotifyAudioSessionCheck(const int32_t uid); 279 void NotifySystemUI(const AVSessionDescriptor* historyDescriptor, bool isActiveSession); 280 void NotifyDeviceChange(const DeviceChangeAction& deviceChangeAction); 281 282 void AddClientDeathObserver(pid_t pid, const sptr<IClientDeath>& observer, 283 const sptr<ClientDeathRecipient> recipient); 284 void RemoveClientDeathObserver(pid_t pid); 285 286 void AddSessionListener(pid_t pid, const sptr<ISessionListener>& listener); 287 void AddSessionListenerForAllUsers(pid_t pid, const sptr<ISessionListener>& listener); 288 void RemoveSessionListener(pid_t pid); 289 290 void AddInnerSessionListener(SessionListener* listener); 291 void RemoveInnerSessionListener(SessionListener* listener); 292 293 sptr<AVSessionItem> SelectSessionByUid(const AudioStandard::AudioRendererChangeInfo& info); 294 295 void OutputDeviceChangeListener(const AudioRendererChangeInfos& infos); 296 297 sptr<AVSessionItem> CreateSessionInner(const std::string& tag, int32_t type, bool thirdPartyApp, 298 const AppExecFwk::ElementName& elementName); 299 300 int32_t CreateSessionInner(const std::string& tag, int32_t type, bool thirdPartyApp, 301 const AppExecFwk::ElementName& elementName, sptr<AVSessionItem>& sessionItem); 302 303 bool IsParamInvalid(const std::string& tag, int32_t type, const AppExecFwk::ElementName& elementName); 304 305 void ServiceCallback(sptr<AVSessionItem>& sessionItem); 306 307 sptr<AVSessionItem> CreateNewSession(const std::string& tag, int32_t type, bool thirdPartyApp, 308 const AppExecFwk::ElementName& elementName); 309 310 sptr<AVControllerItem> CreateNewControllerForSession(pid_t pid, sptr<AVSessionItem>& session); 311 312 int32_t CancelCastAudioForClientExit(pid_t pid, const sptr<AVSessionItem>& session); 313 314 void ClearSessionForClientDiedNoLock(pid_t pid); 315 316 void ClearControllerForClientDiedNoLock(pid_t pid); 317 318 void InitKeyEvent(); 319 320 void InitAudio(); 321 322 void InitAMS(); 323 324 void InitDM(); 325 326 void InitBMS(); 327 328 void InitRadarBMS(); 329 330 void InitAccountMgr(); 331 332 void InitCommonEventService(); 333 334 bool SelectFocusSession(const FocusSessionStrategy::FocusSessionChangeInfo& info); 335 336 void RefreshFocusSessionSort(sptr<AVSessionItem> &session); 337 338 void UpdateTopSession(const sptr<AVSessionItem>& newTopSession); 339 340 void HandleFocusSession(const FocusSessionStrategy::FocusSessionChangeInfo& info); 341 342 void HandleDeviceChange(const AudioStandard::DeviceChangeAction& deviceChangeAction); 343 344 __attribute__((no_sanitize("cfi"))) std::shared_ptr<RemoteSessionCommandProcess> GetService( 345 const std::string& deviceId); 346 347 int32_t CastAudioProcess(const std::vector<AudioStandard::AudioDeviceDescriptor>& descriptors, 348 const std::string& sourceSessionInfo, 349 sptr<AVSessionItem>& session); 350 351 int32_t CastAudioInner(const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkAudioDescriptors, 352 const std::string& sourceSessionInfo, 353 const sptr<AVSessionItem>& session); 354 355 int32_t CancelCastAudioInner(const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkDevices, 356 const std::string& sourceSessionInfo, 357 const sptr<AVSessionItem>& session); 358 359 int32_t RemoteCastAudioInner(const std::string& sourceSessionInfo, std::string& sinkSessionInfo); 360 361 int32_t RemoteCancelCastAudioInner(const std::string& sessionInfo); 362 363 int32_t ProcessCastAudioCommand(const RemoteServiceCommand command, const std::string& input, 364 std::string& output) override; 365 366 int32_t CastAudioForNewSession(const sptr<AVSessionItem>& session); 367 368 bool IsLocalDevice(const std::string& networkId); 369 370 int32_t GetLocalNetworkId(std::string& networkId); 371 372 int32_t GetTrustedDeviceName(const std::string& networkId, std::string& deviceName); 373 374 int32_t GetTrustedDevicesInfo(std::vector<OHOS::DistributedHardware::DmDeviceInfo>& deviceList); 375 376 int32_t SetBasicInfo(std::string& sessionInfo); 377 378 void SetDeviceInfo(const std::vector<AudioStandard::AudioDeviceDescriptor>& castAudioDescriptors, 379 sptr<AVSessionItem>& session); 380 381 int32_t GetAudioDescriptor(const std::string deviceId, 382 std::vector<AudioStandard::AudioDeviceDescriptor>& audioDeviceDescriptors); 383 384 bool GetAudioDescriptorByDeviceId(const std::vector<sptr<AudioStandard::AudioDeviceDescriptor>>& descriptors, 385 const std::string& deviceId, 386 AudioStandard::AudioDeviceDescriptor& audioDescriptor); 387 388 void GetDeviceInfo(const sptr<AVSessionItem>& session, 389 const std::vector<AudioStandard::AudioDeviceDescriptor>& descriptors, 390 std::vector<AudioStandard::AudioDeviceDescriptor>& castSinkDescriptors, 391 std::vector<AudioStandard::AudioDeviceDescriptor>& cancelSinkDescriptors); 392 393 int32_t SelectOutputDevice(const int32_t uid, const AudioStandard::AudioDeviceDescriptor& descriptor); 394 395 int32_t StartDefaultAbilityByCall(std::string& sessionId); 396 397 int32_t StartAbilityByCall(const std::string& sessionIdNeeded, std::string& sessionId); 398 399 void HandleEventHandlerCallBack(); 400 401 bool IsHistoricalSession(const std::string& sessionId); 402 403 void DeleteHistoricalRecord(const std::string& bundleName, int32_t userId = 0); 404 405 void DeleteAVQueueInfoRecord(const std::string& bundleName, int32_t userId = 0); 406 407 const nlohmann::json& GetSubNode(const nlohmann::json& node, const std::string& name); 408 409 void SaveSessionInfoInFile(const std::string& sessionId, const std::string& sessionType, 410 const AppExecFwk::ElementName& elementName); 411 412 bool CheckAndCreateDir(const std::string& filePath); 413 414 bool CheckUserDirValid(int32_t userId = 0); 415 416 bool LoadStringFromFileEx(const std::string& filePath, std::string& content); 417 418 bool SaveStringToFileEx(const std::string& filePath, const std::string& content); 419 420 bool CheckStringAndCleanFile(const std::string& filePath); 421 422 void ClearClientResources(pid_t pid); 423 424 bool SaveAvQueueInfo(std::string& oldContent, const std::string &bundleName, 425 const AVMetaData& meta, const int32_t userId); 426 427 int32_t GetHistoricalSessionDescriptorsFromFile(std::vector<AVSessionDescriptor>& descriptors); 428 429 void ReportStartCastBegin(std::string func, const OutputDeviceInfo& outputDeviceInfo, int32_t uid); 430 431 void ReportStartCastEnd(std::string func, const OutputDeviceInfo &outputDeviceInfo, int32_t uid, int ret); 432 433 void HandleAppStateChange(int uid, int state); 434 435 void UpdateFrontSession(sptr<AVSessionItem>& sessionItem, bool isAdd); 436 437 std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> CreateWantAgent( 438 const AVSessionDescriptor* histroyDescriptor); 439 440 void DoMetadataImgClean(AVMetaData& data); 441 442 void HandleSystemKeyColdStart(const AVControlCommand &command); 443 444 bool SubscribeCommonEvent(); 445 446 bool UnSubscribeCommonEvent(); 447 448 void ReportSessionInfo(const sptr <AVSessionItem>& session, int res); 449 450 bool CheckAncoAudio(); 451 452 int32_t ConvertKeyCodeToCommand(int keyCode); 453 454 void RemoveExpired(std::list<std::chrono::system_clock::time_point> &list, 455 const std::chrono::system_clock::time_point &now, int32_t time = 1); 456 457 std::shared_ptr<std::list<sptr<AVSessionItem>>> GetCurSessionListForFront(); 458 459 std::atomic<uint32_t> sessionSeqNum_ {}; 460 461 sptr<AVSessionItem> topSession_; 462 std::map<pid_t, std::list<sptr<AVControllerItem>>> controllers_; 463 std::map<pid_t, sptr<IClientDeath>> clientDeathObservers_; 464 std::map<pid_t, sptr<ClientDeathRecipient>> clientDeathRecipients_; 465 std::list<SessionListener*> innerSessionListeners_; 466 std::map<std::string, std::shared_ptr<AbilityManagerAdapter>> abilityManager_; 467 FocusSessionStrategy focusSessionStrategy_; 468 BackgroundAudioController backgroundAudioController_; 469 std::map<std::string, std::string> castAudioSessionMap_; 470 bool isAllSessionCast_ {}; 471 std::string outputDeviceId_; 472 std::unique_ptr<AVSessionDumper> dumpHelper_ {}; 473 friend class AVSessionDumper; 474 std::shared_ptr<MigrateAVSessionServer> migrateAVSession_; 475 std::shared_ptr<EventSubscriber> subscriber_; 476 bool isScreenOn_ = false; 477 bool isScreenLocked_ = true; 478 std::list<std::chrono::system_clock::time_point> flowControlPublishTimestampList_; 479 480 // The following locks are used in the defined order of priority 481 std::recursive_mutex sessionServiceLock_; 482 483 std::recursive_mutex sessionFrontLock_; 484 485 std::recursive_mutex sessionListenersLock_; 486 487 std::recursive_mutex migrateListenersLock_; 488 489 std::recursive_mutex sessionFileLock_; 490 491 std::recursive_mutex avQueueFileLock_; 492 493 std::recursive_mutex abilityManagerLock_; 494 495 std::recursive_mutex screenStateLock_; 496 497 std::recursive_mutex clientDeathLock_; 498 499 // DMSDP related locks 500 std::recursive_mutex isAllSessionCastLock_; 501 502 std::recursive_mutex outputDeviceIdLock_; 503 504 std::recursive_mutex castAudioSessionMapLock_; 505 506 #ifdef BLUETOOTH_ENABLE 507 OHOS::Bluetooth::BluetoothHost *bluetoothHost_ = nullptr; 508 std::shared_ptr<DetectBluetoothHostObserver> bluetoothObserver; 509 #endif 510 511 #ifdef CASTPLUS_CAST_ENGINE_ENABLE 512 std::map<std::string, std::string> castServiceNameMapState_; 513 const std::string deviceStateConnection = "CONNECT_SUCC"; 514 const std::string seperator = ","; 515 int appState = -1; 516 bool isSupportMirrorToStream_ = false; 517 std::string castDeviceId_ = "0"; 518 std::string castDeviceName_ = " "; 519 int32_t castDeviceType_ = 0; 520 const int32_t beginAddPos = 3; 521 const int32_t endDecPos = 4; 522 const int32_t typeAddPos = 2; 523 #endif 524 525 static constexpr const char *SORT_FILE_NAME = "sortinfo"; 526 static constexpr const char *DEFAULT_SESSION_ID = "default"; 527 static constexpr const char *DEFAULT_BUNDLE_NAME = "com.example.himusicdemo"; 528 static constexpr const char *DEFAULT_ABILITY_NAME = "MainAbility"; 529 static constexpr const int32_t SYSTEMUI_LIVEVIEW_TYPECODE_MDEDIACONTROLLER = 2; 530 static constexpr const char *AVQUEUE_FILE_NAME = "avqueueinfo"; 531 532 const std::string MEDIA_CONTROL_BUNDLENAME = "com.ohos.mediacontroller"; 533 const std::string MEDIA_CONTROL_ABILITYNAME = "com.ohos.mediacontroller.avplayer.mainability"; 534 535 int32_t pressCount_ {}; 536 int32_t maxHistoryNums_ = 10; 537 int uidForAppStateChange_ = 0; 538 bool isFirstPress_ = true; 539 bool isSourceInCast_ = false; 540 bool isInCast_ = false; 541 bool is2in1_ = false; 542 543 void *migrateStubFuncHandle_ = nullptr; 544 545 const int32_t ONE_CLICK = 1; 546 const int32_t DOUBLE_CLICK = 2; 547 const int32_t THREE_CLICK = 3; 548 const int32_t unSetHistoryNum = 3; 549 const int32_t CLICK_TIMEOUT = 500; 550 const int32_t defMaxHistoryNum = 10; 551 const int32_t maxFileLength = 32 * 1024 * 1024; 552 const int32_t maxAVQueueInfoLen = 99; 553 const int32_t allocSpace = 2; 554 const int32_t avSessionUid = 6700; 555 const int32_t ancoUid = 1041; 556 const int32_t saType = 1; 557 const int32_t MAX_NOTIFICATION_NUM = 3; 558 const int32_t NOTIFICATION_CONTROL_TIME = 1000; 559 }; 560 } // namespace OHOS::AVSession 561 #endif // OHOS_AVSESSION_SERVICE_H 562