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; OnRemoteDied()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; OnDiscoveryStateChanged(int status)81 void OnDiscoveryStateChanged(int status) override 82 { 83 return; 84 } 85 OnDiscoveryResult(const OHOS::Bluetooth::BluetoothRemoteDevice & device,int rssi,const std::string deviceName,int deviceClass)86 void OnDiscoveryResult(const OHOS::Bluetooth::BluetoothRemoteDevice &device, int rssi, 87 const std::string deviceName, int deviceClass) override 88 { 89 return; 90 } 91 OnPairRequested(const OHOS::Bluetooth::BluetoothRemoteDevice & device)92 void OnPairRequested(const OHOS::Bluetooth::BluetoothRemoteDevice &device) override 93 { 94 return; 95 } 96 OnPairConfirmed(const OHOS::Bluetooth::BluetoothRemoteDevice & device,int reqType,int number)97 void OnPairConfirmed(const OHOS::Bluetooth::BluetoothRemoteDevice &device, int reqType, int number) override 98 { 99 return; 100 } 101 OnScanModeChanged(int mode)102 void OnScanModeChanged(int mode) override 103 { 104 return; 105 } 106 OnDeviceNameChanged(const std::string & deviceName)107 void OnDeviceNameChanged(const std::string &deviceName) override 108 { 109 return; 110 } 111 OnDeviceAddrChanged(const std::string & address)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 #ifdef CASTPLUS_CAST_ENGINE_ENABLE 175 int32_t GetAVCastControllerInner(const std::string& sessionId, sptr<IRemoteObject>& object) override; 176 #endif 177 178 int32_t RegisterSessionListener(const sptr<ISessionListener>& listener) override; 179 180 int32_t RegisterSessionListenerForAllUsers(const sptr<ISessionListener>& listener) override; 181 182 int32_t SendSystemAVKeyEvent(const MMI::KeyEvent& keyEvent) override; 183 184 int32_t SendSystemControlCommand(const AVControlCommand& command) override; 185 186 int32_t RegisterClientDeathObserver(const sptr<IClientDeath>& observer) override; 187 188 void OnClientDied(pid_t pid); 189 190 void HandleSessionRelease(std::string sessionId); 191 192 void HandleCallStartEvent(); 193 194 #ifdef CASTPLUS_CAST_ENGINE_ENABLE 195 __attribute__((no_sanitize("cfi"))) int32_t MirrorToStreamCast(sptr<AVSessionItem>& session); 196 197 void SplitExtraInfo(std::string info); 198 #endif 199 200 void HandleControllerRelease(AVControllerItem& controller); 201 202 std::int32_t Dump(std::int32_t fd, const std::vector<std::u16string>& args) override; 203 204 int32_t CastAudio(const SessionToken& token, 205 const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkAudioDescriptors) override; 206 207 int32_t CastAudioForAll(const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkAudioDescriptors) override; 208 NotifyAudioSessionCheckTrigger(const int32_t uid)209 void NotifyAudioSessionCheckTrigger(const int32_t uid) 210 { 211 return NotifyAudioSessionCheck(uid); 212 } 213 214 void SuperLauncher(std::string deviceId, std::string serviceName, 215 std::string extraInfo, const std::string& state); 216 217 #ifdef CASTPLUS_CAST_ENGINE_ENABLE 218 void ReleaseCastSession() override; 219 220 void CreateSessionByCast(const int64_t castHandle) override; 221 222 void NotifyDeviceAvailable(const OutputDeviceInfo& castOutputDeviceInfo) override; 223 224 void NotifyDeviceLogEvent(const DeviceLogEventCode eventId, const int64_t param) override; 225 226 void NotifyDeviceOffline(const std::string& deviceId) override; 227 228 void NotifyMirrorToStreamCast(); 229 230 int32_t StartCast(const SessionToken& sessionToken, const OutputDeviceInfo& outputDeviceInfo) override; 231 232 int32_t StopCast(const SessionToken& sessionToken) override; 233 234 int32_t checkEnableCast(bool enable) override; 235 #endif 236 237 int32_t Close(void) override; 238 239 void AddAvQueueInfoToFile(AVSessionItem& session); 240 241 void SetScreenOn(bool on); 242 243 bool GetScreenOn(); 244 245 void SetScreenLocked(bool isLocked); 246 247 bool GetScreenLocked(); 248 249 std::string GetAVQueueDir(int32_t userId = 0); 250 251 std::string GetAVSortDir(int32_t userId = 0); 252 253 void HandleUserEvent(const std::string &type, const int &userId); 254 255 void HandleScreenStatusChange(std::string event); 256 257 void RegisterBundleDeleteEventForHistory(int32_t userId = 0); 258 259 void NotifyMigrateStop(const std::string &deviceId); 260 261 private: 262 void CheckInitCast(); 263 264 void CheckBrEnable(); 265 266 void NotifyProcessStatus(bool isStart); 267 268 static SessionContainer& GetContainer(); 269 static AVSessionUsersManager& GetUsersManager(); 270 271 std::string AllocSessionId(); 272 273 bool AbilityHasSession(pid_t pid); 274 275 sptr<AVControllerItem> GetPresentController(pid_t pid, const std::string& sessionId); 276 277 void NotifySessionCreate(const AVSessionDescriptor& descriptor); 278 void NotifySessionRelease(const AVSessionDescriptor& descriptor); 279 void NotifyTopSessionChanged(const AVSessionDescriptor& descriptor); 280 void NotifyAudioSessionCheck(const int32_t uid); 281 void NotifySystemUI(const AVSessionDescriptor* historyDescriptor, bool isActiveSession); 282 void NotifyDeviceChange(const DeviceChangeAction& deviceChangeAction); 283 284 void AddClientDeathObserver(pid_t pid, const sptr<IClientDeath>& observer, 285 const sptr<ClientDeathRecipient> recipient); 286 void RemoveClientDeathObserver(pid_t pid); 287 288 void AddSessionListener(pid_t pid, const sptr<ISessionListener>& listener); 289 void AddSessionListenerForAllUsers(pid_t pid, const sptr<ISessionListener>& listener); 290 void RemoveSessionListener(pid_t pid); 291 292 void AddInnerSessionListener(SessionListener* listener); 293 void RemoveInnerSessionListener(SessionListener* listener); 294 295 sptr<AVSessionItem> SelectSessionByUid(const AudioStandard::AudioRendererChangeInfo& info); 296 297 void OutputDeviceChangeListener(const AudioRendererChangeInfos& infos); 298 299 sptr<AVSessionItem> CreateSessionInner(const std::string& tag, int32_t type, bool thirdPartyApp, 300 const AppExecFwk::ElementName& elementName); 301 302 int32_t CreateSessionInner(const std::string& tag, int32_t type, bool thirdPartyApp, 303 const AppExecFwk::ElementName& elementName, sptr<AVSessionItem>& sessionItem); 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 bool SaveAvQueueInfo(std::string& oldContent, const std::string &bundleName, AVSessionItem& session); 408 409 const nlohmann::json& GetSubNode(const nlohmann::json& node, const std::string& name); 410 411 void refreshSortFileOnCreateSession(const std::string& sessionId, const std::string& sessionType, 412 const AppExecFwk::ElementName& elementName); 413 414 bool CheckAndCreateDir(const std::string& filePath); 415 416 bool CheckUserDirValid(int32_t userId = 0); 417 418 bool LoadStringFromFileEx(const std::string& filePath, std::string& content); 419 420 bool SaveStringToFileEx(const std::string& filePath, const std::string& content); 421 422 bool CheckStringAndCleanFile(const std::string& filePath); 423 424 void ClearClientResources(pid_t pid); 425 426 bool SaveAvQueueInfo(std::string& oldContent, const std::string &bundleName, 427 const AVMetaData& meta, const int32_t userId); 428 429 int32_t GetHistoricalSessionDescriptorsFromFile(std::vector<AVSessionDescriptor>& descriptors); 430 431 void ReportStartCastBegin(std::string func, const OutputDeviceInfo& outputDeviceInfo, int32_t uid); 432 433 void ReportStartCastEnd(std::string func, const OutputDeviceInfo &outputDeviceInfo, int32_t uid, int ret); 434 435 void HandleAppStateChange(int uid, int state); 436 437 bool IsMediaStream(AudioStandard::StreamUsage usage); 438 439 void UpdateFrontSession(sptr<AVSessionItem>& sessionItem, bool isAdd); 440 441 std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> CreateWantAgent( 442 const AVSessionDescriptor* histroyDescriptor); 443 444 void DoMetadataImgClean(AVMetaData& data); 445 446 void HandleSystemKeyColdStart(const AVControlCommand &command); 447 448 bool SubscribeCommonEvent(); 449 450 bool UnSubscribeCommonEvent(); 451 452 void ReportSessionInfo(const sptr <AVSessionItem>& session, int res); 453 454 bool CheckAncoAudio(); 455 456 int32_t ConvertKeyCodeToCommand(int keyCode); 457 458 std::shared_ptr<std::list<sptr<AVSessionItem>>> GetCurSessionListForFront(); 459 460 void RemoveExpired(std::list<std::chrono::system_clock::time_point> &list, 461 const std::chrono::system_clock::time_point &now, int32_t time = 1); 462 463 std::atomic<uint32_t> sessionSeqNum_ {}; 464 465 std::recursive_mutex sessionAndControllerLock_; 466 sptr<AVSessionItem> topSession_; 467 std::map<pid_t, std::list<sptr<AVControllerItem>>> controllers_; 468 std::recursive_mutex sessionFrontLock_; 469 470 std::recursive_mutex clientDeathObserversLock_; 471 std::map<pid_t, sptr<IClientDeath>> clientDeathObservers_; 472 std::map<pid_t, sptr<ClientDeathRecipient>> clientDeathRecipients_; 473 474 std::recursive_mutex sessionListenersLock_; 475 std::list<SessionListener*> innerSessionListeners_; 476 477 std::recursive_mutex abilityManagerLock_; 478 std::map<std::string, std::shared_ptr<AbilityManagerAdapter>> abilityManager_; 479 480 FocusSessionStrategy focusSessionStrategy_; 481 BackgroundAudioController backgroundAudioController_; 482 483 std::recursive_mutex castAudioSessionMapLock_; 484 std::map<std::string, std::string> castAudioSessionMap_; 485 486 std::recursive_mutex isAllSessionCastLock_; 487 bool isAllSessionCast_ {}; 488 489 std::recursive_mutex outputDeviceIdLock_; 490 std::string outputDeviceId_; 491 492 std::unique_ptr<AVSessionDumper> dumpHelper_ {}; 493 friend class AVSessionDumper; 494 495 std::recursive_mutex sortFileReadWriteLock_; 496 std::recursive_mutex avQueueFileReadWriteLock_; 497 std::recursive_mutex fileCheckLock_; 498 499 std::recursive_mutex migrateListenersLock_; 500 std::shared_ptr<MigrateAVSessionServer> migrateAVSession_; 501 std::map<int32_t, bool> sessionPublishedMap_; 502 503 std::shared_ptr<EventSubscriber> subscriber_; 504 std::recursive_mutex screenStateLock_; 505 bool screenOn = false; 506 bool screenLocked = true; 507 508 std::list<std::chrono::system_clock::time_point> flowControlPublishTimestampList_; 509 510 #ifdef BLUETOOTH_ENABLE 511 OHOS::Bluetooth::BluetoothHost *bluetoothHost_ = nullptr; 512 std::shared_ptr<DetectBluetoothHostObserver> bluetoothObserver; 513 #endif 514 515 #ifdef CASTPLUS_CAST_ENGINE_ENABLE 516 std::map<std::string, std::string> castServiceNameMapState_; 517 const std::string deviceStateConnection = "CONNECT_SUCC"; 518 const std::string deviceStateDisconnection = "IDLE"; 519 const std::string seperator = ","; 520 int appState = -1; 521 bool isSupportMirrorToStream_ = false; 522 std::string castDeviceId_ = "0"; 523 std::string castDeviceName_ = " "; 524 int32_t castDeviceType_ = 0; 525 const int32_t beginAddPos = 3; 526 const int32_t endDecPos = 4; 527 const int32_t typeAddPos = 2; 528 #endif 529 530 static constexpr const char *SORT_FILE_NAME = "sortinfo"; 531 static constexpr const char *DEFAULT_SESSION_ID = "default"; 532 static constexpr const char *DEFAULT_BUNDLE_NAME = "com.example.himusicdemo"; 533 static constexpr const char *DEFAULT_ABILITY_NAME = "MainAbility"; 534 static constexpr const int32_t SYSTEMUI_LIVEVIEW_TYPECODE_MDEDIACONTROLLER = 2; 535 static constexpr const char *AVQUEUE_FILE_NAME = "avqueueinfo"; 536 537 const std::string MEDIA_CONTROL_BUNDLENAME = "com.ohos.mediacontroller"; 538 const std::string MEDIA_CONTROL_ABILITYNAME = 539 "com.ohos.mediacontroller.avplayer.mainability"; 540 541 int32_t pressCount_ {}; 542 int32_t maxHistoryNums = 10; 543 int uidForAppStateChange_ = 0; 544 bool isFirstPress_ = true; 545 bool isSourceInCast_ = false; 546 bool isInCast_ = false; 547 bool is2in1_ = false; 548 549 void *migrateStubFuncHandle_ = nullptr; 550 551 const int32_t ONE_CLICK = 1; 552 const int32_t DOUBLE_CLICK = 2; 553 const int32_t THREE_CLICK = 3; 554 const int32_t unSetHistoryNum = 3; 555 const int32_t CLICK_TIMEOUT = 500; 556 const int32_t defMaxHistoryNum = 10; 557 const int32_t maxFileLength = 32 * 1024 * 1024; 558 const int32_t maxAVQueueInfoLen = 99; 559 const int32_t allocSpace = 2; 560 const int32_t avSessionUid = 6700; 561 const int32_t ancoUid = 1041; 562 const int32_t saType = 1; 563 const int32_t MAX_NOTIFICATION_NUM = 3; 564 const int32_t NOTIFICATION_CONTROL_TIME = 1000; 565 }; 566 } // namespace OHOS::AVSession 567 #endif // OHOS_AVSESSION_SERVICE_H 568