• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include <sstream>
17 #include <iomanip>
18 #include <iostream>
19 #include <regex>
20 #include <dlfcn.h>
21 #include <thread>
22 #include <chrono>
23 
24 #include "accesstoken_kit.h"
25 #include "app_manager_adapter.h"
26 #include "audio_adapter.h"
27 #include "avsession_errors.h"
28 #include "avsession_log.h"
29 #include "avsession_info.h"
30 #include "device_manager.h"
31 #include "remote_session_capability_set.h"
32 #include "remote_session_source_proxy.h"
33 #include "remote_session_sink_proxy.h"
34 #include "file_ex.h"
35 #include "iservice_registry.h"
36 #include "key_event_adapter.h"
37 #include "nlohmann/json.hpp"
38 #include "permission_checker.h"
39 #include "system_ability_definition.h"
40 #include "session_stack.h"
41 #include "avsession_trace.h"
42 #include "hash_calculator.h"
43 #include "avsession_dumper.h"
44 #include "command_send_limit.h"
45 #include "avsession_sysevent.h"
46 #include "json_utils.h"
47 #include "avsession_utils.h"
48 #include "avcontrol_command.h"
49 #include "avsession_event_handler.h"
50 #include "bundle_status_adapter.h"
51 #include "params_config_operator.h"
52 #include "notification_content.h"
53 #include "notification_helper.h"
54 #include "notification_request.h"
55 #include "notification_constant.h"
56 #include "insight_intent_execute_param.h"
57 #include "ability_connect_helper.h"
58 #include "if_system_ability_manager.h"
59 #include "parameter.h"
60 #include "parameters.h"
61 #include "avsession_service.h"
62 #include "want_agent_helper.h"
63 
64 typedef void (*MigrateStubFunc)(std::function<void(std::string, std::string, std::string, std::string)>);
65 typedef void (*StopMigrateStubFunc)(void);
66 
67 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
68 #include "av_router.h"
69 #endif
70 
71 #if !defined(WINDOWS_PLATFORM) and !defined(MAC_PLATFORM) and !defined(IOS_PLATFORM)
72 #include <malloc.h>
73 #endif
74 
75 using namespace std;
76 using namespace nlohmann;
77 using namespace OHOS::AudioStandard;
78 
79 namespace OHOS::AVSession {
80 static const std::string SOURCE_LIBRARY_PATH = std::string(SYSTEM_LIB_PATH) +
81     std::string("platformsdk/libsuspend_manager_client.z.so");
82 static const std::string MIGRATE_STUB_SOURCE_LIBRARY_PATH = std::string(SYSTEM_LIB_PATH) +
83     std::string("libavsession_migration.z.so");
84 static const int32_t CAST_ENGINE_SA_ID = 65546;
85 
86 class NotificationSubscriber : public Notification::NotificationLocalLiveViewSubscriber {
OnConnected()87     void OnConnected() {}
OnDisconnected()88     void OnDisconnected() {}
OnResponse(int32_t notificationId,sptr<Notification::NotificationButtonOption> buttonOption)89     void OnResponse(int32_t notificationId, sptr<Notification::NotificationButtonOption> buttonOption) {}
OnDied()90     void OnDied() {}
91 };
92 
93 static const auto NOTIFICATION_SUBSCRIBER = NotificationSubscriber();
94 
95 REGISTER_SYSTEM_ABILITY_BY_ID(AVSessionService, AVSESSION_SERVICE_ID, true);
96 
AVSessionService(int32_t systemAbilityId,bool runOnCreate)97 AVSessionService::AVSessionService(int32_t systemAbilityId, bool runOnCreate)
98     : SystemAbility(systemAbilityId, runOnCreate)
99 {
100     SLOGD("construct");
101 }
102 
~AVSessionService()103 AVSessionService::~AVSessionService()
104 {
105     std::string cachePath(AVSessionUtils::GetCachePathName());
106     AVSessionUtils::DeleteCacheFiles(cachePath);
107     SLOGD("destroy");
108 }
109 
OnStart()110 void AVSessionService::OnStart()
111 {
112     std::string cachePath(AVSessionUtils::GetCachePathName());
113     AVSessionUtils::DeleteCacheFiles(cachePath);
114     CHECK_AND_RETURN_LOG(Publish(this), "publish avsession service failed");
115     dumpHelper_ = std::make_unique<AVSessionDumper>();
116     CHECK_AND_RETURN_LOG(dumpHelper_ != nullptr, "no memory");
117     CommandSendLimit::GetInstance().StartTimer();
118 
119     ParamsConfigOperator::GetInstance().InitConfig();
120     auto ret = ParamsConfigOperator::GetInstance().GetValueIntByKey("historicalRecordMaxNum", &maxHistoryNums);
121     if (ret == AVSESSION_ERROR) {
122         maxHistoryNums = defMaxHistoryNum;
123     }
124 
125 #ifdef ENABLE_BACKGROUND_AUDIO_CONTROL
126     backgroundAudioController_.Init(this);
127     AddInnerSessionListener(&backgroundAudioController_);
128 #endif
129 
130     AddSystemAbilityListener(MULTIMODAL_INPUT_SERVICE_ID);
131     AddSystemAbilityListener(AUDIO_POLICY_SERVICE_ID);
132     AddSystemAbilityListener(APP_MGR_SERVICE_ID);
133     AddSystemAbilityListener(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID);
134     AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
135     AddSystemAbilityListener(CAST_ENGINE_SA_ID);
136 
137 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
138     auto deviceProp = system::GetParameter("const.product.devicetype", "default");
139     SLOGI("GetDeviceType, deviceProp=%{public}s", deviceProp.c_str());
140     int32_t is2in1 = strcmp(deviceProp.c_str(), "2in1");
141     if (is2in1 == 0) {
142         SLOGI("startup enable cast check 2in1");
143         checkEnableCast(true);
144         AVRouter::GetInstance().SetDiscoverable(true);
145     }
146 #endif
147     PullMigrateStub();
148     HISYSEVENT_REGITER;
149     HISYSEVENT_BEHAVIOR("SESSION_SERVICE_START", "SERVICE_NAME", "AVSessionService",
150         "SERVICE_ID", AVSESSION_SERVICE_ID, "DETAILED_MSG", "avsession service start success");
151 }
152 
OnDump()153 void AVSessionService::OnDump()
154 {
155 }
156 
OnStop()157 void AVSessionService::OnStop()
158 {
159     StopMigrateStubFunc stopMigrateStub =
160         reinterpret_cast<StopMigrateStubFunc>(dlsym(migrateStubFuncHandle_, "StopMigrateStub"));
161     if (stopMigrateStub == nullptr) {
162         SLOGE("failed to find library, reason: %{public}sn", dlerror());
163     } else {
164         stopMigrateStub();
165     }
166     dlclose(migrateStubFuncHandle_);
167     CommandSendLimit::GetInstance().StopTimer();
168 }
169 
PullMigrateStub()170 void AVSessionService::PullMigrateStub()
171 {
172     char sourceLibraryRealPath[PATH_MAX] = { 0x00 };
173     if (realpath(MIGRATE_STUB_SOURCE_LIBRARY_PATH.c_str(), sourceLibraryRealPath) == nullptr) {
174         SLOGE("check libmigrate_avsession_service path failed %{public}s", MIGRATE_STUB_SOURCE_LIBRARY_PATH.c_str());
175         return;
176     }
177     migrateStubFuncHandle_ = dlopen(sourceLibraryRealPath, RTLD_NOW);
178     if (migrateStubFuncHandle_ == nullptr) {
179         SLOGE("failed to dlopen library, reason: %{public}sn", dlerror());
180         return;
181     }
182     MigrateStubFunc startMigrateStub =
183         reinterpret_cast<MigrateStubFunc>(dlsym(migrateStubFuncHandle_, "StartMigrateStub"));
184     if (startMigrateStub == nullptr) {
185         SLOGE("failed to find library, reason: %{public}sn", dlerror());
186         return;
187     }
188     std::thread([startMigrateStub, this]() {
189         SLOGI("create thread to keep MigrateStub");
190         startMigrateStub([this](std::string deviceId, std::string serviceName, std::string extraInfo,
191             std::string state) { SuperLauncher(deviceId, serviceName, extraInfo, state); });
192     }).detach();
193 }
194 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)195 void AVSessionService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
196 {
197     switch (systemAbilityId) {
198         case MULTIMODAL_INPUT_SERVICE_ID:
199             InitKeyEvent();
200             break;
201         case AUDIO_POLICY_SERVICE_ID:
202             InitAudio();
203             break;
204         case APP_MGR_SERVICE_ID:
205             InitAMS();
206             break;
207         case DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID:
208             InitDM();
209             break;
210         case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID:
211             InitBMS();
212             break;
213         case CAST_ENGINE_SA_ID:
214             CheckInitCast();
215             break;
216         default:
217             SLOGE("undefined system ability %{public}d", systemAbilityId);
218     }
219 }
220 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)221 void AVSessionService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
222 {
223     if (systemAbilityId == CAST_ENGINE_SA_ID) {
224         SLOGE("on cast engine remove ability");
225         isInCast_ = false;
226     }
227 }
228 
CheckInitCast()229 void AVSessionService::CheckInitCast()
230 {
231 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
232     SLOGI("AVSessionService CheckInitCast in");
233     sptr<ISystemAbilityManager> samgrProxy;
234     samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
235     if (samgrProxy == nullptr) {
236         SLOGE("AVSessionService CheckInitCast with samgrProxy null");
237         return;
238     }
239     if (samgrProxy->CheckSystemAbility(CAST_ENGINE_SA_ID) == nullptr) {
240         SLOGI("check cast engine has been removed");
241     } else {
242         SLOGI("check cast engine has been started");
243     }
244 #endif
245 }
246 
InitKeyEvent()247 void AVSessionService::InitKeyEvent()
248 {
249     SLOGI("enter");
250     std::vector<int32_t> keyCodes = {
251         MMI::KeyEvent::KEYCODE_MEDIA_PLAY_PAUSE,
252         MMI::KeyEvent::KEYCODE_MEDIA_STOP,
253         MMI::KeyEvent::KEYCODE_MEDIA_NEXT,
254         MMI::KeyEvent::KEYCODE_MEDIA_PREVIOUS,
255         MMI::KeyEvent::KEYCODE_MEDIA_REWIND,
256         MMI::KeyEvent::KEYCODE_MEDIA_FAST_FORWARD,
257         MMI::KeyEvent::KEYCODE_HEADSETHOOK,
258     };
259 
260     KeyEventAdapter::GetInstance().SubscribeKeyEvent(
261         keyCodes, [this](const auto& keyEvent) { SendSystemAVKeyEvent(*keyEvent); });
262 }
263 
UpdateTopSession(const sptr<AVSessionItem> & newTopSession)264 void AVSessionService::UpdateTopSession(const sptr<AVSessionItem>& newTopSession)
265 {
266     if (newTopSession == nullptr) {
267         std::lock_guard lockGuard(sessionAndControllerLock_);
268         if (topSession_ != nullptr) {
269             topSession_->SetTop(false);
270         }
271         topSession_ = nullptr;
272         SLOGI("set topSession to nullptr");
273         HISYSEVENT_BEHAVIOR("FOCUS_CHANGE", "DETAILED_MSG", "avsessionservice set topsession to nullptr");
274         return;
275     }
276 
277     SLOGI("uid=%{public}d sessionId=%{public}s", newTopSession->GetUid(),
278         AVSessionUtils::GetAnonySessionId(newTopSession->GetSessionId()).c_str());
279     AVSessionDescriptor descriptor;
280     {
281         std::lock_guard lockGuard(sessionAndControllerLock_);
282         if (topSession_ != nullptr) {
283             topSession_->SetTop(false);
284             HISYSEVENT_BEHAVIOR("FOCUS_CHANGE",
285                 "OLD_BUNDLE_NAME", topSession_->GetDescriptor().elementName_.GetBundleName(),
286                 "OLD_MODULE_NAME", topSession_->GetDescriptor().elementName_.GetModuleName(),
287                 "OLD_ABILITY_NAME", topSession_->GetAbilityName(), "OLD_SESSION_PID", topSession_->GetPid(),
288                 "OLD_SESSION_UID", topSession_->GetUid(), "OLD_SESSION_ID", topSession_->GetSessionId(),
289                 "OLD_SESSION_TAG", topSession_->GetDescriptor().sessionTag_,
290                 "OLD_SESSION_TYPE", topSession_->GetDescriptor().sessionType_,
291                 "BUNDLE_NAME", newTopSession->GetDescriptor().elementName_.GetBundleName(),
292                 "MODULE_NAME", newTopSession->GetDescriptor().elementName_.GetModuleName(),
293                 "ABILITY_NAME", newTopSession->GetAbilityName(), "SESSION_PID", newTopSession->GetPid(),
294                 "SESSION_UID", newTopSession->GetUid(), "SESSION_ID", newTopSession->GetSessionId(),
295                 "SESSION_TAG", newTopSession->GetDescriptor().sessionTag_,
296                 "SESSION_TYPE", newTopSession->GetDescriptor().sessionType_,
297                 "DETAILED_MSG", "avsessionservice handlefocussession, updatetopsession");
298         }
299         topSession_ = newTopSession;
300         topSession_->SetTop(true);
301         descriptor = topSession_->GetDescriptor();
302     }
303     NotifyTopSessionChanged(descriptor);
304 }
305 
HandleFocusSession(const FocusSessionStrategy::FocusSessionChangeInfo & info)306 void AVSessionService::HandleFocusSession(const FocusSessionStrategy::FocusSessionChangeInfo& info)
307 {
308     std::lock_guard lockGuard(sessionAndControllerLock_);
309     if (topSession_ && topSession_->GetUid() == info.uid) {
310         SLOGI("same session");
311         if (topSession_->GetSessionType() == "audio") {
312             AVSessionService::NotifySystemUI(nullptr);
313         }
314         return;
315     }
316     for (const auto& session : GetContainer().GetAllSessions()) {
317         if (session->GetUid() == info.uid) {
318             UpdateTopSession(session);
319             if (topSession_->GetSessionType() == "audio") {
320                 AVSessionService::NotifySystemUI(nullptr);
321             }
322             return;
323         }
324     }
325 }
326 
RefreshFocusSessionSort(sptr<AVSessionItem> & session)327 void AVSessionService::RefreshFocusSessionSort(sptr<AVSessionItem> &session)
328 {
329     std::lock_guard sortFileLockGuard(sortFileReadWriteLock_);
330     std::string oldSortContent;
331     if (!LoadStringFromFileEx(AVSESSION_FILE_DIR + SORT_FILE_NAME, oldSortContent)) {
332         SLOGE("SelectFocusSession read sort fail !");
333         return;
334     }
335     nlohmann::json values = json::parse(oldSortContent, nullptr, false);
336     CHECK_AND_RETURN_LOG(!values.is_discarded(), "json object is null");
337     bool sessionExist = false;
338     for (auto value : values) {
339         if (session->GetBundleName() == value["bundleName"] &&
340             session->GetAbilityName() == value["abilityName"]) {
341             values.erase(std::remove(values.begin(), values.end(), value));
342             sessionExist = true;
343             break;
344         }
345     }
346     if (sessionExist) {
347         SLOGI("SelectFocusSession sessionExist, change order");
348         if (values.size() >= (size_t)maxHistoryNums) {
349             values.erase(values.end() - 1);
350         }
351         nlohmann::json value;
352         value["sessionId"] = session->GetSessionId();
353         value["bundleName"] = session->GetBundleName();
354         value["abilityName"] = session->GetAbilityName();
355         value["sessionType"] = session->GetSessionType();
356         if (values.size() <= 0) {
357             values.push_back(value);
358         } else {
359             values.insert(values.begin(), value);
360         }
361     }
362 
363     std::string newSortContent = values.dump();
364     SLOGD("SelectFocusSession::Dump json object finished");
365     if (!SaveStringToFileEx(AVSESSION_FILE_DIR + SORT_FILE_NAME, newSortContent)) {
366         SLOGE("SelectFocusSession save sort fail !");
367     }
368 }
369 
370 
SelectFocusSession(const FocusSessionStrategy::FocusSessionChangeInfo & info)371 bool AVSessionService::SelectFocusSession(const FocusSessionStrategy::FocusSessionChangeInfo& info)
372 {
373     for (auto& session : GetContainer().GetAllSessions()) {
374         if (session->GetDescriptor().sessionTag_ == "RemoteCast") {
375             SLOGI("Remote sessions do not need to be saved to history");
376             continue;
377         }
378         if (session->GetUid() != info.uid) {
379             continue;
380         }
381         GetContainer().UpdateSessionSort(session);
382         RefreshFocusSessionSort(session);
383         return true;
384     }
385     return false;
386 }
387 
InitAudio()388 void AVSessionService::InitAudio()
389 {
390     SLOGI("enter");
391     AudioAdapter::GetInstance().Init();
392     focusSessionStrategy_.Init();
393     focusSessionStrategy_.RegisterFocusSessionChangeCallback([this] (const auto& info) {
394         HandleFocusSession(info);
395     });
396     focusSessionStrategy_.RegisterFocusSessionSelector([this] (const auto& info) {
397         return SelectFocusSession(info);
398     });
399     AudioAdapter::GetInstance().AddStreamRendererStateListener([this] (const AudioRendererChangeInfos& infos) {
400         OutputDeviceChangeListener(infos);
401     });
402     AudioAdapter::GetInstance().AddDeviceChangeListener([this] (const DeviceChangeAction& deviceChangeAction) {
403         HandleDeviceChange(deviceChangeAction);
404     });
405 }
406 
SelectSessionByUid(const AudioRendererChangeInfo & info)407 sptr <AVSessionItem> AVSessionService::SelectSessionByUid(const AudioRendererChangeInfo& info)
408 {
409     for (const auto& session : GetContainer().GetAllSessions()) {
410         if (session->GetUid() == info.clientUID) {
411             return session;
412         }
413     }
414     SLOGI("has no session");
415     return nullptr;
416 }
417 
OutputDeviceChangeListener(const AudioRendererChangeInfos & infos)418 void AVSessionService::OutputDeviceChangeListener(const AudioRendererChangeInfos& infos)
419 {
420     for (const auto& info : infos) {
421         SLOGD("clientUID  is %{public}d, rendererState is %{public}d, deviceId is %{public}d", info->clientUID,
422               static_cast<int32_t>(info->rendererState), info->outputDeviceInfo.deviceId);
423     }
424 }
425 
InitAMS()426 void AVSessionService::InitAMS()
427 {
428     SLOGI("enter");
429     AppManagerAdapter::GetInstance().Init();
430 }
431 
InitDM()432 void AVSessionService::InitDM()
433 {
434     SLOGI("enter");
435     auto callback = std::make_shared<AVSessionInitDMCallback>();
436     CHECK_AND_RETURN_LOG(callback != nullptr, "no memory");
437     int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().InitDeviceManager("av_session", callback);
438     CHECK_AND_RETURN_LOG(ret == 0, "InitDeviceManager error ret is %{public}d", ret);
439 }
440 
InitBMS()441 void AVSessionService::InitBMS()
442 {
443     std::lock_guard sortFileLockGuard(sortFileReadWriteLock_);
444     SLOGI("enter");
445     BundleStatusAdapter::GetInstance().Init();
446     std::string oldSortContent;
447     if (LoadStringFromFileEx(AVSESSION_FILE_DIR + SORT_FILE_NAME, oldSortContent)) {
448         nlohmann::json values = json::parse(oldSortContent, nullptr, false);
449         CHECK_AND_RETURN_LOG(!values.is_discarded(), "json object is null");
450         auto callback = [this](std::string bundleName) {
451             DeleteAVQueueInfoRecord(bundleName);
452             DeleteHistoricalRecord(bundleName);
453         };
454         for (auto value : values) {
455             if (!BundleStatusAdapter::GetInstance().SubscribeBundleStatusEvent(value["bundleName"], callback)) {
456                 std::string bundleName = value["bundleName"];
457                 SLOGE("SubscribeBundleStatusEvent failed for bundle:%{public}s", bundleName.c_str());
458             }
459         }
460     }
461 }
462 
GetContainer()463 SessionContainer& AVSessionService::GetContainer()
464 {
465     static SessionStack sessionStack;
466     return sessionStack;
467 }
468 
AllocSessionId()469 std::string AVSessionService::AllocSessionId()
470 {
471     auto curNum = sessionSeqNum_++;
472     std::string id = std::to_string(GetCallingPid()) + "-" + std::to_string(GetCallingUid()) + "-" +
473                      std::to_string(curNum);
474     SLOGI("%{public}s", id.c_str());
475 
476     HashCalculator hashCalculator;
477     CHECK_AND_RETURN_RET_LOG(hashCalculator.Init() == AVSESSION_SUCCESS, "", "hash init failed");
478     CHECK_AND_RETURN_RET_LOG(hashCalculator.Update(std::vector<uint8_t>(id.begin(), id.end())) == AVSESSION_SUCCESS,
479                              "", "hash update failed");
480     std::vector<uint8_t> hash;
481     CHECK_AND_RETURN_RET_LOG(hashCalculator.GetResult(hash) == AVSESSION_SUCCESS, "", "hash get result failed");
482 
483     std::stringstream stream;
484     for (const auto byte : hash) {
485         stream << std::uppercase << std::hex << std::setfill('0') << std::setw(allocSpace) << static_cast<int>(byte);
486     }
487     return stream.str();
488 }
489 
AbilityHasSession(pid_t pid)490 bool AVSessionService::AbilityHasSession(pid_t pid)
491 {
492     std::lock_guard lockGuard(sessionAndControllerLock_);
493     return GetContainer().PidHasSession(pid);
494 }
495 
GetPresentController(pid_t pid,const std::string & sessionId)496 sptr<AVControllerItem> AVSessionService::GetPresentController(pid_t pid, const std::string& sessionId)
497 {
498     std::lock_guard lockGuard(sessionAndControllerLock_);
499     auto it = controllers_.find(pid);
500     if (it != controllers_.end()) {
501         for (const auto& controller: it->second) {
502             if (controller->HasSession(sessionId)) {
503                 return controller;
504             }
505         }
506     }
507     SLOGI("not found");
508     return nullptr;
509 }
510 
NotifySessionCreate(const AVSessionDescriptor & descriptor)511 void AVSessionService::NotifySessionCreate(const AVSessionDescriptor& descriptor)
512 {
513     std::lock_guard lockGuard(sessionListenersLock_);
514     for (const auto& listener : innerSessionListeners_) {
515         listener->OnSessionCreate(descriptor);
516     }
517     for (const auto& [pid, listener] : sessionListeners_) {
518         AVSESSION_TRACE_SYNC_START("AVSessionService::OnSessionCreate");
519         listener->OnSessionCreate(descriptor);
520     }
521 }
522 
NotifySessionRelease(const AVSessionDescriptor & descriptor)523 void AVSessionService::NotifySessionRelease(const AVSessionDescriptor& descriptor)
524 {
525     std::lock_guard lockGuard(sessionListenersLock_);
526     for (const auto& listener : innerSessionListeners_) {
527         listener->OnSessionRelease(descriptor);
528     }
529     for (const auto& [pid, listener] : sessionListeners_) {
530         listener->OnSessionRelease(descriptor);
531     }
532 }
533 
NotifyTopSessionChanged(const AVSessionDescriptor & descriptor)534 void AVSessionService::NotifyTopSessionChanged(const AVSessionDescriptor& descriptor)
535 {
536     std::lock_guard lockGuard(sessionListenersLock_);
537     for (const auto& listener : innerSessionListeners_) {
538         listener->OnTopSessionChange(descriptor);
539     }
540     for (const auto& [pid, listener] : sessionListeners_) {
541         AVSESSION_TRACE_SYNC_START("AVSessionService::OnTopSessionChange");
542         listener->OnTopSessionChange(descriptor);
543     }
544 }
545 
NotifyAudioSessionCheck(const int32_t uid)546 void AVSessionService::NotifyAudioSessionCheck(const int32_t uid)
547 {
548     SLOGI("Start searching for the corresponding callback");
549     std::lock_guard lockGuard(sessionListenersLock_);
550     for (const auto& listener : innerSessionListeners_) {
551         SLOGI("Found inner session listener");
552         listener->OnAudioSessionChecked(uid);
553     }
554     for (const auto& [pid, listener] : sessionListeners_) {
555         SLOGI("Found session listener with pid");
556         AVSESSION_TRACE_SYNC_START("AVSessionService::OnAudioSessionCheck");
557         listener->OnAudioSessionChecked(uid);
558     }
559 }
560 
561 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
562 
checkEnableCast(bool enable)563 void AVSessionService::checkEnableCast(bool enable)
564 {
565     SLOGI("checkEnableCast enable:%{public}d, isInCast:%{public}d", enable, isInCast_);
566     if (enable == true && isInCast_ == false) {
567         isInCast_ = true;
568         AVRouter::GetInstance().Init(this);
569     } else if (enable == false && isInCast_ == true) {
570         isInCast_ = AVRouter::GetInstance().Release();
571     } else {
572         SLOGD("AVRouter Init in nothing change");
573     }
574     return AVSESSION_SUCCESS;
575 }
576 
ReleaseCastSession()577 void AVSessionService::ReleaseCastSession()
578 {
579     SLOGI("Start release cast session");
580     for (const auto& session : GetContainer().GetAllSessions()) {
581         if (session->GetDescriptor().sessionTag_ == "RemoteCast") {
582             std::string sessionId = session->GetDescriptor().sessionId_;
583             SLOGI("Already has a cast session %{public}s", AVSessionUtils::GetAnonySessionId(sessionId).c_str());
584             UpdateTopSession(nullptr);
585             auto session = GetContainer().RemoveSession(sessionId);
586             session->UnRegisterDeviceStateCallback();
587             session->StopCastSession();
588             session->ReleaseAVCastControllerInner();
589             session->Destroy();
590         }
591     }
592 }
593 
CreateSessionByCast(const int64_t castHandle)594 void AVSessionService::CreateSessionByCast(const int64_t castHandle)
595 {
596     SLOGI("AVSessionService CreateSessionByCast in");
597     if (isSourceInCast_) {
598         SLOGI("Create Cast in source, return");
599         return;
600     }
601     AppExecFwk::ElementName elementName;
602     elementName.SetBundleName("castBundleName");
603     elementName.SetAbilityName("castAbilityName");
604     sptr<AVSessionItem> sinkSession = CreateSessionInner("RemoteCast",
605         AVSession::SESSION_TYPE_AUDIO, false, elementName);
606     CHECK_AND_RETURN_LOG(sinkSession != nullptr, "CreateSession at sink failed");
607     SLOGI("Create Cast sink sessionId %{public}s",
608         AVSessionUtils::GetAnonySessionId(sinkSession->GetSessionId()).c_str());
609     sinkSession->SetCastHandle(castHandle);
610     sinkSession->RegisterDeviceStateCallback();
611 
612     HISYSEVENT_BEHAVIOR("SESSION_CAST",
613         "BUNDLE_NAME", "castBundleName",
614         "ABILITY_NAME", "castAbilityName",
615         "SESSION_PID", sinkSession->GetDescriptor().pid_,
616         "SESSION_UID", sinkSession->GetDescriptor().uid_,
617         "SESSION_ID", sinkSession->GetDescriptor().sessionId_,
618         "SESSION_TAG", sinkSession->GetDescriptor().sessionTag_,
619         "SESSION_TYPE", sinkSession->GetDescriptor().sessionType_,
620         "DETAILED_MSG", "session create from cast+ callback");
621 }
622 
NotifyDeviceAvailable(const OutputDeviceInfo & castOutputDeviceInfo)623 void AVSessionService::NotifyDeviceAvailable(const OutputDeviceInfo& castOutputDeviceInfo)
624 {
625     for (DeviceInfo deviceInfo : castOutputDeviceInfo.deviceInfos_) {
626         std::lock_guard lockGuard(castDeviceInfoMapLock_);
627         castDeviceInfoMap_[deviceInfo.deviceId_] = deviceInfo;
628         for (const auto& session : GetContainer().GetAllSessions()) {
629             session->UpdateCastDeviceMap(deviceInfo);
630         }
631     }
632     std::lock_guard lockGuard(sessionListenersLock_);
633     for (const auto& listener : innerSessionListeners_) {
634         listener->OnDeviceAvailable(castOutputDeviceInfo);
635     }
636     for (const auto& [pid, listener] : sessionListeners_) {
637         AVSESSION_TRACE_SYNC_START("AVSessionService::OnDeviceAvailable");
638         listener->OnDeviceAvailable(castOutputDeviceInfo);
639     }
640 }
641 
NotifyDeviceOffline(const std::string & deviceId)642 void AVSessionService::NotifyDeviceOffline(const std::string& deviceId)
643 {
644     std::lock_guard lockGuard(sessionListenersLock_);
645     for (const auto& listener : innerSessionListeners_) {
646         listener->OnDeviceOffline(deviceId);
647     }
648     for (const auto& [pid, listener] : sessionListeners_) {
649         AVSESSION_TRACE_SYNC_START("AVSessionService::OnDeviceOffline");
650         listener->OnDeviceOffline(deviceId);
651     }
652 }
653 
StartCast(const SessionToken & sessionToken,const OutputDeviceInfo & outputDeviceInfo)654 int32_t AVSessionService::StartCast(const SessionToken& sessionToken, const OutputDeviceInfo& outputDeviceInfo)
655 {
656     SLOGI("SessionId is %{public}s", AVSessionUtils::GetAnonySessionId(sessionToken.sessionId).c_str());
657     if (!PermissionChecker::GetInstance().CheckSystemPermission()) {
658         SLOGE("StartCast: CheckSystemPermission failed");
659         HISYSEVENT_SECURITY("CONTROL_PERMISSION_DENIED", "CALLER_UID", GetCallingUid(), "CALLER_PID", GetCallingPid(),
660             "ERROR_MSG", "avsessionservice StartCast checksystempermission failed");
661         return ERR_NO_PERMISSION;
662     }
663 
664     sptr<AVSessionItem> session = GetContainer().GetSessionById(sessionToken.sessionId);
665     CHECK_AND_RETURN_RET_LOG(session != nullptr, ERR_SESSION_NOT_EXIST, "session %{public}s not exist",
666         AVSessionUtils::GetAnonySessionId(sessionToken.sessionId).c_str());
667 
668     int32_t ret = session->StartCast(outputDeviceInfo);
669     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "StartCast failed");
670     SLOGD("StartCast set isSourceInCast");
671     isSourceInCast_ = true;
672 
673 #ifdef EFFICIENCY_MANAGER_ENABLE
674     int32_t uid = session->GetDescriptor().uid_;
675     int32_t pid = session->GetDescriptor().pid_;
676     std::string bundleName = BundleStatusAdapter::GetInstance().GetBundleNameFromUid(uid);
677     CHECK_AND_RETURN_RET_LOG(bundleName != "", AVSESSION_ERROR, "GetBundleNameFromUid failed");
678 
679     char sourceLibraryRealPath[PATH_MAX] = { 0x00 };
680     if (realpath(SOURCE_LIBRARY_PATH.c_str(), sourceLibraryRealPath) == nullptr) {
681         SLOGE("check libsuspend_manager_client path failed %{public}s", SOURCE_LIBRARY_PATH.c_str());
682         return AVSESSION_ERROR;
683     }
684     void *handle_ = dlopen(sourceLibraryRealPath, RTLD_NOW);
685     if (handle_ == nullptr) {
686         SLOGE("failed to open library libsuspend_manager_client reaseon %{public}s", dlerror());
687         return AVSESSION_ERROR;
688     }
689     SLOGI("open library libsuspend_manager_client success");
690     typedef ErrCode (*handler) (int32_t eventType, int32_t uid, int32_t pid,
691         const std::string bundleName, int32_t taskState, int32_t serviceId);
692     handler reportContinuousTaskEventEx = reinterpret_cast<handler>(dlsym(handle_, "ReportContinuousTaskEventEx"));
693     ErrCode errCode = reportContinuousTaskEventEx(0, uid, pid, bundleName, 1, AVSESSION_SERVICE_ID);
694     SLOGI("reportContinuousTaskEventEx done, result: %{public}d", errCode);
695     dlclose(handle_);
696 #endif
697     HISYSEVENT_BEHAVIOR("SESSION_CAST",
698         "BUNDLE_NAME", session->GetDescriptor().elementName_.GetBundleName(),
699         "MODULE_NAME", session->GetDescriptor().elementName_.GetModuleName(),
700         "ABILITY_NAME", session->GetDescriptor().elementName_.GetAbilityName(),
701         "SESSION_PID", session->GetDescriptor().pid_, "SESSION_UID", session->GetDescriptor().uid_,
702         "SESSION_ID", session->GetDescriptor().sessionId_, "SESSION_TAG", session->GetDescriptor().sessionTag_,
703         "SESSION_TYPE", session->GetDescriptor().sessionType_, "DETAILED_MSG", "start cast session");
704     return AVSESSION_SUCCESS;
705 }
706 
StopCast(const SessionToken & sessionToken)707 int32_t AVSessionService::StopCast(const SessionToken& sessionToken)
708 {
709     if (!PermissionChecker::GetInstance().CheckSystemPermission()) {
710         SLOGE("StopCast: CheckSystemPermission failed");
711         HISYSEVENT_SECURITY("CONTROL_PERMISSION_DENIED", "CALLER_UID", GetCallingUid(), "CALLER_PID", GetCallingPid(),
712             "ERROR_MSG", "avsessionservice StopCast checksystempermission failed");
713         return ERR_NO_PERMISSION;
714     }
715 
716     sptr<AVSessionItem> session = GetContainer().GetSessionById(sessionToken.sessionId);
717     CHECK_AND_RETURN_RET_LOG(session != nullptr, AVSESSION_SUCCESS, "StopCast: session is not exist");
718     CHECK_AND_RETURN_RET_LOG(session->StopCast() == AVSESSION_SUCCESS, AVSESSION_ERROR, "StopCast failed");
719     if (session->GetDescriptor().sessionTag_ == "RemoteCast") {
720         SLOGI("Stop cast at sink, start destroy sink avsession");
721         session->Destroy();
722         return AVSESSION_SUCCESS;
723     }
724 
725 #ifdef EFFICIENCY_MANAGER_ENABLE
726     SLOGI("Stop register continuous task");
727     int32_t uid = session->GetDescriptor().uid_;
728     int32_t pid = session->GetDescriptor().pid_;
729     std::string bundleName = BundleStatusAdapter::GetInstance().GetBundleNameFromUid(uid);
730     CHECK_AND_RETURN_RET_LOG(bundleName != "", AVSESSION_ERROR, "GetBundleNameFromUid failed");
731 
732     char sourceLibraryRealPath[PATH_MAX] = { 0x00 };
733     if (realpath(SOURCE_LIBRARY_PATH.c_str(), sourceLibraryRealPath) == nullptr) {
734         SLOGE("check libsuspend_manager_client path failed %{public}s when stop cast", SOURCE_LIBRARY_PATH.c_str());
735         return AVSESSION_ERROR;
736     }
737     void *handle_ = dlopen(sourceLibraryRealPath, RTLD_NOW);
738     if (handle_ == nullptr) {
739         SLOGE("failed to open library libsuspend_manager_client when stop cast, reaseon %{public}s", dlerror());
740         return AVSESSION_ERROR;
741     }
742     SLOGI("open library libsuspend_manager_client success when stop cast");
743     typedef ErrCode (*handler) (int32_t eventType, int32_t uid, int32_t pid,
744         const std::string bundleName, int32_t taskState, int32_t serviceId);
745     handler reportContinuousTaskEventEx = reinterpret_cast<handler>(dlsym(handle_, "ReportContinuousTaskEventEx"));
746     ErrCode errCode = reportContinuousTaskEventEx(0, uid, pid, bundleName, 2, AVSESSION_SERVICE_ID);
747     SLOGI("reportContinuousTaskEventEx done when stop cast, result: %{public}d", errCode);
748     dlclose(handle_);
749 #endif
750     return AVSESSION_SUCCESS;
751 }
752 #endif
753 
HandleCallStartEvent()754 void AVSessionService::HandleCallStartEvent()
755 {
756     SLOGI("Start handle CallStartEvent");
757     AbilityConnectHelper::GetInstance().StartAbilityForegroundByCall(MEDIA_CONTROL_BUNDLENAME,
758         MEDIA_CONTROL_ABILITYNAME);
759 }
760 
CreateNewSession(const std::string & tag,int32_t type,bool thirdPartyApp,const AppExecFwk::ElementName & elementName)761 sptr<AVSessionItem> AVSessionService::CreateNewSession(const std::string& tag, int32_t type, bool thirdPartyApp,
762                                                        const AppExecFwk::ElementName& elementName)
763 {
764     SLOGI("%{public}s %{public}d %{public}s %{public}s", tag.c_str(), type,
765           elementName.GetBundleName().c_str(), elementName.GetAbilityName().c_str());
766     AVSessionDescriptor descriptor;
767     descriptor.sessionId_ = AllocSessionId();
768     if (descriptor.sessionId_.empty()) {
769         SLOGE("alloc session id failed");
770         return nullptr;
771     }
772     descriptor.sessionTag_ = tag;
773     descriptor.sessionType_ = type;
774     descriptor.elementName_ = elementName;
775     descriptor.isThirdPartyApp_ = thirdPartyApp;
776 
777     sptr<AVSessionItem> result = new(std::nothrow) AVSessionItem(descriptor);
778     if (result == nullptr) {
779         return nullptr;
780     }
781     result->SetPid(GetCallingPid());
782     result->SetUid(GetCallingUid());
783     result->SetServiceCallbackForRelease([this](AVSessionItem& session) {
784         SLOGI("Start handle session release event");
785         HandleSessionRelease(session.GetDescriptor().sessionId_);
786     });
787     result->SetServiceCallbackForAVQueueInfo([this](AVSessionItem& session) {
788         AddAvQueueInfoToFile(session);
789     });
790     result->SetServiceCallbackForCallStart([this](AVSessionItem& session) {
791         SLOGI("Start handle call start event for %{public}s",
792             AVSessionUtils::GetAnonySessionId(session.GetDescriptor().sessionId_).c_str());
793         HandleCallStartEvent();
794     });
795     SLOGI("success sessionId=%{public}s",  AVSessionUtils::GetAnonySessionId(result->GetSessionId()).c_str());
796     {
797         std::lock_guard lockGuard(sessionAndControllerLock_);
798         if (topSession_ == nullptr) {
799             UpdateTopSession(result);
800         }
801     }
802 
803     OutputDeviceInfo outputDeviceInfo;
804     DeviceInfo deviceInfo;
805     deviceInfo.castCategory_ = AVCastCategory::CATEGORY_LOCAL;
806     deviceInfo.deviceId_ = "0";
807     deviceInfo.deviceName_ = "LocalDevice";
808     outputDeviceInfo.deviceInfos_.emplace_back(deviceInfo);
809     result->SetOutputDevice(outputDeviceInfo);
810 
811     return result;
812 }
813 
CreateSessionInner(const std::string & tag,int32_t type,bool thirdPartyApp,const AppExecFwk::ElementName & elementName)814 sptr <AVSessionItem> AVSessionService::CreateSessionInner(const std::string& tag, int32_t type, bool thirdPartyApp,
815                                                           const AppExecFwk::ElementName& elementName)
816 {
817     SLOGI("CreateSessionInner enter");
818     CHECK_AND_RETURN_RET_LOG(!tag.empty(), nullptr, "tag is empty");
819     CHECK_AND_RETURN_RET_LOG(type == AVSession::SESSION_TYPE_AUDIO || type == AVSession::SESSION_TYPE_VIDEO
820         || type == AVSession::SESSION_TYPE_VOICE_CALL, nullptr, "type is invalid");
821     CHECK_AND_RETURN_RET_LOG(!elementName.GetBundleName().empty() && !elementName.GetAbilityName().empty(),
822         nullptr, "element is invalid");
823     std::regex nameRegex("[A-Za-z\\w\\.]*");
824     if (!std::regex_match(elementName.GetBundleName(), nameRegex)) {
825         SLOGE("CreateSessionInner err regex, bundleName=%{public}s", (elementName.GetBundleName()).c_str());
826         return nullptr;
827     }
828     if (!std::regex_match(elementName.GetAbilityName(), nameRegex)) {
829         SLOGE("CreateSessionInner err regex, abilityName=%{public}s", (elementName.GetAbilityName()).c_str());
830         return nullptr;
831     }
832     auto pid = GetCallingPid();
833     std::lock_guard lockGuard(sessionAndControllerLock_);
834     if (AbilityHasSession(pid)) {
835         SLOGI("process %{public}d %{public}s already has one session", pid, elementName.GetAbilityName().c_str());
836         return nullptr;
837     }
838 
839     auto result = CreateNewSession(tag, type, thirdPartyApp, elementName);
840     if (result == nullptr) {
841         SLOGE("create new session failed");
842         dumpHelper_->SetErrorInfo("  AVSessionService::CreateSessionInner  create new session failed");
843         HISYSEVENT_FAULT("CONTROL_COMMAND_FAILED", "CALLER_PID", pid, "TAG", tag, "TYPE", type, "BUNDLE_NAME",
844             elementName.GetBundleName(), "ERROR_MSG", "avsessionservice createsessioninner create new session failed");
845         return nullptr;
846     }
847     if (GetContainer().AddSession(pid, elementName.GetAbilityName(), result) != AVSESSION_SUCCESS) {
848         SLOGI("session num exceed max");
849         return nullptr;
850     }
851     HISYSEVENT_ADD_LIFE_CYCLE_INFO(elementName.GetBundleName(),
852         AppManagerAdapter::GetInstance().IsAppBackground(GetCallingUid()), type, true);
853 
854     NotifySessionCreate(result->GetDescriptor());
855     SLOGI("success");
856     return result;
857 }
858 
CreateSessionInner(const std::string & tag,int32_t type,const AppExecFwk::ElementName & elementName)859 sptr <IRemoteObject> AVSessionService::CreateSessionInner(const std::string& tag, int32_t type,
860                                                           const AppExecFwk::ElementName& elementName)
861 {
862     auto session = CreateSessionInner(tag, type, !PermissionChecker::GetInstance().CheckSystemPermission(),
863                                       elementName);
864     CHECK_AND_RETURN_RET_LOG(session != nullptr, session, "session is nullptr");
865 
866     std::string supportModule;
867     std::string profile;
868     if (BundleStatusAdapter::GetInstance().IsSupportPlayIntent(elementName.GetBundleName(), supportModule, profile) ||
869         DEFAULT_BUNDLE_NAME == elementName.GetBundleName()) {
870         SLOGI("bundleName=%{public}s support play intent, refreshSortFile", elementName.GetBundleName().c_str());
871         refreshSortFileOnCreateSession(session->GetSessionId(), session->GetSessionType(), elementName);
872     }
873 
874     {
875         std::lock_guard lockGuard1(abilityManagerLock_);
876         std::string bundleName = session->GetDescriptor().elementName_.GetBundleName();
877         std::string abilityName = session->GetDescriptor().elementName_.GetAbilityName();
878         auto it = abilityManager_.find(bundleName + abilityName);
879         if (it != abilityManager_.end()) {
880             it->second->StartAbilityByCallDone(session->GetDescriptor().sessionId_);
881         }
882     }
883 
884     {
885         std::lock_guard lockGuard(isAllSessionCastLock_);
886         SLOGI("isAllSessionCast_ is %{public}d", isAllSessionCast_);
887         CHECK_AND_RETURN_RET_LOG(isAllSessionCast_, session, "no need to cast");
888     }
889     CHECK_AND_RETURN_RET_LOG(CastAudioForNewSession(session) == AVSESSION_SUCCESS, session, "cast new session error");
890     return session;
891 }
892 
refreshSortFileOnCreateSession(const std::string & sessionId,const std::string & sessionType,const AppExecFwk::ElementName & elementName)893 void AVSessionService::refreshSortFileOnCreateSession(const std::string& sessionId, const std::string& sessionType,
894                                                       const AppExecFwk::ElementName& elementName)
895 {
896     std::lock_guard sortFileLockGuard(sortFileReadWriteLock_);
897     SLOGI("refresh sort when session created, bundleName=%{public}s", (elementName.GetBundleName()).c_str());
898     std::string oldSortContent;
899     if (LoadStringFromFileEx(AVSESSION_FILE_DIR + SORT_FILE_NAME, oldSortContent)) {
900         nlohmann::json values = json::parse(oldSortContent, nullptr, false);
901         CHECK_AND_RETURN_LOG(!values.is_discarded(), "sort json object is null");
902         if (oldSortContent.find(elementName.GetBundleName()) == string::npos) {
903             auto callback = [this](std::string bundleName) {
904                 DeleteAVQueueInfoRecord(bundleName);
905                 DeleteHistoricalRecord(bundleName);
906             };
907             if (!BundleStatusAdapter::GetInstance().SubscribeBundleStatusEvent(elementName.GetBundleName(), callback)) {
908                 SLOGE("SubscribeBundleStatusEvent failed");
909             }
910         }
911         for (auto value : values) {
912             if (elementName.GetBundleName() == value["bundleName"] &&
913                 elementName.GetAbilityName() == value["abilityName"]) {
914                 values.erase(std::remove(values.begin(), values.end(), value));
915             }
916         }
917         if (values.size() >= (size_t)maxHistoryNums) {
918             values.erase(values.end() - 1);
919         }
920         nlohmann::json value;
921         value["sessionId"] = sessionId;
922         value["bundleName"] = elementName.GetBundleName();
923         value["abilityName"] = elementName.GetAbilityName();
924         value["sessionType"] = sessionType;
925         if (values.size() <= 0) {
926             values.push_back(value);
927         } else {
928             values.insert(values.begin(), value);
929         }
930         std::string newSortContent = values.dump();
931         SLOGD("refreshSortFileOnCreateSession::Dump json object finished");
932         if (!SaveStringToFileEx(AVSESSION_FILE_DIR + SORT_FILE_NAME, newSortContent)) {
933             SLOGE("SaveStringToFile failed, filename=%{public}s", SORT_FILE_NAME);
934         }
935     } else {
936         SLOGE("LoadStringToFile failed, filename=%{public}s", SORT_FILE_NAME);
937     }
938 }
939 
GetAllSessionDescriptors(std::vector<AVSessionDescriptor> & descriptors)940 int32_t AVSessionService::GetAllSessionDescriptors(std::vector<AVSessionDescriptor>& descriptors)
941 {
942     if (!PermissionChecker::GetInstance().CheckSystemPermission()) {
943         SLOGE("GetAllSessionDescriptors: CheckSystemPermission failed");
944         HISYSEVENT_SECURITY("CONTROL_PERMISSION_DENIED", "CALLER_UID", GetCallingUid(), "CALLER_PID", GetCallingPid(),
945             "ERROR_MSG", "avsessionservice getallsessiondescriptors checksystempermission failed");
946         return ERR_NO_PERMISSION;
947     }
948 
949     std::lock_guard lockGuard(sessionAndControllerLock_);
950     std::lock_guard sortFileLockGuard(sortFileReadWriteLock_);
951 
952     std::string oldSortContent;
953     if (!LoadStringFromFileEx(AVSESSION_FILE_DIR + SORT_FILE_NAME, oldSortContent)) {
954         SLOGE("GetAllSessionDescriptors read sort fail! ");
955         for (const auto& session: GetContainer().GetAllSessions()) {
956             descriptors.push_back(session->GetDescriptor());
957         }
958         SLOGI("size=%{public}d", static_cast<int32_t>(descriptors.size()));
959         return AVSESSION_SUCCESS;
960     }
961     nlohmann::json values = json::parse(oldSortContent, nullptr, false);
962     CHECK_AND_RETURN_RET_LOG(!values.is_discarded(), AVSESSION_SUCCESS, "json object is null");
963     for (auto& value : values) {
964         auto session = GetContainer().GetSessionById(value["sessionId"]);
965         if (session != nullptr) {
966             descriptors.push_back(session->GetDescriptor());
967         }
968     }
969 
970     for (const auto& session: GetContainer().GetAllSessions()) {
971         bool duplicateSession = false;
972         for (const auto& desc: descriptors) {
973             if (desc.sessionId_ == session->GetSessionId()) {
974                 duplicateSession = true;
975                 break;
976             }
977         }
978         if (!duplicateSession) {
979             descriptors.push_back(session->GetDescriptor());
980         }
981     }
982     SLOGI("size=%{public}d", static_cast<int32_t>(descriptors.size()));
983     return AVSESSION_SUCCESS;
984 }
985 
GetSessionDescriptorsBySessionId(const std::string & sessionId,AVSessionDescriptor & descriptor)986 int32_t AVSessionService::GetSessionDescriptorsBySessionId(const std::string& sessionId,
987                                                            AVSessionDescriptor& descriptor)
988 {
989     std::lock_guard lockGuard(sessionAndControllerLock_);
990     sptr<AVSessionItem> session = GetContainer().GetSessionById(sessionId);
991     CHECK_AND_RETURN_RET_LOG(session != nullptr, AVSESSION_ERROR, "session not exist");
992 
993     SLOGI("find descriptor by id %{public}s",  AVSessionUtils::GetAnonySessionId(sessionId).c_str());
994     auto pid = GetCallingPid();
995     if (pid == session->GetPid()) {
996         descriptor = session->GetDescriptor();
997         return AVSESSION_SUCCESS;
998     }
999     if (!PermissionChecker::GetInstance().CheckSystemPermission()) {
1000         SLOGE("GetSessionDescriptorsBySessionId: CheckSystemPermission failed");
1001         HISYSEVENT_SECURITY("CONTROL_PERMISSION_DENIED", "CALLER_UID", GetCallingUid(),
1002             "CALLER_PID", pid, "SESSION_ID", sessionId,
1003             "ERROR_MSG", "avsessionservice getsessiondescriptors by sessionid checksystempermission failed");
1004         return ERR_NO_PERMISSION;
1005     }
1006     descriptor = session->GetDescriptor();
1007     return AVSESSION_SUCCESS;
1008 }
1009 
GetHistoricalSessionDescriptorsFromFile(std::vector<AVSessionDescriptor> & descriptors)1010 int32_t AVSessionService::GetHistoricalSessionDescriptorsFromFile(std::vector<AVSessionDescriptor>& descriptors)
1011 {
1012     std::string oldSortContent;
1013     if (!LoadStringFromFileEx(AVSESSION_FILE_DIR + SORT_FILE_NAME, oldSortContent)) {
1014         SLOGE("GetHistoricalSessionDescriptorsFromFile read sort fail, Return!");
1015         return AVSESSION_ERROR;
1016     }
1017 
1018     nlohmann::json sortValues = json::parse(oldSortContent, nullptr, false);
1019     CHECK_AND_RETURN_RET_LOG(!sortValues.is_discarded(), AVSESSION_ERROR, "json object is null");
1020     for (const auto& value : sortValues) {
1021         if (value["sessionType"] == "video") {
1022             SLOGI("GetHistoricalSessionDescriptorsFromFile with no video type session");
1023             continue;
1024         }
1025         AVSessionDescriptor descriptor;
1026         descriptor.sessionId_ = value["sessionId"];
1027         descriptor.elementName_.SetBundleName(value["bundleName"]);
1028         descriptor.elementName_.SetAbilityName(value["abilityName"]);
1029         descriptor.sessionType_ = AVSession::SESSION_TYPE_AUDIO;
1030         descriptors.push_back(descriptor);
1031     }
1032     if (descriptors.size() == 0 && GetContainer().GetAllSessions().size() == 0) {
1033         SLOGE("GetHistoricalSessionDescriptorsFromFile read empty, return default!");
1034         AVSessionDescriptor descriptor;
1035         descriptor.sessionId_ = DEFAULT_SESSION_ID;
1036         descriptor.elementName_.SetBundleName(DEFAULT_BUNDLE_NAME);
1037         descriptor.elementName_.SetAbilityName(DEFAULT_ABILITY_NAME);
1038         descriptor.sessionType_ = AVSession::SESSION_TYPE_AUDIO;
1039         descriptors.push_back(descriptor);
1040     }
1041     return AVSESSION_SUCCESS;
1042 }
1043 
GetHistoricalSessionDescriptors(int32_t maxSize,std::vector<AVSessionDescriptor> & descriptors)1044 int32_t AVSessionService::GetHistoricalSessionDescriptors(int32_t maxSize,
1045                                                           std::vector<AVSessionDescriptor>& descriptors)
1046 {
1047     if (!PermissionChecker::GetInstance().CheckSystemPermission()) {
1048         SLOGE("GetAllSessionDescriptors: CheckSystemPermission failed");
1049         HISYSEVENT_SECURITY("CONTROL_PERMISSION_DENIED", "CALLER_UID", GetCallingUid(), "CALLER_PID", GetCallingPid(),
1050             "ERROR_MSG", "avsessionservice GetHistoricalSessionDescriptors checksystempermission failed");
1051         return ERR_NO_PERMISSION;
1052     }
1053 
1054     std::lock_guard lockGuard(sessionAndControllerLock_);
1055     std::lock_guard sortFileLockGuard(sortFileReadWriteLock_);
1056 
1057     std::vector<AVSessionDescriptor> tempDescriptors;
1058     GetHistoricalSessionDescriptorsFromFile(tempDescriptors);
1059     if (maxSize < 0 || maxSize > maxHistoryNums) {
1060         maxSize = unSetHistoryNum;
1061     }
1062     for (auto iterator = tempDescriptors.begin(); iterator != tempDescriptors.end(); ++iterator) {
1063         if (descriptors.size() >= (size_t)maxSize) {
1064             break;
1065         }
1066         descriptors.push_back(*iterator);
1067     }
1068     SLOGI("get historical session size=%{public}d", static_cast<int>(descriptors.size()));
1069     return AVSESSION_SUCCESS;
1070 }
1071 
GetHistoricalAVQueueInfos(int32_t maxSize,int32_t maxAppSize,std::vector<AVQueueInfo> & avQueueInfos)1072 int32_t AVSessionService::GetHistoricalAVQueueInfos(int32_t maxSize, int32_t maxAppSize,
1073                                                     std::vector<AVQueueInfo>& avQueueInfos)
1074 {
1075     if (!PermissionChecker::GetInstance().CheckSystemPermission()) {
1076         SLOGE("GetHistoricalAVQueueInfos: CheckSystemPermission failed");
1077         HISYSEVENT_SECURITY("CONTROL_PERMISSION_DENIED", "CALLER_UID", GetCallingUid(), "CALLER_PID", GetCallingPid(),
1078             "ERROR_MSG", "avsessionservice GetHistoricalAVQueueInfos checksystempermission failed");
1079         return ERR_NO_PERMISSION;
1080     }
1081 
1082     std::lock_guard avQueueFileLockGuard(avQueueFileReadWriteLock_);
1083     std::string oldAVQueueInfoContent;
1084     std::vector<AVQueueInfo> tempAVQueueInfos;
1085     if (!LoadStringFromFileEx(AVSESSION_FILE_DIR + AVQUEUE_FILE_NAME, oldAVQueueInfoContent)) {
1086         SLOGE("GetHistoricalAVQueueInfos read avqueueinfo fail, Return!");
1087         return AVSESSION_ERROR;
1088     }
1089 
1090     nlohmann::json avQueueValues = json::parse(oldAVQueueInfoContent, nullptr, false);
1091     CHECK_AND_RETURN_RET_LOG(!avQueueValues.is_discarded(), AVSESSION_ERROR, "json object is null");
1092     for (const auto& value : avQueueValues) {
1093         AVQueueInfo avQueueInfo;
1094         avQueueInfo.SetBundleName(value["bundleName"]);
1095         avQueueInfo.SetAVQueueName(value["avQueueName"]);
1096         avQueueInfo.SetAVQueueId(value["avQueueId"]);
1097         std::shared_ptr<AVSessionPixelMap> avQueuePixelMap = std::make_shared<AVSessionPixelMap>();
1098         AVSessionUtils::ReadImageFromFile(avQueuePixelMap, value["avQueueImage"]);
1099         avQueueInfo.SetAVQueueImage(avQueuePixelMap);
1100         avQueueInfo.SetAVQueueImageUri(value["avQueueImageUri"]);
1101         tempAVQueueInfos.push_back(avQueueInfo);
1102     }
1103     for (auto iterator = tempAVQueueInfos.begin(); iterator != tempAVQueueInfos.end(); ++iterator) {
1104         avQueueInfos.push_back(*iterator);
1105     }
1106     SLOGI("get historical avqueueinfo size=%{public}d", static_cast<int>(avQueueInfos.size()));
1107     return AVSESSION_SUCCESS;
1108 }
1109 
SaveAvQueueInfo(std::string & oldContent,const std::string & bundleName,const AVMetaData & meta)1110 bool AVSessionService::SaveAvQueueInfo(std::string& oldContent, const std::string &bundleName, const AVMetaData& meta)
1111 {
1112     nlohmann::json values = json::parse(oldContent, nullptr, false);
1113     CHECK_AND_RETURN_RET_LOG(!values.is_discarded(), false, "avQueue json object is null");
1114     auto it = values.begin();
1115     for (auto& value : values) {
1116         if (bundleName == value["bundleName"] && meta.GetAVQueueId() == value["avQueueId"]) {
1117             if (meta.GetAVQueueId() == it->at("avQueueId")) {
1118                 SLOGI("SaveAvQueueInfo avqueue=%{public}s is first, return", meta.GetAVQueueId().c_str());
1119                 return false;
1120             }
1121             values.erase(std::remove(values.begin(), values.end(), value));
1122         }
1123     }
1124     if (values.size() >= (size_t)maxAVQueueInfoLen) {
1125         values.erase(values.end() - 1);
1126     }
1127 
1128     nlohmann::json value;
1129     value["bundleName"] = bundleName;
1130     value["avQueueName"] = meta.GetAVQueueName();
1131     value["avQueueId"] = meta.GetAVQueueId();
1132     std::shared_ptr<AVSessionPixelMap> innerPixelMap = meta.GetAVQueueImage();
1133     if (innerPixelMap != nullptr) {
1134         std::string fileName = AVSessionUtils::GetFixedPathName() + bundleName + "_" +
1135             meta.GetAVQueueId() + AVSessionUtils::GetFileSuffix();
1136         AVSessionUtils::WriteImageToFile(innerPixelMap, fileName);
1137         innerPixelMap->Clear();
1138         value["avQueueImage"] = fileName;
1139     } else {
1140         value["avQueueImage"] = "";
1141     }
1142     value["avQueueImageUri"] = meta.GetAVQueueImageUri();
1143     if (values.size() <= 0) {
1144         values.push_back(value);
1145     } else {
1146         values.insert(values.begin(), value);
1147     }
1148     std::string newContent = values.dump();
1149     SLOGD("SaveAvQueueInfo::Dump json object finished");
1150     if (!SaveStringToFileEx(AVSESSION_FILE_DIR + AVQUEUE_FILE_NAME, newContent)) {
1151         SLOGE("SaveStringToFile failed, filename=%{public}s", AVQUEUE_FILE_NAME);
1152         return false;
1153     }
1154     return true;
1155 }
1156 
AddAvQueueInfoToFile(AVSessionItem & session)1157 void AVSessionService::AddAvQueueInfoToFile(AVSessionItem& session)
1158 {
1159     SLOGD("add queueinfo to file in");
1160     // check is this session support playmusiclist intent
1161     std::lock_guard lockGuard(sessionAndControllerLock_);
1162     std::string bundleName = session.GetBundleName();
1163     std::string supportModule;
1164     std::string profile;
1165     if (!BundleStatusAdapter::GetInstance().IsSupportPlayIntent(bundleName, supportModule, profile)) {
1166         SLOGE("bundleName=%{public}s does not support play intent", bundleName.c_str());
1167         return;
1168     }
1169     AVMetaData meta = session.GetMetaData();
1170     if (meta.GetAVQueueId().empty() || meta.GetAVQueueName().empty()) {
1171         SLOGI("AddAvQueueInfoToFile avqueueinfo empty, return");
1172         return;
1173     }
1174     std::lock_guard avQueueFileLockGuard(avQueueFileReadWriteLock_);
1175     std::string oldContent;
1176     if (!LoadStringFromFileEx(AVSESSION_FILE_DIR + AVQUEUE_FILE_NAME, oldContent)) {
1177         SLOGE("AddAvQueueInfoToFile read avqueueinfo fail, Return!");
1178         return;
1179     }
1180     if (!SaveAvQueueInfo(oldContent, bundleName, meta)) {
1181         SLOGE("SaveAvQueueInfo same avqueueinfo, Return!");
1182         return;
1183     }
1184     SLOGD("add queueinfo to file done");
1185 }
1186 
StartAVPlayback(const std::string & bundleName,const std::string & assetId)1187 int32_t AVSessionService::StartAVPlayback(const std::string& bundleName, const std::string& assetId)
1188 {
1189     if (!PermissionChecker::GetInstance().CheckSystemPermission()) {
1190         SLOGE("StartAVPlayback: CheckSystemPermission failed");
1191         HISYSEVENT_SECURITY("CONTROL_PERMISSION_DENIED", "CALLER_UID", GetCallingUid(), "CALLER_PID", GetCallingPid(),
1192             "ERROR_MSG", "avsessionservice StartAVPlayback checksystempermission failed");
1193         return ERR_NO_PERMISSION;
1194     }
1195     // get execute param
1196     AppExecFwk::InsightIntentExecuteParam executeParam;
1197     bool isSupport = BundleStatusAdapter::GetInstance().GetPlayIntentParam(bundleName, assetId, executeParam);
1198     if (!isSupport || executeParam.insightIntentName_.empty()) {
1199         SLOGE("StartAVPlayback GetPlayIntentParam fail, Return!");
1200         return AVSESSION_ERROR;
1201     }
1202     int32_t ret = AbilityConnectHelper::GetInstance().StartAVPlayback(executeParam);
1203     if (ret != AVSESSION_SUCCESS) {
1204         SLOGE("StartAVPlayback fail: %{public}d", ret);
1205     }
1206     return ret;
1207 }
1208 
CreateNewControllerForSession(pid_t pid,sptr<AVSessionItem> & session)1209 sptr<AVControllerItem> AVSessionService::CreateNewControllerForSession(pid_t pid, sptr<AVSessionItem>& session)
1210 {
1211     SLOGI("pid=%{public}d sessionId=%{public}s", pid,
1212         AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str());
1213     sptr<AVControllerItem> result = new(std::nothrow) AVControllerItem(pid, session);
1214     if (result == nullptr) {
1215         SLOGE("malloc controller failed");
1216         return nullptr;
1217     }
1218     result->SetServiceCallbackForRelease([this](AVControllerItem& controller) { HandleControllerRelease(controller); });
1219     session->AddController(pid, result);
1220     return result;
1221 }
1222 
GetSubNode(const nlohmann::json & node,const std::string & name)1223 const nlohmann::json& AVSessionService::GetSubNode(const nlohmann::json& node, const std::string& name)
1224 {
1225     static const nlohmann::json jsonNull = nlohmann::json::value_t::null;
1226     if (node.is_discarded() || node.is_null()) {
1227         SLOGE("json node is invalid");
1228         return jsonNull;
1229     }
1230 
1231     if (name.empty()) {
1232         SLOGE("name is invalid");
1233         return node;
1234     }
1235 
1236     auto it = node.find(name);
1237     if (it == node.end()) {
1238         SLOGE("%{public}s is not exist in json", name.c_str());
1239         return jsonNull;
1240     }
1241     return *it;
1242 }
1243 
IsHistoricalSession(const std::string & sessionId)1244 bool AVSessionService::IsHistoricalSession(const std::string& sessionId)
1245 {
1246     {
1247         std::string sortContent;
1248         std::lock_guard sortFileLockGuard(sortFileReadWriteLock_);
1249         if (!LoadStringFromFileEx(AVSESSION_FILE_DIR + SORT_FILE_NAME, sortContent)) {
1250             SLOGE("IsHistoricalSession read sort failed, filename=%{public}s", SORT_FILE_NAME);
1251             return false;
1252         }
1253         if (sortContent.find(sessionId) == string::npos) {
1254             SLOGE("IsHistoricalSession find session no sort, sessionId=%{public}s",
1255                 AVSessionUtils::GetAnonySessionId(sessionId).c_str());
1256             return false;
1257         }
1258     }
1259 
1260     auto session = GetContainer().GetSessionById(sessionId);
1261     if (session != nullptr) {
1262         SLOGE("IsHistoricalSession find session alive, sessionId=%{public}s",
1263             AVSessionUtils::GetAnonySessionId(sessionId).c_str());
1264         return false;
1265     }
1266     SLOGE("IsHistoricalSession find session historical, sessionId=%{public}s",
1267         AVSessionUtils::GetAnonySessionId(sessionId).c_str());
1268     return true;
1269 }
1270 
StartDefaultAbilityByCall(std::string & sessionId)1271 int32_t AVSessionService::StartDefaultAbilityByCall(std::string& sessionId)
1272 {
1273     std::string bundleName = DEFAULT_BUNDLE_NAME;
1274     std::string abilityName = DEFAULT_ABILITY_NAME;
1275     std::string sortContent;
1276 
1277     {
1278         std::lock_guard sortFileLockGuard(sortFileReadWriteLock_);
1279         if (!LoadStringFromFileEx(AVSESSION_FILE_DIR + SORT_FILE_NAME, sortContent)) {
1280             SLOGE("GetAllSessionDescriptors read sort fail! ");
1281             return AVSESSION_ERROR;
1282         }
1283     }
1284 
1285     if (!sortContent.empty()) {
1286         nlohmann::json sortValues = json::parse(sortContent, nullptr, false);
1287         CHECK_AND_RETURN_RET_LOG(!sortValues.is_discarded(), AVSESSION_ERROR, "json object is null");
1288         for (auto& value : sortValues) {
1289             auto session = GetContainer().GetSessionById(value["sessionId"]);
1290             if (session == nullptr) {
1291                 bundleName = value["bundleName"];
1292                 abilityName = value["abilityName"];
1293                 break;
1294             }
1295         }
1296     }
1297     std::shared_ptr<AbilityManagerAdapter> ability = nullptr;
1298     {
1299         std::lock_guard lockGuard(abilityManagerLock_);
1300         auto it = abilityManager_.find(bundleName + abilityName);
1301         if (it != abilityManager_.end()) {
1302             ability = it->second;
1303         } else {
1304             ability = std::make_shared<AbilityManagerAdapter>(bundleName, abilityName);
1305             if (ability == nullptr) {
1306                 return ERR_NO_MEMORY;
1307             }
1308             abilityManager_[bundleName + abilityName] = ability;
1309         }
1310     }
1311     int32_t ret = ability->StartAbilityByCall(sessionId);
1312 
1313     std::lock_guard lockGuard(abilityManagerLock_);
1314     if (ret != ERR_START_ABILITY_IS_RUNNING) {
1315         abilityManager_.erase(bundleName + abilityName);
1316     }
1317     return ret;
1318 }
1319 
StartAbilityByCall(const std::string & sessionIdNeeded,std::string & sessionId)1320 int32_t AVSessionService::StartAbilityByCall(const std::string& sessionIdNeeded, std::string& sessionId)
1321 {
1322     std::string content;
1323 
1324     {
1325         std::lock_guard sortFileLockGuard(sortFileReadWriteLock_);
1326         if (!LoadStringFromFileEx(AVSESSION_FILE_DIR + SORT_FILE_NAME, content)) {
1327             SLOGE("LoadStringFromFile failed, filename=%{public}s", SORT_FILE_NAME);
1328             return AVSESSION_ERROR;
1329         }
1330     }
1331 
1332     nlohmann::json values = json::parse(content, nullptr, false);
1333     CHECK_AND_RETURN_RET_LOG(!values.is_discarded(), AVSESSION_ERROR, "json object is null");
1334     std::string bundleName;
1335     std::string abilityName;
1336     for (auto& value : values) {
1337         if (sessionIdNeeded == value["sessionId"]) {
1338             bundleName = value["bundleName"];
1339             abilityName = value["abilityName"];
1340             break;
1341         }
1342     }
1343     if (bundleName.empty() || abilityName.empty()) {
1344         SLOGE("Get bundle name & ability name failed, sessionId=%{public}s",
1345             AVSessionUtils::GetAnonySessionId(sessionIdNeeded).c_str());
1346         return AVSESSION_ERROR;
1347     }
1348     std::shared_ptr<AbilityManagerAdapter> ability = nullptr;
1349     {
1350         std::lock_guard lockGuard(abilityManagerLock_);
1351         auto it = abilityManager_.find(bundleName + abilityName);
1352         if (it != abilityManager_.end()) {
1353             ability = it->second;
1354         } else {
1355             ability = std::make_shared<AbilityManagerAdapter>(bundleName, abilityName);
1356             if (ability == nullptr) {
1357                 return ERR_NO_MEMORY;
1358             }
1359             abilityManager_[bundleName + abilityName] = ability;
1360         }
1361     }
1362     int32_t ret = ability->StartAbilityByCall(sessionId);
1363 
1364     std::lock_guard lockGuard(abilityManagerLock_);
1365     if (ret != ERR_START_ABILITY_IS_RUNNING) {
1366         abilityManager_.erase(bundleName + abilityName);
1367     }
1368     return ret;
1369 }
1370 
CreateControllerInner(const std::string & sessionId,sptr<IRemoteObject> & object)1371 int32_t AVSessionService::CreateControllerInner(const std::string& sessionId, sptr<IRemoteObject>& object)
1372 {
1373     if (!PermissionChecker::GetInstance().CheckSystemPermission()) {
1374         SLOGE("CreateControllerInner: CheckSystemPermission failed");
1375         HISYSEVENT_SECURITY("CONTROL_PERMISSION_DENIED", "CALLER_UID", GetCallingUid(),
1376             "CALLER_PID", GetCallingPid(), "SESSION_ID", sessionId,
1377             "ERROR_MSG", "avsessionservice createcontrollerinner checksystempermission failed");
1378         return ERR_NO_PERMISSION;
1379     }
1380     std::string sessionIdInner;
1381     if (sessionId == "default") {
1382         auto ret = StartDefaultAbilityByCall(sessionIdInner);
1383         if (ret != AVSESSION_SUCCESS) {
1384             SLOGE("StartDefaultAbilityByCall failed: %{public}d", ret);
1385             return ret;
1386         }
1387     } else {
1388         if (IsHistoricalSession(sessionId)) {
1389             auto ret = StartAbilityByCall(sessionId, sessionIdInner);
1390             if (ret != AVSESSION_SUCCESS) {
1391                 SLOGE("StartAbilityByCall failed: %{public}d", ret);
1392                 return ret;
1393             }
1394         } else {
1395             sessionIdInner = sessionId;
1396         }
1397     }
1398     auto pid = GetCallingPid();
1399     std::lock_guard lockGuard(sessionAndControllerLock_);
1400     auto controllerAlreadyExist = GetPresentController(pid, sessionIdInner);
1401     if (controllerAlreadyExist != nullptr) {
1402         SLOGI("controller already exist, try pass instance and return exist");
1403         object = controllerAlreadyExist;
1404         return ERR_CONTROLLER_IS_EXIST;
1405     }
1406 
1407     auto session = GetContainer().GetSessionById(sessionIdInner);
1408     if (session == nullptr) {
1409         SLOGE("no session id %{public}s", AVSessionUtils::GetAnonySessionId(sessionIdInner).c_str());
1410         return ERR_SESSION_NOT_EXIST;
1411     }
1412 
1413     auto result = CreateNewControllerForSession(pid, session);
1414     if (result == nullptr) {
1415         SLOGE("create new controller failed");
1416         return ERR_NO_MEMORY;
1417     }
1418 
1419     controllers_[pid].push_back(result);
1420     object = result;
1421     SLOGI("success");
1422     return AVSESSION_SUCCESS;
1423 }
1424 
1425 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
GetAVCastControllerInner(const std::string & sessionId,sptr<IRemoteObject> & object)1426 int32_t AVSessionService::GetAVCastControllerInner(const std::string& sessionId, sptr<IRemoteObject>& object)
1427 {
1428     SLOGI("Start get cast controller");
1429     auto session = GetContainer().GetSessionById(sessionId);
1430     CHECK_AND_RETURN_RET_LOG(session != nullptr, AVSESSION_ERROR, "StopCast: session is not exist");
1431     auto result = session->GetAVCastControllerInner();
1432     CHECK_AND_RETURN_RET_LOG(result != nullptr, AVSESSION_ERROR, "GetAVCastControllerInner failed");
1433     object = result;
1434     return AVSESSION_SUCCESS;
1435 }
1436 #endif
1437 
AddSessionListener(pid_t pid,const sptr<ISessionListener> & listener)1438 void AVSessionService::AddSessionListener(pid_t pid, const sptr<ISessionListener>& listener)
1439 {
1440     std::lock_guard lockGuard(sessionListenersLock_);
1441     sessionListeners_[pid] = listener;
1442 }
1443 
RemoveSessionListener(pid_t pid)1444 void AVSessionService::RemoveSessionListener(pid_t pid)
1445 {
1446     std::lock_guard lockGuard(sessionListenersLock_);
1447     sessionListeners_.erase(pid);
1448 }
1449 
RegisterSessionListener(const sptr<ISessionListener> & listener)1450 int32_t AVSessionService::RegisterSessionListener(const sptr<ISessionListener>& listener)
1451 {
1452     SLOGI("Enter RegisterSessionListener process");
1453     if (!PermissionChecker::GetInstance().CheckSystemPermission()) {
1454         SLOGE("RegisterSessionListener: CheckSystemPermission failed");
1455         HISYSEVENT_SECURITY("CONTROL_PERMISSION_DENIED", "CALLER_UID", GetCallingUid(), "CALLER_PID", GetCallingPid(),
1456             "ERROR_MSG", "avsessionservice registersessionlistener checksystempermission failed");
1457         return ERR_NO_PERMISSION;
1458     }
1459     AddSessionListener(GetCallingPid(), listener);
1460     return AVSESSION_SUCCESS;
1461 }
1462 
HandleEventHandlerCallBack()1463 void AVSessionService::HandleEventHandlerCallBack()
1464 {
1465     SLOGI("handle eventHandler callback");
1466     AVControlCommand cmd;
1467     std::lock_guard lockGuard(sessionAndControllerLock_);
1468     if (pressCount_ >= THREE_CLICK && topSession_) {
1469         cmd.SetCommand(AVControlCommand::SESSION_CMD_PLAY_PREVIOUS);
1470         topSession_->ExecuteControllerCommand(cmd);
1471     } else if (pressCount_ == DOUBLE_CLICK && topSession_) {
1472         cmd.SetCommand(AVControlCommand::SESSION_CMD_PLAY_NEXT);
1473         topSession_->ExecuteControllerCommand(cmd);
1474     } else if (pressCount_ == ONE_CLICK) {
1475         SLOGI("HandleEventHandlerCallBack on ONE_CLICK ");
1476         if (!topSession_) {
1477             SLOGI("HandleEventHandlerCallBack ONE_CLICK without topSession_");
1478             sptr<IRemoteObject> object;
1479             int32_t ret = CreateControllerInner("default", object);
1480             SLOGI("HandleEventHandlerCallBack ONE_CLICK !topSession_ ret : %{public}d", static_cast<int32_t>(ret));
1481         }
1482         if (topSession_) {
1483             SLOGI("HandleEventHandlerCallBack ONE_CLICK with topSession_ ");
1484             auto playbackState = topSession_->GetPlaybackState();
1485             if (playbackState.GetState() == AVPlaybackState::PLAYBACK_STATE_PLAY) {
1486                 cmd.SetCommand(AVControlCommand::SESSION_CMD_PAUSE);
1487             } else {
1488                 cmd.SetCommand(AVControlCommand::SESSION_CMD_PLAY);
1489             }
1490             topSession_->ExecuteControllerCommand(cmd);
1491         }
1492     } else {
1493         SLOGI("press invalid");
1494     }
1495     pressCount_ = 0;
1496     isFirstPress_ = true;
1497 }
1498 
SendSystemAVKeyEvent(const MMI::KeyEvent & keyEvent)1499 int32_t AVSessionService::SendSystemAVKeyEvent(const MMI::KeyEvent& keyEvent)
1500 {
1501     if (!PermissionChecker::GetInstance().CheckSystemPermission()) {
1502         SLOGE("SendSystemAVKeyEvent: CheckSystemPermission failed");
1503         HISYSEVENT_SECURITY("CONTROL_PERMISSION_DENIED", "CALLER_UID", GetCallingUid(), "CALLER_PID", GetCallingPid(),
1504             "KEY_CODE", keyEvent.GetKeyCode(), "KEY_ACTION", keyEvent.GetKeyAction(),
1505             "ERROR_MSG", "avsessionservice sendsystemavkeyevent checksystempermission failed");
1506         return ERR_NO_PERMISSION;
1507     }
1508     SLOGI("key=%{public}d", keyEvent.GetKeyCode());
1509     if (keyEvent.GetKeyCode() == MMI::KeyEvent::KEYCODE_HEADSETHOOK) {
1510         pressCount_++;
1511         if (isFirstPress_) {
1512             auto ret = AVSessionEventHandler::GetInstance().AVSessionPostTask([this]() {
1513                 HandleEventHandlerCallBack();
1514             }, "SendSystemAVKeyEvent", CLICK_TIMEOUT);
1515             CHECK_AND_RETURN_RET_LOG(ret, AVSESSION_ERROR, "init eventHandler failed");
1516             isFirstPress_ = false;
1517         }
1518         return AVSESSION_SUCCESS;
1519     }
1520     std::lock_guard lockGuard(sessionAndControllerLock_);
1521     if (topSession_) {
1522         topSession_->HandleMediaKeyEvent(keyEvent);
1523     } else {
1524         SLOGI("topSession is nullptr");
1525     }
1526     return AVSESSION_SUCCESS;
1527 }
1528 
SendSystemControlCommand(const AVControlCommand & command)1529 int32_t AVSessionService::SendSystemControlCommand(const AVControlCommand &command)
1530 {
1531     if (!PermissionChecker::GetInstance().CheckSystemPermission()) {
1532         SLOGE("SendSystemControlCommand: CheckSystemPermission failed");
1533         HISYSEVENT_SECURITY("CONTROL_PERMISSION_DENIED", "CALLER_UID", GetCallingUid(),
1534             "CALLER_PID", GetCallingPid(), "CMD", command.GetCommand(),
1535             "ERROR_MSG", "avsessionservice sendsystemcontrolcommand checksystempermission failed");
1536         return ERR_NO_PERMISSION;
1537     }
1538     SLOGI("cmd=%{public}d", command.GetCommand());
1539     std::lock_guard lockGuard(sessionAndControllerLock_);
1540     if (topSession_) {
1541         CHECK_AND_RETURN_RET_LOG(CommandSendLimit::GetInstance().IsCommandSendEnable(GetCallingPid()),
1542             ERR_COMMAND_SEND_EXCEED_MAX, "command excuted number exceed max");
1543         topSession_->ExecuteControllerCommand(command);
1544     } else if (command.GetCommand() == AVControlCommand::SESSION_CMD_PLAY) {
1545         SLOGI("SendSystemControlCommand code start without topSession_");
1546         sptr<IRemoteObject> object;
1547         int32_t ret = CreateControllerInner("default", object);
1548         SLOGI("SendSystemControlCommand code start ret : %{public}d", static_cast<int32_t>(ret));
1549     }
1550     return AVSESSION_SUCCESS;
1551 }
1552 
AddClientDeathObserver(pid_t pid,const sptr<IClientDeath> & observer)1553 void AVSessionService::AddClientDeathObserver(pid_t pid, const sptr<IClientDeath>& observer)
1554 {
1555     std::lock_guard lockGuard(clientDeathObserversLock_);
1556     clientDeathObservers_[pid] = observer;
1557 }
1558 
RemoveClientDeathObserver(pid_t pid)1559 void AVSessionService::RemoveClientDeathObserver(pid_t pid)
1560 {
1561     std::lock_guard lockGuard(clientDeathObserversLock_);
1562     if (clientDeathObservers_.empty()) {
1563         SLOGE("try remove observer with empty list");
1564         return;
1565     }
1566     clientDeathObservers_.erase(pid);
1567 }
1568 
RegisterClientDeathObserver(const sptr<IClientDeath> & observer)1569 int32_t AVSessionService::RegisterClientDeathObserver(const sptr<IClientDeath>& observer)
1570 {
1571     SLOGI("enter ClientDeathObserver register");
1572     auto pid = GetCallingPid();
1573     auto* recipient = new(std::nothrow) ClientDeathRecipient([this, pid]() { OnClientDied(pid); });
1574     if (recipient == nullptr) {
1575         SLOGE("malloc failed");
1576         HISYSEVENT_FAULT("CONTROL_COMMAND_FAILED", "ERROR_TYPE", "RGS_CLIENT_DEATH_OBSERVER_FAILED",
1577             "ERROR_INFO", "avsession service register client death observer malloc failed");
1578         return AVSESSION_ERROR;
1579     }
1580 
1581     if (!observer->AsObject()->AddDeathRecipient(recipient)) {
1582         SLOGE("add death recipient for %{public}d failed", pid);
1583         HISYSEVENT_FAULT("CONTROL_COMMAND_FAILED", "ERROR_TYPE", "RGS_CLIENT_DEATH_FAILED", "CALLING_PID", pid,
1584             "ERROR_INFO", "avsession service register client death observer, add death recipient failed");
1585         return AVSESSION_ERROR;
1586     }
1587 
1588     AddClientDeathObserver(pid, observer);
1589     return AVSESSION_SUCCESS;
1590 }
1591 
ClearClientResources(pid_t pid)1592 void AVSessionService::ClearClientResources(pid_t pid)
1593 {
1594     RemoveSessionListener(pid);
1595     {
1596         std::lock_guard lockGuard(sessionAndControllerLock_);
1597         ClearSessionForClientDiedNoLock(pid);
1598         ClearControllerForClientDiedNoLock(pid);
1599     }
1600     SLOGI("remove ClientDeathObserver to %{public}d", pid);
1601     RemoveClientDeathObserver(pid);
1602 }
1603 
Close(void)1604 int32_t AVSessionService::Close(void)
1605 {
1606     if (!PermissionChecker::GetInstance().CheckSystemPermission()) {
1607         SLOGE("Close: CheckSystemPermission failed");
1608         HISYSEVENT_SECURITY("CONTROL_PERMISSION_DENIED", "CALLER_UID", GetCallingUid(), "CALLER_PID", GetCallingPid(),
1609                             "ERROR_MSG", "avsessionservice Close checksystempermission failed");
1610         return ERR_NO_PERMISSION;
1611     }
1612     auto pid = GetCallingPid();
1613     SLOGI("pid=%{public}d", pid);
1614     ClearClientResources(pid);
1615     return AVSESSION_SUCCESS;
1616 }
1617 
OnClientDied(pid_t pid)1618 void AVSessionService::OnClientDied(pid_t pid)
1619 {
1620     SLOGI("pid=%{public}d", pid);
1621     ClearClientResources(pid);
1622 }
1623 
DeleteHistoricalRecord(const std::string & bundleName)1624 void AVSessionService::DeleteHistoricalRecord(const std::string& bundleName)
1625 {
1626     std::lock_guard sortFileLockGuard(sortFileReadWriteLock_);
1627     SLOGI("delete historical record, bundleName=%{public}s", bundleName.c_str());
1628     std::string oldContent;
1629     std::string newContent;
1630     nlohmann::json values;
1631     if (!LoadStringFromFileEx(AVSESSION_FILE_DIR + SORT_FILE_NAME, oldContent)) {
1632         SLOGE("LoadStringFromFile failed, filename=%{public}s", SORT_FILE_NAME);
1633         return;
1634     }
1635     values = json::parse(oldContent, nullptr, false);
1636     CHECK_AND_RETURN_LOG(!values.is_discarded(), "json object is null");
1637     for (auto value : values) {
1638         if (bundleName == value["bundleName"]) {
1639             values.erase(std::remove(values.begin(), values.end(), value));
1640             break;
1641         }
1642     }
1643     newContent = values.dump();
1644     SLOGD("DeleteHistoricalRecord::Dump json object finished");
1645     if (!SaveStringToFileEx(AVSESSION_FILE_DIR + SORT_FILE_NAME, newContent)) {
1646         SLOGE("SaveStringToFile failed, filename=%{public}s", SORT_FILE_NAME);
1647         return;
1648     }
1649 }
1650 
DeleteAVQueueInfoRecord(const std::string & bundleName)1651 void AVSessionService::DeleteAVQueueInfoRecord(const std::string& bundleName)
1652 {
1653     std::lock_guard avQueueFileLockGuard(avQueueFileReadWriteLock_);
1654     SLOGI("DeleteAVQueueInfoRecord, bundleName=%{public}s", bundleName.c_str());
1655     std::string oldContent;
1656     std::string newContent;
1657     nlohmann::json values;
1658     if (!LoadStringFromFileEx(AVSESSION_FILE_DIR + AVQUEUE_FILE_NAME, oldContent)) {
1659         SLOGE("LoadStringFromFile failed, filename=%{public}s", AVQUEUE_FILE_NAME);
1660         return;
1661     }
1662     values = json::parse(oldContent, nullptr, false);
1663     CHECK_AND_RETURN_LOG(!values.is_discarded(), "json object is null");
1664     for (auto it = values.begin(); it != values.end();) {
1665         if (it->at("bundleName") == bundleName) {
1666             std::string avQueueId = it->at("avQueueId");
1667             std::string fileName = AVSessionUtils::GetFixedPathName() + bundleName + "_" +
1668                 avQueueId + AVSessionUtils::GetFileSuffix();
1669             AVSessionUtils::DeleteFile(fileName);
1670             values.erase(it);
1671         } else {
1672             ++it;
1673         }
1674     }
1675     newContent = values.dump();
1676     SLOGD("DeleteAVQueueInfoRecord::Dump json object finished");
1677     if (!SaveStringToFileEx(AVSESSION_FILE_DIR + AVQUEUE_FILE_NAME, newContent)) {
1678         SLOGE("SaveStringToFile failed, filename=%{public}s", AVQUEUE_FILE_NAME);
1679         return;
1680     }
1681 }
1682 
HandleSessionRelease(std::string sessionId)1683 void AVSessionService::HandleSessionRelease(std::string sessionId)
1684 {
1685     SLOGI("HandleSessionRelease, sessionId=%{public}s", AVSessionUtils::GetAnonySessionId(sessionId).c_str());
1686 
1687     sptr<AVSessionItem> sessionItem = GetContainer().GetSessionById(sessionId);
1688     CHECK_AND_RETURN_LOG(sessionItem != nullptr, "Session item is nullptr");
1689     NotifySessionRelease(sessionItem->GetDescriptor());
1690     std::lock_guard lockGuard(sessionAndControllerLock_);
1691     if (topSession_.GetRefPtr() == sessionItem.GetRefPtr()) {
1692         SLOGD("Top session is released session");
1693         UpdateTopSession(nullptr);
1694     }
1695     if (sessionItem->GetRemoteSource() != nullptr) {
1696         int32_t ret = CancelCastAudioForClientExit(sessionItem->GetPid(), sessionItem);
1697         SLOGI("CancelCastAudioForClientExit ret is %{public}d", ret);
1698     } else {
1699         SLOGI("GetContainer has no this session");
1700     }
1701     HISYSEVENT_ADD_LIFE_CYCLE_INFO(sessionItem->GetDescriptor().elementName_.GetBundleName(),
1702         AppManagerAdapter::GetInstance().IsAppBackground(GetCallingUid()),
1703         sessionItem->GetDescriptor().sessionType_, false);
1704     SLOGI("HandleSessionRelease, remove session: sessionId=%{public}s",
1705         AVSessionUtils::GetAnonySessionId(sessionId).c_str());
1706     GetContainer().RemoveSession(sessionItem->GetPid(), sessionItem->GetAbilityName());
1707 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
1708     if (GetContainer().GetAllSessions().size() == 0) {
1709         SLOGI("call disable cast on no session alive");
1710         checkEnableCast(false);
1711     }
1712 #endif
1713 }
1714 
HandleControllerRelease(AVControllerItem & controller)1715 void AVSessionService::HandleControllerRelease(AVControllerItem& controller)
1716 {
1717     auto pid = controller.GetPid();
1718     std::lock_guard lockGuard(sessionAndControllerLock_);
1719     auto it = controllers_.find(pid);
1720     if (it == controllers_.end()) {
1721         return;
1722     }
1723     SLOGI("remove controller");
1724     it->second.remove(&controller);
1725     if (it->second.empty()) {
1726         controllers_.erase(pid);
1727     }
1728 }
1729 
Dump(std::int32_t fd,const std::vector<std::u16string> & args)1730 std::int32_t AVSessionService::Dump(std::int32_t fd, const std::vector<std::u16string>& args)
1731 {
1732     if (fd < 0) {
1733         SLOGE("dump fd invalid");
1734         return ERR_INVALID_PARAM;
1735     }
1736 
1737     if (dumpHelper_ == nullptr) {
1738         SLOGE("dumpHelper_ is nullptr!");
1739         return ERR_INVALID_PARAM;
1740     }
1741 
1742     std::vector<std::string> argsInStr;
1743     for (const auto& arg : args) {
1744         SLOGI("Dump args: %s", Str16ToStr8(arg).c_str());
1745         argsInStr.emplace_back(Str16ToStr8(arg));
1746     }
1747 
1748     std::string result;
1749     dumpHelper_->Dump(argsInStr, result, *this);
1750     std::int32_t ret = dprintf(fd, "%s", result.c_str());
1751     if (ret < 0) {
1752         SLOGI("dprintf to dump fd failed");
1753         return ERR_INVALID_PARAM;
1754     }
1755     return AVSESSION_SUCCESS;
1756 }
1757 
GetService(const std::string & deviceId)1758 __attribute__((no_sanitize("cfi"))) std::shared_ptr<RemoteSessionCommandProcess> AVSessionService::GetService(
1759     const std::string& deviceId)
1760 {
1761     SLOGI("enter");
1762     auto mgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1763     if (mgr == nullptr) {
1764         SLOGE("failed to get sa mgr");
1765         return nullptr;
1766     }
1767     auto object = mgr->GetSystemAbility(AVSESSION_SERVICE_ID, deviceId);
1768     if (object == nullptr) {
1769         SLOGE("failed to get service");
1770         return nullptr;
1771     }
1772     SLOGI("check remoteService create");
1773     std::shared_ptr<RemoteSessionCommandProcess> remoteService = std::make_shared<RemoteSessionCommandProcess>(object);
1774     SLOGI("check remoteService create done");
1775     return remoteService;
1776 }
1777 
IsLocalDevice(const std::string & networkId)1778 bool AVSessionService::IsLocalDevice(const std::string& networkId)
1779 {
1780     std::string localNetworkId;
1781     CHECK_AND_RETURN_RET_LOG(GetLocalNetworkId(localNetworkId) == AVSESSION_SUCCESS, AVSESSION_ERROR,
1782                              "GetLocalNetworkId error");
1783     if (networkId == localNetworkId || networkId == "LocalDevice") {
1784         SLOGI("local device");
1785         return true;
1786     }
1787     SLOGI("not local device");
1788     return false;
1789 }
1790 
GetLocalNetworkId(std::string & networkId)1791 int32_t AVSessionService::GetLocalNetworkId(std::string& networkId)
1792 {
1793     SLOGI("GetLocalNetworkId");
1794     DistributedHardware::DmDeviceInfo deviceInfo;
1795     int32_t ret = DistributedHardware::DeviceManager::GetInstance().GetLocalDeviceInfo("av_session", deviceInfo);
1796     CHECK_AND_RETURN_RET_LOG(ret == 0, ret, "get local deviceInfo failed");
1797     networkId = deviceInfo.networkId;
1798     return AVSESSION_SUCCESS;
1799 }
1800 
GetTrustedDeviceName(const std::string & networkId,std::string & deviceName)1801 int32_t AVSessionService::GetTrustedDeviceName(const std::string& networkId, std::string& deviceName)
1802 {
1803     SLOGI("GetTrustedDeviceName");
1804     std::vector<OHOS::DistributedHardware::DmDeviceInfo> deviceList {};
1805     if (IsLocalDevice(networkId)) {
1806         deviceName = "LocalDevice";
1807         return AVSESSION_SUCCESS;
1808     }
1809     int32_t ret = GetTrustedDevicesInfo(deviceList);
1810     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "get devicesInfo failed");
1811     SLOGI("deviceList size is %{public}d", static_cast<int32_t>(deviceList.size()));
1812     for (const auto& device : deviceList) {
1813         SLOGI("device networkId is %{public}.6s", device.networkId);
1814         ret = strcmp(device.networkId, networkId.c_str());
1815         if (ret == 0) {
1816             deviceName = device.deviceName;
1817             SLOGI("deviceName is %{public}s", deviceName.c_str());
1818             return AVSESSION_SUCCESS;
1819         }
1820     }
1821     SLOGI("can not find this device %{public}.6s", networkId.c_str());
1822     return AVSESSION_ERROR;
1823 }
1824 
GetTrustedDevicesInfo(std::vector<OHOS::DistributedHardware::DmDeviceInfo> & deviceList)1825 int32_t AVSessionService::GetTrustedDevicesInfo(std::vector<OHOS::DistributedHardware::DmDeviceInfo>& deviceList)
1826 {
1827     SLOGI("GetTrustedDevicesInfo");
1828     int32_t ret = DistributedHardware::DeviceManager::GetInstance().GetTrustedDeviceList("av_session", "", deviceList);
1829     CHECK_AND_RETURN_RET_LOG(ret == 0, ret, "get trusted device list failed");
1830     return AVSESSION_SUCCESS;
1831 }
1832 
SetBasicInfo(std::string & sessionInfo)1833 int32_t AVSessionService::SetBasicInfo(std::string& sessionInfo)
1834 {
1835     AVSessionBasicInfo basicInfo;
1836     basicInfo.metaDataCap_ = AVMetaData::localCapability;
1837     basicInfo.playBackStateCap_ = AVPlaybackState::localCapability;
1838     basicInfo.controlCommandCap_ = AVControlCommand::localCapability;
1839     int32_t ret = GetLocalNetworkId(basicInfo.networkId_);
1840     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, AVSESSION_ERROR, "GetLocalNetworkId failed");
1841 
1842     ret = JsonUtils::SetSessionBasicInfo(sessionInfo, basicInfo);
1843     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, AVSESSION_ERROR, "SetDeviceId failed");
1844     return AVSESSION_SUCCESS;
1845 }
1846 
SetDeviceInfo(const std::vector<AudioStandard::AudioDeviceDescriptor> & castAudioDescriptors,sptr<AVSessionItem> & session)1847 void AVSessionService::SetDeviceInfo(const std::vector<AudioStandard::AudioDeviceDescriptor>& castAudioDescriptors,
1848     sptr <AVSessionItem>& session)
1849 {
1850     CHECK_AND_RETURN_LOG(session != nullptr && castAudioDescriptors.size() > 0, "invalid argument");
1851     SLOGI("castAudioDescriptors size is %{public}d", static_cast<int32_t>(castAudioDescriptors.size()));
1852     SLOGI("session id is %{public}s", AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str());
1853 
1854     OutputDeviceInfo outputDeviceInfo;
1855     outputDeviceInfo.deviceInfos_.clear();
1856     int32_t castCategory = AVCastCategory::CATEGORY_LOCAL;
1857     if (!IsLocalDevice(castAudioDescriptors[0].networkId_)) {
1858         castCategory = AVCastCategory::CATEGORY_REMOTE;
1859     }
1860     for (const auto &audioDescriptor : castAudioDescriptors) {
1861         DeviceInfo deviceInfo;
1862         deviceInfo.castCategory_ = castCategory;
1863         deviceInfo.deviceId_ = std::to_string(audioDescriptor.deviceId_);
1864         deviceInfo.deviceName_ = audioDescriptor.deviceName_;
1865         SLOGI("deviceName is %{public}s", audioDescriptor.deviceName_.c_str());
1866         SLOGI("deviceId is %{public}d", audioDescriptor.deviceId_);
1867         outputDeviceInfo.deviceInfos_.emplace_back(deviceInfo);
1868     }
1869     session->SetOutputDevice(outputDeviceInfo);
1870 }
1871 
GetAudioDescriptorByDeviceId(const std::vector<sptr<AudioStandard::AudioDeviceDescriptor>> & descriptors,const std::string & deviceId,AudioStandard::AudioDeviceDescriptor & audioDescriptor)1872 bool AVSessionService::GetAudioDescriptorByDeviceId(const std::vector<sptr<AudioStandard::AudioDeviceDescriptor>>&
1873     descriptors, const std::string& deviceId,
1874     AudioStandard::AudioDeviceDescriptor& audioDescriptor)
1875 {
1876     for (const auto& descriptor : descriptors) {
1877         if (std::to_string(descriptor->deviceId_) == deviceId) {
1878             audioDescriptor = *descriptor;
1879             SLOGI("deviceId is %{public}d, networkId is %{public}.6s", audioDescriptor.deviceId_,
1880                   audioDescriptor.networkId_.c_str());
1881             return true;
1882         }
1883     }
1884     SLOGI("deviceId is %{public}s, not found in all audio descriptor", deviceId.c_str());
1885     return false;
1886 }
1887 
GetDeviceInfo(const sptr<AVSessionItem> & session,const std::vector<AudioStandard::AudioDeviceDescriptor> & descriptors,std::vector<AudioStandard::AudioDeviceDescriptor> & castSinkDescriptors,std::vector<AudioStandard::AudioDeviceDescriptor> & cancelSinkDescriptors)1888 void AVSessionService::GetDeviceInfo(const sptr <AVSessionItem>& session,
1889     const std::vector<AudioStandard::AudioDeviceDescriptor>& descriptors,
1890     std::vector<AudioStandard::AudioDeviceDescriptor>& castSinkDescriptors,
1891     std::vector<AudioStandard::AudioDeviceDescriptor>& cancelSinkDescriptors)
1892 {
1893     if (descriptors.size() != 1) {
1894         SLOGI("descriptor size is %{public}d, not support", static_cast<int32_t>(descriptors.size()));
1895         return;
1896     }
1897     castSinkDescriptors.push_back(descriptors[0]);
1898     SLOGI("cast to deviceId %{public}d, networkId_ is %{public}.6s", descriptors[0].deviceId_,
1899           descriptors[0].networkId_.c_str());
1900 
1901     OutputDeviceInfo tempOutputDeviceInfo;
1902     session->GetOutputDevice(tempOutputDeviceInfo);
1903     // If not in remote, return directly
1904     if (tempOutputDeviceInfo.deviceInfos_.size() == 0 || tempOutputDeviceInfo.deviceInfos_[0].castCategory_ == 1) {
1905         SLOGI("castCategory is %{public}d, no need to cancel", tempOutputDeviceInfo.deviceInfos_[0].castCategory_);
1906         return;
1907     }
1908     int32_t ret = GetAudioDescriptor(session->GetDescriptor().outputDeviceInfo_.deviceInfos_[0].deviceId_,
1909                                      cancelSinkDescriptors);
1910     CHECK_AND_RETURN_LOG(ret == AVSESSION_SUCCESS, "get cancelSinkDescriptors failed");
1911 }
1912 
SelectOutputDevice(const int32_t uid,const AudioDeviceDescriptor & descriptor)1913 int32_t AVSessionService::SelectOutputDevice(const int32_t uid, const AudioDeviceDescriptor& descriptor)
1914 {
1915     SLOGI("uid is %{public}d", uid);
1916     sptr <AudioStandard::AudioRendererFilter> audioFilter = new(std::nothrow) AudioRendererFilter();
1917     CHECK_AND_RETURN_RET_LOG(audioFilter != nullptr, ERR_NO_MEMORY, "new AudioRendererFilter failed");
1918     audioFilter->uid = uid;
1919     audioFilter->rendererInfo.contentType = ContentType::CONTENT_TYPE_MUSIC;
1920     audioFilter->rendererInfo.streamUsage = StreamUsage::STREAM_USAGE_MEDIA;
1921 
1922     std::vector<sptr<AudioDeviceDescriptor>> audioDescriptor;
1923     auto audioDeviceDescriptor = new(std::nothrow) AudioDeviceDescriptor(descriptor);
1924     CHECK_AND_RETURN_RET_LOG(audioDeviceDescriptor != nullptr, ERR_NO_MEMORY, "audioDeviceDescriptor is nullptr");
1925     audioDescriptor.push_back(audioDeviceDescriptor);
1926     SLOGI("select the device %{public}s id %{public}d role is %{public}d, networkId is %{public}.6s",
1927           descriptor.deviceName_.c_str(), descriptor.deviceId_, static_cast<int32_t>(descriptor.deviceRole_),
1928           descriptor.networkId_.c_str());
1929 
1930     AudioSystemManager *audioSystemMgr = AudioSystemManager::GetInstance();
1931     CHECK_AND_RETURN_RET_LOG(audioSystemMgr != nullptr, AVSESSION_ERROR, "get AudioSystemManager instance failed");
1932     int32_t ret = audioSystemMgr->SelectOutputDevice(audioFilter, audioDescriptor);
1933     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, AVSESSION_ERROR, "SelectOutputDevice failed");
1934 
1935     return AVSESSION_SUCCESS;
1936 }
1937 
CastAudio(const SessionToken & token,const std::vector<AudioStandard::AudioDeviceDescriptor> & sinkAudioDescriptors)1938 int32_t AVSessionService::CastAudio(const SessionToken& token,
1939                                     const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkAudioDescriptors)
1940 {
1941     SLOGI("sessionId is %{public}s", AVSessionUtils::GetAnonySessionId(token.sessionId).c_str());
1942     if (!PermissionChecker::GetInstance().CheckSystemPermission()) {
1943         SLOGE("CastAudio: CheckSystemPermission failed");
1944         HISYSEVENT_SECURITY("CONTROL_PERMISSION_DENIED", "CALLER_UID", GetCallingUid(), "CALLER_PID", GetCallingPid(),
1945                             "ERROR_MSG", "avsessionservice CastAudio checksystempermission failed");
1946         return ERR_NO_PERMISSION;
1947     }
1948 
1949     std::string sourceSessionInfo;
1950     int32_t ret = SetBasicInfo(sourceSessionInfo);
1951     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetBasicInfo failed");
1952     sptr<AVSessionItem> session = GetContainer().GetSessionById(token.sessionId);
1953     CHECK_AND_RETURN_RET_LOG(session != nullptr, ERR_SESSION_NOT_EXIST, "session %{public}s not exist",
1954                              AVSessionUtils::GetAnonySessionId(token.sessionId).c_str());
1955     ret = JsonUtils::SetSessionDescriptor(sourceSessionInfo, session->GetDescriptor());
1956     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetDescriptorInfo failed");
1957     ret = CastAudioProcess(sinkAudioDescriptors, sourceSessionInfo, session);
1958     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudioProcess failed");
1959     return AVSESSION_SUCCESS;
1960 }
1961 
CastAudioProcess(const std::vector<AudioStandard::AudioDeviceDescriptor> & descriptors,const std::string & sourceSessionInfo,sptr<AVSessionItem> & session)1962 int32_t AVSessionService::CastAudioProcess(const std::vector<AudioStandard::AudioDeviceDescriptor>& descriptors,
1963                                            const std::string& sourceSessionInfo,
1964                                            sptr <AVSessionItem>& session)
1965 {
1966     SLOGI("start");
1967     std::vector<AudioDeviceDescriptor> castSinkDescriptors;
1968     std::vector<AudioDeviceDescriptor> cancelSinkDescriptors;
1969     GetDeviceInfo(session, descriptors, castSinkDescriptors, cancelSinkDescriptors);
1970 
1971     if (cancelSinkDescriptors.size() > 0) {
1972         int32_t ret = CancelCastAudioInner(cancelSinkDescriptors, sourceSessionInfo, session);
1973         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CancelCastAudioInner failed");
1974     }
1975 
1976     if (castSinkDescriptors.size() > 0) {
1977         int32_t ret = CastAudioInner(castSinkDescriptors, sourceSessionInfo, session);
1978         if (ret != AVSESSION_SUCCESS) {
1979             SLOGE("CastAudioInner failed, try cancel it. ret is %{public}d",
1980                 CancelCastAudioInner(castSinkDescriptors, sourceSessionInfo, session));
1981             return ret;
1982         }
1983     }
1984 
1985     SetDeviceInfo(descriptors, session);
1986     return AVSESSION_SUCCESS;
1987 }
1988 
CastAudioInner(const std::vector<AudioStandard::AudioDeviceDescriptor> & sinkAudioDescriptors,const std::string & sourceSessionInfo,const sptr<AVSessionItem> & session)1989 int32_t AVSessionService::CastAudioInner(const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkAudioDescriptors,
1990                                          const std::string& sourceSessionInfo,
1991                                          const sptr <AVSessionItem>& session)
1992 {
1993     SLOGI("start");
1994     CHECK_AND_RETURN_RET_LOG(sinkAudioDescriptors.size() > 0, AVSESSION_ERROR, "sinkDescriptors is empty");
1995     std::string sourceDevice;
1996     CHECK_AND_RETURN_RET_LOG(GetLocalNetworkId(sourceDevice) == AVSESSION_SUCCESS, AVSESSION_ERROR,
1997                              "GetLocalNetworkId failed");
1998     SLOGI("networkId_: %{public}.6s, role %{public}d", sinkAudioDescriptors[0].networkId_.c_str(),
1999           static_cast<int32_t>(sinkAudioDescriptors[0].deviceRole_));
2000     if (IsLocalDevice(sinkAudioDescriptors[0].networkId_)) {
2001         int32_t ret = SelectOutputDevice(session->GetUid(), sinkAudioDescriptors[0]);
2002         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "selectOutputDevice failed");
2003         return AVSESSION_SUCCESS;
2004     }
2005 
2006     SLOGI("sinkAudioDescriptors size is %{public}d", static_cast<int32_t>(sinkAudioDescriptors.size()));
2007     for (const auto& sinkAudioDescriptor : sinkAudioDescriptors) {
2008         std::string sinkSessionInfo;
2009         auto service = GetService(sinkAudioDescriptor.networkId_);
2010         CHECK_AND_RETURN_RET_LOG(service != nullptr, AVSESSION_ERROR, "GetService %{public}s failed",
2011                                  sinkAudioDescriptor.networkId_.c_str());
2012         int32_t ret = service->ProcessCastAudioCommand(RemoteServiceCommand::COMMAND_CAST_AUDIO, sourceSessionInfo,
2013                                                        sinkSessionInfo);
2014         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "ProcessCastAudioCommand failed");
2015         std::string sinkCapability;
2016         ret = JsonUtils::GetAllCapability(sinkSessionInfo, sinkCapability);
2017         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetAllCapability failed");
2018         ret = session->CastAudioToRemote(sourceDevice, sinkAudioDescriptor.networkId_, sinkCapability);
2019         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudioToRemote failed");
2020         HISYSEVENT_BEHAVIOR("SESSION_CAST",
2021             "BUNDLE_NAME", session->GetDescriptor().elementName_.GetBundleName(),
2022             "MODULE_NAME", session->GetDescriptor().elementName_.GetModuleName(),
2023             "ABILITY_NAME", session->GetDescriptor().elementName_.GetAbilityName(),
2024             "SESSION_PID", session->GetDescriptor().pid_,
2025             "SESSION_UID", session->GetDescriptor().uid_,
2026             "SESSION_ID", session->GetDescriptor().sessionId_,
2027             "SESSION_TAG", session->GetDescriptor().sessionTag_,
2028             "SESSION_TYPE", session->GetDescriptor().sessionType_,
2029             "CAST_TYPE", 0,
2030             "DEST_DEVICE_TYPE", sinkAudioDescriptor.deviceType_,
2031             "DEST_DEVICE_NAME", sinkAudioDescriptor.deviceName_.c_str(),
2032             "DEST_DEVICE_ID", sinkAudioDescriptor.deviceId_,
2033             "DETAILED_MSG", "avsession service cast audio");
2034         ret = SelectOutputDevice(session->GetUid(), sinkAudioDescriptor);
2035         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "selectOutputDevice failed");
2036     }
2037     SLOGI("success");
2038     return AVSESSION_SUCCESS;
2039 }
2040 
CancelCastAudioInner(const std::vector<AudioStandard::AudioDeviceDescriptor> & sinkDevices,const std::string & sourceSessionInfo,const sptr<AVSessionItem> & session)2041 int32_t AVSessionService::CancelCastAudioInner(const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkDevices,
2042                                                const std::string& sourceSessionInfo,
2043                                                const sptr <AVSessionItem>& session)
2044 {
2045     SLOGI("cancel sinkDevices size is %{public}d", static_cast<int32_t>(sinkDevices.size()));
2046     CHECK_AND_RETURN_RET_LOG(!sinkDevices.empty(), AVSESSION_ERROR, "sinkDevices is empty");
2047     for (const auto& sinkDevice : sinkDevices) {
2048         if (IsLocalDevice(sinkDevice.networkId_)) {
2049             SLOGI("cancel Local device %{public}.6s", sinkDevice.networkId_.c_str());
2050             continue;
2051         }
2052         std::string sinkSessionInfo;
2053         SLOGI("cancel sinkDevices sinkDevice.networkId_ is %{public}.6s", sinkDevice.networkId_.c_str());
2054         auto service = GetService(sinkDevice.networkId_);
2055         CHECK_AND_RETURN_RET_LOG(service != nullptr, AVSESSION_ERROR, "GetService %{public}s failed",
2056                                  sinkDevice.networkId_.c_str());
2057         int32_t ret = service->ProcessCastAudioCommand(RemoteServiceCommand::COMMAND_CANCEL_CAST_AUDIO,
2058                                                        sourceSessionInfo, sinkSessionInfo);
2059         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "ProcessCastAudioCommand failed");
2060         ret = session->SourceCancelCastAudio(sinkDevice.networkId_);
2061         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SourceCancelCastAudio failed");
2062     }
2063     return AVSESSION_SUCCESS;
2064 }
2065 
CastAudioForNewSession(const sptr<AVSessionItem> & session)2066 int32_t AVSessionService::CastAudioForNewSession(const sptr<AVSessionItem>& session)
2067 {
2068     SLOGI("new sessionId is %{public}s", AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str());
2069     SessionToken token;
2070     token.sessionId = session->GetSessionId();
2071     token.pid = session->GetPid();
2072     token.uid = session->GetUid();
2073 
2074     int32_t ret = AVSESSION_SUCCESS;
2075     std::vector<AudioStandard::AudioDeviceDescriptor> castSinkDevices;
2076     {
2077         std::lock_guard lockGuard(outputDeviceIdLock_);
2078         ret = GetAudioDescriptor(outputDeviceId_, castSinkDevices);
2079         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetAudioDescriptor failed");
2080     }
2081 
2082     ret = CastAudio(token, castSinkDevices);
2083     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudio error, session Id is %{public}s",
2084                              AVSessionUtils::GetAnonySessionId(token.sessionId).c_str());
2085 
2086     SLOGI("success");
2087     return AVSESSION_SUCCESS;
2088 }
2089 
CastAudioForAll(const std::vector<AudioStandard::AudioDeviceDescriptor> & sinkAudioDescriptors)2090 int32_t AVSessionService::CastAudioForAll(const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkAudioDescriptors)
2091 {
2092     CHECK_AND_RETURN_RET_LOG(sinkAudioDescriptors.size() > 0, ERR_INVALID_PARAM, "sinkAudioDescriptors is empty");
2093     if (!PermissionChecker::GetInstance().CheckSystemPermission()) {
2094         SLOGE("CastAudioForAll: CheckSystemPermission failed");
2095         HISYSEVENT_SECURITY("CONTROL_PERMISSION_DENIED", "CALLER_UID", GetCallingUid(), "CALLER_PID", GetCallingPid(),
2096                             "ERROR_MSG", "avsessionservice CastAudioForAll checksystempermission failed");
2097         return ERR_NO_PERMISSION;
2098     }
2099 
2100     {
2101         std::lock_guard lockGuard(isAllSessionCastLock_);
2102         isAllSessionCast_ = false;
2103         if (!IsLocalDevice(sinkAudioDescriptors[0].networkId_)) {
2104             isAllSessionCast_ = true;
2105         }
2106     }
2107     for (const auto& session : GetContainer().GetAllSessions()) {
2108         SessionToken token;
2109         token.sessionId = session->GetSessionId();
2110         token.pid = session->GetPid();
2111         token.uid = session->GetUid();
2112         SLOGI("cast session %{public}s", token.sessionId.c_str());
2113         int32_t ret = CastAudio(token, sinkAudioDescriptors);
2114         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudio session %{public}s failed",
2115                                  AVSessionUtils::GetAnonySessionId(token.sessionId).c_str());
2116         {
2117             std::lock_guard lockGuard(outputDeviceIdLock_);
2118             outputDeviceId_ = session->GetDescriptor().outputDeviceInfo_.deviceInfos_[0].deviceId_;
2119         }
2120     }
2121 
2122     SLOGI("isAllSessionCast_ %{public}d, outputDeviceId_ is %{public}s", isAllSessionCast_, outputDeviceId_.c_str());
2123     return AVSESSION_SUCCESS;
2124 }
2125 
ProcessCastAudioCommand(const RemoteServiceCommand command,const std::string & input,std::string & output)2126 int32_t AVSessionService::ProcessCastAudioCommand(const RemoteServiceCommand command, const std::string& input,
2127                                                   std::string& output)
2128 {
2129     SLOGI("ProcessCastAudioCommand is %{public}d", static_cast<int32_t>(command));
2130     CHECK_AND_RETURN_RET_LOG(command > COMMAND_INVALID && command < COMMAND_MAX, AVSESSION_ERROR, "invalid command");
2131     if (command == COMMAND_CAST_AUDIO) {
2132         int ret = RemoteCastAudioInner(input, output);
2133         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "RemoteCastAudioInner error");
2134         return AVSESSION_SUCCESS;
2135     }
2136 
2137     int ret = RemoteCancelCastAudioInner(input);
2138     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "RemoteCancelCastAudioInner error");
2139     SLOGI("success");
2140     return AVSESSION_SUCCESS;
2141 }
2142 
RemoteCastAudioInner(const std::string & sourceSessionInfo,std::string & sinkSessionInfo)2143 int32_t AVSessionService::RemoteCastAudioInner(const std::string& sourceSessionInfo, std::string& sinkSessionInfo)
2144 {
2145     SLOGI("sourceInfo : %{public}s", sourceSessionInfo.c_str());
2146     AVSessionDescriptor sourceDescriptor;
2147     int32_t ret = JsonUtils::GetSessionDescriptor(sourceSessionInfo, sourceDescriptor);
2148     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetSessionDescriptor failed");
2149 
2150     ret = SetBasicInfo(sinkSessionInfo);
2151     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, AVSESSION_ERROR, "SetBasicInfo failed");
2152     AVSessionBasicInfo sinkDeviceInfo;
2153     ret = JsonUtils::GetSessionBasicInfo(sinkSessionInfo, sinkDeviceInfo);
2154     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetBasicInfo failed");
2155 
2156     sptr <AVSessionItem> session = CreateSessionInner(sourceDescriptor.sessionTag_, sourceDescriptor.sessionType_,
2157                                                       sourceDescriptor.isThirdPartyApp_,
2158                                                       sourceDescriptor.elementName_);
2159     SLOGI("source sessionId_ %{public}s", AVSessionUtils::GetAnonySessionId(sourceDescriptor.sessionId_).c_str());
2160     CHECK_AND_RETURN_RET_LOG(session != nullptr, AVSESSION_ERROR, "CreateSession failed");
2161     SLOGI("sink deviceId %{public}s", AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str());
2162 
2163     {
2164         std::lock_guard lockGuard(castAudioSessionMapLock_);
2165         castAudioSessionMap_[sourceDescriptor.sessionId_] = session->GetSessionId();
2166     }
2167 
2168     AVSessionBasicInfo sourceDeviceInfo;
2169     ret = JsonUtils::GetSessionBasicInfo(sourceSessionInfo, sourceDeviceInfo);
2170     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetBasicInfo failed");
2171     std::string sourceCapability;
2172     ret = JsonUtils::GetAllCapability(sourceSessionInfo, sourceCapability);
2173     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetAllCapability failed");
2174     ret = session->CastAudioFromRemote(sourceDescriptor.sessionId_, sourceDeviceInfo.networkId_,
2175                                        sinkDeviceInfo.networkId_, sourceCapability);
2176     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudioFromRemote failed");
2177     SLOGI("CastAudioFromRemote success");
2178     JsonUtils::SetSessionDescriptor(sinkSessionInfo, session->GetDescriptor());
2179     SLOGI("sinkSessionInfo : %{public}s", sinkSessionInfo.c_str());
2180     return AVSESSION_SUCCESS;
2181 }
2182 
RemoteCancelCastAudioInner(const std::string & sessionInfo)2183 int32_t AVSessionService::RemoteCancelCastAudioInner(const std::string& sessionInfo)
2184 {
2185     SLOGI("sessionInfo is %{public}s", sessionInfo.c_str());
2186     AVSessionBasicInfo sourceDeviceInfo;
2187     int32_t ret = JsonUtils::GetSessionBasicInfo(sessionInfo, sourceDeviceInfo);
2188     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetBasicInfo failed");
2189     AVSessionDescriptor sourceDescriptor;
2190     ret = JsonUtils::GetSessionDescriptor(sessionInfo, sourceDescriptor);
2191     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetSessionDescriptor failed");
2192 
2193     std::lock_guard lockGuard(castAudioSessionMapLock_);
2194     auto iter = castAudioSessionMap_.find(sourceDescriptor.sessionId_);
2195     CHECK_AND_RETURN_RET_LOG(iter != castAudioSessionMap_.end(), AVSESSION_ERROR, "no source session %{public}s",
2196                              AVSessionUtils::GetAnonySessionId(sourceDescriptor.sessionId_).c_str());
2197     auto session = GetContainer().GetSessionById(iter->second);
2198     CHECK_AND_RETURN_RET_LOG(session != nullptr, AVSESSION_ERROR, "no sink session %{public}s",
2199         AVSessionUtils::GetAnonySessionId(iter->second).c_str());
2200 
2201     ret = session->SinkCancelCastAudio();
2202     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SinkCancelCastAudio failed");
2203     ClearSessionNoLock(session->GetSessionId());
2204     castAudioSessionMap_.erase(sourceDescriptor.sessionId_);
2205     SLOGI("cancel source session %{public}s success",
2206         AVSessionUtils::GetAnonySessionId(sourceDescriptor.sessionId_).c_str());
2207     return AVSESSION_SUCCESS;
2208 }
2209 
CancelCastAudioForClientExit(pid_t pid,const sptr<AVSessionItem> & session)2210 int32_t AVSessionService::CancelCastAudioForClientExit(pid_t pid, const sptr<AVSessionItem>& session)
2211 {
2212     CHECK_AND_RETURN_RET_LOG(session != nullptr, AVSESSION_ERROR, "session is nullptr");
2213     SLOGI("pid is %{public}d, sessionId is %{public}s", static_cast<int32_t>(pid),
2214         AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str());
2215     std::string sourceSessionInfo;
2216     int32_t ret = SetBasicInfo(sourceSessionInfo);
2217     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetBasicInfo failed");
2218     ret = JsonUtils::SetSessionDescriptor(sourceSessionInfo, session->GetDescriptor());
2219     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetDescriptorInfo failed");
2220 
2221     std::vector<AudioStandard::AudioDeviceDescriptor> cancelSinkDevices;
2222     ret = GetAudioDescriptor(session->GetDescriptor().outputDeviceInfo_.deviceInfos_[0].deviceId_, cancelSinkDevices);
2223     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetAudioDescriptor failed");
2224 
2225     ret = CancelCastAudioInner(cancelSinkDevices, sourceSessionInfo, session);
2226     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CancelCastAudioInner failed");
2227     return AVSESSION_SUCCESS;
2228 }
2229 
GetAudioDescriptor(const std::string deviceId,std::vector<AudioStandard::AudioDeviceDescriptor> & audioDeviceDescriptors)2230 int32_t AVSessionService::GetAudioDescriptor(const std::string deviceId,
2231                                              std::vector<AudioStandard::AudioDeviceDescriptor>& audioDeviceDescriptors)
2232 {
2233     auto audioDescriptors = AudioSystemManager::GetInstance()->GetDevices(ALL_L_D_DEVICES_FLAG);
2234     AudioDeviceDescriptor audioDescriptor;
2235     if (GetAudioDescriptorByDeviceId(audioDescriptors, deviceId, audioDescriptor)) {
2236         audioDeviceDescriptors.push_back(audioDescriptor);
2237         SLOGI("get audio deviceId %{public}d, networkId_ is %{public}.6s", audioDescriptor.deviceId_,
2238               audioDescriptor.networkId_.c_str());
2239         return AVSESSION_SUCCESS;
2240     }
2241     SLOGI("can not get deviceId %{public}s info", deviceId.c_str());
2242     return AVSESSION_ERROR;
2243 }
2244 
ClearSessionForClientDiedNoLock(pid_t pid)2245 void AVSessionService::ClearSessionForClientDiedNoLock(pid_t pid)
2246 {
2247     auto sessions = GetContainer().RemoveSession(pid);
2248     for (const auto& session : sessions) {
2249         if (topSession_ == session) {
2250             UpdateTopSession(nullptr);
2251         }
2252         if (session->GetRemoteSource() != nullptr) {
2253             int32_t ret = CancelCastAudioForClientExit(pid, session);
2254             SLOGI("CancelCastAudioForClientExit ret is %{public}d", ret);
2255         }
2256         SLOGI("remove sessionId=%{public}s", AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str());
2257         session->Destroy();
2258     }
2259 }
2260 
ClearSessionNoLock(const std::string & sessionId)2261 void AVSessionService::ClearSessionNoLock(const std::string& sessionId)
2262 {
2263     auto session = GetContainer().RemoveSession(sessionId);
2264     if (topSession_ == session) {
2265         UpdateTopSession(nullptr);
2266     }
2267     SLOGI("remove sessionId=%{public}s", AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str());
2268     session->Destroy();
2269 }
2270 
ClearControllerForClientDiedNoLock(pid_t pid)2271 void AVSessionService::ClearControllerForClientDiedNoLock(pid_t pid)
2272 {
2273     auto it = controllers_.find(pid);
2274     CHECK_AND_RETURN_LOG(it != controllers_.end(), "no find controller");
2275     auto controllers = std::move(it->second);
2276     SLOGI("remove controllers size=%{public}d", static_cast<int>(controllers.size()));
2277     if (!controllers.empty()) {
2278         for (const auto& controller : controllers) {
2279             controller->Destroy();
2280         }
2281     }
2282     it = controllers_.find(pid);
2283     CHECK_AND_RETURN_LOG(it != controllers_.end(), "no find controller");
2284     controllers_.erase(pid);
2285 }
2286 
ClientDeathRecipient(const std::function<void ()> & callback)2287 ClientDeathRecipient::ClientDeathRecipient(const std::function<void()>& callback)
2288     : callback_(callback)
2289 {
2290     SLOGD("construct");
2291 }
2292 
OnRemoteDied(const wptr<IRemoteObject> & object)2293 void ClientDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& object)
2294 {
2295     if (callback_) {
2296         callback_();
2297     }
2298 }
2299 
LoadStringFromFileEx(const string & filePath,string & content)2300 bool AVSessionService::LoadStringFromFileEx(const string& filePath, string& content)
2301 {
2302     std::lock_guard lockGuard(fileCheckLock_);
2303     SLOGI("file load in for path: %{public}s", filePath.c_str());
2304     ifstream file(filePath.c_str());
2305     if (!file.is_open()) {
2306         SLOGD("file not open! try open first ! ");
2307         file.open(filePath.c_str(), ios::app);
2308         if (!file.is_open()) {
2309             SLOGE("open file again fail !");
2310             return false;
2311         }
2312     }
2313     file.seekg(0, ios::end);
2314     const long fileLength = file.tellg();
2315     SLOGI("get file length(%{public}ld)!", fileLength);
2316     if (fileLength > maxFileLength) {
2317         SLOGE("invalid file length(%{public}ld)!", fileLength);
2318         return false;
2319     }
2320     if (fileLength <= 0) {
2321         SLOGD("file new create empty ! try set init json ");
2322         ofstream fileWrite;
2323         fileWrite.open(filePath.c_str(), ios::out | ios::trunc);
2324         if (!fileWrite.is_open()) {
2325             SLOGE("open file in create new failed!");
2326             file.close();
2327             return false;
2328         }
2329         nlohmann::json emptyValue;
2330         std::string emptyContent = emptyValue.dump();
2331         SLOGD("LoadStringFromFileEx::Dump json object finished");
2332         fileWrite.write(emptyContent.c_str(), emptyContent.length());
2333         if (fileWrite.fail()) {
2334             SLOGE("file empty init json fail !");
2335             file.close();
2336             fileWrite.close();
2337             return false;
2338         }
2339         fileWrite.close();
2340     }
2341     content.clear();
2342     file.seekg(0, ios::beg);
2343     copy(istreambuf_iterator<char>(file), istreambuf_iterator<char>(), back_inserter(content));
2344     file.close();
2345     return CheckStringAndCleanFile(filePath);
2346 }
2347 
SaveStringToFileEx(const std::string & filePath,const std::string & content)2348 bool AVSessionService::SaveStringToFileEx(const std::string& filePath, const std::string& content)
2349 {
2350     std::lock_guard lockGuard(fileCheckLock_);
2351     SLOGI("file save in for path:%{public}s, content:%{public}s", filePath.c_str(), content.c_str());
2352     nlohmann::json checkValues = json::parse(content, nullptr, false);
2353     CHECK_AND_RETURN_RET_LOG(!checkValues.is_discarded(), false, "recv content discarded");
2354     ofstream file;
2355     file.open(filePath.c_str(), ios::out | ios::trunc);
2356     if (!file.is_open()) {
2357         SLOGE("open file in save failed!");
2358         return false;
2359     }
2360     if (content.empty()) {
2361         SLOGE("write content is empty, no need to do write!");
2362         file.close();
2363         return true;
2364     }
2365     file.write(content.c_str(), content.length());
2366     if (file.fail()) {
2367         SLOGE("write content to file failed!");
2368         file.close();
2369         return false;
2370     }
2371     file.close();
2372     return CheckStringAndCleanFile(filePath);
2373 }
2374 
CheckStringAndCleanFile(const std::string & filePath)2375 bool AVSessionService::CheckStringAndCleanFile(const std::string& filePath)
2376 {
2377     SLOGI("file check for path:%{public}s", filePath.c_str());
2378     string content {};
2379     ifstream fileRead(filePath.c_str());
2380     if (!fileRead.is_open()) {
2381         SLOGD("file not open! try open first ! ");
2382         fileRead.open(filePath.c_str(), ios::app);
2383         if (!fileRead.is_open()) {
2384             SLOGE("open file again fail !");
2385             return false;
2386         }
2387     }
2388     content.clear();
2389     fileRead.seekg(0, ios::beg);
2390     copy(istreambuf_iterator<char>(fileRead), istreambuf_iterator<char>(), back_inserter(content));
2391     SLOGI("check content pre clean it: %{public}s", content.c_str());
2392     nlohmann::json checkValues = json::parse(content, nullptr, false);
2393     if (checkValues.is_discarded()) {
2394         SLOGE("check content discarded!");
2395         ofstream fileWrite;
2396         fileWrite.open(filePath.c_str(), ios::out | ios::trunc);
2397         if (!fileWrite.is_open()) {
2398             SLOGE("open file in create new failed!");
2399             fileRead.close();
2400             return false;
2401         }
2402         nlohmann::json emptyValue;
2403         std::string emptyContent = emptyValue.dump();
2404         SLOGD("LoadStringFromFileEx::Dump json object finished");
2405         fileWrite.write(emptyContent.c_str(), emptyContent.length());
2406         if (fileWrite.fail()) {
2407             SLOGE("file empty init json fail !");
2408             fileRead.close();
2409             fileWrite.close();
2410             return false;
2411         }
2412         fileWrite.close();
2413     }
2414     fileRead.close();
2415     return true;
2416 }
2417 
CreateWantAgent(const AVSessionDescriptor * histroyDescriptor)2418 std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> AVSessionService::CreateWantAgent(
2419     const AVSessionDescriptor* histroyDescriptor)
2420 {
2421     if (histroyDescriptor == nullptr && topSession_ == nullptr) {
2422         SLOGE("CreateWantAgent error, histroyDescriptor and topSession_ null");
2423         return nullptr;
2424     }
2425     std::vector<AbilityRuntime::WantAgent::WantAgentConstant::Flags> flags;
2426     flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG);
2427     std::vector<std::shared_ptr<AAFwk::Want>> wants;
2428     std::shared_ptr<AAFwk::Want> want = std::make_shared<AAFwk::Want>();
2429     string bundleName = DEFAULT_BUNDLE_NAME;
2430     string abilityName = DEFAULT_ABILITY_NAME;
2431     auto uid = -1;
2432     if (topSession_ != nullptr) {
2433         bundleName = topSession_->GetBundleName();
2434         abilityName = topSession_->GetAbilityName();
2435         uid = topSession_->GetUid();
2436     }
2437     if (histroyDescriptor != nullptr) {
2438         SLOGI("CreateWantAgent with historyDescriptor");
2439         bundleName = histroyDescriptor->elementName_.GetBundleName();
2440         abilityName = histroyDescriptor->elementName_.GetAbilityName();
2441         uid = histroyDescriptor->uid_;
2442     }
2443     SLOGI("CreateWantAgent bundleName %{public}s, abilityName %{public}s", bundleName.c_str(), abilityName.c_str());
2444     AppExecFwk::ElementName element("", bundleName, abilityName);
2445     want->SetElement(element);
2446     wants.push_back(want);
2447     AbilityRuntime::WantAgent::WantAgentInfo wantAgentInfo(
2448         0,
2449         AbilityRuntime::WantAgent::WantAgentConstant::OperationType::START_ABILITY,
2450         flags,
2451         wants,
2452         nullptr
2453     );
2454     return AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, uid);
2455 }
2456 
NotifySystemUI(const AVSessionDescriptor * historyDescriptor)2457 void AVSessionService::NotifySystemUI(const AVSessionDescriptor* historyDescriptor)
2458 {
2459     auto deviceProp = system::GetParameter("const.product.devicetype", "default");
2460     CHECK_AND_RETURN_LOG(strcmp(deviceProp.c_str(), "2in1") != 0, "2in1 not support");
2461     int32_t result = Notification::NotificationHelper::SubscribeLocalLiveViewNotification(NOTIFICATION_SUBSCRIBER);
2462     CHECK_AND_RETURN_LOG(result == ERR_OK, "create notification subscriber error %{public}d", result);
2463 
2464     Notification::NotificationRequest request;
2465     std::shared_ptr<Notification::NotificationLocalLiveViewContent> localLiveViewContent =
2466         std::make_shared<Notification::NotificationLocalLiveViewContent>();
2467     CHECK_AND_RETURN_LOG(localLiveViewContent != nullptr, "avsession item local live view content nullptr error");
2468     localLiveViewContent->SetType(SYSTEMUI_LIVEVIEW_TYPECODE_MDEDIACONTROLLER);
2469     localLiveViewContent->SetTitle(historyDescriptor ? "" : "AVSession NotifySystemUI");
2470     localLiveViewContent->SetText(historyDescriptor ? "" : "AVSession NotifySystemUI");
2471 
2472     std::shared_ptr<Notification::NotificationContent> content =
2473         std::make_shared<Notification::NotificationContent>(localLiveViewContent);
2474     CHECK_AND_RETURN_LOG(content != nullptr, "avsession item notification content nullptr error");
2475 
2476     auto uid = topSession_ ? topSession_->GetUid() : getuid();
2477     request.SetSlotType(Notification::NotificationConstant::SlotType::LIVE_VIEW);
2478     request.SetNotificationId(0);
2479     request.SetContent(content);
2480     request.SetCreatorUid(uid);
2481     request.SetUnremovable(true);
2482     request.SetInProgress(true);
2483     std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> wantAgent = CreateWantAgent(historyDescriptor);
2484     CHECK_AND_RETURN_LOG(wantAgent != nullptr, "wantAgent nullptr error");
2485     request.SetWantAgent(wantAgent);
2486     result = Notification::NotificationHelper::PublishNotification(request);
2487     SLOGI("AVSession service PublishNotification uid %{public}d, result %{public}d", uid, result);
2488 }
2489 
NotifyDeviceChange(const DeviceChangeAction & deviceChangeAction)2490 void AVSessionService::NotifyDeviceChange(const DeviceChangeAction& deviceChangeAction)
2491 {
2492     // historical sessions
2493     std::vector<AVSessionDescriptor> hisDescriptors;
2494     GetHistoricalSessionDescriptors(1, hisDescriptors);
2495     // all sessions
2496     std::vector<AVSessionDescriptor> activeDescriptors;
2497     GetAllSessionDescriptors(activeDescriptors);
2498     // historical avqueueinfos
2499     std::vector<AVQueueInfo> avQueueInfos;
2500     GetHistoricalAVQueueInfos(1, 1, avQueueInfos);
2501     AVSessionDescriptor selectSession;
2502     if (activeDescriptors.size() != 0 || hisDescriptors.size() == 0 || avQueueInfos.size() == 0) {
2503         return;
2504     }
2505     for (AVSessionDescriptor session : hisDescriptors) {
2506         if (session.elementName_.GetBundleName() == avQueueInfos[0].GetBundleName()) {
2507             selectSession = session;
2508             break;
2509         }
2510     }
2511     if (deviceChangeAction.type == AudioStandard::CONNECT) {
2512         SLOGI("history bundle name %{public}s", selectSession.elementName_.GetBundleName().c_str());
2513         NotifySystemUI(&selectSession);
2514     }
2515 }
2516 
HandleDeviceChange(const DeviceChangeAction & deviceChangeAction)2517 void AVSessionService::HandleDeviceChange(const DeviceChangeAction& deviceChangeAction)
2518 {
2519     SLOGI("AVSessionService HandleDeviceChange");
2520     for (auto &audioDeviceDescriptor : deviceChangeAction.deviceDescriptors) {
2521         SLOGI("AVSessionService HandleDeviceChange device type %{public}d", audioDeviceDescriptor->deviceType_);
2522         if (audioDeviceDescriptor->deviceType_ == AudioStandard::DEVICE_TYPE_WIRED_HEADSET ||
2523             audioDeviceDescriptor->deviceType_ == AudioStandard::DEVICE_TYPE_WIRED_HEADPHONES ||
2524             audioDeviceDescriptor->deviceType_ == AudioStandard::DEVICE_TYPE_USB_HEADSET ||
2525             audioDeviceDescriptor->deviceType_ == AudioStandard::DEVICE_TYPE_BLUETOOTH_A2DP) {
2526             NotifyDeviceChange(deviceChangeAction);
2527         }
2528     }
2529 }
2530 } // namespace OHOS::AVSession
2531