1 /*
2 * Copyright (c) 2022-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #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 "account_manager_adapter.h"
26 #include "app_manager_adapter.h"
27 #include "audio_adapter.h"
28 #include "avsession_dynamic_loader.h"
29 #include "avsession_errors.h"
30 #include "avsession_log.h"
31 #include "avsession_info.h"
32 #include "device_manager.h"
33 #include "remote_session_capability_set.h"
34 #include "remote_session_source_proxy.h"
35 #include "remote_session_sink_proxy.h"
36 #include "file_ex.h"
37 #include "iservice_registry.h"
38 #include "key_event_adapter.h"
39 #include "nlohmann/json.hpp"
40 #include "permission_checker.h"
41 #include "system_ability_definition.h"
42 #include "session_stack.h"
43 #include "avsession_trace.h"
44 #include "hash_calculator.h"
45 #include "avsession_dumper.h"
46 #include "command_send_limit.h"
47 #include "avsession_sysevent.h"
48 #include "json_utils.h"
49 #include "avsession_utils.h"
50 #include "avcontrol_command.h"
51 #include "avsession_event_handler.h"
52 #include "bundle_status_adapter.h"
53 #include "params_config_operator.h"
54 #include "notification_content.h"
55 #include "notification_helper.h"
56 #include "notification_request.h"
57 #include "notification_constant.h"
58 #include "ability_connect_helper.h"
59 #include "if_system_ability_manager.h"
60 #include "parameter.h"
61 #include "parameters.h"
62 #include "avsession_service.h"
63 #include "want_agent_helper.h"
64 #include "avsession_radar.h"
65 #include "os_account_manager.h"
66
67 typedef void (*MigrateStubFunc)(std::function<void(std::string, std::string, std::string, std::string)>);
68 typedef void (*StopMigrateStubFunc)(void);
69
70 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
71 #include "av_router.h"
72 #include "collaboration_manager.h"
73 #endif
74
75 #if !defined(WINDOWS_PLATFORM) and !defined(MAC_PLATFORM) and !defined(IOS_PLATFORM)
76 #include <malloc.h>
77 #endif
78
79 using namespace std;
80 using namespace nlohmann;
81 using namespace OHOS::AudioStandard;
82
83 namespace OHOS::AVSession {
84
85 static const std::string AVSESSION_DYNAMIC_INSIGHT_LIBRARY_PATH = std::string("libavsession_dynamic_insight.z.so");
86
87 static const int32_t CAST_ENGINE_SA_ID = 65546;
88 static const int32_t COLLABORATION_SA_ID = 70633;
89 static const int32_t MININUM_FOR_NOTIFICATION = 5;
90 const std::string BOOTEVENT_AVSESSION_SERVICE_READY = "bootevent.avsessionservice.ready";
91
92 class NotificationSubscriber : public Notification::NotificationLocalLiveViewSubscriber {
OnConnected()93 void OnConnected() {}
OnDisconnected()94 void OnDisconnected() {}
OnResponse(int32_t notificationId,sptr<Notification::NotificationButtonOption> buttonOption)95 void OnResponse(int32_t notificationId, sptr<Notification::NotificationButtonOption> buttonOption) {}
OnDied()96 void OnDied() {}
97 };
98
99 static const auto NOTIFICATION_SUBSCRIBER = NotificationSubscriber();
100
101 REGISTER_SYSTEM_ABILITY_BY_ID(AVSessionService, AVSESSION_SERVICE_ID, true);
102
AVSessionService(int32_t systemAbilityId,bool runOnCreate)103 AVSessionService::AVSessionService(int32_t systemAbilityId, bool runOnCreate)
104 : SystemAbility(systemAbilityId, runOnCreate)
105 {
106 SLOGD("construct");
107 }
108
~AVSessionService()109 AVSessionService::~AVSessionService()
110 {
111 GetUsersManager().ClearCache();
112 SLOGD("destroy");
113 }
114
OnStart()115 void AVSessionService::OnStart()
116 {
117 GetUsersManager().ClearCache();
118 CHECK_AND_RETURN_LOG(Publish(this), "publish avsession service failed");
119 dumpHelper_ = std::make_unique<AVSessionDumper>();
120 CHECK_AND_RETURN_LOG(dumpHelper_ != nullptr, "no memory");
121 CommandSendLimit::GetInstance().StartTimer();
122
123 ParamsConfigOperator::GetInstance().InitConfig();
124 auto ret = ParamsConfigOperator::GetInstance().GetValueIntByKey("historicalRecordMaxNum", &maxHistoryNums);
125 if (ret == AVSESSION_ERROR) {
126 maxHistoryNums = defMaxHistoryNum;
127 }
128
129 #ifdef ENABLE_BACKGROUND_AUDIO_CONTROL
130 backgroundAudioController_.Init(this);
131 AddInnerSessionListener(&backgroundAudioController_);
132 #endif
133
134 AddSystemAbilityListener(MULTIMODAL_INPUT_SERVICE_ID);
135 AddSystemAbilityListener(AUDIO_POLICY_SERVICE_ID);
136 AddSystemAbilityListener(APP_MGR_SERVICE_ID);
137 AddSystemAbilityListener(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID);
138 AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
139 AddSystemAbilityListener(CAST_ENGINE_SA_ID);
140 AddSystemAbilityListener(COLLABORATION_SA_ID);
141 AddSystemAbilityListener(MEMORY_MANAGER_SA_ID);
142 AddSystemAbilityListener(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN);
143 AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
144
145 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
146 is2in1_ = system::GetBoolParameter("const.audio.volume_apply_to_all", false);
147 SLOGI("GetDeviceEnableCast, Prop=%{public}d", static_cast<int>(is2in1_));
148 CollaborationManager::GetInstance().ReadCollaborationManagerSo();
149 CollaborationManager::GetInstance().RegisterLifecycleCallback();
150 #endif
151
152 HISYSEVENT_REGITER;
153 HISYSEVENT_BEHAVIOR("SESSION_SERVICE_START", "SERVICE_NAME", "AVSessionService",
154 "SERVICE_ID", AVSESSION_SERVICE_ID, "DETAILED_MSG", "avsession service start success");
155 if (!system::GetBoolParameter(BOOTEVENT_AVSESSION_SERVICE_READY.c_str(), false)) {
156 system::SetParameter(BOOTEVENT_AVSESSION_SERVICE_READY.c_str(), "true");
157 SLOGI("set boot avsession service started true");
158 }
159 }
160
OnDump()161 void AVSessionService::OnDump()
162 {
163 }
164
OnStop()165 void AVSessionService::OnStop()
166 {
167 StopMigrateStubFunc stopMigrateStub =
168 reinterpret_cast<StopMigrateStubFunc>(dlsym(migrateStubFuncHandle_, "StopMigrateStub"));
169 if (stopMigrateStub == nullptr) {
170 SLOGE("failed to find library, reason: %{public}sn", dlerror());
171 } else {
172 stopMigrateStub();
173 }
174 #ifndef TEST_COVERAGE
175 dlclose(migrateStubFuncHandle_);
176 #endif
177 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
178 CollaborationManager::GetInstance().UnRegisterLifecycleCallback();
179 #endif
180 CommandSendLimit::GetInstance().StopTimer();
181 NotifyProcessStatus(false);
182 SLOGI("UnSubscribeCommonEvent result=%{public}d", UnSubscribeCommonEvent());
183 }
184
EventSubscriber(const EventFwk::CommonEventSubscribeInfo & subscriberInfo,AVSessionService * ptr)185 EventSubscriber::EventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscriberInfo, AVSessionService *ptr)
186 : EventFwk::CommonEventSubscriber(subscriberInfo)
187 {
188 servicePtr_ = ptr;
189 }
190
OnReceiveEvent(const EventFwk::CommonEventData & eventData)191 void EventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &eventData)
192 {
193 const AAFwk::Want &want = eventData.GetWant();
194 std::string action = want.GetAction();
195 SLOGI("OnReceiveEvent action:%{public}s.", action.c_str());
196 if (servicePtr_ == nullptr) {
197 SLOGE("OnReceiveEvent get action:%{public}s with servicePtr_ null", action.c_str());
198 return;
199 }
200 if (action.compare(EventFwk::CommonEventSupport::COMMON_EVENT_USER_FOREGROUND) == 0) {
201 int32_t userIdForeground = eventData.GetCode();
202 servicePtr_->HandleUserEvent(AVSessionUsersManager::accountEventSwitched, userIdForeground);
203 } else if (action.compare(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) == 0) {
204 int32_t userIdSwitched = eventData.GetCode();
205 servicePtr_->HandleUserEvent(AVSessionUsersManager::accountEventSwitched, userIdSwitched);
206 } else if (action.compare(EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED) == 0) {
207 int32_t userId = eventData.GetCode();
208 servicePtr_->HandleUserEvent(AVSessionUsersManager::accountEventRemoved, userId);
209 } else if (action.compare(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED) == 0) {
210 int32_t userId = eventData.GetCode();
211 servicePtr_->RegisterBundleDeleteEventForHistory(userId);
212 }
213 }
214
GetAVQueueDir(int32_t userId)215 std::string AVSessionService::GetAVQueueDir(int32_t userId)
216 {
217 return GetUsersManager().GetDirForCurrentUser(userId) + AVQUEUE_FILE_NAME;
218 }
219
GetAVSortDir(int32_t userId)220 std::string AVSessionService::GetAVSortDir(int32_t userId)
221 {
222 return GetUsersManager().GetDirForCurrentUser(userId) + SORT_FILE_NAME;
223 }
224
HandleUserEvent(const std::string & type,const int & userId)225 void AVSessionService::HandleUserEvent(const std::string &type, const int &userId)
226 {
227 GetUsersManager().NotifyAccountsEvent(type, userId);
228 UpdateTopSession(GetUsersManager().GetTopSession());
229 }
230
SubscribeCommonEvent()231 bool AVSessionService::SubscribeCommonEvent()
232 {
233 const std::vector<std::string> events = {
234 EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF,
235 EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON,
236 EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED,
237 EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED,
238 EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED,
239 EventFwk::CommonEventSupport::COMMON_EVENT_USER_FOREGROUND,
240 EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED,
241 EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED,
242 };
243
244 EventFwk::MatchingSkills matchingSkills;
245 for (auto event : events) {
246 matchingSkills.AddEvent(event);
247 }
248 EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
249
250 subscriber_ = std::make_shared<EventSubscriber>(subscribeInfo, this);
251 return EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber_);
252 }
253
UnSubscribeCommonEvent()254 bool AVSessionService::UnSubscribeCommonEvent()
255 {
256 bool subscribeResult = false;
257 if (subscriber_ != nullptr) {
258 subscribeResult = EventFwk::CommonEventManager::UnSubscribeCommonEvent(subscriber_);
259 subscriber_ = nullptr;
260 SLOGI("UnSubscribeCommonEvent subscribeResult = %{public}d", subscribeResult);
261 }
262 return subscribeResult;
263 }
264
PullMigrateStub()265 void AVSessionService::PullMigrateStub()
266 {
267 migrateStubFuncHandle_ = dlopen("libavsession_migration.z.so", RTLD_NOW);
268 if (migrateStubFuncHandle_ == nullptr) {
269 SLOGE("failed to dlopen library, reason: %{public}sn", dlerror());
270 return;
271 }
272 MigrateStubFunc startMigrateStub =
273 reinterpret_cast<MigrateStubFunc>(dlsym(migrateStubFuncHandle_, "StartMigrateStub"));
274 if (startMigrateStub == nullptr) {
275 SLOGE("failed to find library, reason: %{public}sn", dlerror());
276 return;
277 }
278 std::thread([startMigrateStub, this]() {
279 SLOGI("create thread to keep MigrateStub");
280 startMigrateStub([this](std::string deviceId, std::string serviceName, std::string extraInfo,
281 std::string state) { SuperLauncher(deviceId, serviceName, extraInfo, state); });
282 }).detach();
283 }
284
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)285 void AVSessionService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
286 {
287 switch (systemAbilityId) {
288 case MULTIMODAL_INPUT_SERVICE_ID:
289 InitKeyEvent();
290 break;
291 case AUDIO_POLICY_SERVICE_ID:
292 InitAudio();
293 break;
294 case APP_MGR_SERVICE_ID:
295 InitAMS();
296 break;
297 case DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID:
298 InitDM();
299 break;
300 case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID:
301 InitBMS();
302 InitRadarBMS();
303 break;
304 case CAST_ENGINE_SA_ID:
305 CheckInitCast();
306 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
307 if (is2in1_) {
308 checkEnableCast(true);
309 }
310 #endif
311 break;
312 case COLLABORATION_SA_ID:
313 PullMigrateStub();
314 break;
315 case MEMORY_MANAGER_SA_ID:
316 NotifyProcessStatus(true);
317 break;
318 case SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN:
319 InitAccountMgr();
320 break;
321 case COMMON_EVENT_SERVICE_ID:
322 InitCommonEventService();
323 break;
324 default:
325 SLOGE("undefined system ability %{public}d", systemAbilityId);
326 }
327 }
328
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)329 void AVSessionService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
330 {
331 SLOGI("remove system ability %{public}d", systemAbilityId);
332 }
333
334 // LCOV_EXCL_START
CheckInitCast()335 void AVSessionService::CheckInitCast()
336 {
337 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
338 SLOGI("AVSessionService CheckInitCast in");
339 sptr<ISystemAbilityManager> samgrProxy;
340 samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
341 if (samgrProxy == nullptr) {
342 SLOGE("AVSessionService CheckInitCast with samgrProxy null ");
343 return;
344 }
345 if (samgrProxy->CheckSystemAbility(CAST_ENGINE_SA_ID) == nullptr) {
346 SLOGI("check cast engine has been removed");
347 } else {
348 SLOGI("check cast engine has been started");
349 }
350 #endif
351 }
352 // LCOV_EXCL_STOP
353
NotifyProcessStatus(bool isStart)354 void AVSessionService::NotifyProcessStatus(bool isStart)
355 {
356 int pid = getpid();
357 void *libMemMgrClientHandle = dlopen("libmemmgrclient.z.so", RTLD_NOW);
358 if (!libMemMgrClientHandle) {
359 SLOGE("dlopen libmemmgrclient library failed");
360 return;
361 }
362 void *notifyProcessStatusFunc = dlsym(libMemMgrClientHandle, "notify_process_status");
363 if (!notifyProcessStatusFunc) {
364 SLOGE("dlsm notify_process_status failed");
365 #ifndef TEST_COVERAGE
366 dlclose(libMemMgrClientHandle);
367 #endif
368 return;
369 }
370 auto notifyProcessStatus = reinterpret_cast<int(*)(int, int, int, int)>(notifyProcessStatusFunc);
371 if (isStart) {
372 SLOGI("notify to memmgr when av_session is started");
373 notifyProcessStatus(pid, saType, 1, AVSESSION_SERVICE_ID); // 1 indicates the service is started
374 } else {
375 SLOGI("notify to memmgr when av_session is stopped");
376 notifyProcessStatus(pid, saType, 0, AVSESSION_SERVICE_ID); // 0 indicates the service is stopped
377 }
378 #ifndef TEST_COVERAGE
379 dlclose(libMemMgrClientHandle);
380 #endif
381 }
382
InitKeyEvent()383 void AVSessionService::InitKeyEvent()
384 {
385 SLOGI("enter");
386 std::vector<int32_t> keyCodes = {
387 MMI::KeyEvent::KEYCODE_MEDIA_PLAY,
388 MMI::KeyEvent::KEYCODE_MEDIA_PAUSE,
389 MMI::KeyEvent::KEYCODE_MEDIA_PLAY_PAUSE,
390 MMI::KeyEvent::KEYCODE_MEDIA_STOP,
391 MMI::KeyEvent::KEYCODE_MEDIA_NEXT,
392 MMI::KeyEvent::KEYCODE_MEDIA_PREVIOUS,
393 MMI::KeyEvent::KEYCODE_MEDIA_REWIND,
394 MMI::KeyEvent::KEYCODE_MEDIA_FAST_FORWARD,
395 MMI::KeyEvent::KEYCODE_HEADSETHOOK,
396 };
397
398 KeyEventAdapter::GetInstance().SubscribeKeyEvent(
399 keyCodes, [this](const auto& keyEvent) { SendSystemAVKeyEvent(*keyEvent); });
400 }
401
UpdateTopSession(const sptr<AVSessionItem> & newTopSession)402 void AVSessionService::UpdateTopSession(const sptr<AVSessionItem>& newTopSession)
403 {
404 if (newTopSession == nullptr) {
405 std::lock_guard lockGuard(sessionAndControllerLock_);
406 if (topSession_ != nullptr) {
407 topSession_->SetTop(false);
408 }
409 topSession_ = nullptr;
410 GetUsersManager().SetTopSession(nullptr);
411 SLOGI("set topSession to nullptr");
412 HISYSEVENT_BEHAVIOR("FOCUS_CHANGE", "DETAILED_MSG", "avsessionservice set topsession to nullptr");
413 return;
414 }
415
416 SLOGI("uid=%{public}d sessionId=%{public}s", newTopSession->GetUid(),
417 AVSessionUtils::GetAnonySessionId(newTopSession->GetSessionId()).c_str());
418 AVSessionDescriptor descriptor;
419 {
420 std::lock_guard lockGuard(sessionAndControllerLock_);
421 if (topSession_ != nullptr) {
422 topSession_->SetTop(false);
423 HISYSEVENT_BEHAVIOR("FOCUS_CHANGE",
424 "OLD_BUNDLE_NAME", topSession_->GetDescriptor().elementName_.GetBundleName(),
425 "OLD_MODULE_NAME", topSession_->GetDescriptor().elementName_.GetModuleName(),
426 "OLD_ABILITY_NAME", topSession_->GetAbilityName(), "OLD_SESSION_PID", topSession_->GetPid(),
427 "OLD_SESSION_UID", topSession_->GetUid(), "OLD_SESSION_ID", topSession_->GetSessionId(),
428 "OLD_SESSION_TAG", topSession_->GetDescriptor().sessionTag_,
429 "OLD_SESSION_TYPE", topSession_->GetDescriptor().sessionType_,
430 "BUNDLE_NAME", newTopSession->GetDescriptor().elementName_.GetBundleName(),
431 "MODULE_NAME", newTopSession->GetDescriptor().elementName_.GetModuleName(),
432 "ABILITY_NAME", newTopSession->GetAbilityName(), "SESSION_PID", newTopSession->GetPid(),
433 "SESSION_UID", newTopSession->GetUid(), "SESSION_ID", newTopSession->GetSessionId(),
434 "SESSION_TAG", newTopSession->GetDescriptor().sessionTag_,
435 "SESSION_TYPE", newTopSession->GetDescriptor().sessionType_,
436 "DETAILED_MSG", "avsessionservice handlefocussession, updatetopsession");
437 }
438 topSession_ = newTopSession;
439 GetUsersManager().SetTopSession(newTopSession);
440 topSession_->SetTop(true);
441 descriptor = topSession_->GetDescriptor();
442 }
443 NotifyTopSessionChanged(descriptor);
444 }
445
446 // LCOV_EXCL_START
HandleFocusSession(const FocusSessionStrategy::FocusSessionChangeInfo & info)447 void AVSessionService::HandleFocusSession(const FocusSessionStrategy::FocusSessionChangeInfo& info)
448 {
449 SLOGI("HandleFocusSession with uid=%{public}d, cur topSession:%{public}s",
450 info.uid, (topSession_ == nullptr ? "null" : topSession_->GetBundleName()).c_str());
451 std::lock_guard lockGuard(sessionAndControllerLock_);
452 if (topSession_ && topSession_->GetUid() == info.uid) {
453 SLOGI("same session");
454 if ((topSession_->GetSessionType() == "audio" || topSession_->GetSessionType() == "video") &&
455 topSession_->GetUid() != ancoUid) {
456 AVSessionService::NotifySystemUI(nullptr, true);
457 sessionPublishedMap_[info.uid] = true;
458 }
459 return;
460 }
461 std::lock_guard frontLockGuard(sessionFrontLock_);
462 std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront();
463 CHECK_AND_RETURN_LOG(sessionListForFront != nullptr, "sessionListForFront ptr nullptr!");
464 for (const auto& session : *sessionListForFront) {
465 if (session->GetUid() == info.uid &&
466 (session->GetSessionType() != "voice_call" && session->GetSessionType() != "video_call")) {
467 UpdateTopSession(session);
468 if ((topSession_->GetSessionType() == "audio" || topSession_->GetSessionType() == "video") &&
469 topSession_->GetUid() != ancoUid) {
470 AVSessionService::NotifySystemUI(nullptr, true);
471 sessionPublishedMap_[info.uid] = true;
472 }
473 return;
474 }
475 }
476 }
477 // LCOV_EXCL_STOP
478
479 // LCOV_EXCL_START
RefreshFocusSessionSort(sptr<AVSessionItem> & session)480 void AVSessionService::RefreshFocusSessionSort(sptr<AVSessionItem> &session)
481 {
482 std::lock_guard sortFileLockGuard(sortFileReadWriteLock_);
483 std::string oldSortContent;
484 if (!LoadStringFromFileEx(GetAVSortDir(), oldSortContent)) {
485 SLOGE("SelectFocusSession read sort fail !");
486 return;
487 }
488 nlohmann::json values = json::parse(oldSortContent, nullptr, false);
489 CHECK_AND_RETURN_LOG(!values.is_discarded(), "json object is null");
490 bool sessionExist = false;
491 for (auto value : values) {
492 if (!value.contains("bundleName") || !value.contains("abilityName")) {
493 SLOGI("not contain bundleName or abilityName, pass");
494 continue;
495 }
496 if (session->GetBundleName() == value["bundleName"] &&
497 session->GetAbilityName() == value["abilityName"]) {
498 values.erase(std::remove(values.begin(), values.end(), value));
499 sessionExist = true;
500 break;
501 }
502 }
503 if (sessionExist) {
504 SLOGI("SelectFocusSession sessionExist, change order");
505 if (values.size() >= (size_t)maxHistoryNums) {
506 values.erase(values.end() - 1);
507 }
508 nlohmann::json value;
509 value["sessionId"] = session->GetSessionId();
510 value["bundleName"] = session->GetBundleName();
511 value["abilityName"] = session->GetAbilityName();
512 value["sessionType"] = session->GetSessionType();
513 if (values.size() <= 0) {
514 values.push_back(value);
515 } else {
516 values.insert(values.begin(), value);
517 }
518 }
519
520 std::string newSortContent = values.dump();
521 SLOGD("SelectFocusSession::Dump json object finished");
522 if (!SaveStringToFileEx(GetAVSortDir(), newSortContent)) {
523 SLOGE("SelectFocusSession save sort fail !");
524 }
525 }
526 // LCOV_EXCL_STOP
527
IsMediaStream(AudioStandard::StreamUsage usage)528 bool AVSessionService::IsMediaStream(AudioStandard::StreamUsage usage)
529 {
530 return usage == STREAM_USAGE_MEDIA || usage == STREAM_USAGE_MUSIC ||
531 usage == STREAM_USAGE_MOVIE || usage == STREAM_USAGE_AUDIOBOOK;
532 }
533
UpdateFrontSession(sptr<AVSessionItem> & sessionItem,bool isAdd)534 void AVSessionService::UpdateFrontSession(sptr<AVSessionItem>& sessionItem, bool isAdd)
535 {
536 SLOGI("UpdateFrontSession with bundle=%{public}s isAdd=%{public}d", sessionItem->GetBundleName().c_str(), isAdd);
537 std::lock_guard frontLockGuard(sessionFrontLock_);
538 SLOGD("UpdateFrontSession pass lock");
539 int32_t userId = GetUsersManager().GetCurrentUserId();
540 std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront();
541 CHECK_AND_RETURN_LOG(sessionListForFront != nullptr, "sessionListForFront ptr nullptr!");
542 auto it = std::find(sessionListForFront->begin(), sessionListForFront->end(), sessionItem);
543 if (isAdd) {
544 if (it != sessionListForFront->end()) {
545 SLOGI("sessionListForFront has same session bundle=%{public}s", sessionItem->GetBundleName().c_str());
546 return;
547 }
548 sessionListForFront->push_front(sessionItem);
549 auto iter = sessionPublishedMap_.find(sessionItem->GetUid());
550 if (iter != sessionPublishedMap_.end() && !sessionPublishedMap_[sessionItem->GetUid()]) {
551 SLOGI("RepublishNotification for uid=%{public}d", sessionItem->GetUid());
552 UpdateTopSession(sessionItem);
553 AVSessionDescriptor selectSession = sessionItem->GetDescriptor();
554 NotifySystemUI(&selectSession, true);
555 }
556 } else {
557 if (topSession_.GetRefPtr() == sessionItem.GetRefPtr()) {
558 SLOGD("top session is remove session");
559 UpdateTopSession(nullptr);
560 int32_t ret = Notification::NotificationHelper::CancelNotification(std::to_string(userId), 0);
561 SLOGI("CancelNotification with userId:%{public}d, ret=%{public}d", userId, ret);
562 }
563 sessionListForFront->remove(sessionItem);
564 SLOGI("sessionListForFront with size %{public}d", static_cast<int32_t>(sessionListForFront->size()));
565 }
566 }
567
568 // LCOV_EXCL_START
SelectFocusSession(const FocusSessionStrategy::FocusSessionChangeInfo & info)569 bool AVSessionService::SelectFocusSession(const FocusSessionStrategy::FocusSessionChangeInfo& info)
570 {
571 for (auto& session : GetContainer().GetAllSessions()) {
572 if (session->GetDescriptor().sessionTag_ == "RemoteCast") {
573 SLOGI("Remote sessions do not need to be saved to history");
574 continue;
575 }
576 if (session->GetUid() != info.uid) {
577 continue;
578 }
579 GetContainer().UpdateSessionSort(session);
580 RefreshFocusSessionSort(session);
581 std::lock_guard frontLockGuard(sessionFrontLock_);
582 std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront();
583 CHECK_AND_RETURN_RET_LOG(sessionListForFront != nullptr, false, "sessionListForFront ptr nullptr!");
584 auto it = std::find(sessionListForFront->begin(), sessionListForFront->end(), session);
585 if (it != sessionListForFront->end()) {
586 SLOGI(" front session exist, change order");
587 sessionListForFront->remove(session);
588 sessionListForFront->push_front(session);
589 }
590 return true;
591 }
592 return false;
593 }
594 // LCOV_EXCL_STOP
595
InitAudio()596 void AVSessionService::InitAudio()
597 {
598 SLOGI("enter");
599 AudioAdapter::GetInstance().Init();
600 focusSessionStrategy_.Init();
601 focusSessionStrategy_.RegisterFocusSessionChangeCallback([this] (const auto& info) {
602 HandleFocusSession(info);
603 });
604 focusSessionStrategy_.RegisterFocusSessionSelector([this] (const auto& info) {
605 return SelectFocusSession(info);
606 });
607 AudioAdapter::GetInstance().AddStreamRendererStateListener([this] (const AudioRendererChangeInfos& infos) {
608 OutputDeviceChangeListener(infos);
609 });
610 AudioAdapter::GetInstance().AddDeviceChangeListener([this] (const DeviceChangeAction& deviceChangeAction) {
611 HandleDeviceChange(deviceChangeAction);
612 });
613 }
614
SelectSessionByUid(const AudioRendererChangeInfo & info)615 sptr <AVSessionItem> AVSessionService::SelectSessionByUid(const AudioRendererChangeInfo& info)
616 {
617 for (const auto& session : GetContainer().GetAllSessions()) {
618 if (session->GetUid() == info.clientUID) {
619 return session;
620 }
621 }
622 SLOGI("has no session");
623 return nullptr;
624 }
625
OutputDeviceChangeListener(const AudioRendererChangeInfos & infos)626 void AVSessionService::OutputDeviceChangeListener(const AudioRendererChangeInfos& infos)
627 {
628 for (const auto& info : infos) {
629 SLOGD("clientUID is %{public}d, rendererState is %{public}d", info->clientUID,
630 static_cast<int32_t>(info->rendererState));
631 }
632 }
633
InitAMS()634 void AVSessionService::InitAMS()
635 {
636 SLOGI("enter");
637 AppManagerAdapter::GetInstance().Init();
638 AppManagerAdapter::GetInstance().SetServiceCallbackForAppStateChange([this] (int uid, int state) {
639 SLOGD("uid = %{public}d, state = %{public}d", uid, state);
640 HandleAppStateChange(uid, state);
641 });
642 }
643
644 // LCOV_EXCL_START
HandleAppStateChange(int uid,int state)645 void AVSessionService::HandleAppStateChange(int uid, int state)
646 {
647 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
648 SLOGD("uidForAppStateChange_ = %{public}d, uid = %{public}d, state = %{public}d",
649 uidForAppStateChange_, uid, state);
650 if (uidForAppStateChange_ == uid) {
651 if (state == appState) {
652 return;
653 }
654 if (state == static_cast<int>(AppExecFwk::ApplicationState::APP_STATE_FOREGROUND)) {
655 SLOGI("enter notifyMirrorToStreamCast by background to foreground state change, and counts = 2");
656 NotifyMirrorToStreamCast();
657 }
658 appState = state;
659 }
660 #endif //CASTPLUS_CAST_ENGINE_ENABLE
661 }
662 // LCOV_EXCL_STOP
663
InitDM()664 void AVSessionService::InitDM()
665 {
666 SLOGI("enter");
667 auto callback = std::make_shared<AVSessionInitDMCallback>();
668 CHECK_AND_RETURN_LOG(callback != nullptr, "no memory");
669 int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().InitDeviceManager("av_session", callback);
670 CHECK_AND_RETURN_LOG(ret == 0, "InitDeviceManager error ret is %{public}d", ret);
671 }
672
InitBMS()673 void AVSessionService::InitBMS()
674 {
675 std::lock_guard sortFileLockGuard(sortFileReadWriteLock_);
676 SLOGI("enter");
677 BundleStatusAdapter::GetInstance().Init();
678 int userId = GetUsersManager().GetCurrentUserId();
679 if (userId < 0) {
680 SLOGE("InitBMS with userId: %{public}d, not valid, return and wait for InitAccountMgr", userId);
681 return;
682 }
683 RegisterBundleDeleteEventForHistory(userId);
684 }
685
InitAccountMgr()686 void AVSessionService::InitAccountMgr()
687 {
688 SLOGI("InitAccountMgr in");
689 GetUsersManager().Init();
690 RegisterBundleDeleteEventForHistory();
691 }
692
InitCommonEventService()693 void AVSessionService::InitCommonEventService()
694 {
695 SLOGI("InitCommonEventService in");
696 bool ret = SubscribeCommonEvent();
697 CHECK_AND_RETURN_LOG(ret, "SubscribeCommonEvent error!");
698 }
699
RegisterBundleDeleteEventForHistory(int32_t userId)700 void AVSessionService::RegisterBundleDeleteEventForHistory(int32_t userId)
701 {
702 if (userId <= 0) {
703 userId = GetUsersManager().GetCurrentUserId();
704 SLOGI("do RegisterBundleDeleteEventForHistory with cur userId:%{public}d", userId);
705 } else {
706 SLOGI("do RegisterBundleDeleteEventForHistory with recv userId:%{public}d", userId);
707 }
708
709 std::string oldSortContent;
710 if (LoadStringFromFileEx(GetAVSortDir(userId), oldSortContent)) {
711 nlohmann::json values = json::parse(oldSortContent, nullptr, false);
712 CHECK_AND_RETURN_LOG(!values.is_discarded(), "json object is null");
713 auto callback = [this](std::string bundleName, int32_t userId) {
714 SLOGI("recv delete bundle:%{public}s at user:%{public}d", bundleName.c_str(), userId);
715 DeleteAVQueueInfoRecord(bundleName, userId);
716 DeleteHistoricalRecord(bundleName, userId);
717 };
718 for (auto value : values) {
719 if (!BundleStatusAdapter::GetInstance().SubscribeBundleStatusEvent(value["bundleName"], callback, userId)) {
720 std::string bundleName = value["bundleName"];
721 SLOGE("SubscribeBundleStatusEvent failed for bundle:%{public}s", bundleName.c_str());
722 }
723 }
724 }
725 }
726
GetContainer()727 SessionContainer& AVSessionService::GetContainer()
728 {
729 return GetUsersManager().GetContainer();
730 }
731
GetUsersManager()732 AVSessionUsersManager& AVSessionService::GetUsersManager()
733 {
734 static AVSessionUsersManager usersManager;
735 return usersManager;
736 }
737
GetCurSessionListForFront()738 inline std::shared_ptr<std::list<sptr<AVSessionItem>>> AVSessionService::GetCurSessionListForFront()
739 {
740 return GetUsersManager().GetCurSessionListForFront();
741 }
742
AllocSessionId()743 std::string AVSessionService::AllocSessionId()
744 {
745 auto curNum = sessionSeqNum_++;
746 std::string id = std::to_string(GetCallingPid()) + "-" + std::to_string(GetCallingUid()) + "-" +
747 std::to_string(curNum);
748 SLOGI("%{public}s", id.c_str());
749
750 HashCalculator hashCalculator;
751 CHECK_AND_RETURN_RET_LOG(hashCalculator.Init() == AVSESSION_SUCCESS, "", "hash init failed");
752 CHECK_AND_RETURN_RET_LOG(hashCalculator.Update(std::vector<uint8_t>(id.begin(), id.end())) == AVSESSION_SUCCESS,
753 "", "hash update failed");
754 std::vector<uint8_t> hash;
755 CHECK_AND_RETURN_RET_LOG(hashCalculator.GetResult(hash) == AVSESSION_SUCCESS, "", "hash get result failed");
756
757 std::stringstream stream;
758 for (const auto byte : hash) {
759 stream << std::uppercase << std::hex << std::setfill('0') << std::setw(allocSpace) << static_cast<int>(byte);
760 }
761 return stream.str();
762 }
763
AbilityHasSession(pid_t pid)764 bool AVSessionService::AbilityHasSession(pid_t pid)
765 {
766 std::lock_guard lockGuard(sessionAndControllerLock_);
767 return GetContainer().PidHasSession(pid);
768 }
769
GetPresentController(pid_t pid,const std::string & sessionId)770 sptr<AVControllerItem> AVSessionService::GetPresentController(pid_t pid, const std::string& sessionId)
771 {
772 std::lock_guard lockGuard(sessionAndControllerLock_);
773 auto it = controllers_.find(pid);
774 if (it != controllers_.end()) {
775 for (const auto& controller: it->second) {
776 if (controller->HasSession(sessionId)) {
777 return controller;
778 }
779 }
780 }
781 SLOGI("not found");
782 return nullptr;
783 }
784
NotifySessionCreate(const AVSessionDescriptor & descriptor)785 void AVSessionService::NotifySessionCreate(const AVSessionDescriptor& descriptor)
786 {
787 {
788 std::lock_guard lockGuard(migrateListenersLock_);
789 for (const auto& listener : innerSessionListeners_) {
790 listener->OnSessionCreate(descriptor);
791 }
792 }
793 std::lock_guard lockGuard(sessionListenersLock_);
794 std::map<pid_t, sptr<ISessionListener>> listenerMap = GetUsersManager().GetSessionListener();
795 for (const auto& [pid, listener] : listenerMap) {
796 AVSESSION_TRACE_SYNC_START("AVSessionService::OnSessionCreate");
797 SLOGI("notify session create for pid %{public}d", static_cast<int>(pid));
798 listener->OnSessionCreate(descriptor);
799 }
800 std::map<pid_t, sptr<ISessionListener>> listenerMapForAll = GetUsersManager().GetSessionListenerForAllUsers();
801 for (const auto& [pid, listener] : listenerMapForAll) {
802 AVSESSION_TRACE_SYNC_START("AVSessionService::OnSessionCreate");
803 SLOGI("notify session create for pid %{public}d across users", static_cast<int>(pid));
804 listener->OnSessionCreate(descriptor);
805 }
806 }
807
NotifySessionRelease(const AVSessionDescriptor & descriptor)808 void AVSessionService::NotifySessionRelease(const AVSessionDescriptor& descriptor)
809 {
810 {
811 std::lock_guard lockGuard(migrateListenersLock_);
812 for (const auto& listener : innerSessionListeners_) {
813 listener->OnSessionRelease(descriptor);
814 }
815 }
816 std::lock_guard lockGuard(sessionListenersLock_);
817 std::map<pid_t, sptr<ISessionListener>> listenerMap = GetUsersManager().GetSessionListener();
818 for (const auto& [pid, listener] : listenerMap) {
819 SLOGI("notify session release for pid %{public}d", static_cast<int>(pid));
820 listener->OnSessionRelease(descriptor);
821 }
822 std::map<pid_t, sptr<ISessionListener>> listenerMapForAll = GetUsersManager().GetSessionListenerForAllUsers();
823 for (const auto& [pid, listener] : listenerMapForAll) {
824 SLOGI("notify session release for pid %{public}d across users", static_cast<int>(pid));
825 listener->OnSessionRelease(descriptor);
826 }
827 }
828
NotifyTopSessionChanged(const AVSessionDescriptor & descriptor)829 void AVSessionService::NotifyTopSessionChanged(const AVSessionDescriptor& descriptor)
830 {
831 {
832 std::lock_guard lockGuard(migrateListenersLock_);
833 for (const auto& listener : innerSessionListeners_) {
834 listener->OnTopSessionChange(descriptor);
835 }
836 }
837 std::lock_guard lockGuard(sessionListenersLock_);
838 std::map<pid_t, sptr<ISessionListener>> listenerMap = GetUsersManager().GetSessionListener();
839 for (const auto& [pid, listener] : listenerMap) {
840 AVSESSION_TRACE_SYNC_START("AVSessionService::OnTopSessionChange");
841 SLOGI("notify top session change to pid %{public}d", static_cast<int>(pid));
842 listener->OnTopSessionChange(descriptor);
843 }
844 std::map<pid_t, sptr<ISessionListener>> listenerMapForAll = GetUsersManager().GetSessionListenerForAllUsers();
845 for (const auto& [pid, listener] : listenerMapForAll) {
846 AVSESSION_TRACE_SYNC_START("AVSessionService::OnTopSessionChange");
847 SLOGI("notify top session change to pid %{public}d across users", static_cast<int>(pid));
848 listener->OnTopSessionChange(descriptor);
849 }
850 }
851
852 // LCOV_EXCL_START
NotifyAudioSessionCheck(const int32_t uid)853 void AVSessionService::NotifyAudioSessionCheck(const int32_t uid)
854 {
855 SLOGI("Start searching for the corresponding callback");
856 {
857 std::lock_guard lockGuard(migrateListenersLock_);
858 for (const auto& listener : innerSessionListeners_) {
859 listener->OnAudioSessionChecked(uid);
860 }
861 }
862 std::lock_guard lockGuard(sessionListenersLock_);
863 std::map<pid_t, sptr<ISessionListener>> listenerMap = GetUsersManager().GetSessionListener();
864 for (const auto& [pid, listener] : listenerMap) {
865 SLOGI("Found session listener with pid %{public}d", static_cast<int>(pid));
866 AVSESSION_TRACE_SYNC_START("AVSessionService::OnAudioSessionCheck");
867 listener->OnAudioSessionChecked(uid);
868 }
869 std::map<pid_t, sptr<ISessionListener>> listenerMapForAll = GetUsersManager().GetSessionListenerForAllUsers();
870 for (const auto& [pid, listener] : listenerMapForAll) {
871 SLOGI("Found session listener with pid %{public}d across users", static_cast<int>(pid));
872 AVSESSION_TRACE_SYNC_START("AVSessionService::OnAudioSessionCheck");
873 listener->OnAudioSessionChecked(uid);
874 }
875 }
876 // LCOV_EXCL_STOP
877
CheckAncoAudio()878 bool AVSessionService::CheckAncoAudio()
879 {
880 for (const auto& session : GetContainer().GetAllSessions()) {
881 if (session->GetBundleName() == "anco_audio") {
882 return true;
883 }
884 }
885 return false;
886 }
887
888 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
889
checkEnableCast(bool enable)890 int32_t AVSessionService::checkEnableCast(bool enable)
891 {
892 SLOGI("checkEnableCast enable:%{public}d, isInCast:%{public}d", enable, isInCast_);
893 if (enable == true && isInCast_ == false) {
894 isInCast_ = true;
895 return AVRouter::GetInstance().Init(this);
896 } else if (enable == false && isInCast_ == true) {
897 CHECK_AND_RETURN_RET_LOG(!((GetContainer().GetAllSessions().size() > 1 ||
898 (GetContainer().GetAllSessions().size() == 1 && !CheckAncoAudio())) && !is2in1_),
899 AVSESSION_SUCCESS, "can not release cast with session alive");
900 CHECK_AND_RETURN_RET_LOG(!(castServiceNameMapState_["HuaweiCast"] == deviceStateConnection ||
901 castServiceNameMapState_["HuaweiCast-Dual"] == deviceStateConnection),
902 AVSESSION_SUCCESS, "can not release cast with casting");
903 isInCast_ = AVRouter::GetInstance().Release();
904 } else {
905 SLOGD("AVRouter Init in nothing change ");
906 }
907 return AVSESSION_SUCCESS;
908 }
909
setInCast(bool isInCast)910 void AVSessionService::setInCast(bool isInCast)
911 {
912 SLOGI("setInCast, isInCast:%{public}d", isInCast);
913 isInCast_ = isInCast;
914 }
915
916 // LCOV_EXCL_START
ReleaseCastSession()917 void AVSessionService::ReleaseCastSession()
918 {
919 std::lock_guard lockGuard(sessionAndControllerLock_);
920 SLOGI("Start release cast session");
921 for (const auto& session : GetContainer().GetAllSessions()) {
922 if (session->GetDescriptor().sessionTag_ == "RemoteCast") {
923 std::string sessionId = session->GetDescriptor().sessionId_;
924 SLOGI("Already has a cast session %{public}s", AVSessionUtils::GetAnonySessionId(sessionId).c_str());
925 session->UnRegisterDeviceStateCallback();
926 session->StopCastSession();
927 session->ReleaseAVCastControllerInner();
928 HandleSessionRelease(sessionId);
929 }
930 }
931 }
932 // LCOV_EXCL_STOP
933
934 // LCOV_EXCL_START
CreateSessionByCast(const int64_t castHandle)935 void AVSessionService::CreateSessionByCast(const int64_t castHandle)
936 {
937 SLOGI("AVSessionService CreateSessionByCast in");
938 if (isSourceInCast_) {
939 AVSessionRadarInfo info("AVSessionService::CreateSessionByCast");
940 AVSessionRadar::GetInstance().StartConnect(info);
941 SLOGI("Create Cast in source, return");
942 return;
943 }
944 AppExecFwk::ElementName elementName;
945 elementName.SetBundleName("castBundleName");
946 elementName.SetAbilityName("castAbilityName");
947 sptr <AVSessionItem> sinkSession = CreateSessionInner("RemoteCast",
948 AVSession::SESSION_TYPE_AUDIO, false, elementName);
949 CHECK_AND_RETURN_LOG(sinkSession != nullptr, "CreateSession at sink failed");
950 SLOGI("Create Cast sink sessionId %{public}s",
951 AVSessionUtils::GetAnonySessionId(sinkSession->GetSessionId()).c_str());
952 sinkSession->SetCastHandle(castHandle);
953 sinkSession->RegisterDeviceStateCallback();
954
955 {
956 std::lock_guard frontLockGuard(sessionFrontLock_);
957 std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront();
958 CHECK_AND_RETURN_LOG(sessionListForFront != nullptr, "sessionListForFront ptr nullptr!");
959 auto it = std::find(sessionListForFront->begin(), sessionListForFront->end(), sinkSession);
960 if (it == sessionListForFront->end()) {
961 SLOGI(" front session add cast session");
962 sessionListForFront->push_front(sinkSession);
963 }
964 }
965
966 HISYSEVENT_BEHAVIOR("SESSION_CAST",
967 "BUNDLE_NAME", "castBundleName",
968 "ABILITY_NAME", "castAbilityName",
969 "SESSION_PID", sinkSession->GetDescriptor().pid_,
970 "SESSION_UID", sinkSession->GetDescriptor().uid_,
971 "SESSION_ID", sinkSession->GetDescriptor().sessionId_,
972 "SESSION_TAG", sinkSession->GetDescriptor().sessionTag_,
973 "SESSION_TYPE", sinkSession->GetDescriptor().sessionType_,
974 "DETAILED_MSG", "session create from cast+ callback");
975 }
976 // LCOV_EXCL_STOP
977
978 // LCOV_EXCL_START
NotifyDeviceAvailable(const OutputDeviceInfo & castOutputDeviceInfo)979 void AVSessionService::NotifyDeviceAvailable(const OutputDeviceInfo& castOutputDeviceInfo)
980 {
981 AVSessionRadarInfo info("AVSessionService::NotifyDeviceAvailable");
982 AVSessionRadar::GetInstance().CastDeviceAvailable(castOutputDeviceInfo, info);
983
984 for (DeviceInfo deviceInfo : castOutputDeviceInfo.deviceInfos_) {
985 for (const auto& session : GetContainer().GetAllSessions()) {
986 session->UpdateCastDeviceMap(deviceInfo);
987 }
988 }
989 std::lock_guard lockGuard(sessionListenersLock_);
990 for (const auto& listener : innerSessionListeners_) {
991 listener->OnDeviceAvailable(castOutputDeviceInfo);
992 }
993 std::map<pid_t, sptr<ISessionListener>> listenerMap = GetUsersManager().GetSessionListener();
994 for (const auto& [pid, listener] : listenerMap) {
995 AVSESSION_TRACE_SYNC_START("AVSessionService::OnDeviceAvailable");
996 listener->OnDeviceAvailable(castOutputDeviceInfo);
997 }
998 std::map<pid_t, sptr<ISessionListener>> listenerMapForAll = GetUsersManager().GetSessionListenerForAllUsers();
999 for (const auto& [pid, listener] : listenerMapForAll) {
1000 AVSESSION_TRACE_SYNC_START("AVSessionService::OnDeviceAvailable");
1001 listener->OnDeviceAvailable(castOutputDeviceInfo);
1002 }
1003 }
1004 // LCOV_EXCL_STOP
1005
NotifyDeviceLogEvent(const DeviceLogEventCode eventId,const int64_t param)1006 void AVSessionService::NotifyDeviceLogEvent(const DeviceLogEventCode eventId, const int64_t param)
1007 {
1008 std::lock_guard lockGuard(sessionListenersLock_);
1009 std::map<pid_t, sptr<ISessionListener>> listenerMap = GetUsersManager().GetSessionListener();
1010 for (const auto& [pid, listener] : listenerMap) {
1011 AVSESSION_TRACE_SYNC_START("AVSessionService::OnDeviceLogEvent");
1012 listener->OnDeviceLogEvent(eventId, param);
1013 }
1014 }
1015
1016 // LCOV_EXCL_START
NotifyDeviceOffline(const std::string & deviceId)1017 void AVSessionService::NotifyDeviceOffline(const std::string& deviceId)
1018 {
1019 std::lock_guard lockGuard(sessionListenersLock_);
1020 for (const auto& listener : innerSessionListeners_) {
1021 listener->OnDeviceOffline(deviceId);
1022 }
1023 std::map<pid_t, sptr<ISessionListener>> listenerMap = GetUsersManager().GetSessionListener();
1024 for (const auto& [pid, listener] : listenerMap) {
1025 SLOGI("notify device offline with pid %{public}d", static_cast<int>(pid));
1026 AVSESSION_TRACE_SYNC_START("AVSessionService::OnDeviceOffline");
1027 listener->OnDeviceOffline(deviceId);
1028 }
1029 std::map<pid_t, sptr<ISessionListener>> listenerMapForAll = GetUsersManager().GetSessionListenerForAllUsers();
1030 for (const auto& [pid, listener] : listenerMapForAll) {
1031 SLOGI("notify device offline with pid %{public}d across users", static_cast<int>(pid));
1032 AVSESSION_TRACE_SYNC_START("AVSessionService::OnDeviceOffline");
1033 listener->OnDeviceOffline(deviceId);
1034 }
1035 }
1036 // LCOV_EXCL_STOP
1037
StartCast(const SessionToken & sessionToken,const OutputDeviceInfo & outputDeviceInfo)1038 int32_t AVSessionService::StartCast(const SessionToken& sessionToken, const OutputDeviceInfo& outputDeviceInfo)
1039 {
1040 SLOGI("SessionId is %{public}s", AVSessionUtils::GetAnonySessionId(sessionToken.sessionId).c_str());
1041 sptr<AVSessionItem> session = GetContainer().GetSessionById(sessionToken.sessionId);
1042 CHECK_AND_RETURN_RET_LOG(session != nullptr, ERR_SESSION_NOT_EXIST, "session %{public}s not exist",
1043 AVSessionUtils::GetAnonySessionId(sessionToken.sessionId).c_str());
1044 ReportStartCastBegin("AVSessionService::StartCast", outputDeviceInfo, session->GetDescriptor().uid_);
1045 int32_t ret = session->StartCast(outputDeviceInfo);
1046 ReportStartCastEnd("AVSessionService::StartCast", outputDeviceInfo, session->GetDescriptor().uid_, ret);
1047 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "StartCast failed");
1048 SLOGD("StartCast set isSourceInCast");
1049 isSourceInCast_ = true;
1050
1051 SLOGI("no set continuous task in service");
1052 HISYSEVENT_BEHAVIOR("SESSION_CAST",
1053 "BUNDLE_NAME", session->GetDescriptor().elementName_.GetBundleName(),
1054 "MODULE_NAME", session->GetDescriptor().elementName_.GetModuleName(),
1055 "ABILITY_NAME", session->GetDescriptor().elementName_.GetAbilityName(),
1056 "SESSION_PID", session->GetDescriptor().pid_, "SESSION_UID", session->GetDescriptor().uid_,
1057 "SESSION_ID", session->GetDescriptor().sessionId_, "SESSION_TAG", session->GetDescriptor().sessionTag_,
1058 "SESSION_TYPE", session->GetDescriptor().sessionType_, "DETAILED_MSG", "start cast session");
1059 return AVSESSION_SUCCESS;
1060 }
1061
StopCast(const SessionToken & sessionToken)1062 int32_t AVSessionService::StopCast(const SessionToken& sessionToken)
1063 {
1064 sptr<AVSessionItem> session = GetUsersManager().GetContainerFromAll().GetSessionById(sessionToken.sessionId);
1065 CHECK_AND_RETURN_RET_LOG(session != nullptr, AVSESSION_SUCCESS, "StopCast: session is not exist");
1066 CHECK_AND_RETURN_RET_LOG(session->StopCast() == AVSESSION_SUCCESS, AVSESSION_ERROR, "StopCast failed");
1067 if (session->GetDescriptor().sessionTag_ == "RemoteCast") {
1068 SLOGI("Stop cast at sink, start destroy sink avsession task");
1069 HandleSessionRelease(sessionToken.sessionId);
1070 return AVSESSION_SUCCESS;
1071 }
1072
1073 SLOGI("no set continuous task in service");
1074 return AVSESSION_SUCCESS;
1075 }
1076
NotifyMirrorToStreamCast()1077 void AVSessionService::NotifyMirrorToStreamCast()
1078 {
1079 for (auto& session : GetContainer().GetAllSessions()) {
1080 if (session->GetUid() == uidForAppStateChange_ && isSupportMirrorToStream_ &&
1081 !AppManagerAdapter::GetInstance().IsAppBackground(session->GetUid(), session->GetPid())) {
1082 MirrorToStreamCast(session);
1083 }
1084 }
1085 if (castServiceNameMapState_["HuaweiCast"] == deviceStateDisconnection ||
1086 castServiceNameMapState_["HuaweiCast-Dual"] == deviceStateDisconnection) {
1087 DeviceInfo localDeviceInfo;
1088 AVRouter::GetInstance().SetServiceAllConnectState(-1, localDeviceInfo);
1089 }
1090 }
1091
MirrorToStreamCast(sptr<AVSessionItem> & session)1092 __attribute__((no_sanitize("cfi"))) int32_t AVSessionService::MirrorToStreamCast(sptr<AVSessionItem>& session)
1093 {
1094 SLOGI("enter MirrorToStreamCast with ptr");
1095 if (!is2in1_) {
1096 if (castServiceNameMapState_["HuaweiCast"] == deviceStateConnection ||
1097 castServiceNameMapState_["HuaweiCast-Dual"] == deviceStateConnection) {
1098 checkEnableCast(true);
1099 DeviceInfo deviceInfo;
1100 deviceInfo.deviceId_ = castDeviceId_;
1101 deviceInfo.deviceName_ = castDeviceName_;
1102 deviceInfo.deviceType_ = castDeviceType_;
1103 deviceInfo.castCategory_ = AVCastCategory::CATEGORY_REMOTE;
1104 deviceInfo.supportedProtocols_ = ProtocolType::TYPE_CAST_PLUS_STREAM;
1105 deviceInfo.providerId_ = 1;
1106 return session->RegisterListenerStreamToCast(castServiceNameMapState_, deviceInfo);
1107 }
1108 }
1109 return AVSESSION_SUCCESS;
1110 }
1111 #endif
1112
1113 // LCOV_EXCL_START
HandleCallStartEvent()1114 void AVSessionService::HandleCallStartEvent()
1115 {
1116 SLOGI("Start handle CallStartEvent");
1117 AbilityConnectHelper::GetInstance().StartAbilityForegroundByCall(MEDIA_CONTROL_BUNDLENAME,
1118 MEDIA_CONTROL_ABILITYNAME);
1119 }
1120 // LCOV_EXCL_STOP
1121
ServiceCallback(sptr<AVSessionItem> & sessionItem)1122 void AVSessionService::ServiceCallback(sptr<AVSessionItem>& sessionItem)
1123 {
1124 sessionItem->SetServiceCallbackForRelease([this](AVSessionItem& session) {
1125 SLOGI("Start handle session release event");
1126 HandleSessionRelease(session.GetDescriptor().sessionId_, true);
1127 });
1128 sessionItem->SetServiceCallbackForAVQueueInfo([this](AVSessionItem& session) {
1129 AddAvQueueInfoToFile(session);
1130 });
1131 sessionItem->SetServiceCallbackForCallStart([this](AVSessionItem& session) {
1132 SLOGI("Start handle call start event for %{public}s",
1133 AVSessionUtils::GetAnonySessionId(session.GetDescriptor().sessionId_).c_str());
1134 HandleCallStartEvent();
1135 });
1136 sessionItem->SetServiceCallbackForUpdateSession([this](std::string sessionId, bool isAdd) {
1137 SLOGI("serviceCallback for session update %{public}s", AVSessionUtils::GetAnonySessionId(sessionId).c_str());
1138 std::lock_guard lockGuard(sessionAndControllerLock_);
1139 sptr<AVSessionItem> session = GetContainer().GetSessionById(sessionId);
1140 CHECK_AND_RETURN_LOG(session != nullptr, "session not exist for UpdateFrontSession");
1141 UpdateFrontSession(session, isAdd);
1142 });
1143 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
1144 sessionItem->SetServiceCallbackForStream([this](std::string sessionId) {
1145 sptr<AVSessionItem> session = GetContainer().GetSessionById(sessionId);
1146 CHECK_AND_RETURN_LOG(session != nullptr, "Session not exist");
1147 uidForAppStateChange_ = session->GetUid();
1148 if (isSupportMirrorToStream_ &&
1149 !AppManagerAdapter::GetInstance().IsAppBackground(session->GetUid(), session->GetPid())) {
1150 MirrorToStreamCast(session);
1151 }
1152 });
1153 #endif // CASTPLUS_CAST_ENGINE_ENABLE
1154 }
1155
CreateNewSession(const std::string & tag,int32_t type,bool thirdPartyApp,const AppExecFwk::ElementName & elementName)1156 sptr<AVSessionItem> AVSessionService::CreateNewSession(const std::string& tag, int32_t type, bool thirdPartyApp,
1157 const AppExecFwk::ElementName& elementName)
1158 {
1159 SLOGI("%{public}s %{public}d %{public}s %{public}s", tag.c_str(), type,
1160 elementName.GetBundleName().c_str(), elementName.GetAbilityName().c_str());
1161 AVSessionDescriptor descriptor;
1162 descriptor.sessionId_ = AllocSessionId();
1163 if (descriptor.sessionId_.empty()) {
1164 SLOGE("alloc session id failed");
1165 return nullptr;
1166 }
1167 descriptor.sessionTag_ = tag;
1168 descriptor.sessionType_ = type;
1169 descriptor.elementName_ = elementName;
1170 descriptor.isThirdPartyApp_ = thirdPartyApp;
1171
1172 sptr<AVSessionItem> result = new(std::nothrow) AVSessionItem(descriptor, GetUsersManager().GetCurrentUserId());
1173 if (result == nullptr) {
1174 return nullptr;
1175 }
1176 result->SetPid(GetCallingPid());
1177 result->SetUid(GetCallingUid());
1178 ServiceCallback(result);
1179 SLOGI("success sessionId=%{public}s", AVSessionUtils::GetAnonySessionId(result->GetSessionId()).c_str());
1180
1181 OutputDeviceInfo outputDeviceInfo;
1182 DeviceInfo deviceInfo;
1183 deviceInfo.castCategory_ = AVCastCategory::CATEGORY_LOCAL;
1184 deviceInfo.deviceId_ = "0";
1185 deviceInfo.deviceName_ = "LocalDevice";
1186 outputDeviceInfo.deviceInfos_.emplace_back(deviceInfo);
1187 result->SetOutputDevice(outputDeviceInfo);
1188
1189 return result;
1190 }
1191
CreateSessionInner(const std::string & tag,int32_t type,bool thirdPartyApp,const AppExecFwk::ElementName & elementName,sptr<AVSessionItem> & sessionItem)1192 int32_t AVSessionService::CreateSessionInner(const std::string& tag, int32_t type, bool thirdPartyApp,
1193 const AppExecFwk::ElementName& elementName,
1194 sptr<AVSessionItem>& sessionItem)
1195 {
1196 SLOGI("CreateSessionInner enter");
1197 CHECK_AND_RETURN_RET_LOG(!tag.empty(), ERR_INVALID_PARAM, "tag is empty");
1198 CHECK_AND_RETURN_RET_LOG(type == AVSession::SESSION_TYPE_AUDIO || type == AVSession::SESSION_TYPE_VIDEO
1199 || type == AVSession::SESSION_TYPE_VOICE_CALL || type == AVSession::SESSION_TYPE_VIDEO_CALL,
1200 ERR_INVALID_PARAM, "type is invalid");
1201 CHECK_AND_RETURN_RET_LOG(!elementName.GetBundleName().empty() && !elementName.GetAbilityName().empty(),
1202 ERR_INVALID_PARAM, "element is invalid");
1203 std::regex nameRegex("[A-Za-z\\w\\.]*");
1204 if (!std::regex_match(elementName.GetBundleName(), nameRegex)) {
1205 SLOGE("CreateSessionInner err regex, bundleName=%{public}s", (elementName.GetBundleName()).c_str());
1206 return ERR_INVALID_PARAM;
1207 }
1208 if (!std::regex_match(elementName.GetAbilityName(), nameRegex)) {
1209 SLOGE("CreateSessionInner err regex, abilityName=%{public}s", (elementName.GetAbilityName()).c_str());
1210 return ERR_INVALID_PARAM;
1211 }
1212 auto pid = GetCallingPid();
1213 std::lock_guard lockGuard(sessionAndControllerLock_);
1214 if (AbilityHasSession(pid)) {
1215 SLOGE("process %{public}d %{public}s already has one session", pid, elementName.GetAbilityName().c_str());
1216 return ERR_SESSION_IS_EXIST;
1217 }
1218
1219 auto result = CreateNewSession(tag, type, thirdPartyApp, elementName);
1220 if (result == nullptr) {
1221 SLOGE("create new session failed");
1222 dumpHelper_->SetErrorInfo(" AVSessionService::CreateSessionInner create new session failed");
1223 HISYSEVENT_FAULT("CONTROL_COMMAND_FAILED", "CALLER_PID", pid, "TAG", tag, "TYPE", type, "BUNDLE_NAME",
1224 elementName.GetBundleName(), "ERROR_MSG", "avsessionservice createsessioninner create new session failed");
1225 return ERR_NO_MEMORY;
1226 }
1227 if (GetUsersManager().AddSessionForCurrentUser(pid, elementName.GetAbilityName(), result) != AVSESSION_SUCCESS) {
1228 SLOGE("session num exceed max");
1229 return ERR_SESSION_EXCEED_MAX;
1230 }
1231
1232 HISYSEVENT_ADD_LIFE_CYCLE_INFO(elementName.GetBundleName(),
1233 AppManagerAdapter::GetInstance().IsAppBackground(GetCallingUid(), GetCallingPid()), type, true);
1234
1235 NotifySessionCreate(result->GetDescriptor());
1236 sessionItem = result;
1237
1238 std::lock_guard frontLockGuard(sessionFrontLock_);
1239 std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront();
1240 CHECK_AND_RETURN_RET_LOG(sessionListForFront != nullptr, AVSESSION_ERROR, "sessionListForFront ptr nullptr!");
1241 auto it = std::find(sessionListForFront->begin(), sessionListForFront->end(), sessionItem);
1242 if ((type == AVSession::SESSION_TYPE_VOICE_CALL || type == AVSession::SESSION_TYPE_VIDEO_CALL ||
1243 (tag == "anco_audio" && GetCallingUid() == ancoUid)) && it == sessionListForFront->end()) {
1244 SLOGI(" front session add voice_call session=%{public}s", sessionItem->GetBundleName().c_str());
1245 sessionListForFront->push_front(sessionItem);
1246 }
1247 return AVSESSION_SUCCESS;
1248 }
1249
CreateSessionInner(const std::string & tag,int32_t type,bool thirdPartyApp,const AppExecFwk::ElementName & elementName)1250 sptr<AVSessionItem> AVSessionService::CreateSessionInner(const std::string& tag, int32_t type, bool thirdPartyApp,
1251 const AppExecFwk::ElementName& elementName)
1252 {
1253 sptr<AVSessionItem> sessionItem;
1254 auto res = CreateSessionInner(tag, type, thirdPartyApp, elementName, sessionItem);
1255 CHECK_AND_RETURN_RET_LOG(res == AVSESSION_SUCCESS, nullptr, "create session fail");
1256 return sessionItem;
1257 }
1258
ReportSessionInfo(const sptr<AVSessionItem> & session,int32_t res)1259 void AVSessionService::ReportSessionInfo(const sptr <AVSessionItem>& session, int32_t res)
1260 {
1261 std::string sessionId = "";
1262 std::string sessionTag = "";
1263 std::string SessionType = "";
1264 std::string bundleName = "";
1265 std::string API_PARAM_STRING = "";
1266 if (session != nullptr) {
1267 sessionId = AVSessionUtils::GetAnonySessionId(session->GetDescriptor().sessionId_);
1268 sessionTag = session->GetDescriptor().sessionTag_;
1269 SessionType = session->GetSessionType();
1270 bundleName = session->GetDescriptor().elementName_.GetBundleName();
1271 API_PARAM_STRING = "abilityName: " +
1272 session->GetDescriptor().elementName_.GetAbilityName() + ","
1273 + "moduleName: " + session->GetDescriptor().elementName_.GetModuleName();
1274 }
1275 std::string errMsg = (res == AVSESSION_SUCCESS) ? "SUCCESS" : "create session failed";
1276 HISYSEVENT_BEHAVIOR("SESSION_API_BEHAVIOR",
1277 "API_NAME", "CreateSession",
1278 "BUNDLE_NAME", bundleName,
1279 "SESSION_ID", sessionId,
1280 "SESSION_TAG", sessionTag,
1281 "SESSION_TYPE", SessionType,
1282 "API_PARAM", API_PARAM_STRING,
1283 "ERROR_CODE", res,
1284 "ERROR_MSG", errMsg);
1285 }
1286
CreateSessionInner(const std::string & tag,int32_t type,const AppExecFwk::ElementName & elementName,sptr<IRemoteObject> & object)1287 int32_t AVSessionService::CreateSessionInner(const std::string& tag, int32_t type,
1288 const AppExecFwk::ElementName& elementName,
1289 sptr<IRemoteObject>& object)
1290 {
1291 sptr<AVSessionItem> session;
1292 auto res = CreateSessionInner(tag, type,
1293 !PermissionChecker::GetInstance().CheckPermission(PermissionChecker::CHECK_SYSTEM_PERMISSION),
1294 elementName, session);
1295 CHECK_AND_RETURN_RET_LOG(res == AVSESSION_SUCCESS, res, "create session fail");
1296
1297 std::string supportModule;
1298 std::string profile;
1299 if (BundleStatusAdapter::GetInstance().IsSupportPlayIntent(elementName.GetBundleName(), supportModule, profile)) {
1300 SLOGI("bundleName=%{public}s support play intent, refreshSortFile", elementName.GetBundleName().c_str());
1301 refreshSortFileOnCreateSession(session->GetSessionId(), session->GetSessionType(), elementName);
1302 }
1303
1304 {
1305 std::lock_guard lockGuard1(abilityManagerLock_);
1306 std::string bundleName = session->GetDescriptor().elementName_.GetBundleName();
1307 std::string abilityName = session->GetDescriptor().elementName_.GetAbilityName();
1308 auto it = abilityManager_.find(bundleName + abilityName);
1309 if (it != abilityManager_.end()) {
1310 it->second->StartAbilityByCallDone(session->GetDescriptor().sessionId_);
1311 }
1312 }
1313
1314 object = session;
1315 ReportSessionInfo(session, static_cast<int32_t>(res));
1316
1317 {
1318 std::lock_guard lockGuard(isAllSessionCastLock_);
1319 SLOGI("isAllSessionCast_ is %{public}d", isAllSessionCast_);
1320 CHECK_AND_RETURN_RET_LOG(isAllSessionCast_, AVSESSION_SUCCESS, "no need to cast");
1321 }
1322 CHECK_AND_RETURN_RET_LOG(CastAudioForNewSession(session) == AVSESSION_SUCCESS,
1323 AVSESSION_SUCCESS, "cast new session error");
1324 return res;
1325 }
1326
CreateSessionInner(const std::string & tag,int32_t type,const AppExecFwk::ElementName & elementName)1327 sptr <IRemoteObject> AVSessionService::CreateSessionInner(const std::string& tag, int32_t type,
1328 const AppExecFwk::ElementName& elementName)
1329 {
1330 sptr<IRemoteObject> object;
1331 auto res = CreateSessionInner(tag, type, elementName, object);
1332 CHECK_AND_RETURN_RET_LOG(res == AVSESSION_SUCCESS, nullptr, "create session fail");
1333 return object;
1334 }
1335
1336 // LCOV_EXCL_START
refreshSortFileOnCreateSession(const std::string & sessionId,const std::string & sessionType,const AppExecFwk::ElementName & elementName)1337 void AVSessionService::refreshSortFileOnCreateSession(const std::string& sessionId, const std::string& sessionType,
1338 const AppExecFwk::ElementName& elementName)
1339 {
1340 std::lock_guard sortFileLockGuard(sortFileReadWriteLock_);
1341 SLOGI("refresh sort when session created, bundleName=%{public}s", (elementName.GetBundleName()).c_str());
1342 std::string oldSortContent;
1343 if (LoadStringFromFileEx(GetAVSortDir(), oldSortContent)) {
1344 nlohmann::json values = json::parse(oldSortContent, nullptr, false);
1345 CHECK_AND_RETURN_LOG(!values.is_discarded(), "sort json object is null");
1346 if (!values.is_array()) {
1347 SLOGI("create new json array for SaveSessionInfoInFile");
1348 values = json::array();
1349 }
1350 if (oldSortContent.find(elementName.GetBundleName()) == string::npos) {
1351 auto callback = [this](std::string bundleName, int32_t userId) {
1352 SLOGI("recv delete bundle:%{public}s at user:%{public}d", bundleName.c_str(), userId);
1353 DeleteAVQueueInfoRecord(bundleName, userId);
1354 DeleteHistoricalRecord(bundleName, userId);
1355 };
1356 if (!BundleStatusAdapter::GetInstance().SubscribeBundleStatusEvent(elementName.GetBundleName(),
1357 callback, GetUsersManager().GetCurrentUserId())) {
1358 SLOGE("SubscribeBundleStatusEvent failed");
1359 }
1360 }
1361 for (auto value : values) {
1362 if (elementName.GetBundleName() == value["bundleName"] &&
1363 elementName.GetAbilityName() == value["abilityName"]) {
1364 values.erase(std::remove(values.begin(), values.end(), value));
1365 }
1366 }
1367 if (values.size() >= (size_t)maxHistoryNums) {
1368 values.erase(values.end() - 1);
1369 }
1370 nlohmann::json value;
1371 value["sessionId"] = sessionId;
1372 value["bundleName"] = elementName.GetBundleName();
1373 value["abilityName"] = elementName.GetAbilityName();
1374 value["sessionType"] = sessionType;
1375 if (values.size() <= 0) {
1376 values.push_back(value);
1377 } else {
1378 values.insert(values.begin(), value);
1379 }
1380 std::string newSortContent = values.dump();
1381 SLOGD("refreshSortFileOnCreateSession::Dump json object finished");
1382 if (!SaveStringToFileEx(GetAVSortDir(), newSortContent)) {
1383 SLOGE("SaveStringToFile failed, filename=%{public}s", SORT_FILE_NAME);
1384 }
1385 } else {
1386 SLOGE("LoadStringToFile failed, filename=%{public}s", SORT_FILE_NAME);
1387 }
1388 }
1389 // LCOV_EXCL_STOP
1390
GetAllSessionDescriptors(std::vector<AVSessionDescriptor> & descriptors)1391 int32_t AVSessionService::GetAllSessionDescriptors(std::vector<AVSessionDescriptor>& descriptors)
1392 {
1393 std::lock_guard frontLockGuard(sessionFrontLock_);
1394 std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront();
1395 CHECK_AND_RETURN_RET_LOG(sessionListForFront != nullptr, AVSESSION_ERROR, "sessionListForFront ptr nullptr!");
1396 for (const auto& session : *sessionListForFront) {
1397 descriptors.push_back(session->GetDescriptor());
1398 }
1399 for (const auto& desc: descriptors) {
1400 SLOGD("desc=%{public}s", desc.elementName_.GetBundleName().c_str());
1401 }
1402 SLOGI("GetAllSessionDescriptors with size=%{public}d, topSession:%{public}s",
1403 static_cast<int32_t>(descriptors.size()),
1404 (topSession_ == nullptr ? "null" : topSession_->GetBundleName()).c_str());
1405 return AVSESSION_SUCCESS;
1406 }
1407
GetSessionDescriptorsBySessionId(const std::string & sessionId,AVSessionDescriptor & descriptor)1408 int32_t AVSessionService::GetSessionDescriptorsBySessionId(const std::string& sessionId,
1409 AVSessionDescriptor& descriptor)
1410 {
1411 std::lock_guard lockGuard(sessionAndControllerLock_);
1412 sptr<AVSessionItem> session = GetContainer().GetSessionById(sessionId);
1413 CHECK_AND_RETURN_RET_LOG(session != nullptr, AVSESSION_ERROR, "session not exist");
1414
1415 SLOGI("find descriptor by id %{public}s", AVSessionUtils::GetAnonySessionId(sessionId).c_str());
1416 auto pid = GetCallingPid();
1417 if (pid == session->GetPid()) {
1418 descriptor = session->GetDescriptor();
1419 return AVSESSION_SUCCESS;
1420 }
1421 int32_t err = PermissionChecker::GetInstance().CheckPermission(PermissionChecker::CHECK_SYSTEM_PERMISSION);
1422 if (err != ERR_NONE) {
1423 SLOGE("GetSessionDescriptorsBySessionId: CheckPermission failed");
1424 HISYSEVENT_SECURITY("CONTROL_PERMISSION_DENIED", "CALLER_UID", GetCallingUid(),
1425 "CALLER_PID", GetCallingUid(), "SESSION_ID", sessionId,
1426 "ERROR_MSG", "avsessionservice getsessiondescriptors by sessionid checkpermission failed");
1427 return err;
1428 }
1429 descriptor = session->GetDescriptor();
1430 return AVSESSION_SUCCESS;
1431 }
1432
GetHistoricalSessionDescriptorsFromFile(std::vector<AVSessionDescriptor> & descriptors)1433 int32_t AVSessionService::GetHistoricalSessionDescriptorsFromFile(std::vector<AVSessionDescriptor>& descriptors)
1434 {
1435 std::string oldSortContent;
1436 if (!LoadStringFromFileEx(GetAVSortDir(), oldSortContent)) {
1437 SLOGE("GetHistoricalSessionDescriptorsFromFile read sort fail, Return!");
1438 return AVSESSION_ERROR;
1439 }
1440
1441 nlohmann::json sortValues = json::parse(oldSortContent, nullptr, false);
1442 CHECK_AND_RETURN_RET_LOG(!sortValues.is_discarded(), AVSESSION_ERROR, "json object is null");
1443 for (const auto& value : sortValues) {
1444 if (value["sessionType"] == "video") {
1445 SLOGI("GetHistoricalSessionDescriptorsFromFile with no video type session");
1446 continue;
1447 }
1448 AVSessionDescriptor descriptor;
1449 descriptor.sessionId_ = value["sessionId"];
1450 descriptor.elementName_.SetBundleName(value["bundleName"]);
1451 descriptor.elementName_.SetAbilityName(value["abilityName"]);
1452 descriptor.sessionType_ = AVSession::SESSION_TYPE_AUDIO;
1453 descriptors.push_back(descriptor);
1454 }
1455 if (descriptors.size() == 0 && GetContainer().GetAllSessions().size() == 0) {
1456 SLOGE("GetHistoricalSessionDescriptorsFromFile read empty, return!");
1457 }
1458 return AVSESSION_SUCCESS;
1459 }
1460
GetHistoricalSessionDescriptors(int32_t maxSize,std::vector<AVSessionDescriptor> & descriptors)1461 int32_t AVSessionService::GetHistoricalSessionDescriptors(int32_t maxSize,
1462 std::vector<AVSessionDescriptor>& descriptors)
1463 {
1464 std::lock_guard lockGuard(sessionAndControllerLock_);
1465 std::lock_guard sortFileLockGuard(sortFileReadWriteLock_);
1466
1467 std::vector<AVSessionDescriptor> tempDescriptors;
1468 GetHistoricalSessionDescriptorsFromFile(tempDescriptors);
1469 if (maxSize < 0 || maxSize > maxHistoryNums) {
1470 maxSize = unSetHistoryNum;
1471 }
1472 for (auto iterator = tempDescriptors.begin(); iterator != tempDescriptors.end(); ++iterator) {
1473 if (descriptors.size() >= (size_t)maxSize) {
1474 break;
1475 }
1476 descriptors.push_back(*iterator);
1477 }
1478 SLOGI("get historical session size=%{public}d", static_cast<int>(descriptors.size()));
1479 return AVSESSION_SUCCESS;
1480 }
1481
1482 // LCOV_EXCL_START
GetHistoricalAVQueueInfos(int32_t maxSize,int32_t maxAppSize,std::vector<AVQueueInfo> & avQueueInfos)1483 int32_t AVSessionService::GetHistoricalAVQueueInfos(int32_t maxSize, int32_t maxAppSize,
1484 std::vector<AVQueueInfo>& avQueueInfos)
1485 {
1486 std::lock_guard avQueueFileLockGuard(avQueueFileReadWriteLock_);
1487 std::string oldAVQueueInfoContent;
1488 std::vector<AVQueueInfo> tempAVQueueInfos;
1489 if (!LoadStringFromFileEx(GetAVQueueDir(), oldAVQueueInfoContent)) {
1490 SLOGE("GetHistoricalAVQueueInfos read avqueueinfo fail, Return!");
1491 return AVSESSION_ERROR;
1492 }
1493 nlohmann::json avQueueValues = json::parse(oldAVQueueInfoContent, nullptr, false);
1494 CHECK_AND_RETURN_RET_LOG(!avQueueValues.is_discarded(), AVSESSION_ERROR, "json object is null");
1495 for (const auto& value : avQueueValues) {
1496 AVQueueInfo avQueueInfo;
1497 avQueueInfo.SetBundleName(value["bundleName"]);
1498 avQueueInfo.SetAVQueueName(value["avQueueName"]);
1499 avQueueInfo.SetAVQueueId(value["avQueueId"]);
1500 std::shared_ptr<AVSessionPixelMap> avQueuePixelMap = std::make_shared<AVSessionPixelMap>();
1501 CHECK_AND_RETURN_RET_LOG(value.contains("avQueueImageDir"), AVSESSION_ERROR, "avQueueImageDir not contain");
1502 CHECK_AND_RETURN_RET_LOG(value.contains("avQueueImageName"), AVSESSION_ERROR, "avQueueImageName not contain");
1503 AVSessionUtils::ReadImageFromFile(avQueuePixelMap, value["avQueueImageDir"], value["avQueueImageName"]);
1504 avQueueInfo.SetAVQueueImage(avQueuePixelMap);
1505 avQueueInfo.SetAVQueueImageUri(value["avQueueImageUri"]);
1506 tempAVQueueInfos.push_back(avQueueInfo);
1507 }
1508 for (auto iterator = tempAVQueueInfos.begin(); iterator != tempAVQueueInfos.end(); ++iterator) {
1509 avQueueInfos.push_back(*iterator);
1510 }
1511 SLOGI("get historical avQueueinfo size=%{public}d", static_cast<int>(avQueueInfos.size()));
1512 return AVSESSION_SUCCESS;
1513 }
1514 // LCOV_EXCL_STOP
1515
1516 // LCOV_EXCL_START
SaveAvQueueInfo(std::string & oldContent,const std::string & bundleName,const AVMetaData & meta,const int32_t userId)1517 bool AVSessionService::SaveAvQueueInfo(std::string& oldContent, const std::string &bundleName,
1518 const AVMetaData& meta, const int32_t userId)
1519 {
1520 nlohmann::json values = json::parse(oldContent, nullptr, false);
1521 CHECK_AND_RETURN_RET_LOG(!values.is_discarded(), false, "avQueue json object is null");
1522 auto it = values.begin();
1523 for (auto& value : values) {
1524 if (bundleName == value["bundleName"] && meta.GetAVQueueId() == value["avQueueId"]) {
1525 if (meta.GetAVQueueId() == it->at("avQueueId")) {
1526 SLOGI("SaveAvQueueInfo avqueue=%{public}s is first, return", meta.GetAVQueueId().c_str());
1527 return false;
1528 }
1529 values.erase(std::remove(values.begin(), values.end(), value));
1530 }
1531 }
1532 if (values.size() >= (size_t)maxAVQueueInfoLen) {
1533 values.erase(values.end() - 1);
1534 }
1535 nlohmann::json value;
1536 value["bundleName"] = bundleName;
1537 value["avQueueName"] = meta.GetAVQueueName();
1538 value["avQueueId"] = meta.GetAVQueueId();
1539 std::shared_ptr<AVSessionPixelMap> innerPixelMap = meta.GetAVQueueImage();
1540 if (innerPixelMap != nullptr) {
1541 std::string fileDir = AVSessionUtils::GetFixedPathName(userId);
1542 std::string fileName = bundleName + "_" + meta.GetAVQueueId() + AVSessionUtils::GetFileSuffix();
1543 AVSessionUtils::WriteImageToFile(innerPixelMap, fileDir, fileName);
1544 innerPixelMap->Clear();
1545 value["avQueueImageDir"] = fileDir;
1546 value["avQueueImageName"] = fileName;
1547 } else {
1548 value["avQueueImageDir"] = "";
1549 value["avQueueImageName"] = "";
1550 }
1551 value["avQueueImageUri"] = meta.GetAVQueueImageUri();
1552 if (values.size() <= 0) {
1553 values.push_back(value);
1554 } else {
1555 values.insert(values.begin(), value);
1556 }
1557 std::string newContent = values.dump();
1558 SLOGD("SaveAvQueueInfo::Dump json object finished");
1559 if (!SaveStringToFileEx(GetAVQueueDir(userId), newContent)) {
1560 SLOGE("SaveStringToFile failed, filename=%{public}s", AVQUEUE_FILE_NAME);
1561 return false;
1562 }
1563 return true;
1564 }
1565 // LCOV_EXCL_STOP
1566
1567 // LCOV_EXCL_START
AddAvQueueInfoToFile(AVSessionItem & session)1568 void AVSessionService::AddAvQueueInfoToFile(AVSessionItem& session)
1569 {
1570 SLOGD("add queueinfo to file in");
1571 // check is this session support playmusiclist intent
1572 std::lock_guard lockGuard(sessionAndControllerLock_);
1573 std::string bundleName = session.GetBundleName();
1574 std::string supportModule;
1575 std::string profile;
1576 if (!BundleStatusAdapter::GetInstance().IsSupportPlayIntent(bundleName, supportModule, profile)) {
1577 SLOGE("bundleName=%{public}s does not support play intent", bundleName.c_str());
1578 return;
1579 }
1580 AVMetaData meta = session.GetMetaData();
1581 if (meta.GetAVQueueId().empty() || meta.GetAVQueueName().empty()) {
1582 SLOGI("AddAvQueueInfoToFile avqueueinfo empty, return");
1583 DoMetadataImgClean(meta);
1584 return;
1585 }
1586 std::lock_guard avQueueFileLockGuard(avQueueFileReadWriteLock_);
1587 std::string oldContent;
1588 int32_t userId = session.GetUserId();
1589 SLOGI("AddAvQueueInfoToFile for bundleName:%{public}s,userId:%{public}d", bundleName.c_str(), userId);
1590 if (!LoadStringFromFileEx(GetAVQueueDir(userId), oldContent)) {
1591 SLOGE("AddAvQueueInfoToFile read avqueueinfo fail, Return!");
1592 DoMetadataImgClean(meta);
1593 return;
1594 }
1595 if (!SaveAvQueueInfo(oldContent, bundleName, meta, userId)) {
1596 SLOGE("SaveAvQueueInfo same avqueueinfo, Return!");
1597 DoMetadataImgClean(meta);
1598 return;
1599 }
1600 DoMetadataImgClean(meta);
1601 SLOGD("add queueinfo to file done");
1602 }
1603 // LCOV_EXCL_STOP
1604
DoMetadataImgClean(AVMetaData & data)1605 void AVSessionService::DoMetadataImgClean(AVMetaData& data)
1606 {
1607 SLOGI("clear media img in DoMetadataImgClean");
1608 std::shared_ptr<AVSessionPixelMap> innerQueuePixelMap = data.GetAVQueueImage();
1609 if (innerQueuePixelMap != nullptr) {
1610 innerQueuePixelMap->Clear();
1611 }
1612 std::shared_ptr<AVSessionPixelMap> innerMediaPixelMap = data.GetMediaImage();
1613 if (innerMediaPixelMap != nullptr) {
1614 innerMediaPixelMap->Clear();
1615 }
1616 }
1617
StartAVPlayback(const std::string & bundleName,const std::string & assetId)1618 int32_t AVSessionService::StartAVPlayback(const std::string& bundleName, const std::string& assetId)
1619 {
1620 SLOGE("StartAVPlayback in!");
1621 std::unique_ptr<AVSessionDynamicLoader> dynamicLoader = std::make_unique<AVSessionDynamicLoader>();
1622
1623 typedef int32_t (*StartAVPlaybackFunc)(const std::string& bundleName, const std::string& assetId);
1624 StartAVPlaybackFunc startAVPlayback =
1625 reinterpret_cast<StartAVPlaybackFunc>(dynamicLoader->GetFuntion(
1626 AVSESSION_DYNAMIC_INSIGHT_LIBRARY_PATH, "StartAVPlayback"));
1627 if (startAVPlayback) {
1628 return (*startAVPlayback)(bundleName, assetId);
1629 }
1630 SLOGE("StartAVPlayback fail");
1631 return AVSESSION_ERROR;
1632 }
1633
CreateNewControllerForSession(pid_t pid,sptr<AVSessionItem> & session)1634 sptr<AVControllerItem> AVSessionService::CreateNewControllerForSession(pid_t pid, sptr<AVSessionItem>& session)
1635 {
1636 SLOGI("pid=%{public}d sessionId=%{public}s", pid,
1637 AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str());
1638 sptr<AVControllerItem> result = new(std::nothrow) AVControllerItem(pid, session, session->GetUserId());
1639 if (result == nullptr) {
1640 SLOGE("malloc controller failed");
1641 return nullptr;
1642 }
1643 result->SetServiceCallbackForRelease([this](AVControllerItem& controller) { HandleControllerRelease(controller); });
1644 session->AddController(pid, result);
1645 if (AbilityHasSession(pid)) {
1646 SLOGI("set isfromsession for pid %{public}d", static_cast<int>(pid));
1647 result->isFromSession_ = true;
1648 }
1649 return result;
1650 }
1651
1652 // LCOV_EXCL_START
GetSubNode(const nlohmann::json & node,const std::string & name)1653 const nlohmann::json& AVSessionService::GetSubNode(const nlohmann::json& node, const std::string& name)
1654 {
1655 static const nlohmann::json jsonNull = nlohmann::json::value_t::null;
1656 if (node.is_discarded() || node.is_null()) {
1657 SLOGE("json node is invalid");
1658 return jsonNull;
1659 }
1660
1661 if (name.empty()) {
1662 SLOGE("name is invalid");
1663 return node;
1664 }
1665
1666 auto it = node.find(name);
1667 if (it == node.end()) {
1668 SLOGE("%{public}s is not exist in json", name.c_str());
1669 return jsonNull;
1670 }
1671 return *it;
1672 }
1673 // LCOV_EXCL_STOP
1674
IsHistoricalSession(const std::string & sessionId)1675 bool AVSessionService::IsHistoricalSession(const std::string& sessionId)
1676 {
1677 {
1678 std::string sortContent;
1679 std::lock_guard sortFileLockGuard(sortFileReadWriteLock_);
1680 if (!LoadStringFromFileEx(GetAVSortDir(), sortContent)) {
1681 SLOGE("IsHistoricalSession read sort failed, filename=%{public}s", SORT_FILE_NAME);
1682 return false;
1683 }
1684 if (sortContent.find(sessionId) == string::npos) {
1685 SLOGE("IsHistoricalSession find session no sort, sessionId=%{public}s",
1686 AVSessionUtils::GetAnonySessionId(sessionId).c_str());
1687 return false;
1688 }
1689 }
1690
1691 auto session = GetContainer().GetSessionById(sessionId);
1692 if (session != nullptr) {
1693 SLOGE("IsHistoricalSession find session alive, sessionId=%{public}s",
1694 AVSessionUtils::GetAnonySessionId(sessionId).c_str());
1695 return false;
1696 }
1697 SLOGE("IsHistoricalSession find session historical, sessionId=%{public}s",
1698 AVSessionUtils::GetAnonySessionId(sessionId).c_str());
1699 return true;
1700 }
1701
StartDefaultAbilityByCall(std::string & sessionId)1702 int32_t AVSessionService::StartDefaultAbilityByCall(std::string& sessionId)
1703 {
1704 std::string bundleName = DEFAULT_BUNDLE_NAME;
1705 std::string abilityName = DEFAULT_ABILITY_NAME;
1706 std::string sortContent;
1707 {
1708 std::lock_guard sortFileLockGuard(sortFileReadWriteLock_);
1709 if (!LoadStringFromFileEx(GetAVSortDir(), sortContent)) {
1710 SLOGE("GetAllSessionDescriptors read sort fail! ");
1711 return AVSESSION_ERROR;
1712 }
1713 }
1714 if (!sortContent.empty()) {
1715 nlohmann::json sortValues = json::parse(sortContent, nullptr, false);
1716 CHECK_AND_RETURN_RET_LOG(!sortValues.is_discarded(), AVSESSION_ERROR, "json object is null");
1717 for (auto& value : sortValues) {
1718 CHECK_AND_CONTINUE(!value.is_null() && !value.is_discarded() && value.contains("sessionId"));
1719 auto session = GetContainer().GetSessionById(value["sessionId"]);
1720 if (session == nullptr) {
1721 bundleName = value["bundleName"];
1722 abilityName = value["abilityName"];
1723 SLOGI("Default start not alive %{public}s", bundleName.c_str());
1724 break;
1725 } else {
1726 SLOGE("Default start alive %{public}s", AVSessionUtils::GetAnonySessionId(value["sessionId"]).c_str());
1727 return AVSESSION_ERROR;
1728 }
1729 }
1730 }
1731 std::shared_ptr<AbilityManagerAdapter> ability = nullptr;
1732 {
1733 std::lock_guard lockGuard(abilityManagerLock_);
1734 auto it = abilityManager_.find(bundleName + abilityName);
1735 if (it != abilityManager_.end()) {
1736 ability = it->second;
1737 } else {
1738 ability = std::make_shared<AbilityManagerAdapter>(bundleName, abilityName);
1739 if (ability == nullptr) {
1740 return ERR_NO_MEMORY;
1741 }
1742 abilityManager_[bundleName + abilityName] = ability;
1743 }
1744 }
1745 int32_t ret = ability->StartAbilityByCall(sessionId);
1746
1747 std::lock_guard lockGuard(abilityManagerLock_);
1748 if (ret != ERR_START_ABILITY_IS_RUNNING) {
1749 abilityManager_.erase(bundleName + abilityName);
1750 }
1751 return ret;
1752 }
1753
StartAbilityByCall(const std::string & sessionIdNeeded,std::string & sessionId)1754 int32_t AVSessionService::StartAbilityByCall(const std::string& sessionIdNeeded, std::string& sessionId)
1755 {
1756 std::string content;
1757
1758 {
1759 std::lock_guard sortFileLockGuard(sortFileReadWriteLock_);
1760 if (!LoadStringFromFileEx(GetAVSortDir(), content)) {
1761 SLOGE("LoadStringFromFile failed, filename=%{public}s", SORT_FILE_NAME);
1762 return AVSESSION_ERROR;
1763 }
1764 }
1765
1766 nlohmann::json values = json::parse(content, nullptr, false);
1767 CHECK_AND_RETURN_RET_LOG(!values.is_discarded(), AVSESSION_ERROR, "json object is null");
1768 std::string bundleName;
1769 std::string abilityName;
1770 for (auto& value : values) {
1771 if (sessionIdNeeded == value["sessionId"]) {
1772 bundleName = value["bundleName"];
1773 abilityName = value["abilityName"];
1774 break;
1775 }
1776 }
1777 if (bundleName.empty() || abilityName.empty()) {
1778 SLOGE("Get bundle name & ability name failed, sessionId=%{public}s",
1779 AVSessionUtils::GetAnonySessionId(sessionIdNeeded).c_str());
1780 return AVSESSION_ERROR;
1781 }
1782 std::shared_ptr<AbilityManagerAdapter> ability = nullptr;
1783 {
1784 std::lock_guard lockGuard(abilityManagerLock_);
1785 auto it = abilityManager_.find(bundleName + abilityName);
1786 if (it != abilityManager_.end()) {
1787 ability = it->second;
1788 } else {
1789 ability = std::make_shared<AbilityManagerAdapter>(bundleName, abilityName);
1790 if (ability == nullptr) {
1791 return ERR_NO_MEMORY;
1792 }
1793 abilityManager_[bundleName + abilityName] = ability;
1794 }
1795 }
1796 int32_t ret = ability->StartAbilityByCall(sessionId);
1797
1798 std::lock_guard lockGuard(abilityManagerLock_);
1799 if (ret != ERR_START_ABILITY_IS_RUNNING) {
1800 abilityManager_.erase(bundleName + abilityName);
1801 }
1802 return ret;
1803 }
1804
CreateControllerInner(const std::string & sessionId,sptr<IRemoteObject> & object)1805 int32_t AVSessionService::CreateControllerInner(const std::string& sessionId, sptr<IRemoteObject>& object)
1806 {
1807 auto pid = GetCallingPid();
1808 std::string sessionIdInner;
1809 SLOGI("CreateControllerInner for sessionId:%{public}s, pid:%{public}d",
1810 AVSessionUtils::GetAnonySessionId(sessionId).c_str(), static_cast<int>(pid));
1811 if (sessionId == "default") {
1812 auto ret = StartDefaultAbilityByCall(sessionIdInner);
1813 if (ret != AVSESSION_SUCCESS) {
1814 SLOGE("StartDefaultAbilityByCall failed: %{public}d", ret);
1815 return ret;
1816 }
1817 } else {
1818 if (IsHistoricalSession(sessionId)) {
1819 auto ret = StartAbilityByCall(sessionId, sessionIdInner);
1820 if (ret != AVSESSION_SUCCESS) {
1821 SLOGE("StartAbilityByCall failed: %{public}d", ret);
1822 return ret;
1823 }
1824 } else {
1825 sessionIdInner = sessionId;
1826 }
1827 }
1828 std::lock_guard lockGuard(sessionAndControllerLock_);
1829 auto controllerAlreadyExist = GetPresentController(pid, sessionIdInner);
1830 if (controllerAlreadyExist != nullptr) {
1831 SLOGI("controller already exist, try pass instance and return exist");
1832 object = controllerAlreadyExist;
1833 return ERR_CONTROLLER_IS_EXIST;
1834 }
1835
1836 auto session = GetContainer().GetSessionById(sessionIdInner);
1837 if (session == nullptr) {
1838 SLOGE("no session id %{public}s", AVSessionUtils::GetAnonySessionId(sessionIdInner).c_str());
1839 return ERR_SESSION_NOT_EXIST;
1840 }
1841
1842 auto result = CreateNewControllerForSession(pid, session);
1843 if (result == nullptr) {
1844 SLOGE("create new controller failed");
1845 return ERR_NO_MEMORY;
1846 }
1847
1848 controllers_[pid].push_back(result);
1849 object = result;
1850 SLOGI("success");
1851 return AVSESSION_SUCCESS;
1852 }
1853
1854 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
GetAVCastControllerInner(const std::string & sessionId,sptr<IRemoteObject> & object)1855 int32_t AVSessionService::GetAVCastControllerInner(const std::string& sessionId, sptr<IRemoteObject>& object)
1856 {
1857 SLOGI("Start get cast controller with pid %{public}d", static_cast<int>(GetCallingPid()));
1858 auto session = GetContainer().GetSessionById(sessionId);
1859 CHECK_AND_RETURN_RET_LOG(session != nullptr, AVSESSION_ERROR, "StopCast: session is not exist");
1860 auto result = session->GetAVCastControllerInner();
1861 CHECK_AND_RETURN_RET_LOG(result != nullptr, AVSESSION_ERROR, "GetAVCastControllerInner failed");
1862 object = result;
1863 return AVSESSION_SUCCESS;
1864 }
1865 #endif
1866
AddSessionListener(pid_t pid,const sptr<ISessionListener> & listener)1867 void AVSessionService::AddSessionListener(pid_t pid, const sptr<ISessionListener>& listener)
1868 {
1869 std::lock_guard lockGuard(sessionListenersLock_);
1870 GetUsersManager().AddSessionListener(pid, listener);
1871 }
1872
AddSessionListenerForAllUsers(pid_t pid,const sptr<ISessionListener> & listener)1873 void AVSessionService::AddSessionListenerForAllUsers(pid_t pid, const sptr<ISessionListener>& listener)
1874 {
1875 std::lock_guard lockGuard(sessionListenersLock_);
1876 GetUsersManager().AddSessionListenerForAllUsers(pid, listener);
1877 }
1878
RemoveSessionListener(pid_t pid)1879 void AVSessionService::RemoveSessionListener(pid_t pid)
1880 {
1881 std::lock_guard lockGuard(sessionListenersLock_);
1882 GetUsersManager().RemoveSessionListener(pid);
1883 }
1884
RegisterSessionListener(const sptr<ISessionListener> & listener)1885 int32_t AVSessionService::RegisterSessionListener(const sptr<ISessionListener>& listener)
1886 {
1887 SLOGI("Enter RegisterSessionListener process and return current userId");
1888 AddSessionListener(GetCallingPid(), listener);
1889 return GetUsersManager().GetCurrentUserId();
1890 }
1891
RegisterSessionListenerForAllUsers(const sptr<ISessionListener> & listener)1892 int32_t AVSessionService::RegisterSessionListenerForAllUsers(const sptr<ISessionListener>& listener)
1893 {
1894 SLOGI("Enter RegisterSessionListenerForAllUsers process");
1895 AddSessionListenerForAllUsers(GetCallingPid(), listener);
1896 return AVSESSION_SUCCESS;
1897 }
1898
1899 // LCOV_EXCL_START
HandleEventHandlerCallBack()1900 void AVSessionService::HandleEventHandlerCallBack()
1901 {
1902 SLOGI("handle eventHandler callback isFirstPress_=%{public}d, pressCount_:%{public}d", isFirstPress_, pressCount_);
1903 AVControlCommand cmd;
1904 bool shouldColdPlay = false;
1905 {
1906 std::lock_guard lockGuard(sessionAndControllerLock_);
1907 if (pressCount_ >= THREE_CLICK) {
1908 cmd.SetCommand(AVControlCommand::SESSION_CMD_PLAY_PREVIOUS);
1909 } else if (pressCount_ == DOUBLE_CLICK) {
1910 cmd.SetCommand(AVControlCommand::SESSION_CMD_PLAY_NEXT);
1911 } else if (pressCount_ == ONE_CLICK) {
1912 if (topSession_) {
1913 auto playbackState = topSession_->GetPlaybackState();
1914 cmd.SetCommand(playbackState.GetState() == AVPlaybackState::PLAYBACK_STATE_PLAY ?
1915 AVControlCommand::SESSION_CMD_PAUSE : AVControlCommand::SESSION_CMD_PLAY);
1916 } else {
1917 cmd.SetCommand(AVControlCommand::SESSION_CMD_PLAY);
1918 }
1919 } else {
1920 pressCount_ = 0;
1921 isFirstPress_ = true;
1922 SLOGI("press invalid return, topSession alive:%{public}d", static_cast<int>(topSession_ != nullptr));
1923 return;
1924 }
1925 SLOGI("HandleEventHandlerCallBack proc cmd=%{public}d", cmd.GetCommand());
1926 if (!topSession_) {
1927 shouldColdPlay = true;
1928 SLOGI("HandleEventHandlerCallBack without topSession_ shouldColdStart=%{public}d", shouldColdPlay);
1929 } else {
1930 if (topSession_->GetDescriptor().sessionTag_ == "external_audio") {
1931 SLOGI("HandleEventHandlerCallBack this is an external audio");
1932 } else {
1933 topSession_->ExecuteControllerCommand(cmd);
1934 }
1935 }
1936 }
1937 if (shouldColdPlay) {
1938 HandleSystemKeyColdStart(cmd);
1939 }
1940 pressCount_ = 0;
1941 isFirstPress_ = true;
1942 }
1943 // LCOV_EXCL_STOP
1944
SendSystemAVKeyEvent(const MMI::KeyEvent & keyEvent)1945 int32_t AVSessionService::SendSystemAVKeyEvent(const MMI::KeyEvent& keyEvent)
1946 {
1947 SLOGI("SendSystemAVKeyEvent get key=%{public}d", keyEvent.GetKeyCode());
1948 if (keyEvent.GetKeyCode() == MMI::KeyEvent::KEYCODE_HEADSETHOOK) {
1949 pressCount_++;
1950 SLOGI("isFirstPress_=%{public}d", isFirstPress_);
1951 if (isFirstPress_) {
1952 auto ret = AVSessionEventHandler::GetInstance().AVSessionPostTask([this]() {
1953 HandleEventHandlerCallBack();
1954 }, "SendSystemAVKeyEvent", CLICK_TIMEOUT);
1955 CHECK_AND_RETURN_RET_LOG(ret, AVSESSION_ERROR, "init eventHandler failed");
1956 isFirstPress_ = false;
1957 }
1958 return AVSESSION_SUCCESS;
1959 }
1960 {
1961 std::lock_guard lockGuard(sessionAndControllerLock_);
1962 if (topSession_) {
1963 topSession_->HandleMediaKeyEvent(keyEvent);
1964 return AVSESSION_SUCCESS;
1965 }
1966 }
1967 {
1968 int cmd = ConvertKeyCodeToCommand(keyEvent.GetKeyCode());
1969 AVControlCommand controlCommand;
1970 controlCommand.SetCommand(cmd);
1971 SLOGI("topSession get nullptr, check if cold start for cmd %{public}d", cmd);
1972 HandleSystemKeyColdStart(controlCommand);
1973 }
1974 return AVSESSION_SUCCESS;
1975 }
1976
ConvertKeyCodeToCommand(int keyCode)1977 int32_t AVSessionService::ConvertKeyCodeToCommand(int keyCode)
1978 {
1979 if (keyCode == MMI::KeyEvent::KEYCODE_MEDIA_PLAY_PAUSE) {
1980 return AVControlCommand::SESSION_CMD_PLAY;
1981 } else if (keyCode == MMI::KeyEvent::KEYCODE_MEDIA_PLAY) {
1982 return AVControlCommand::SESSION_CMD_PLAY;
1983 } else if (keyCode == MMI::KeyEvent::KEYCODE_MEDIA_PAUSE) {
1984 return AVControlCommand::SESSION_CMD_PAUSE;
1985 } else if (keyCode == MMI::KeyEvent::KEYCODE_MEDIA_STOP) {
1986 return AVControlCommand::SESSION_CMD_STOP;
1987 } else if (keyCode == MMI::KeyEvent::KEYCODE_MEDIA_NEXT) {
1988 return AVControlCommand::SESSION_CMD_PLAY_NEXT;
1989 } else if (keyCode == MMI::KeyEvent::KEYCODE_MEDIA_PREVIOUS) {
1990 return AVControlCommand::SESSION_CMD_PLAY_PREVIOUS;
1991 } else if (keyCode == MMI::KeyEvent::KEYCODE_MEDIA_REWIND) {
1992 return AVControlCommand::SESSION_CMD_REWIND;
1993 } else if (keyCode == MMI::KeyEvent::KEYCODE_MEDIA_FAST_FORWARD) {
1994 return AVControlCommand::SESSION_CMD_FAST_FORWARD;
1995 }
1996 return AVControlCommand::SESSION_CMD_PLAY;
1997 }
1998
HandleSystemKeyColdStart(const AVControlCommand & command)1999 void AVSessionService::HandleSystemKeyColdStart(const AVControlCommand &command)
2000 {
2001 SLOGI("HandleSystemKeyColdStart cmd=%{public}d without topsession", command.GetCommand());
2002 // try proc command for first front session
2003 {
2004 std::lock_guard frontLockGuard(sessionFrontLock_);
2005 std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront();
2006 CHECK_AND_RETURN_LOG(sessionListForFront != nullptr, "sessionListForFront ptr nullptr!");
2007 for (const auto& session : *sessionListForFront) {
2008 if (session->GetSessionType() != "voice_call" && session->GetSessionType() != "video_call") {
2009 session->ExecuteControllerCommand(command);
2010 SLOGI("ExecuteCommand %{public}d for front session: %{public}s", command.GetCommand(),
2011 session->GetBundleName().c_str());
2012 return;
2013 }
2014 }
2015 }
2016
2017 std::vector<AVSessionDescriptor> hisDescriptors;
2018 {
2019 std::lock_guard sortFileLockGuard(sortFileReadWriteLock_);
2020 GetHistoricalSessionDescriptorsFromFile(hisDescriptors);
2021 }
2022 // try start play for first history session
2023 if ((command.GetCommand() == AVControlCommand::SESSION_CMD_PLAY ||
2024 command.GetCommand() == AVControlCommand::SESSION_CMD_PLAY_NEXT ||
2025 command.GetCommand() == AVControlCommand::SESSION_CMD_PLAY_PREVIOUS) && hisDescriptors.size() != 0) {
2026 sptr<IRemoteObject> object;
2027 int32_t ret = CreateControllerInner(hisDescriptors[0].sessionId_, object);
2028 SLOGI("Cold play %{public}s, ret=%{public}d", hisDescriptors[0].elementName_.GetBundleName().c_str(), ret);
2029 } else {
2030 SLOGI("Cold start command=%{public}d, hisDescriptorsSize=%{public}d return", command.GetCommand(),
2031 static_cast<int>(hisDescriptors.size()));
2032 }
2033 }
2034
SendSystemControlCommand(const AVControlCommand & command)2035 int32_t AVSessionService::SendSystemControlCommand(const AVControlCommand &command)
2036 {
2037 {
2038 std::lock_guard lockGuard(sessionAndControllerLock_);
2039 SLOGI("SendSystemControlCommand with cmd:%{public}d, topSession alive:%{public}d",
2040 command.GetCommand(), static_cast<int>(topSession_ != nullptr));
2041 if (topSession_) {
2042 CHECK_AND_RETURN_RET_LOG(CommandSendLimit::GetInstance().IsCommandSendEnable(GetCallingPid()),
2043 ERR_COMMAND_SEND_EXCEED_MAX, "command excuted number exceed max");
2044 topSession_->ExecuteControllerCommand(command);
2045 return AVSESSION_SUCCESS;
2046 }
2047 }
2048 SLOGI("SendSystemControlCommand cmd:%{public}d without topSession_", command.GetCommand());
2049 HandleSystemKeyColdStart(command);
2050 return AVSESSION_SUCCESS;
2051 }
2052
AddClientDeathObserver(pid_t pid,const sptr<IClientDeath> & observer,const sptr<ClientDeathRecipient> recipient)2053 void AVSessionService::AddClientDeathObserver(pid_t pid, const sptr<IClientDeath>& observer,
2054 const sptr<ClientDeathRecipient> recipient)
2055 {
2056 std::lock_guard lockGuard(clientDeathObserversLock_);
2057 clientDeathObservers_[pid] = observer;
2058 clientDeathRecipients_[pid] = recipient;
2059 }
2060
RemoveClientDeathObserver(pid_t pid)2061 void AVSessionService::RemoveClientDeathObserver(pid_t pid)
2062 {
2063 std::lock_guard lockGuard(clientDeathObserversLock_);
2064 if (clientDeathObservers_.empty()) {
2065 SLOGE("try remove observer with empty list");
2066 } else {
2067 clientDeathObservers_.erase(pid);
2068 }
2069
2070 if (clientDeathRecipients_.empty()) {
2071 SLOGE("try remove recipient with empty list");
2072 } else {
2073 clientDeathRecipients_.erase(pid);
2074 }
2075 SLOGI("do RemoveClientDeathObserver for pid %{public}d done", static_cast<int>(pid));
2076 }
2077
RegisterClientDeathObserver(const sptr<IClientDeath> & observer)2078 int32_t AVSessionService::RegisterClientDeathObserver(const sptr<IClientDeath>& observer)
2079 {
2080 SLOGI("enter ClientDeathObserver register with recipient point");
2081 auto pid = GetCallingPid();
2082 sptr<ClientDeathRecipient> recipient =
2083 new(std::nothrow) ClientDeathRecipient([this, pid]() { OnClientDied(pid); });
2084 if (recipient == nullptr) {
2085 SLOGE("malloc failed");
2086 HISYSEVENT_FAULT("CONTROL_COMMAND_FAILED", "ERROR_TYPE", "RGS_CLIENT_DEATH_OBSERVER_FAILED",
2087 "ERROR_INFO", "avsession service register client death observer malloc failed");
2088 return AVSESSION_ERROR;
2089 }
2090
2091 if (!observer->AsObject()->AddDeathRecipient(recipient)) {
2092 SLOGE("add death recipient for %{public}d failed", pid);
2093 HISYSEVENT_FAULT("CONTROL_COMMAND_FAILED", "ERROR_TYPE", "RGS_CLIENT_DEATH_FAILED", "CALLING_PID", pid,
2094 "ERROR_INFO", "avsession service register client death observer, add death recipient failed");
2095 return AVSESSION_ERROR;
2096 }
2097
2098 AddClientDeathObserver(pid, observer, recipient);
2099 return AVSESSION_SUCCESS;
2100 }
2101
ClearClientResources(pid_t pid,bool continuePlay)2102 void AVSessionService::ClearClientResources(pid_t pid, bool continuePlay)
2103 {
2104 RemoveSessionListener(pid);
2105 {
2106 std::lock_guard lockGuard(sessionAndControllerLock_);
2107 ClearSessionForClientDiedNoLock(pid, continuePlay);
2108 ClearControllerForClientDiedNoLock(pid);
2109 }
2110 SLOGI("remove ClientDeathObserver to %{public}d", pid);
2111 RemoveClientDeathObserver(pid);
2112 }
2113
Close(void)2114 int32_t AVSessionService::Close(void)
2115 {
2116 auto pid = GetCallingPid();
2117 SLOGI("pid=%{public}d", pid);
2118 ClearClientResources(pid, false);
2119 return AVSESSION_SUCCESS;
2120 }
2121
OnClientDied(pid_t pid)2122 void AVSessionService::OnClientDied(pid_t pid)
2123 {
2124 SLOGI("pid=%{public}d", pid);
2125 ClearClientResources(pid, true);
2126 }
2127
2128 // LCOV_EXCL_START
DeleteHistoricalRecord(const std::string & bundleName,int32_t userId)2129 void AVSessionService::DeleteHistoricalRecord(const std::string& bundleName, int32_t userId)
2130 {
2131 if (userId <= 0) {
2132 userId = GetUsersManager().GetCurrentUserId();
2133 }
2134 if (!CheckUserDirValid(userId)) {
2135 SLOGE("DeleteHistoricalRecord target user:%{public}d not valid, return", userId);
2136 return;
2137 }
2138 SLOGI("delete historical record, bundleName=%{public}s, userId=%{public}d", bundleName.c_str(), userId);
2139 std::string oldContent;
2140 std::string newContent;
2141 nlohmann::json values;
2142 if (!LoadStringFromFileEx(GetAVSortDir(userId), oldContent)) {
2143 SLOGE("LoadStringFromFile failed, filename=%{public}s", SORT_FILE_NAME);
2144 return;
2145 }
2146 values = json::parse(oldContent, nullptr, false);
2147 CHECK_AND_RETURN_LOG(!values.is_discarded(), "json object is null");
2148 for (auto value : values) {
2149 if (bundleName == value["bundleName"]) {
2150 values.erase(std::remove(values.begin(), values.end(), value));
2151 break;
2152 }
2153 }
2154 newContent = values.dump();
2155 SLOGD("DeleteHistoricalRecord::Dump json object finished");
2156 if (!SaveStringToFileEx(GetAVSortDir(userId), newContent)) {
2157 SLOGE("SaveStringToFile failed, filename=%{public}s", SORT_FILE_NAME);
2158 return;
2159 }
2160 }
2161 // LCOV_EXCL_STOP
2162
2163 // LCOV_EXCL_START
DeleteAVQueueInfoRecord(const std::string & bundleName,int32_t userId)2164 void AVSessionService::DeleteAVQueueInfoRecord(const std::string& bundleName, int32_t userId)
2165 {
2166 if (userId <= 0) {
2167 userId = GetUsersManager().GetCurrentUserId();
2168 }
2169 if (!CheckUserDirValid(userId)) {
2170 SLOGE("DeleteAVQueueInfoRecord target user:%{public}d not valid, return", userId);
2171 return;
2172 }
2173 SLOGI("DeleteAVQueueInfoRecord, bundleName=%{public}s, userId=%{public}d", bundleName.c_str(), userId);
2174 std::string oldContent;
2175 std::string newContent;
2176 nlohmann::json values;
2177 if (!LoadStringFromFileEx(GetAVQueueDir(userId), oldContent)) {
2178 SLOGE("LoadStringFromFile failed, filename=%{public}s", AVQUEUE_FILE_NAME);
2179 return;
2180 }
2181 values = json::parse(oldContent, nullptr, false);
2182 CHECK_AND_RETURN_LOG(!values.is_discarded(), "json object is null");
2183 for (auto it = values.begin(); it != values.end();) {
2184 if (it->at("bundleName") == bundleName) {
2185 std::string avQueueId = it->at("avQueueId");
2186 std::string fileName = AVSessionUtils::GetFixedPathName(userId) + bundleName + "_" +
2187 avQueueId + AVSessionUtils::GetFileSuffix();
2188 AVSessionUtils::DeleteFile(fileName);
2189 values.erase(it);
2190 } else {
2191 ++it;
2192 }
2193 }
2194 newContent = values.dump();
2195 SLOGD("DeleteAVQueueInfoRecord::Dump json object finished");
2196 if (!SaveStringToFileEx(GetAVQueueDir(userId), newContent)) {
2197 SLOGE("SaveStringToFile failed, filename=%{public}s", AVQUEUE_FILE_NAME);
2198 return;
2199 }
2200 }
2201 // LCOV_EXCL_STOP
2202
HandleSessionRelease(std::string sessionId,bool continuePlay)2203 void AVSessionService::HandleSessionRelease(std::string sessionId, bool continuePlay)
2204 {
2205 SLOGI("HandleSessionRelease, sessionId=%{public}s", AVSessionUtils::GetAnonySessionId(sessionId).c_str());
2206 {
2207 std::lock_guard lockGuard(sessionAndControllerLock_);
2208 std::lock_guard frontLockGuard(sessionFrontLock_);
2209 sptr<AVSessionItem> sessionItem = GetUsersManager().GetContainerFromAll().GetSessionById(sessionId);
2210 CHECK_AND_RETURN_LOG(sessionItem != nullptr, "Session item is nullptr");
2211 NotifySessionRelease(sessionItem->GetDescriptor());
2212 sessionItem->DestroyTask(continuePlay);
2213 if (topSession_.GetRefPtr() == sessionItem.GetRefPtr()) {
2214 SLOGD("Top session is released session");
2215 UpdateTopSession(nullptr);
2216 int32_t userId = GetUsersManager().GetCurrentUserId();
2217 int32_t ret = Notification::NotificationHelper::CancelNotification(std::to_string(userId), 0);
2218 SLOGI("Topsession release CancelNotification with userId:%{public}d, ret=%{public}d", userId, ret);
2219 }
2220 if (sessionItem->GetRemoteSource() != nullptr) {
2221 int32_t ret = CancelCastAudioForClientExit(sessionItem->GetPid(), sessionItem);
2222 SLOGI("CancelCastAudioForClientExit ret is %{public}d", ret);
2223 } else {
2224 SLOGI("GetContainer has no this session");
2225 }
2226 HISYSEVENT_ADD_LIFE_CYCLE_INFO(sessionItem->GetDescriptor().elementName_.GetBundleName(),
2227 AppManagerAdapter::GetInstance().IsAppBackground(GetCallingUid(), GetCallingPid()),
2228 sessionItem->GetDescriptor().sessionType_, false);
2229 SLOGI("HandleSessionRelease, remove session: sessionId=%{public}s",
2230 AVSessionUtils::GetAnonySessionId(sessionId).c_str());
2231 GetUsersManager().RemoveSessionForAllUser(sessionItem->GetPid(), sessionItem->GetAbilityName());
2232 UpdateFrontSession(sessionItem, false);
2233 }
2234 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
2235 if ((GetUsersManager().GetContainerFromAll().GetAllSessions().size() == 0 ||
2236 (GetUsersManager().GetContainerFromAll().GetAllSessions().size() == 1 &&
2237 CheckAncoAudio())) && !is2in1_) {
2238 SLOGI("call disable cast for no session alive");
2239 checkEnableCast(false);
2240 }
2241 #endif
2242 }
2243
HandleControllerRelease(AVControllerItem & controller)2244 void AVSessionService::HandleControllerRelease(AVControllerItem& controller)
2245 {
2246 auto pid = controller.GetPid();
2247 std::lock_guard lockGuard(sessionAndControllerLock_);
2248 auto it = controllers_.find(pid);
2249 if (it == controllers_.end()) {
2250 return;
2251 }
2252 SLOGI("remove controller");
2253 it->second.remove(&controller);
2254 if (it->second.empty()) {
2255 controllers_.erase(pid);
2256 }
2257 }
2258
Dump(std::int32_t fd,const std::vector<std::u16string> & args)2259 std::int32_t AVSessionService::Dump(std::int32_t fd, const std::vector<std::u16string>& args)
2260 {
2261 if (fd < 0) {
2262 SLOGE("dump fd invalid");
2263 return ERR_INVALID_PARAM;
2264 }
2265
2266 if (dumpHelper_ == nullptr) {
2267 SLOGE("dumpHelper_ is nullptr!");
2268 return ERR_INVALID_PARAM;
2269 }
2270
2271 std::vector<std::string> argsInStr;
2272 for (const auto& arg : args) {
2273 SLOGI("Dump args: %s", Str16ToStr8(arg).c_str());
2274 argsInStr.emplace_back(Str16ToStr8(arg));
2275 }
2276
2277 std::string result;
2278 dumpHelper_->Dump(argsInStr, result, *this);
2279 std::int32_t ret = dprintf(fd, "%s", result.c_str());
2280 if (ret < 0) {
2281 SLOGI("dprintf to dump fd failed");
2282 return ERR_INVALID_PARAM;
2283 }
2284 return AVSESSION_SUCCESS;
2285 }
2286
GetService(const std::string & deviceId)2287 __attribute__((no_sanitize("cfi"))) std::shared_ptr<RemoteSessionCommandProcess> AVSessionService::GetService(
2288 const std::string& deviceId)
2289 {
2290 SLOGI("enter");
2291 auto mgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2292 if (mgr == nullptr) {
2293 SLOGE("failed to get sa mgr");
2294 return nullptr;
2295 }
2296 auto object = mgr->GetSystemAbility(AVSESSION_SERVICE_ID, deviceId);
2297 if (object == nullptr) {
2298 SLOGE("failed to get service");
2299 return nullptr;
2300 }
2301 SLOGI("check remoteService create");
2302 std::shared_ptr<RemoteSessionCommandProcess> remoteService = std::make_shared<RemoteSessionCommandProcess>(object);
2303 SLOGI("check remoteService create done");
2304 return remoteService;
2305 }
2306
IsLocalDevice(const std::string & networkId)2307 bool AVSessionService::IsLocalDevice(const std::string& networkId)
2308 {
2309 std::string localNetworkId;
2310 CHECK_AND_RETURN_RET_LOG(GetLocalNetworkId(localNetworkId) == AVSESSION_SUCCESS, AVSESSION_ERROR,
2311 "GetLocalNetworkId error");
2312 if (networkId == localNetworkId || networkId == "LocalDevice") {
2313 SLOGI("local device");
2314 return true;
2315 }
2316 SLOGI("not local device");
2317 return false;
2318 }
2319
GetLocalNetworkId(std::string & networkId)2320 int32_t AVSessionService::GetLocalNetworkId(std::string& networkId)
2321 {
2322 SLOGI("GetLocalNetworkId");
2323 DistributedHardware::DmDeviceInfo deviceInfo;
2324 int32_t ret = DistributedHardware::DeviceManager::GetInstance().GetLocalDeviceInfo("av_session", deviceInfo);
2325 CHECK_AND_RETURN_RET_LOG(ret == 0, ret, "get local deviceInfo failed");
2326 networkId = deviceInfo.networkId;
2327 return AVSESSION_SUCCESS;
2328 }
2329
GetTrustedDeviceName(const std::string & networkId,std::string & deviceName)2330 int32_t AVSessionService::GetTrustedDeviceName(const std::string& networkId, std::string& deviceName)
2331 {
2332 SLOGI("GetTrustedDeviceName");
2333 std::vector<OHOS::DistributedHardware::DmDeviceInfo> deviceList {};
2334 if (IsLocalDevice(networkId)) {
2335 deviceName = "LocalDevice";
2336 return AVSESSION_SUCCESS;
2337 }
2338 int32_t ret = GetTrustedDevicesInfo(deviceList);
2339 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "get devicesInfo failed");
2340 SLOGI("deviceList size is %{public}d", static_cast<int32_t>(deviceList.size()));
2341 for (const auto& device : deviceList) {
2342 SLOGI("device networkId is %{public}.6s", device.networkId);
2343 ret = strcmp(device.networkId, networkId.c_str());
2344 if (ret == 0) {
2345 deviceName = device.deviceName;
2346 SLOGI("deviceName is %{public}s", deviceName.c_str());
2347 return AVSESSION_SUCCESS;
2348 }
2349 }
2350 SLOGI("can not find this device %{public}.6s", networkId.c_str());
2351 return AVSESSION_ERROR;
2352 }
2353
GetTrustedDevicesInfo(std::vector<OHOS::DistributedHardware::DmDeviceInfo> & deviceList)2354 int32_t AVSessionService::GetTrustedDevicesInfo(std::vector<OHOS::DistributedHardware::DmDeviceInfo>& deviceList)
2355 {
2356 SLOGI("GetTrustedDevicesInfo");
2357 int32_t ret = DistributedHardware::DeviceManager::GetInstance().GetTrustedDeviceList("av_session", "", deviceList);
2358 CHECK_AND_RETURN_RET_LOG(ret == 0, ret, "get trusted device list failed");
2359 return AVSESSION_SUCCESS;
2360 }
2361
SetBasicInfo(std::string & sessionInfo)2362 int32_t AVSessionService::SetBasicInfo(std::string& sessionInfo)
2363 {
2364 AVSessionBasicInfo basicInfo;
2365 basicInfo.metaDataCap_ = AVMetaData::localCapability;
2366 basicInfo.playBackStateCap_ = AVPlaybackState::localCapability;
2367 basicInfo.controlCommandCap_ = AVControlCommand::localCapability;
2368 int32_t ret = GetLocalNetworkId(basicInfo.networkId_);
2369 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, AVSESSION_ERROR, "GetLocalNetworkId failed");
2370
2371 ret = JsonUtils::SetSessionBasicInfo(sessionInfo, basicInfo);
2372 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, AVSESSION_ERROR, "SetDeviceId failed");
2373 return AVSESSION_SUCCESS;
2374 }
2375
SetDeviceInfo(const std::vector<AudioStandard::AudioDeviceDescriptor> & castAudioDescriptors,sptr<AVSessionItem> & session)2376 void AVSessionService::SetDeviceInfo(const std::vector<AudioStandard::AudioDeviceDescriptor>& castAudioDescriptors,
2377 sptr <AVSessionItem>& session)
2378 {
2379 CHECK_AND_RETURN_LOG(session != nullptr && castAudioDescriptors.size() > 0, "invalid argument");
2380 SLOGI("castAudioDescriptors size is %{public}d", static_cast<int32_t>(castAudioDescriptors.size()));
2381 SLOGI("session id is %{public}s", AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str());
2382
2383 OutputDeviceInfo outputDeviceInfo;
2384 outputDeviceInfo.deviceInfos_.clear();
2385 int32_t castCategory = AVCastCategory::CATEGORY_LOCAL;
2386 if (!IsLocalDevice(castAudioDescriptors[0].networkId_)) {
2387 castCategory = AVCastCategory::CATEGORY_REMOTE;
2388 }
2389 for (const auto &audioDescriptor : castAudioDescriptors) {
2390 DeviceInfo deviceInfo;
2391 deviceInfo.castCategory_ = castCategory;
2392 deviceInfo.deviceId_ = std::to_string(audioDescriptor.deviceId_);
2393 deviceInfo.deviceName_ = audioDescriptor.deviceName_;
2394 SLOGI("deviceName is %{public}s", audioDescriptor.deviceName_.c_str());
2395 outputDeviceInfo.deviceInfos_.emplace_back(deviceInfo);
2396 }
2397 session->SetOutputDevice(outputDeviceInfo);
2398 }
2399
GetAudioDescriptorByDeviceId(const std::vector<sptr<AudioStandard::AudioDeviceDescriptor>> & descriptors,const std::string & deviceId,AudioStandard::AudioDeviceDescriptor & audioDescriptor)2400 bool AVSessionService::GetAudioDescriptorByDeviceId(const std::vector<sptr<AudioStandard::AudioDeviceDescriptor>>&
2401 descriptors, const std::string& deviceId,
2402 AudioStandard::AudioDeviceDescriptor& audioDescriptor)
2403 {
2404 for (const auto& descriptor : descriptors) {
2405 if (std::to_string(descriptor->deviceId_) == deviceId) {
2406 audioDescriptor = *descriptor;
2407 SLOGI("networkId is %{public}.6s", audioDescriptor.networkId_.c_str());
2408 return true;
2409 }
2410 }
2411 SLOGI("deviceId is %{public}s, not found in all audio descriptor", deviceId.c_str());
2412 return false;
2413 }
2414
GetDeviceInfo(const sptr<AVSessionItem> & session,const std::vector<AudioStandard::AudioDeviceDescriptor> & descriptors,std::vector<AudioStandard::AudioDeviceDescriptor> & castSinkDescriptors,std::vector<AudioStandard::AudioDeviceDescriptor> & cancelSinkDescriptors)2415 void AVSessionService::GetDeviceInfo(const sptr <AVSessionItem>& session,
2416 const std::vector<AudioStandard::AudioDeviceDescriptor>& descriptors,
2417 std::vector<AudioStandard::AudioDeviceDescriptor>& castSinkDescriptors,
2418 std::vector<AudioStandard::AudioDeviceDescriptor>& cancelSinkDescriptors)
2419 {
2420 if (descriptors.size() != 1) {
2421 SLOGI("descriptor size is %{public}d, not support", static_cast<int32_t>(descriptors.size()));
2422 return;
2423 }
2424 castSinkDescriptors.push_back(descriptors[0]);
2425 SLOGI("cast to networkId_ is %{public}.6s", descriptors[0].networkId_.c_str());
2426
2427 OutputDeviceInfo tempOutputDeviceInfo;
2428 session->GetOutputDevice(tempOutputDeviceInfo);
2429 // If not in remote, return directly
2430 if (tempOutputDeviceInfo.deviceInfos_.size() == 0 || tempOutputDeviceInfo.deviceInfos_[0].castCategory_ == 1) {
2431 SLOGI("castCategory is %{public}d, no need to cancel", tempOutputDeviceInfo.deviceInfos_[0].castCategory_);
2432 return;
2433 }
2434 int32_t ret = GetAudioDescriptor(session->GetDescriptor().outputDeviceInfo_.deviceInfos_[0].deviceId_,
2435 cancelSinkDescriptors);
2436 CHECK_AND_RETURN_LOG(ret == AVSESSION_SUCCESS, "get cancelSinkDescriptors failed");
2437 }
2438
SelectOutputDevice(const int32_t uid,const AudioDeviceDescriptor & descriptor)2439 int32_t AVSessionService::SelectOutputDevice(const int32_t uid, const AudioDeviceDescriptor& descriptor)
2440 {
2441 SLOGI("uid is %{public}d", uid);
2442 sptr <AudioStandard::AudioRendererFilter> audioFilter = new(std::nothrow) AudioRendererFilter();
2443 CHECK_AND_RETURN_RET_LOG(audioFilter != nullptr, ERR_NO_MEMORY, "new AudioRendererFilter failed");
2444 audioFilter->uid = uid;
2445 audioFilter->rendererInfo.contentType = ContentType::CONTENT_TYPE_MUSIC;
2446 audioFilter->rendererInfo.streamUsage = StreamUsage::STREAM_USAGE_MEDIA;
2447
2448 std::vector<sptr<AudioDeviceDescriptor>> audioDescriptor;
2449 auto audioDeviceDescriptor = new(std::nothrow) AudioDeviceDescriptor(descriptor);
2450 CHECK_AND_RETURN_RET_LOG(audioDeviceDescriptor != nullptr, ERR_NO_MEMORY, "audioDeviceDescriptor is nullptr");
2451 audioDescriptor.push_back(audioDeviceDescriptor);
2452 SLOGI("select the device %{public}s role is %{public}d, networkId is %{public}.6s",
2453 descriptor.deviceName_.c_str(), static_cast<int32_t>(descriptor.deviceRole_), descriptor.networkId_.c_str());
2454
2455 AudioSystemManager *audioSystemMgr = AudioSystemManager::GetInstance();
2456 CHECK_AND_RETURN_RET_LOG(audioSystemMgr != nullptr, AVSESSION_ERROR, "get AudioSystemManager instance failed");
2457 int32_t ret = audioSystemMgr->SelectOutputDevice(audioFilter, audioDescriptor);
2458 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, AVSESSION_ERROR, "SelectOutputDevice failed");
2459
2460 return AVSESSION_SUCCESS;
2461 }
2462
CastAudio(const SessionToken & token,const std::vector<AudioStandard::AudioDeviceDescriptor> & sinkAudioDescriptors)2463 int32_t AVSessionService::CastAudio(const SessionToken& token,
2464 const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkAudioDescriptors)
2465 {
2466 SLOGI("sessionId is %{public}s", AVSessionUtils::GetAnonySessionId(token.sessionId).c_str());
2467 std::string sourceSessionInfo;
2468 int32_t ret = SetBasicInfo(sourceSessionInfo);
2469 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetBasicInfo failed");
2470 sptr<AVSessionItem> session = GetContainer().GetSessionById(token.sessionId);
2471 CHECK_AND_RETURN_RET_LOG(session != nullptr, ERR_SESSION_NOT_EXIST, "session %{public}s not exist",
2472 AVSessionUtils::GetAnonySessionId(token.sessionId).c_str());
2473 ret = JsonUtils::SetSessionDescriptor(sourceSessionInfo, session->GetDescriptor());
2474 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetDescriptorInfo failed");
2475 ret = CastAudioProcess(sinkAudioDescriptors, sourceSessionInfo, session);
2476 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudioProcess failed");
2477 return AVSESSION_SUCCESS;
2478 }
2479
CastAudioProcess(const std::vector<AudioStandard::AudioDeviceDescriptor> & descriptors,const std::string & sourceSessionInfo,sptr<AVSessionItem> & session)2480 int32_t AVSessionService::CastAudioProcess(const std::vector<AudioStandard::AudioDeviceDescriptor>& descriptors,
2481 const std::string& sourceSessionInfo,
2482 sptr <AVSessionItem>& session)
2483 {
2484 SLOGI("start");
2485 std::vector<AudioDeviceDescriptor> castSinkDescriptors;
2486 std::vector<AudioDeviceDescriptor> cancelSinkDescriptors;
2487 GetDeviceInfo(session, descriptors, castSinkDescriptors, cancelSinkDescriptors);
2488
2489 if (cancelSinkDescriptors.size() > 0) {
2490 int32_t ret = CancelCastAudioInner(cancelSinkDescriptors, sourceSessionInfo, session);
2491 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CancelCastAudioInner failed");
2492 }
2493
2494 if (castSinkDescriptors.size() > 0) {
2495 int32_t ret = CastAudioInner(castSinkDescriptors, sourceSessionInfo, session);
2496 if (ret != AVSESSION_SUCCESS) {
2497 SLOGE("CastAudioInner failed, try cancel it. ret is %{public}d",
2498 CancelCastAudioInner(castSinkDescriptors, sourceSessionInfo, session));
2499 return ret;
2500 }
2501 }
2502
2503 SetDeviceInfo(descriptors, session);
2504 return AVSESSION_SUCCESS;
2505 }
2506
CastAudioInner(const std::vector<AudioStandard::AudioDeviceDescriptor> & sinkAudioDescriptors,const std::string & sourceSessionInfo,const sptr<AVSessionItem> & session)2507 int32_t AVSessionService::CastAudioInner(const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkAudioDescriptors,
2508 const std::string& sourceSessionInfo,
2509 const sptr <AVSessionItem>& session)
2510 {
2511 SLOGI("start");
2512 CHECK_AND_RETURN_RET_LOG(sinkAudioDescriptors.size() > 0, AVSESSION_ERROR, "sinkDescriptors is empty");
2513 std::string sourceDevice;
2514 CHECK_AND_RETURN_RET_LOG(GetLocalNetworkId(sourceDevice) == AVSESSION_SUCCESS, AVSESSION_ERROR,
2515 "GetLocalNetworkId failed");
2516 SLOGI("networkId_: %{public}.6s, role %{public}d", sinkAudioDescriptors[0].networkId_.c_str(),
2517 static_cast<int32_t>(sinkAudioDescriptors[0].deviceRole_));
2518 if (IsLocalDevice(sinkAudioDescriptors[0].networkId_)) {
2519 int32_t ret = SelectOutputDevice(session->GetUid(), sinkAudioDescriptors[0]);
2520 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "selectOutputDevice failed");
2521 return AVSESSION_SUCCESS;
2522 }
2523
2524 SLOGI("sinkAudioDescriptors size is %{public}d", static_cast<int32_t>(sinkAudioDescriptors.size()));
2525 for (const auto& sinkAudioDescriptor : sinkAudioDescriptors) {
2526 std::string sinkSessionInfo;
2527 auto service = GetService(sinkAudioDescriptor.networkId_);
2528 CHECK_AND_RETURN_RET_LOG(service != nullptr, AVSESSION_ERROR, "GetService %{public}s failed",
2529 sinkAudioDescriptor.networkId_.c_str());
2530 int32_t ret = service->ProcessCastAudioCommand(RemoteServiceCommand::COMMAND_CAST_AUDIO, sourceSessionInfo,
2531 sinkSessionInfo);
2532 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "ProcessCastAudioCommand failed");
2533 std::string sinkCapability;
2534 ret = JsonUtils::GetAllCapability(sinkSessionInfo, sinkCapability);
2535 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetAllCapability failed");
2536 ret = session->CastAudioToRemote(sourceDevice, sinkAudioDescriptor.networkId_, sinkCapability);
2537 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudioToRemote failed");
2538 HISYSEVENT_BEHAVIOR("SESSION_CAST",
2539 "BUNDLE_NAME", session->GetDescriptor().elementName_.GetBundleName(),
2540 "MODULE_NAME", session->GetDescriptor().elementName_.GetModuleName(),
2541 "ABILITY_NAME", session->GetDescriptor().elementName_.GetAbilityName(),
2542 "SESSION_PID", session->GetDescriptor().pid_,
2543 "SESSION_UID", session->GetDescriptor().uid_,
2544 "SESSION_ID", session->GetDescriptor().sessionId_,
2545 "SESSION_TAG", session->GetDescriptor().sessionTag_,
2546 "SESSION_TYPE", session->GetDescriptor().sessionType_,
2547 "CAST_TYPE", 0,
2548 "DEST_DEVICE_TYPE", sinkAudioDescriptor.deviceType_,
2549 "DEST_DEVICE_NAME", sinkAudioDescriptor.deviceName_.c_str(),
2550 "DEST_DEVICE_ID", sinkAudioDescriptor.deviceId_,
2551 "DETAILED_MSG", "avsession service cast audio");
2552 ret = SelectOutputDevice(session->GetUid(), sinkAudioDescriptor);
2553 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "selectOutputDevice failed");
2554 }
2555 SLOGI("success");
2556 return AVSESSION_SUCCESS;
2557 }
2558
CancelCastAudioInner(const std::vector<AudioStandard::AudioDeviceDescriptor> & sinkDevices,const std::string & sourceSessionInfo,const sptr<AVSessionItem> & session)2559 int32_t AVSessionService::CancelCastAudioInner(const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkDevices,
2560 const std::string& sourceSessionInfo,
2561 const sptr <AVSessionItem>& session)
2562 {
2563 SLOGI("cancel sinkDevices size is %{public}d", static_cast<int32_t>(sinkDevices.size()));
2564 CHECK_AND_RETURN_RET_LOG(!sinkDevices.empty(), AVSESSION_ERROR, "sinkDevices is empty");
2565 for (const auto& sinkDevice : sinkDevices) {
2566 if (IsLocalDevice(sinkDevice.networkId_)) {
2567 SLOGI("cancel Local device %{public}.6s", sinkDevice.networkId_.c_str());
2568 continue;
2569 }
2570 std::string sinkSessionInfo;
2571 SLOGI("cancel sinkDevices sinkDevice.networkId_ is %{public}.6s", sinkDevice.networkId_.c_str());
2572 auto service = GetService(sinkDevice.networkId_);
2573 CHECK_AND_RETURN_RET_LOG(service != nullptr, AVSESSION_ERROR, "GetService %{public}s failed",
2574 sinkDevice.networkId_.c_str());
2575 int32_t ret = service->ProcessCastAudioCommand(RemoteServiceCommand::COMMAND_CANCEL_CAST_AUDIO,
2576 sourceSessionInfo, sinkSessionInfo);
2577 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "ProcessCastAudioCommand failed");
2578 ret = session->SourceCancelCastAudio(sinkDevice.networkId_);
2579 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SourceCancelCastAudio failed");
2580 }
2581 return AVSESSION_SUCCESS;
2582 }
2583
CastAudioForNewSession(const sptr<AVSessionItem> & session)2584 int32_t AVSessionService::CastAudioForNewSession(const sptr<AVSessionItem>& session)
2585 {
2586 SLOGI("new sessionId is %{public}s", AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str());
2587 SessionToken token;
2588 token.sessionId = session->GetSessionId();
2589 token.pid = session->GetPid();
2590 token.uid = session->GetUid();
2591
2592 int32_t ret = AVSESSION_SUCCESS;
2593 std::vector<AudioStandard::AudioDeviceDescriptor> castSinkDevices;
2594 {
2595 std::lock_guard lockGuard(outputDeviceIdLock_);
2596 ret = GetAudioDescriptor(outputDeviceId_, castSinkDevices);
2597 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetAudioDescriptor failed");
2598 }
2599
2600 ret = CastAudio(token, castSinkDevices);
2601 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudio error, session Id is %{public}s",
2602 AVSessionUtils::GetAnonySessionId(token.sessionId).c_str());
2603
2604 SLOGI("success");
2605 return AVSESSION_SUCCESS;
2606 }
2607
CastAudioForAll(const std::vector<AudioStandard::AudioDeviceDescriptor> & sinkAudioDescriptors)2608 int32_t AVSessionService::CastAudioForAll(const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkAudioDescriptors)
2609 {
2610 CHECK_AND_RETURN_RET_LOG(sinkAudioDescriptors.size() > 0, ERR_INVALID_PARAM, "sinkAudioDescriptors is empty");
2611 {
2612 std::lock_guard lockGuard(isAllSessionCastLock_);
2613 isAllSessionCast_ = false;
2614 if (!IsLocalDevice(sinkAudioDescriptors[0].networkId_)) {
2615 isAllSessionCast_ = true;
2616 }
2617 }
2618 for (const auto& session : GetContainer().GetAllSessions()) {
2619 SessionToken token;
2620 token.sessionId = session->GetSessionId();
2621 token.pid = session->GetPid();
2622 token.uid = session->GetUid();
2623 SLOGI("cast session %{public}s", AVSessionUtils::GetAnonySessionId(token.sessionId).c_str());
2624 int32_t ret = CastAudio(token, sinkAudioDescriptors);
2625 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudio session %{public}s failed",
2626 AVSessionUtils::GetAnonySessionId(token.sessionId).c_str());
2627 {
2628 std::lock_guard lockGuard(outputDeviceIdLock_);
2629 outputDeviceId_ = session->GetDescriptor().outputDeviceInfo_.deviceInfos_[0].deviceId_;
2630 }
2631 }
2632
2633 SLOGI("isAllSessionCast_ %{public}d, outputDeviceId_ is %{public}s", isAllSessionCast_, outputDeviceId_.c_str());
2634 return AVSESSION_SUCCESS;
2635 }
2636
ProcessCastAudioCommand(const RemoteServiceCommand command,const std::string & input,std::string & output)2637 int32_t AVSessionService::ProcessCastAudioCommand(const RemoteServiceCommand command, const std::string& input,
2638 std::string& output)
2639 {
2640 SLOGI("ProcessCastAudioCommand is %{public}d", static_cast<int32_t>(command));
2641 CHECK_AND_RETURN_RET_LOG(command > COMMAND_INVALID && command < COMMAND_MAX, AVSESSION_ERROR, "invalid command");
2642 if (command == COMMAND_CAST_AUDIO) {
2643 int ret = RemoteCastAudioInner(input, output);
2644 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "RemoteCastAudioInner error");
2645 return AVSESSION_SUCCESS;
2646 }
2647
2648 int ret = RemoteCancelCastAudioInner(input);
2649 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "RemoteCancelCastAudioInner error");
2650 SLOGI("success");
2651 return AVSESSION_SUCCESS;
2652 }
2653
RemoteCastAudioInner(const std::string & sourceSessionInfo,std::string & sinkSessionInfo)2654 int32_t AVSessionService::RemoteCastAudioInner(const std::string& sourceSessionInfo, std::string& sinkSessionInfo)
2655 {
2656 SLOGI("sourceInfo : %{public}s", sourceSessionInfo.c_str());
2657 AVSessionDescriptor sourceDescriptor;
2658 int32_t ret = JsonUtils::GetSessionDescriptor(sourceSessionInfo, sourceDescriptor);
2659 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetSessionDescriptor failed");
2660
2661 ret = SetBasicInfo(sinkSessionInfo);
2662 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, AVSESSION_ERROR, "SetBasicInfo failed");
2663 AVSessionBasicInfo sinkDeviceInfo;
2664 ret = JsonUtils::GetSessionBasicInfo(sinkSessionInfo, sinkDeviceInfo);
2665 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetBasicInfo failed");
2666
2667 sptr <AVSessionItem> session = CreateSessionInner(sourceDescriptor.sessionTag_, sourceDescriptor.sessionType_,
2668 sourceDescriptor.isThirdPartyApp_,
2669 sourceDescriptor.elementName_);
2670 SLOGI("source sessionId_ %{public}s", AVSessionUtils::GetAnonySessionId(sourceDescriptor.sessionId_).c_str());
2671 CHECK_AND_RETURN_RET_LOG(session != nullptr, AVSESSION_ERROR, "CreateSession failed");
2672 SLOGI("sink deviceId %{public}s", AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str());
2673
2674 {
2675 std::lock_guard lockGuard(castAudioSessionMapLock_);
2676 castAudioSessionMap_[sourceDescriptor.sessionId_] = session->GetSessionId();
2677 }
2678
2679 AVSessionBasicInfo sourceDeviceInfo;
2680 ret = JsonUtils::GetSessionBasicInfo(sourceSessionInfo, sourceDeviceInfo);
2681 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetBasicInfo failed");
2682 std::string sourceCapability;
2683 ret = JsonUtils::GetAllCapability(sourceSessionInfo, sourceCapability);
2684 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetAllCapability failed");
2685 ret = session->CastAudioFromRemote(sourceDescriptor.sessionId_, sourceDeviceInfo.networkId_,
2686 sinkDeviceInfo.networkId_, sourceCapability);
2687 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudioFromRemote failed");
2688 SLOGI("CastAudioFromRemote success");
2689 JsonUtils::SetSessionDescriptor(sinkSessionInfo, session->GetDescriptor());
2690 SLOGI("sinkSessionInfo : %{public}s", sinkSessionInfo.c_str());
2691 return AVSESSION_SUCCESS;
2692 }
2693
RemoteCancelCastAudioInner(const std::string & sessionInfo)2694 int32_t AVSessionService::RemoteCancelCastAudioInner(const std::string& sessionInfo)
2695 {
2696 SLOGI("sessionInfo is %{public}s", sessionInfo.c_str());
2697 AVSessionBasicInfo sourceDeviceInfo;
2698 int32_t ret = JsonUtils::GetSessionBasicInfo(sessionInfo, sourceDeviceInfo);
2699 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetBasicInfo failed");
2700 AVSessionDescriptor sourceDescriptor;
2701 ret = JsonUtils::GetSessionDescriptor(sessionInfo, sourceDescriptor);
2702 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetSessionDescriptor failed");
2703
2704 std::lock_guard lockGuard(castAudioSessionMapLock_);
2705 auto iter = castAudioSessionMap_.find(sourceDescriptor.sessionId_);
2706 CHECK_AND_RETURN_RET_LOG(iter != castAudioSessionMap_.end(), AVSESSION_ERROR, "no source session %{public}s",
2707 AVSessionUtils::GetAnonySessionId(sourceDescriptor.sessionId_).c_str());
2708 auto session = GetContainer().GetSessionById(iter->second);
2709 CHECK_AND_RETURN_RET_LOG(session != nullptr, AVSESSION_ERROR, "no sink session %{public}s",
2710 AVSessionUtils::GetAnonySessionId(iter->second).c_str());
2711
2712 ret = session->SinkCancelCastAudio();
2713 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SinkCancelCastAudio failed");
2714 HandleSessionRelease(session->GetSessionId());
2715 castAudioSessionMap_.erase(sourceDescriptor.sessionId_);
2716 SLOGI("cancel source session %{public}s success",
2717 AVSessionUtils::GetAnonySessionId(sourceDescriptor.sessionId_).c_str());
2718 return AVSESSION_SUCCESS;
2719 }
2720
CancelCastAudioForClientExit(pid_t pid,const sptr<AVSessionItem> & session)2721 int32_t AVSessionService::CancelCastAudioForClientExit(pid_t pid, const sptr<AVSessionItem>& session)
2722 {
2723 CHECK_AND_RETURN_RET_LOG(session != nullptr, AVSESSION_ERROR, "session is nullptr");
2724 SLOGI("pid is %{public}d, sessionId is %{public}s", static_cast<int32_t>(pid),
2725 AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str());
2726 std::string sourceSessionInfo;
2727 int32_t ret = SetBasicInfo(sourceSessionInfo);
2728 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetBasicInfo failed");
2729 ret = JsonUtils::SetSessionDescriptor(sourceSessionInfo, session->GetDescriptor());
2730 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetDescriptorInfo failed");
2731
2732 std::vector<AudioStandard::AudioDeviceDescriptor> cancelSinkDevices;
2733 ret = GetAudioDescriptor(session->GetDescriptor().outputDeviceInfo_.deviceInfos_[0].deviceId_, cancelSinkDevices);
2734 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetAudioDescriptor failed");
2735
2736 ret = CancelCastAudioInner(cancelSinkDevices, sourceSessionInfo, session);
2737 CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CancelCastAudioInner failed");
2738 return AVSESSION_SUCCESS;
2739 }
2740
GetAudioDescriptor(const std::string deviceId,std::vector<AudioStandard::AudioDeviceDescriptor> & audioDeviceDescriptors)2741 int32_t AVSessionService::GetAudioDescriptor(const std::string deviceId,
2742 std::vector<AudioStandard::AudioDeviceDescriptor>& audioDeviceDescriptors)
2743 {
2744 auto audioDescriptors = AudioSystemManager::GetInstance()->GetDevices(ALL_L_D_DEVICES_FLAG);
2745 AudioDeviceDescriptor audioDescriptor;
2746 if (GetAudioDescriptorByDeviceId(audioDescriptors, deviceId, audioDescriptor)) {
2747 audioDeviceDescriptors.push_back(audioDescriptor);
2748 SLOGI("get audio networkId_ is %{public}.6s", audioDescriptor.networkId_.c_str());
2749 return AVSESSION_SUCCESS;
2750 }
2751 SLOGI("can not get deviceId %{public}s info", deviceId.c_str());
2752 return AVSESSION_ERROR;
2753 }
2754
ClearSessionForClientDiedNoLock(pid_t pid,bool continuePlay)2755 void AVSessionService::ClearSessionForClientDiedNoLock(pid_t pid, bool continuePlay)
2756 {
2757 SLOGI("clear session in ");
2758 auto sessions = GetUsersManager().GetContainerFromAll().GetSessionsByPid(pid);
2759 for (const auto& session : sessions) {
2760 SLOGI("check session release task for id %{public}s",
2761 AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str());
2762 HandleSessionRelease(session->GetSessionId(), continuePlay);
2763 }
2764 }
2765
ClearControllerForClientDiedNoLock(pid_t pid)2766 void AVSessionService::ClearControllerForClientDiedNoLock(pid_t pid)
2767 {
2768 auto it = controllers_.find(pid);
2769 CHECK_AND_RETURN_LOG(it != controllers_.end(), "no find controller");
2770 auto controllers = std::move(it->second);
2771 SLOGI("remove controllers size=%{public}d without reply", static_cast<int>(controllers.size()));
2772 if (!controllers.empty()) {
2773 for (const auto& controller : controllers) {
2774 controller->DestroyWithoutReply();
2775 }
2776 }
2777 it = controllers_.find(pid);
2778 CHECK_AND_RETURN_LOG(it != controllers_.end(), "no find controller");
2779 controllers_.erase(pid);
2780 }
2781
ClientDeathRecipient(const std::function<void ()> & callback)2782 ClientDeathRecipient::ClientDeathRecipient(const std::function<void()>& callback)
2783 : callback_(callback)
2784 {
2785 SLOGD("construct");
2786 }
2787
OnRemoteDied(const wptr<IRemoteObject> & object)2788 void ClientDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& object)
2789 {
2790 if (callback_) {
2791 callback_();
2792 }
2793 }
2794
CheckUserDirValid(int32_t userId)2795 bool AVSessionService::CheckUserDirValid(int32_t userId)
2796 {
2797 std::string filePath = GetUsersManager().GetDirForCurrentUser(userId);
2798 filesystem::path directory(filePath);
2799 std::error_code errCode;
2800 if (!filesystem::exists(directory, errCode)) {
2801 SLOGE("check user dir not exsit %{public}s for user %{public}d, errCode %{public}d",
2802 filePath.c_str(), userId, static_cast<int>(errCode.value()));
2803 return false;
2804 }
2805 return true;
2806 }
2807
CheckAndCreateDir(const string & filePath)2808 bool AVSessionService::CheckAndCreateDir(const string& filePath)
2809 {
2810 std::lock_guard lockGuard(fileCheckLock_);
2811 CHECK_AND_RETURN_RET_LOG(CheckUserDirValid(), false, "check userDir err!");
2812 filesystem::path directory = filesystem::path(filePath).parent_path();
2813 if (!filesystem::exists(directory)) {
2814 SLOGI("check file not exist and try create %{public}s", filePath.c_str());
2815 CHECK_AND_RETURN_RET_LOG(filesystem::create_directories(directory),
2816 false, "Failed to create directory");
2817 }
2818 return true;
2819 }
2820
LoadStringFromFileEx(const string & filePath,string & content)2821 bool AVSessionService::LoadStringFromFileEx(const string& filePath, string& content)
2822 {
2823 std::lock_guard lockGuard(fileCheckLock_);
2824 SLOGD("file load in for path: %{public}s", filePath.c_str());
2825 CheckAndCreateDir(filePath);
2826 ifstream file(filePath.c_str());
2827 if (!file.is_open()) {
2828 SLOGD("file not open! try open first ! ");
2829 file.open(filePath.c_str(), ios::out | ios::app);
2830 if (!file.is_open()) {
2831 SLOGE("open file again fail !");
2832 return false;
2833 }
2834 }
2835 file.seekg(0, ios::end);
2836 const long fileLength = file.tellg();
2837 SLOGD("get file length(%{public}ld)!", fileLength);
2838 if (fileLength > maxFileLength) {
2839 SLOGE("invalid file length(%{public}ld)!", fileLength);
2840 return false;
2841 }
2842 if (fileLength <= 0) {
2843 SLOGD("file new create empty ! try set init json ");
2844 ofstream fileWrite;
2845 fileWrite.open(filePath.c_str(), ios::out | ios::trunc);
2846 if (!fileWrite.is_open()) {
2847 SLOGE("open file in create new failed!");
2848 file.close();
2849 return false;
2850 }
2851 nlohmann::json emptyValue;
2852 std::string emptyContent = emptyValue.dump();
2853 SLOGD("LoadStringFromFileEx::Dump json object finished");
2854 fileWrite.write(emptyContent.c_str(), emptyContent.length());
2855 if (fileWrite.fail()) {
2856 SLOGE("file empty init json fail !");
2857 file.close();
2858 fileWrite.close();
2859 return false;
2860 }
2861 fileWrite.close();
2862 }
2863 content.clear();
2864 file.seekg(0, ios::beg);
2865 copy(istreambuf_iterator<char>(file), istreambuf_iterator<char>(), back_inserter(content));
2866 file.close();
2867 return CheckStringAndCleanFile(filePath);
2868 }
2869
SaveStringToFileEx(const std::string & filePath,const std::string & content)2870 bool AVSessionService::SaveStringToFileEx(const std::string& filePath, const std::string& content)
2871 {
2872 std::lock_guard lockGuard(fileCheckLock_);
2873 SLOGI("file save in for path:%{public}s, content:%{public}s", filePath.c_str(), content.c_str());
2874 nlohmann::json checkValues = json::parse(content, nullptr, false);
2875 CHECK_AND_RETURN_RET_LOG(!checkValues.is_discarded(), false, "recv content discarded");
2876 ofstream file;
2877 file.open(filePath.c_str(), ios::out | ios::trunc);
2878 if (!file.is_open()) {
2879 SLOGE("open file in save failed!");
2880 return false;
2881 }
2882 if (content.empty()) {
2883 SLOGE("write content is empty, no need to do write!");
2884 file.close();
2885 return true;
2886 }
2887 file.write(content.c_str(), content.length());
2888 if (file.fail()) {
2889 SLOGE("write content to file failed!");
2890 file.close();
2891 return false;
2892 }
2893 file.close();
2894 return CheckStringAndCleanFile(filePath);
2895 }
2896
CheckStringAndCleanFile(const std::string & filePath)2897 bool AVSessionService::CheckStringAndCleanFile(const std::string& filePath)
2898 {
2899 SLOGD("file check for path:%{public}s", filePath.c_str());
2900 string content {};
2901 ifstream fileRead(filePath.c_str());
2902 if (!fileRead.is_open()) {
2903 SLOGD("file not open! try open first ! ");
2904 fileRead.open(filePath.c_str(), ios::app);
2905 if (!fileRead.is_open()) {
2906 SLOGE("open file again fail !");
2907 return false;
2908 }
2909 }
2910 content.clear();
2911 fileRead.seekg(0, ios::beg);
2912 copy(istreambuf_iterator<char>(fileRead), istreambuf_iterator<char>(), back_inserter(content));
2913 SLOGD("check content pre clean it: %{public}s", content.c_str());
2914 nlohmann::json checkValues = json::parse(content, nullptr, false);
2915 if (checkValues.is_discarded()) {
2916 SLOGE("check content discarded! content %{public}s", content.c_str());
2917 ofstream fileWrite;
2918 fileWrite.open(filePath.c_str(), ios::out | ios::trunc);
2919 if (!fileWrite.is_open()) {
2920 SLOGE("open file in create new failed!");
2921 fileRead.close();
2922 return false;
2923 }
2924 nlohmann::json emptyValue;
2925 std::string emptyContent = emptyValue.dump();
2926 SLOGD("LoadStringFromFileEx::Dump json object finished");
2927 fileWrite.write(emptyContent.c_str(), emptyContent.length());
2928 if (fileWrite.fail()) {
2929 SLOGE("file empty init json fail! content %{public}s", content.c_str());
2930 fileRead.close();
2931 fileWrite.close();
2932 return false;
2933 }
2934 fileWrite.close();
2935 }
2936 fileRead.close();
2937 return true;
2938 }
2939
CreateWantAgent(const AVSessionDescriptor * histroyDescriptor)2940 std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> AVSessionService::CreateWantAgent(
2941 const AVSessionDescriptor* histroyDescriptor)
2942 {
2943 if (histroyDescriptor == nullptr && topSession_ == nullptr) {
2944 SLOGE("CreateWantAgent error, histroyDescriptor and topSession_ null");
2945 return nullptr;
2946 }
2947 std::vector<AbilityRuntime::WantAgent::WantAgentConstant::Flags> flags;
2948 flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG);
2949 std::vector<std::shared_ptr<AAFwk::Want>> wants;
2950 std::shared_ptr<AAFwk::Want> want = std::make_shared<AAFwk::Want>();
2951 std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> launWantAgent;
2952 string bundleName = DEFAULT_BUNDLE_NAME;
2953 string abilityName = DEFAULT_ABILITY_NAME;
2954 auto uid = -1;
2955 auto isCustomer = false;
2956 if (topSession_ != nullptr) {
2957 bundleName = topSession_->GetBundleName();
2958 abilityName = topSession_->GetAbilityName();
2959 uid = topSession_->GetUid();
2960 launWantAgent = std::make_shared<AbilityRuntime::WantAgent::WantAgent>(topSession_->GetLaunchAbility());
2961 auto res = AbilityRuntime::WantAgent::WantAgentHelper::GetWant(launWantAgent, want);
2962 isCustomer = (res == AVSESSION_SUCCESS) && (bundleName == want->GetElement().GetBundleName());
2963 SLOGI("CreateWantAgent GetWant res=%{public}d", res);
2964 }
2965 if (histroyDescriptor != nullptr) {
2966 SLOGI("CreateWantAgent with histroyDescriptor");
2967 bundleName = histroyDescriptor->elementName_.GetBundleName();
2968 abilityName = histroyDescriptor->elementName_.GetAbilityName();
2969 uid = histroyDescriptor->uid_;
2970 isCustomer = false;
2971 }
2972 SLOGI("CreateWantAgent bundleName %{public}s, abilityName %{public}s, isCustomer %{public}d",
2973 bundleName.c_str(), abilityName.c_str(), isCustomer);
2974 if (!isCustomer) {
2975 AppExecFwk::ElementName element("", bundleName, abilityName);
2976 want->SetElement(element);
2977 }
2978 wants.push_back(want);
2979 AbilityRuntime::WantAgent::WantAgentInfo wantAgentInfo(
2980 0,
2981 AbilityRuntime::WantAgent::WantAgentConstant::OperationType::START_ABILITY,
2982 flags,
2983 wants,
2984 nullptr
2985 );
2986 return AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, uid);
2987 }
2988
RemoveExpired(std::list<std::chrono::system_clock::time_point> & list,const std::chrono::system_clock::time_point & now,int32_t time)2989 void AVSessionService::RemoveExpired(std::list<std::chrono::system_clock::time_point> &list,
2990 const std::chrono::system_clock::time_point &now, int32_t time)
2991 {
2992 auto iter = list.begin();
2993 while (iter != list.end()) {
2994 auto duration = now - static_cast<std::chrono::system_clock::time_point>(*iter);
2995 int32_t durationInSeconds = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
2996 if (std::abs(durationInSeconds) > time) {
2997 iter = list.erase(iter);
2998 } else {
2999 break;
3000 }
3001 }
3002 }
3003
3004 // LCOV_EXCL_START
NotifySystemUI(const AVSessionDescriptor * historyDescriptor,bool isActiveSession)3005 void AVSessionService::NotifySystemUI(const AVSessionDescriptor* historyDescriptor, bool isActiveSession)
3006 {
3007 is2in1_ = system::GetBoolParameter("const.audio.volume_apply_to_all", false);
3008 SLOGI("NotifySystemUI, Prop=%{public}d", static_cast<int>(is2in1_));
3009 CHECK_AND_RETURN_LOG(!is2in1_, "2in1 not support");
3010 // flow control
3011 std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
3012 RemoveExpired(flowControlPublishTimestampList_, now);
3013 if (flowControlPublishTimestampList_.size() >= MAX_NOTIFICATION_NUM) {
3014 SLOGE("PublishNotification Exceed MAX_NOTIFICATION_NUM");
3015 return;
3016 }
3017 flowControlPublishTimestampList_.push_back(now);
3018 int32_t result = Notification::NotificationHelper::SubscribeLocalLiveViewNotification(NOTIFICATION_SUBSCRIBER);
3019 CHECK_AND_RETURN_LOG(result == ERR_OK, "create notification subscriber error %{public}d", result);
3020
3021 Notification::NotificationRequest request;
3022 std::shared_ptr<Notification::NotificationLocalLiveViewContent> localLiveViewContent =
3023 std::make_shared<Notification::NotificationLocalLiveViewContent>();
3024 CHECK_AND_RETURN_LOG(localLiveViewContent != nullptr, "avsession item local live view content nullptr error");
3025 localLiveViewContent->SetType(SYSTEMUI_LIVEVIEW_TYPECODE_MDEDIACONTROLLER);
3026 localLiveViewContent->SetTitle(historyDescriptor && !isActiveSession ? "" : "AVSession NotifySystemUI");
3027 localLiveViewContent->SetText(historyDescriptor && !isActiveSession ? "" : "AVSession NotifySystemUI");
3028
3029 std::shared_ptr<Notification::NotificationContent> content =
3030 std::make_shared<Notification::NotificationContent>(localLiveViewContent);
3031 CHECK_AND_RETURN_LOG(content != nullptr, "avsession item notification content nullptr error");
3032 int32_t userId = GetUsersManager().GetCurrentUserId();
3033
3034 auto uid = topSession_ ? topSession_->GetUid() : (historyDescriptor ? historyDescriptor->uid_ : -1);
3035 request.SetSlotType(Notification::NotificationConstant::SlotType::LIVE_VIEW);
3036 request.SetNotificationId(0);
3037 request.SetContent(content);
3038 request.SetCreatorUid(avSessionUid);
3039 request.SetUnremovable(true);
3040 request.SetInProgress(true);
3041 auto res = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
3042 request.SetCreatorUserId((res == 0) ? userId : 0);
3043 std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> wantAgent = CreateWantAgent(historyDescriptor);
3044 CHECK_AND_RETURN_LOG(wantAgent != nullptr, "wantAgent nullptr error");
3045 request.SetWantAgent(wantAgent);
3046 request.SetLabel(std::to_string(userId));
3047 result = Notification::NotificationHelper::PublishNotification(request);
3048 SLOGI("PublishNotification uid %{public}d, user id %{public}d, result %{public}d", uid, userId, result);
3049 }
3050 // LCOV_EXCL_STOP
3051
3052 // LCOV_EXCL_START
NotifyDeviceChange(const DeviceChangeAction & deviceChangeAction)3053 void AVSessionService::NotifyDeviceChange(const DeviceChangeAction& deviceChangeAction)
3054 {
3055 // historical sessions
3056 std::vector<AVSessionDescriptor> hisDescriptors;
3057 GetHistoricalSessionDescriptors(1, hisDescriptors);
3058 // all sessions
3059 std::vector<AVSessionDescriptor> activeDescriptors;
3060 GetAllSessionDescriptors(activeDescriptors);
3061 // historical avqueueinfos
3062 std::vector<AVQueueInfo> avQueueInfos;
3063 GetHistoricalAVQueueInfos(1, 1, avQueueInfos);
3064 AVSessionDescriptor selectSession;
3065 if (activeDescriptors.size() != 0 || hisDescriptors.size() == 0 || avQueueInfos.size() == 0) {
3066 return;
3067 }
3068 for (AVSessionDescriptor session : hisDescriptors) {
3069 if (session.elementName_.GetBundleName() == avQueueInfos[0].GetBundleName()) {
3070 selectSession = session;
3071 break;
3072 }
3073 }
3074 if (deviceChangeAction.type == AudioStandard::CONNECT && avQueueInfos.size() >= MININUM_FOR_NOTIFICATION) {
3075 SLOGI("history bundle name %{public}s", selectSession.elementName_.GetBundleName().c_str());
3076 NotifySystemUI(&selectSession, false);
3077 }
3078 }
3079 // LCOV_EXCL_STOP
3080
3081 // LCOV_EXCL_START
HandleDeviceChange(const DeviceChangeAction & deviceChangeAction)3082 void AVSessionService::HandleDeviceChange(const DeviceChangeAction& deviceChangeAction)
3083 {
3084 for (auto &audioDeviceDescriptor : deviceChangeAction.deviceDescriptors) {
3085 if (audioDeviceDescriptor->deviceType_ == AudioStandard::DEVICE_TYPE_WIRED_HEADSET ||
3086 audioDeviceDescriptor->deviceType_ == AudioStandard::DEVICE_TYPE_WIRED_HEADPHONES ||
3087 audioDeviceDescriptor->deviceType_ == AudioStandard::DEVICE_TYPE_USB_HEADSET ||
3088 audioDeviceDescriptor->deviceType_ == AudioStandard::DEVICE_TYPE_BLUETOOTH_A2DP) {
3089 SLOGI("AVSessionService handle pre notify device type %{public}d", audioDeviceDescriptor->deviceType_);
3090 NotifyDeviceChange(deviceChangeAction);
3091 }
3092 }
3093 }
3094 // LCOV_EXCL_STOP
3095
InitRadarBMS()3096 void AVSessionService::InitRadarBMS()
3097 {
3098 SLOGI("InitRadarBMS");
3099 AVSessionRadar::GetInstance().InitBMS();
3100 }
3101
ReportStartCastBegin(std::string func,const OutputDeviceInfo & outputDeviceInfo,int32_t uid)3102 void AVSessionService::ReportStartCastBegin(std::string func, const OutputDeviceInfo& outputDeviceInfo, int32_t uid)
3103 {
3104 AVSessionRadarInfo info(func);
3105 info.bundleName_ = BundleStatusAdapter::GetInstance().GetBundleNameFromUid(uid);
3106 AVSessionRadar::GetInstance().StartCastBegin(outputDeviceInfo, info);
3107 }
3108
ReportStartCastEnd(std::string func,const OutputDeviceInfo & outputDeviceInfo,int32_t uid,int ret)3109 void AVSessionService::ReportStartCastEnd(std::string func, const OutputDeviceInfo& outputDeviceInfo,
3110 int32_t uid, int ret)
3111 {
3112 AVSessionRadarInfo info(func);
3113 info.bundleName_ = BundleStatusAdapter::GetInstance().GetBundleNameFromUid(uid);
3114 if (ret == AVSESSION_SUCCESS) {
3115 AVSessionRadar::GetInstance().StartCastEnd(outputDeviceInfo, info);
3116 } else {
3117 info.errorCode_ = AVSessionRadar::GetRadarErrorCode(ret);
3118 AVSessionRadar::GetInstance().FailToStartCast(outputDeviceInfo, info);
3119 }
3120 }
3121 } // namespace OHOS::AVSession
3122