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