180922886Sopenharmony_ci/* 280922886Sopenharmony_ci * Copyright (c) 2022-2024 Huawei Device Co., Ltd. 380922886Sopenharmony_ci * Licensed under the Apache License, Version 2.0 (the "License"); 480922886Sopenharmony_ci * you may not use this file except in compliance with the License. 580922886Sopenharmony_ci * You may obtain a copy of the License at 680922886Sopenharmony_ci * 780922886Sopenharmony_ci * http://www.apache.org/licenses/LICENSE-2.0 880922886Sopenharmony_ci * 980922886Sopenharmony_ci * Unless required by applicable law or agreed to in writing, software 1080922886Sopenharmony_ci * distributed under the License is distributed on an "AS IS" BASIS, 1180922886Sopenharmony_ci * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 1280922886Sopenharmony_ci * See the License for the specific language governing permissions and 1380922886Sopenharmony_ci * limitations under the License. 1480922886Sopenharmony_ci */ 1580922886Sopenharmony_ci 1680922886Sopenharmony_ci#include <sstream> 1780922886Sopenharmony_ci#include <iomanip> 1880922886Sopenharmony_ci#include <iostream> 1980922886Sopenharmony_ci#include <regex> 2080922886Sopenharmony_ci#include <dlfcn.h> 2180922886Sopenharmony_ci#include <thread> 2280922886Sopenharmony_ci#include <chrono> 2380922886Sopenharmony_ci#include <filesystem> 2480922886Sopenharmony_ci#include <openssl/crypto.h> 2580922886Sopenharmony_ci 2680922886Sopenharmony_ci#include "accesstoken_kit.h" 2780922886Sopenharmony_ci#include "account_manager_adapter.h" 2880922886Sopenharmony_ci#include "app_manager_adapter.h" 2980922886Sopenharmony_ci#include "audio_adapter.h" 3080922886Sopenharmony_ci#include "avsession_dynamic_loader.h" 3180922886Sopenharmony_ci#include "avsession_errors.h" 3280922886Sopenharmony_ci#include "avsession_log.h" 3380922886Sopenharmony_ci#include "avsession_info.h" 3480922886Sopenharmony_ci#include "device_manager.h" 3580922886Sopenharmony_ci#include "remote_session_capability_set.h" 3680922886Sopenharmony_ci#include "remote_session_source_proxy.h" 3780922886Sopenharmony_ci#include "remote_session_sink_proxy.h" 3880922886Sopenharmony_ci#include "file_ex.h" 3980922886Sopenharmony_ci#include "iservice_registry.h" 4080922886Sopenharmony_ci#include "key_event_adapter.h" 4180922886Sopenharmony_ci#include "nlohmann/json.hpp" 4280922886Sopenharmony_ci#include "permission_checker.h" 4380922886Sopenharmony_ci#include "system_ability_definition.h" 4480922886Sopenharmony_ci#include "session_stack.h" 4580922886Sopenharmony_ci#include "avsession_trace.h" 4680922886Sopenharmony_ci#include "hash_calculator.h" 4780922886Sopenharmony_ci#include "avsession_dumper.h" 4880922886Sopenharmony_ci#include "command_send_limit.h" 4980922886Sopenharmony_ci#include "avsession_sysevent.h" 5080922886Sopenharmony_ci#include "json_utils.h" 5180922886Sopenharmony_ci#include "avsession_utils.h" 5280922886Sopenharmony_ci#include "avcontrol_command.h" 5380922886Sopenharmony_ci#include "avsession_event_handler.h" 5480922886Sopenharmony_ci#include "bundle_status_adapter.h" 5580922886Sopenharmony_ci#include "params_config_operator.h" 5680922886Sopenharmony_ci#include "notification_content.h" 5780922886Sopenharmony_ci#include "notification_helper.h" 5880922886Sopenharmony_ci#include "notification_request.h" 5980922886Sopenharmony_ci#include "notification_constant.h" 6080922886Sopenharmony_ci#include "ability_connect_helper.h" 6180922886Sopenharmony_ci#include "if_system_ability_manager.h" 6280922886Sopenharmony_ci#include "parameter.h" 6380922886Sopenharmony_ci#include "parameters.h" 6480922886Sopenharmony_ci#include "avsession_service.h" 6580922886Sopenharmony_ci#include "want_agent_helper.h" 6680922886Sopenharmony_ci#include "avsession_radar.h" 6780922886Sopenharmony_ci 6880922886Sopenharmony_citypedef void (*MigrateStubFunc)(std::function<void(std::string, std::string, std::string, std::string)>); 6980922886Sopenharmony_citypedef void (*StopMigrateStubFunc)(void); 7080922886Sopenharmony_ci 7180922886Sopenharmony_ci#ifdef CASTPLUS_CAST_ENGINE_ENABLE 7280922886Sopenharmony_ci#include "av_router.h" 7380922886Sopenharmony_ci#include "collaboration_manager.h" 7480922886Sopenharmony_ci#endif 7580922886Sopenharmony_ci 7680922886Sopenharmony_ci#if !defined(WINDOWS_PLATFORM) and !defined(MAC_PLATFORM) and !defined(IOS_PLATFORM) 7780922886Sopenharmony_ci#include <malloc.h> 7880922886Sopenharmony_ci#endif 7980922886Sopenharmony_ci 8080922886Sopenharmony_ciusing namespace std; 8180922886Sopenharmony_ciusing namespace nlohmann; 8280922886Sopenharmony_ciusing namespace OHOS::AudioStandard; 8380922886Sopenharmony_ci 8480922886Sopenharmony_cinamespace OHOS::AVSession { 8580922886Sopenharmony_ci 8680922886Sopenharmony_cistatic const std::string AVSESSION_DYNAMIC_INSIGHT_LIBRARY_PATH = std::string("libavsession_dynamic_insight.z.so"); 8780922886Sopenharmony_ci 8880922886Sopenharmony_cistatic const int32_t CAST_ENGINE_SA_ID = 65546; 8980922886Sopenharmony_cistatic const int32_t MINNUM_FOR_NOTIFICATION = 5; 9080922886Sopenharmony_ciconst std::string BOOTEVENT_AVSESSION_SERVICE_READY = "bootevent.avsessionservice.ready"; 9180922886Sopenharmony_ci 9280922886Sopenharmony_ciconst std::map<int, int32_t> keyCodeToCommandMap_ = { 9380922886Sopenharmony_ci {MMI::KeyEvent::KEYCODE_MEDIA_PLAY_PAUSE, AVControlCommand::SESSION_CMD_PLAY}, 9480922886Sopenharmony_ci {MMI::KeyEvent::KEYCODE_MEDIA_PLAY, AVControlCommand::SESSION_CMD_PLAY}, 9580922886Sopenharmony_ci {MMI::KeyEvent::KEYCODE_MEDIA_PAUSE, AVControlCommand::SESSION_CMD_PAUSE}, 9680922886Sopenharmony_ci {MMI::KeyEvent::KEYCODE_MEDIA_STOP, AVControlCommand::SESSION_CMD_STOP}, 9780922886Sopenharmony_ci {MMI::KeyEvent::KEYCODE_MEDIA_NEXT, AVControlCommand::SESSION_CMD_PLAY_NEXT}, 9880922886Sopenharmony_ci {MMI::KeyEvent::KEYCODE_MEDIA_PREVIOUS, AVControlCommand::SESSION_CMD_PLAY_PREVIOUS}, 9980922886Sopenharmony_ci {MMI::KeyEvent::KEYCODE_MEDIA_REWIND, AVControlCommand::SESSION_CMD_REWIND}, 10080922886Sopenharmony_ci {MMI::KeyEvent::KEYCODE_MEDIA_FAST_FORWARD, AVControlCommand::SESSION_CMD_FAST_FORWARD}, 10180922886Sopenharmony_ci}; 10280922886Sopenharmony_ci 10380922886Sopenharmony_ciclass NotificationSubscriber : public Notification::NotificationLocalLiveViewSubscriber { 10480922886Sopenharmony_ci void OnConnected() {} 10580922886Sopenharmony_ci void OnDisconnected() {} 10680922886Sopenharmony_ci void OnResponse(int32_t notificationId, sptr<Notification::NotificationButtonOption> buttonOption) {} 10780922886Sopenharmony_ci void OnDied() {} 10880922886Sopenharmony_ci}; 10980922886Sopenharmony_ci 11080922886Sopenharmony_cistatic const auto NOTIFICATION_SUBSCRIBER = NotificationSubscriber(); 11180922886Sopenharmony_ci 11280922886Sopenharmony_ciREGISTER_SYSTEM_ABILITY_BY_ID(AVSessionService, AVSESSION_SERVICE_ID, true); 11380922886Sopenharmony_ci 11480922886Sopenharmony_ciAVSessionService::AVSessionService(int32_t systemAbilityId, bool runOnCreate) 11580922886Sopenharmony_ci : SystemAbility(systemAbilityId, runOnCreate) 11680922886Sopenharmony_ci{ 11780922886Sopenharmony_ci} 11880922886Sopenharmony_ci 11980922886Sopenharmony_ciAVSessionService::~AVSessionService() 12080922886Sopenharmony_ci{ 12180922886Sopenharmony_ci GetUsersManager().ClearCache(); 12280922886Sopenharmony_ci} 12380922886Sopenharmony_ci 12480922886Sopenharmony_civoid AVSessionService::OnStart() 12580922886Sopenharmony_ci{ 12680922886Sopenharmony_ci GetUsersManager().ClearCache(); 12780922886Sopenharmony_ci CHECK_AND_RETURN_LOG(Publish(this), "publish avsession service failed"); 12880922886Sopenharmony_ci dumpHelper_ = std::make_unique<AVSessionDumper>(); 12980922886Sopenharmony_ci CommandSendLimit::GetInstance().StartTimer(); 13080922886Sopenharmony_ci 13180922886Sopenharmony_ci ParamsConfigOperator::GetInstance().InitConfig(); 13280922886Sopenharmony_ci auto ret = ParamsConfigOperator::GetInstance().GetValueIntByKey("historicalRecordMaxNum", &maxHistoryNums_); 13380922886Sopenharmony_ci if (ret == AVSESSION_ERROR) { 13480922886Sopenharmony_ci maxHistoryNums_ = defMaxHistoryNum; 13580922886Sopenharmony_ci } 13680922886Sopenharmony_ci 13780922886Sopenharmony_ci#ifdef ENABLE_BACKGROUND_AUDIO_CONTROL 13880922886Sopenharmony_ci backgroundAudioController_.Init(this); 13980922886Sopenharmony_ci AddInnerSessionListener(&backgroundAudioController_); 14080922886Sopenharmony_ci#endif 14180922886Sopenharmony_ci 14280922886Sopenharmony_ci AddSystemAbilityListener(MULTIMODAL_INPUT_SERVICE_ID); 14380922886Sopenharmony_ci AddSystemAbilityListener(AUDIO_POLICY_SERVICE_ID); 14480922886Sopenharmony_ci AddSystemAbilityListener(APP_MGR_SERVICE_ID); 14580922886Sopenharmony_ci AddSystemAbilityListener(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID); 14680922886Sopenharmony_ci AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); 14780922886Sopenharmony_ci AddSystemAbilityListener(CAST_ENGINE_SA_ID); 14880922886Sopenharmony_ci AddSystemAbilityListener(BLUETOOTH_HOST_SYS_ABILITY_ID); 14980922886Sopenharmony_ci AddSystemAbilityListener(MEMORY_MANAGER_SA_ID); 15080922886Sopenharmony_ci AddSystemAbilityListener(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN); 15180922886Sopenharmony_ci AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID); 15280922886Sopenharmony_ci 15380922886Sopenharmony_ci#ifdef CASTPLUS_CAST_ENGINE_ENABLE 15480922886Sopenharmony_ci is2in1_ = system::GetBoolParameter("const.audio.volume_apply_to_all", false); 15580922886Sopenharmony_ci SLOGI("GetDeviceEnableCast, Prop=%{public}d", static_cast<int>(is2in1_)); 15680922886Sopenharmony_ci if (is2in1_) { 15780922886Sopenharmony_ci SLOGI("startup enable cast check 2in1"); 15880922886Sopenharmony_ci checkEnableCast(true); 15980922886Sopenharmony_ci AVRouter::GetInstance().SetDiscoverable(false); 16080922886Sopenharmony_ci AVRouter::GetInstance().SetDiscoverable(true); 16180922886Sopenharmony_ci } 16280922886Sopenharmony_ci CollaborationManager::GetInstance().ReadCollaborationManagerSo(); 16380922886Sopenharmony_ci CollaborationManager::GetInstance().RegisterLifecycleCallback(); 16480922886Sopenharmony_ci#endif 16580922886Sopenharmony_ci PullMigrateStub(); 16680922886Sopenharmony_ci HISYSEVENT_REGITER; 16780922886Sopenharmony_ci HISYSEVENT_BEHAVIOR("SESSION_SERVICE_START", "SERVICE_NAME", "AVSessionService", 16880922886Sopenharmony_ci "SERVICE_ID", AVSESSION_SERVICE_ID, "DETAILED_MSG", "avsession service start success"); 16980922886Sopenharmony_ci if (!system::GetBoolParameter(BOOTEVENT_AVSESSION_SERVICE_READY.c_str(), false)) { 17080922886Sopenharmony_ci system::SetParameter(BOOTEVENT_AVSESSION_SERVICE_READY.c_str(), "true"); 17180922886Sopenharmony_ci SLOGI("set boot avsession service started true"); 17280922886Sopenharmony_ci } 17380922886Sopenharmony_ci} 17480922886Sopenharmony_ci 17580922886Sopenharmony_civoid AVSessionService::OnDump() 17680922886Sopenharmony_ci{ 17780922886Sopenharmony_ci} 17880922886Sopenharmony_ci 17980922886Sopenharmony_civoid AVSessionService::OnStop() 18080922886Sopenharmony_ci{ 18180922886Sopenharmony_ci StopMigrateStubFunc stopMigrateStub = 18280922886Sopenharmony_ci reinterpret_cast<StopMigrateStubFunc>(dlsym(migrateStubFuncHandle_, "StopMigrateStub")); 18380922886Sopenharmony_ci if (stopMigrateStub == nullptr) { 18480922886Sopenharmony_ci SLOGE("failed to find library, reason: %{public}sn", dlerror()); 18580922886Sopenharmony_ci } else { 18680922886Sopenharmony_ci stopMigrateStub(); 18780922886Sopenharmony_ci } 18880922886Sopenharmony_ci#ifndef TEST_COVERAGE 18980922886Sopenharmony_ci if (migrateStubFuncHandle_ != nullptr) { 19080922886Sopenharmony_ci OPENSSL_thread_stop(); 19180922886Sopenharmony_ci } 19280922886Sopenharmony_ci dlclose(migrateStubFuncHandle_); 19380922886Sopenharmony_ci#endif 19480922886Sopenharmony_ci#ifdef CASTPLUS_CAST_ENGINE_ENABLE 19580922886Sopenharmony_ci CollaborationManager::GetInstance().UnRegisterLifecycleCallback(); 19680922886Sopenharmony_ci#endif 19780922886Sopenharmony_ci CommandSendLimit::GetInstance().StopTimer(); 19880922886Sopenharmony_ci NotifyProcessStatus(false); 19980922886Sopenharmony_ci UnSubscribeCommonEvent(); 20080922886Sopenharmony_ci} 20180922886Sopenharmony_ci 20280922886Sopenharmony_ciEventSubscriber::EventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscriberInfo, AVSessionService *ptr) 20380922886Sopenharmony_ci : EventFwk::CommonEventSubscriber(subscriberInfo) 20480922886Sopenharmony_ci{ 20580922886Sopenharmony_ci servicePtr_ = ptr; 20680922886Sopenharmony_ci} 20780922886Sopenharmony_ci 20880922886Sopenharmony_civoid EventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &eventData) 20980922886Sopenharmony_ci{ 21080922886Sopenharmony_ci const AAFwk::Want &want = eventData.GetWant(); 21180922886Sopenharmony_ci std::string action = want.GetAction(); 21280922886Sopenharmony_ci SLOGI("OnReceiveEvent action:%{public}s.", action.c_str()); 21380922886Sopenharmony_ci 21480922886Sopenharmony_ci if (action.compare(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF) == 0 || 21580922886Sopenharmony_ci action.compare(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON) == 0 || 21680922886Sopenharmony_ci action.compare(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED) == 0 || 21780922886Sopenharmony_ci action.compare(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED) == 0) { 21880922886Sopenharmony_ci if (servicePtr_ != nullptr) { 21980922886Sopenharmony_ci servicePtr_->HandleScreenStatusChange(action); 22080922886Sopenharmony_ci } else { 22180922886Sopenharmony_ci SLOGE("get screenEvent with servicePtr_ null"); 22280922886Sopenharmony_ci } 22380922886Sopenharmony_ci } else if (action.compare(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) == 0) { 22480922886Sopenharmony_ci int32_t userId = eventData.GetCode(); 22580922886Sopenharmony_ci if (servicePtr_ != nullptr) { 22680922886Sopenharmony_ci servicePtr_->HandleUserEvent(AVSessionUsersManager::accountEventSwitched, userId); 22780922886Sopenharmony_ci } else { 22880922886Sopenharmony_ci SLOGE("get accountEventSwitched with servicePtr_ null"); 22980922886Sopenharmony_ci } 23080922886Sopenharmony_ci } else if (action.compare(EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED) == 0) { 23180922886Sopenharmony_ci int32_t userId = eventData.GetCode(); 23280922886Sopenharmony_ci if (servicePtr_ != nullptr) { 23380922886Sopenharmony_ci servicePtr_->HandleUserEvent(AVSessionUsersManager::accountEventRemoved, userId); 23480922886Sopenharmony_ci } else { 23580922886Sopenharmony_ci SLOGE("get accountEventRemoved with servicePtr_ null"); 23680922886Sopenharmony_ci } 23780922886Sopenharmony_ci } else if (action.compare(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED) == 0) { 23880922886Sopenharmony_ci int32_t userId = eventData.GetCode(); 23980922886Sopenharmony_ci if (servicePtr_ != nullptr) { 24080922886Sopenharmony_ci servicePtr_->RegisterBundleDeleteEventForHistory(userId); 24180922886Sopenharmony_ci } else { 24280922886Sopenharmony_ci SLOGE("get user unlock with servicePtr_ null"); 24380922886Sopenharmony_ci } 24480922886Sopenharmony_ci } 24580922886Sopenharmony_ci} 24680922886Sopenharmony_ci 24780922886Sopenharmony_cistd::string AVSessionService::GetAVQueueDir(int32_t userId) 24880922886Sopenharmony_ci{ 24980922886Sopenharmony_ci return GetUsersManager().GetDirForCurrentUser(userId) + AVQUEUE_FILE_NAME; 25080922886Sopenharmony_ci} 25180922886Sopenharmony_ci 25280922886Sopenharmony_cistd::string AVSessionService::GetAVSortDir(int32_t userId) 25380922886Sopenharmony_ci{ 25480922886Sopenharmony_ci return GetUsersManager().GetDirForCurrentUser(userId) + SORT_FILE_NAME; 25580922886Sopenharmony_ci} 25680922886Sopenharmony_ci 25780922886Sopenharmony_civoid AVSessionService::HandleUserEvent(const std::string &type, const int &userId) 25880922886Sopenharmony_ci{ 25980922886Sopenharmony_ci GetUsersManager().NotifyAccountsEvent(type, userId); 26080922886Sopenharmony_ci UpdateTopSession(GetUsersManager().GetTopSession()); 26180922886Sopenharmony_ci} 26280922886Sopenharmony_ci 26380922886Sopenharmony_civoid AVSessionService::HandleScreenStatusChange(std::string event) 26480922886Sopenharmony_ci{ 26580922886Sopenharmony_ci std::lock_guard lockGuard(screenStateLock_); 26680922886Sopenharmony_ci 26780922886Sopenharmony_ci if (event.compare(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF) == 0) { 26880922886Sopenharmony_ci SetScreenOn(false); 26980922886Sopenharmony_ci } else if (event.compare(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON) == 0) { 27080922886Sopenharmony_ci SetScreenOn(true); 27180922886Sopenharmony_ci } else if (event.compare(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED) == 0) { 27280922886Sopenharmony_ci SetScreenLocked(true); 27380922886Sopenharmony_ci } else if (event.compare(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED) == 0) { 27480922886Sopenharmony_ci SetScreenLocked(false); 27580922886Sopenharmony_ci } 27680922886Sopenharmony_ci SLOGI("check screen status with screenOn %{public}d and screenLocked %{public}d", 27780922886Sopenharmony_ci static_cast<int>(GetScreenOn()), static_cast<int>(GetScreenLocked())); 27880922886Sopenharmony_ci 27980922886Sopenharmony_ci#ifdef CASTPLUS_CAST_ENGINE_ENABLE 28080922886Sopenharmony_ci bool is2in1 = system::GetBoolParameter("const.audio.volume_apply_to_all", false); 28180922886Sopenharmony_ci if (!is2in1) { 28280922886Sopenharmony_ci return; 28380922886Sopenharmony_ci } 28480922886Sopenharmony_ci if (GetScreenOn() && !GetScreenLocked()) { 28580922886Sopenharmony_ci SLOGI("enable cast check 2in1"); 28680922886Sopenharmony_ci AVRouter::GetInstance().SetDiscoverable(false); 28780922886Sopenharmony_ci AVRouter::GetInstance().SetDiscoverable(true); 28880922886Sopenharmony_ci } else { 28980922886Sopenharmony_ci SLOGI("disable cast check 2in1"); 29080922886Sopenharmony_ci AVRouter::GetInstance().SetDiscoverable(false); 29180922886Sopenharmony_ci } 29280922886Sopenharmony_ci 29380922886Sopenharmony_ci#endif 29480922886Sopenharmony_ci} 29580922886Sopenharmony_ci 29680922886Sopenharmony_civoid AVSessionService::SetScreenOn(bool on) 29780922886Sopenharmony_ci{ 29880922886Sopenharmony_ci std::lock_guard lockGuard(screenStateLock_); 29980922886Sopenharmony_ci isScreenOn_ = on; 30080922886Sopenharmony_ci} 30180922886Sopenharmony_ci 30280922886Sopenharmony_cibool AVSessionService::GetScreenOn() 30380922886Sopenharmony_ci{ 30480922886Sopenharmony_ci std::lock_guard lockGuard(screenStateLock_); 30580922886Sopenharmony_ci return isScreenOn_; 30680922886Sopenharmony_ci} 30780922886Sopenharmony_ci 30880922886Sopenharmony_civoid AVSessionService::SetScreenLocked(bool isLocked) 30980922886Sopenharmony_ci{ 31080922886Sopenharmony_ci std::lock_guard lockGuard(screenStateLock_); 31180922886Sopenharmony_ci isScreenLocked_ = isLocked; 31280922886Sopenharmony_ci} 31380922886Sopenharmony_ci 31480922886Sopenharmony_cibool AVSessionService::GetScreenLocked() 31580922886Sopenharmony_ci{ 31680922886Sopenharmony_ci std::lock_guard lockGuard(screenStateLock_); 31780922886Sopenharmony_ci return isScreenLocked_; 31880922886Sopenharmony_ci} 31980922886Sopenharmony_ci 32080922886Sopenharmony_cibool AVSessionService::SubscribeCommonEvent() 32180922886Sopenharmony_ci{ 32280922886Sopenharmony_ci const std::vector<std::string> events = { 32380922886Sopenharmony_ci EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF, 32480922886Sopenharmony_ci EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON, 32580922886Sopenharmony_ci EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED, 32680922886Sopenharmony_ci EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED, 32780922886Sopenharmony_ci EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED, 32880922886Sopenharmony_ci EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED, 32980922886Sopenharmony_ci EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED, 33080922886Sopenharmony_ci }; 33180922886Sopenharmony_ci 33280922886Sopenharmony_ci EventFwk::MatchingSkills matchingSkills; 33380922886Sopenharmony_ci for (auto event : events) { 33480922886Sopenharmony_ci matchingSkills.AddEvent(event); 33580922886Sopenharmony_ci } 33680922886Sopenharmony_ci EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); 33780922886Sopenharmony_ci 33880922886Sopenharmony_ci subscriber_ = std::make_shared<EventSubscriber>(subscribeInfo, this); 33980922886Sopenharmony_ci return EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber_); 34080922886Sopenharmony_ci} 34180922886Sopenharmony_ci 34280922886Sopenharmony_cibool AVSessionService::UnSubscribeCommonEvent() 34380922886Sopenharmony_ci{ 34480922886Sopenharmony_ci bool subscribeResult = false; 34580922886Sopenharmony_ci if (subscriber_ != nullptr) { 34680922886Sopenharmony_ci subscribeResult = EventFwk::CommonEventManager::UnSubscribeCommonEvent(subscriber_); 34780922886Sopenharmony_ci subscriber_ = nullptr; 34880922886Sopenharmony_ci } 34980922886Sopenharmony_ci SLOGI("UnSubscribeCommonEvent subscribeResult = %{public}d", subscribeResult); 35080922886Sopenharmony_ci 35180922886Sopenharmony_ci return subscribeResult; 35280922886Sopenharmony_ci} 35380922886Sopenharmony_ci 35480922886Sopenharmony_civoid AVSessionService::PullMigrateStub() 35580922886Sopenharmony_ci{ 35680922886Sopenharmony_ci migrateStubFuncHandle_ = dlopen("libavsession_migration.z.so", RTLD_NOW); 35780922886Sopenharmony_ci if (migrateStubFuncHandle_ == nullptr) { 35880922886Sopenharmony_ci SLOGE("failed to dlopen library, reason: %{public}sn", dlerror()); 35980922886Sopenharmony_ci return; 36080922886Sopenharmony_ci } 36180922886Sopenharmony_ci MigrateStubFunc startMigrateStub = 36280922886Sopenharmony_ci reinterpret_cast<MigrateStubFunc>(dlsym(migrateStubFuncHandle_, "StartMigrateStub")); 36380922886Sopenharmony_ci if (startMigrateStub == nullptr) { 36480922886Sopenharmony_ci SLOGE("failed to find library, reason: %{public}sn", dlerror()); 36580922886Sopenharmony_ci return; 36680922886Sopenharmony_ci } 36780922886Sopenharmony_ci std::thread([startMigrateStub, this]() { 36880922886Sopenharmony_ci SLOGI("create thread to keep MigrateStub"); 36980922886Sopenharmony_ci startMigrateStub([this](std::string deviceId, std::string serviceName, std::string extraInfo, 37080922886Sopenharmony_ci std::string state) { SuperLauncher(deviceId, serviceName, extraInfo, state); }); 37180922886Sopenharmony_ci }).detach(); 37280922886Sopenharmony_ci} 37380922886Sopenharmony_ci 37480922886Sopenharmony_civoid AVSessionService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) 37580922886Sopenharmony_ci{ 37680922886Sopenharmony_ci SLOGI("Receive SA: %{public}d start callback.", systemAbilityId); 37780922886Sopenharmony_ci switch (systemAbilityId) { 37880922886Sopenharmony_ci case MULTIMODAL_INPUT_SERVICE_ID: 37980922886Sopenharmony_ci InitKeyEvent(); 38080922886Sopenharmony_ci break; 38180922886Sopenharmony_ci case AUDIO_POLICY_SERVICE_ID: 38280922886Sopenharmony_ci InitAudio(); 38380922886Sopenharmony_ci break; 38480922886Sopenharmony_ci case APP_MGR_SERVICE_ID: 38580922886Sopenharmony_ci InitAMS(); 38680922886Sopenharmony_ci break; 38780922886Sopenharmony_ci case DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID: 38880922886Sopenharmony_ci InitDM(); 38980922886Sopenharmony_ci break; 39080922886Sopenharmony_ci case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: 39180922886Sopenharmony_ci InitBMS(); 39280922886Sopenharmony_ci InitRadarBMS(); 39380922886Sopenharmony_ci break; 39480922886Sopenharmony_ci case CAST_ENGINE_SA_ID: 39580922886Sopenharmony_ci break; 39680922886Sopenharmony_ci case BLUETOOTH_HOST_SYS_ABILITY_ID: 39780922886Sopenharmony_ci CheckBrEnable(); 39880922886Sopenharmony_ci break; 39980922886Sopenharmony_ci case MEMORY_MANAGER_SA_ID: 40080922886Sopenharmony_ci NotifyProcessStatus(true); 40180922886Sopenharmony_ci break; 40280922886Sopenharmony_ci case SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN: 40380922886Sopenharmony_ci InitAccountMgr(); 40480922886Sopenharmony_ci break; 40580922886Sopenharmony_ci case COMMON_EVENT_SERVICE_ID: 40680922886Sopenharmony_ci InitCommonEventService(); 40780922886Sopenharmony_ci break; 40880922886Sopenharmony_ci default: 40980922886Sopenharmony_ci SLOGE("undefined system ability %{public}d", systemAbilityId); 41080922886Sopenharmony_ci } 41180922886Sopenharmony_ci} 41280922886Sopenharmony_ci 41380922886Sopenharmony_civoid AVSessionService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) 41480922886Sopenharmony_ci{ 41580922886Sopenharmony_ci if (systemAbilityId == CAST_ENGINE_SA_ID) { 41680922886Sopenharmony_ci SLOGI("cast engine ability is removed"); 41780922886Sopenharmony_ci#ifdef CASTPLUS_CAST_ENGINE_ENABLE 41880922886Sopenharmony_ci for (auto& session : GetContainer().GetAllSessions()) { 41980922886Sopenharmony_ci if (session != nullptr) { 42080922886Sopenharmony_ci session->OnRemoveCastEngine(); 42180922886Sopenharmony_ci } 42280922886Sopenharmony_ci } 42380922886Sopenharmony_ci#endif 42480922886Sopenharmony_ci isInCast_ = false; 42580922886Sopenharmony_ci } 42680922886Sopenharmony_ci if (systemAbilityId == BLUETOOTH_HOST_SYS_ABILITY_ID) { 42780922886Sopenharmony_ci#ifdef BLUETOOTH_ENABLE 42880922886Sopenharmony_ci SLOGI("on bluetooth remove ability"); 42980922886Sopenharmony_ci bluetoothHost_ = &OHOS::Bluetooth::BluetoothHost::GetDefaultHost(); 43080922886Sopenharmony_ci if (bluetoothHost_ != nullptr && bluetoothObserver != nullptr) { 43180922886Sopenharmony_ci bluetoothHost_->DeregisterObserver(bluetoothObserver); 43280922886Sopenharmony_ci } 43380922886Sopenharmony_ci#endif 43480922886Sopenharmony_ci } 43580922886Sopenharmony_ci} 43680922886Sopenharmony_ci 43780922886Sopenharmony_ci#ifdef BLUETOOTH_ENABLE 43880922886Sopenharmony_ciDetectBluetoothHostObserver::DetectBluetoothHostObserver(AVSessionService *ptr) 43980922886Sopenharmony_ci{ 44080922886Sopenharmony_ci is2in1_ = system::GetBoolParameter("const.audio.volume_apply_to_all", false); 44180922886Sopenharmony_ci SLOGI("DetectBluetoothHostObserver, Prop=%{public}d", static_cast<int>(is2in1_)); 44280922886Sopenharmony_ci servicePtr_ = ptr; 44380922886Sopenharmony_ci} 44480922886Sopenharmony_ci 44580922886Sopenharmony_civoid DetectBluetoothHostObserver::OnStateChanged(const int transport, const int status) 44680922886Sopenharmony_ci{ 44780922886Sopenharmony_ci SLOGI("transport=%{public}d status=%{public}d", transport, status); 44880922886Sopenharmony_ci if (transport != OHOS::Bluetooth::BTTransport::ADAPTER_BREDR) { 44980922886Sopenharmony_ci return; 45080922886Sopenharmony_ci } 45180922886Sopenharmony_ci bool newStatus = (status == OHOS::Bluetooth::BTStateID::STATE_TURN_ON); 45280922886Sopenharmony_ci if (newStatus == lastEnabled_) { 45380922886Sopenharmony_ci return; 45480922886Sopenharmony_ci } 45580922886Sopenharmony_ci bool isScreenOn = true; 45680922886Sopenharmony_ci if (servicePtr_ != nullptr) { 45780922886Sopenharmony_ci isScreenOn = servicePtr_->GetScreenOn(); 45880922886Sopenharmony_ci SLOGI("isScreenOn=%{public}d", isScreenOn); 45980922886Sopenharmony_ci } 46080922886Sopenharmony_ci#ifdef CASTPLUS_CAST_ENGINE_ENABLE 46180922886Sopenharmony_ci if (newStatus && is2in1_ && isScreenOn) { 46280922886Sopenharmony_ci AVRouter::GetInstance().SetDiscoverable(false); 46380922886Sopenharmony_ci AVRouter::GetInstance().SetDiscoverable(true); 46480922886Sopenharmony_ci } 46580922886Sopenharmony_ci#endif 46680922886Sopenharmony_ci lastEnabled_ = newStatus; 46780922886Sopenharmony_ci} 46880922886Sopenharmony_ci#endif 46980922886Sopenharmony_ci 47080922886Sopenharmony_civoid AVSessionService::CheckBrEnable() 47180922886Sopenharmony_ci{ 47280922886Sopenharmony_ci#ifdef BLUETOOTH_ENABLE 47380922886Sopenharmony_ci bluetoothHost_ = &OHOS::Bluetooth::BluetoothHost::GetDefaultHost(); 47480922886Sopenharmony_ci bluetoothObserver = std::make_shared<DetectBluetoothHostObserver>(this); 47580922886Sopenharmony_ci if (bluetoothHost_ != nullptr) { 47680922886Sopenharmony_ci bluetoothHost_->RegisterObserver(bluetoothObserver); 47780922886Sopenharmony_ci } 47880922886Sopenharmony_ci#endif 47980922886Sopenharmony_ci} 48080922886Sopenharmony_ci 48180922886Sopenharmony_civoid AVSessionService::NotifyProcessStatus(bool isStart) 48280922886Sopenharmony_ci{ 48380922886Sopenharmony_ci int pid = getpid(); 48480922886Sopenharmony_ci void *libMemMgrClientHandle = dlopen("libmemmgrclient.z.so", RTLD_NOW); 48580922886Sopenharmony_ci if (!libMemMgrClientHandle) { 48680922886Sopenharmony_ci SLOGE("dlopen libmemmgrclient library failed"); 48780922886Sopenharmony_ci return; 48880922886Sopenharmony_ci } 48980922886Sopenharmony_ci void *notifyProcessStatusFunc = dlsym(libMemMgrClientHandle, "notify_process_status"); 49080922886Sopenharmony_ci if (!notifyProcessStatusFunc) { 49180922886Sopenharmony_ci SLOGE("dlsm notify_process_status failed"); 49280922886Sopenharmony_ci#ifndef TEST_COVERAGE 49380922886Sopenharmony_ci if (libMemMgrClientHandle != nullptr) { 49480922886Sopenharmony_ci OPENSSL_thread_stop(); 49580922886Sopenharmony_ci } 49680922886Sopenharmony_ci dlclose(libMemMgrClientHandle); 49780922886Sopenharmony_ci#endif 49880922886Sopenharmony_ci return; 49980922886Sopenharmony_ci } 50080922886Sopenharmony_ci auto notifyProcessStatus = reinterpret_cast<int(*)(int, int, int, int)>(notifyProcessStatusFunc); 50180922886Sopenharmony_ci if (isStart) { 50280922886Sopenharmony_ci SLOGI("notify to memmgr when av_session is started"); 50380922886Sopenharmony_ci notifyProcessStatus(pid, saType, 1, AVSESSION_SERVICE_ID); // 1 indicates the service is started 50480922886Sopenharmony_ci } else { 50580922886Sopenharmony_ci SLOGI("notify to memmgr when av_session is stopped"); 50680922886Sopenharmony_ci notifyProcessStatus(pid, saType, 0, AVSESSION_SERVICE_ID); // 0 indicates the service is stopped 50780922886Sopenharmony_ci } 50880922886Sopenharmony_ci#ifndef TEST_COVERAGE 50980922886Sopenharmony_ci if (libMemMgrClientHandle != nullptr) { 51080922886Sopenharmony_ci OPENSSL_thread_stop(); 51180922886Sopenharmony_ci } 51280922886Sopenharmony_ci dlclose(libMemMgrClientHandle); 51380922886Sopenharmony_ci#endif 51480922886Sopenharmony_ci} 51580922886Sopenharmony_ci 51680922886Sopenharmony_civoid AVSessionService::InitKeyEvent() 51780922886Sopenharmony_ci{ 51880922886Sopenharmony_ci SLOGI("enter init keyEvent"); 51980922886Sopenharmony_ci std::vector<int32_t> keyCodes = { 52080922886Sopenharmony_ci MMI::KeyEvent::KEYCODE_MEDIA_PLAY, 52180922886Sopenharmony_ci MMI::KeyEvent::KEYCODE_MEDIA_PAUSE, 52280922886Sopenharmony_ci MMI::KeyEvent::KEYCODE_MEDIA_PLAY_PAUSE, 52380922886Sopenharmony_ci MMI::KeyEvent::KEYCODE_MEDIA_STOP, 52480922886Sopenharmony_ci MMI::KeyEvent::KEYCODE_MEDIA_NEXT, 52580922886Sopenharmony_ci MMI::KeyEvent::KEYCODE_MEDIA_PREVIOUS, 52680922886Sopenharmony_ci MMI::KeyEvent::KEYCODE_MEDIA_REWIND, 52780922886Sopenharmony_ci MMI::KeyEvent::KEYCODE_MEDIA_FAST_FORWARD, 52880922886Sopenharmony_ci MMI::KeyEvent::KEYCODE_HEADSETHOOK, 52980922886Sopenharmony_ci }; 53080922886Sopenharmony_ci 53180922886Sopenharmony_ci KeyEventAdapter::GetInstance().SubscribeKeyEvent( 53280922886Sopenharmony_ci keyCodes, [this](const auto& keyEvent) { SendSystemAVKeyEvent(*keyEvent); }); 53380922886Sopenharmony_ci} 53480922886Sopenharmony_ci 53580922886Sopenharmony_civoid AVSessionService::UpdateTopSession(const sptr<AVSessionItem>& newTopSession) 53680922886Sopenharmony_ci{ 53780922886Sopenharmony_ci AVSessionDescriptor descriptor; 53880922886Sopenharmony_ci { 53980922886Sopenharmony_ci std::lock_guard lockGuard(sessionServiceLock_); 54080922886Sopenharmony_ci if (newTopSession == nullptr) { 54180922886Sopenharmony_ci if (topSession_ != nullptr) { 54280922886Sopenharmony_ci topSession_->SetTop(false); 54380922886Sopenharmony_ci } 54480922886Sopenharmony_ci topSession_ = nullptr; 54580922886Sopenharmony_ci GetUsersManager().SetTopSession(nullptr); 54680922886Sopenharmony_ci SLOGI("set topSession to nullptr"); 54780922886Sopenharmony_ci HISYSEVENT_BEHAVIOR("FOCUS_CHANGE", "DETAILED_MSG", "avsessionservice set topsession to nullptr"); 54880922886Sopenharmony_ci return; 54980922886Sopenharmony_ci } 55080922886Sopenharmony_ci 55180922886Sopenharmony_ci SLOGI("uid=%{public}d sessionId=%{public}s", newTopSession->GetUid(), 55280922886Sopenharmony_ci AVSessionUtils::GetAnonySessionId(newTopSession->GetSessionId()).c_str()); 55380922886Sopenharmony_ci if (topSession_ != nullptr) { 55480922886Sopenharmony_ci topSession_->SetTop(false); 55580922886Sopenharmony_ci HISYSEVENT_BEHAVIOR("FOCUS_CHANGE", 55680922886Sopenharmony_ci "OLD_BUNDLE_NAME", topSession_->GetDescriptor().elementName_.GetBundleName(), 55780922886Sopenharmony_ci "OLD_MODULE_NAME", topSession_->GetDescriptor().elementName_.GetModuleName(), 55880922886Sopenharmony_ci "OLD_ABILITY_NAME", topSession_->GetAbilityName(), "OLD_SESSION_PID", topSession_->GetPid(), 55980922886Sopenharmony_ci "OLD_SESSION_UID", topSession_->GetUid(), "OLD_SESSION_ID", topSession_->GetSessionId(), 56080922886Sopenharmony_ci "OLD_SESSION_TAG", topSession_->GetDescriptor().sessionTag_, 56180922886Sopenharmony_ci "OLD_SESSION_TYPE", topSession_->GetDescriptor().sessionType_, 56280922886Sopenharmony_ci "BUNDLE_NAME", newTopSession->GetDescriptor().elementName_.GetBundleName(), 56380922886Sopenharmony_ci "MODULE_NAME", newTopSession->GetDescriptor().elementName_.GetModuleName(), 56480922886Sopenharmony_ci "ABILITY_NAME", newTopSession->GetAbilityName(), "SESSION_PID", newTopSession->GetPid(), 56580922886Sopenharmony_ci "SESSION_UID", newTopSession->GetUid(), "SESSION_ID", newTopSession->GetSessionId(), 56680922886Sopenharmony_ci "SESSION_TAG", newTopSession->GetDescriptor().sessionTag_, 56780922886Sopenharmony_ci "SESSION_TYPE", newTopSession->GetDescriptor().sessionType_, 56880922886Sopenharmony_ci "DETAILED_MSG", "avsessionservice handlefocussession, updatetopsession"); 56980922886Sopenharmony_ci } 57080922886Sopenharmony_ci topSession_ = newTopSession; 57180922886Sopenharmony_ci GetUsersManager().SetTopSession(newTopSession); 57280922886Sopenharmony_ci topSession_->SetTop(true); 57380922886Sopenharmony_ci descriptor = topSession_->GetDescriptor(); 57480922886Sopenharmony_ci } 57580922886Sopenharmony_ci 57680922886Sopenharmony_ci NotifyTopSessionChanged(descriptor); 57780922886Sopenharmony_ci} 57880922886Sopenharmony_ci 57980922886Sopenharmony_ci// LCOV_EXCL_START 58080922886Sopenharmony_civoid AVSessionService::HandleFocusSession(const FocusSessionStrategy::FocusSessionChangeInfo& info) 58180922886Sopenharmony_ci{ 58280922886Sopenharmony_ci SLOGI("HandleFocusSession with uid=%{public}d", info.uid); 58380922886Sopenharmony_ci std::lock_guard lockGuard(sessionServiceLock_); 58480922886Sopenharmony_ci if (topSession_ && topSession_->GetUid() == info.uid) { 58580922886Sopenharmony_ci SLOGI("The focusSession is the same as current topSession."); 58680922886Sopenharmony_ci if ((topSession_->GetSessionType() == "audio" || topSession_->GetSessionType() == "video") && 58780922886Sopenharmony_ci topSession_->GetUid() != ancoUid) { 58880922886Sopenharmony_ci AVSessionService::NotifySystemUI(nullptr, true); 58980922886Sopenharmony_ci } 59080922886Sopenharmony_ci return; 59180922886Sopenharmony_ci } 59280922886Sopenharmony_ci 59380922886Sopenharmony_ci std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront(); 59480922886Sopenharmony_ci CHECK_AND_RETURN_LOG(sessionListForFront != nullptr, "sessionListForFront ptr nullptr!"); 59580922886Sopenharmony_ci for (const auto& session : *sessionListForFront) { 59680922886Sopenharmony_ci if (session->GetUid() == info.uid && 59780922886Sopenharmony_ci (session->GetSessionType() != "voice_call" && session->GetSessionType() != "video_call")) { 59880922886Sopenharmony_ci UpdateTopSession(session); 59980922886Sopenharmony_ci if ((topSession_->GetSessionType() == "audio" || topSession_->GetSessionType() == "video") && 60080922886Sopenharmony_ci topSession_->GetUid() != ancoUid) { 60180922886Sopenharmony_ci AVSessionService::NotifySystemUI(nullptr, true); 60280922886Sopenharmony_ci } 60380922886Sopenharmony_ci return; 60480922886Sopenharmony_ci } 60580922886Sopenharmony_ci } 60680922886Sopenharmony_ci} 60780922886Sopenharmony_ci// LCOV_EXCL_STOP 60880922886Sopenharmony_ci 60980922886Sopenharmony_ci// LCOV_EXCL_START 61080922886Sopenharmony_civoid AVSessionService::RefreshFocusSessionSort(sptr<AVSessionItem> &session) 61180922886Sopenharmony_ci{ 61280922886Sopenharmony_ci std::lock_guard sortFileLockGuard(sessionFileLock_); 61380922886Sopenharmony_ci std::string oldSortContent; 61480922886Sopenharmony_ci if (!LoadStringFromFileEx(GetAVSortDir(), oldSortContent)) { 61580922886Sopenharmony_ci SLOGE("LoadStringFromFileEx failed when refresh focus session sort!"); 61680922886Sopenharmony_ci return; 61780922886Sopenharmony_ci } 61880922886Sopenharmony_ci nlohmann::json values = json::parse(oldSortContent, nullptr, false); 61980922886Sopenharmony_ci CHECK_AND_RETURN_LOG(!values.is_discarded(), "json object is null"); 62080922886Sopenharmony_ci bool sessionExist = false; 62180922886Sopenharmony_ci for (auto value : values) { 62280922886Sopenharmony_ci if (session->GetBundleName() == value["bundleName"] && 62380922886Sopenharmony_ci session->GetAbilityName() == value["abilityName"]) { 62480922886Sopenharmony_ci values.erase(std::remove(values.begin(), values.end(), value)); 62580922886Sopenharmony_ci sessionExist = true; 62680922886Sopenharmony_ci break; 62780922886Sopenharmony_ci } 62880922886Sopenharmony_ci } 62980922886Sopenharmony_ci if (sessionExist) { 63080922886Sopenharmony_ci nlohmann::json value; 63180922886Sopenharmony_ci value["sessionId"] = session->GetSessionId(); 63280922886Sopenharmony_ci value["bundleName"] = session->GetBundleName(); 63380922886Sopenharmony_ci value["abilityName"] = session->GetAbilityName(); 63480922886Sopenharmony_ci value["sessionType"] = session->GetSessionType(); 63580922886Sopenharmony_ci if (values.size() <= 0) { 63680922886Sopenharmony_ci values.push_back(value); 63780922886Sopenharmony_ci } else { 63880922886Sopenharmony_ci values.insert(values.begin(), value); 63980922886Sopenharmony_ci } 64080922886Sopenharmony_ci } 64180922886Sopenharmony_ci 64280922886Sopenharmony_ci std::string newSortContent = values.dump(); 64380922886Sopenharmony_ci if (!SaveStringToFileEx(GetAVSortDir(), newSortContent)) { 64480922886Sopenharmony_ci SLOGE("SaveStringToFileEx failed when refresh focus session sort!"); 64580922886Sopenharmony_ci } 64680922886Sopenharmony_ci} 64780922886Sopenharmony_ci// LCOV_EXCL_STOP 64880922886Sopenharmony_ci 64980922886Sopenharmony_civoid AVSessionService::UpdateFrontSession(sptr<AVSessionItem>& sessionItem, bool isAdd) 65080922886Sopenharmony_ci{ 65180922886Sopenharmony_ci SLOGI("UpdateFrontSession with bundle=%{public}s isAdd=%{public}d", sessionItem->GetBundleName().c_str(), isAdd); 65280922886Sopenharmony_ci std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront(); 65380922886Sopenharmony_ci CHECK_AND_RETURN_LOG(sessionListForFront != nullptr, "sessionListForFront ptr nullptr!"); 65480922886Sopenharmony_ci auto it = std::find(sessionListForFront->begin(), sessionListForFront->end(), sessionItem); 65580922886Sopenharmony_ci if (isAdd) { 65680922886Sopenharmony_ci if (it != sessionListForFront->end()) { 65780922886Sopenharmony_ci SLOGI("sessionListForFront has same session bundle=%{public}s", sessionItem->GetBundleName().c_str()); 65880922886Sopenharmony_ci return; 65980922886Sopenharmony_ci } 66080922886Sopenharmony_ci sessionListForFront->push_front(sessionItem); 66180922886Sopenharmony_ci if (AudioAdapter::GetInstance().GetRendererRunning(sessionItem->GetUid())) { 66280922886Sopenharmony_ci SLOGI("Renderer Running, RepublishNotification for uid=%{public}d", sessionItem->GetUid()); 66380922886Sopenharmony_ci UpdateTopSession(sessionItem); 66480922886Sopenharmony_ci AVSessionDescriptor selectSession = sessionItem->GetDescriptor(); 66580922886Sopenharmony_ci NotifySystemUI(&selectSession, true); 66680922886Sopenharmony_ci } 66780922886Sopenharmony_ci } else { 66880922886Sopenharmony_ci std::lock_guard lockGuard(sessionServiceLock_); 66980922886Sopenharmony_ci if (topSession_.GetRefPtr() == sessionItem.GetRefPtr()) { 67080922886Sopenharmony_ci UpdateTopSession(nullptr); 67180922886Sopenharmony_ci int32_t ret = Notification::NotificationHelper::CancelNotification(0); 67280922886Sopenharmony_ci SLOGI("CancelNotification ret=%{public}d", ret); 67380922886Sopenharmony_ci } 67480922886Sopenharmony_ci sessionListForFront->remove(sessionItem); 67580922886Sopenharmony_ci } 67680922886Sopenharmony_ci} 67780922886Sopenharmony_ci 67880922886Sopenharmony_ci// LCOV_EXCL_START 67980922886Sopenharmony_cibool AVSessionService::SelectFocusSession(const FocusSessionStrategy::FocusSessionChangeInfo& info) 68080922886Sopenharmony_ci{ 68180922886Sopenharmony_ci for (auto& session : GetContainer().GetAllSessions()) { 68280922886Sopenharmony_ci if (session->GetDescriptor().sessionTag_ == "RemoteCast" || session->GetUid() != info.uid) { 68380922886Sopenharmony_ci continue; 68480922886Sopenharmony_ci } 68580922886Sopenharmony_ci GetContainer().UpdateSessionSort(session); 68680922886Sopenharmony_ci RefreshFocusSessionSort(session); 68780922886Sopenharmony_ci std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront(); 68880922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(sessionListForFront != nullptr, false, "sessionListForFront ptr nullptr!"); 68980922886Sopenharmony_ci auto it = std::find(sessionListForFront->begin(), sessionListForFront->end(), session); 69080922886Sopenharmony_ci if (it != sessionListForFront->end()) { 69180922886Sopenharmony_ci SLOGI("Focus session is in sessionListForFront_, need to change order of it."); 69280922886Sopenharmony_ci sessionListForFront->remove(session); 69380922886Sopenharmony_ci sessionListForFront->push_front(session); 69480922886Sopenharmony_ci } 69580922886Sopenharmony_ci return true; 69680922886Sopenharmony_ci } 69780922886Sopenharmony_ci return false; 69880922886Sopenharmony_ci} 69980922886Sopenharmony_ci// LCOV_EXCL_STOP 70080922886Sopenharmony_ci 70180922886Sopenharmony_civoid AVSessionService::InitAudio() 70280922886Sopenharmony_ci{ 70380922886Sopenharmony_ci SLOGI("enter"); 70480922886Sopenharmony_ci AudioAdapter::GetInstance().Init(); 70580922886Sopenharmony_ci focusSessionStrategy_.Init(); 70680922886Sopenharmony_ci focusSessionStrategy_.RegisterFocusSessionChangeCallback([this] (const auto& info) { 70780922886Sopenharmony_ci HandleFocusSession(info); 70880922886Sopenharmony_ci }); 70980922886Sopenharmony_ci focusSessionStrategy_.RegisterFocusSessionSelector([this] (const auto& info) { 71080922886Sopenharmony_ci return SelectFocusSession(info); 71180922886Sopenharmony_ci }); 71280922886Sopenharmony_ci AudioAdapter::GetInstance().AddStreamRendererStateListener([this] (const AudioRendererChangeInfos& infos) { 71380922886Sopenharmony_ci OutputDeviceChangeListener(infos); 71480922886Sopenharmony_ci }); 71580922886Sopenharmony_ci AudioAdapter::GetInstance().AddDeviceChangeListener([this] (const DeviceChangeAction& deviceChangeAction) { 71680922886Sopenharmony_ci HandleDeviceChange(deviceChangeAction); 71780922886Sopenharmony_ci }); 71880922886Sopenharmony_ci} 71980922886Sopenharmony_ci 72080922886Sopenharmony_cisptr <AVSessionItem> AVSessionService::SelectSessionByUid(const AudioRendererChangeInfo& info) 72180922886Sopenharmony_ci{ 72280922886Sopenharmony_ci for (const auto& session : GetContainer().GetAllSessions()) { 72380922886Sopenharmony_ci if (session != nullptr && session->GetUid() == info.clientUID) { 72480922886Sopenharmony_ci return session; 72580922886Sopenharmony_ci } 72680922886Sopenharmony_ci } 72780922886Sopenharmony_ci SLOGI("AudioRendererInfo with uid: %{public}d does not have a corresponding session.", info.clientUID); 72880922886Sopenharmony_ci return nullptr; 72980922886Sopenharmony_ci} 73080922886Sopenharmony_ci 73180922886Sopenharmony_civoid AVSessionService::OutputDeviceChangeListener(const AudioRendererChangeInfos& infos) 73280922886Sopenharmony_ci{ 73380922886Sopenharmony_ci} 73480922886Sopenharmony_ci 73580922886Sopenharmony_civoid AVSessionService::InitAMS() 73680922886Sopenharmony_ci{ 73780922886Sopenharmony_ci SLOGI("enter"); 73880922886Sopenharmony_ci AppManagerAdapter::GetInstance().Init(); 73980922886Sopenharmony_ci AppManagerAdapter::GetInstance().SetServiceCallbackForAppStateChange([this] (int uid, int state) { 74080922886Sopenharmony_ci SLOGD("uid = %{public}d, state = %{public}d", uid, state); 74180922886Sopenharmony_ci HandleAppStateChange(uid, state); 74280922886Sopenharmony_ci }); 74380922886Sopenharmony_ci} 74480922886Sopenharmony_ci 74580922886Sopenharmony_civoid AVSessionService::InitDM() 74680922886Sopenharmony_ci{ 74780922886Sopenharmony_ci SLOGI("enter"); 74880922886Sopenharmony_ci auto callback = std::make_shared<AVSessionInitDMCallback>(); 74980922886Sopenharmony_ci CHECK_AND_RETURN_LOG(callback != nullptr, "no memory"); 75080922886Sopenharmony_ci int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().InitDeviceManager("av_session", callback); 75180922886Sopenharmony_ci CHECK_AND_RETURN_LOG(ret == 0, "InitDeviceManager error ret is %{public}d", ret); 75280922886Sopenharmony_ci} 75380922886Sopenharmony_ci 75480922886Sopenharmony_civoid AVSessionService::InitBMS() 75580922886Sopenharmony_ci{ 75680922886Sopenharmony_ci std::lock_guard sortFileLockGuard(sessionFileLock_); 75780922886Sopenharmony_ci SLOGI("enter"); 75880922886Sopenharmony_ci BundleStatusAdapter::GetInstance().Init(); 75980922886Sopenharmony_ci int userId = GetUsersManager().GetCurrentUserId(); 76080922886Sopenharmony_ci if (userId < 0) { 76180922886Sopenharmony_ci SLOGE("InitBMS with userId: %{public}d, not valid, return and wait for InitAccountMgr", userId); 76280922886Sopenharmony_ci return; 76380922886Sopenharmony_ci } 76480922886Sopenharmony_ci RegisterBundleDeleteEventForHistory(userId); 76580922886Sopenharmony_ci} 76680922886Sopenharmony_ci 76780922886Sopenharmony_civoid AVSessionService::InitAccountMgr() 76880922886Sopenharmony_ci{ 76980922886Sopenharmony_ci SLOGI("InitAccountMgr in"); 77080922886Sopenharmony_ci GetUsersManager().Init(); 77180922886Sopenharmony_ci RegisterBundleDeleteEventForHistory(); 77280922886Sopenharmony_ci} 77380922886Sopenharmony_ci 77480922886Sopenharmony_civoid AVSessionService::InitCommonEventService() 77580922886Sopenharmony_ci{ 77680922886Sopenharmony_ci SLOGI("InitCommonEventService in"); 77780922886Sopenharmony_ci bool ret = SubscribeCommonEvent(); 77880922886Sopenharmony_ci CHECK_AND_RETURN_LOG(ret, "SubscribeCommonEvent error!"); 77980922886Sopenharmony_ci} 78080922886Sopenharmony_ci 78180922886Sopenharmony_civoid AVSessionService::RegisterBundleDeleteEventForHistory(int32_t userId) 78280922886Sopenharmony_ci{ 78380922886Sopenharmony_ci if (userId <= 0) { 78480922886Sopenharmony_ci userId = GetUsersManager().GetCurrentUserId(); 78580922886Sopenharmony_ci SLOGI("do RegisterBundleDeleteEventForHistory with cur userId:%{public}d", userId); 78680922886Sopenharmony_ci } else { 78780922886Sopenharmony_ci SLOGI("do RegisterBundleDeleteEventForHistory with recv userId:%{public}d", userId); 78880922886Sopenharmony_ci } 78980922886Sopenharmony_ci 79080922886Sopenharmony_ci std::string oldSortContent; 79180922886Sopenharmony_ci if (LoadStringFromFileEx(GetAVSortDir(userId), oldSortContent)) { 79280922886Sopenharmony_ci nlohmann::json values = json::parse(oldSortContent, nullptr, false); 79380922886Sopenharmony_ci CHECK_AND_RETURN_LOG(!values.is_discarded(), "json object is null"); 79480922886Sopenharmony_ci auto callback = [this](std::string bundleName, int32_t userId) { 79580922886Sopenharmony_ci SLOGI("recv delete bundle:%{public}s at user:%{public}d", bundleName.c_str(), userId); 79680922886Sopenharmony_ci DeleteAVQueueInfoRecord(bundleName, userId); 79780922886Sopenharmony_ci DeleteHistoricalRecord(bundleName, userId); 79880922886Sopenharmony_ci }; 79980922886Sopenharmony_ci for (auto value : values) { 80080922886Sopenharmony_ci if (!BundleStatusAdapter::GetInstance().SubscribeBundleStatusEvent(value["bundleName"], callback, userId)) { 80180922886Sopenharmony_ci std::string bundleName = value["bundleName"]; 80280922886Sopenharmony_ci SLOGE("SubscribeBundleStatusEvent failed for bundle:%{public}s", bundleName.c_str()); 80380922886Sopenharmony_ci } 80480922886Sopenharmony_ci } 80580922886Sopenharmony_ci } 80680922886Sopenharmony_ci} 80780922886Sopenharmony_ci 80880922886Sopenharmony_ciSessionContainer& AVSessionService::GetContainer() 80980922886Sopenharmony_ci{ 81080922886Sopenharmony_ci return GetUsersManager().GetContainer(); 81180922886Sopenharmony_ci} 81280922886Sopenharmony_ci 81380922886Sopenharmony_ciAVSessionUsersManager& AVSessionService::GetUsersManager() 81480922886Sopenharmony_ci{ 81580922886Sopenharmony_ci static AVSessionUsersManager usersManager; 81680922886Sopenharmony_ci return usersManager; 81780922886Sopenharmony_ci} 81880922886Sopenharmony_ci 81980922886Sopenharmony_ciinline std::shared_ptr<std::list<sptr<AVSessionItem>>> AVSessionService::GetCurSessionListForFront() 82080922886Sopenharmony_ci{ 82180922886Sopenharmony_ci return GetUsersManager().GetCurSessionListForFront(); 82280922886Sopenharmony_ci} 82380922886Sopenharmony_ci 82480922886Sopenharmony_cistd::string AVSessionService::AllocSessionId() 82580922886Sopenharmony_ci{ 82680922886Sopenharmony_ci auto curNum = sessionSeqNum_++; 82780922886Sopenharmony_ci std::string id = std::to_string(GetCallingPid()) + "-" + std::to_string(GetCallingUid()) + "-" + 82880922886Sopenharmony_ci std::to_string(curNum); 82980922886Sopenharmony_ci 83080922886Sopenharmony_ci HashCalculator hashCalculator; 83180922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(hashCalculator.Init() == AVSESSION_SUCCESS, "", "hash init failed"); 83280922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(hashCalculator.Update(std::vector<uint8_t>(id.begin(), id.end())) == AVSESSION_SUCCESS, 83380922886Sopenharmony_ci "", "hash update failed"); 83480922886Sopenharmony_ci std::vector<uint8_t> hash; 83580922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(hashCalculator.GetResult(hash) == AVSESSION_SUCCESS, "", "hash get result failed"); 83680922886Sopenharmony_ci 83780922886Sopenharmony_ci std::stringstream stream; 83880922886Sopenharmony_ci for (const auto byte : hash) { 83980922886Sopenharmony_ci stream << std::uppercase << std::hex << std::setfill('0') << std::setw(allocSpace) << static_cast<int>(byte); 84080922886Sopenharmony_ci } 84180922886Sopenharmony_ci return stream.str(); 84280922886Sopenharmony_ci} 84380922886Sopenharmony_ci 84480922886Sopenharmony_cibool AVSessionService::AbilityHasSession(pid_t pid) 84580922886Sopenharmony_ci{ 84680922886Sopenharmony_ci std::lock_guard lockGuard(sessionServiceLock_); 84780922886Sopenharmony_ci return GetContainer().PidHasSession(pid); 84880922886Sopenharmony_ci} 84980922886Sopenharmony_ci 85080922886Sopenharmony_cisptr<AVControllerItem> AVSessionService::GetPresentController(pid_t pid, const std::string& sessionId) 85180922886Sopenharmony_ci{ 85280922886Sopenharmony_ci std::lock_guard lockGuard(sessionServiceLock_); 85380922886Sopenharmony_ci auto it = controllers_.find(pid); 85480922886Sopenharmony_ci if (it != controllers_.end()) { 85580922886Sopenharmony_ci for (const auto& controller: it->second) { 85680922886Sopenharmony_ci if (controller != nullptr && controller->HasSession(sessionId)) { 85780922886Sopenharmony_ci return controller; 85880922886Sopenharmony_ci } 85980922886Sopenharmony_ci } 86080922886Sopenharmony_ci } 86180922886Sopenharmony_ci SLOGI("Not found controller for pid:%{public}d, sessionId:%{public}s.", pid, sessionId.c_str()); 86280922886Sopenharmony_ci return nullptr; 86380922886Sopenharmony_ci} 86480922886Sopenharmony_ci 86580922886Sopenharmony_civoid AVSessionService::NotifySessionCreate(const AVSessionDescriptor& descriptor) 86680922886Sopenharmony_ci{ 86780922886Sopenharmony_ci std::lock_guard lockGuard(sessionListenersLock_); 86880922886Sopenharmony_ci std::map<pid_t, sptr<ISessionListener>> listenerMap = GetUsersManager().GetSessionListener(); 86980922886Sopenharmony_ci for (const auto& [pid, listener] : listenerMap) { 87080922886Sopenharmony_ci AVSESSION_TRACE_SYNC_START("AVSessionService::OnSessionCreate"); 87180922886Sopenharmony_ci if (listener != nullptr) { 87280922886Sopenharmony_ci listener->OnSessionCreate(descriptor); 87380922886Sopenharmony_ci } 87480922886Sopenharmony_ci } 87580922886Sopenharmony_ci std::map<pid_t, sptr<ISessionListener>> listenerMapForAll = GetUsersManager().GetSessionListenerForAllUsers(); 87680922886Sopenharmony_ci for (const auto& [pid, listener] : listenerMapForAll) { 87780922886Sopenharmony_ci AVSESSION_TRACE_SYNC_START("AVSessionService::OnSessionCreate"); 87880922886Sopenharmony_ci if (listener != nullptr) { 87980922886Sopenharmony_ci listener->OnSessionCreate(descriptor); 88080922886Sopenharmony_ci } 88180922886Sopenharmony_ci } 88280922886Sopenharmony_ci 88380922886Sopenharmony_ci { 88480922886Sopenharmony_ci std::lock_guard lockGuard(migrateListenersLock_); 88580922886Sopenharmony_ci for (const auto& listener : innerSessionListeners_) { 88680922886Sopenharmony_ci if (listener != nullptr) { 88780922886Sopenharmony_ci listener->OnSessionCreate(descriptor); 88880922886Sopenharmony_ci } 88980922886Sopenharmony_ci } 89080922886Sopenharmony_ci } 89180922886Sopenharmony_ci} 89280922886Sopenharmony_ci 89380922886Sopenharmony_civoid AVSessionService::NotifySessionRelease(const AVSessionDescriptor& descriptor) 89480922886Sopenharmony_ci{ 89580922886Sopenharmony_ci std::lock_guard lockGuard(sessionListenersLock_); 89680922886Sopenharmony_ci std::map<pid_t, sptr<ISessionListener>> listenerMap = GetUsersManager().GetSessionListener(); 89780922886Sopenharmony_ci for (const auto& [pid, listener] : listenerMap) { 89880922886Sopenharmony_ci if (listener != nullptr) { 89980922886Sopenharmony_ci listener->OnSessionRelease(descriptor); 90080922886Sopenharmony_ci } 90180922886Sopenharmony_ci } 90280922886Sopenharmony_ci std::map<pid_t, sptr<ISessionListener>> listenerMapForAll = GetUsersManager().GetSessionListenerForAllUsers(); 90380922886Sopenharmony_ci for (const auto& [pid, listener] : listenerMapForAll) { 90480922886Sopenharmony_ci if (listener != nullptr) { 90580922886Sopenharmony_ci listener->OnSessionRelease(descriptor); 90680922886Sopenharmony_ci } 90780922886Sopenharmony_ci } 90880922886Sopenharmony_ci 90980922886Sopenharmony_ci { 91080922886Sopenharmony_ci std::lock_guard lockGuard(migrateListenersLock_); 91180922886Sopenharmony_ci for (const auto& listener : innerSessionListeners_) { 91280922886Sopenharmony_ci if (listener != nullptr) { 91380922886Sopenharmony_ci listener->OnSessionRelease(descriptor); 91480922886Sopenharmony_ci } 91580922886Sopenharmony_ci } 91680922886Sopenharmony_ci } 91780922886Sopenharmony_ci} 91880922886Sopenharmony_ci 91980922886Sopenharmony_civoid AVSessionService::NotifyTopSessionChanged(const AVSessionDescriptor& descriptor) 92080922886Sopenharmony_ci{ 92180922886Sopenharmony_ci std::lock_guard lockGuard(sessionListenersLock_); 92280922886Sopenharmony_ci std::map<pid_t, sptr<ISessionListener>> listenerMap = GetUsersManager().GetSessionListener(); 92380922886Sopenharmony_ci for (const auto& [pid, listener] : listenerMap) { 92480922886Sopenharmony_ci AVSESSION_TRACE_SYNC_START("AVSessionService::OnTopSessionChange"); 92580922886Sopenharmony_ci if (listener != nullptr) { 92680922886Sopenharmony_ci listener->OnTopSessionChange(descriptor); 92780922886Sopenharmony_ci } 92880922886Sopenharmony_ci } 92980922886Sopenharmony_ci std::map<pid_t, sptr<ISessionListener>> listenerMapForAll = GetUsersManager().GetSessionListenerForAllUsers(); 93080922886Sopenharmony_ci for (const auto& [pid, listener] : listenerMapForAll) { 93180922886Sopenharmony_ci AVSESSION_TRACE_SYNC_START("AVSessionService::OnTopSessionChange"); 93280922886Sopenharmony_ci if (listener != nullptr) { 93380922886Sopenharmony_ci listener->OnTopSessionChange(descriptor); 93480922886Sopenharmony_ci } 93580922886Sopenharmony_ci } 93680922886Sopenharmony_ci 93780922886Sopenharmony_ci { 93880922886Sopenharmony_ci std::lock_guard lockGuard(migrateListenersLock_); 93980922886Sopenharmony_ci for (const auto& listener : innerSessionListeners_) { 94080922886Sopenharmony_ci if (listener != nullptr) { 94180922886Sopenharmony_ci listener->OnTopSessionChange(descriptor); 94280922886Sopenharmony_ci } 94380922886Sopenharmony_ci } 94480922886Sopenharmony_ci } 94580922886Sopenharmony_ci} 94680922886Sopenharmony_ci 94780922886Sopenharmony_ci// LCOV_EXCL_START 94880922886Sopenharmony_civoid AVSessionService::NotifyAudioSessionCheck(const int32_t uid) 94980922886Sopenharmony_ci{ 95080922886Sopenharmony_ci std::lock_guard lockGuard(sessionListenersLock_); 95180922886Sopenharmony_ci std::map<pid_t, sptr<ISessionListener>> listenerMap = GetUsersManager().GetSessionListener(); 95280922886Sopenharmony_ci for (const auto& [pid, listener] : listenerMap) { 95380922886Sopenharmony_ci AVSESSION_TRACE_SYNC_START("AVSessionService::OnAudioSessionCheck"); 95480922886Sopenharmony_ci if (listener != nullptr) { 95580922886Sopenharmony_ci listener->OnAudioSessionChecked(uid); 95680922886Sopenharmony_ci } 95780922886Sopenharmony_ci } 95880922886Sopenharmony_ci std::map<pid_t, sptr<ISessionListener>> listenerMapForAll = GetUsersManager().GetSessionListenerForAllUsers(); 95980922886Sopenharmony_ci for (const auto& [pid, listener] : listenerMapForAll) { 96080922886Sopenharmony_ci AVSESSION_TRACE_SYNC_START("AVSessionService::OnAudioSessionCheck"); 96180922886Sopenharmony_ci if (listener != nullptr) { 96280922886Sopenharmony_ci listener->OnAudioSessionChecked(uid); 96380922886Sopenharmony_ci } 96480922886Sopenharmony_ci } 96580922886Sopenharmony_ci { 96680922886Sopenharmony_ci std::lock_guard lockGuard(migrateListenersLock_); 96780922886Sopenharmony_ci for (const auto& listener : innerSessionListeners_) { 96880922886Sopenharmony_ci if (listener != nullptr) { 96980922886Sopenharmony_ci listener->OnAudioSessionChecked(uid); 97080922886Sopenharmony_ci } 97180922886Sopenharmony_ci } 97280922886Sopenharmony_ci } 97380922886Sopenharmony_ci} 97480922886Sopenharmony_ci// LCOV_EXCL_STOP 97580922886Sopenharmony_ci 97680922886Sopenharmony_cibool AVSessionService::CheckAncoAudio() 97780922886Sopenharmony_ci{ 97880922886Sopenharmony_ci for (const auto& session : GetContainer().GetAllSessions()) { 97980922886Sopenharmony_ci if (session->GetBundleName() == "anco_audio") { 98080922886Sopenharmony_ci return true; 98180922886Sopenharmony_ci } 98280922886Sopenharmony_ci } 98380922886Sopenharmony_ci return false; 98480922886Sopenharmony_ci} 98580922886Sopenharmony_ci 98680922886Sopenharmony_ci// LCOV_EXCL_START 98780922886Sopenharmony_civoid AVSessionService::HandleCallStartEvent() 98880922886Sopenharmony_ci{ 98980922886Sopenharmony_ci SLOGI("Call mediaController player in sink side when cast state is connected."); 99080922886Sopenharmony_ci AbilityConnectHelper::GetInstance().StartAbilityForegroundByCall(MEDIA_CONTROL_BUNDLENAME, 99180922886Sopenharmony_ci MEDIA_CONTROL_ABILITYNAME); 99280922886Sopenharmony_ci} 99380922886Sopenharmony_ci// LCOV_EXCL_STOP 99480922886Sopenharmony_ci 99580922886Sopenharmony_civoid AVSessionService::ServiceCallback(sptr<AVSessionItem>& sessionItem) 99680922886Sopenharmony_ci{ 99780922886Sopenharmony_ci if (sessionItem == nullptr) { 99880922886Sopenharmony_ci SLOGE("sessionItem is null when serviceCallback"); 99980922886Sopenharmony_ci return; 100080922886Sopenharmony_ci } 100180922886Sopenharmony_ci sessionItem->SetServiceCallbackForRelease([this](AVSessionItem& session) { 100280922886Sopenharmony_ci HandleSessionRelease(session.GetDescriptor().sessionId_); 100380922886Sopenharmony_ci }); 100480922886Sopenharmony_ci sessionItem->SetServiceCallbackForAVQueueInfo([this](AVSessionItem& session) { 100580922886Sopenharmony_ci AddAvQueueInfoToFile(session); 100680922886Sopenharmony_ci }); 100780922886Sopenharmony_ci sessionItem->SetServiceCallbackForCallStart([this](AVSessionItem& session) { 100880922886Sopenharmony_ci HandleCallStartEvent(); 100980922886Sopenharmony_ci }); 101080922886Sopenharmony_ci sessionItem->SetServiceCallbackForUpdateSession([this](std::string sessionId, bool isAdd) { 101180922886Sopenharmony_ci std::lock_guard lockGuard(sessionServiceLock_); 101280922886Sopenharmony_ci sptr<AVSessionItem> session = GetContainer().GetSessionById(sessionId); 101380922886Sopenharmony_ci CHECK_AND_RETURN_LOG(session != nullptr, "session not exist for UpdateFrontSession"); 101480922886Sopenharmony_ci UpdateFrontSession(session, isAdd); 101580922886Sopenharmony_ci }); 101680922886Sopenharmony_ci#ifdef CASTPLUS_CAST_ENGINE_ENABLE 101780922886Sopenharmony_ci sessionItem->SetServiceCallbackForStream([this](std::string sessionId) { 101880922886Sopenharmony_ci sptr<AVSessionItem> session = GetContainer().GetSessionById(sessionId); 101980922886Sopenharmony_ci uidForAppStateChange_ = session->GetUid(); 102080922886Sopenharmony_ci if (isSupportMirrorToStream_ && 102180922886Sopenharmony_ci !AppManagerAdapter::GetInstance().IsAppBackground(session->GetUid(), session->GetPid())) { 102280922886Sopenharmony_ci MirrorToStreamCast(session); 102380922886Sopenharmony_ci } 102480922886Sopenharmony_ci }); 102580922886Sopenharmony_ci#endif // CASTPLUS_CAST_ENGINE_ENABLE 102680922886Sopenharmony_ci} 102780922886Sopenharmony_ci 102880922886Sopenharmony_cisptr<AVSessionItem> AVSessionService::CreateNewSession(const std::string& tag, int32_t type, bool thirdPartyApp, 102980922886Sopenharmony_ci const AppExecFwk::ElementName& elementName) 103080922886Sopenharmony_ci{ 103180922886Sopenharmony_ci SLOGI("%{public}s %{public}d %{public}s %{public}s thirdPartyApp=%{public}d", tag.c_str(), type, 103280922886Sopenharmony_ci elementName.GetBundleName().c_str(), elementName.GetAbilityName().c_str(), thirdPartyApp); 103380922886Sopenharmony_ci AVSessionDescriptor descriptor; 103480922886Sopenharmony_ci descriptor.sessionId_ = AllocSessionId(); 103580922886Sopenharmony_ci if (descriptor.sessionId_.empty()) { 103680922886Sopenharmony_ci SLOGE("alloc session id failed"); 103780922886Sopenharmony_ci return nullptr; 103880922886Sopenharmony_ci } 103980922886Sopenharmony_ci descriptor.sessionTag_ = tag; 104080922886Sopenharmony_ci descriptor.sessionType_ = type; 104180922886Sopenharmony_ci descriptor.elementName_ = elementName; 104280922886Sopenharmony_ci descriptor.isThirdPartyApp_ = thirdPartyApp; 104380922886Sopenharmony_ci 104480922886Sopenharmony_ci sptr<AVSessionItem> result = new(std::nothrow) AVSessionItem(descriptor, GetUsersManager().GetCurrentUserId()); 104580922886Sopenharmony_ci if (result == nullptr) { 104680922886Sopenharmony_ci return nullptr; 104780922886Sopenharmony_ci } 104880922886Sopenharmony_ci result->SetPid(GetCallingPid()); 104980922886Sopenharmony_ci result->SetUid(GetCallingUid()); 105080922886Sopenharmony_ci ServiceCallback(result); 105180922886Sopenharmony_ci 105280922886Sopenharmony_ci OutputDeviceInfo outputDeviceInfo; 105380922886Sopenharmony_ci DeviceInfo deviceInfo; 105480922886Sopenharmony_ci deviceInfo.castCategory_ = AVCastCategory::CATEGORY_LOCAL; 105580922886Sopenharmony_ci deviceInfo.deviceId_ = "0"; 105680922886Sopenharmony_ci deviceInfo.deviceName_ = "LocalDevice"; 105780922886Sopenharmony_ci outputDeviceInfo.deviceInfos_.emplace_back(deviceInfo); 105880922886Sopenharmony_ci result->SetOutputDevice(outputDeviceInfo); 105980922886Sopenharmony_ci 106080922886Sopenharmony_ci return result; 106180922886Sopenharmony_ci} 106280922886Sopenharmony_ci 106380922886Sopenharmony_cibool AVSessionService::IsParamInvalid(const std::string& tag, int32_t type, const AppExecFwk::ElementName& elementName) 106480922886Sopenharmony_ci{ 106580922886Sopenharmony_ci if (tag.empty()) { 106680922886Sopenharmony_ci SLOGE("tag is empty when create session"); 106780922886Sopenharmony_ci return false; 106880922886Sopenharmony_ci } 106980922886Sopenharmony_ci if (type != AVSession::SESSION_TYPE_AUDIO && type != AVSession::SESSION_TYPE_VIDEO 107080922886Sopenharmony_ci && type != AVSession::SESSION_TYPE_VOICE_CALL && type != AVSession::SESSION_TYPE_VIDEO_CALL) { 107180922886Sopenharmony_ci SLOGE("type is invalid when create session"); 107280922886Sopenharmony_ci return false; 107380922886Sopenharmony_ci } 107480922886Sopenharmony_ci if (elementName.GetBundleName().empty() || elementName.GetAbilityName().empty()) { 107580922886Sopenharmony_ci SLOGE("element is invalid when create session"); 107680922886Sopenharmony_ci return false; 107780922886Sopenharmony_ci } 107880922886Sopenharmony_ci std::regex nameRegex("[A-Za-z\\w\\.]*"); 107980922886Sopenharmony_ci if (!std::regex_match(elementName.GetBundleName(), nameRegex)) { 108080922886Sopenharmony_ci SLOGE("err regex when create session, bundleName=%{public}s", (elementName.GetBundleName()).c_str()); 108180922886Sopenharmony_ci return false; 108280922886Sopenharmony_ci } 108380922886Sopenharmony_ci if (!std::regex_match(elementName.GetAbilityName(), nameRegex)) { 108480922886Sopenharmony_ci SLOGE("err regex when create session, abilityName=%{public}s", (elementName.GetAbilityName()).c_str()); 108580922886Sopenharmony_ci return false; 108680922886Sopenharmony_ci } 108780922886Sopenharmony_ci 108880922886Sopenharmony_ci return true; 108980922886Sopenharmony_ci} 109080922886Sopenharmony_ci 109180922886Sopenharmony_ciint32_t AVSessionService::CreateSessionInner(const std::string& tag, int32_t type, bool thirdPartyApp, 109280922886Sopenharmony_ci const AppExecFwk::ElementName& elementName, 109380922886Sopenharmony_ci sptr<AVSessionItem>& sessionItem) 109480922886Sopenharmony_ci{ 109580922886Sopenharmony_ci if (!IsParamInvalid(tag, type, elementName)) { 109680922886Sopenharmony_ci return ERR_INVALID_PARAM; 109780922886Sopenharmony_ci } 109880922886Sopenharmony_ci auto pid = GetCallingPid(); 109980922886Sopenharmony_ci std::lock_guard lockGuard(sessionServiceLock_); 110080922886Sopenharmony_ci if (AbilityHasSession(pid)) { 110180922886Sopenharmony_ci SLOGE("process %{public}d %{public}s already has one session", pid, elementName.GetAbilityName().c_str()); 110280922886Sopenharmony_ci return ERR_SESSION_IS_EXIST; 110380922886Sopenharmony_ci } 110480922886Sopenharmony_ci 110580922886Sopenharmony_ci sptr<AVSessionItem> result = CreateNewSession(tag, type, thirdPartyApp, elementName); 110680922886Sopenharmony_ci if (result == nullptr) { 110780922886Sopenharmony_ci SLOGE("create new session failed"); 110880922886Sopenharmony_ci if (dumpHelper_ != nullptr) { 110980922886Sopenharmony_ci dumpHelper_->SetErrorInfo(" AVSessionService::CreateSessionInner create new session failed"); 111080922886Sopenharmony_ci } 111180922886Sopenharmony_ci HISYSEVENT_FAULT("CONTROL_COMMAND_FAILED", "CALLER_PID", pid, "TAG", tag, "TYPE", type, "BUNDLE_NAME", 111280922886Sopenharmony_ci elementName.GetBundleName(), "ERROR_MSG", "avsessionservice createsessioninner create new session failed"); 111380922886Sopenharmony_ci return ERR_NO_MEMORY; 111480922886Sopenharmony_ci } 111580922886Sopenharmony_ci if (GetUsersManager().AddSessionForCurrentUser(pid, elementName.GetAbilityName(), result) != AVSESSION_SUCCESS) { 111680922886Sopenharmony_ci SLOGE("session num exceed max"); 111780922886Sopenharmony_ci return ERR_SESSION_EXCEED_MAX; 111880922886Sopenharmony_ci } 111980922886Sopenharmony_ci 112080922886Sopenharmony_ci HISYSEVENT_ADD_LIFE_CYCLE_INFO(elementName.GetBundleName(), 112180922886Sopenharmony_ci AppManagerAdapter::GetInstance().IsAppBackground(GetCallingUid(), GetCallingPid()), type, true); 112280922886Sopenharmony_ci 112380922886Sopenharmony_ci NotifySessionCreate(result->GetDescriptor()); 112480922886Sopenharmony_ci sessionItem = result; 112580922886Sopenharmony_ci 112680922886Sopenharmony_ci std::lock_guard frontLockGuard(sessionFrontLock_); 112780922886Sopenharmony_ci std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront(); 112880922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(sessionListForFront != nullptr, AVSESSION_ERROR, "sessionListForFront ptr nullptr!"); 112980922886Sopenharmony_ci auto it = std::find(sessionListForFront->begin(), sessionListForFront->end(), sessionItem); 113080922886Sopenharmony_ci if ((type == AVSession::SESSION_TYPE_VOICE_CALL || type == AVSession::SESSION_TYPE_VIDEO_CALL || 113180922886Sopenharmony_ci (tag == "anco_audio" && GetCallingUid() == ancoUid)) && it == sessionListForFront->end()) { 113280922886Sopenharmony_ci SLOGI(" front session add voice_call session=%{public}s", sessionItem->GetBundleName().c_str()); 113380922886Sopenharmony_ci sessionListForFront->push_front(sessionItem); 113480922886Sopenharmony_ci } 113580922886Sopenharmony_ci return AVSESSION_SUCCESS; 113680922886Sopenharmony_ci} 113780922886Sopenharmony_ci 113880922886Sopenharmony_cisptr<AVSessionItem> AVSessionService::CreateSessionInner(const std::string& tag, int32_t type, bool thirdPartyApp, 113980922886Sopenharmony_ci const AppExecFwk::ElementName& elementName) 114080922886Sopenharmony_ci{ 114180922886Sopenharmony_ci sptr<AVSessionItem> sessionItem; 114280922886Sopenharmony_ci auto res = CreateSessionInner(tag, type, thirdPartyApp, elementName, sessionItem); 114380922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(res == AVSESSION_SUCCESS, nullptr, "create avSessionItem failed"); 114480922886Sopenharmony_ci return sessionItem; 114580922886Sopenharmony_ci} 114680922886Sopenharmony_ci 114780922886Sopenharmony_civoid AVSessionService::ReportSessionInfo(const sptr <AVSessionItem>& session, int32_t res) 114880922886Sopenharmony_ci{ 114980922886Sopenharmony_ci std::string sessionId = ""; 115080922886Sopenharmony_ci std::string sessionTag = ""; 115180922886Sopenharmony_ci std::string SessionType = ""; 115280922886Sopenharmony_ci std::string bundleName = ""; 115380922886Sopenharmony_ci std::string API_PARAM_STRING = ""; 115480922886Sopenharmony_ci if (session != nullptr) { 115580922886Sopenharmony_ci sessionId = AVSessionUtils::GetAnonySessionId(session->GetDescriptor().sessionId_); 115680922886Sopenharmony_ci sessionTag = session->GetDescriptor().sessionTag_; 115780922886Sopenharmony_ci SessionType = session->GetSessionType(); 115880922886Sopenharmony_ci bundleName = session->GetDescriptor().elementName_.GetBundleName(); 115980922886Sopenharmony_ci API_PARAM_STRING = "abilityName: " + 116080922886Sopenharmony_ci session->GetDescriptor().elementName_.GetAbilityName() + "," 116180922886Sopenharmony_ci + "moduleName: " + session->GetDescriptor().elementName_.GetModuleName(); 116280922886Sopenharmony_ci } 116380922886Sopenharmony_ci std::string errMsg = (res == AVSESSION_SUCCESS) ? "SUCCESS" : "create session failed"; 116480922886Sopenharmony_ci HISYSEVENT_BEHAVIOR("SESSION_API_BEHAVIOR", 116580922886Sopenharmony_ci "API_NAME", "CreateSession", 116680922886Sopenharmony_ci "BUNDLE_NAME", bundleName, 116780922886Sopenharmony_ci "SESSION_ID", sessionId, 116880922886Sopenharmony_ci "SESSION_TAG", sessionTag, 116980922886Sopenharmony_ci "SESSION_TYPE", SessionType, 117080922886Sopenharmony_ci "ERROR_CODE", res, 117180922886Sopenharmony_ci "ERROR_MSG", errMsg); 117280922886Sopenharmony_ci} 117380922886Sopenharmony_ci 117480922886Sopenharmony_ciint32_t AVSessionService::CreateSessionInner(const std::string& tag, int32_t type, 117580922886Sopenharmony_ci const AppExecFwk::ElementName& elementName, 117680922886Sopenharmony_ci sptr<IRemoteObject>& object) 117780922886Sopenharmony_ci{ 117880922886Sopenharmony_ci sptr<AVSessionItem> session; 117980922886Sopenharmony_ci auto res = CreateSessionInner(tag, type, 118080922886Sopenharmony_ci PermissionChecker::GetInstance().CheckPermission(PermissionChecker::CHECK_SYSTEM_PERMISSION), 118180922886Sopenharmony_ci elementName, session); 118280922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(res == AVSESSION_SUCCESS, res, "create session fail"); 118380922886Sopenharmony_ci 118480922886Sopenharmony_ci std::string supportModule; 118580922886Sopenharmony_ci std::string profile; 118680922886Sopenharmony_ci if (BundleStatusAdapter::GetInstance().IsSupportPlayIntent(elementName.GetBundleName(), supportModule, profile)) { 118780922886Sopenharmony_ci SLOGI("bundleName=%{public}s support play intent, refreshSortFile", elementName.GetBundleName().c_str()); 118880922886Sopenharmony_ci SaveSessionInfoInFile(session->GetSessionId(), session->GetSessionType(), elementName); 118980922886Sopenharmony_ci } 119080922886Sopenharmony_ci 119180922886Sopenharmony_ci { 119280922886Sopenharmony_ci std::lock_guard lockGuard1(abilityManagerLock_); 119380922886Sopenharmony_ci std::string bundleName = session->GetDescriptor().elementName_.GetBundleName(); 119480922886Sopenharmony_ci std::string abilityName = session->GetDescriptor().elementName_.GetAbilityName(); 119580922886Sopenharmony_ci auto it = abilityManager_.find(bundleName + abilityName); 119680922886Sopenharmony_ci if (it != abilityManager_.end() && it->second != nullptr) { 119780922886Sopenharmony_ci it->second->StartAbilityByCallDone(session->GetDescriptor().sessionId_); 119880922886Sopenharmony_ci } 119980922886Sopenharmony_ci } 120080922886Sopenharmony_ci 120180922886Sopenharmony_ci object = session; 120280922886Sopenharmony_ci ReportSessionInfo(session, static_cast<int32_t>(res)); 120380922886Sopenharmony_ci 120480922886Sopenharmony_ci { 120580922886Sopenharmony_ci std::lock_guard lockGuard(isAllSessionCastLock_); 120680922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(isAllSessionCast_, AVSESSION_SUCCESS, "no need to cast"); 120780922886Sopenharmony_ci } 120880922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(CastAudioForNewSession(session) == AVSESSION_SUCCESS, 120980922886Sopenharmony_ci AVSESSION_SUCCESS, "cast new session error"); 121080922886Sopenharmony_ci return res; 121180922886Sopenharmony_ci} 121280922886Sopenharmony_ci 121380922886Sopenharmony_cisptr <IRemoteObject> AVSessionService::CreateSessionInner(const std::string& tag, int32_t type, 121480922886Sopenharmony_ci const AppExecFwk::ElementName& elementName) 121580922886Sopenharmony_ci{ 121680922886Sopenharmony_ci sptr<IRemoteObject> object; 121780922886Sopenharmony_ci auto res = CreateSessionInner(tag, type, elementName, object); 121880922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(res == AVSESSION_SUCCESS, nullptr, "create session fail"); 121980922886Sopenharmony_ci return object; 122080922886Sopenharmony_ci} 122180922886Sopenharmony_ci 122280922886Sopenharmony_ci// LCOV_EXCL_START 122380922886Sopenharmony_civoid AVSessionService::SaveSessionInfoInFile(const std::string& sessionId, const std::string& sessionType, 122480922886Sopenharmony_ci const AppExecFwk::ElementName& elementName) 122580922886Sopenharmony_ci{ 122680922886Sopenharmony_ci std::lock_guard sortFileLockGuard(sessionFileLock_); 122780922886Sopenharmony_ci SLOGI("refresh sort when session created, bundleName=%{public}s", (elementName.GetBundleName()).c_str()); 122880922886Sopenharmony_ci std::string oldSortContent; 122980922886Sopenharmony_ci if (LoadStringFromFileEx(GetAVSortDir(), oldSortContent)) { 123080922886Sopenharmony_ci nlohmann::json values = json::parse(oldSortContent, nullptr, false); 123180922886Sopenharmony_ci CHECK_AND_RETURN_LOG(!values.is_discarded(), "sort json object is null"); 123280922886Sopenharmony_ci if (oldSortContent.find(elementName.GetBundleName()) == string::npos) { 123380922886Sopenharmony_ci auto callback = [this](std::string bundleName, int32_t userId) { 123480922886Sopenharmony_ci SLOGI("recv delete bundle:%{public}s at user:%{public}d", bundleName.c_str(), userId); 123580922886Sopenharmony_ci DeleteAVQueueInfoRecord(bundleName, userId); 123680922886Sopenharmony_ci DeleteHistoricalRecord(bundleName, userId); 123780922886Sopenharmony_ci }; 123880922886Sopenharmony_ci if (!BundleStatusAdapter::GetInstance().SubscribeBundleStatusEvent(elementName.GetBundleName(), 123980922886Sopenharmony_ci callback, GetUsersManager().GetCurrentUserId())) { 124080922886Sopenharmony_ci SLOGE("SubscribeBundleStatusEvent failed"); 124180922886Sopenharmony_ci } 124280922886Sopenharmony_ci } 124380922886Sopenharmony_ci for (auto value : values) { 124480922886Sopenharmony_ci if (elementName.GetBundleName() == value["bundleName"] && 124580922886Sopenharmony_ci elementName.GetAbilityName() == value["abilityName"]) { 124680922886Sopenharmony_ci values.erase(std::remove(values.begin(), values.end(), value)); 124780922886Sopenharmony_ci } 124880922886Sopenharmony_ci } 124980922886Sopenharmony_ci nlohmann::json value; 125080922886Sopenharmony_ci value["sessionId"] = sessionId; 125180922886Sopenharmony_ci value["bundleName"] = elementName.GetBundleName(); 125280922886Sopenharmony_ci value["abilityName"] = elementName.GetAbilityName(); 125380922886Sopenharmony_ci value["sessionType"] = sessionType; 125480922886Sopenharmony_ci if (values.size() <= 0) { 125580922886Sopenharmony_ci values.push_back(value); 125680922886Sopenharmony_ci } else { 125780922886Sopenharmony_ci values.insert(values.begin(), value); 125880922886Sopenharmony_ci } 125980922886Sopenharmony_ci std::string newSortContent = values.dump(); 126080922886Sopenharmony_ci SLOGD("SaveSessionInfoInFile::Dump json object finished"); 126180922886Sopenharmony_ci if (!SaveStringToFileEx(GetAVSortDir(), newSortContent)) { 126280922886Sopenharmony_ci SLOGE("SaveStringToFile failed, filename=%{public}s", SORT_FILE_NAME); 126380922886Sopenharmony_ci } 126480922886Sopenharmony_ci } else { 126580922886Sopenharmony_ci SLOGE("LoadStringToFile failed, filename=%{public}s", SORT_FILE_NAME); 126680922886Sopenharmony_ci } 126780922886Sopenharmony_ci} 126880922886Sopenharmony_ci// LCOV_EXCL_STOP 126980922886Sopenharmony_ci 127080922886Sopenharmony_ciint32_t AVSessionService::GetAllSessionDescriptors(std::vector<AVSessionDescriptor>& descriptors) 127180922886Sopenharmony_ci{ 127280922886Sopenharmony_ci std::lock_guard frontLockGuard(sessionFrontLock_); 127380922886Sopenharmony_ci std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront(); 127480922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(sessionListForFront != nullptr, AVSESSION_ERROR, "sessionListForFront ptr nullptr!"); 127580922886Sopenharmony_ci for (const auto& session : *sessionListForFront) { 127680922886Sopenharmony_ci if (session != nullptr) { 127780922886Sopenharmony_ci descriptors.push_back(session->GetDescriptor()); 127880922886Sopenharmony_ci } 127980922886Sopenharmony_ci } 128080922886Sopenharmony_ci SLOGI("GetAllSessionDescriptors with size=%{public}d, topSession:%{public}s", 128180922886Sopenharmony_ci static_cast<int32_t>(descriptors.size()), 128280922886Sopenharmony_ci (topSession_ == nullptr ? "null" : topSession_->GetBundleName()).c_str()); 128380922886Sopenharmony_ci return AVSESSION_SUCCESS; 128480922886Sopenharmony_ci} 128580922886Sopenharmony_ci 128680922886Sopenharmony_ciint32_t AVSessionService::GetSessionDescriptorsBySessionId(const std::string& sessionId, 128780922886Sopenharmony_ci AVSessionDescriptor& descriptor) 128880922886Sopenharmony_ci{ 128980922886Sopenharmony_ci std::lock_guard lockGuard(sessionServiceLock_); 129080922886Sopenharmony_ci sptr<AVSessionItem> session = GetContainer().GetSessionById(sessionId); 129180922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(session != nullptr, AVSESSION_ERROR, "session to be got is not existed"); 129280922886Sopenharmony_ci 129380922886Sopenharmony_ci auto pid = GetCallingPid(); 129480922886Sopenharmony_ci if (pid == session->GetPid()) { 129580922886Sopenharmony_ci descriptor = session->GetDescriptor(); 129680922886Sopenharmony_ci return AVSESSION_SUCCESS; 129780922886Sopenharmony_ci } 129880922886Sopenharmony_ci int32_t err = PermissionChecker::GetInstance().CheckPermission(PermissionChecker::CHECK_SYSTEM_PERMISSION); 129980922886Sopenharmony_ci if (err != ERR_NONE) { 130080922886Sopenharmony_ci SLOGE("GetSessionDescriptorsBySessionId: CheckPermission failed!"); 130180922886Sopenharmony_ci HISYSEVENT_SECURITY("CONTROL_PERMISSION_DENIED", "CALLER_UID", GetCallingUid(), 130280922886Sopenharmony_ci "CALLER_PID", GetCallingUid(), "SESSION_ID", sessionId, 130380922886Sopenharmony_ci "ERROR_MSG", "avsessionservice getsessiondescriptors by sessionid checkpermission failed"); 130480922886Sopenharmony_ci return err; 130580922886Sopenharmony_ci } 130680922886Sopenharmony_ci descriptor = session->GetDescriptor(); 130780922886Sopenharmony_ci return AVSESSION_SUCCESS; 130880922886Sopenharmony_ci} 130980922886Sopenharmony_ci 131080922886Sopenharmony_ciint32_t AVSessionService::GetHistoricalSessionDescriptorsFromFile(std::vector<AVSessionDescriptor>& descriptors) 131180922886Sopenharmony_ci{ 131280922886Sopenharmony_ci std::string oldSortContent; 131380922886Sopenharmony_ci if (!LoadStringFromFileEx(GetAVSortDir(), oldSortContent)) { 131480922886Sopenharmony_ci SLOGE("GetHistoricalSessionDescriptorsFromFile read sort fail, Return!"); 131580922886Sopenharmony_ci return AVSESSION_ERROR; 131680922886Sopenharmony_ci } 131780922886Sopenharmony_ci 131880922886Sopenharmony_ci nlohmann::json sortValues = json::parse(oldSortContent, nullptr, false); 131980922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(!sortValues.is_discarded(), AVSESSION_ERROR, "json object is null"); 132080922886Sopenharmony_ci for (const auto& value : sortValues) { 132180922886Sopenharmony_ci if (value["sessionType"] == "video") { 132280922886Sopenharmony_ci SLOGI("GetHistoricalSessionDescriptorsFromFile with no video type session."); 132380922886Sopenharmony_ci continue; 132480922886Sopenharmony_ci } 132580922886Sopenharmony_ci AVSessionDescriptor descriptor; 132680922886Sopenharmony_ci descriptor.sessionId_ = value["sessionId"]; 132780922886Sopenharmony_ci descriptor.elementName_.SetBundleName(value["bundleName"]); 132880922886Sopenharmony_ci descriptor.elementName_.SetAbilityName(value["abilityName"]); 132980922886Sopenharmony_ci descriptor.sessionType_ = AVSession::SESSION_TYPE_AUDIO; 133080922886Sopenharmony_ci descriptors.push_back(descriptor); 133180922886Sopenharmony_ci } 133280922886Sopenharmony_ci if (descriptors.size() == 0 && GetContainer().GetAllSessions().size() == 0) { 133380922886Sopenharmony_ci SLOGE("GetHistoricalSessionDescriptorsFromFile read empty, return!"); 133480922886Sopenharmony_ci } 133580922886Sopenharmony_ci return AVSESSION_SUCCESS; 133680922886Sopenharmony_ci} 133780922886Sopenharmony_ci 133880922886Sopenharmony_ciint32_t AVSessionService::GetHistoricalSessionDescriptors(int32_t maxSize, 133980922886Sopenharmony_ci std::vector<AVSessionDescriptor>& descriptors) 134080922886Sopenharmony_ci{ 134180922886Sopenharmony_ci std::lock_guard sortFileLockGuard(sessionFileLock_); 134280922886Sopenharmony_ci std::vector<AVSessionDescriptor> tempDescriptors; 134380922886Sopenharmony_ci GetHistoricalSessionDescriptorsFromFile(tempDescriptors); 134480922886Sopenharmony_ci if (maxSize < 0 || maxSize > maxHistoryNums_) { 134580922886Sopenharmony_ci maxSize = unSetHistoryNum; 134680922886Sopenharmony_ci } 134780922886Sopenharmony_ci for (auto iterator = tempDescriptors.begin(); iterator != tempDescriptors.end(); ++iterator) { 134880922886Sopenharmony_ci if (descriptors.size() >= (size_t)maxSize) { 134980922886Sopenharmony_ci break; 135080922886Sopenharmony_ci } 135180922886Sopenharmony_ci descriptors.push_back(*iterator); 135280922886Sopenharmony_ci } 135380922886Sopenharmony_ci 135480922886Sopenharmony_ci return AVSESSION_SUCCESS; 135580922886Sopenharmony_ci} 135680922886Sopenharmony_ci 135780922886Sopenharmony_ci// LCOV_EXCL_START 135880922886Sopenharmony_ciint32_t AVSessionService::GetHistoricalAVQueueInfos(int32_t maxSize, int32_t maxAppSize, 135980922886Sopenharmony_ci std::vector<AVQueueInfo>& avQueueInfos) 136080922886Sopenharmony_ci{ 136180922886Sopenharmony_ci std::lock_guard avQueueFileLockGuard(avQueueFileLock_); 136280922886Sopenharmony_ci std::string oldAVQueueInfoContent; 136380922886Sopenharmony_ci std::vector<AVQueueInfo> tempAVQueueInfos; 136480922886Sopenharmony_ci if (!LoadStringFromFileEx(GetAVQueueDir(), oldAVQueueInfoContent)) { 136580922886Sopenharmony_ci SLOGE("GetHistoricalAVQueueInfos read avqueueinfo fail, Return!"); 136680922886Sopenharmony_ci return AVSESSION_ERROR; 136780922886Sopenharmony_ci } 136880922886Sopenharmony_ci 136980922886Sopenharmony_ci nlohmann::json avQueueValues = json::parse(oldAVQueueInfoContent, nullptr, false); 137080922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(!avQueueValues.is_discarded(), AVSESSION_ERROR, "json object is null"); 137180922886Sopenharmony_ci for (const auto& value : avQueueValues) { 137280922886Sopenharmony_ci AVQueueInfo avQueueInfo; 137380922886Sopenharmony_ci avQueueInfo.SetBundleName(value["bundleName"]); 137480922886Sopenharmony_ci avQueueInfo.SetAVQueueName(value["avQueueName"]); 137580922886Sopenharmony_ci avQueueInfo.SetAVQueueId(value["avQueueId"]); 137680922886Sopenharmony_ci std::shared_ptr<AVSessionPixelMap> avQueuePixelMap = std::make_shared<AVSessionPixelMap>(); 137780922886Sopenharmony_ci AVSessionUtils::ReadImageFromFile(avQueuePixelMap, value["avQueueImageDir"], value["avQueueImageName"]); 137880922886Sopenharmony_ci avQueueInfo.SetAVQueueImage(avQueuePixelMap); 137980922886Sopenharmony_ci avQueueInfo.SetAVQueueImageUri(value["avQueueImageUri"]); 138080922886Sopenharmony_ci tempAVQueueInfos.push_back(avQueueInfo); 138180922886Sopenharmony_ci } 138280922886Sopenharmony_ci for (auto iterator = tempAVQueueInfos.begin(); iterator != tempAVQueueInfos.end(); ++iterator) { 138380922886Sopenharmony_ci avQueueInfos.push_back(*iterator); 138480922886Sopenharmony_ci } 138580922886Sopenharmony_ci 138680922886Sopenharmony_ci return AVSESSION_SUCCESS; 138780922886Sopenharmony_ci} 138880922886Sopenharmony_ci// LCOV_EXCL_STOP 138980922886Sopenharmony_ci 139080922886Sopenharmony_ci// LCOV_EXCL_START 139180922886Sopenharmony_cibool AVSessionService::SaveAvQueueInfo(std::string& oldContent, const std::string &bundleName, 139280922886Sopenharmony_ci const AVMetaData& meta, const int32_t userId) 139380922886Sopenharmony_ci{ 139480922886Sopenharmony_ci nlohmann::json values = json::parse(oldContent, nullptr, false); 139580922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(!values.is_discarded(), false, "avQueue json object is null"); 139680922886Sopenharmony_ci auto it = values.begin(); 139780922886Sopenharmony_ci for (auto& value : values) { 139880922886Sopenharmony_ci if (bundleName == value["bundleName"] && meta.GetAVQueueId() == value["avQueueId"]) { 139980922886Sopenharmony_ci if (meta.GetAVQueueId() == it->at("avQueueId")) { 140080922886Sopenharmony_ci return false; 140180922886Sopenharmony_ci } 140280922886Sopenharmony_ci values.erase(std::remove(values.begin(), values.end(), value)); 140380922886Sopenharmony_ci } 140480922886Sopenharmony_ci } 140580922886Sopenharmony_ci if (values.size() >= (size_t)maxHistoryNums_) { 140680922886Sopenharmony_ci values.erase(values.end() - 1); 140780922886Sopenharmony_ci } 140880922886Sopenharmony_ci 140980922886Sopenharmony_ci nlohmann::json value; 141080922886Sopenharmony_ci value["bundleName"] = bundleName; 141180922886Sopenharmony_ci value["avQueueName"] = meta.GetAVQueueName(); 141280922886Sopenharmony_ci value["avQueueId"] = meta.GetAVQueueId(); 141380922886Sopenharmony_ci std::shared_ptr<AVSessionPixelMap> innerPixelMap = meta.GetAVQueueImage(); 141480922886Sopenharmony_ci if (innerPixelMap != nullptr) { 141580922886Sopenharmony_ci std::string fileDir = AVSessionUtils::GetFixedPathName(); 141680922886Sopenharmony_ci std::string fileName = bundleName + "_" + meta.GetAVQueueId() + AVSessionUtils::GetFileSuffix(); 141780922886Sopenharmony_ci AVSessionUtils::WriteImageToFile(innerPixelMap, fileDir, fileName); 141880922886Sopenharmony_ci innerPixelMap->Clear(); 141980922886Sopenharmony_ci value["avQueueImageDir"] = fileDir; 142080922886Sopenharmony_ci value["avQueueImageName"] = fileName; 142180922886Sopenharmony_ci } else { 142280922886Sopenharmony_ci value["avQueueImageDir"] = ""; 142380922886Sopenharmony_ci value["avQueueImageName"] = ""; 142480922886Sopenharmony_ci } 142580922886Sopenharmony_ci value["avQueueImageUri"] = meta.GetAVQueueImageUri(); 142680922886Sopenharmony_ci if (values.size() <= 0) { 142780922886Sopenharmony_ci values.push_back(value); 142880922886Sopenharmony_ci } else { 142980922886Sopenharmony_ci values.insert(values.begin(), value); 143080922886Sopenharmony_ci } 143180922886Sopenharmony_ci std::string newContent = values.dump(); 143280922886Sopenharmony_ci if (!SaveStringToFileEx(GetAVQueueDir(), newContent)) { 143380922886Sopenharmony_ci SLOGE("SaveStringToFile failed, filename=%{public}s", AVQUEUE_FILE_NAME); 143480922886Sopenharmony_ci return false; 143580922886Sopenharmony_ci } 143680922886Sopenharmony_ci return true; 143780922886Sopenharmony_ci} 143880922886Sopenharmony_ci// LCOV_EXCL_STOP 143980922886Sopenharmony_ci 144080922886Sopenharmony_ci// LCOV_EXCL_START 144180922886Sopenharmony_civoid AVSessionService::AddAvQueueInfoToFile(AVSessionItem& session) 144280922886Sopenharmony_ci{ 144380922886Sopenharmony_ci // check is this session support playmusiclist intent 144480922886Sopenharmony_ci std::lock_guard lockGuard(sessionServiceLock_); 144580922886Sopenharmony_ci std::string bundleName = session.GetBundleName(); 144680922886Sopenharmony_ci std::string supportModule; 144780922886Sopenharmony_ci std::string profile; 144880922886Sopenharmony_ci if (!BundleStatusAdapter::GetInstance().IsSupportPlayIntent(bundleName, supportModule, profile)) { 144980922886Sopenharmony_ci SLOGE("bundleName=%{public}s does not support play intent", bundleName.c_str()); 145080922886Sopenharmony_ci return; 145180922886Sopenharmony_ci } 145280922886Sopenharmony_ci AVMetaData meta = session.GetMetaData(); 145380922886Sopenharmony_ci if (meta.GetAVQueueId().empty() || meta.GetAVQueueName().empty()) { 145480922886Sopenharmony_ci SLOGI("AddAvQueueInfoToFile avqueueinfo empty, return"); 145580922886Sopenharmony_ci DoMetadataImgClean(meta); 145680922886Sopenharmony_ci return; 145780922886Sopenharmony_ci } 145880922886Sopenharmony_ci std::lock_guard avQueueFileLockGuard(avQueueFileLock_); 145980922886Sopenharmony_ci std::string oldContent; 146080922886Sopenharmony_ci if (!LoadStringFromFileEx(GetAVQueueDir(), oldContent)) { 146180922886Sopenharmony_ci SLOGE("AddAvQueueInfoToFile read avqueueinfo fail, Return!"); 146280922886Sopenharmony_ci DoMetadataImgClean(meta); 146380922886Sopenharmony_ci return; 146480922886Sopenharmony_ci } 146580922886Sopenharmony_ci if (!SaveAvQueueInfo(oldContent, bundleName, meta, session.GetUserId())) { 146680922886Sopenharmony_ci SLOGE("SaveAvQueueInfo same avqueueinfo, Return!"); 146780922886Sopenharmony_ci DoMetadataImgClean(meta); 146880922886Sopenharmony_ci return; 146980922886Sopenharmony_ci } 147080922886Sopenharmony_ci DoMetadataImgClean(meta); 147180922886Sopenharmony_ci} 147280922886Sopenharmony_ci// LCOV_EXCL_STOP 147380922886Sopenharmony_ci 147480922886Sopenharmony_civoid AVSessionService::DoMetadataImgClean(AVMetaData& data) 147580922886Sopenharmony_ci{ 147680922886Sopenharmony_ci SLOGI("clear media img in DoMetadataImgClean"); 147780922886Sopenharmony_ci std::shared_ptr<AVSessionPixelMap> innerQueuePixelMap = data.GetAVQueueImage(); 147880922886Sopenharmony_ci if (innerQueuePixelMap != nullptr) { 147980922886Sopenharmony_ci innerQueuePixelMap->Clear(); 148080922886Sopenharmony_ci } 148180922886Sopenharmony_ci std::shared_ptr<AVSessionPixelMap> innerMediaPixelMap = data.GetMediaImage(); 148280922886Sopenharmony_ci if (innerMediaPixelMap != nullptr) { 148380922886Sopenharmony_ci innerMediaPixelMap->Clear(); 148480922886Sopenharmony_ci } 148580922886Sopenharmony_ci} 148680922886Sopenharmony_ci 148780922886Sopenharmony_ciint32_t AVSessionService::StartAVPlayback(const std::string& bundleName, const std::string& assetId) 148880922886Sopenharmony_ci{ 148980922886Sopenharmony_ci std::unique_ptr<AVSessionDynamicLoader> dynamicLoader = std::make_unique<AVSessionDynamicLoader>(); 149080922886Sopenharmony_ci if (dynamicLoader == nullptr) { 149180922886Sopenharmony_ci SLOGI("dynamicLoader is null"); 149280922886Sopenharmony_ci return AVSESSION_ERROR; 149380922886Sopenharmony_ci } 149480922886Sopenharmony_ci 149580922886Sopenharmony_ci typedef int32_t (*StartAVPlaybackFunc)(const std::string& bundleName, const std::string& assetId); 149680922886Sopenharmony_ci StartAVPlaybackFunc startAVPlayback = 149780922886Sopenharmony_ci reinterpret_cast<StartAVPlaybackFunc>(dynamicLoader->GetFuntion( 149880922886Sopenharmony_ci AVSESSION_DYNAMIC_INSIGHT_LIBRARY_PATH, "StartAVPlayback")); 149980922886Sopenharmony_ci if (startAVPlayback) { 150080922886Sopenharmony_ci return (*startAVPlayback)(bundleName, assetId); 150180922886Sopenharmony_ci } 150280922886Sopenharmony_ci SLOGE("StartAVPlayback fail"); 150380922886Sopenharmony_ci return AVSESSION_ERROR; 150480922886Sopenharmony_ci} 150580922886Sopenharmony_ci 150680922886Sopenharmony_cibool AVSessionService::IsAudioPlaybackAllowed(const int32_t uid, const int32_t pid) 150780922886Sopenharmony_ci{ 150880922886Sopenharmony_ci bool hasSession = GetContainer().UidHasSession(uid); 150980922886Sopenharmony_ci bool isBack = AppManagerAdapter::GetInstance().IsAppBackground(uid, pid); 151080922886Sopenharmony_ci bool isSystem = PermissionChecker::GetInstance().CheckSystemPermissionByUid(uid); 151180922886Sopenharmony_ci SLOGI("uid=%{public}d pid=%{public}d hasSession=%{public}d isBack=%{public}d isSystem=%{public}d", uid, 151280922886Sopenharmony_ci pid, hasSession, isBack, isSystem); 151380922886Sopenharmony_ci return hasSession || isSystem || !isBack; 151480922886Sopenharmony_ci} 151580922886Sopenharmony_ci 151680922886Sopenharmony_cisptr<AVControllerItem> AVSessionService::CreateNewControllerForSession(pid_t pid, sptr<AVSessionItem>& session) 151780922886Sopenharmony_ci{ 151880922886Sopenharmony_ci SLOGI("pid=%{public}d sessionId=%{public}s", pid, 151980922886Sopenharmony_ci AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str()); 152080922886Sopenharmony_ci sptr<AVControllerItem> result = new(std::nothrow) AVControllerItem(pid, session, session->GetUserId()); 152180922886Sopenharmony_ci if (result == nullptr) { 152280922886Sopenharmony_ci SLOGE("malloc controller failed"); 152380922886Sopenharmony_ci return nullptr; 152480922886Sopenharmony_ci } 152580922886Sopenharmony_ci result->SetServiceCallbackForRelease([this](AVControllerItem& controller) { HandleControllerRelease(controller); }); 152680922886Sopenharmony_ci session->AddController(pid, result); 152780922886Sopenharmony_ci if (AbilityHasSession(pid)) { 152880922886Sopenharmony_ci SLOGI("set isfromsession for pid %{public}d", static_cast<int>(pid)); 152980922886Sopenharmony_ci result->isFromSession_ = true; 153080922886Sopenharmony_ci } 153180922886Sopenharmony_ci return result; 153280922886Sopenharmony_ci} 153380922886Sopenharmony_ci 153480922886Sopenharmony_ci// LCOV_EXCL_START 153580922886Sopenharmony_ciconst nlohmann::json& AVSessionService::GetSubNode(const nlohmann::json& node, const std::string& name) 153680922886Sopenharmony_ci{ 153780922886Sopenharmony_ci static const nlohmann::json jsonNull = nlohmann::json::value_t::null; 153880922886Sopenharmony_ci if (node.is_discarded() || node.is_null()) { 153980922886Sopenharmony_ci SLOGE("json node is invalid"); 154080922886Sopenharmony_ci return jsonNull; 154180922886Sopenharmony_ci } 154280922886Sopenharmony_ci 154380922886Sopenharmony_ci if (name.empty()) { 154480922886Sopenharmony_ci SLOGE("name is invalid"); 154580922886Sopenharmony_ci return node; 154680922886Sopenharmony_ci } 154780922886Sopenharmony_ci 154880922886Sopenharmony_ci auto it = node.find(name); 154980922886Sopenharmony_ci if (it == node.end()) { 155080922886Sopenharmony_ci SLOGE("%{public}s is not exist in json", name.c_str()); 155180922886Sopenharmony_ci return jsonNull; 155280922886Sopenharmony_ci } 155380922886Sopenharmony_ci return *it; 155480922886Sopenharmony_ci} 155580922886Sopenharmony_ci// LCOV_EXCL_STOP 155680922886Sopenharmony_ci 155780922886Sopenharmony_cibool AVSessionService::IsHistoricalSession(const std::string& sessionId) 155880922886Sopenharmony_ci{ 155980922886Sopenharmony_ci { 156080922886Sopenharmony_ci std::string sortContent; 156180922886Sopenharmony_ci std::lock_guard sortFileLockGuard(sessionFileLock_); 156280922886Sopenharmony_ci if (!LoadStringFromFileEx(GetAVSortDir(), sortContent)) { 156380922886Sopenharmony_ci SLOGE("IsHistoricalSession read sort failed, filename=%{public}s", SORT_FILE_NAME); 156480922886Sopenharmony_ci return false; 156580922886Sopenharmony_ci } 156680922886Sopenharmony_ci if (sortContent.find(sessionId) == string::npos) { 156780922886Sopenharmony_ci SLOGE("IsHistoricalSession find session no sort, sessionId=%{public}s", 156880922886Sopenharmony_ci AVSessionUtils::GetAnonySessionId(sessionId).c_str()); 156980922886Sopenharmony_ci return false; 157080922886Sopenharmony_ci } 157180922886Sopenharmony_ci } 157280922886Sopenharmony_ci 157380922886Sopenharmony_ci auto session = GetContainer().GetSessionById(sessionId); 157480922886Sopenharmony_ci if (session != nullptr) { 157580922886Sopenharmony_ci SLOGE("IsHistoricalSession find session alive, sessionId=%{public}s", 157680922886Sopenharmony_ci AVSessionUtils::GetAnonySessionId(sessionId).c_str()); 157780922886Sopenharmony_ci return false; 157880922886Sopenharmony_ci } 157980922886Sopenharmony_ci SLOGE("IsHistoricalSession find session historical, sessionId=%{public}s", 158080922886Sopenharmony_ci AVSessionUtils::GetAnonySessionId(sessionId).c_str()); 158180922886Sopenharmony_ci return true; 158280922886Sopenharmony_ci} 158380922886Sopenharmony_ci 158480922886Sopenharmony_ciint32_t AVSessionService::StartDefaultAbilityByCall(std::string& sessionId) 158580922886Sopenharmony_ci{ 158680922886Sopenharmony_ci std::string bundleName = DEFAULT_BUNDLE_NAME; 158780922886Sopenharmony_ci std::string abilityName = DEFAULT_ABILITY_NAME; 158880922886Sopenharmony_ci std::string sortContent; 158980922886Sopenharmony_ci 159080922886Sopenharmony_ci { 159180922886Sopenharmony_ci std::lock_guard sortFileLockGuard(sessionFileLock_); 159280922886Sopenharmony_ci if (!LoadStringFromFileEx(GetAVSortDir(), sortContent)) { 159380922886Sopenharmony_ci SLOGE("GetAllSessionDescriptors read sort fail! "); 159480922886Sopenharmony_ci return AVSESSION_ERROR; 159580922886Sopenharmony_ci } 159680922886Sopenharmony_ci } 159780922886Sopenharmony_ci 159880922886Sopenharmony_ci if (!sortContent.empty()) { 159980922886Sopenharmony_ci nlohmann::json sortValues = json::parse(sortContent, nullptr, false); 160080922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(!sortValues.is_discarded(), AVSESSION_ERROR, "json object is null"); 160180922886Sopenharmony_ci for (auto& value : sortValues) { 160280922886Sopenharmony_ci auto session = GetContainer().GetSessionById(value["sessionId"]); 160380922886Sopenharmony_ci if (session == nullptr) { 160480922886Sopenharmony_ci bundleName = value["bundleName"]; 160580922886Sopenharmony_ci abilityName = value["abilityName"]; 160680922886Sopenharmony_ci break; 160780922886Sopenharmony_ci } else { 160880922886Sopenharmony_ci SLOGE("Default start alive %{public}s", AVSessionUtils::GetAnonySessionId(value["sessionId"]).c_str()); 160980922886Sopenharmony_ci return AVSESSION_ERROR; 161080922886Sopenharmony_ci } 161180922886Sopenharmony_ci } 161280922886Sopenharmony_ci } 161380922886Sopenharmony_ci 161480922886Sopenharmony_ci std::shared_ptr<AbilityManagerAdapter> ability = nullptr; 161580922886Sopenharmony_ci { 161680922886Sopenharmony_ci std::lock_guard lockGuard(abilityManagerLock_); 161780922886Sopenharmony_ci auto it = abilityManager_.find(bundleName + abilityName); 161880922886Sopenharmony_ci if (it != abilityManager_.end()) { 161980922886Sopenharmony_ci ability = it->second; 162080922886Sopenharmony_ci } else { 162180922886Sopenharmony_ci ability = std::make_shared<AbilityManagerAdapter>(bundleName, abilityName); 162280922886Sopenharmony_ci if (ability == nullptr) { 162380922886Sopenharmony_ci return ERR_NO_MEMORY; 162480922886Sopenharmony_ci } 162580922886Sopenharmony_ci abilityManager_[bundleName + abilityName] = ability; 162680922886Sopenharmony_ci } 162780922886Sopenharmony_ci } 162880922886Sopenharmony_ci if (ability == nullptr) { 162980922886Sopenharmony_ci return AVSESSION_ERROR; 163080922886Sopenharmony_ci } 163180922886Sopenharmony_ci int32_t ret = ability->StartAbilityByCall(sessionId); 163280922886Sopenharmony_ci if (ret != ERR_START_ABILITY_IS_RUNNING) { 163380922886Sopenharmony_ci abilityManager_.erase(bundleName + abilityName); 163480922886Sopenharmony_ci } 163580922886Sopenharmony_ci return ret; 163680922886Sopenharmony_ci} 163780922886Sopenharmony_ci 163880922886Sopenharmony_ciint32_t AVSessionService::StartAbilityByCall(const std::string& sessionIdNeeded, std::string& sessionId) 163980922886Sopenharmony_ci{ 164080922886Sopenharmony_ci std::string content; 164180922886Sopenharmony_ci 164280922886Sopenharmony_ci { 164380922886Sopenharmony_ci std::lock_guard sortFileLockGuard(sessionFileLock_); 164480922886Sopenharmony_ci if (!LoadStringFromFileEx(GetAVSortDir(), content)) { 164580922886Sopenharmony_ci SLOGE("LoadStringFromFile failed, filename=%{public}s", SORT_FILE_NAME); 164680922886Sopenharmony_ci return AVSESSION_ERROR; 164780922886Sopenharmony_ci } 164880922886Sopenharmony_ci } 164980922886Sopenharmony_ci 165080922886Sopenharmony_ci nlohmann::json values = json::parse(content, nullptr, false); 165180922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(!values.is_discarded(), AVSESSION_ERROR, "json object is null"); 165280922886Sopenharmony_ci std::string bundleName; 165380922886Sopenharmony_ci std::string abilityName; 165480922886Sopenharmony_ci for (auto& value : values) { 165580922886Sopenharmony_ci if (sessionIdNeeded == value["sessionId"]) { 165680922886Sopenharmony_ci bundleName = value["bundleName"]; 165780922886Sopenharmony_ci abilityName = value["abilityName"]; 165880922886Sopenharmony_ci break; 165980922886Sopenharmony_ci } 166080922886Sopenharmony_ci } 166180922886Sopenharmony_ci if (bundleName.empty() || abilityName.empty()) { 166280922886Sopenharmony_ci SLOGE("Get bundle name & ability name failed, sessionId=%{public}s", 166380922886Sopenharmony_ci AVSessionUtils::GetAnonySessionId(sessionIdNeeded).c_str()); 166480922886Sopenharmony_ci return AVSESSION_ERROR; 166580922886Sopenharmony_ci } 166680922886Sopenharmony_ci 166780922886Sopenharmony_ci std::shared_ptr<AbilityManagerAdapter> ability = nullptr; 166880922886Sopenharmony_ci { 166980922886Sopenharmony_ci std::lock_guard lockGuard(abilityManagerLock_); 167080922886Sopenharmony_ci auto it = abilityManager_.find(bundleName + abilityName); 167180922886Sopenharmony_ci if (it != abilityManager_.end()) { 167280922886Sopenharmony_ci ability = it->second; 167380922886Sopenharmony_ci } else { 167480922886Sopenharmony_ci ability = std::make_shared<AbilityManagerAdapter>(bundleName, abilityName); 167580922886Sopenharmony_ci if (ability == nullptr) { 167680922886Sopenharmony_ci return ERR_NO_MEMORY; 167780922886Sopenharmony_ci } 167880922886Sopenharmony_ci abilityManager_[bundleName + abilityName] = ability; 167980922886Sopenharmony_ci } 168080922886Sopenharmony_ci } 168180922886Sopenharmony_ci if (ability == nullptr) { 168280922886Sopenharmony_ci return AVSESSION_ERROR; 168380922886Sopenharmony_ci } 168480922886Sopenharmony_ci int32_t ret = ability->StartAbilityByCall(sessionId); 168580922886Sopenharmony_ci if (ret != ERR_START_ABILITY_IS_RUNNING) { 168680922886Sopenharmony_ci abilityManager_.erase(bundleName + abilityName); 168780922886Sopenharmony_ci } 168880922886Sopenharmony_ci return ret; 168980922886Sopenharmony_ci} 169080922886Sopenharmony_ci 169180922886Sopenharmony_ciint32_t AVSessionService::CreateControllerInner(const std::string& sessionId, sptr<IRemoteObject>& object) 169280922886Sopenharmony_ci{ 169380922886Sopenharmony_ci std::string sessionIdInner; 169480922886Sopenharmony_ci if (sessionId == "default") { 169580922886Sopenharmony_ci auto ret = StartDefaultAbilityByCall(sessionIdInner); 169680922886Sopenharmony_ci if (ret != AVSESSION_SUCCESS) { 169780922886Sopenharmony_ci SLOGE("StartDefaultAbilityByCall failed: %{public}d.", ret); 169880922886Sopenharmony_ci return ret; 169980922886Sopenharmony_ci } 170080922886Sopenharmony_ci } else { 170180922886Sopenharmony_ci if (IsHistoricalSession(sessionId)) { 170280922886Sopenharmony_ci auto ret = StartAbilityByCall(sessionId, sessionIdInner); 170380922886Sopenharmony_ci if (ret != AVSESSION_SUCCESS) { 170480922886Sopenharmony_ci SLOGE("StartAbilityByCall failed: %{public}d", ret); 170580922886Sopenharmony_ci return ret; 170680922886Sopenharmony_ci } 170780922886Sopenharmony_ci } else { 170880922886Sopenharmony_ci sessionIdInner = sessionId; 170980922886Sopenharmony_ci } 171080922886Sopenharmony_ci } 171180922886Sopenharmony_ci 171280922886Sopenharmony_ci auto pid = GetCallingPid(); 171380922886Sopenharmony_ci auto existController = GetPresentController(pid, sessionIdInner); 171480922886Sopenharmony_ci if (existController != nullptr) { 171580922886Sopenharmony_ci SLOGI("Controller is already existed."); 171680922886Sopenharmony_ci object = existController; 171780922886Sopenharmony_ci return ERR_CONTROLLER_IS_EXIST; 171880922886Sopenharmony_ci } 171980922886Sopenharmony_ci 172080922886Sopenharmony_ci sptr<AVSessionItem> session = GetContainer().GetSessionById(sessionIdInner); 172180922886Sopenharmony_ci if (session == nullptr) { 172280922886Sopenharmony_ci SLOGE("no session id %{public}s", AVSessionUtils::GetAnonySessionId(sessionIdInner).c_str()); 172380922886Sopenharmony_ci return ERR_SESSION_NOT_EXIST; 172480922886Sopenharmony_ci } 172580922886Sopenharmony_ci sptr<AVControllerItem> newController = CreateNewControllerForSession(pid, session); 172680922886Sopenharmony_ci if (newController == nullptr) { 172780922886Sopenharmony_ci SLOGE("Create new controller failed."); 172880922886Sopenharmony_ci return ERR_NO_MEMORY; 172980922886Sopenharmony_ci } 173080922886Sopenharmony_ci 173180922886Sopenharmony_ci std::lock_guard lockGuard(sessionServiceLock_); 173280922886Sopenharmony_ci controllers_[pid].push_back(newController); 173380922886Sopenharmony_ci object = newController; 173480922886Sopenharmony_ci 173580922886Sopenharmony_ci return AVSESSION_SUCCESS; 173680922886Sopenharmony_ci} 173780922886Sopenharmony_ci 173880922886Sopenharmony_civoid AVSessionService::AddSessionListener(pid_t pid, const sptr<ISessionListener>& listener) 173980922886Sopenharmony_ci{ 174080922886Sopenharmony_ci std::lock_guard lockGuard(sessionListenersLock_); 174180922886Sopenharmony_ci GetUsersManager().AddSessionListener(pid, listener); 174280922886Sopenharmony_ci} 174380922886Sopenharmony_ci 174480922886Sopenharmony_civoid AVSessionService::AddSessionListenerForAllUsers(pid_t pid, const sptr<ISessionListener>& listener) 174580922886Sopenharmony_ci{ 174680922886Sopenharmony_ci std::lock_guard lockGuard(sessionListenersLock_); 174780922886Sopenharmony_ci GetUsersManager().AddSessionListenerForAllUsers(pid, listener); 174880922886Sopenharmony_ci} 174980922886Sopenharmony_ci 175080922886Sopenharmony_civoid AVSessionService::RemoveSessionListener(pid_t pid) 175180922886Sopenharmony_ci{ 175280922886Sopenharmony_ci std::lock_guard lockGuard(sessionListenersLock_); 175380922886Sopenharmony_ci GetUsersManager().RemoveSessionListener(pid); 175480922886Sopenharmony_ci} 175580922886Sopenharmony_ci 175680922886Sopenharmony_ciint32_t AVSessionService::RegisterSessionListener(const sptr<ISessionListener>& listener) 175780922886Sopenharmony_ci{ 175880922886Sopenharmony_ci SLOGI("Enter RegisterSessionListener process and return current userId"); 175980922886Sopenharmony_ci AddSessionListener(GetCallingPid(), listener); 176080922886Sopenharmony_ci return GetUsersManager().GetCurrentUserId(); 176180922886Sopenharmony_ci} 176280922886Sopenharmony_ci 176380922886Sopenharmony_ciint32_t AVSessionService::RegisterSessionListenerForAllUsers(const sptr<ISessionListener>& listener) 176480922886Sopenharmony_ci{ 176580922886Sopenharmony_ci SLOGI("Enter RegisterSessionListenerForAllUsers process"); 176680922886Sopenharmony_ci AddSessionListenerForAllUsers(GetCallingPid(), listener); 176780922886Sopenharmony_ci return AVSESSION_SUCCESS; 176880922886Sopenharmony_ci} 176980922886Sopenharmony_ci 177080922886Sopenharmony_ci// LCOV_EXCL_START 177180922886Sopenharmony_civoid AVSessionService::HandleEventHandlerCallBack() 177280922886Sopenharmony_ci{ 177380922886Sopenharmony_ci SLOGI("handle eventHandler callback isFirstPress_=%{public}d, pressCount_:%{public}d", isFirstPress_, pressCount_); 177480922886Sopenharmony_ci AVControlCommand cmd; 177580922886Sopenharmony_ci bool shouldColdPlay = false; 177680922886Sopenharmony_ci { 177780922886Sopenharmony_ci std::lock_guard lockGuard(sessionServiceLock_); 177880922886Sopenharmony_ci if (pressCount_ >= THREE_CLICK) { 177980922886Sopenharmony_ci cmd.SetCommand(AVControlCommand::SESSION_CMD_PLAY_PREVIOUS); 178080922886Sopenharmony_ci } else if (pressCount_ == DOUBLE_CLICK) { 178180922886Sopenharmony_ci cmd.SetCommand(AVControlCommand::SESSION_CMD_PLAY_NEXT); 178280922886Sopenharmony_ci } else if (pressCount_ == ONE_CLICK) { 178380922886Sopenharmony_ci if (topSession_) { 178480922886Sopenharmony_ci auto playbackState = topSession_->GetPlaybackState(); 178580922886Sopenharmony_ci cmd.SetCommand(playbackState.GetState() == AVPlaybackState::PLAYBACK_STATE_PLAY ? 178680922886Sopenharmony_ci AVControlCommand::SESSION_CMD_PAUSE : AVControlCommand::SESSION_CMD_PLAY); 178780922886Sopenharmony_ci } else { 178880922886Sopenharmony_ci cmd.SetCommand(AVControlCommand::SESSION_CMD_PLAY); 178980922886Sopenharmony_ci } 179080922886Sopenharmony_ci } else { 179180922886Sopenharmony_ci pressCount_ = 0; 179280922886Sopenharmony_ci isFirstPress_ = true; 179380922886Sopenharmony_ci SLOGI("press invalid return, topSession alive:%{public}d", static_cast<int>(topSession_ != nullptr)); 179480922886Sopenharmony_ci return; 179580922886Sopenharmony_ci } 179680922886Sopenharmony_ci SLOGI("HandleEventHandlerCallBack proc cmd=%{public}d", cmd.GetCommand()); 179780922886Sopenharmony_ci if (!topSession_) { 179880922886Sopenharmony_ci shouldColdPlay = true; 179980922886Sopenharmony_ci SLOGI("HandleEventHandlerCallBack without topSession_ shouldColdStart=%{public}d", shouldColdPlay); 180080922886Sopenharmony_ci } else { 180180922886Sopenharmony_ci if (topSession_->GetDescriptor().sessionTag_ == "external_audio") { 180280922886Sopenharmony_ci SLOGI("HandleEventHandlerCallBack this is an external audio"); 180380922886Sopenharmony_ci } else { 180480922886Sopenharmony_ci topSession_->ExecuteControllerCommand(cmd); 180580922886Sopenharmony_ci } 180680922886Sopenharmony_ci } 180780922886Sopenharmony_ci } 180880922886Sopenharmony_ci if (shouldColdPlay) { 180980922886Sopenharmony_ci HandleSystemKeyColdStart(cmd); 181080922886Sopenharmony_ci } 181180922886Sopenharmony_ci pressCount_ = 0; 181280922886Sopenharmony_ci isFirstPress_ = true; 181380922886Sopenharmony_ci} 181480922886Sopenharmony_ci// LCOV_EXCL_STOP 181580922886Sopenharmony_ci 181680922886Sopenharmony_ciint32_t AVSessionService::SendSystemAVKeyEvent(const MMI::KeyEvent& keyEvent) 181780922886Sopenharmony_ci{ 181880922886Sopenharmony_ci SLOGI("SendSystemAVKeyEvent get key=%{public}d", keyEvent.GetKeyCode()); 181980922886Sopenharmony_ci if (keyEvent.GetKeyCode() == MMI::KeyEvent::KEYCODE_HEADSETHOOK) { 182080922886Sopenharmony_ci pressCount_++; 182180922886Sopenharmony_ci SLOGI("isFirstPress_=%{public}d", isFirstPress_); 182280922886Sopenharmony_ci if (isFirstPress_) { 182380922886Sopenharmony_ci auto ret = AVSessionEventHandler::GetInstance().AVSessionPostTask([this]() { 182480922886Sopenharmony_ci HandleEventHandlerCallBack(); 182580922886Sopenharmony_ci }, "SendSystemAVKeyEvent", CLICK_TIMEOUT); 182680922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret, AVSESSION_ERROR, "init eventHandler failed"); 182780922886Sopenharmony_ci isFirstPress_ = false; 182880922886Sopenharmony_ci } 182980922886Sopenharmony_ci return AVSESSION_SUCCESS; 183080922886Sopenharmony_ci } 183180922886Sopenharmony_ci { 183280922886Sopenharmony_ci std::lock_guard lockGuard(sessionServiceLock_); 183380922886Sopenharmony_ci if (topSession_) { 183480922886Sopenharmony_ci topSession_->HandleMediaKeyEvent(keyEvent); 183580922886Sopenharmony_ci return AVSESSION_SUCCESS; 183680922886Sopenharmony_ci } 183780922886Sopenharmony_ci } 183880922886Sopenharmony_ci { 183980922886Sopenharmony_ci int cmd = ConvertKeyCodeToCommand(keyEvent.GetKeyCode()); 184080922886Sopenharmony_ci AVControlCommand controlCommand; 184180922886Sopenharmony_ci controlCommand.SetCommand(cmd); 184280922886Sopenharmony_ci SLOGI("topSession get nullptr, check if cold start for cmd %{public}d", cmd); 184380922886Sopenharmony_ci HandleSystemKeyColdStart(controlCommand); 184480922886Sopenharmony_ci } 184580922886Sopenharmony_ci return AVSESSION_SUCCESS; 184680922886Sopenharmony_ci} 184780922886Sopenharmony_ci 184880922886Sopenharmony_ciint32_t AVSessionService::ConvertKeyCodeToCommand(int keyCode) 184980922886Sopenharmony_ci{ 185080922886Sopenharmony_ci auto iter = keyCodeToCommandMap_.find(keyCode); 185180922886Sopenharmony_ci if (iter != keyCodeToCommandMap_.end()) { 185280922886Sopenharmony_ci return iter->second; 185380922886Sopenharmony_ci } else { 185480922886Sopenharmony_ci return AVControlCommand::SESSION_CMD_PLAY; 185580922886Sopenharmony_ci } 185680922886Sopenharmony_ci} 185780922886Sopenharmony_ci 185880922886Sopenharmony_civoid AVSessionService::HandleSystemKeyColdStart(const AVControlCommand &command) 185980922886Sopenharmony_ci{ 186080922886Sopenharmony_ci SLOGI("HandleSystemKeyColdStart cmd=%{public}d without topsession", command.GetCommand()); 186180922886Sopenharmony_ci // try proc command for first front session 186280922886Sopenharmony_ci { 186380922886Sopenharmony_ci std::lock_guard frontLockGuard(sessionFrontLock_); 186480922886Sopenharmony_ci std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront(); 186580922886Sopenharmony_ci CHECK_AND_RETURN_LOG(sessionListForFront != nullptr, "sessionListForFront ptr nullptr!"); 186680922886Sopenharmony_ci for (const auto& session : *sessionListForFront) { 186780922886Sopenharmony_ci if (session->GetSessionType() != "voice_call" && session->GetSessionType() != "video_call") { 186880922886Sopenharmony_ci session->ExecuteControllerCommand(command); 186980922886Sopenharmony_ci SLOGI("ExecuteCommand %{public}d for front session: %{public}s", command.GetCommand(), 187080922886Sopenharmony_ci session->GetBundleName().c_str()); 187180922886Sopenharmony_ci return; 187280922886Sopenharmony_ci } 187380922886Sopenharmony_ci } 187480922886Sopenharmony_ci } 187580922886Sopenharmony_ci 187680922886Sopenharmony_ci std::vector<AVSessionDescriptor> hisDescriptors; 187780922886Sopenharmony_ci GetHistoricalSessionDescriptorsFromFile(hisDescriptors); 187880922886Sopenharmony_ci // try start play for first history session 187980922886Sopenharmony_ci if (command.GetCommand() == AVControlCommand::SESSION_CMD_PLAY && hisDescriptors.size() != 0) { 188080922886Sopenharmony_ci sptr<IRemoteObject> object; 188180922886Sopenharmony_ci int32_t ret = CreateControllerInner(hisDescriptors[0].sessionId_, object); 188280922886Sopenharmony_ci SLOGI("Cold play %{public}s, ret=%{public}d", hisDescriptors[0].elementName_.GetBundleName().c_str(), ret); 188380922886Sopenharmony_ci } else { 188480922886Sopenharmony_ci SLOGI("Cold start command=%{public}d, hisDescriptorsSize=%{public}d return", command.GetCommand(), 188580922886Sopenharmony_ci static_cast<int>(hisDescriptors.size())); 188680922886Sopenharmony_ci } 188780922886Sopenharmony_ci} 188880922886Sopenharmony_ci 188980922886Sopenharmony_ciint32_t AVSessionService::SendSystemControlCommand(const AVControlCommand &command) 189080922886Sopenharmony_ci{ 189180922886Sopenharmony_ci { 189280922886Sopenharmony_ci std::lock_guard lockGuard(sessionServiceLock_); 189380922886Sopenharmony_ci SLOGI("SendSystemControlCommand with cmd:%{public}d, topSession alive:%{public}d", 189480922886Sopenharmony_ci command.GetCommand(), static_cast<int>(topSession_ != nullptr)); 189580922886Sopenharmony_ci if (topSession_) { 189680922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(CommandSendLimit::GetInstance().IsCommandSendEnable(GetCallingPid()), 189780922886Sopenharmony_ci ERR_COMMAND_SEND_EXCEED_MAX, "command excuted number exceed max"); 189880922886Sopenharmony_ci topSession_->ExecuteControllerCommand(command); 189980922886Sopenharmony_ci return AVSESSION_SUCCESS; 190080922886Sopenharmony_ci } 190180922886Sopenharmony_ci } 190280922886Sopenharmony_ci HandleSystemKeyColdStart(command); 190380922886Sopenharmony_ci return AVSESSION_SUCCESS; 190480922886Sopenharmony_ci} 190580922886Sopenharmony_ci 190680922886Sopenharmony_civoid AVSessionService::AddClientDeathObserver(pid_t pid, const sptr<IClientDeath>& observer, 190780922886Sopenharmony_ci const sptr<ClientDeathRecipient> recipient) 190880922886Sopenharmony_ci{ 190980922886Sopenharmony_ci std::lock_guard lockGuard(clientDeathLock_); 191080922886Sopenharmony_ci clientDeathObservers_[pid] = observer; 191180922886Sopenharmony_ci clientDeathRecipients_[pid] = recipient; 191280922886Sopenharmony_ci} 191380922886Sopenharmony_ci 191480922886Sopenharmony_civoid AVSessionService::RemoveClientDeathObserver(pid_t pid) 191580922886Sopenharmony_ci{ 191680922886Sopenharmony_ci std::lock_guard lockGuard(clientDeathLock_); 191780922886Sopenharmony_ci if (clientDeathObservers_.empty()) { 191880922886Sopenharmony_ci SLOGE("try remove observer with empty list"); 191980922886Sopenharmony_ci } else { 192080922886Sopenharmony_ci clientDeathObservers_.erase(pid); 192180922886Sopenharmony_ci } 192280922886Sopenharmony_ci 192380922886Sopenharmony_ci if (clientDeathRecipients_.empty()) { 192480922886Sopenharmony_ci SLOGE("try remove recipient with empty list"); 192580922886Sopenharmony_ci } else { 192680922886Sopenharmony_ci clientDeathRecipients_.erase(pid); 192780922886Sopenharmony_ci } 192880922886Sopenharmony_ci} 192980922886Sopenharmony_ci 193080922886Sopenharmony_ciint32_t AVSessionService::RegisterClientDeathObserver(const sptr<IClientDeath>& observer) 193180922886Sopenharmony_ci{ 193280922886Sopenharmony_ci SLOGI("enter ClientDeathObserver register with recipient point"); 193380922886Sopenharmony_ci auto pid = GetCallingPid(); 193480922886Sopenharmony_ci sptr<ClientDeathRecipient> recipient = 193580922886Sopenharmony_ci new(std::nothrow) ClientDeathRecipient([this, pid]() { OnClientDied(pid); }); 193680922886Sopenharmony_ci if (recipient == nullptr) { 193780922886Sopenharmony_ci SLOGE("New ClientDeathRecipient failed."); 193880922886Sopenharmony_ci HISYSEVENT_FAULT("CONTROL_COMMAND_FAILED", "ERROR_TYPE", "RGS_CLIENT_DEATH_OBSERVER_FAILED", 193980922886Sopenharmony_ci "ERROR_INFO", "avsession service register client death observer malloc failed"); 194080922886Sopenharmony_ci return AVSESSION_ERROR; 194180922886Sopenharmony_ci } 194280922886Sopenharmony_ci 194380922886Sopenharmony_ci if (!observer->AsObject()->AddDeathRecipient(recipient)) { 194480922886Sopenharmony_ci SLOGE("add death recipient failed for %{public}d failed", pid); 194580922886Sopenharmony_ci HISYSEVENT_FAULT("CONTROL_COMMAND_FAILED", "ERROR_TYPE", "RGS_CLIENT_DEATH_FAILED", "CALLING_PID", pid, 194680922886Sopenharmony_ci "ERROR_INFO", "avsession service register client death observer, add death recipient failed"); 194780922886Sopenharmony_ci return AVSESSION_ERROR; 194880922886Sopenharmony_ci } 194980922886Sopenharmony_ci 195080922886Sopenharmony_ci AddClientDeathObserver(pid, observer, recipient); 195180922886Sopenharmony_ci return AVSESSION_SUCCESS; 195280922886Sopenharmony_ci} 195380922886Sopenharmony_ci 195480922886Sopenharmony_civoid AVSessionService::ClearClientResources(pid_t pid) 195580922886Sopenharmony_ci{ 195680922886Sopenharmony_ci RemoveSessionListener(pid); 195780922886Sopenharmony_ci { 195880922886Sopenharmony_ci std::lock_guard lockGuard(sessionServiceLock_); 195980922886Sopenharmony_ci ClearSessionForClientDiedNoLock(pid); 196080922886Sopenharmony_ci ClearControllerForClientDiedNoLock(pid); 196180922886Sopenharmony_ci } 196280922886Sopenharmony_ci RemoveClientDeathObserver(pid); 196380922886Sopenharmony_ci} 196480922886Sopenharmony_ci 196580922886Sopenharmony_ciint32_t AVSessionService::Close(void) 196680922886Sopenharmony_ci{ 196780922886Sopenharmony_ci auto pid = GetCallingPid(); 196880922886Sopenharmony_ci ClearClientResources(pid); 196980922886Sopenharmony_ci return AVSESSION_SUCCESS; 197080922886Sopenharmony_ci} 197180922886Sopenharmony_ci 197280922886Sopenharmony_civoid AVSessionService::OnClientDied(pid_t pid) 197380922886Sopenharmony_ci{ 197480922886Sopenharmony_ci ClearClientResources(pid); 197580922886Sopenharmony_ci} 197680922886Sopenharmony_ci 197780922886Sopenharmony_ci// LCOV_EXCL_START 197880922886Sopenharmony_civoid AVSessionService::DeleteHistoricalRecord(const std::string& bundleName, int32_t userId) 197980922886Sopenharmony_ci{ 198080922886Sopenharmony_ci std::lock_guard sortFileLockGuard(sessionFileLock_); 198180922886Sopenharmony_ci if (userId <= 0) { 198280922886Sopenharmony_ci userId = GetUsersManager().GetCurrentUserId(); 198380922886Sopenharmony_ci } 198480922886Sopenharmony_ci if (!CheckUserDirValid(userId)) { 198580922886Sopenharmony_ci SLOGE("DeleteHistoricalRecord target user:%{public}d not valid, return", userId); 198680922886Sopenharmony_ci return; 198780922886Sopenharmony_ci } 198880922886Sopenharmony_ci SLOGI("delete historical record, bundleName=%{public}s, userId=%{public}d", bundleName.c_str(), userId); 198980922886Sopenharmony_ci std::string oldContent; 199080922886Sopenharmony_ci std::string newContent; 199180922886Sopenharmony_ci nlohmann::json values; 199280922886Sopenharmony_ci if (!LoadStringFromFileEx(GetAVSortDir(userId), oldContent)) { 199380922886Sopenharmony_ci SLOGE("LoadStringFromFile failed, filename=%{public}s", SORT_FILE_NAME); 199480922886Sopenharmony_ci return; 199580922886Sopenharmony_ci } 199680922886Sopenharmony_ci values = json::parse(oldContent, nullptr, false); 199780922886Sopenharmony_ci CHECK_AND_RETURN_LOG(!values.is_discarded(), "json object is null"); 199880922886Sopenharmony_ci for (auto value : values) { 199980922886Sopenharmony_ci if (bundleName == value["bundleName"]) { 200080922886Sopenharmony_ci values.erase(std::remove(values.begin(), values.end(), value)); 200180922886Sopenharmony_ci break; 200280922886Sopenharmony_ci } 200380922886Sopenharmony_ci } 200480922886Sopenharmony_ci newContent = values.dump(); 200580922886Sopenharmony_ci SLOGD("DeleteHistoricalRecord::Dump json object finished"); 200680922886Sopenharmony_ci if (!SaveStringToFileEx(GetAVSortDir(userId), newContent)) { 200780922886Sopenharmony_ci SLOGE("SaveStringToFile failed, filename=%{public}s", SORT_FILE_NAME); 200880922886Sopenharmony_ci return; 200980922886Sopenharmony_ci } 201080922886Sopenharmony_ci} 201180922886Sopenharmony_ci// LCOV_EXCL_STOP 201280922886Sopenharmony_ci 201380922886Sopenharmony_ci// LCOV_EXCL_START 201480922886Sopenharmony_civoid AVSessionService::DeleteAVQueueInfoRecord(const std::string& bundleName, int32_t userId) 201580922886Sopenharmony_ci{ 201680922886Sopenharmony_ci std::lock_guard avQueueFileLockGuard(avQueueFileLock_); 201780922886Sopenharmony_ci if (userId <= 0) { 201880922886Sopenharmony_ci userId = GetUsersManager().GetCurrentUserId(); 201980922886Sopenharmony_ci } 202080922886Sopenharmony_ci if (!CheckUserDirValid(userId)) { 202180922886Sopenharmony_ci SLOGE("DeleteAVQueueInfoRecord target user:%{public}d not valid, return", userId); 202280922886Sopenharmony_ci return; 202380922886Sopenharmony_ci } 202480922886Sopenharmony_ci SLOGI("DeleteAVQueueInfoRecord, bundleName=%{public}s, userId=%{public}d", bundleName.c_str(), userId); 202580922886Sopenharmony_ci std::string oldContent; 202680922886Sopenharmony_ci std::string newContent; 202780922886Sopenharmony_ci nlohmann::json values; 202880922886Sopenharmony_ci if (!LoadStringFromFileEx(GetAVQueueDir(userId), oldContent)) { 202980922886Sopenharmony_ci SLOGE("LoadStringFromFile failed, filename=%{public}s", AVQUEUE_FILE_NAME); 203080922886Sopenharmony_ci return; 203180922886Sopenharmony_ci } 203280922886Sopenharmony_ci values = json::parse(oldContent, nullptr, false); 203380922886Sopenharmony_ci CHECK_AND_RETURN_LOG(!values.is_discarded(), "json object is null"); 203480922886Sopenharmony_ci for (auto it = values.begin(); it != values.end();) { 203580922886Sopenharmony_ci if (it->at("bundleName") == bundleName) { 203680922886Sopenharmony_ci std::string avQueueId = it->at("avQueueId"); 203780922886Sopenharmony_ci std::string fileName = AVSessionUtils::GetFixedPathName(userId) + bundleName + "_" + 203880922886Sopenharmony_ci avQueueId + AVSessionUtils::GetFileSuffix(); 203980922886Sopenharmony_ci AVSessionUtils::DeleteFile(fileName); 204080922886Sopenharmony_ci values.erase(it); 204180922886Sopenharmony_ci } else { 204280922886Sopenharmony_ci ++it; 204380922886Sopenharmony_ci } 204480922886Sopenharmony_ci } 204580922886Sopenharmony_ci newContent = values.dump(); 204680922886Sopenharmony_ci SLOGD("DeleteAVQueueInfoRecord::Dump json object finished"); 204780922886Sopenharmony_ci if (!SaveStringToFileEx(GetAVQueueDir(userId), newContent)) { 204880922886Sopenharmony_ci SLOGE("SaveStringToFile failed, filename=%{public}s", AVQUEUE_FILE_NAME); 204980922886Sopenharmony_ci return; 205080922886Sopenharmony_ci } 205180922886Sopenharmony_ci} 205280922886Sopenharmony_ci// LCOV_EXCL_STOP 205380922886Sopenharmony_ci 205480922886Sopenharmony_civoid AVSessionService::HandleSessionRelease(std::string sessionId) 205580922886Sopenharmony_ci{ 205680922886Sopenharmony_ci SLOGI("HandleSessionRelease, sessionId=%{public}s", AVSessionUtils::GetAnonySessionId(sessionId).c_str()); 205780922886Sopenharmony_ci std::lock_guard lockGuard(sessionServiceLock_); 205880922886Sopenharmony_ci std::lock_guard frontLockGuard(sessionFrontLock_); 205980922886Sopenharmony_ci sptr<AVSessionItem> sessionItem = GetUsersManager().GetContainerFromAll().GetSessionById(sessionId); 206080922886Sopenharmony_ci CHECK_AND_RETURN_LOG(sessionItem != nullptr, "Session item is nullptr"); 206180922886Sopenharmony_ci NotifySessionRelease(sessionItem->GetDescriptor()); 206280922886Sopenharmony_ci sessionItem->DestroyTask(); 206380922886Sopenharmony_ci if (topSession_.GetRefPtr() == sessionItem.GetRefPtr()) { 206480922886Sopenharmony_ci UpdateTopSession(nullptr); 206580922886Sopenharmony_ci int32_t ret = Notification::NotificationHelper::CancelNotification(0); 206680922886Sopenharmony_ci SLOGI("topsession release cancelNotification ret=%{public}d", ret); 206780922886Sopenharmony_ci } 206880922886Sopenharmony_ci if (sessionItem->GetRemoteSource() != nullptr) { 206980922886Sopenharmony_ci int32_t ret = CancelCastAudioForClientExit(sessionItem->GetPid(), sessionItem); 207080922886Sopenharmony_ci SLOGI("CancelCastAudioForClientExit ret is %{public}d", ret); 207180922886Sopenharmony_ci } 207280922886Sopenharmony_ci HISYSEVENT_ADD_LIFE_CYCLE_INFO(sessionItem->GetDescriptor().elementName_.GetBundleName(), 207380922886Sopenharmony_ci AppManagerAdapter::GetInstance().IsAppBackground(GetCallingUid(), GetCallingPid()), 207480922886Sopenharmony_ci sessionItem->GetDescriptor().sessionType_, false); 207580922886Sopenharmony_ci GetUsersManager().RemoveSessionForAllUser(sessionItem->GetPid(), sessionItem->GetAbilityName()); 207680922886Sopenharmony_ci UpdateFrontSession(sessionItem, false); 207780922886Sopenharmony_ci#ifdef CASTPLUS_CAST_ENGINE_ENABLE 207880922886Sopenharmony_ci if ((GetUsersManager().GetContainerFromAll().GetAllSessions().size() == 0 || 207980922886Sopenharmony_ci (GetUsersManager().GetContainerFromAll().GetAllSessions().size() == 1 && 208080922886Sopenharmony_ci CheckAncoAudio())) && !is2in1_) { 208180922886Sopenharmony_ci SLOGI("call disable cast for no session alive"); 208280922886Sopenharmony_ci checkEnableCast(false); 208380922886Sopenharmony_ci } 208480922886Sopenharmony_ci#endif 208580922886Sopenharmony_ci} 208680922886Sopenharmony_ci 208780922886Sopenharmony_civoid AVSessionService::HandleControllerRelease(AVControllerItem& controller) 208880922886Sopenharmony_ci{ 208980922886Sopenharmony_ci auto pid = controller.GetPid(); 209080922886Sopenharmony_ci std::lock_guard lockGuard(sessionServiceLock_); 209180922886Sopenharmony_ci auto it = controllers_.find(pid); 209280922886Sopenharmony_ci if (it == controllers_.end()) { 209380922886Sopenharmony_ci return; 209480922886Sopenharmony_ci } 209580922886Sopenharmony_ci it->second.remove(&controller); 209680922886Sopenharmony_ci if (it->second.empty()) { 209780922886Sopenharmony_ci controllers_.erase(pid); 209880922886Sopenharmony_ci } 209980922886Sopenharmony_ci} 210080922886Sopenharmony_ci 210180922886Sopenharmony_cistd::int32_t AVSessionService::Dump(std::int32_t fd, const std::vector<std::u16string>& args) 210280922886Sopenharmony_ci{ 210380922886Sopenharmony_ci if (fd < 0) { 210480922886Sopenharmony_ci SLOGE("dump fd invalid"); 210580922886Sopenharmony_ci return ERR_INVALID_PARAM; 210680922886Sopenharmony_ci } 210780922886Sopenharmony_ci 210880922886Sopenharmony_ci if (dumpHelper_ == nullptr) { 210980922886Sopenharmony_ci SLOGE("dumpHelper_ is nullptr!"); 211080922886Sopenharmony_ci return ERR_INVALID_PARAM; 211180922886Sopenharmony_ci } 211280922886Sopenharmony_ci 211380922886Sopenharmony_ci std::vector<std::string> argsInStr; 211480922886Sopenharmony_ci for (const auto& arg : args) { 211580922886Sopenharmony_ci SLOGI("Dump args: %s", Str16ToStr8(arg).c_str()); 211680922886Sopenharmony_ci argsInStr.emplace_back(Str16ToStr8(arg)); 211780922886Sopenharmony_ci } 211880922886Sopenharmony_ci 211980922886Sopenharmony_ci std::string result; 212080922886Sopenharmony_ci dumpHelper_->Dump(argsInStr, result, *this); 212180922886Sopenharmony_ci std::int32_t ret = dprintf(fd, "%s", result.c_str()); 212280922886Sopenharmony_ci if (ret < 0) { 212380922886Sopenharmony_ci SLOGI("dprintf to dump fd failed"); 212480922886Sopenharmony_ci return ERR_INVALID_PARAM; 212580922886Sopenharmony_ci } 212680922886Sopenharmony_ci return AVSESSION_SUCCESS; 212780922886Sopenharmony_ci} 212880922886Sopenharmony_ci 212980922886Sopenharmony_ci__attribute__((no_sanitize("cfi"))) std::shared_ptr<RemoteSessionCommandProcess> AVSessionService::GetService( 213080922886Sopenharmony_ci const std::string& deviceId) 213180922886Sopenharmony_ci{ 213280922886Sopenharmony_ci SLOGI("Enter GetService."); 213380922886Sopenharmony_ci auto mgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); 213480922886Sopenharmony_ci if (mgr == nullptr) { 213580922886Sopenharmony_ci SLOGE("GetService failed when GetSystemAbilityManager."); 213680922886Sopenharmony_ci return nullptr; 213780922886Sopenharmony_ci } 213880922886Sopenharmony_ci auto object = mgr->GetSystemAbility(AVSESSION_SERVICE_ID, deviceId); 213980922886Sopenharmony_ci if (object == nullptr) { 214080922886Sopenharmony_ci SLOGE("GetService failed to get AVSESSION_SERVICE_ID object."); 214180922886Sopenharmony_ci return nullptr; 214280922886Sopenharmony_ci } 214380922886Sopenharmony_ci std::shared_ptr<RemoteSessionCommandProcess> remoteService = std::make_shared<RemoteSessionCommandProcess>(object); 214480922886Sopenharmony_ci return remoteService; 214580922886Sopenharmony_ci} 214680922886Sopenharmony_ci 214780922886Sopenharmony_cibool AVSessionService::IsLocalDevice(const std::string& networkId) 214880922886Sopenharmony_ci{ 214980922886Sopenharmony_ci std::string localNetworkId; 215080922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(GetLocalNetworkId(localNetworkId) == AVSESSION_SUCCESS, AVSESSION_ERROR, 215180922886Sopenharmony_ci "GetLocalNetworkId error"); 215280922886Sopenharmony_ci if (networkId == localNetworkId || networkId == "LocalDevice") { 215380922886Sopenharmony_ci SLOGI("This networkId is local device."); 215480922886Sopenharmony_ci return true; 215580922886Sopenharmony_ci } 215680922886Sopenharmony_ci SLOGI("This networkId is not local device."); 215780922886Sopenharmony_ci return false; 215880922886Sopenharmony_ci} 215980922886Sopenharmony_ci 216080922886Sopenharmony_ciint32_t AVSessionService::GetLocalNetworkId(std::string& networkId) 216180922886Sopenharmony_ci{ 216280922886Sopenharmony_ci DistributedHardware::DmDeviceInfo deviceInfo; 216380922886Sopenharmony_ci int32_t ret = DistributedHardware::DeviceManager::GetInstance().GetLocalDeviceInfo("av_session", deviceInfo); 216480922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == 0, ret, "get local deviceInfo failed"); 216580922886Sopenharmony_ci networkId = deviceInfo.networkId; 216680922886Sopenharmony_ci return AVSESSION_SUCCESS; 216780922886Sopenharmony_ci} 216880922886Sopenharmony_ci 216980922886Sopenharmony_ciint32_t AVSessionService::GetTrustedDeviceName(const std::string& networkId, std::string& deviceName) 217080922886Sopenharmony_ci{ 217180922886Sopenharmony_ci std::vector<OHOS::DistributedHardware::DmDeviceInfo> deviceList {}; 217280922886Sopenharmony_ci if (IsLocalDevice(networkId)) { 217380922886Sopenharmony_ci deviceName = "LocalDevice"; 217480922886Sopenharmony_ci return AVSESSION_SUCCESS; 217580922886Sopenharmony_ci } 217680922886Sopenharmony_ci int32_t ret = GetTrustedDevicesInfo(deviceList); 217780922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "get devicesInfo failed"); 217880922886Sopenharmony_ci for (const auto& device : deviceList) { 217980922886Sopenharmony_ci ret = strcmp(device.networkId, networkId.c_str()); 218080922886Sopenharmony_ci if (ret == 0) { 218180922886Sopenharmony_ci deviceName = device.deviceName; 218280922886Sopenharmony_ci return AVSESSION_SUCCESS; 218380922886Sopenharmony_ci } 218480922886Sopenharmony_ci } 218580922886Sopenharmony_ci SLOGI("GetTrustedDeviceName is not find this device %{public}.6s", networkId.c_str()); 218680922886Sopenharmony_ci return AVSESSION_ERROR; 218780922886Sopenharmony_ci} 218880922886Sopenharmony_ci 218980922886Sopenharmony_ciint32_t AVSessionService::GetTrustedDevicesInfo(std::vector<OHOS::DistributedHardware::DmDeviceInfo>& deviceList) 219080922886Sopenharmony_ci{ 219180922886Sopenharmony_ci int32_t ret = DistributedHardware::DeviceManager::GetInstance().GetTrustedDeviceList("av_session", "", deviceList); 219280922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == 0, ret, "get trusted device list failed"); 219380922886Sopenharmony_ci return AVSESSION_SUCCESS; 219480922886Sopenharmony_ci} 219580922886Sopenharmony_ci 219680922886Sopenharmony_ciint32_t AVSessionService::SetBasicInfo(std::string& sessionInfo) 219780922886Sopenharmony_ci{ 219880922886Sopenharmony_ci AVSessionBasicInfo basicInfo; 219980922886Sopenharmony_ci basicInfo.metaDataCap_ = AVMetaData::localCapability; 220080922886Sopenharmony_ci basicInfo.playBackStateCap_ = AVPlaybackState::localCapability; 220180922886Sopenharmony_ci basicInfo.controlCommandCap_ = AVControlCommand::localCapability; 220280922886Sopenharmony_ci int32_t ret = GetLocalNetworkId(basicInfo.networkId_); 220380922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, AVSESSION_ERROR, "GetLocalNetworkId failed"); 220480922886Sopenharmony_ci 220580922886Sopenharmony_ci ret = JsonUtils::SetSessionBasicInfo(sessionInfo, basicInfo); 220680922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, AVSESSION_ERROR, "SetDeviceId failed"); 220780922886Sopenharmony_ci return AVSESSION_SUCCESS; 220880922886Sopenharmony_ci} 220980922886Sopenharmony_ci 221080922886Sopenharmony_civoid AVSessionService::SetDeviceInfo(const std::vector<AudioStandard::AudioDeviceDescriptor>& castAudioDescriptors, 221180922886Sopenharmony_ci sptr <AVSessionItem>& session) 221280922886Sopenharmony_ci{ 221380922886Sopenharmony_ci CHECK_AND_RETURN_LOG(session != nullptr && castAudioDescriptors.size() > 0, "invalid argument"); 221480922886Sopenharmony_ci 221580922886Sopenharmony_ci OutputDeviceInfo outputDeviceInfo; 221680922886Sopenharmony_ci outputDeviceInfo.deviceInfos_.clear(); 221780922886Sopenharmony_ci int32_t castCategory = AVCastCategory::CATEGORY_LOCAL; 221880922886Sopenharmony_ci if (!IsLocalDevice(castAudioDescriptors[0].networkId_)) { 221980922886Sopenharmony_ci castCategory = AVCastCategory::CATEGORY_REMOTE; 222080922886Sopenharmony_ci } 222180922886Sopenharmony_ci for (const auto &audioDescriptor : castAudioDescriptors) { 222280922886Sopenharmony_ci DeviceInfo deviceInfo; 222380922886Sopenharmony_ci deviceInfo.castCategory_ = castCategory; 222480922886Sopenharmony_ci deviceInfo.deviceId_ = std::to_string(audioDescriptor.deviceId_); 222580922886Sopenharmony_ci deviceInfo.deviceName_ = audioDescriptor.deviceName_; 222680922886Sopenharmony_ci SLOGI("SetDeviceInfo the deviceName is %{public}s", audioDescriptor.deviceName_.c_str()); 222780922886Sopenharmony_ci outputDeviceInfo.deviceInfos_.emplace_back(deviceInfo); 222880922886Sopenharmony_ci } 222980922886Sopenharmony_ci session->SetOutputDevice(outputDeviceInfo); 223080922886Sopenharmony_ci} 223180922886Sopenharmony_ci 223280922886Sopenharmony_cibool AVSessionService::GetAudioDescriptorByDeviceId(const std::vector<sptr<AudioStandard::AudioDeviceDescriptor>>& 223380922886Sopenharmony_ci descriptors, const std::string& deviceId, 223480922886Sopenharmony_ci AudioStandard::AudioDeviceDescriptor& audioDescriptor) 223580922886Sopenharmony_ci{ 223680922886Sopenharmony_ci for (const auto& descriptor : descriptors) { 223780922886Sopenharmony_ci if (std::to_string(descriptor->deviceId_) == deviceId) { 223880922886Sopenharmony_ci audioDescriptor = *descriptor; 223980922886Sopenharmony_ci return true; 224080922886Sopenharmony_ci } 224180922886Sopenharmony_ci } 224280922886Sopenharmony_ci SLOGI("GetAudioDescriptorByDeviceId deviceId:%{public}s is not found in all audio descriptors", deviceId.c_str()); 224380922886Sopenharmony_ci return false; 224480922886Sopenharmony_ci} 224580922886Sopenharmony_ci 224680922886Sopenharmony_civoid AVSessionService::GetDeviceInfo(const sptr <AVSessionItem>& session, 224780922886Sopenharmony_ci const std::vector<AudioStandard::AudioDeviceDescriptor>& descriptors, 224880922886Sopenharmony_ci std::vector<AudioStandard::AudioDeviceDescriptor>& castSinkDescriptors, 224980922886Sopenharmony_ci std::vector<AudioStandard::AudioDeviceDescriptor>& cancelSinkDescriptors) 225080922886Sopenharmony_ci{ 225180922886Sopenharmony_ci if (descriptors.size() != 1) { 225280922886Sopenharmony_ci SLOGI("descriptor size is %{public}d, not support", static_cast<int32_t>(descriptors.size())); 225380922886Sopenharmony_ci return; 225480922886Sopenharmony_ci } 225580922886Sopenharmony_ci castSinkDescriptors.push_back(descriptors[0]); 225680922886Sopenharmony_ci OutputDeviceInfo tempOutputDeviceInfo; 225780922886Sopenharmony_ci session->GetOutputDevice(tempOutputDeviceInfo); 225880922886Sopenharmony_ci // If not in remote, return directly 225980922886Sopenharmony_ci if (tempOutputDeviceInfo.deviceInfos_.size() == 0 || tempOutputDeviceInfo.deviceInfos_[0].castCategory_ == 1) { 226080922886Sopenharmony_ci SLOGI("castCategory is %{public}d, no need to cancel", tempOutputDeviceInfo.deviceInfos_[0].castCategory_); 226180922886Sopenharmony_ci return; 226280922886Sopenharmony_ci } 226380922886Sopenharmony_ci int32_t ret = GetAudioDescriptor(session->GetDescriptor().outputDeviceInfo_.deviceInfos_[0].deviceId_, 226480922886Sopenharmony_ci cancelSinkDescriptors); 226580922886Sopenharmony_ci CHECK_AND_RETURN_LOG(ret == AVSESSION_SUCCESS, "get cancelSinkDescriptors failed"); 226680922886Sopenharmony_ci} 226780922886Sopenharmony_ci 226880922886Sopenharmony_ciint32_t AVSessionService::SelectOutputDevice(const int32_t uid, const AudioDeviceDescriptor& descriptor) 226980922886Sopenharmony_ci{ 227080922886Sopenharmony_ci sptr <AudioStandard::AudioRendererFilter> audioFilter = new(std::nothrow) AudioRendererFilter(); 227180922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(audioFilter != nullptr, ERR_NO_MEMORY, "new AudioRendererFilter failed"); 227280922886Sopenharmony_ci audioFilter->uid = uid; 227380922886Sopenharmony_ci audioFilter->rendererInfo.contentType = ContentType::CONTENT_TYPE_MUSIC; 227480922886Sopenharmony_ci audioFilter->rendererInfo.streamUsage = StreamUsage::STREAM_USAGE_MEDIA; 227580922886Sopenharmony_ci 227680922886Sopenharmony_ci std::vector<sptr<AudioDeviceDescriptor>> audioDescriptor; 227780922886Sopenharmony_ci auto audioDeviceDescriptor = new(std::nothrow) AudioDeviceDescriptor(descriptor); 227880922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(audioDeviceDescriptor != nullptr, ERR_NO_MEMORY, "audioDeviceDescriptor is nullptr"); 227980922886Sopenharmony_ci audioDescriptor.push_back(audioDeviceDescriptor); 228080922886Sopenharmony_ci SLOGI("select the device %{public}s role is %{public}d, networkId is %{public}.6s", 228180922886Sopenharmony_ci descriptor.deviceName_.c_str(), static_cast<int32_t>(descriptor.deviceRole_), descriptor.networkId_.c_str()); 228280922886Sopenharmony_ci 228380922886Sopenharmony_ci AudioSystemManager *audioSystemMgr = AudioSystemManager::GetInstance(); 228480922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(audioSystemMgr != nullptr, AVSESSION_ERROR, "get AudioSystemManager instance failed"); 228580922886Sopenharmony_ci int32_t ret = audioSystemMgr->SelectOutputDevice(audioFilter, audioDescriptor); 228680922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, AVSESSION_ERROR, "SelectOutputDevice failed"); 228780922886Sopenharmony_ci 228880922886Sopenharmony_ci return AVSESSION_SUCCESS; 228980922886Sopenharmony_ci} 229080922886Sopenharmony_ci 229180922886Sopenharmony_ciint32_t AVSessionService::CastAudio(const SessionToken& token, 229280922886Sopenharmony_ci const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkAudioDescriptors) 229380922886Sopenharmony_ci{ 229480922886Sopenharmony_ci std::string sourceSessionInfo; 229580922886Sopenharmony_ci int32_t ret = SetBasicInfo(sourceSessionInfo); 229680922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetBasicInfo failed"); 229780922886Sopenharmony_ci sptr<AVSessionItem> session = GetContainer().GetSessionById(token.sessionId); 229880922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(session != nullptr, ERR_SESSION_NOT_EXIST, "session %{public}s not exist", 229980922886Sopenharmony_ci AVSessionUtils::GetAnonySessionId(token.sessionId).c_str()); 230080922886Sopenharmony_ci ret = JsonUtils::SetSessionDescriptor(sourceSessionInfo, session->GetDescriptor()); 230180922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetDescriptorInfo failed"); 230280922886Sopenharmony_ci ret = CastAudioProcess(sinkAudioDescriptors, sourceSessionInfo, session); 230380922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudioProcess failed"); 230480922886Sopenharmony_ci return AVSESSION_SUCCESS; 230580922886Sopenharmony_ci} 230680922886Sopenharmony_ci 230780922886Sopenharmony_ciint32_t AVSessionService::CastAudioProcess(const std::vector<AudioStandard::AudioDeviceDescriptor>& descriptors, 230880922886Sopenharmony_ci const std::string& sourceSessionInfo, 230980922886Sopenharmony_ci sptr <AVSessionItem>& session) 231080922886Sopenharmony_ci{ 231180922886Sopenharmony_ci std::vector<AudioDeviceDescriptor> castSinkDescriptors; 231280922886Sopenharmony_ci std::vector<AudioDeviceDescriptor> cancelSinkDescriptors; 231380922886Sopenharmony_ci GetDeviceInfo(session, descriptors, castSinkDescriptors, cancelSinkDescriptors); 231480922886Sopenharmony_ci 231580922886Sopenharmony_ci if (cancelSinkDescriptors.size() > 0) { 231680922886Sopenharmony_ci int32_t ret = CancelCastAudioInner(cancelSinkDescriptors, sourceSessionInfo, session); 231780922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CancelCastAudioInner failed"); 231880922886Sopenharmony_ci } 231980922886Sopenharmony_ci 232080922886Sopenharmony_ci if (castSinkDescriptors.size() > 0) { 232180922886Sopenharmony_ci int32_t ret = CastAudioInner(castSinkDescriptors, sourceSessionInfo, session); 232280922886Sopenharmony_ci if (ret != AVSESSION_SUCCESS) { 232380922886Sopenharmony_ci SLOGE("CastAudioInner failed, try cancel it. ret is %{public}d", 232480922886Sopenharmony_ci CancelCastAudioInner(castSinkDescriptors, sourceSessionInfo, session)); 232580922886Sopenharmony_ci return ret; 232680922886Sopenharmony_ci } 232780922886Sopenharmony_ci } 232880922886Sopenharmony_ci 232980922886Sopenharmony_ci SetDeviceInfo(descriptors, session); 233080922886Sopenharmony_ci return AVSESSION_SUCCESS; 233180922886Sopenharmony_ci} 233280922886Sopenharmony_ci 233380922886Sopenharmony_ciint32_t AVSessionService::CastAudioInner(const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkAudioDescriptors, 233480922886Sopenharmony_ci const std::string& sourceSessionInfo, 233580922886Sopenharmony_ci const sptr <AVSessionItem>& session) 233680922886Sopenharmony_ci{ 233780922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(sinkAudioDescriptors.size() > 0, AVSESSION_ERROR, "sinkDescriptors is empty"); 233880922886Sopenharmony_ci std::string sourceDevice; 233980922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(GetLocalNetworkId(sourceDevice) == AVSESSION_SUCCESS, AVSESSION_ERROR, 234080922886Sopenharmony_ci "GetLocalNetworkId failed"); 234180922886Sopenharmony_ci SLOGI("networkId_: %{public}.6s, role %{public}d", sinkAudioDescriptors[0].networkId_.c_str(), 234280922886Sopenharmony_ci static_cast<int32_t>(sinkAudioDescriptors[0].deviceRole_)); 234380922886Sopenharmony_ci if (IsLocalDevice(sinkAudioDescriptors[0].networkId_)) { 234480922886Sopenharmony_ci int32_t ret = SelectOutputDevice(session->GetUid(), sinkAudioDescriptors[0]); 234580922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "selectOutputDevice failed"); 234680922886Sopenharmony_ci return AVSESSION_SUCCESS; 234780922886Sopenharmony_ci } 234880922886Sopenharmony_ci 234980922886Sopenharmony_ci SLOGI("sinkAudioDescriptors size is %{public}d", static_cast<int32_t>(sinkAudioDescriptors.size())); 235080922886Sopenharmony_ci for (const auto& sinkAudioDescriptor : sinkAudioDescriptors) { 235180922886Sopenharmony_ci std::string sinkSessionInfo; 235280922886Sopenharmony_ci auto service = GetService(sinkAudioDescriptor.networkId_); 235380922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(service != nullptr, AVSESSION_ERROR, "GetService %{public}s failed", 235480922886Sopenharmony_ci sinkAudioDescriptor.networkId_.c_str()); 235580922886Sopenharmony_ci int32_t ret = service->ProcessCastAudioCommand(RemoteServiceCommand::COMMAND_CAST_AUDIO, sourceSessionInfo, 235680922886Sopenharmony_ci sinkSessionInfo); 235780922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "ProcessCastAudioCommand failed"); 235880922886Sopenharmony_ci std::string sinkCapability; 235980922886Sopenharmony_ci ret = JsonUtils::GetAllCapability(sinkSessionInfo, sinkCapability); 236080922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetAllCapability failed"); 236180922886Sopenharmony_ci ret = session->CastAudioToRemote(sourceDevice, sinkAudioDescriptor.networkId_, sinkCapability); 236280922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudioToRemote failed"); 236380922886Sopenharmony_ci HISYSEVENT_BEHAVIOR("SESSION_CAST", 236480922886Sopenharmony_ci "BUNDLE_NAME", session->GetDescriptor().elementName_.GetBundleName(), 236580922886Sopenharmony_ci "MODULE_NAME", session->GetDescriptor().elementName_.GetModuleName(), 236680922886Sopenharmony_ci "ABILITY_NAME", session->GetDescriptor().elementName_.GetAbilityName(), 236780922886Sopenharmony_ci "SESSION_PID", session->GetDescriptor().pid_, 236880922886Sopenharmony_ci "SESSION_UID", session->GetDescriptor().uid_, 236980922886Sopenharmony_ci "SESSION_ID", session->GetDescriptor().sessionId_, 237080922886Sopenharmony_ci "SESSION_TAG", session->GetDescriptor().sessionTag_, 237180922886Sopenharmony_ci "SESSION_TYPE", session->GetDescriptor().sessionType_, 237280922886Sopenharmony_ci "CAST_TYPE", 0, 237380922886Sopenharmony_ci "DEST_DEVICE_TYPE", sinkAudioDescriptor.deviceType_, 237480922886Sopenharmony_ci "DEST_DEVICE_NAME", sinkAudioDescriptor.deviceName_.c_str(), 237580922886Sopenharmony_ci "DEST_DEVICE_ID", sinkAudioDescriptor.deviceId_, 237680922886Sopenharmony_ci "DETAILED_MSG", "avsession service cast audio"); 237780922886Sopenharmony_ci ret = SelectOutputDevice(session->GetUid(), sinkAudioDescriptor); 237880922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "selectOutputDevice failed"); 237980922886Sopenharmony_ci } 238080922886Sopenharmony_ci SLOGI("success"); 238180922886Sopenharmony_ci return AVSESSION_SUCCESS; 238280922886Sopenharmony_ci} 238380922886Sopenharmony_ci 238480922886Sopenharmony_ciint32_t AVSessionService::CancelCastAudioInner(const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkDevices, 238580922886Sopenharmony_ci const std::string& sourceSessionInfo, 238680922886Sopenharmony_ci const sptr <AVSessionItem>& session) 238780922886Sopenharmony_ci{ 238880922886Sopenharmony_ci SLOGI("cancel sinkDevices size is %{public}d", static_cast<int32_t>(sinkDevices.size())); 238980922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(!sinkDevices.empty(), AVSESSION_ERROR, "sinkDevices is empty"); 239080922886Sopenharmony_ci for (const auto& sinkDevice : sinkDevices) { 239180922886Sopenharmony_ci if (IsLocalDevice(sinkDevice.networkId_)) { 239280922886Sopenharmony_ci SLOGI("cancel Local device %{public}.6s", sinkDevice.networkId_.c_str()); 239380922886Sopenharmony_ci continue; 239480922886Sopenharmony_ci } 239580922886Sopenharmony_ci std::string sinkSessionInfo; 239680922886Sopenharmony_ci SLOGI("cancel sinkDevices sinkDevice.networkId_ is %{public}.6s", sinkDevice.networkId_.c_str()); 239780922886Sopenharmony_ci auto service = GetService(sinkDevice.networkId_); 239880922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(service != nullptr, AVSESSION_ERROR, "GetService %{public}s failed", 239980922886Sopenharmony_ci sinkDevice.networkId_.c_str()); 240080922886Sopenharmony_ci int32_t ret = service->ProcessCastAudioCommand(RemoteServiceCommand::COMMAND_CANCEL_CAST_AUDIO, 240180922886Sopenharmony_ci sourceSessionInfo, sinkSessionInfo); 240280922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "ProcessCastAudioCommand failed"); 240380922886Sopenharmony_ci ret = session->SourceCancelCastAudio(sinkDevice.networkId_); 240480922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SourceCancelCastAudio failed"); 240580922886Sopenharmony_ci } 240680922886Sopenharmony_ci return AVSESSION_SUCCESS; 240780922886Sopenharmony_ci} 240880922886Sopenharmony_ci 240980922886Sopenharmony_ciint32_t AVSessionService::CastAudioForNewSession(const sptr<AVSessionItem>& session) 241080922886Sopenharmony_ci{ 241180922886Sopenharmony_ci SLOGI("new sessionId is %{public}s", AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str()); 241280922886Sopenharmony_ci SessionToken token; 241380922886Sopenharmony_ci token.sessionId = session->GetSessionId(); 241480922886Sopenharmony_ci token.pid = session->GetPid(); 241580922886Sopenharmony_ci token.uid = session->GetUid(); 241680922886Sopenharmony_ci 241780922886Sopenharmony_ci int32_t ret = AVSESSION_SUCCESS; 241880922886Sopenharmony_ci std::vector<AudioStandard::AudioDeviceDescriptor> castSinkDevices; 241980922886Sopenharmony_ci { 242080922886Sopenharmony_ci std::lock_guard lockGuard(outputDeviceIdLock_); 242180922886Sopenharmony_ci ret = GetAudioDescriptor(outputDeviceId_, castSinkDevices); 242280922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetAudioDescriptor failed"); 242380922886Sopenharmony_ci } 242480922886Sopenharmony_ci 242580922886Sopenharmony_ci ret = CastAudio(token, castSinkDevices); 242680922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudio error, session Id is %{public}s", 242780922886Sopenharmony_ci AVSessionUtils::GetAnonySessionId(token.sessionId).c_str()); 242880922886Sopenharmony_ci 242980922886Sopenharmony_ci SLOGI("success"); 243080922886Sopenharmony_ci return AVSESSION_SUCCESS; 243180922886Sopenharmony_ci} 243280922886Sopenharmony_ci 243380922886Sopenharmony_ciint32_t AVSessionService::CastAudioForAll(const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkAudioDescriptors) 243480922886Sopenharmony_ci{ 243580922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(sinkAudioDescriptors.size() > 0, ERR_INVALID_PARAM, "sinkAudioDescriptors is empty"); 243680922886Sopenharmony_ci { 243780922886Sopenharmony_ci std::lock_guard lockGuard(isAllSessionCastLock_); 243880922886Sopenharmony_ci isAllSessionCast_ = false; 243980922886Sopenharmony_ci if (!IsLocalDevice(sinkAudioDescriptors[0].networkId_)) { 244080922886Sopenharmony_ci isAllSessionCast_ = true; 244180922886Sopenharmony_ci } 244280922886Sopenharmony_ci } 244380922886Sopenharmony_ci for (const auto& session : GetContainer().GetAllSessions()) { 244480922886Sopenharmony_ci SessionToken token; 244580922886Sopenharmony_ci token.sessionId = session->GetSessionId(); 244680922886Sopenharmony_ci token.pid = session->GetPid(); 244780922886Sopenharmony_ci token.uid = session->GetUid(); 244880922886Sopenharmony_ci SLOGI("cast session %{public}s", token.sessionId.c_str()); 244980922886Sopenharmony_ci int32_t ret = CastAudio(token, sinkAudioDescriptors); 245080922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudio session %{public}s failed", 245180922886Sopenharmony_ci AVSessionUtils::GetAnonySessionId(token.sessionId).c_str()); 245280922886Sopenharmony_ci { 245380922886Sopenharmony_ci std::lock_guard lockGuard(outputDeviceIdLock_); 245480922886Sopenharmony_ci outputDeviceId_ = session->GetDescriptor().outputDeviceInfo_.deviceInfos_[0].deviceId_; 245580922886Sopenharmony_ci } 245680922886Sopenharmony_ci } 245780922886Sopenharmony_ci 245880922886Sopenharmony_ci SLOGI("isAllSessionCast_ %{public}d, outputDeviceId_ is %{public}s", isAllSessionCast_, outputDeviceId_.c_str()); 245980922886Sopenharmony_ci return AVSESSION_SUCCESS; 246080922886Sopenharmony_ci} 246180922886Sopenharmony_ci 246280922886Sopenharmony_ciint32_t AVSessionService::ProcessCastAudioCommand(const RemoteServiceCommand command, const std::string& input, 246380922886Sopenharmony_ci std::string& output) 246480922886Sopenharmony_ci{ 246580922886Sopenharmony_ci SLOGI("ProcessCastAudioCommand command is %{public}d", static_cast<int32_t>(command)); 246680922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(command > COMMAND_INVALID && command < COMMAND_MAX, AVSESSION_ERROR, "invalid command"); 246780922886Sopenharmony_ci if (command == COMMAND_CAST_AUDIO) { 246880922886Sopenharmony_ci int ret = RemoteCastAudioInner(input, output); 246980922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "RemoteCastAudioInner error"); 247080922886Sopenharmony_ci return AVSESSION_SUCCESS; 247180922886Sopenharmony_ci } 247280922886Sopenharmony_ci 247380922886Sopenharmony_ci int ret = RemoteCancelCastAudioInner(input); 247480922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "RemoteCancelCastAudioInner error"); 247580922886Sopenharmony_ci return AVSESSION_SUCCESS; 247680922886Sopenharmony_ci} 247780922886Sopenharmony_ci 247880922886Sopenharmony_ciint32_t AVSessionService::RemoteCastAudioInner(const std::string& sourceSessionInfo, std::string& sinkSessionInfo) 247980922886Sopenharmony_ci{ 248080922886Sopenharmony_ci SLOGI("sourceInfo : %{public}s", sourceSessionInfo.c_str()); 248180922886Sopenharmony_ci AVSessionDescriptor sourceDescriptor; 248280922886Sopenharmony_ci int32_t ret = JsonUtils::GetSessionDescriptor(sourceSessionInfo, sourceDescriptor); 248380922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetSessionDescriptor failed"); 248480922886Sopenharmony_ci 248580922886Sopenharmony_ci ret = SetBasicInfo(sinkSessionInfo); 248680922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, AVSESSION_ERROR, "SetBasicInfo failed"); 248780922886Sopenharmony_ci AVSessionBasicInfo sinkDeviceInfo; 248880922886Sopenharmony_ci ret = JsonUtils::GetSessionBasicInfo(sinkSessionInfo, sinkDeviceInfo); 248980922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetBasicInfo failed"); 249080922886Sopenharmony_ci 249180922886Sopenharmony_ci sptr <AVSessionItem> session; 249280922886Sopenharmony_ci auto res = CreateSessionInner(sourceDescriptor.sessionTag_, sourceDescriptor.sessionType_, 249380922886Sopenharmony_ci sourceDescriptor.isThirdPartyApp_, sourceDescriptor.elementName_, session); 249480922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(res == AVSESSION_SUCCESS, res, "CreateSession failed"); 249580922886Sopenharmony_ci 249680922886Sopenharmony_ci { 249780922886Sopenharmony_ci std::lock_guard lockGuard(castAudioSessionMapLock_); 249880922886Sopenharmony_ci castAudioSessionMap_[sourceDescriptor.sessionId_] = session->GetSessionId(); 249980922886Sopenharmony_ci } 250080922886Sopenharmony_ci 250180922886Sopenharmony_ci AVSessionBasicInfo sourceDeviceInfo; 250280922886Sopenharmony_ci ret = JsonUtils::GetSessionBasicInfo(sourceSessionInfo, sourceDeviceInfo); 250380922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetBasicInfo failed"); 250480922886Sopenharmony_ci std::string sourceCapability; 250580922886Sopenharmony_ci ret = JsonUtils::GetAllCapability(sourceSessionInfo, sourceCapability); 250680922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetAllCapability failed"); 250780922886Sopenharmony_ci ret = session->CastAudioFromRemote(sourceDescriptor.sessionId_, sourceDeviceInfo.networkId_, 250880922886Sopenharmony_ci sinkDeviceInfo.networkId_, sourceCapability); 250980922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudioFromRemote failed"); 251080922886Sopenharmony_ci JsonUtils::SetSessionDescriptor(sinkSessionInfo, session->GetDescriptor()); 251180922886Sopenharmony_ci return AVSESSION_SUCCESS; 251280922886Sopenharmony_ci} 251380922886Sopenharmony_ci 251480922886Sopenharmony_ciint32_t AVSessionService::RemoteCancelCastAudioInner(const std::string& sessionInfo) 251580922886Sopenharmony_ci{ 251680922886Sopenharmony_ci SLOGI("sessionInfo is %{public}s", sessionInfo.c_str()); 251780922886Sopenharmony_ci AVSessionBasicInfo sourceDeviceInfo; 251880922886Sopenharmony_ci int32_t ret = JsonUtils::GetSessionBasicInfo(sessionInfo, sourceDeviceInfo); 251980922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetBasicInfo failed"); 252080922886Sopenharmony_ci AVSessionDescriptor sourceDescriptor; 252180922886Sopenharmony_ci ret = JsonUtils::GetSessionDescriptor(sessionInfo, sourceDescriptor); 252280922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetSessionDescriptor failed"); 252380922886Sopenharmony_ci 252480922886Sopenharmony_ci std::lock_guard lockGuard(castAudioSessionMapLock_); 252580922886Sopenharmony_ci auto iter = castAudioSessionMap_.find(sourceDescriptor.sessionId_); 252680922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(iter != castAudioSessionMap_.end(), AVSESSION_ERROR, "no source session %{public}s", 252780922886Sopenharmony_ci AVSessionUtils::GetAnonySessionId(sourceDescriptor.sessionId_).c_str()); 252880922886Sopenharmony_ci auto session = GetContainer().GetSessionById(iter->second); 252980922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(session != nullptr, AVSESSION_ERROR, "no sink session %{public}s", 253080922886Sopenharmony_ci AVSessionUtils::GetAnonySessionId(iter->second).c_str()); 253180922886Sopenharmony_ci 253280922886Sopenharmony_ci ret = session->SinkCancelCastAudio(); 253380922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SinkCancelCastAudio failed"); 253480922886Sopenharmony_ci HandleSessionRelease(session->GetSessionId()); 253580922886Sopenharmony_ci castAudioSessionMap_.erase(sourceDescriptor.sessionId_); 253680922886Sopenharmony_ci SLOGI("cancel source session %{public}s success", 253780922886Sopenharmony_ci AVSessionUtils::GetAnonySessionId(sourceDescriptor.sessionId_).c_str()); 253880922886Sopenharmony_ci return AVSESSION_SUCCESS; 253980922886Sopenharmony_ci} 254080922886Sopenharmony_ci 254180922886Sopenharmony_ciint32_t AVSessionService::CancelCastAudioForClientExit(pid_t pid, const sptr<AVSessionItem>& session) 254280922886Sopenharmony_ci{ 254380922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(session != nullptr, AVSESSION_ERROR, "session is nullptr"); 254480922886Sopenharmony_ci SLOGI("pid is %{public}d, sessionId is %{public}s", static_cast<int32_t>(pid), 254580922886Sopenharmony_ci AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str()); 254680922886Sopenharmony_ci std::string sourceSessionInfo; 254780922886Sopenharmony_ci int32_t ret = SetBasicInfo(sourceSessionInfo); 254880922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetBasicInfo failed"); 254980922886Sopenharmony_ci ret = JsonUtils::SetSessionDescriptor(sourceSessionInfo, session->GetDescriptor()); 255080922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetDescriptorInfo failed"); 255180922886Sopenharmony_ci 255280922886Sopenharmony_ci std::vector<AudioStandard::AudioDeviceDescriptor> cancelSinkDevices; 255380922886Sopenharmony_ci ret = GetAudioDescriptor(session->GetDescriptor().outputDeviceInfo_.deviceInfos_[0].deviceId_, cancelSinkDevices); 255480922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetAudioDescriptor failed"); 255580922886Sopenharmony_ci 255680922886Sopenharmony_ci ret = CancelCastAudioInner(cancelSinkDevices, sourceSessionInfo, session); 255780922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CancelCastAudioInner failed"); 255880922886Sopenharmony_ci return AVSESSION_SUCCESS; 255980922886Sopenharmony_ci} 256080922886Sopenharmony_ci 256180922886Sopenharmony_ciint32_t AVSessionService::GetAudioDescriptor(const std::string deviceId, 256280922886Sopenharmony_ci std::vector<AudioStandard::AudioDeviceDescriptor>& audioDeviceDescriptors) 256380922886Sopenharmony_ci{ 256480922886Sopenharmony_ci auto audioDescriptors = AudioSystemManager::GetInstance()->GetDevices(ALL_L_D_DEVICES_FLAG); 256580922886Sopenharmony_ci AudioDeviceDescriptor audioDescriptor; 256680922886Sopenharmony_ci if (GetAudioDescriptorByDeviceId(audioDescriptors, deviceId, audioDescriptor)) { 256780922886Sopenharmony_ci audioDeviceDescriptors.push_back(audioDescriptor); 256880922886Sopenharmony_ci SLOGI("get audio networkId_ is %{public}.6s", audioDescriptor.networkId_.c_str()); 256980922886Sopenharmony_ci return AVSESSION_SUCCESS; 257080922886Sopenharmony_ci } 257180922886Sopenharmony_ci SLOGI("can not get deviceId %{public}s info", deviceId.c_str()); 257280922886Sopenharmony_ci return AVSESSION_ERROR; 257380922886Sopenharmony_ci} 257480922886Sopenharmony_ci 257580922886Sopenharmony_civoid AVSessionService::ClearSessionForClientDiedNoLock(pid_t pid) 257680922886Sopenharmony_ci{ 257780922886Sopenharmony_ci SLOGI("clear session in "); 257880922886Sopenharmony_ci auto sessions = GetUsersManager().GetContainerFromAll().GetSessionsByPid(pid); 257980922886Sopenharmony_ci for (const auto& session : sessions) { 258080922886Sopenharmony_ci SLOGI("check session release task for id %{public}s", 258180922886Sopenharmony_ci AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str()); 258280922886Sopenharmony_ci HandleSessionRelease(session->GetSessionId()); 258380922886Sopenharmony_ci } 258480922886Sopenharmony_ci} 258580922886Sopenharmony_ci 258680922886Sopenharmony_civoid AVSessionService::ClearControllerForClientDiedNoLock(pid_t pid) 258780922886Sopenharmony_ci{ 258880922886Sopenharmony_ci auto it = controllers_.find(pid); 258980922886Sopenharmony_ci CHECK_AND_RETURN_LOG(it != controllers_.end(), "no find controller"); 259080922886Sopenharmony_ci auto controllers = std::move(it->second); 259180922886Sopenharmony_ci SLOGI("remove controllers size=%{public}d", static_cast<int>(controllers.size())); 259280922886Sopenharmony_ci if (!controllers.empty()) { 259380922886Sopenharmony_ci for (const auto& controller : controllers) { 259480922886Sopenharmony_ci controller->Destroy(); 259580922886Sopenharmony_ci } 259680922886Sopenharmony_ci } 259780922886Sopenharmony_ci it = controllers_.find(pid); 259880922886Sopenharmony_ci CHECK_AND_RETURN_LOG(it != controllers_.end(), "no find controller"); 259980922886Sopenharmony_ci controllers_.erase(pid); 260080922886Sopenharmony_ci} 260180922886Sopenharmony_ci 260280922886Sopenharmony_ciClientDeathRecipient::ClientDeathRecipient(const std::function<void()>& callback) 260380922886Sopenharmony_ci : callback_(callback) 260480922886Sopenharmony_ci{ 260580922886Sopenharmony_ci SLOGD("construct"); 260680922886Sopenharmony_ci} 260780922886Sopenharmony_ci 260880922886Sopenharmony_civoid ClientDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& object) 260980922886Sopenharmony_ci{ 261080922886Sopenharmony_ci if (callback_) { 261180922886Sopenharmony_ci callback_(); 261280922886Sopenharmony_ci } 261380922886Sopenharmony_ci} 261480922886Sopenharmony_ci 261580922886Sopenharmony_cibool AVSessionService::CheckUserDirValid(int32_t userId) 261680922886Sopenharmony_ci{ 261780922886Sopenharmony_ci std::string filePath = GetUsersManager().GetDirForCurrentUser(userId); 261880922886Sopenharmony_ci filesystem::path directory(filePath); 261980922886Sopenharmony_ci std::error_code errCode; 262080922886Sopenharmony_ci if (!filesystem::exists(directory, errCode)) { 262180922886Sopenharmony_ci SLOGE("check user dir not exsit %{public}s for user %{public}d, errCode %{public}d", 262280922886Sopenharmony_ci filePath.c_str(), userId, static_cast<int>(errCode.value())); 262380922886Sopenharmony_ci return false; 262480922886Sopenharmony_ci } 262580922886Sopenharmony_ci return true; 262680922886Sopenharmony_ci} 262780922886Sopenharmony_ci 262880922886Sopenharmony_cibool AVSessionService::CheckAndCreateDir(const string& filePath) 262980922886Sopenharmony_ci{ 263080922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(CheckUserDirValid(), false, "check userDir err!"); 263180922886Sopenharmony_ci filesystem::path directory = filesystem::path(filePath).parent_path(); 263280922886Sopenharmony_ci if (!filesystem::exists(directory)) { 263380922886Sopenharmony_ci SLOGI("check file not exist and try create %{public}s", filePath.c_str()); 263480922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(filesystem::create_directories(directory), 263580922886Sopenharmony_ci false, "Failed to create directory"); 263680922886Sopenharmony_ci } 263780922886Sopenharmony_ci return true; 263880922886Sopenharmony_ci} 263980922886Sopenharmony_ci 264080922886Sopenharmony_cibool AVSessionService::LoadStringFromFileEx(const string& filePath, string& content) 264180922886Sopenharmony_ci{ 264280922886Sopenharmony_ci SLOGD("file load in for path: %{public}s", filePath.c_str()); 264380922886Sopenharmony_ci CheckAndCreateDir(filePath); 264480922886Sopenharmony_ci ifstream file(filePath.c_str()); 264580922886Sopenharmony_ci if (!file.is_open()) { 264680922886Sopenharmony_ci SLOGD("file not open! try open first ! "); 264780922886Sopenharmony_ci file.open(filePath.c_str(), ios::out | ios::app); 264880922886Sopenharmony_ci if (!file.is_open()) { 264980922886Sopenharmony_ci SLOGE("open file again fail !"); 265080922886Sopenharmony_ci return false; 265180922886Sopenharmony_ci } 265280922886Sopenharmony_ci } 265380922886Sopenharmony_ci file.seekg(0, ios::end); 265480922886Sopenharmony_ci const long fileLength = file.tellg(); 265580922886Sopenharmony_ci SLOGD("get file length(%{public}ld)!", fileLength); 265680922886Sopenharmony_ci if (fileLength > maxFileLength) { 265780922886Sopenharmony_ci SLOGE("invalid file length(%{public}ld)!", fileLength); 265880922886Sopenharmony_ci return false; 265980922886Sopenharmony_ci } 266080922886Sopenharmony_ci if (fileLength <= 0) { 266180922886Sopenharmony_ci SLOGD("file new create empty ! try set init json "); 266280922886Sopenharmony_ci ofstream fileWrite; 266380922886Sopenharmony_ci fileWrite.open(filePath.c_str(), ios::out | ios::trunc); 266480922886Sopenharmony_ci if (!fileWrite.is_open()) { 266580922886Sopenharmony_ci SLOGE("open file in create new failed!"); 266680922886Sopenharmony_ci file.close(); 266780922886Sopenharmony_ci return false; 266880922886Sopenharmony_ci } 266980922886Sopenharmony_ci nlohmann::json emptyValue; 267080922886Sopenharmony_ci std::string emptyContent = emptyValue.dump(); 267180922886Sopenharmony_ci SLOGD("LoadStringFromFileEx::Dump json object finished"); 267280922886Sopenharmony_ci fileWrite.write(emptyContent.c_str(), emptyContent.length()); 267380922886Sopenharmony_ci if (fileWrite.fail()) { 267480922886Sopenharmony_ci SLOGE("file empty init json fail !"); 267580922886Sopenharmony_ci file.close(); 267680922886Sopenharmony_ci fileWrite.close(); 267780922886Sopenharmony_ci return false; 267880922886Sopenharmony_ci } 267980922886Sopenharmony_ci fileWrite.close(); 268080922886Sopenharmony_ci } 268180922886Sopenharmony_ci content.clear(); 268280922886Sopenharmony_ci file.seekg(0, ios::beg); 268380922886Sopenharmony_ci copy(istreambuf_iterator<char>(file), istreambuf_iterator<char>(), back_inserter(content)); 268480922886Sopenharmony_ci file.close(); 268580922886Sopenharmony_ci return CheckStringAndCleanFile(filePath); 268680922886Sopenharmony_ci} 268780922886Sopenharmony_ci 268880922886Sopenharmony_cibool AVSessionService::SaveStringToFileEx(const std::string& filePath, const std::string& content) 268980922886Sopenharmony_ci{ 269080922886Sopenharmony_ci SLOGI("file save in for path:%{public}s, content:%{public}s", filePath.c_str(), content.c_str()); 269180922886Sopenharmony_ci nlohmann::json checkValues = json::parse(content, nullptr, false); 269280922886Sopenharmony_ci CHECK_AND_RETURN_RET_LOG(!checkValues.is_discarded(), false, "recv content discarded"); 269380922886Sopenharmony_ci ofstream file; 269480922886Sopenharmony_ci file.open(filePath.c_str(), ios::out | ios::trunc); 269580922886Sopenharmony_ci if (!file.is_open()) { 269680922886Sopenharmony_ci SLOGE("open file in save failed!"); 269780922886Sopenharmony_ci return false; 269880922886Sopenharmony_ci } 269980922886Sopenharmony_ci if (content.empty()) { 270080922886Sopenharmony_ci SLOGE("write content is empty, no need to do write!"); 270180922886Sopenharmony_ci file.close(); 270280922886Sopenharmony_ci return true; 270380922886Sopenharmony_ci } 270480922886Sopenharmony_ci file.write(content.c_str(), content.length()); 270580922886Sopenharmony_ci if (file.fail()) { 270680922886Sopenharmony_ci SLOGE("write content to file failed!"); 270780922886Sopenharmony_ci file.close(); 270880922886Sopenharmony_ci return false; 270980922886Sopenharmony_ci } 271080922886Sopenharmony_ci file.close(); 271180922886Sopenharmony_ci return CheckStringAndCleanFile(filePath); 271280922886Sopenharmony_ci} 271380922886Sopenharmony_ci 271480922886Sopenharmony_cibool AVSessionService::CheckStringAndCleanFile(const std::string& filePath) 271580922886Sopenharmony_ci{ 271680922886Sopenharmony_ci SLOGD("file check for path:%{public}s", filePath.c_str()); 271780922886Sopenharmony_ci string content {}; 271880922886Sopenharmony_ci ifstream fileRead(filePath.c_str()); 271980922886Sopenharmony_ci if (!fileRead.is_open()) { 272080922886Sopenharmony_ci SLOGD("file not open! try open first ! "); 272180922886Sopenharmony_ci fileRead.open(filePath.c_str(), ios::app); 272280922886Sopenharmony_ci if (!fileRead.is_open()) { 272380922886Sopenharmony_ci SLOGE("open file again fail !"); 272480922886Sopenharmony_ci return false; 272580922886Sopenharmony_ci } 272680922886Sopenharmony_ci } 272780922886Sopenharmony_ci content.clear(); 272880922886Sopenharmony_ci fileRead.seekg(0, ios::beg); 272980922886Sopenharmony_ci copy(istreambuf_iterator<char>(fileRead), istreambuf_iterator<char>(), back_inserter(content)); 273080922886Sopenharmony_ci SLOGD("check content pre clean it: %{public}s", content.c_str()); 273180922886Sopenharmony_ci nlohmann::json checkValues = json::parse(content, nullptr, false); 273280922886Sopenharmony_ci if (checkValues.is_discarded()) { 273380922886Sopenharmony_ci SLOGE("check content discarded! content %{public}s", content.c_str()); 273480922886Sopenharmony_ci ofstream fileWrite; 273580922886Sopenharmony_ci fileWrite.open(filePath.c_str(), ios::out | ios::trunc); 273680922886Sopenharmony_ci if (!fileWrite.is_open()) { 273780922886Sopenharmony_ci SLOGE("open file in create new failed!"); 273880922886Sopenharmony_ci fileRead.close(); 273980922886Sopenharmony_ci return false; 274080922886Sopenharmony_ci } 274180922886Sopenharmony_ci nlohmann::json emptyValue; 274280922886Sopenharmony_ci std::string emptyContent = emptyValue.dump(); 274380922886Sopenharmony_ci SLOGD("LoadStringFromFileEx::Dump json object finished"); 274480922886Sopenharmony_ci fileWrite.write(emptyContent.c_str(), emptyContent.length()); 274580922886Sopenharmony_ci if (fileWrite.fail()) { 274680922886Sopenharmony_ci SLOGE("file empty init json fail! content %{public}s", content.c_str()); 274780922886Sopenharmony_ci fileRead.close(); 274880922886Sopenharmony_ci fileWrite.close(); 274980922886Sopenharmony_ci return false; 275080922886Sopenharmony_ci } 275180922886Sopenharmony_ci fileWrite.close(); 275280922886Sopenharmony_ci } 275380922886Sopenharmony_ci fileRead.close(); 275480922886Sopenharmony_ci return true; 275580922886Sopenharmony_ci} 275680922886Sopenharmony_ci 275780922886Sopenharmony_cistd::shared_ptr<AbilityRuntime::WantAgent::WantAgent> AVSessionService::CreateWantAgent( 275880922886Sopenharmony_ci const AVSessionDescriptor* histroyDescriptor) 275980922886Sopenharmony_ci{ 276080922886Sopenharmony_ci if (histroyDescriptor == nullptr && topSession_ == nullptr) { 276180922886Sopenharmony_ci SLOGE("CreateWantAgent error, histroyDescriptor and topSession_ null"); 276280922886Sopenharmony_ci return nullptr; 276380922886Sopenharmony_ci } 276480922886Sopenharmony_ci std::vector<AbilityRuntime::WantAgent::WantAgentConstant::Flags> flags; 276580922886Sopenharmony_ci flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); 276680922886Sopenharmony_ci std::vector<std::shared_ptr<AAFwk::Want>> wants; 276780922886Sopenharmony_ci std::shared_ptr<AAFwk::Want> want = std::make_shared<AAFwk::Want>(); 276880922886Sopenharmony_ci std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> launWantAgent; 276980922886Sopenharmony_ci string bundleName = DEFAULT_BUNDLE_NAME; 277080922886Sopenharmony_ci string abilityName = DEFAULT_ABILITY_NAME; 277180922886Sopenharmony_ci auto uid = -1; 277280922886Sopenharmony_ci auto isCustomer = false; 277380922886Sopenharmony_ci if (topSession_ != nullptr) { 277480922886Sopenharmony_ci bundleName = topSession_->GetBundleName(); 277580922886Sopenharmony_ci abilityName = topSession_->GetAbilityName(); 277680922886Sopenharmony_ci uid = topSession_->GetUid(); 277780922886Sopenharmony_ci launWantAgent = std::make_shared<AbilityRuntime::WantAgent::WantAgent>(topSession_->GetLaunchAbility()); 277880922886Sopenharmony_ci auto res = AbilityRuntime::WantAgent::WantAgentHelper::GetWant(launWantAgent, want); 277980922886Sopenharmony_ci isCustomer = (res == AVSESSION_SUCCESS) && (bundleName == want->GetElement().GetBundleName()); 278080922886Sopenharmony_ci SLOGI("CreateWantAgent GetWant res=%{public}d", res); 278180922886Sopenharmony_ci } 278280922886Sopenharmony_ci if (histroyDescriptor != nullptr) { 278380922886Sopenharmony_ci SLOGI("CreateWantAgent with historyDescriptor"); 278480922886Sopenharmony_ci bundleName = histroyDescriptor->elementName_.GetBundleName(); 278580922886Sopenharmony_ci abilityName = histroyDescriptor->elementName_.GetAbilityName(); 278680922886Sopenharmony_ci uid = histroyDescriptor->uid_; 278780922886Sopenharmony_ci isCustomer = false; 278880922886Sopenharmony_ci } 278980922886Sopenharmony_ci SLOGI("CreateWantAgent bundleName %{public}s, abilityName %{public}s, isCustomer %{public}d", 279080922886Sopenharmony_ci bundleName.c_str(), abilityName.c_str(), isCustomer); 279180922886Sopenharmony_ci if (!isCustomer) { 279280922886Sopenharmony_ci AppExecFwk::ElementName element("", bundleName, abilityName); 279380922886Sopenharmony_ci want->SetElement(element); 279480922886Sopenharmony_ci } 279580922886Sopenharmony_ci wants.push_back(want); 279680922886Sopenharmony_ci AbilityRuntime::WantAgent::WantAgentInfo wantAgentInfo( 279780922886Sopenharmony_ci 0, 279880922886Sopenharmony_ci AbilityRuntime::WantAgent::WantAgentConstant::OperationType::START_ABILITY, 279980922886Sopenharmony_ci flags, 280080922886Sopenharmony_ci wants, 280180922886Sopenharmony_ci nullptr 280280922886Sopenharmony_ci ); 280380922886Sopenharmony_ci return AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, uid); 280480922886Sopenharmony_ci} 280580922886Sopenharmony_ci 280680922886Sopenharmony_civoid AVSessionService::RemoveExpired(std::list<std::chrono::system_clock::time_point> &list, 280780922886Sopenharmony_ci const std::chrono::system_clock::time_point &now, int32_t time) 280880922886Sopenharmony_ci{ 280980922886Sopenharmony_ci auto iter = list.begin(); 281080922886Sopenharmony_ci while (iter != list.end()) { 281180922886Sopenharmony_ci auto duration = now - static_cast<std::chrono::system_clock::time_point>(*iter); 281280922886Sopenharmony_ci int32_t durationInSeconds = std::chrono::duration_cast<std::chrono::seconds>(duration).count(); 281380922886Sopenharmony_ci if (std::abs(durationInSeconds) > time) { 281480922886Sopenharmony_ci iter = list.erase(iter); 281580922886Sopenharmony_ci } else { 281680922886Sopenharmony_ci break; 281780922886Sopenharmony_ci } 281880922886Sopenharmony_ci } 281980922886Sopenharmony_ci} 282080922886Sopenharmony_ci 282180922886Sopenharmony_ci// LCOV_EXCL_START 282280922886Sopenharmony_civoid AVSessionService::NotifySystemUI(const AVSessionDescriptor* historyDescriptor, bool isActiveSession) 282380922886Sopenharmony_ci{ 282480922886Sopenharmony_ci is2in1_ = system::GetBoolParameter("const.audio.volume_apply_to_all", false); 282580922886Sopenharmony_ci CHECK_AND_RETURN_LOG(!is2in1_, "2in1 not support"); 282680922886Sopenharmony_ci // flow control 282780922886Sopenharmony_ci std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); 282880922886Sopenharmony_ci RemoveExpired(flowControlPublishTimestampList_, now); 282980922886Sopenharmony_ci if (flowControlPublishTimestampList_.size() >= MAX_NOTIFICATION_NUM) { 283080922886Sopenharmony_ci SLOGE("PublishNotification Exeed MAX_NOTIFICATION_NUM"); 283180922886Sopenharmony_ci return; 283280922886Sopenharmony_ci } 283380922886Sopenharmony_ci flowControlPublishTimestampList_.push_back(now); 283480922886Sopenharmony_ci int32_t result = Notification::NotificationHelper::SubscribeLocalLiveViewNotification(NOTIFICATION_SUBSCRIBER); 283580922886Sopenharmony_ci CHECK_AND_RETURN_LOG(result == ERR_OK, "create notification subscriber error %{public}d", result); 283680922886Sopenharmony_ci 283780922886Sopenharmony_ci Notification::NotificationRequest request; 283880922886Sopenharmony_ci std::shared_ptr<Notification::NotificationLocalLiveViewContent> localLiveViewContent = 283980922886Sopenharmony_ci std::make_shared<Notification::NotificationLocalLiveViewContent>(); 284080922886Sopenharmony_ci CHECK_AND_RETURN_LOG(localLiveViewContent != nullptr, "avsession item local live view content nullptr error"); 284180922886Sopenharmony_ci localLiveViewContent->SetType(SYSTEMUI_LIVEVIEW_TYPECODE_MDEDIACONTROLLER); 284280922886Sopenharmony_ci localLiveViewContent->SetTitle(historyDescriptor && !isActiveSession ? "" : "AVSession NotifySystemUI"); 284380922886Sopenharmony_ci localLiveViewContent->SetText(historyDescriptor && !isActiveSession ? "" : "AVSession NotifySystemUI"); 284480922886Sopenharmony_ci 284580922886Sopenharmony_ci std::shared_ptr<Notification::NotificationContent> content = 284680922886Sopenharmony_ci std::make_shared<Notification::NotificationContent>(localLiveViewContent); 284780922886Sopenharmony_ci CHECK_AND_RETURN_LOG(content != nullptr, "avsession item notification content nullptr error"); 284880922886Sopenharmony_ci 284980922886Sopenharmony_ci auto uid = topSession_ ? topSession_->GetUid() : (historyDescriptor ? historyDescriptor->uid_ : -1); 285080922886Sopenharmony_ci request.SetSlotType(Notification::NotificationConstant::SlotType::LIVE_VIEW); 285180922886Sopenharmony_ci request.SetNotificationId(0); 285280922886Sopenharmony_ci request.SetContent(content); 285380922886Sopenharmony_ci request.SetCreatorUid(avSessionUid); 285480922886Sopenharmony_ci request.SetUnremovable(true); 285580922886Sopenharmony_ci request.SetInProgress(true); 285680922886Sopenharmony_ci int32_t userId = GetUsersManager().GetCurrentUserId(); 285780922886Sopenharmony_ci request.SetCreatorUserId(userId); 285880922886Sopenharmony_ci std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> wantAgent = CreateWantAgent(historyDescriptor); 285980922886Sopenharmony_ci CHECK_AND_RETURN_LOG(wantAgent != nullptr, "wantAgent nullptr error"); 286080922886Sopenharmony_ci request.SetWantAgent(wantAgent); 286180922886Sopenharmony_ci result = Notification::NotificationHelper::PublishNotification(request); 286280922886Sopenharmony_ci SLOGI("PublishNotification uid %{public}d, userId %{public}d, result %{public}d", uid, userId, result); 286380922886Sopenharmony_ci} 286480922886Sopenharmony_ci// LCOV_EXCL_STOP 286580922886Sopenharmony_ci 286680922886Sopenharmony_ci// LCOV_EXCL_START 286780922886Sopenharmony_civoid AVSessionService::NotifyDeviceChange(const DeviceChangeAction& deviceChangeAction) 286880922886Sopenharmony_ci{ 286980922886Sopenharmony_ci // historical sessions 287080922886Sopenharmony_ci std::vector<AVSessionDescriptor> hisDescriptors; 287180922886Sopenharmony_ci GetHistoricalSessionDescriptors(1, hisDescriptors); 287280922886Sopenharmony_ci // all sessions 287380922886Sopenharmony_ci std::vector<AVSessionDescriptor> activeDescriptors; 287480922886Sopenharmony_ci GetAllSessionDescriptors(activeDescriptors); 287580922886Sopenharmony_ci // historical avqueueinfos 287680922886Sopenharmony_ci std::vector<AVQueueInfo> avQueueInfos; 287780922886Sopenharmony_ci GetHistoricalAVQueueInfos(1, 1, avQueueInfos); 287880922886Sopenharmony_ci AVSessionDescriptor selectSession; 287980922886Sopenharmony_ci if (activeDescriptors.size() != 0 || hisDescriptors.size() == 0 || avQueueInfos.size() == 0) { 288080922886Sopenharmony_ci return; 288180922886Sopenharmony_ci } 288280922886Sopenharmony_ci bool isHisMatch = false; 288380922886Sopenharmony_ci for (AVQueueInfo avqueue : avQueueInfos) { 288480922886Sopenharmony_ci if (avqueue.GetBundleName() == hisDescriptors[0].elementName_.GetBundleName()) { 288580922886Sopenharmony_ci isHisMatch = true; 288680922886Sopenharmony_ci break; 288780922886Sopenharmony_ci } 288880922886Sopenharmony_ci } 288980922886Sopenharmony_ci if (!isHisMatch) { 289080922886Sopenharmony_ci SLOGI("no match hisAvqueue for %{public}s", hisDescriptors[0].elementName_.GetBundleName().c_str()); 289180922886Sopenharmony_ci return; 289280922886Sopenharmony_ci } 289380922886Sopenharmony_ci if (deviceChangeAction.type == AudioStandard::CONNECT && avQueueInfos.size() >= MINNUM_FOR_NOTIFICATION) { 289480922886Sopenharmony_ci SLOGI("history bundle name %{public}s", hisDescriptors[0].elementName_.GetBundleName().c_str()); 289580922886Sopenharmony_ci NotifySystemUI(&(hisDescriptors[0]), false); 289680922886Sopenharmony_ci } 289780922886Sopenharmony_ci} 289880922886Sopenharmony_ci// LCOV_EXCL_STOP 289980922886Sopenharmony_ci 290080922886Sopenharmony_ci// LCOV_EXCL_START 290180922886Sopenharmony_civoid AVSessionService::HandleDeviceChange(const DeviceChangeAction& deviceChangeAction) 290280922886Sopenharmony_ci{ 290380922886Sopenharmony_ci for (auto &audioDeviceDescriptor : deviceChangeAction.deviceDescriptors) { 290480922886Sopenharmony_ci if (audioDeviceDescriptor->deviceType_ == AudioStandard::DEVICE_TYPE_WIRED_HEADSET || 290580922886Sopenharmony_ci audioDeviceDescriptor->deviceType_ == AudioStandard::DEVICE_TYPE_WIRED_HEADPHONES || 290680922886Sopenharmony_ci audioDeviceDescriptor->deviceType_ == AudioStandard::DEVICE_TYPE_USB_HEADSET || 290780922886Sopenharmony_ci audioDeviceDescriptor->deviceType_ == AudioStandard::DEVICE_TYPE_BLUETOOTH_A2DP) { 290880922886Sopenharmony_ci SLOGI("AVSessionService handle pre notify device type %{public}d", audioDeviceDescriptor->deviceType_); 290980922886Sopenharmony_ci NotifyDeviceChange(deviceChangeAction); 291080922886Sopenharmony_ci } 291180922886Sopenharmony_ci } 291280922886Sopenharmony_ci} 291380922886Sopenharmony_ci// LCOV_EXCL_STOP 291480922886Sopenharmony_ci 291580922886Sopenharmony_civoid AVSessionService::InitRadarBMS() 291680922886Sopenharmony_ci{ 291780922886Sopenharmony_ci AVSessionRadar::GetInstance().InitBMS(); 291880922886Sopenharmony_ci} 291980922886Sopenharmony_ci 292080922886Sopenharmony_civoid AVSessionService::ReportStartCastBegin(std::string func, const OutputDeviceInfo& outputDeviceInfo, int32_t uid) 292180922886Sopenharmony_ci{ 292280922886Sopenharmony_ci AVSessionRadarInfo info(func); 292380922886Sopenharmony_ci info.bundleName_ = BundleStatusAdapter::GetInstance().GetBundleNameFromUid(uid); 292480922886Sopenharmony_ci AVSessionRadar::GetInstance().StartCastBegin(outputDeviceInfo, info); 292580922886Sopenharmony_ci} 292680922886Sopenharmony_ci 292780922886Sopenharmony_civoid AVSessionService::ReportStartCastEnd(std::string func, const OutputDeviceInfo& outputDeviceInfo, 292880922886Sopenharmony_ci int32_t uid, int ret) 292980922886Sopenharmony_ci{ 293080922886Sopenharmony_ci AVSessionRadarInfo info(func); 293180922886Sopenharmony_ci info.bundleName_ = BundleStatusAdapter::GetInstance().GetBundleNameFromUid(uid); 293280922886Sopenharmony_ci if (ret == AVSESSION_SUCCESS) { 293380922886Sopenharmony_ci AVSessionRadar::GetInstance().StartCastEnd(outputDeviceInfo, info); 293480922886Sopenharmony_ci } else { 293580922886Sopenharmony_ci info.errorCode_ = AVSessionRadar::GetRadarErrorCode(ret); 293680922886Sopenharmony_ci AVSessionRadar::GetInstance().FailToStartCast(outputDeviceInfo, info); 293780922886Sopenharmony_ci } 293880922886Sopenharmony_ci} 293980922886Sopenharmony_ci} // namespace OHOS::AVSession 2940