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