• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2025 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 #include <filesystem>
24 #include <openssl/crypto.h>
25 
26 #include "accesstoken_kit.h"
27 #include "account_manager_adapter.h"
28 #include "app_manager_adapter.h"
29 #include "audio_adapter.h"
30 #include "audio_system_manager.h"
31 #include "avsession_dynamic_loader.h"
32 #include "avsession_errors.h"
33 #include "avsession_log.h"
34 #include "avsession_info.h"
35 #include "device_manager.h"
36 #include "remote_session_capability_set.h"
37 #include "remote_session_source_proxy.h"
38 #include "remote_session_sink_proxy.h"
39 #include "file_ex.h"
40 #include "iservice_registry.h"
41 #include "key_event_adapter.h"
42 #include "cJSON.h"
43 #include "permission_checker.h"
44 #include "system_ability_definition.h"
45 #include "session_stack.h"
46 #include "avsession_trace.h"
47 #include "hash_calculator.h"
48 #include "avsession_dumper.h"
49 #include "command_send_limit.h"
50 #include "avsession_sysevent.h"
51 #include "json_utils.h"
52 #include "avsession_utils.h"
53 #include "avcontrol_command.h"
54 #include "avsession_event_handler.h"
55 #include "bundle_status_adapter.h"
56 #include "params_config_operator.h"
57 #include "notification_content.h"
58 #include "notification_helper.h"
59 #include "notification_request.h"
60 #include "notification_constant.h"
61 #include "ability_connect_helper.h"
62 #include "if_system_ability_manager.h"
63 #include "parameter.h"
64 #include "parameters.h"
65 #include "avsession_service.h"
66 #include "want_agent_helper.h"
67 #include "avsession_radar.h"
68 #include "int_wrapper.h"
69 #include "array_wrapper.h"
70 #include "bool_wrapper.h"
71 #include "image_source.h"
72 #include "avsession_pixel_map_adapter.h"
73 #include "avsession_dynamic_insight.h"
74 #include "softbus/softbus_session_utils.h"
75 
76 typedef void (*MigrateStubFunc)(std::function<void(std::string, std::string, std::string, std::string)>);
77 typedef void (*StopMigrateStubFunc)(void);
78 
79 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
80 #include "av_router.h"
81 #include "collaboration_manager.h"
82 #endif
83 
84 #if !defined(WINDOWS_PLATFORM) and !defined(MAC_PLATFORM) and !defined(IOS_PLATFORM)
85 #include <malloc.h>
86 #endif
87 
88 using namespace std;
89 using namespace OHOS::AudioStandard;
90 
91 namespace OHOS::AVSession {
92 
93 static const std::string AVSESSION_DYNAMIC_INSIGHT_LIBRARY_PATH = std::string("libavsession_dynamic_insight.z.so");
94 
95 static const int32_t CAST_ENGINE_SA_ID = 65546;
96 static const int32_t COLLABORATION_SA_ID = 70633;
97 static const int32_t AVSESSION_CONTINUE = 1;
98 #ifndef START_STOP_ON_DEMAND_ENABLE
99 const std::string BOOTEVENT_AVSESSION_SERVICE_READY = "bootevent.avsessionservice.ready";
100 #endif
101 #ifdef ENABLE_AVSESSION_SYSEVENT_CONTROL
102 static const int32_t CONTROL_COLD_START = 2;
103 #endif
104 
105 const std::map<int, int32_t> keyCodeToCommandMap_ = {
106     {MMI::KeyEvent::KEYCODE_MEDIA_PLAY_PAUSE, AVControlCommand::SESSION_CMD_PLAY},
107     {MMI::KeyEvent::KEYCODE_MEDIA_PLAY, AVControlCommand::SESSION_CMD_PLAY},
108     {MMI::KeyEvent::KEYCODE_MEDIA_PAUSE, AVControlCommand::SESSION_CMD_PAUSE},
109     {MMI::KeyEvent::KEYCODE_MEDIA_STOP, AVControlCommand::SESSION_CMD_STOP},
110     {MMI::KeyEvent::KEYCODE_MEDIA_NEXT, AVControlCommand::SESSION_CMD_PLAY_NEXT},
111     {MMI::KeyEvent::KEYCODE_MEDIA_PREVIOUS, AVControlCommand::SESSION_CMD_PLAY_PREVIOUS},
112     {MMI::KeyEvent::KEYCODE_MEDIA_REWIND, AVControlCommand::SESSION_CMD_REWIND},
113     {MMI::KeyEvent::KEYCODE_MEDIA_FAST_FORWARD, AVControlCommand::SESSION_CMD_FAST_FORWARD},
114 };
115 
116 const std::map<int32_t, int32_t> cmdToOffsetMap_ = {
117     {AVControlCommand::SESSION_CMD_SET_TARGET_LOOP_MODE, 9},
118     {AVControlCommand::SESSION_CMD_PLAY, 8},
119     {AVControlCommand::SESSION_CMD_PAUSE, 7},
120     {AVControlCommand::SESSION_CMD_PLAY_NEXT, 6},
121     {AVControlCommand::SESSION_CMD_PLAY_PREVIOUS, 5},
122     {AVControlCommand::SESSION_CMD_FAST_FORWARD, 4},
123     {AVControlCommand::SESSION_CMD_REWIND, 3},
124     {AVControlCommand::SESSION_CMD_SEEK, 2},
125     {AVControlCommand::SESSION_CMD_SET_LOOP_MODE, 1},
126     {AVControlCommand::SESSION_CMD_TOGGLE_FAVORITE, 0}
127 };
128 
129 class NotificationSubscriber : public Notification::NotificationLocalLiveViewSubscriber {
OnConnected()130     void OnConnected() {}
OnDisconnected()131     void OnDisconnected() {}
OnResponse(int32_t notificationId,sptr<Notification::NotificationButtonOption> buttonOption)132     void OnResponse(int32_t notificationId, sptr<Notification::NotificationButtonOption> buttonOption) {}
OnDied()133     void OnDied() {}
134 };
135 
136 static const auto NOTIFICATION_SUBSCRIBER = NotificationSubscriber();
137 
138 #ifndef START_STOP_ON_DEMAND_ENABLE
139 REGISTER_SYSTEM_ABILITY_BY_ID(AVSessionService, AVSESSION_SERVICE_ID, true);
140 #else
141 REGISTER_SYSTEM_ABILITY_BY_ID(AVSessionService, AVSESSION_SERVICE_ID, false);
142 #endif
143 
144 bool g_isCapsuleLive2 = system::GetBoolParameter("persist.systemui.live2", false);
145 std::shared_ptr<Media::PixelMap> g_defaultMediaImage = nullptr;
146 Notification::NotificationRequest g_NotifyRequest;
147 
AVSessionService(int32_t systemAbilityId,bool runOnCreate)148 AVSessionService::AVSessionService(int32_t systemAbilityId, bool runOnCreate)
149     : SystemAbility(systemAbilityId, runOnCreate)
150 {
151 }
152 
~AVSessionService()153 AVSessionService::~AVSessionService()
154 {
155     GetUsersManager().ClearCache();
156 }
157 
OnStart()158 void AVSessionService::OnStart()
159 {
160     SLOGI("OnStart SA with process check");
161     GetUsersManager().ClearCache();
162     CHECK_AND_RETURN_LOG(Publish(this), "publish avsession service failed");
163     OnStartProcess();
164 }
165 
OnStartProcess()166 void AVSessionService::OnStartProcess()
167 {
168     dumpHelper_ = std::make_unique<AVSessionDumper>();
169     CommandSendLimit::GetInstance().StartTimer();
170 
171     ParamsConfigOperator::GetInstance().InitConfig();
172     auto ret = ParamsConfigOperator::GetInstance().GetValueIntByKey("historicalRecordMaxNum", &maxHistoryNums_);
173     if (ret == AVSESSION_ERROR) {
174         maxHistoryNums_ = defMaxHistoryNum;
175     }
176 
177 #ifdef ENABLE_BACKGROUND_AUDIO_CONTROL
178     backgroundAudioController_.Init(this);
179     AddInnerSessionListener(&backgroundAudioController_);
180     for (auto& session : GetContainer().GetAllSessions()) {
181         CHECK_AND_CONTINUE(session != nullptr);
182         SLOGI("backgroundAudioController add sessionCreateBef:%{public}s",
183             AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str());
184         backgroundAudioController_.OnSessionCreate(session->GetDescriptor());
185     }
186 #endif
187 
188     AddSystemAbilityListener(MULTIMODAL_INPUT_SERVICE_ID);
189     AddSystemAbilityListener(AUDIO_POLICY_SERVICE_ID);
190     AddSystemAbilityListener(APP_MGR_SERVICE_ID);
191     AddSystemAbilityListener(DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID);
192     AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
193     AddSystemAbilityListener(CAST_ENGINE_SA_ID);
194     AddSystemAbilityListener(COLLABORATION_SA_ID);
195     AddSystemAbilityListener(MEMORY_MANAGER_SA_ID);
196     AddSystemAbilityListener(SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN);
197     AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID);
198 
199     HISYSEVENT_REGITER;
200     HISYSEVENT_BEHAVIOR("SESSION_SERVICE_START", "SERVICE_NAME", "AVSessionService",
201         "SERVICE_ID", AVSESSION_SERVICE_ID, "DETAILED_MSG", "avsession service start success");
202 #ifndef START_STOP_ON_DEMAND_ENABLE
203     if (!system::GetBoolParameter(BOOTEVENT_AVSESSION_SERVICE_READY.c_str(), false)) {
204         system::SetParameter(BOOTEVENT_AVSESSION_SERVICE_READY.c_str(), "true");
205         SLOGI("set boot avsession service started true");
206     }
207 #endif
208 
209     AVSessionUtils::PublishCommonEvent("usual.event.AVSESSION_START");
210 }
211 
OnDump()212 void AVSessionService::OnDump()
213 {
214 }
215 
OnIdle(const SystemAbilityOnDemandReason & idleReason)216 int32_t AVSessionService::OnIdle(const SystemAbilityOnDemandReason& idleReason)
217 {
218     SLOGI("OnIdle SA, idle reason %{public}d, %{public}s, %{public}s",
219         idleReason.GetId(), idleReason.GetName().c_str(), idleReason.GetValue().c_str());
220     uint32_t ret = GetUsersManager().GetContainerFromAll().GetAllSessions().size();
221     if (ret != 0) {
222         SLOGI("IPC is not used for a long time, there are %{public}d sessions.", ret);
223         return -1;
224     }
225     for (const auto& pair : migrateAVSessionProxyMap_) {
226         std::shared_ptr<MigrateAVSessionProxy> migrateAVSessionProxy =
227             std::static_pointer_cast<MigrateAVSessionProxy>(pair.second);
228         CHECK_AND_CONTINUE(migrateAVSessionProxy != nullptr);
229         CHECK_AND_RETURN_RET_LOG(!migrateAVSessionProxy->CheckMediaAlive(), -1,
230             "migrate proxy with media alive, should not stop");
231     }
232     return 0;
233 }
234 
OnActive(const SystemAbilityOnDemandReason & activeReason)235 void AVSessionService::OnActive(const SystemAbilityOnDemandReason& activeReason)
236 {
237     SLOGI("OnActive SA, idle reason %{public}d, %{public}s, %{public}s",
238         activeReason.GetId(), activeReason.GetName().c_str(), activeReason.GetValue().c_str());
239 }
240 
OnStop()241 void AVSessionService::OnStop()
242 {
243     PublishEvent(remoteMediaNone);
244     StopMigrateStubFunc stopMigrateStub =
245         reinterpret_cast<StopMigrateStubFunc>(dlsym(migrateStubFuncHandle_, "StopMigrateStub"));
246     if (stopMigrateStub == nullptr) {
247         SLOGE("failed to find library, reason: %{public}sn", dlerror());
248     } else {
249         stopMigrateStub();
250     }
251 #ifndef TEST_COVERAGE
252     if (migrateStubFuncHandle_ != nullptr) {
253         OPENSSL_thread_stop();
254     }
255     dlclose(migrateStubFuncHandle_);
256 #endif
257 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
258     CollaborationManager::GetInstance().UnRegisterLifecycleCallback();
259     CollaborationManager::ReleaseInstance();
260 #endif
261     CommandSendLimit::GetInstance().StopTimer();
262     NotifyProcessStatus(false);
263     UnSubscribeCommonEvent();
264     BundleStatusAdapter::ReleaseInstance();
265 }
266 
EventSubscriber(const EventFwk::CommonEventSubscribeInfo & subscriberInfo,AVSessionService * ptr)267 EventSubscriber::EventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscriberInfo, AVSessionService *ptr)
268     : EventFwk::CommonEventSubscriber(subscriberInfo)
269 {
270     servicePtr_ = ptr;
271 }
272 
OnReceiveEvent(const EventFwk::CommonEventData & eventData)273 void EventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &eventData)
274 {
275     const AAFwk::Want &want = eventData.GetWant();
276     std::string action = want.GetAction();
277     SLOGI("OnReceiveEvent action:%{public}s.", action.c_str());
278     if (servicePtr_ == nullptr) {
279         SLOGE("OnReceiveEvent get action:%{public}s with servicePtr_ null", action.c_str());
280         return;
281     }
282     if (action.compare(EventFwk::CommonEventSupport::COMMON_EVENT_USER_FOREGROUND) == 0) {
283         int32_t userIdForeground = eventData.GetCode();
284         servicePtr_->HandleUserEvent(AVSessionUsersManager::accountEventSwitched, userIdForeground);
285     } else if (action.compare(EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED) == 0) {
286         int32_t userIdSwitched = eventData.GetCode();
287         servicePtr_->HandleUserEvent(AVSessionUsersManager::accountEventSwitched, userIdSwitched);
288     } else if (action.compare(EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED) == 0) {
289         int32_t userId = eventData.GetCode();
290         servicePtr_->HandleUserEvent(AVSessionUsersManager::accountEventRemoved, userId);
291     } else if (action.compare(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED) == 0) {
292         int32_t userId = eventData.GetCode();
293         servicePtr_->RegisterBundleDeleteEventForHistory(userId);
294     } else if (action.compare(EventFwk::CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED) == 0 ||
295         action.compare(EventFwk::CommonEventSupport::COMMON_EVENT_LOCKED_BOOT_COMPLETED) == 0) {
296         servicePtr_->InitCastEngineService();
297     } else if (action.compare("EVENT_REMOVE_MEDIACONTROLLER_LIVEVIEW") == 0) {
298         servicePtr_->HandleRemoveMediaCardEvent();
299     } else if (action.compare("EVENT_AVSESSION_MEDIA_CAPSULE_STATE_CHANGE") == 0) {
300         std::string param = eventData.GetData();
301         SLOGI("OnReceiveEvent notify data:%{public}s", param.c_str());
302         servicePtr_->HandleMediaCardStateChangeEvent(param);
303     }
304 }
305 
GetAVQueueDir(int32_t userId)306 std::string AVSessionService::GetAVQueueDir(int32_t userId)
307 {
308     return GetUsersManager().GetDirForCurrentUser(userId) + AVQUEUE_FILE_NAME;
309 }
310 
GetAVSortDir(int32_t userId)311 std::string AVSessionService::GetAVSortDir(int32_t userId)
312 {
313     return GetUsersManager().GetDirForCurrentUser(userId) + SORT_FILE_NAME;
314 }
315 
HandleUserEvent(const std::string & type,const int & userId)316 void AVSessionService::HandleUserEvent(const std::string &type, const int &userId)
317 {
318     // del capsule before account switching
319     int32_t curUserId = GetUsersManager().GetCurrentUserId();
320     if (type == AVSessionUsersManager::accountEventSwitched && userId != curUserId && hasMediaCapsule_.load()) {
321         SLOGI("userSwitch userId:%{public}d curUserId:%{public}d hasCapsule:%{public}d",
322             userId, curUserId, hasMediaCapsule_.load());
323         std::lock_guard lockGuard(sessionServiceLock_);
324         NotifySystemUI(nullptr, true, false, false);
325     }
326     GetUsersManager().NotifyAccountsEvent(type, userId);
327     if (type == AVSessionUsersManager::accountEventSwitched) {
328         SLOGD("userSwitch and updateTopSession for userId:%{public}d", userId);
329         UpdateTopSession(GetUsersManager().GetTopSession(), userId);
330     }
331 }
332 
HandleRemoveMediaCardEvent()333 void AVSessionService::HandleRemoveMediaCardEvent()
334 {
335     hasRemoveEvent_ = true;
336     hasMediaCapsule_ = false;
337     std::lock_guard lockGuard(sessionServiceLock_);
338     if (!topSession_) {
339         return;
340     }
341     auto ret = BackgroundTaskMgr::BackgroundTaskMgrHelper::AVSessionNotifyUpdateNotification(
342         topSession_->GetUid(), topSession_->GetPid(), false);
343     if (ret != AVSESSION_SUCCESS) {
344         SLOGE("AVSessionNotifyUpdateNotification failed, uid = %{public}d, pid = %{public}d, ret = %{public}d",
345             topSession_->GetUid(), topSession_->GetPid(), ret);
346     }
347     AVSessionEventHandler::GetInstance().AVSessionRemoveTask("NotifyFlowControl");
348     if (topSession_->IsCasting()) {
349         AVCastControlCommand castCmd;
350         castCmd.SetCommand(AVCastControlCommand::CAST_CONTROL_CMD_PAUSE);
351         topSession_->SendControlCommandToCast(castCmd);
352     } else {
353         AVControlCommand cmd;
354         cmd.SetCommand(AVControlCommand::SESSION_CMD_PAUSE);
355         topSession_->ExecuteControllerCommand(cmd);
356     }
357 }
358 
IsTopSessionPlaying()359 bool AVSessionService::IsTopSessionPlaying()
360 {
361     std::lock_guard lockGuard(sessionServiceLock_);
362     if (!topSession_) {
363         return false;
364     }
365     bool isPlaying = topSession_->IsCasting() ?
366         (topSession_->GetCastAVPlaybackState().GetState() == AVPlaybackState::PLAYBACK_STATE_PLAY) :
367         AudioAdapter::GetInstance().GetRendererRunning(topSession_->GetUid(), topSession_->GetPid());
368     return isPlaying;
369 }
370 
HandleMediaCardStateChangeEvent(std::string isAppear)371 void AVSessionService::HandleMediaCardStateChangeEvent(std::string isAppear)
372 {
373     if (isAppear == "APPEAR") {
374         isMediaCardOpen_ = true;
375         AVSessionEventHandler::GetInstance().AVSessionRemoveTask("CheckCardStateChangeStop");
376         hasCardStateChangeStopTask_ = false;
377     } else if (isAppear == "DISAPPEAR") {
378         isMediaCardOpen_ = false;
379         if (IsTopSessionPlaying() || hasRemoveEvent_.load()) {
380             SLOGI("HandleMediaCardState hasRemoveEvent_:%{public}d ", hasRemoveEvent_.load());
381             return;
382         }
383         hasCardStateChangeStopTask_ = true;
384         AVSessionEventHandler::GetInstance().AVSessionPostTask(
385             [this]() {
386                 if (IsTopSessionPlaying() || hasRemoveEvent_.load() || isMediaCardOpen_.load()) {
387                     SLOGI("HandleMediaCardState hasRemoveEvent_:%{public}d isMediaCardOpen_:%{public}d",
388                         hasRemoveEvent_.load(), isMediaCardOpen_.load());
389                     return;
390                 }
391                 {
392                     std::lock_guard lockGuard(sessionServiceLock_);
393                     NotifySystemUI(nullptr, true, false, false);
394                     hasCardStateChangeStopTask_ = false;
395                 }
396             }, "CheckCardStateChangeStop", cancelTimeout);
397     }
398 }
399 
SubscribeCommonEvent()400 bool AVSessionService::SubscribeCommonEvent()
401 {
402     const std::vector<std::string> events = {
403         EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF,
404         EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON,
405         EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED,
406         EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED,
407         EventFwk::CommonEventSupport::COMMON_EVENT_USER_SWITCHED,
408         EventFwk::CommonEventSupport::COMMON_EVENT_USER_FOREGROUND,
409         EventFwk::CommonEventSupport::COMMON_EVENT_USER_REMOVED,
410         EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED,
411         EventFwk::CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED,
412         EventFwk::CommonEventSupport::COMMON_EVENT_LOCKED_BOOT_COMPLETED,
413         "EVENT_REMOVE_MEDIACONTROLLER_LIVEVIEW",
414         "EVENT_AVSESSION_MEDIA_CAPSULE_STATE_CHANGE"
415     };
416 
417     EventFwk::MatchingSkills matchingSkills;
418     for (auto event : events) {
419         matchingSkills.AddEvent(event);
420     }
421     EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
422 
423     subscriber_ = std::make_shared<EventSubscriber>(subscribeInfo, this);
424     return EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber_);
425 }
426 
UnSubscribeCommonEvent()427 bool AVSessionService::UnSubscribeCommonEvent()
428 {
429     bool subscribeResult = false;
430     if (subscriber_ != nullptr) {
431         subscribeResult = EventFwk::CommonEventManager::UnSubscribeCommonEvent(subscriber_);
432         subscriber_ = nullptr;
433     }
434     SLOGI("UnSubscribeCommonEvent subscribeResult = %{public}d", subscribeResult);
435 
436     return subscribeResult;
437 }
438 
PullMigrateStub()439 void AVSessionService::PullMigrateStub()
440 {
441     migrateStubFuncHandle_ = dlopen("libavsession_migration.z.so", RTLD_NOW);
442     if (migrateStubFuncHandle_ == nullptr) {
443         SLOGE("failed to dlopen library, reason: %{public}sn", dlerror());
444         return;
445     }
446     MigrateStubFunc startMigrateStub =
447         reinterpret_cast<MigrateStubFunc>(dlsym(migrateStubFuncHandle_, "StartMigrateStub"));
448     if (startMigrateStub == nullptr) {
449         SLOGE("failed to find library, reason: %{public}sn", dlerror());
450         return;
451     }
452     std::thread([startMigrateStub, this]() {
453         SLOGI("create thread to keep MigrateStub");
454         startMigrateStub([this](std::string deviceId, std::string serviceName, std::string extraInfo,
455             std::string state) { SuperLauncher(deviceId, serviceName, extraInfo, state); });
456     }).detach();
457 }
458 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)459 void AVSessionService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
460 {
461     SLOGI("Receive SA: %{public}d start callback.", systemAbilityId);
462     switch (systemAbilityId) {
463         case MULTIMODAL_INPUT_SERVICE_ID:
464             InitKeyEvent();
465             break;
466         case AUDIO_POLICY_SERVICE_ID:
467             InitAudio();
468             break;
469         case APP_MGR_SERVICE_ID:
470             InitAMS();
471             break;
472         case DISTRIBUTED_HARDWARE_DEVICEMANAGER_SA_ID:
473             InitDM();
474             break;
475         case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID:
476             InitBMS();
477             InitRadarBMS();
478             break;
479         case CAST_ENGINE_SA_ID:
480 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
481             if (is2in1_) {
482                 checkEnableCast(true);
483             }
484 #endif
485             break;
486         case COLLABORATION_SA_ID:
487             InitCollaboration();
488             PullMigrateStub();
489             break;
490         case MEMORY_MANAGER_SA_ID:
491             NotifyProcessStatus(true);
492             break;
493         case SUBSYS_ACCOUNT_SYS_ABILITY_ID_BEGIN:
494             InitAccountMgr();
495             break;
496         case COMMON_EVENT_SERVICE_ID:
497             InitCommonEventService();
498             break;
499         default:
500             SLOGE("undefined system ability %{public}d", systemAbilityId);
501     }
502 }
503 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)504 void AVSessionService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
505 {
506     SLOGI("remove system ability %{public}d", systemAbilityId);
507 }
508 
NotifyProcessStatus(bool isStart)509 void AVSessionService::NotifyProcessStatus(bool isStart)
510 {
511     int pid = getpid();
512     void *libMemMgrClientHandle = dlopen("libmemmgrclient.z.so", RTLD_NOW);
513     if (!libMemMgrClientHandle) {
514         SLOGE("dlopen libmemmgrclient library failed");
515         return;
516     }
517     void *notifyProcessStatusFunc = dlsym(libMemMgrClientHandle, "notify_process_status");
518     if (!notifyProcessStatusFunc) {
519         SLOGE("dlsm notify_process_status failed");
520 #ifndef TEST_COVERAGE
521         if (libMemMgrClientHandle != nullptr) {
522             OPENSSL_thread_stop();
523         }
524         dlclose(libMemMgrClientHandle);
525 #endif
526         return;
527     }
528     auto notifyProcessStatus = reinterpret_cast<int(*)(int, int, int, int)>(notifyProcessStatusFunc);
529     if (isStart) {
530         SLOGI("notify to memmgr when av_session is started");
531         notifyProcessStatus(pid, saType, 1, AVSESSION_SERVICE_ID); // 1 indicates the service is started
532     } else {
533         SLOGI("notify to memmgr when av_session is stopped");
534         notifyProcessStatus(pid, saType, 0, AVSESSION_SERVICE_ID); // 0 indicates the service is stopped
535     }
536 #ifndef TEST_COVERAGE
537     if (libMemMgrClientHandle != nullptr) {
538         OPENSSL_thread_stop();
539     }
540     dlclose(libMemMgrClientHandle);
541 #endif
542 }
543 
InitKeyEvent()544 void AVSessionService::InitKeyEvent()
545 {
546     SLOGI("enter init keyEvent");
547     std::vector<int32_t> keyCodes = {
548         MMI::KeyEvent::KEYCODE_MEDIA_PLAY,
549         MMI::KeyEvent::KEYCODE_MEDIA_PAUSE,
550         MMI::KeyEvent::KEYCODE_MEDIA_PLAY_PAUSE,
551         MMI::KeyEvent::KEYCODE_MEDIA_STOP,
552         MMI::KeyEvent::KEYCODE_MEDIA_NEXT,
553         MMI::KeyEvent::KEYCODE_MEDIA_PREVIOUS,
554         MMI::KeyEvent::KEYCODE_MEDIA_REWIND,
555         MMI::KeyEvent::KEYCODE_MEDIA_FAST_FORWARD,
556         MMI::KeyEvent::KEYCODE_HEADSETHOOK,
557     };
558 
559     KeyEventAdapter::GetInstance().SubscribeKeyEvent(
560         keyCodes, [this](const auto& keyEvent) { SendSystemAVKeyEvent(*keyEvent); });
561 }
562 
ReportFocusSessionChange(const sptr<AVSessionItem> & topSession,const sptr<AVSessionItem> & newTopSession)563 void ReportFocusSessionChange(const sptr<AVSessionItem>& topSession, const sptr<AVSessionItem>& newTopSession)
564 {
565     HISYSEVENT_BEHAVIOR("FOCUS_CHANGE",
566         "OLD_BUNDLE_NAME", topSession->GetDescriptor().elementName_.GetBundleName(),
567         "OLD_MODULE_NAME", topSession->GetDescriptor().elementName_.GetModuleName(),
568         "OLD_ABILITY_NAME", topSession->GetAbilityName(), "OLD_SESSION_PID", topSession->GetPid(),
569         "OLD_SESSION_UID", topSession->GetUid(), "OLD_SESSION_ID", topSession->GetSessionId(),
570         "OLD_SESSION_TAG", topSession->GetDescriptor().sessionTag_,
571         "OLD_SESSION_TYPE", topSession->GetDescriptor().sessionType_,
572         "BUNDLE_NAME", newTopSession->GetDescriptor().elementName_.GetBundleName(),
573         "MODULE_NAME", newTopSession->GetDescriptor().elementName_.GetModuleName(),
574         "ABILITY_NAME", newTopSession->GetAbilityName(), "SESSION_PID", newTopSession->GetPid(),
575         "SESSION_UID", newTopSession->GetUid(), "SESSION_ID", newTopSession->GetSessionId(),
576         "SESSION_TAG", newTopSession->GetDescriptor().sessionTag_,
577         "SESSION_TYPE", newTopSession->GetDescriptor().sessionType_,
578         "DETAILED_MSG", "avsessionservice handlefocussession, updatetopsession");
579 }
580 
UpdateSessionTimestamp(sptr<AVSessionItem> sessionItem)581 void AVSessionService::UpdateSessionTimestamp(sptr<AVSessionItem> sessionItem)
582 {
583     CHECK_AND_RETURN_LOG(sessionItem != nullptr, "UpdateSessionTimestamp sessionItem is null");
584     auto now = std::chrono::system_clock::now();
585     auto timeSinceEpoch = now.time_since_epoch();
586     auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(timeSinceEpoch).count();
587     sessionItem->SetPlayingTime(milliseconds);
588 }
589 
UpdateTopSession(const sptr<AVSessionItem> & newTopSession,int32_t userId)590 void AVSessionService::UpdateTopSession(const sptr<AVSessionItem>& newTopSession, int32_t userId)
591 {
592     AVSessionDescriptor descriptor;
593     int32_t userIdForNewTopSession = newTopSession != nullptr ? newTopSession->GetUserId() :
594         (userId <= 0 ? GetUsersManager().GetCurrentUserId() : userId);
595     {
596         std::lock_guard lockGuard(sessionServiceLock_);
597         if (newTopSession == nullptr) {
598             if (topSession_ != nullptr && GetUsersManager().GetCurrentUserId() == userIdForNewTopSession) {
599                 topSession_->SetTop(false);
600                 topSession_ = nullptr;
601             }
602             GetUsersManager().SetTopSession(nullptr, userIdForNewTopSession);
603             SLOGI("set topSession to nullptr for userId:%{public}d", userIdForNewTopSession);
604             HISYSEVENT_BEHAVIOR("FOCUS_CHANGE", "DETAILED_MSG", "avsessionservice set topsession to nullptr");
605             return;
606         }
607 
608         SLOGI("updateNewTop uid=%{public}d|pid=%{public}d|userId:%{public}d|sessionId=%{public}s",
609             newTopSession->GetUid(), newTopSession->GetPid(), userIdForNewTopSession,
610             AVSessionUtils::GetAnonySessionId(newTopSession->GetSessionId()).c_str());
611         if (userIdForNewTopSession == GetUsersManager().GetCurrentUserId()) {
612             if (topSession_ != nullptr) {
613                 topSession_->SetTop(false);
614                 ReportFocusSessionChange(topSession_, newTopSession);
615             }
616             topSession_ = newTopSession;
617             // update topsession playingtime
618             UpdateSessionTimestamp(topSession_);
619 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
620             MirrorToStreamCast(topSession_);
621 #endif // CASTPLUS_CAST_ENGINE_ENABLE
622         }
623         GetUsersManager().SetTopSession(newTopSession, userIdForNewTopSession);
624         newTopSession->SetTop(true);
625         descriptor = newTopSession->GetDescriptor();
626     }
627 
628     NotifyTopSessionChanged(descriptor);
629     if (topSession_ != nullptr && !topSession_->IsCasting()) {
630         std::string preloadSessionId = topSession_->GetSessionId();
631         NotifyLocalFrontSessionChangeForMigrate(preloadSessionId);
632     }
633 }
634 
HandleChangeTopSession(int32_t infoUid,int32_t infoPid,int32_t userId)635 void AVSessionService::HandleChangeTopSession(int32_t infoUid, int32_t infoPid, int32_t userId)
636 {
637     std::lock_guard frontLockGuard(sessionFrontLock_);
638     std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront();
639     CHECK_AND_RETURN_LOG(sessionListForFront != nullptr, "sessionListForFront ptr nullptr!");
640     for (const auto& session : *sessionListForFront) {
641         if (session->GetUid() == infoUid && session->GetPid() == infoPid &&
642             (session->GetSessionType() != "voice_call" && session->GetSessionType() != "video_call")) {
643             UpdateTopSession(session);
644             if (topSession_ != nullptr &&
645                 (topSession_->GetSessionType() == "audio" || topSession_->GetSessionType() == "video")) {
646                 AVSessionService::NotifySystemUI(nullptr, true, IsCapsuleNeeded(), false);
647                 PublishEvent(mediaPlayStateTrue);
648                 auto ret = BackgroundTaskMgr::BackgroundTaskMgrHelper::AVSessionNotifyUpdateNotification(
649                     topSession_->GetUid(), topSession_->GetPid(), true);
650                 SLOGD("HandleChangeTopSession Notify Bg, uid = %{public}d, pid = %{public}d, ret = %{public}d",
651                     topSession_->GetUid(), topSession_->GetPid(), ret);
652             }
653             return;
654         }
655     }
656 }
657 
658 // LCOV_EXCL_START
HandleFocusSession(const FocusSessionStrategy::FocusSessionChangeInfo & info,bool isPlaying)659 void AVSessionService::HandleFocusSession(const FocusSessionStrategy::FocusSessionChangeInfo& info, bool isPlaying)
660 {
661     SLOGI("uid=%{public}d, pid=%{public}d curTop:%{public}s",
662         info.uid, info.pid, (topSession_ == nullptr ? "null" : topSession_->GetBundleName()).c_str());
663     std::lock_guard lockGuard(sessionServiceLock_);
664     if (info.uid == ancoUid && isPlaying) {
665         sptr<AVSessionItem> sessionItem = GetContainer().GetSessionByUid(info.uid);
666         CHECK_AND_RETURN_LOG(sessionItem != nullptr, "handle focusession no anco_audio");
667         ancoSession_ = sessionItem;
668         UpdateSessionTimestamp(ancoSession_);
669         return;
670     }
671     int32_t userId = GetUsersManager().GetCurrentUserId();
672     if ((topSession_ && topSession_->GetUid() == info.uid && topSession_->GetPid() == info.pid) &&
673         topSession_->IsCasting()) {
674         SLOGI("cur topSession:%{public}s isCasting", topSession_->GetBundleName().c_str());
675         return;
676     }
677     if (topSession_ && topSession_->GetUid() == info.uid && topSession_->GetPid() == info.pid) {
678         SLOGI(" HandleFocusSession focusSession is current topSession.");
679         auto hasOtherPlayingSession = false;
680         if (topSession_->GetSessionType() == "audio" || topSession_->GetSessionType() == "video") {
681             bool notPublishNotification = !isPlaying &&
682                 (isMediaCardOpen_ || hasRemoveEvent_.load() || hasCardStateChangeStopTask_.load());
683             CHECK_AND_RETURN_LOG(!notPublishNotification,
684                 "isPlaying:%{public}d isCardOpen_:%{public}d hasRemoveEvent_:%{public}d hasRemoveTask_:%{public}d",
685                 isPlaying, isMediaCardOpen_.load(), hasRemoveEvent_.load(), hasCardStateChangeStopTask_.load());
686             if (isPlaying) {
687                 auto ret = BackgroundTaskMgr::BackgroundTaskMgrHelper::AVSessionNotifyUpdateNotification(
688                     topSession_->GetUid(), topSession_->GetPid(), true);
689                 SLOGD("call AVSessionNotifyUpdateNotification, uid = %{public}d, pid = %{public}d, ret = %{public}d",
690                     topSession_->GetUid(), topSession_->GetPid(), ret);
691             } else {
692                 sptr<AVSessionItem> result = GetOtherPlayingSession(userId, "");
693                 hasOtherPlayingSession = (result != nullptr);
694                 HandleOtherSessionPlaying(result);
695             }
696             if (!hasOtherPlayingSession) {
697                 AVSessionService::NotifySystemUI(nullptr, true, isPlaying && IsCapsuleNeeded(), false);
698             }
699 #ifdef START_STOP_ON_DEMAND_ENABLE
700             PublishEvent(mediaPlayStateTrue);
701 #endif
702         }
703         return;
704     }
705     CHECK_AND_RETURN_LOG(isPlaying, "focusSession no play");
706     HandleChangeTopSession(info.uid, info.pid, userId);
707 }
708 // LCOV_EXCL_STOP
709 
710 // LCOV_EXCL_START
InsertSessionItemToCJSON(sptr<AVSessionItem> & session,cJSON * valuesArray)711 bool AVSessionService::InsertSessionItemToCJSON(sptr<AVSessionItem> &session, cJSON* valuesArray)
712 {
713     CHECK_AND_RETURN_RET_LOG(session != nullptr, false, "session get null");
714     CHECK_AND_RETURN_RET_LOG(valuesArray != nullptr, false, "valuesArray get null");
715     cJSON* newValue = cJSON_CreateObject();
716     CHECK_AND_RETURN_RET_LOG(newValue != nullptr, false, "newValue get null");
717     cJSON_AddStringToObject(newValue, "sessionId", session->GetSessionId().c_str());
718     cJSON_AddStringToObject(newValue, "bundleName", session->GetBundleName().c_str());
719     cJSON_AddStringToObject(newValue, "abilityName", session->GetAbilityName().c_str());
720     cJSON_AddStringToObject(newValue, "sessionType", session->GetSessionType().c_str());
721     if (cJSON_GetArraySize(valuesArray) <= 0) {
722         cJSON_AddItemToArray(valuesArray, newValue);
723     } else {
724         cJSON_InsertItemInArray(valuesArray, 0, newValue);
725     }
726     if (cJSON_IsInvalid(valuesArray)) {
727         SLOGE("get newValueArray invalid");
728         return false;
729     }
730     return true;
731 }
732 // LCOV_EXCL_STOP
733 
734 // LCOV_EXCL_START
RefreshFocusSessionSort(sptr<AVSessionItem> & session)735 void AVSessionService::RefreshFocusSessionSort(sptr<AVSessionItem> &session)
736 {
737     std::lock_guard sortFileLockGuard(sessionFileLock_);
738     std::string oldSortContent;
739     if (!LoadStringFromFileEx(GetAVSortDir(), oldSortContent)) {
740         SLOGE("LoadStringFromFileEx failed when refresh focus session sort!");
741         return;
742     }
743     cJSON* valuesArray = cJSON_Parse(oldSortContent.c_str());
744     CHECK_AND_RETURN_LOG(valuesArray != nullptr, "cjson parse nullptr");
745     if (cJSON_IsInvalid(valuesArray) || !cJSON_IsArray(valuesArray)) {
746         SLOGE("parse json invalid");
747         cJSON_Delete(valuesArray);
748         return;
749     }
750     bool sessionExist = false;
751     int arraySize = cJSON_GetArraySize(valuesArray);
752     for (int i = arraySize - 1; i >= 0; i--) {
753         cJSON* itemToDelete = cJSON_GetArrayItem(valuesArray, i);
754         CHECK_AND_CONTINUE(itemToDelete != nullptr && !cJSON_IsInvalid(itemToDelete));
755         cJSON* bundleNameItem = cJSON_GetObjectItem(itemToDelete, "bundleName");
756         cJSON* abilityNameItem = cJSON_GetObjectItem(itemToDelete, "abilityName");
757         if (bundleNameItem == nullptr || cJSON_IsInvalid(bundleNameItem) || !cJSON_IsString(bundleNameItem) ||
758             abilityNameItem == nullptr || cJSON_IsInvalid(abilityNameItem) || !cJSON_IsString(abilityNameItem)) {
759             SLOGI("not contain bundleName or abilityName, pass");
760             continue;
761         }
762         if (strcmp(session->GetBundleName().c_str(), bundleNameItem->valuestring) == 0 &&
763             strcmp(session->GetAbilityName().c_str(), abilityNameItem->valuestring) == 0) {
764             cJSON_DeleteItemFromArray(valuesArray, i);
765             sessionExist = true;
766             break;
767         }
768     }
769     if (sessionExist) {
770         InsertSessionItemToCJSON(session, valuesArray);
771     }
772     std::string newSortContentStr = DoCJSONArrayTransformToString(valuesArray);
773     if (!SaveStringToFileEx(GetAVSortDir(), newSortContentStr)) {
774         SLOGE("SaveStringToFileEx failed when refresh focus session sort!");
775     }
776     cJSON_Delete(valuesArray);
777 }
778 
DoCJSONArrayTransformToString(cJSON * valueItem)779 std::string AVSessionService::DoCJSONArrayTransformToString(cJSON* valueItem)
780 {
781     CHECK_AND_RETURN_RET_LOG(valueItem != nullptr && !cJSON_IsInvalid(valueItem), "", "valueItem invalid");
782     char* newSortContent = cJSON_Print(valueItem);
783     CHECK_AND_RETURN_RET_LOG(newSortContent != nullptr, "", "newValueArray print fail nullptr");
784     std::string newSortContentStr(newSortContent);
785     cJSON_free(newSortContent);
786     return newSortContentStr;
787 }
788 
789 // LCOV_EXCL_STOP
790 
UpdateFrontSession(sptr<AVSessionItem> & sessionItem,bool isAdd)791 void AVSessionService::UpdateFrontSession(sptr<AVSessionItem>& sessionItem, bool isAdd)
792 {
793     CHECK_AND_RETURN_LOG(sessionItem != nullptr, "sessionItem get nullptr!");
794     int32_t userId = sessionItem->GetUserId();
795     SLOGI("UpdateFrontSession with bundle=%{public}s,userId=%{public}d,isAdd=%{public}d",
796         sessionItem->GetBundleName().c_str(), userId, isAdd);
797     std::lock_guard frontLockGuard(sessionFrontLock_);
798     std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront(userId);
799     CHECK_AND_RETURN_LOG(sessionListForFront != nullptr, "sessionListForFront ptr nullptr!");
800     auto ret = BackgroundTaskMgr::BackgroundTaskMgrHelper::AVSessionNotifyUpdateNotification(
801         sessionItem->GetUid(), sessionItem->GetPid(), isAdd);
802     if (ret != AVSESSION_SUCCESS) {
803         SLOGE("AVSessionNotifyUpdateNotification failed, uid = %{public}d, pid = %{public}d, ret = %{public}d",
804             sessionItem->GetUid(), sessionItem->GetPid(), ret);
805     }
806     auto it = std::find(sessionListForFront->begin(), sessionListForFront->end(), sessionItem);
807     if (isAdd) {
808         if (it != sessionListForFront->end()) {
809             SLOGI("sessionListForFront has same session bundle=%{public}s", sessionItem->GetBundleName().c_str());
810             return;
811         }
812         sessionListForFront->push_front(sessionItem);
813         if (AudioAdapter::GetInstance().GetRendererRunning(sessionItem->GetUid(), sessionItem->GetPid())) {
814             SLOGI("Renderer Running, RepublishNotification for uid=%{public}d", sessionItem->GetUid());
815             UpdateTopSession(sessionItem);
816             AVSessionDescriptor selectSession = sessionItem->GetDescriptor();
817             NotifySystemUI(&selectSession, true, IsCapsuleNeeded(), false);
818             PublishEvent(mediaPlayStateTrue);
819         }
820     } else {
821         std::lock_guard lockGuard(sessionServiceLock_);
822         HandleTopSessionRelease(userId, sessionItem);
823         sessionListForFront->remove(sessionItem);
824         SLOGI("sessionListForFront with size %{public}d", static_cast<int32_t>(sessionListForFront->size()));
825     }
826     UpdateLocalFrontSession(sessionListForFront);
827 }
828 
UpdateOrder(sptr<AVSessionItem> & sessionItem)829 bool AVSessionService::UpdateOrder(sptr<AVSessionItem>& sessionItem)
830 {
831     CHECK_AND_RETURN_RET_LOG(sessionItem != nullptr, false, "sessionItem is nullptr!");
832     GetContainer().UpdateSessionSort(sessionItem);
833     RefreshFocusSessionSort(sessionItem);
834     std::lock_guard frontLockGuard(sessionFrontLock_);
835     std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront();
836     CHECK_AND_RETURN_RET_LOG(sessionListForFront != nullptr, false, "sessionListForFront ptr nullptr!");
837     auto it = std::find(sessionListForFront->begin(), sessionListForFront->end(), sessionItem);
838     if (it != sessionListForFront->end()) {
839         SLOGI("session is in sessionListForFront_, need to change order of it.");
840         sessionListForFront->remove(sessionItem);
841         sessionListForFront->push_front(sessionItem);
842         UpdateSessionTimestamp(sessionItem);
843     }
844     return true;
845 }
846 
SelectFocusSession(const FocusSessionStrategy::FocusSessionChangeInfo & info)847 bool AVSessionService::SelectFocusSession(const FocusSessionStrategy::FocusSessionChangeInfo& info)
848 {
849     for (auto& session : GetContainer().GetAllSessions()) {
850         if (session->GetDescriptor().sessionTag_ == "RemoteCast" || session->GetPid() != info.pid) {
851             continue;
852         }
853         bool ret = UpdateOrder(session);
854         CHECK_AND_RETURN_RET_LOG(ret, false, "UpdateOrder fail");
855         return true;
856     }
857     return false;
858 }
859 
InitAudio()860 void AVSessionService::InitAudio()
861 {
862     SLOGI("enter");
863     AudioAdapter::GetInstance().Init();
864     focusSessionStrategy_.Init();
865     focusSessionStrategy_.RegisterFocusSessionChangeCallback([this] (const auto& info, bool isPlaying) {
866         HandleFocusSession(info, isPlaying);
867     });
868     focusSessionStrategy_.RegisterFocusSessionSelector([this] (const auto& info) {
869         return SelectFocusSession(info);
870     });
871     queryAllowedPlaybackCallbackFunc_ = GetAllowedPlaybackCallbackFunc();
872     auto ret = AudioAdapter::GetInstance().RegisterAllowedPlaybackCallback(queryAllowedPlaybackCallbackFunc_);
873     if (ret != AVSESSION_SUCCESS) {
874         SLOGE("register query allowed playback callback failed!");
875     }
876 }
877 
SelectSessionByUid(const AudioRendererChangeInfo & info)878 sptr <AVSessionItem> AVSessionService::SelectSessionByUid(const AudioRendererChangeInfo& info)
879 {
880     for (const auto& session : GetContainer().GetAllSessions()) {
881         if (session != nullptr && session->GetUid() == info.clientUID) {
882             return session;
883         }
884     }
885     SLOGI("AudioRendererInfo with uid: %{public}d does not have a corresponding session.", info.clientUID);
886     return nullptr;
887 }
888 
InitAMS()889 void AVSessionService::InitAMS()
890 {
891     SLOGI("enter");
892     AppManagerAdapter::GetInstance().Init();
893     AppManagerAdapter::GetInstance().SetServiceCallbackForAppStateChange([this] (int uid, int state) {
894         SLOGD("uid = %{public}d, state = %{public}d", uid, state);
895         HandleAppStateChange(uid, state);
896     });
897 }
898 
InitDM()899 void AVSessionService::InitDM()
900 {
901     SLOGI("enter");
902     auto callback = std::make_shared<AVSessionInitDMCallback>();
903     CHECK_AND_RETURN_LOG(callback != nullptr, "no memory");
904     int32_t ret = OHOS::DistributedHardware::DeviceManager::GetInstance().InitDeviceManager("av_session", callback);
905     CHECK_AND_RETURN_LOG(ret == 0, "InitDeviceManager error ret is %{public}d", ret);
906     DoTargetDevListenWithDM();
907 }
908 
InitBMS()909 void AVSessionService::InitBMS()
910 {
911     std::lock_guard sortFileLockGuard(sessionFileLock_);
912     SLOGI("enter");
913     BundleStatusAdapter::GetInstance().Init();
914     int userId = GetUsersManager().GetCurrentUserId();
915     if (userId < 0) {
916         SLOGE("InitBMS with userId: %{public}d, not valid, return and wait for InitAccountMgr", userId);
917         return;
918     }
919     RegisterBundleDeleteEventForHistory(userId);
920 }
921 
InitAccountMgr()922 void AVSessionService::InitAccountMgr()
923 {
924     SLOGI("InitAccountMgr in");
925     GetUsersManager().Init();
926     RegisterBundleDeleteEventForHistory();
927 }
928 
InitCommonEventService()929 void AVSessionService::InitCommonEventService()
930 {
931     SLOGI("InitCommonEventService in");
932     bool ret = SubscribeCommonEvent();
933     CHECK_AND_RETURN_LOG(ret, "SubscribeCommonEvent error!");
934 }
935 
InitCollaboration()936 void AVSessionService::InitCollaboration()
937 {
938     SLOGI("InitCollaboration in");
939 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
940     CollaborationManager::GetInstance().ReadCollaborationManagerSo();
941     CollaborationManager::GetInstance().RegisterLifecycleCallback();
942 #endif
943 }
944 
InitCastEngineService()945 void AVSessionService::InitCastEngineService()
946 {
947     SLOGI("InitCastEngineService in");
948 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
949     SLOGI("GetDeviceEnableCast, Prop=%{public}d", static_cast<int>(is2in1_));
950 #endif
951 }
952 
RegisterBundleDeleteEventForHistory(int32_t userId)953 void AVSessionService::RegisterBundleDeleteEventForHistory(int32_t userId)
954 {
955     if (userId <= 0) {
956         userId = GetUsersManager().GetCurrentUserId();
957         SLOGI("do RegisterBundleDeleteEventForHistory with cur userId:%{public}d", userId);
958     } else {
959         SLOGI("do RegisterBundleDeleteEventForHistory with recv userId:%{public}d", userId);
960     }
961 
962     std::string oldSortContent;
963     if (LoadStringFromFileEx(GetAVSortDir(userId), oldSortContent)) {
964         cJSON* valuesArray = cJSON_Parse(oldSortContent.c_str());
965         CHECK_AND_RETURN_LOG(valuesArray != nullptr, "parse json get nullptr");
966         if (cJSON_IsInvalid(valuesArray) || !cJSON_IsArray(valuesArray)) {
967             SLOGE("parse json not valid");
968             cJSON_Delete(valuesArray);
969             return;
970         }
971         auto callback = [this](std::string bundleName, int32_t userId) {
972             SLOGI("recv delete bundle:%{public}s at user:%{public}d", bundleName.c_str(), userId);
973             DeleteAVQueueInfoRecord(bundleName, userId);
974             DeleteHistoricalRecord(bundleName, userId);
975             NotifyHistoricalRecordChange(bundleName, userId);
976         };
977         cJSON* valueItem = nullptr;
978         cJSON_ArrayForEach(valueItem, valuesArray) {
979             CHECK_AND_CONTINUE(valueItem != nullptr && !cJSON_IsInvalid(valueItem));
980             cJSON* bundleNameItem = cJSON_GetObjectItem(valueItem, "bundleName");
981             CHECK_AND_CONTINUE(bundleNameItem != nullptr &&
982                 !cJSON_IsInvalid(bundleNameItem) && cJSON_IsString(bundleNameItem));
983             std::string bundleNameStr(bundleNameItem->valuestring);
984             if (!BundleStatusAdapter::GetInstance().SubscribeBundleStatusEvent(bundleNameStr, callback, userId)) {
985                 SLOGE("SubscribeBundleStatusEvent failed for bundle:%{public}s", bundleNameStr.c_str());
986             }
987         }
988         cJSON_Delete(valuesArray);
989     }
990 }
991 
GetContainer()992 SessionContainer& AVSessionService::GetContainer()
993 {
994     return GetUsersManager().GetContainer();
995 }
996 
GetUsersManager()997 AVSessionUsersManager& AVSessionService::GetUsersManager()
998 {
999     static AVSessionUsersManager usersManager;
1000     return usersManager;
1001 }
1002 
GetCurSessionListForFront(int32_t userId)1003 inline std::shared_ptr<std::list<sptr<AVSessionItem>>> AVSessionService::GetCurSessionListForFront(int32_t userId)
1004 {
1005     return GetUsersManager().GetCurSessionListForFront(userId);
1006 }
1007 
1008 
GetCurKeyEventSessionList(int32_t userId)1009 inline std::shared_ptr<std::list<sptr<AVSessionItem>>> AVSessionService::GetCurKeyEventSessionList(int32_t userId)
1010 {
1011     return GetUsersManager().GetCurSessionListForKeyEvent(userId);
1012 }
1013 
AllocSessionId()1014 std::string AVSessionService::AllocSessionId()
1015 {
1016     auto curNum = sessionSeqNum_++;
1017     std::string id = std::to_string(GetCallingPid()) + "-" + std::to_string(GetCallingUid()) + "-" +
1018                      std::to_string(curNum);
1019 
1020     HashCalculator hashCalculator;
1021     CHECK_AND_RETURN_RET_LOG(hashCalculator.Init() == AVSESSION_SUCCESS, "", "hash init failed");
1022     CHECK_AND_RETURN_RET_LOG(hashCalculator.Update(std::vector<uint8_t>(id.begin(), id.end())) == AVSESSION_SUCCESS,
1023                              "", "hash update failed");
1024     std::vector<uint8_t> hash;
1025     CHECK_AND_RETURN_RET_LOG(hashCalculator.GetResult(hash) == AVSESSION_SUCCESS, "", "hash get result failed");
1026 
1027     std::stringstream stream;
1028     for (const auto byte : hash) {
1029         stream << std::uppercase << std::hex << std::setfill('0') << std::setw(allocSpace) << static_cast<int>(byte);
1030     }
1031     return stream.str();
1032 }
1033 
AbilityHasSession(pid_t pid)1034 bool AVSessionService::AbilityHasSession(pid_t pid)
1035 {
1036     std::lock_guard lockGuard(sessionServiceLock_);
1037     return GetContainer().PidHasSession(pid);
1038 }
1039 
GetPresentController(pid_t pid,const std::string & sessionId)1040 sptr<AVControllerItem> AVSessionService::GetPresentController(pid_t pid, const std::string& sessionId)
1041 {
1042     std::lock_guard lockGuard(sessionServiceLock_);
1043     auto it = controllers_.find(pid);
1044     if (it != controllers_.end()) {
1045         for (const auto& controller: it->second) {
1046             if (controller != nullptr && controller->HasSession(sessionId)) {
1047                 return controller;
1048             }
1049         }
1050     }
1051     SLOGI("Not found controller for pid:%{public}d, sessionId:%{public}s.", pid,
1052         AVSessionUtils::GetAnonySessionId(sessionId).c_str());
1053     return nullptr;
1054 }
1055 
NotifySessionCreate(const AVSessionDescriptor & descriptor)1056 void AVSessionService::NotifySessionCreate(const AVSessionDescriptor& descriptor)
1057 {
1058     std::lock_guard lockGuard(sessionListenersLock_);
1059     auto audioSystemManager = AudioStandard::AudioSystemManager::GetInstance();
1060     if (audioSystemManager != nullptr) {
1061         auto ret = audioSystemManager->NotifySessionStateChange(descriptor.uid_, descriptor.pid_, true);
1062         if (ret != AVSESSION_SUCCESS) {
1063             SLOGE("NotifySessionStateChange failed, uid = %{public}d, pid = %{public}d, ret = %{public}d",
1064                 descriptor.uid_, descriptor.pid_, ret);
1065         }
1066     } else {
1067         SLOGE("AudioSystemManager is nullptr");
1068     }
1069     std::map<pid_t, sptr<ISessionListener>> listenerMap = GetUsersManager().GetSessionListener();
1070 #ifdef START_STOP_ON_DEMAND_ENABLE
1071         PublishEvent(mediaPlayStateTrue);
1072 #endif
1073     for (const auto& [pid, listener] : listenerMap) {
1074         AVSESSION_TRACE_SYNC_START("AVSessionService::OnSessionCreate");
1075         if (listener != nullptr) {
1076             listener->OnSessionCreate(descriptor);
1077         }
1078     }
1079     std::map<pid_t, sptr<ISessionListener>> listenerMapForAll = GetUsersManager().GetSessionListenerForAllUsers();
1080     for (const auto& [pid, listener] : listenerMapForAll) {
1081         AVSESSION_TRACE_SYNC_START("AVSessionService::OnSessionCreate");
1082         if (listener != nullptr) {
1083             listener->OnSessionCreate(descriptor);
1084         }
1085     }
1086 
1087     {
1088         std::lock_guard lockGuard(migrateListenersLock_);
1089         for (const auto& listener : innerSessionListeners_) {
1090             if (listener != nullptr) {
1091                 listener->OnSessionCreate(descriptor);
1092             }
1093         }
1094     }
1095 }
1096 
NotifySessionRelease(const AVSessionDescriptor & descriptor)1097 void AVSessionService::NotifySessionRelease(const AVSessionDescriptor& descriptor)
1098 {
1099     std::lock_guard lockGuard(sessionListenersLock_);
1100     auto audioSystemManager = AudioStandard::AudioSystemManager::GetInstance();
1101     if (audioSystemManager != nullptr) {
1102         auto ret = audioSystemManager->NotifySessionStateChange(descriptor.uid_, descriptor.pid_, false);
1103         if (ret != AVSESSION_SUCCESS) {
1104             SLOGE("NotifySessionStateChange failed, uid = %{public}d, pid = %{public}d, ret = %{public}d",
1105                 descriptor.uid_, descriptor.pid_, ret);
1106         }
1107     } else {
1108         SLOGE("AudioSystemManager is nullptr");
1109     }
1110     auto ret = BackgroundTaskMgr::BackgroundTaskMgrHelper::AVSessionNotifyUpdateNotification(
1111         descriptor.uid_, descriptor.pid_, false);
1112     if (ret != AVSESSION_SUCCESS) {
1113         SLOGE("AVSessionNotifyUpdateNotification failed, uid = %{public}d, pid = %{public}d, ret = %{public}d",
1114             descriptor.uid_, descriptor.pid_, ret);
1115     }
1116     std::map<pid_t, sptr<ISessionListener>> listenerMap = GetUsersManager().GetSessionListener(descriptor.userId_);
1117     SLOGI("NotifySessionRelease for user:%{public}d|listenerSize:%{public}d",
1118         descriptor.userId_, static_cast<int>(listenerMap.size()));
1119     for (const auto& [pid, listener] : listenerMap) {
1120         if (listener != nullptr) {
1121             listener->OnSessionRelease(descriptor);
1122         }
1123     }
1124     std::map<pid_t, sptr<ISessionListener>> listenerMapForAll = GetUsersManager().GetSessionListenerForAllUsers();
1125     for (const auto& [pid, listener] : listenerMapForAll) {
1126         if (listener != nullptr) {
1127             listener->OnSessionRelease(descriptor);
1128         }
1129     }
1130 
1131     {
1132         std::lock_guard lockGuard(migrateListenersLock_);
1133         for (const auto& listener : innerSessionListeners_) {
1134             if (listener != nullptr) {
1135                 listener->OnSessionRelease(descriptor);
1136             }
1137         }
1138     }
1139 }
1140 
NotifyTopSessionChanged(const AVSessionDescriptor & descriptor)1141 void AVSessionService::NotifyTopSessionChanged(const AVSessionDescriptor& descriptor)
1142 {
1143     std::lock_guard lockGuard(sessionListenersLock_);
1144     std::map<pid_t, sptr<ISessionListener>> listenerMap = GetUsersManager().GetSessionListener();
1145     for (const auto& [pid, listener] : listenerMap) {
1146         AVSESSION_TRACE_SYNC_START("AVSessionService::OnTopSessionChange");
1147         if (listener != nullptr) {
1148             listener->OnTopSessionChange(descriptor);
1149         }
1150     }
1151     std::map<pid_t, sptr<ISessionListener>> listenerMapForAll = GetUsersManager().GetSessionListenerForAllUsers();
1152     for (const auto& [pid, listener] : listenerMapForAll) {
1153         AVSESSION_TRACE_SYNC_START("AVSessionService::OnTopSessionChange");
1154         if (listener != nullptr) {
1155             listener->OnTopSessionChange(descriptor);
1156         }
1157     }
1158 
1159     {
1160         std::lock_guard lockGuard(migrateListenersLock_);
1161         for (const auto& listener : innerSessionListeners_) {
1162             if (listener != nullptr) {
1163                 listener->OnTopSessionChange(descriptor);
1164             }
1165         }
1166     }
1167 }
1168 
LowQualityCheck(int32_t uid,int32_t pid,AudioStandard::StreamUsage streamUsage,AudioStandard::RendererState rendererState)1169 void AVSessionService::LowQualityCheck(int32_t uid, int32_t pid, AudioStandard::StreamUsage streamUsage,
1170     AudioStandard::RendererState rendererState)
1171 {
1172     sptr<AVSessionItem> session = GetContainer().GetSessionByUid(uid);
1173     CHECK_AND_RETURN_LOG(session != nullptr, "session not exist for LowQualityCheck");
1174 
1175     AVMetaData meta = session->GetMetaDataWithoutImg();
1176     bool hasTitle = !meta.GetTitle().empty();
1177     bool hasImage = meta.GetMediaImage() != nullptr || !meta.GetMediaImageUri().empty();
1178     if ((hasTitle || hasImage) && (session->GetSupportCommand().size() != 0)) {
1179         SLOGD("LowQualityCheck pass for %{public}s, return", session->GetBundleName().c_str());
1180         return;
1181     }
1182     int32_t commandQuality = 0;
1183     for (auto cmd : session->GetSupportCommand()) {
1184         auto it = cmdToOffsetMap_.find(cmd);
1185         if (it != cmdToOffsetMap_.end()) {
1186             commandQuality += (1 << it->second);
1187         }
1188     }
1189     SLOGD("LowQualityCheck report for %{public}s", session->GetBundleName().c_str());
1190     AVSessionSysEvent::BackControlReportInfo reportInfo;
1191     reportInfo.bundleName_ = session->GetBundleName();
1192     reportInfo.streamUsage_ = streamUsage;
1193     reportInfo.isBack_ = AppManagerAdapter::GetInstance().IsAppBackground(uid, pid);
1194     reportInfo.playDuration_ = -1;
1195     reportInfo.isAudioActive_ = true;
1196     reportInfo.metaDataQuality_ = (hasTitle << 1) + hasImage;
1197     reportInfo.cmdQuality_ = commandQuality;
1198     reportInfo.playbackState_ = session->GetPlaybackState().GetState();
1199     AVSessionSysEvent::GetInstance().AddLowQualityInfo(reportInfo);
1200 }
1201 
PlayStateCheck(int32_t uid,AudioStandard::StreamUsage streamUsage,AudioStandard::RendererState rState)1202 void AVSessionService::PlayStateCheck(int32_t uid, AudioStandard::StreamUsage streamUsage,
1203     AudioStandard::RendererState rState)
1204 {
1205     sptr<AVSessionItem> session = GetContainer().GetSessionByUid(uid);
1206     CHECK_AND_RETURN_LOG(session != nullptr, "session not exist for LowQualityCheck");
1207 
1208     AVPlaybackState aState = session->GetPlaybackState();
1209     if ((rState == AudioStandard::RENDERER_RUNNING && aState.GetState() != AVPlaybackState::PLAYBACK_STATE_PLAY) ||
1210         ((rState == AudioStandard::RENDERER_PAUSED || rState == AudioStandard::RENDERER_STOPPED) &&
1211         aState.GetState() == AVPlaybackState::PLAYBACK_STATE_PLAY)) {
1212         SLOGD("PlayStateCheck report for %{public}s", session->GetBundleName().c_str());
1213         HISYSEVENT_FAULT("AVSESSION_WRONG_STATE",
1214             "BUNDLE_NAME", session->GetBundleName(),
1215             "RENDERER_STATE", rState,
1216             "AVSESSION_STATE", aState.GetState());
1217     }
1218 }
1219 
NotifyBackgroundReportCheck(const int32_t uid,const int32_t pid,AudioStandard::StreamUsage streamUsage,AudioStandard::RendererState rendererState)1220 void AVSessionService::NotifyBackgroundReportCheck(const int32_t uid, const int32_t pid,
1221     AudioStandard::StreamUsage streamUsage, AudioStandard::RendererState rendererState)
1222 {
1223     // low quality check
1224     if (rendererState == AudioStandard::RENDERER_RUNNING) {
1225         AVSessionEventHandler::GetInstance().AVSessionPostTask(
1226             [this, uid, pid, streamUsage, rendererState]() {
1227                 LowQualityCheck(uid, pid, streamUsage, rendererState);
1228             }, "LowQualityCheck", lowQualityTimeout);
1229     }
1230 
1231     // error renderer state check
1232     AVSessionEventHandler::GetInstance().AVSessionPostTask(
1233         [this, uid, streamUsage, rendererState]() {
1234             PlayStateCheck(uid, streamUsage, rendererState);
1235         }, "PlayStateCheck", errorStateTimeout);
1236 }
1237 
1238 // LCOV_EXCL_START
NotifyAudioSessionCheck(const int32_t uid)1239 void AVSessionService::NotifyAudioSessionCheck(const int32_t uid)
1240 {
1241     std::lock_guard lockGuard(sessionListenersLock_);
1242     std::map<pid_t, sptr<ISessionListener>> listenerMap = GetUsersManager().GetSessionListener();
1243     for (const auto& [pid, listener] : listenerMap) {
1244         AVSESSION_TRACE_SYNC_START("AVSessionService::OnAudioSessionCheck");
1245         if (listener != nullptr) {
1246             listener->OnAudioSessionChecked(uid);
1247         }
1248     }
1249     std::map<pid_t, sptr<ISessionListener>> listenerMapForAll = GetUsersManager().GetSessionListenerForAllUsers();
1250     for (const auto& [pid, listener] : listenerMapForAll) {
1251         AVSESSION_TRACE_SYNC_START("AVSessionService::OnAudioSessionCheck");
1252         if (listener != nullptr) {
1253             listener->OnAudioSessionChecked(uid);
1254         }
1255     }
1256     {
1257         std::lock_guard lockGuard(migrateListenersLock_);
1258         for (const auto& listener : innerSessionListeners_) {
1259             if (listener != nullptr) {
1260                 listener->OnAudioSessionChecked(uid);
1261             }
1262         }
1263     }
1264 }
1265 // LCOV_EXCL_STOP
1266 
CheckAncoAudio()1267 bool AVSessionService::CheckAncoAudio()
1268 {
1269     for (const auto& session : GetContainer().GetAllSessions()) {
1270         if (session->GetBundleName() == "anco_audio") {
1271             return true;
1272         }
1273     }
1274     return false;
1275 }
1276 
1277 // LCOV_EXCL_START
HandleCallStartEvent()1278 void AVSessionService::HandleCallStartEvent()
1279 {
1280     SLOGI("Call mediaController player in sink side when cast state is connected.");
1281     AbilityConnectHelper::GetInstance().StartAbilityForegroundByCall(MEDIA_CONTROL_BUNDLENAME,
1282         MEDIA_CONTROL_ABILITYNAME);
1283 }
1284 // LCOV_EXCL_STOP
1285 
AddCapsuleServiceCallback(sptr<AVSessionItem> & sessionItem)1286 void AVSessionService::AddCapsuleServiceCallback(sptr<AVSessionItem>& sessionItem)
1287 {
1288     sessionItem->SetServiceCallbackForNtfCapsule([this](std::string sessionId, bool isMediaChange) {
1289         std::lock_guard lockGuard(sessionServiceLock_);
1290         sptr<AVSessionItem> session = GetContainer().GetSessionById(sessionId);
1291         if (session && topSession_ && (topSession_.GetRefPtr() == session.GetRefPtr())) {
1292             SLOGI("MediaCapsule topsession %{public}s updateImage", topSession_->GetBundleName().c_str());
1293             NotifySystemUI(nullptr, true, IsCapsuleNeeded() && hasMediaCapsule_.load(), isMediaChange);
1294         }
1295     });
1296 
1297     sessionItem->SetServiceCallbackForMediaSession([this](std::string sessionId, bool isPlaying, bool isMediaChange) {
1298         // only use for anco mediasession
1299         std::lock_guard lockGuard(sessionServiceLock_);
1300         sptr<AVSessionItem> session = GetContainer().GetSessionById(sessionId);
1301         CHECK_AND_RETURN_LOG(session != nullptr, "session not exist");
1302         bool isSameTop = topSession_ != nullptr && (topSession_.GetRefPtr() == session.GetRefPtr());
1303         if (isSameTop) {
1304             SLOGI("ancoCapsule topSession is %{public}s isPlaying %{public}d isMediaChange %{public}d",
1305                 topSession_->GetBundleName().c_str(), isPlaying, isMediaChange);
1306             if (!isPlaying && (isMediaCardOpen_.load() || hasRemoveEvent_.load())) {
1307                 SLOGI("ancoCapsule del isCardOpen_:%{public}d hasRemoveEvent_:%{public}d",
1308                     isMediaCardOpen_.load(), hasRemoveEvent_.load());
1309                 return;
1310             }
1311             auto hasOtherSessionPlaying = false;
1312             if (!isPlaying) {
1313                 int32_t userId = topSession_->GetUserId();
1314                 userId = userId < 0 ? GetUsersManager().GetCurrentUserId() : userId;
1315                 sptr<AVSessionItem> result = GetOtherPlayingSession(userId, "");
1316                 hasOtherSessionPlaying = result != nullptr;
1317                 HandleOtherSessionPlaying(result);
1318             }
1319             if (!hasOtherSessionPlaying) {
1320                 NotifySystemUI(nullptr, true, isPlaying && IsCapsuleNeeded(), isMediaChange);
1321             }
1322             return;
1323         }
1324         CHECK_AND_RETURN_LOG(isPlaying, "anco media session is not playing");
1325         UpdateTopSession(session);
1326         FocusSessionStrategy::FocusSessionChangeInfo sessionInfo;
1327         sessionInfo.uid = session->GetUid();
1328         sessionInfo.pid = session->GetPid();
1329         SelectFocusSession(sessionInfo);
1330         NotifySystemUI(nullptr, true, isPlaying && IsCapsuleNeeded(), isMediaChange);
1331     });
1332 }
1333 
AddCastCapsuleServiceCallback(sptr<AVSessionItem> & sessionItem)1334 void AVSessionService::AddCastCapsuleServiceCallback(sptr<AVSessionItem>& sessionItem)
1335 {
1336 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
1337     sessionItem->SetServiceCallbackForCastNtfCapsule([this](std::string sessionId, bool isPlaying, bool isChange) {
1338         std::lock_guard lockGuard(sessionServiceLock_);
1339         sptr<AVSessionItem> session = GetContainer().GetSessionById(sessionId);
1340         CHECK_AND_RETURN_LOG(session != nullptr, "castSession not exist");
1341         if (topSession_ && (topSession_.GetRefPtr() == session.GetRefPtr())) {
1342             SLOGI("MediaCapsule topSession is castSession %{public}s isPlaying %{public}d isMediaChange %{public}d",
1343                 topSession_->GetBundleName().c_str(), isPlaying, isChange);
1344             if (!isPlaying && (isMediaCardOpen_ || hasRemoveEvent_.load())) {
1345                 SLOGI("MediaCapsule casttopsession not playing isCardOpen_:%{public}d hasRemoveEvent_:%{public}d",
1346                     isMediaCardOpen_.load(), hasRemoveEvent_.load());
1347                 return;
1348             }
1349             auto hasOtherSessionPlaying = false;
1350             if (!isPlaying) {
1351                 int32_t userId = topSession_->GetUserId();
1352                 userId = userId < 0 ? GetUsersManager().GetCurrentUserId() : userId;
1353                 sptr<AVSessionItem> result = GetOtherPlayingSession(userId, "");
1354                 hasOtherSessionPlaying = result != nullptr;
1355                 HandleOtherSessionPlaying(result);
1356             }
1357             if (!hasOtherSessionPlaying) {
1358                 NotifySystemUI(nullptr, true, isPlaying && IsCapsuleNeeded(), isChange);
1359             }
1360             return;
1361         }
1362         bool castChange = topSession_ && topSession_->IsCasting() && (topSession_.GetRefPtr() != session.GetRefPtr());
1363         if ((topSession_ == nullptr || castChange) && isPlaying) {
1364             SLOGI("MediaCapsule fresh castSession %{public}s to top, isMediaChange %{public}d",
1365                 session->GetBundleName().c_str(), isChange);
1366             UpdateTopSession(session);
1367             NotifySystemUI(nullptr, true, isPlaying, isChange);
1368             bool updateOrderResult = UpdateOrder(session);
1369             CHECK_AND_RETURN_LOG(updateOrderResult, "UpdateOrder fail");
1370         }
1371     });
1372 #endif // CASTPLUS_CAST_ENGINE_ENABLE
1373 }
1374 
AddKeyEventServiceCallback(sptr<AVSessionItem> & sessionItem)1375 void AVSessionService::AddKeyEventServiceCallback(sptr<AVSessionItem>& sessionItem)
1376 {
1377     sessionItem->SetServiceCallbackForKeyEvent([this](std::string sessionId) {
1378         int32_t err = PermissionChecker::GetInstance().CheckPermission(
1379             PermissionChecker::CHECK_MEDIA_RESOURCES_PERMISSION);
1380         CHECK_AND_RETURN_LOG(err == AVSESSION_SUCCESS, "Add KeyEventSession, CheckPermission failed!");
1381         std::lock_guard lockGuard(sessionServiceLock_);
1382         sptr<AVSessionItem> session = GetContainer().GetSessionById(sessionId);
1383         CHECK_AND_RETURN_LOG(session != nullptr, "session not exist for KeyEvent");
1384         {
1385             std::lock_guard lockGuard(keyEventListLock_);
1386             int userId = session->GetUserId();
1387             std::shared_ptr<std::list<sptr<AVSessionItem>>> keyEventList = GetCurKeyEventSessionList(userId);
1388             CHECK_AND_RETURN_LOG(keyEventList != nullptr, "keyEventList ptr nullptr!");
1389             auto it = std::find(keyEventList->begin(), keyEventList->end(), session);
1390             if (it == keyEventList->end()) {
1391                 SLOGI("keyEventList add=%{public}s", session->GetBundleName().c_str());
1392                 keyEventList->push_front(session);
1393                 return;
1394             }
1395         }
1396     });
1397 }
1398 
ServiceCallback(sptr<AVSessionItem> & sessionItem)1399 void AVSessionService::ServiceCallback(sptr<AVSessionItem>& sessionItem)
1400 {
1401     if (sessionItem == nullptr) {
1402         SLOGE("sessionItem is null when serviceCallback");
1403         return;
1404     }
1405     sessionItem->SetServiceCallbackForRelease([this](AVSessionItem& session) {
1406         HandleSessionRelease(session.GetDescriptor().sessionId_, true);
1407     });
1408     sessionItem->SetServiceCallbackForAVQueueInfo([this](AVSessionItem& session) {
1409         AddAvQueueInfoToFile(session);
1410     });
1411     sessionItem->SetServiceCallbackForCallStart([this](AVSessionItem& session) {
1412         HandleCallStartEvent();
1413     });
1414     sessionItem->SetServiceCallbackForUpdateSession([this](std::string sessionId, bool isAdd) {
1415         if (sessionId == sessionCastState_) {
1416             std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront();
1417             UpdateLocalFrontSession(sessionListForFront);
1418             return;
1419         }
1420         std::lock_guard lockGuard(sessionServiceLock_);
1421         sptr<AVSessionItem> session = GetContainer().GetSessionById(sessionId);
1422         CHECK_AND_RETURN_LOG(session != nullptr, "session not exist for UpdateFrontSession");
1423         UpdateFrontSession(session, isAdd);
1424     });
1425     sessionItem->SetServiceCallbackForUpdateExtras([this](std::string sessionId) {
1426         std::lock_guard lockGuard(sessionServiceLock_);
1427         sptr<AVSessionItem> session = GetContainer().GetSessionById(sessionId);
1428         CHECK_AND_RETURN_LOG(session != nullptr, "session not exist for UpdateFrontSession");
1429         if (topSession_ && topSession_.GetRefPtr() == session.GetRefPtr()) {
1430             AVSessionDescriptor selectSession = session->GetDescriptor();
1431             NotifySystemUI(&selectSession, true, IsCapsuleNeeded() && hasMediaCapsule_.load(), false);
1432         }
1433     });
1434     AddCapsuleServiceCallback(sessionItem);
1435     AddCastCapsuleServiceCallback(sessionItem);
1436     AddKeyEventServiceCallback(sessionItem);
1437 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
1438     sessionItem->SetServiceCallbackForStream([this](std::string sessionId) {
1439         sptr<AVSessionItem> session = GetContainer().GetSessionById(sessionId);
1440         CHECK_AND_RETURN_LOG(session != nullptr, "Session not exist");
1441         MirrorToStreamCast(session);
1442     });
1443 #endif // CASTPLUS_CAST_ENGINE_ENABLE
1444 }
1445 
GetIntValueFromJson(const std::string & extraInfo,const char * key)1446 static int32_t GetIntValueFromJson(const std::string& extraInfo, const char* key)
1447 {
1448     auto defaultValue = 0;
1449     cJSON* jsonData = nullptr;
1450     if (!SoftbusSessionUtils::TransferStrToJson(extraInfo, jsonData)) {
1451         SLOGE("json parse fail");
1452         return defaultValue;
1453     }
1454     int32_t value = SoftbusSessionUtils::GetIntFromJson(jsonData, key);
1455     cJSON_Delete(jsonData);
1456     return value;
1457 }
1458 
CreateNewSessionWithExtra(const std::string & tag,int32_t type,const std::string & extraInfo,bool thirdPartyApp,const AppExecFwk::ElementName & elementName)1459 sptr<AVSessionItem> AVSessionService::CreateNewSessionWithExtra(const std::string& tag, int32_t type,
1460                                                                 const std::string& extraInfo, bool thirdPartyApp,
1461                                                                 const AppExecFwk::ElementName& elementName)
1462 {
1463     SLOGI("%{public}s %{public}d %{public}s %{public}s thirdPartyApp=%{public}d", tag.c_str(), type,
1464           elementName.GetBundleName().c_str(), elementName.GetAbilityName().c_str(), thirdPartyApp);
1465     AVSessionDescriptor descriptor;
1466     descriptor.sessionId_ = AllocSessionId();
1467     if (descriptor.sessionId_.empty()) {
1468         SLOGE("alloc session id failed");
1469         return nullptr;
1470     }
1471     descriptor.userId_ = GetUsersManager().GetCurrentUserId();
1472     descriptor.sessionTag_ = tag;
1473     descriptor.sessionType_ = type;
1474     descriptor.elementName_ = elementName;
1475     descriptor.isThirdPartyApp_ = thirdPartyApp;
1476     descriptor.index_ = GetIntValueFromJson(extraInfo, "index");
1477 
1478     sptr<AVSessionItem> result = new(std::nothrow) AVSessionItem(descriptor, descriptor.userId_);
1479     if (result == nullptr) {
1480         return nullptr;
1481     }
1482     result->SetPid(GetCallingPid());
1483     result->SetUid(GetCallingUid());
1484     ServiceCallback(result);
1485 
1486     OutputDeviceInfo outputDeviceInfo;
1487     DeviceInfo deviceInfo;
1488     deviceInfo.castCategory_ = AVCastCategory::CATEGORY_LOCAL;
1489     deviceInfo.deviceId_ = "0";
1490     deviceInfo.deviceName_ = "LocalDevice";
1491     outputDeviceInfo.deviceInfos_.emplace_back(deviceInfo);
1492     result->SetOutputDevice(outputDeviceInfo);
1493 
1494     return result;
1495 }
1496 
CreateNewSession(const std::string & tag,int32_t type,bool thirdPartyApp,const AppExecFwk::ElementName & elementName)1497 sptr<AVSessionItem> AVSessionService::CreateNewSession(const std::string& tag, int32_t type, bool thirdPartyApp,
1498                                                        const AppExecFwk::ElementName& elementName)
1499 {
1500     SLOGI("%{public}s %{public}d %{public}s %{public}s thirdPartyApp=%{public}d", tag.c_str(), type,
1501           elementName.GetBundleName().c_str(), elementName.GetAbilityName().c_str(), thirdPartyApp);
1502     AVSessionDescriptor descriptor;
1503     descriptor.sessionId_ = AllocSessionId();
1504     if (descriptor.sessionId_.empty()) {
1505         SLOGE("alloc session id failed");
1506         return nullptr;
1507     }
1508     descriptor.userId_ = GetUsersManager().GetCurrentUserId();
1509     descriptor.sessionTag_ = tag;
1510     descriptor.sessionType_ = type;
1511     descriptor.elementName_ = elementName;
1512     descriptor.isThirdPartyApp_ = thirdPartyApp;
1513 
1514     sptr<AVSessionItem> result = new(std::nothrow) AVSessionItem(descriptor, descriptor.userId_);
1515     if (result == nullptr) {
1516         return nullptr;
1517     }
1518     result->SetPid(GetCallingPid());
1519     result->SetUid(GetCallingUid());
1520     ServiceCallback(result);
1521 
1522     OutputDeviceInfo outputDeviceInfo;
1523     DeviceInfo deviceInfo;
1524     deviceInfo.castCategory_ = AVCastCategory::CATEGORY_LOCAL;
1525     deviceInfo.deviceId_ = "0";
1526     deviceInfo.deviceName_ = "LocalDevice";
1527     outputDeviceInfo.deviceInfos_.emplace_back(deviceInfo);
1528     result->SetOutputDevice(outputDeviceInfo);
1529 
1530     return result;
1531 }
1532 
IsParamInvalid(const std::string & tag,int32_t type,const AppExecFwk::ElementName & elementName)1533 bool AVSessionService::IsParamInvalid(const std::string& tag, int32_t type, const AppExecFwk::ElementName& elementName)
1534 {
1535     if (tag.empty()) {
1536         SLOGE("tag is empty when create session");
1537         return false;
1538     }
1539     if (type != AVSession::SESSION_TYPE_AUDIO && type != AVSession::SESSION_TYPE_VIDEO
1540         && type != AVSession::SESSION_TYPE_VOICE_CALL && type != AVSession::SESSION_TYPE_VIDEO_CALL) {
1541         SLOGE("type is invalid when create session");
1542         return false;
1543     }
1544     if (elementName.GetBundleName().empty() || elementName.GetAbilityName().empty()) {
1545         SLOGE("element is invalid when create session");
1546         return false;
1547     }
1548     if (GetCallingUid() == audioBrokerUid && tag == "ancoMediaSession") {
1549         return true;
1550     }
1551     std::regex nameRegex("[A-Za-z\\w\\.]*");
1552     if (!std::regex_match(elementName.GetBundleName(), nameRegex)) {
1553         SLOGE("err regex when create session, bundleName=%{public}s", (elementName.GetBundleName()).c_str());
1554         return false;
1555     }
1556     if (!std::regex_match(elementName.GetAbilityName(), nameRegex)) {
1557         SLOGE("err regex when create session, abilityName=%{public}s", (elementName.GetAbilityName()).c_str());
1558         return false;
1559     }
1560 
1561     return true;
1562 }
1563 
CheckAndUpdateAncoMediaSession(const AppExecFwk::ElementName & elementName)1564 void AVSessionService::CheckAndUpdateAncoMediaSession(const AppExecFwk::ElementName& elementName)
1565 {
1566     auto uid = GetCallingUid();
1567     CHECK_AND_RETURN_LOG(uid == audioBrokerUid, "not broker uid");
1568     sptr<AVSessionItem> session = GetContainer().GetSessionByUid(uid);
1569     CHECK_AND_RETURN_LOG(session != nullptr, "anco media session is null");
1570     auto res = GetUsersManager().UpdateSessionForCurrentUser(session->GetPid(), session->GetAbilityName(),
1571         elementName.GetAbilityName(), session);
1572     CHECK_AND_RETURN_LOG(res == AVSESSION_SUCCESS, "update media session fail");
1573     session->UpdateSessionElement(elementName);
1574     SLOGI("updatenewsession %{public}s %{public}s", elementName.GetBundleName().c_str(),
1575         elementName.GetAbilityName().c_str());
1576 }
1577 
CreateSessionInner(const std::string & tag,int32_t type,bool thirdPartyApp,const AppExecFwk::ElementName & elementName,sptr<AVSessionItem> & sessionItem)1578 int32_t AVSessionService::CreateSessionInner(const std::string& tag, int32_t type, bool thirdPartyApp,
1579                                              const AppExecFwk::ElementName& elementName,
1580                                              sptr<AVSessionItem>& sessionItem)
1581 {
1582     if (!IsParamInvalid(tag, type, elementName)) {
1583         return ERR_INVALID_PARAM;
1584     }
1585     auto pid = GetCallingPid();
1586     std::lock_guard lockGuard(sessionServiceLock_);
1587     if (AbilityHasSession(pid)) {
1588         SLOGE("process %{public}d %{public}s already has one session", pid, elementName.GetAbilityName().c_str());
1589         CheckAndUpdateAncoMediaSession(elementName);
1590         return ERR_SESSION_IS_EXIST;
1591     }
1592 
1593     sptr<AVSessionItem> result = CreateNewSession(tag, type, thirdPartyApp, elementName);
1594     if (result == nullptr) {
1595         SLOGE("create new session failed");
1596         if (dumpHelper_ != nullptr) {
1597             dumpHelper_->SetErrorInfo("  AVSessionService::CreateSessionInner  create new session failed");
1598         }
1599         HISYSEVENT_FAULT("CONTROL_COMMAND_FAILED", "CALLER_PID", pid, "TAG", tag, "TYPE", type, "BUNDLE_NAME",
1600             elementName.GetBundleName(), "ERROR_MSG", "avsessionservice createsessioninner create new session failed");
1601         return ERR_NO_MEMORY;
1602     }
1603     if (GetUsersManager().AddSessionForCurrentUser(pid, elementName.GetAbilityName(), result) != AVSESSION_SUCCESS) {
1604         SLOGE("session num exceed max");
1605         return ERR_SESSION_EXCEED_MAX;
1606     }
1607 
1608     HISYSEVENT_ADD_LIFE_CYCLE_INFO(elementName.GetBundleName(),
1609         AppManagerAdapter::GetInstance().IsAppBackground(GetCallingUid(), GetCallingPid()), type, true);
1610 
1611     NotifySessionCreate(result->GetDescriptor());
1612     sessionItem = result;
1613 
1614     std::lock_guard frontLockGuard(sessionFrontLock_);
1615     std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront();
1616     CHECK_AND_RETURN_RET_LOG(sessionListForFront != nullptr, AVSESSION_ERROR, "sessionListForFront ptr nullptr!");
1617     auto it = std::find(sessionListForFront->begin(), sessionListForFront->end(), sessionItem);
1618     if ((type == AVSession::SESSION_TYPE_VOICE_CALL || type == AVSession::SESSION_TYPE_VIDEO_CALL) &&
1619         it == sessionListForFront->end()) {
1620         SLOGI(" front session add voice_call session=%{public}s", sessionItem->GetBundleName().c_str());
1621         sessionListForFront->push_front(sessionItem);
1622     }
1623 
1624 #ifdef ENABLE_AVSESSION_SYSEVENT_CONTROL
1625         ReportSessionState(sessionItem, SessionState::STATE_CREATE);
1626 #endif
1627 
1628     return AVSESSION_SUCCESS;
1629 }
1630 
CreateSessionInnerWithExtra(const std::string & tag,int32_t type,const std::string & extra,bool thirdPartyApp,const AppExecFwk::ElementName & elementName,sptr<AVSessionItem> & sessionItem)1631 int32_t AVSessionService::CreateSessionInnerWithExtra(const std::string& tag, int32_t type, const std::string& extra,
1632                                                       bool thirdPartyApp, const AppExecFwk::ElementName& elementName,
1633                                                       sptr<AVSessionItem>& sessionItem)
1634 {
1635     if (!IsParamInvalid(tag, type, elementName)) {
1636         return ERR_INVALID_PARAM;
1637     }
1638     auto pid = GetCallingPid();
1639     std::lock_guard lockGuard(sessionServiceLock_);
1640     if (AbilityHasSession(pid)) {
1641         SLOGE("process %{public}d %{public}s already has one session", pid, elementName.GetAbilityName().c_str());
1642         CheckAndUpdateAncoMediaSession(elementName);
1643         return ERR_SESSION_IS_EXIST;
1644     }
1645 
1646     sptr<AVSessionItem> result = CreateNewSession(tag, type, thirdPartyApp, elementName);
1647     if (result == nullptr) {
1648         SLOGE("create new session failed");
1649         if (dumpHelper_ != nullptr) {
1650             dumpHelper_->SetErrorInfo("AVSessionService::CreateSessionInner  create new session failed");
1651         }
1652         HISYSEVENT_FAULT("CONTROL_COMMAND_FAILED", "CALLER_PID", pid, "TAG", tag, "TYPE", type, "BUNDLE_NAME",
1653             elementName.GetBundleName(), "ERROR_MSG", "avsessionservice createsessioninner create new session failed");
1654         return ERR_NO_MEMORY;
1655     }
1656     if (GetUsersManager().AddSessionForCurrentUser(pid, elementName.GetAbilityName(), result) != AVSESSION_SUCCESS) {
1657         SLOGE("session num exceed max");
1658         return ERR_SESSION_EXCEED_MAX;
1659     }
1660 
1661     HISYSEVENT_ADD_LIFE_CYCLE_INFO(elementName.GetBundleName(),
1662         AppManagerAdapter::GetInstance().IsAppBackground(GetCallingUid(), GetCallingPid()), type, true);
1663 
1664     NotifySessionCreate(result->GetDescriptor());
1665     sessionItem = result;
1666 
1667     std::lock_guard frontLockGuard(sessionFrontLock_);
1668     std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront();
1669     CHECK_AND_RETURN_RET_LOG(sessionListForFront != nullptr, AVSESSION_ERROR, "sessionListForFront ptr nullptr!");
1670     auto it = std::find(sessionListForFront->begin(), sessionListForFront->end(), sessionItem);
1671     if ((type == AVSession::SESSION_TYPE_VOICE_CALL || type == AVSession::SESSION_TYPE_VIDEO_CALL) &&
1672         it == sessionListForFront->end()) {
1673         SLOGI(" front session add voice_call session=%{public}s", sessionItem->GetBundleName().c_str());
1674         sessionListForFront->push_front(sessionItem);
1675     }
1676 
1677 #ifdef ENABLE_AVSESSION_SYSEVENT_CONTROL
1678         ReportSessionState(sessionItem, SessionState::STATE_CREATE);
1679 #endif
1680 
1681     return AVSESSION_SUCCESS;
1682 }
1683 
CreateSessionInner(const std::string & tag,int32_t type,bool thirdPartyApp,const AppExecFwk::ElementName & elementName)1684 sptr<AVSessionItem> AVSessionService::CreateSessionInner(const std::string& tag, int32_t type, bool thirdPartyApp,
1685                                                          const AppExecFwk::ElementName& elementName)
1686 {
1687     sptr<AVSessionItem> sessionItem;
1688     auto res = CreateSessionInner(tag, type, thirdPartyApp, elementName, sessionItem);
1689     CHECK_AND_RETURN_RET_LOG(res == AVSESSION_SUCCESS, nullptr, "create avSessionItem failed");
1690     return sessionItem;
1691 }
1692 
ReportSessionInfo(const sptr<AVSessionItem> & session,int32_t res)1693 void AVSessionService::ReportSessionInfo(const sptr <AVSessionItem>& session, int32_t res)
1694 {
1695     std::string sessionId = "";
1696     std::string sessionTag = "";
1697     std::string sessionType = "";
1698     std::string bundleName = "";
1699     std::string apiParamString = "";
1700     if (session != nullptr) {
1701         sessionId = AVSessionUtils::GetAnonySessionId(session->GetDescriptor().sessionId_);
1702         sessionTag = session->GetDescriptor().sessionTag_;
1703         sessionType = session->GetSessionType();
1704         bundleName = session->GetDescriptor().elementName_.GetBundleName();
1705         apiParamString = "abilityName: " +
1706             session->GetDescriptor().elementName_.GetAbilityName() + ","
1707             + "moduleName: " + session->GetDescriptor().elementName_.GetModuleName();
1708     }
1709     std::string errMsg = (res == AVSESSION_SUCCESS) ? "SUCCESS" : "create session failed";
1710     HISYSEVENT_BEHAVIOR("SESSION_API_BEHAVIOR",
1711         "API_NAME", "CreateSession",
1712         "BUNDLE_NAME", bundleName,
1713         "SESSION_ID",  sessionId,
1714         "SESSION_TAG", sessionTag,
1715         "SESSION_TYPE", sessionType,
1716         "API_PARAM", apiParamString,
1717         "ERROR_CODE", res,
1718         "ERROR_MSG", errMsg);
1719 }
1720 
CreateSessionInner(const std::string & tag,int32_t type,const AppExecFwk::ElementName & elementName,sptr<IRemoteObject> & object)1721 int32_t AVSessionService::CreateSessionInner(const std::string& tag, int32_t type,
1722                                              const AppExecFwk::ElementName& elementName,
1723                                              sptr<IRemoteObject>& object)
1724 {
1725     sptr<AVSessionItem> session;
1726     auto res = CreateSessionInner(tag, type,
1727         PermissionChecker::GetInstance().CheckPermission(PermissionChecker::CHECK_SYSTEM_PERMISSION),
1728         elementName, session);
1729     CHECK_AND_RETURN_RET_LOG(res == AVSESSION_SUCCESS, res, "create session fail");
1730 
1731     std::string supportModule;
1732     std::string profile;
1733     if (BundleStatusAdapter::GetInstance().IsSupportPlayIntent(elementName.GetBundleName(), supportModule, profile)) {
1734         SLOGI("bundleName=%{public}s support play intent, refreshSortFile", elementName.GetBundleName().c_str());
1735         SaveSessionInfoInFile(session->GetSessionId(), session->GetSessionType(), elementName);
1736     }
1737 
1738     {
1739         std::lock_guard lockGuard1(abilityManagerLock_);
1740         std::string bundleName = session->GetDescriptor().elementName_.GetBundleName();
1741         std::string abilityName = session->GetDescriptor().elementName_.GetAbilityName();
1742         auto it = abilityManager_.find(bundleName + abilityName);
1743         if (it != abilityManager_.end() && it->second != nullptr) {
1744             it->second->StartAbilityByCallDone(session->GetDescriptor().sessionId_);
1745         }
1746     }
1747 
1748     object = session;
1749     ReportSessionInfo(session, static_cast<int32_t>(res));
1750 
1751     {
1752         std::lock_guard lockGuard(isAllSessionCastLock_);
1753         CHECK_AND_RETURN_RET_LOG(isAllSessionCast_, AVSESSION_SUCCESS, "no need to cast");
1754     }
1755     CHECK_AND_RETURN_RET_LOG(CastAudioForNewSession(session) == AVSESSION_SUCCESS,
1756                              AVSESSION_SUCCESS, "cast new session error");
1757     return res;
1758 }
1759 
CreateSessionInnerWithExtra(const std::string & tag,int32_t type,const std::string & extraInfo,const AppExecFwk::ElementName & elementName,sptr<IRemoteObject> & object)1760 int32_t AVSessionService::CreateSessionInnerWithExtra(const std::string& tag, int32_t type,
1761                                                       const std::string& extraInfo,
1762                                                       const AppExecFwk::ElementName& elementName,
1763                                                       sptr<IRemoteObject>& object)
1764 {
1765     sptr<AVSessionItem> session;
1766     auto res = CreateSessionInnerWithExtra(tag, type, extraInfo,
1767         PermissionChecker::GetInstance().CheckPermission(PermissionChecker::CHECK_SYSTEM_PERMISSION),
1768         elementName, session);
1769     CHECK_AND_RETURN_RET_LOG(res == AVSESSION_SUCCESS, res, "create session fail");
1770 
1771     std::string supportModule;
1772     std::string profile;
1773     if (BundleStatusAdapter::GetInstance().IsSupportPlayIntent(elementName.GetBundleName(), supportModule, profile)) {
1774         SaveSessionInfoInFile(session->GetSessionId(), session->GetSessionType(), elementName);
1775     }
1776 
1777     {
1778         std::lock_guard lockGuard1(abilityManagerLock_);
1779         std::string bundleName = session->GetDescriptor().elementName_.GetBundleName();
1780         std::string abilityName = session->GetDescriptor().elementName_.GetAbilityName();
1781         auto it = abilityManager_.find(bundleName + abilityName);
1782         if (it != abilityManager_.end() && it->second != nullptr) {
1783             it->second->StartAbilityByCallDone(session->GetDescriptor().sessionId_);
1784         }
1785     }
1786 
1787     object = session;
1788     ReportSessionInfo(session, static_cast<int32_t>(res));
1789 
1790     {
1791         std::lock_guard lockGuard(isAllSessionCastLock_);
1792         CHECK_AND_RETURN_RET_LOG(isAllSessionCast_, AVSESSION_SUCCESS, "no need to cast");
1793     }
1794     CHECK_AND_RETURN_RET_LOG(CastAudioForNewSession(session) == AVSESSION_SUCCESS,
1795                              AVSESSION_SUCCESS, "cast new session error");
1796     return res;
1797 }
1798 
CreateSessionInner(const std::string & tag,int32_t type,const AppExecFwk::ElementName & elementName)1799 sptr <IRemoteObject> AVSessionService::CreateSessionInner(const std::string& tag, int32_t type,
1800                                                           const AppExecFwk::ElementName& elementName)
1801 {
1802     sptr<IRemoteObject> object;
1803     auto res = CreateSessionInner(tag, type, elementName, object);
1804     CHECK_AND_RETURN_RET_LOG(res == AVSESSION_SUCCESS, nullptr, "create session fail");
1805     return object;
1806 }
1807 
IsCapsuleNeeded()1808 bool AVSessionService::IsCapsuleNeeded()
1809 {
1810     CHECK_AND_RETURN_RET_LOG(topSession_ != nullptr && topSession_->GetUid() != audioBrokerUid,
1811         false, "audio broker capsule");
1812     return topSession_->GetSessionType() == "audio" || topSession_->IsCasting();
1813 }
1814 
1815 // LCOV_EXCL_START
InsertSessionItemToCJSONAndPrint(const std::string & sessionId,const std::string & sessionType,const AppExecFwk::ElementName & elementName,cJSON * valuesArray)1816 bool AVSessionService::InsertSessionItemToCJSONAndPrint(const std::string& sessionId, const std::string& sessionType,
1817     const AppExecFwk::ElementName& elementName, cJSON* valuesArray)
1818 {
1819     CHECK_AND_RETURN_RET_LOG(valuesArray != nullptr, false, "valuesArray get null");
1820     cJSON* newValue = cJSON_CreateObject();
1821     CHECK_AND_RETURN_RET_LOG(newValue != nullptr, false, "newValue get null");
1822     cJSON_AddStringToObject(newValue, "sessionId", sessionId.c_str());
1823     cJSON_AddStringToObject(newValue, "bundleName", elementName.GetBundleName().c_str());
1824     cJSON_AddStringToObject(newValue, "abilityName", elementName.GetAbilityName().c_str());
1825     cJSON_AddStringToObject(newValue, "sessionType", sessionType.c_str());
1826 
1827     if (cJSON_GetArraySize(valuesArray) <= 0) {
1828         cJSON_AddItemToArray(valuesArray, newValue);
1829     } else {
1830         cJSON_InsertItemInArray(valuesArray, 0, newValue);
1831     }
1832     if (cJSON_IsInvalid(valuesArray)) {
1833         SLOGE("get newValueArray invalid");
1834         return false;
1835     }
1836     std::string newSortContentStr = DoCJSONArrayTransformToString(valuesArray);
1837     if (!SaveStringToFileEx(GetAVSortDir(), newSortContentStr)) {
1838         SLOGE("SaveStringToFileEx failed when refresh focus session sort!");
1839     }
1840     return true;
1841 }
1842 // LCOV_EXCL_STOP
1843 
1844 // LCOV_EXCL_START
SaveSessionInfoInFile(const std::string & sessionId,const std::string & sessionType,const AppExecFwk::ElementName & elementName)1845 void AVSessionService::SaveSessionInfoInFile(const std::string& sessionId, const std::string& sessionType,
1846                                              const AppExecFwk::ElementName& elementName)
1847 {
1848     std::lock_guard sortFileLockGuard(sessionFileLock_);
1849     SLOGI("refresh sort when session created, bundleName=%{public}s", (elementName.GetBundleName()).c_str());
1850     std::string oldSortContent;
1851 
1852     if (LoadStringFromFileEx(GetAVSortDir(), oldSortContent)) {
1853         cJSON* valuesArray = cJSON_Parse(oldSortContent.c_str());
1854         CHECK_AND_RETURN_LOG(valuesArray != nullptr, "parse json get nullptr");
1855         if (cJSON_IsInvalid(valuesArray) || !cJSON_IsArray(valuesArray)) {
1856             SLOGE("parse json not valid");
1857             cJSON_Delete(valuesArray);
1858             valuesArray = cJSON_CreateArray();
1859             CHECK_AND_RETURN_LOG(valuesArray != nullptr, "create array json fail");
1860         }
1861         if (oldSortContent.find(elementName.GetBundleName()) == string::npos) {
1862             auto callback = [this](std::string bundleName, int32_t userId) {
1863                 SLOGI("recv delete bundle:%{public}s at user:%{public}d", bundleName.c_str(), userId);
1864                 DeleteAVQueueInfoRecord(bundleName, userId);
1865                 DeleteHistoricalRecord(bundleName, userId);
1866                 NotifyHistoricalRecordChange(bundleName, userId);
1867             };
1868             if (!BundleStatusAdapter::GetInstance().SubscribeBundleStatusEvent(elementName.GetBundleName(),
1869                 callback, GetUsersManager().GetCurrentUserId())) {
1870                 SLOGE("SubscribeBundleStatusEvent failed");
1871             }
1872         }
1873         int arraySize = cJSON_GetArraySize(valuesArray);
1874         for (int i = arraySize - 1; i >= 0; i--) {
1875             cJSON* itemToDelete = cJSON_GetArrayItem(valuesArray, i);
1876             CHECK_AND_CONTINUE(itemToDelete != nullptr && !cJSON_IsInvalid(itemToDelete));
1877             cJSON* bundleNameItem = cJSON_GetObjectItem(itemToDelete, "bundleName");
1878             cJSON* abilityNameItem = cJSON_GetObjectItem(itemToDelete, "abilityName");
1879             if (bundleNameItem == nullptr || cJSON_IsInvalid(bundleNameItem) || !cJSON_IsString(bundleNameItem) ||
1880                 abilityNameItem == nullptr || cJSON_IsInvalid(abilityNameItem) || !cJSON_IsString(abilityNameItem)) {
1881                 SLOGI("not contain bundleName or abilityName, pass");
1882                 continue;
1883             }
1884             if (strcmp(elementName.GetBundleName().c_str(), bundleNameItem->valuestring) == 0 &&
1885                 strcmp(elementName.GetAbilityName().c_str(), abilityNameItem->valuestring) == 0) {
1886                 cJSON_DeleteItemFromArray(valuesArray, i);
1887             }
1888         }
1889         InsertSessionItemToCJSONAndPrint(sessionId, sessionType, elementName, valuesArray);
1890         cJSON_Delete(valuesArray);
1891     } else {
1892         SLOGE("LoadStringToFile failed, filename=%{public}s", SORT_FILE_NAME);
1893     }
1894 }
1895 // LCOV_EXCL_STOP
1896 
GetAllSessionDescriptors(std::vector<AVSessionDescriptor> & descriptors)1897 int32_t AVSessionService::GetAllSessionDescriptors(std::vector<AVSessionDescriptor>& descriptors)
1898 {
1899     std::lock_guard frontLockGuard(sessionFrontLock_);
1900     std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront();
1901     CHECK_AND_RETURN_RET_LOG(sessionListForFront != nullptr, AVSESSION_ERROR, "sessionListForFront ptr nullptr!");
1902     for (const auto& session : *sessionListForFront) {
1903         if (session != nullptr) {
1904             descriptors.push_back(session->GetDescriptor());
1905         }
1906     }
1907     SLOGI("GetAllSessionDescriptors with size=%{public}d, topSession:%{public}s",
1908         static_cast<int32_t>(descriptors.size()),
1909         (topSession_ == nullptr ? "null" : topSession_->GetBundleName()).c_str());
1910     return AVSESSION_SUCCESS;
1911 }
1912 
GetSessionDescriptorsBySessionId(const std::string & sessionId,AVSessionDescriptor & descriptor)1913 int32_t AVSessionService::GetSessionDescriptorsBySessionId(const std::string& sessionId,
1914                                                            AVSessionDescriptor& descriptor)
1915 {
1916     std::lock_guard lockGuard(sessionServiceLock_);
1917     sptr<AVSessionItem> session = GetContainer().GetSessionById(sessionId);
1918     CHECK_AND_RETURN_RET_LOG(session != nullptr, AVSESSION_ERROR, "session to be got is not existed");
1919 
1920     auto pid = GetCallingPid();
1921     if (pid == session->GetPid()) {
1922         descriptor = session->GetDescriptor();
1923         return AVSESSION_SUCCESS;
1924     }
1925     int32_t err = PermissionChecker::GetInstance().CheckPermission(PermissionChecker::CHECK_SYSTEM_PERMISSION);
1926     if (err != ERR_NONE) {
1927         SLOGE("GetSessionDescriptorsBySessionId: CheckPermission failed!");
1928         HISYSEVENT_SECURITY("CONTROL_PERMISSION_DENIED", "CALLER_UID", GetCallingUid(),
1929             "CALLER_PID", GetCallingUid(), "SESSION_ID", sessionId,
1930             "ERROR_MSG", "avsessionservice getsessiondescriptors by sessionid checkpermission failed");
1931         return err;
1932     }
1933     descriptor = session->GetDescriptor();
1934     return AVSESSION_SUCCESS;
1935 }
1936 
ProcessDescriptorsFromCJSON(std::vector<AVSessionDescriptor> & descriptors,cJSON * valueItem)1937 void AVSessionService::ProcessDescriptorsFromCJSON(std::vector<AVSessionDescriptor>& descriptors, cJSON* valueItem)
1938 {
1939     CHECK_AND_RETURN_LOG(valueItem != nullptr && !cJSON_IsInvalid(valueItem), "valueItem get invalid");
1940 
1941     cJSON* sessionIdItem = cJSON_GetObjectItem(valueItem, "sessionId");
1942     if (sessionIdItem == nullptr || cJSON_IsInvalid(sessionIdItem) || !cJSON_IsString(sessionIdItem)) {
1943         SLOGE("valueItem get sessionId fail");
1944         return;
1945     }
1946     std::string sessionId(sessionIdItem->valuestring);
1947     cJSON* bundleNameItem = cJSON_GetObjectItem(valueItem, "bundleName");
1948     if (bundleNameItem == nullptr || cJSON_IsInvalid(bundleNameItem) || !cJSON_IsString(bundleNameItem)) {
1949         SLOGE("valueItem get bundleName fail");
1950         return;
1951     }
1952     std::string bundleName(bundleNameItem->valuestring);
1953     cJSON* abilityNameItem = cJSON_GetObjectItem(valueItem, "abilityName");
1954     if (abilityNameItem == nullptr || cJSON_IsInvalid(abilityNameItem) || !cJSON_IsString(abilityNameItem)) {
1955         SLOGE("valueItem get abilityName fail");
1956         return;
1957     }
1958     std::string abilityName(abilityNameItem->valuestring);
1959 
1960     AVSessionDescriptor descriptor;
1961     descriptor.sessionId_ = sessionId;
1962     descriptor.elementName_.SetBundleName(std::string(bundleNameItem->valuestring));
1963     descriptor.elementName_.SetAbilityName(std::string(abilityNameItem->valuestring));
1964     descriptors.push_back(descriptor);
1965 }
1966 
GetHistoricalSessionDescriptorsFromFile(std::vector<AVSessionDescriptor> & descriptors)1967 int32_t AVSessionService::GetHistoricalSessionDescriptorsFromFile(std::vector<AVSessionDescriptor>& descriptors)
1968 {
1969     std::string oldSortContent;
1970     if (!LoadStringFromFileEx(GetAVSortDir(), oldSortContent)) {
1971         SLOGE("GetHistoricalSessionDescriptorsFromFile read sort fail, Return!");
1972         return AVSESSION_ERROR;
1973     }
1974 
1975     cJSON* sortValuesArray = cJSON_Parse(oldSortContent.c_str());
1976     CHECK_AND_RETURN_RET_LOG(sortValuesArray != nullptr, AVSESSION_ERROR, "json object is null");
1977     if (cJSON_IsInvalid(sortValuesArray) || !cJSON_IsArray(sortValuesArray)) {
1978         SLOGE("parse json not valid");
1979         cJSON_Delete(sortValuesArray);
1980         return AVSESSION_ERROR;
1981     }
1982 
1983     cJSON* valueItem = nullptr;
1984     cJSON_ArrayForEach(valueItem, sortValuesArray) {
1985         ProcessDescriptorsFromCJSON(descriptors, valueItem);
1986     }
1987     if (descriptors.size() == 0 && GetContainer().GetAllSessions().size() == 0) {
1988         SLOGE("GetHistoricalSessionDescriptorsFromFile read empty, return!");
1989     }
1990     cJSON_Delete(sortValuesArray);
1991     return AVSESSION_SUCCESS;
1992 }
1993 
GetColdStartSessionDescriptors(std::vector<AVSessionDescriptor> & descriptors)1994 int32_t AVSessionService::GetColdStartSessionDescriptors(std::vector<AVSessionDescriptor>& descriptors)
1995 {
1996     std::lock_guard sortFileLockGuard(sessionFileLock_);
1997     std::vector<AVSessionDescriptor> tempDescriptors;
1998     GetHistoricalSessionDescriptorsFromFile(tempDescriptors);
1999     for (auto iterator = tempDescriptors.begin(); iterator != tempDescriptors.end(); ++iterator) {
2000         descriptors.push_back(*iterator);
2001     }
2002 
2003     return AVSESSION_SUCCESS;
2004 }
2005 
GetHistoricalSessionDescriptors(int32_t maxSize,std::vector<AVSessionDescriptor> & descriptors)2006 int32_t AVSessionService::GetHistoricalSessionDescriptors(int32_t maxSize,
2007                                                           std::vector<AVSessionDescriptor>& descriptors)
2008 {
2009     std::lock_guard sortFileLockGuard(sessionFileLock_);
2010     std::vector<AVSessionDescriptor> tempDescriptors;
2011     GetHistoricalSessionDescriptorsFromFile(tempDescriptors);
2012     if (maxSize < 0 || maxSize > maxHistoryNums_) {
2013         maxSize = unSetHistoryNum;
2014     }
2015     for (auto iterator = tempDescriptors.begin(); iterator != tempDescriptors.end(); ++iterator) {
2016         if (descriptors.size() >= (size_t)maxSize) {
2017             break;
2018         }
2019         std::string sessionId(iterator->sessionId_);
2020         auto session = GetContainer().GetSessionById(sessionId);
2021         if (session != nullptr) {
2022             SLOGE("GetHistoricalSessionDescriptorsFromFile find session alive, sessionId=%{public}s",
2023                 AVSessionUtils::GetAnonySessionId(sessionId).c_str());
2024             continue;
2025         }
2026         descriptors.push_back(*iterator);
2027     }
2028 
2029     return AVSESSION_SUCCESS;
2030 }
2031 
2032 // LCOV_EXCL_START
ProcessAvQueueInfosFromCJSON(std::vector<AVQueueInfo> & avQueueInfos,cJSON * valueItem)2033 void AVSessionService::ProcessAvQueueInfosFromCJSON(std::vector<AVQueueInfo>& avQueueInfos, cJSON* valueItem)
2034 {
2035     CHECK_AND_RETURN_LOG(valueItem != nullptr && !cJSON_IsInvalid(valueItem), "get valueItem invalid");
2036     cJSON* bundleNameItem = cJSON_GetObjectItem(valueItem, "bundleName");
2037     if (bundleNameItem == nullptr || cJSON_IsInvalid(bundleNameItem) || !cJSON_IsString(bundleNameItem)) {
2038         SLOGE("valueItem get bundleName fail");
2039         return;
2040     }
2041     cJSON* avQueueNameItem = cJSON_GetObjectItem(valueItem, "avQueueName");
2042     if (avQueueNameItem == nullptr || cJSON_IsInvalid(avQueueNameItem) || !cJSON_IsString(avQueueNameItem)) {
2043         SLOGE("valueItem get avQueueName fail");
2044         return;
2045     }
2046     cJSON* avQueueIdItem = cJSON_GetObjectItem(valueItem, "avQueueId");
2047     if (avQueueIdItem == nullptr || cJSON_IsInvalid(avQueueIdItem) || !cJSON_IsString(avQueueIdItem)) {
2048         SLOGE("valueItem get avQueueId fail");
2049         return;
2050     }
2051     cJSON* imageDirItem = cJSON_GetObjectItem(valueItem, "avQueueImageDir");
2052     if (imageDirItem == nullptr || cJSON_IsInvalid(imageDirItem) || !cJSON_IsString(imageDirItem)) {
2053         SLOGE("valueItem get avQueueImageDir fail");
2054         return;
2055     }
2056     cJSON* imageNameItem = cJSON_GetObjectItem(valueItem, "avQueueImageName");
2057     if (imageNameItem == nullptr || cJSON_IsInvalid(imageNameItem) || !cJSON_IsString(imageNameItem)) {
2058         SLOGE("valueItem get avQueueImageName fail");
2059         return;
2060     }
2061     cJSON* imageUri = cJSON_GetObjectItem(valueItem, "avQueueImageUri");
2062     if (imageUri == nullptr || cJSON_IsInvalid(imageUri) || !cJSON_IsString(imageUri)) {
2063         SLOGE("valueItem get avQueueImageUri fail");
2064         return;
2065     }
2066     AVQueueInfo avQueueInfo;
2067     avQueueInfo.SetBundleName(std::string(bundleNameItem->valuestring));
2068     avQueueInfo.SetAVQueueName(std::string(avQueueNameItem->valuestring));
2069     avQueueInfo.SetAVQueueId(std::string(avQueueIdItem->valuestring));
2070     std::shared_ptr<AVSessionPixelMap> avQueuePixelMap = std::make_shared<AVSessionPixelMap>();
2071     AVSessionUtils::ReadImageFromFile(avQueuePixelMap, std::string(imageDirItem->valuestring),
2072         std::string(imageNameItem->valuestring));
2073     avQueueInfo.SetAVQueueImage(avQueuePixelMap);
2074     avQueueInfo.SetAVQueueImageUri(std::string(imageUri->valuestring));
2075     avQueueInfos.push_back(avQueueInfo);
2076 }
2077 // LCOV_EXCL_STOP
2078 
2079 // LCOV_EXCL_START
GetHistoricalAVQueueInfos(int32_t maxSize,int32_t maxAppSize,std::vector<AVQueueInfo> & avQueueInfos)2080 int32_t AVSessionService::GetHistoricalAVQueueInfos(int32_t maxSize, int32_t maxAppSize,
2081                                                     std::vector<AVQueueInfo>& avQueueInfos)
2082 {
2083     std::lock_guard avQueueFileLockGuard(avQueueFileLock_);
2084     std::string oldAVQueueInfoContent;
2085     std::vector<AVQueueInfo> tempAVQueueInfos;
2086     if (!LoadStringFromFileEx(GetAVQueueDir(), oldAVQueueInfoContent)) {
2087         SLOGE("GetHistoricalAVQueueInfos read avqueueinfo fail, Return!");
2088         return AVSESSION_ERROR;
2089     }
2090 
2091     cJSON* avQueueValuesArray = cJSON_Parse(oldAVQueueInfoContent.c_str());
2092     CHECK_AND_RETURN_RET_LOG(avQueueValuesArray != nullptr, AVSESSION_ERROR, "json object is null");
2093     if (cJSON_IsInvalid(avQueueValuesArray) || !cJSON_IsArray(avQueueValuesArray)) {
2094         SLOGE("parse json not valid");
2095         cJSON_Delete(avQueueValuesArray);
2096         return AVSESSION_ERROR;
2097     }
2098     cJSON* valueItem = nullptr;
2099     cJSON_ArrayForEach(valueItem, avQueueValuesArray) {
2100         ProcessAvQueueInfosFromCJSON(tempAVQueueInfos, valueItem);
2101     }
2102     for (auto iterator = tempAVQueueInfos.begin(); iterator != tempAVQueueInfos.end(); ++iterator) {
2103         avQueueInfos.push_back(*iterator);
2104     }
2105     cJSON_Delete(avQueueValuesArray);
2106     return AVSESSION_SUCCESS;
2107 }
2108 // LCOV_EXCL_STOP
2109 
2110 // LCOV_EXCL_START
InsertAvQueueInfoToCJSONAndPrint(const std::string & bundleName,const AVMetaData & meta,const int32_t userId,cJSON * valuesArray)2111 bool AVSessionService::InsertAvQueueInfoToCJSONAndPrint(const std::string &bundleName,
2112     const AVMetaData& meta, const int32_t userId, cJSON* valuesArray)
2113 {
2114     CHECK_AND_RETURN_RET_LOG(valuesArray != nullptr, false, "get valuesArray nullptr");
2115     cJSON* newValue = cJSON_CreateObject();
2116     cJSON_AddStringToObject(newValue, "bundleName", bundleName.c_str());
2117     cJSON_AddStringToObject(newValue, "avQueueName", meta.GetAVQueueName().c_str());
2118     cJSON_AddStringToObject(newValue, "avQueueId", meta.GetAVQueueId().c_str());
2119     std::shared_ptr<AVSessionPixelMap> innerPixelMap = meta.GetAVQueueImage();
2120     std::string fileDir = AVSessionUtils::GetFixedPathName(userId);
2121     std::string fileName = bundleName + "_" + meta.GetAVQueueId() + AVSessionUtils::GetFileSuffix();
2122     if (innerPixelMap != nullptr) {
2123         AVSessionUtils::WriteImageToFile(innerPixelMap, fileDir, fileName);
2124         innerPixelMap->Clear();
2125     }
2126     cJSON_AddStringToObject(newValue, "avQueueImageDir", fileDir.c_str());
2127     cJSON_AddStringToObject(newValue, "avQueueImageName", fileName.c_str());
2128     cJSON_AddStringToObject(newValue, "avQueueImageUri", meta.GetAVQueueImageUri().c_str());
2129     if (cJSON_IsInvalid(newValue)) {
2130         SLOGE("get valuesArray nullptr");
2131         return false;
2132     }
2133     if (cJSON_GetArraySize(valuesArray) <= 0) {
2134         cJSON_AddItemToArray(valuesArray, newValue);
2135     } else {
2136         cJSON_InsertItemInArray(valuesArray, 0, newValue);
2137     }
2138     if (cJSON_IsInvalid(valuesArray)) {
2139         SLOGE("get newValueArray invalid");
2140         return false;
2141     }
2142 
2143     char* newAvqueueContent = cJSON_Print(valuesArray);
2144     if (newAvqueueContent == nullptr) {
2145         SLOGE("newValueArray print fail");
2146         return false;
2147     }
2148     std::string newAvqueueContentStr(newAvqueueContent);
2149     if (!SaveStringToFileEx(GetAVQueueDir(userId), newAvqueueContentStr)) {
2150         SLOGE("SaveStringToFileEx failed when refresh focus session sort!");
2151         cJSON_free(newAvqueueContent);
2152         return false;
2153     }
2154     cJSON_free(newAvqueueContent);
2155     return true;
2156 }
2157 // LCOV_EXCL_STOP
2158 
2159 // LCOV_EXCL_START
SaveAvQueueInfo(std::string & oldContent,const std::string & bundleName,const AVMetaData & meta,const int32_t userId)2160 bool AVSessionService::SaveAvQueueInfo(std::string& oldContent, const std::string &bundleName,
2161     const AVMetaData& meta, const int32_t userId)
2162 {
2163     cJSON* valuesArray = cJSON_Parse(oldContent.c_str());
2164     CHECK_AND_RETURN_RET_LOG(valuesArray != nullptr, false, "json parse get nullptr");
2165     if (cJSON_IsInvalid(valuesArray) || !cJSON_IsArray(valuesArray)) {
2166         SLOGE("get value array invalid but createNew");
2167         cJSON_Delete(valuesArray);
2168         valuesArray = nullptr;
2169         valuesArray = cJSON_CreateArray();
2170         CHECK_AND_RETURN_RET_LOG(valuesArray != nullptr, false, "create array json again fail");
2171     }
2172 
2173     int arraySize = cJSON_GetArraySize(valuesArray);
2174     for (int i = arraySize - 1; i >= 0; i--) {
2175         cJSON* valueItem = cJSON_GetArrayItem(valuesArray, i);
2176         CHECK_AND_CONTINUE(valueItem != nullptr && !cJSON_IsInvalid(valueItem));
2177         cJSON* bundleNameItem = cJSON_GetObjectItem(valueItem, "bundleName");
2178         cJSON* avQueueIdItem = cJSON_GetObjectItem(valueItem, "avQueueId");
2179         if (bundleNameItem == nullptr || avQueueIdItem == nullptr || cJSON_IsInvalid(bundleNameItem) ||
2180             !cJSON_IsString(bundleNameItem) || cJSON_IsInvalid(avQueueIdItem) || !cJSON_IsString(avQueueIdItem)) {
2181             continue;
2182         }
2183         if (strcmp(bundleNameItem->valuestring, bundleName.c_str()) == 0 &&
2184             strcmp(avQueueIdItem->valuestring, meta.GetAVQueueId().c_str()) == 0) {
2185             CHECK_AND_RETURN_RET_LOG(i != 0, false, "avqueue:%{public}s is first", meta.GetAVQueueId().c_str());
2186             cJSON_DeleteItemFromArray(valuesArray, i);
2187         }
2188     }
2189     if (cJSON_GetArraySize(valuesArray) >= maxAVQueueInfoLen) {
2190         cJSON* valueItem = cJSON_GetArrayItem(valuesArray, cJSON_GetArraySize(valuesArray) - 1);
2191         DeleteAVQueueImage(valueItem);
2192         cJSON_DeleteItemFromArray(valuesArray, cJSON_GetArraySize(valuesArray) - 1);
2193     }
2194 
2195     bool ret = InsertAvQueueInfoToCJSONAndPrint(bundleName, meta, userId, valuesArray);
2196     cJSON_Delete(valuesArray);
2197     return ret;
2198 }
2199 // LCOV_EXCL_STOP
2200 
2201 // LCOV_EXCL_START
DeleteAVQueueImage(cJSON * item)2202 void AVSessionService::DeleteAVQueueImage(cJSON* item)
2203 {
2204     if (item == nullptr || cJSON_IsInvalid(item)) {
2205         return;
2206     }
2207     cJSON* imageDirItem = cJSON_GetObjectItem(item, "avQueueImageDir");
2208     cJSON* imageNameItem = cJSON_GetObjectItem(item, "avQueueImageName");
2209 
2210     if (imageDirItem == nullptr || cJSON_IsInvalid(imageDirItem) || !cJSON_IsString(imageDirItem)) {
2211         SLOGE("invalid imageDirItem");
2212         return;
2213     }
2214 
2215     if (imageNameItem == nullptr || cJSON_IsInvalid(imageNameItem) || !cJSON_IsString(imageNameItem)) {
2216         SLOGE("invalid imageNameItem");
2217         return;
2218     }
2219 
2220     std::string fileName = std::string(imageDirItem->valuestring) + std::string(imageNameItem->valuestring);
2221     AVSessionUtils::DeleteFile(fileName);
2222 }
2223 // LCOV_EXCL_STOP
2224 
2225 // LCOV_EXCL_START
AddAvQueueInfoToFile(AVSessionItem & session)2226 void AVSessionService::AddAvQueueInfoToFile(AVSessionItem& session)
2227 {
2228     // check is this session support playmusiclist intent
2229     std::lock_guard lockGuard(sessionServiceLock_);
2230     std::string bundleName = session.GetBundleName();
2231     std::string supportModule;
2232     std::string profile;
2233     if (!BundleStatusAdapter::GetInstance().IsSupportPlayIntent(bundleName, supportModule, profile)) {
2234         SLOGE("bundleName=%{public}s does not support play intent", bundleName.c_str());
2235         return;
2236     }
2237     AVMetaData meta = session.GetMetaData();
2238     if (meta.GetAVQueueId().empty() || meta.GetAVQueueName().empty()) {
2239         SLOGI("AddAvQueueInfoToFile avqueueinfo empty, return");
2240         DoMetadataImgClean(meta);
2241         return;
2242     }
2243     std::lock_guard avQueueFileLockGuard(avQueueFileLock_);
2244     std::string oldContent;
2245     int32_t userId = session.GetUserId();
2246     SLOGI("AddAvQueueInfoToFile for bundleName:%{public}s,userId:%{public}d", bundleName.c_str(), userId);
2247     if (!LoadStringFromFileEx(GetAVQueueDir(userId), oldContent)) {
2248         SLOGE("AddAvQueueInfoToFile read avqueueinfo fail, Return!");
2249         DoMetadataImgClean(meta);
2250         return;
2251     }
2252     if (!SaveAvQueueInfo(oldContent, bundleName, meta, userId)) {
2253         SLOGE("SaveAvQueueInfo same avqueueinfo, Return!");
2254         DoMetadataImgClean(meta);
2255         return;
2256     }
2257     DoMetadataImgClean(meta);
2258 }
2259 // LCOV_EXCL_STOP
2260 
DoMetadataImgClean(AVMetaData & data)2261 void AVSessionService::DoMetadataImgClean(AVMetaData& data)
2262 {
2263     SLOGI("clear media img in DoMetadataImgClean");
2264     std::shared_ptr<AVSessionPixelMap> innerQueuePixelMap = data.GetAVQueueImage();
2265     if (innerQueuePixelMap != nullptr) {
2266         innerQueuePixelMap->Clear();
2267     }
2268     std::shared_ptr<AVSessionPixelMap> innerMediaPixelMap = data.GetMediaImage();
2269     if (innerMediaPixelMap != nullptr) {
2270         innerMediaPixelMap->Clear();
2271     }
2272 }
2273 
StartAVPlayback(const std::string & bundleName,const std::string & assetId,const std::string & deviceId)2274 int32_t AVSessionService::StartAVPlayback(const std::string& bundleName, const std::string& assetId,
2275     const std::string& deviceId)
2276 {
2277     auto uid = GetCallingUid();
2278     auto CallerBundleName = BundleStatusAdapter::GetInstance().GetBundleNameFromUid(uid);
2279     StartPlayType startPlayType = StartPlayType::APP;
2280     if (uid == BLUETOOTH_UID) {
2281         startPlayType = StartPlayType::BLUETOOTH;
2282     }
2283     StartPlayInfo startPlayInfo;
2284     startPlayInfo.setBundleName(CallerBundleName);
2285     startPlayInfo.setDeviceId(deviceId);
2286 
2287     std::unique_ptr<AVSessionDynamicLoader> dynamicLoader = std::make_unique<AVSessionDynamicLoader>();
2288 
2289     typedef int32_t (*StartAVPlaybackFunc)(const std::string& bundleName, const std::string& assetId,
2290         const StartPlayInfo startPlayInfo, StartPlayType startPlayType);
2291     StartAVPlaybackFunc startAVPlayback =
2292         reinterpret_cast<StartAVPlaybackFunc>(dynamicLoader->GetFuntion(
2293             AVSESSION_DYNAMIC_INSIGHT_LIBRARY_PATH, "StartAVPlaybackWithId"));
2294     if (startAVPlayback) {
2295 #ifdef ENABLE_AVSESSION_SYSEVENT_CONTROL
2296         ReportSessionControl(bundleName, CONTROL_COLD_START);
2297 #endif
2298         return (*startAVPlayback)(bundleName, assetId, startPlayInfo, startPlayType);
2299     }
2300     SLOGE("StartAVPlayback fail");
2301     return AVSESSION_ERROR;
2302 }
2303 
StartAVPlayback(const std::string & bundleName,const std::string & assetId)2304 int32_t AVSessionService::StartAVPlayback(const std::string& bundleName, const std::string& assetId)
2305 {
2306     auto uid = GetCallingUid();
2307     auto CallerBundleName = BundleStatusAdapter::GetInstance().GetBundleNameFromUid(uid);
2308     StartPlayType startPlayType = StartPlayType::APP;
2309     if (uid == BLUETOOTH_UID) {
2310         startPlayType = StartPlayType::BLUETOOTH;
2311     }
2312     StartPlayInfo startPlayInfo;
2313     startPlayInfo.setBundleName(CallerBundleName);
2314     std::unique_ptr<AVSessionDynamicLoader> dynamicLoader = std::make_unique<AVSessionDynamicLoader>();
2315     if (dynamicLoader == nullptr) {
2316         SLOGI("dynamicLoader is null");
2317         return AVSESSION_ERROR;
2318     }
2319 
2320     typedef int32_t (*StartAVPlaybackFunc)(const std::string& bundleName, const std::string& assetId,
2321         const StartPlayInfo startPlayInfo, StartPlayType startPlayType);
2322     StartAVPlaybackFunc startAVPlayback =
2323         reinterpret_cast<StartAVPlaybackFunc>(dynamicLoader->GetFuntion(
2324             AVSESSION_DYNAMIC_INSIGHT_LIBRARY_PATH, "StartAVPlaybackWithId"));
2325     if (startAVPlayback) {
2326 #ifdef ENABLE_AVSESSION_SYSEVENT_CONTROL
2327         ReportSessionControl(bundleName, CONTROL_COLD_START);
2328 #endif
2329         return (*startAVPlayback)(bundleName, assetId, startPlayInfo, startPlayType);
2330     }
2331     SLOGE("StartAVPlayback fail");
2332     return AVSESSION_ERROR;
2333 }
2334 
CreateNewControllerForSession(pid_t pid,sptr<AVSessionItem> & session)2335 sptr<AVControllerItem> AVSessionService::CreateNewControllerForSession(pid_t pid, sptr<AVSessionItem>& session)
2336 {
2337     SLOGI("pid=%{public}d sessionId=%{public}s", pid,
2338         AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str());
2339     sptr<AVControllerItem> result = new(std::nothrow) AVControllerItem(pid, session, session->GetUserId());
2340     if (result == nullptr) {
2341         SLOGE("malloc controller failed");
2342         return nullptr;
2343     }
2344     result->SetServiceCallbackForRelease([this](AVControllerItem& controller) { HandleControllerRelease(controller); });
2345     session->AddController(pid, result);
2346     if (AbilityHasSession(pid)) {
2347         SLOGI("set isfromsession for pid %{public}d", static_cast<int>(pid));
2348         result->isFromSession_ = true;
2349     }
2350     return result;
2351 }
2352 
2353 // LCOV_EXCL_START
GetSubNode(const cJSON * nodeItem,const std::string & name)2354 const cJSON* AVSessionService::GetSubNode(const cJSON* nodeItem, const std::string& name)
2355 {
2356     if (nodeItem == nullptr || cJSON_IsInvalid(nodeItem)) {
2357         SLOGE("json node is invalid");
2358         return nullptr;
2359     }
2360 
2361     if (name.empty()) {
2362         SLOGE("name is invalid");
2363         return nodeItem;
2364     }
2365 
2366     const cJSON* subItem = cJSON_GetObjectItem(nodeItem, name.c_str());
2367     if (subItem == nullptr || cJSON_IsInvalid(subItem)) {
2368         SLOGE("%{public}s is not exist in json", name.c_str());
2369         return nullptr;
2370     }
2371     return subItem;
2372 }
2373 // LCOV_EXCL_STOP
2374 
IsHistoricalSession(const std::string & sessionId)2375 bool AVSessionService::IsHistoricalSession(const std::string& sessionId)
2376 {
2377     {
2378         std::string sortContent;
2379         std::lock_guard sortFileLockGuard(sessionFileLock_);
2380         if (!LoadStringFromFileEx(GetAVSortDir(), sortContent)) {
2381             SLOGE("IsHistoricalSession read sort failed, filename=%{public}s", SORT_FILE_NAME);
2382             return false;
2383         }
2384         if (sortContent.find(sessionId) == string::npos) {
2385             SLOGE("IsHistoricalSession find session no sort, sessionId=%{public}s",
2386                 AVSessionUtils::GetAnonySessionId(sessionId).c_str());
2387             return false;
2388         }
2389     }
2390 
2391     auto session = GetContainer().GetSessionById(sessionId);
2392     if (session != nullptr) {
2393         SLOGE("IsHistoricalSession find session alive, sessionId=%{public}s",
2394             AVSessionUtils::GetAnonySessionId(sessionId).c_str());
2395         return false;
2396     }
2397     SLOGE("IsHistoricalSession find session historical, sessionId=%{public}s",
2398         AVSessionUtils::GetAnonySessionId(sessionId).c_str());
2399     return true;
2400 }
2401 
GetDefaultAbilityElementNameFromCJSON(std::string & sortContent,std::string & bundleName,std::string & abilityName)2402 bool AVSessionService::GetDefaultAbilityElementNameFromCJSON(std::string& sortContent,
2403     std::string& bundleName, std::string& abilityName)
2404 {
2405     cJSON* sortValuesArray = cJSON_Parse(sortContent.c_str());
2406     CHECK_AND_RETURN_RET_LOG(sortValuesArray != nullptr, false, "json object is null");
2407     if (cJSON_IsInvalid(sortValuesArray) || !cJSON_IsArray(sortValuesArray)) {
2408         SLOGE("sortValuesArray get invalid");
2409         cJSON_Delete(sortValuesArray);
2410         return false;
2411     }
2412 
2413     cJSON* sortValueItem = nullptr;
2414     cJSON_ArrayForEach(sortValueItem, sortValuesArray) {
2415         CHECK_AND_CONTINUE(sortValueItem != nullptr && !cJSON_IsInvalid(sortValueItem));
2416         cJSON* sessionIdItem = cJSON_GetObjectItem(sortValueItem, "sessionId");
2417         CHECK_AND_CONTINUE(sessionIdItem != nullptr &&
2418             !cJSON_IsInvalid(sessionIdItem) && cJSON_IsString(sessionIdItem));
2419         auto session = GetContainer().GetSessionById(std::string(sessionIdItem->valuestring));
2420         if (session == nullptr) {
2421             cJSON* bundleNameItem = cJSON_GetObjectItem(sortValueItem, "bundleName");
2422             cJSON* abilityNameItem = cJSON_GetObjectItem(sortValueItem, "abilityName");
2423             CHECK_AND_CONTINUE(bundleNameItem != nullptr &&
2424                 !cJSON_IsInvalid(bundleNameItem) && cJSON_IsString(bundleNameItem));
2425             CHECK_AND_CONTINUE(abilityNameItem != nullptr &&
2426                 !cJSON_IsInvalid(abilityNameItem) && cJSON_IsString(abilityNameItem));
2427             bundleName.assign(bundleNameItem->valuestring);
2428             abilityName.assign(abilityNameItem->valuestring);
2429             break;
2430         } else {
2431             SLOGE("Default start alive %{public}s",
2432                 AVSessionUtils::GetAnonySessionId(std::string(sessionIdItem->valuestring)).c_str());
2433             cJSON_Delete(sortValuesArray);
2434             return false;
2435         }
2436     }
2437     cJSON_Delete(sortValuesArray);
2438     return true;
2439 }
2440 
StartDefaultAbilityByCall(std::string & sessionId)2441 int32_t AVSessionService::StartDefaultAbilityByCall(std::string& sessionId)
2442 {
2443     std::string bundleName = DEFAULT_BUNDLE_NAME;
2444     std::string abilityName = DEFAULT_ABILITY_NAME;
2445     std::string sortContent;
2446     {
2447         std::lock_guard sortFileLockGuard(sessionFileLock_);
2448         if (!LoadStringFromFileEx(GetAVSortDir(), sortContent)) {
2449             SLOGE("GetAllSessionDescriptors read sort fail! ");
2450             return AVSESSION_ERROR;
2451         }
2452     }
2453     if (!sortContent.empty()) {
2454         if (!GetDefaultAbilityElementNameFromCJSON(sortContent, bundleName, abilityName)) {
2455             SLOGE("GetDefaultAbilityElementNameFromCJSON fail");
2456             return AVSESSION_ERROR;
2457         }
2458     }
2459     std::shared_ptr<AbilityManagerAdapter> ability = nullptr;
2460     {
2461         std::lock_guard lockGuard(abilityManagerLock_);
2462         auto it = abilityManager_.find(bundleName + abilityName);
2463         if (it != abilityManager_.end()) {
2464             ability = it->second;
2465         } else {
2466             ability = std::make_shared<AbilityManagerAdapter>(bundleName, abilityName);
2467             if (ability == nullptr) {
2468                 return ERR_NO_MEMORY;
2469             }
2470             abilityManager_[bundleName + abilityName] = ability;
2471         }
2472     }
2473     if (ability == nullptr) {
2474         return AVSESSION_ERROR;
2475     }
2476     int32_t ret = ability->StartAbilityByCall(sessionId);
2477     if (ret != ERR_START_ABILITY_IS_RUNNING) {
2478         abilityManager_.erase(bundleName + abilityName);
2479     }
2480     return ret;
2481 }
2482 
GetElementNameBySessionIdFromCJSON(std::string & sortContent,const std::string & sessionIdNeeded,std::string & bundleName,std::string & abilityName)2483 bool AVSessionService::GetElementNameBySessionIdFromCJSON(std::string& sortContent, const std::string& sessionIdNeeded,
2484     std::string& bundleName, std::string& abilityName)
2485 {
2486     cJSON* sortValuesArray = cJSON_Parse(sortContent.c_str());
2487     CHECK_AND_RETURN_RET_LOG(sortValuesArray != nullptr, false, "json object is null");
2488     if (cJSON_IsInvalid(sortValuesArray) || !cJSON_IsArray(sortValuesArray)) {
2489         SLOGE("sortValuesArray get invalid");
2490         cJSON_Delete(sortValuesArray);
2491         return false;
2492     }
2493 
2494     cJSON* sortValueItem = nullptr;
2495     cJSON_ArrayForEach(sortValueItem, sortValuesArray) {
2496         CHECK_AND_CONTINUE(sortValueItem != nullptr && !cJSON_IsInvalid(sortValueItem));
2497         cJSON* sessionIdItem = cJSON_GetObjectItem(sortValueItem, "sessionId");
2498         CHECK_AND_CONTINUE(sessionIdItem != nullptr &&
2499             !cJSON_IsInvalid(sessionIdItem) && cJSON_IsString(sessionIdItem));
2500         if (strcmp(sessionIdNeeded.c_str(), sessionIdItem->valuestring) == 0) {
2501             cJSON* bundleNameItem = cJSON_GetObjectItem(sortValueItem, "bundleName");
2502             cJSON* abilityNameItem = cJSON_GetObjectItem(sortValueItem, "abilityName");
2503             CHECK_AND_CONTINUE(bundleNameItem != nullptr &&
2504                 !cJSON_IsInvalid(bundleNameItem) && cJSON_IsString(bundleNameItem));
2505             CHECK_AND_CONTINUE(abilityNameItem != nullptr &&
2506                 !cJSON_IsInvalid(abilityNameItem) && cJSON_IsString(abilityNameItem));
2507             bundleName.assign(bundleNameItem->valuestring);
2508             abilityName.assign(abilityNameItem->valuestring);
2509             break;
2510         }
2511     }
2512     cJSON_Delete(sortValuesArray);
2513     return true;
2514 }
2515 
StartAbilityByCall(const std::string & sessionIdNeeded,std::string & sessionId)2516 int32_t AVSessionService::StartAbilityByCall(const std::string& sessionIdNeeded, std::string& sessionId)
2517 {
2518     std::string content;
2519 
2520     {
2521         std::lock_guard sortFileLockGuard(sessionFileLock_);
2522         if (!LoadStringFromFileEx(GetAVSortDir(), content)) {
2523             SLOGE("LoadStringFromFile failed, filename=%{public}s", SORT_FILE_NAME);
2524             return AVSESSION_ERROR;
2525         }
2526     }
2527 
2528     std::string bundleName;
2529     std::string abilityName;
2530 
2531     if (!GetElementNameBySessionIdFromCJSON(content, sessionIdNeeded, bundleName, abilityName)) {
2532         SLOGE("parse json failed, sessionId=%{public}s",
2533             AVSessionUtils::GetAnonySessionId(sessionIdNeeded).c_str());
2534         return AVSESSION_ERROR;
2535     }
2536     if (bundleName.empty() || abilityName.empty()) {
2537         SLOGE("Get bundle name & ability name failed, sessionId=%{public}s",
2538             AVSessionUtils::GetAnonySessionId(sessionIdNeeded).c_str());
2539         return AVSESSION_ERROR;
2540     }
2541 
2542     std::shared_ptr<AbilityManagerAdapter> ability = nullptr;
2543     {
2544         std::lock_guard lockGuard(abilityManagerLock_);
2545         auto it = abilityManager_.find(bundleName + abilityName);
2546         if (it != abilityManager_.end()) {
2547             ability = it->second;
2548         } else {
2549             ability = std::make_shared<AbilityManagerAdapter>(bundleName, abilityName);
2550             if (ability == nullptr) {
2551                 return ERR_NO_MEMORY;
2552             }
2553             abilityManager_[bundleName + abilityName] = ability;
2554         }
2555     }
2556     if (ability == nullptr) {
2557         return AVSESSION_ERROR;
2558     }
2559     int32_t ret = ability->StartAbilityByCall(sessionId);
2560     if (ret != ERR_START_ABILITY_IS_RUNNING) {
2561         abilityManager_.erase(bundleName + abilityName);
2562     }
2563     return ret;
2564 }
2565 
CreateControllerInner(const std::string & sessionId,sptr<IRemoteObject> & object)2566 int32_t AVSessionService::CreateControllerInner(const std::string& sessionId, sptr<IRemoteObject>& object)
2567 {
2568     return CreateControllerInner(sessionId, object, -1);
2569 }
2570 
CreateControllerInner(const std::string & sessionId,sptr<IRemoteObject> & object,pid_t pid)2571 int32_t AVSessionService::CreateControllerInner(const std::string& sessionId, sptr<IRemoteObject>& object, pid_t pid)
2572 {
2573     SLOGI("CreateControllerInner for sessionId:%{public}s|%{public}d|%{public}d",
2574         AVSessionUtils::GetAnonySessionId(sessionId).c_str(), pid, GetCallingPid());
2575     sptr<AVSessionItem> session = GetContainer().GetSessionById(sessionId);
2576     if (session == nullptr) {
2577         SLOGE("no session id %{public}s", AVSessionUtils::GetAnonySessionId(sessionId).c_str());
2578         return ERR_SESSION_NOT_EXIST;
2579     }
2580     if (pid < 0 || GetCallingPid() != getpid()) {
2581         pid = GetCallingPid();
2582     }
2583     auto existController = GetPresentController(pid, sessionId);
2584     if (existController != nullptr) {
2585         SLOGI("Controller is already existed.");
2586         object = existController;
2587         return ERR_CONTROLLER_IS_EXIST;
2588     }
2589     sptr<AVControllerItem> newController = CreateNewControllerForSession(pid, session);
2590     if (newController == nullptr) {
2591         SLOGE("Create new controller failed.");
2592         return ERR_NO_MEMORY;
2593     }
2594 
2595     std::lock_guard lockGuard(sessionServiceLock_);
2596     controllers_[pid].push_back(newController);
2597     object = newController;
2598 
2599     return AVSESSION_SUCCESS;
2600 }
2601 
AddSessionListener(pid_t pid,const sptr<ISessionListener> & listener)2602 void AVSessionService::AddSessionListener(pid_t pid, const sptr<ISessionListener>& listener)
2603 {
2604     std::lock_guard lockGuard(sessionListenersLock_);
2605     GetUsersManager().AddSessionListener(pid, listener);
2606 }
2607 
AddSessionListenerForAllUsers(pid_t pid,const sptr<ISessionListener> & listener)2608 void AVSessionService::AddSessionListenerForAllUsers(pid_t pid, const sptr<ISessionListener>& listener)
2609 {
2610     std::lock_guard lockGuard(sessionListenersLock_);
2611     GetUsersManager().AddSessionListenerForAllUsers(pid, listener);
2612 }
2613 
RemoveSessionListener(pid_t pid)2614 void AVSessionService::RemoveSessionListener(pid_t pid)
2615 {
2616     std::lock_guard lockGuard(sessionListenersLock_);
2617     GetUsersManager().RemoveSessionListener(pid);
2618 }
2619 
RegisterSessionListener(const sptr<ISessionListener> & listener)2620 int32_t AVSessionService::RegisterSessionListener(const sptr<ISessionListener>& listener)
2621 {
2622     int32_t userId = GetUsersManager().GetCurrentUserId();
2623     pid_t pid = GetCallingPid();
2624     SLOGI("Enter RegisterSessionListener process for pid:%{public}d and return current userId:%{public}d",
2625         static_cast<int>(pid), userId);
2626     AddSessionListener(pid, listener);
2627     return userId;
2628 }
2629 
RegisterSessionListenerForAllUsers(const sptr<ISessionListener> & listener)2630 int32_t AVSessionService::RegisterSessionListenerForAllUsers(const sptr<ISessionListener>& listener)
2631 {
2632     pid_t pid = GetCallingPid();
2633     SLOGI("Enter RegisterSessionListenerForAllUsers process for pid:%{public}d", static_cast<int>(pid));
2634     AddSessionListenerForAllUsers(pid, listener);
2635     return AVSESSION_SUCCESS;
2636 }
2637 
2638 // LCOV_EXCL_START
GetSessionProcCommand()2639 AVControlCommand AVSessionService::GetSessionProcCommand()
2640 {
2641     AVControlCommand cmd;
2642     if (topSession_ != nullptr) {
2643         sptr<AVSessionItem> procSession = topSession_;
2644         if (IsAncoValid()) {
2645             procSession = topSession_->GetPlayingTime() > ancoSession_->GetPlayingTime() ?
2646                 topSession_ : ancoSession_;
2647         }
2648         auto playbackState = procSession->GetPlaybackState();
2649         cmd.SetCommand(playbackState.GetState() == AVPlaybackState::PLAYBACK_STATE_PLAY ?
2650             AVControlCommand::SESSION_CMD_PAUSE : AVControlCommand::SESSION_CMD_PLAY);
2651     } else if (IsAncoValid()) {
2652         auto state = ancoSession_->GetPlaybackState();
2653         cmd.SetCommand(state.GetState() == AVPlaybackState::PLAYBACK_STATE_PLAY ?
2654             AVControlCommand::SESSION_CMD_PAUSE : AVControlCommand::SESSION_CMD_PLAY);
2655     } else {
2656         cmd.SetCommand(AVControlCommand::SESSION_CMD_PLAY);
2657     }
2658     return cmd;
2659 }
2660 
HandleEventHandlerCallBack()2661 void AVSessionService::HandleEventHandlerCallBack()
2662 {
2663     SLOGI("handle eventHandler callback isFirstPress_=%{public}d, pressCount_:%{public}d", isFirstPress_, pressCount_);
2664     AVControlCommand cmd;
2665     bool shouldColdPlay = false;
2666     {
2667         std::lock_guard lockGuard(sessionServiceLock_);
2668         if (pressCount_ >= THREE_CLICK) {
2669             cmd.SetCommand(AVControlCommand::SESSION_CMD_PLAY_PREVIOUS);
2670         } else if (pressCount_ == DOUBLE_CLICK) {
2671             cmd.SetCommand(AVControlCommand::SESSION_CMD_PLAY_NEXT);
2672         } else if (pressCount_ == ONE_CLICK) {
2673             cmd = GetSessionProcCommand();
2674         } else {
2675             pressCount_ = 0;
2676             isFirstPress_ = true;
2677             SLOGI("press invalid return, topSession alive:%{public}d", static_cast<int>(topSession_ != nullptr));
2678             return;
2679         }
2680         SLOGI("HandleEventHandlerCallBack proc cmd=%{public}d", cmd.GetCommand());
2681         if (!topSession_) {
2682             shouldColdPlay = true;
2683             SLOGI("HandleEventHandlerCallBack checkTop:%{public}d|shouldColdStart=%{public}d",
2684                 static_cast<int>(topSession_ != nullptr), shouldColdPlay);
2685         } else {
2686             if (topSession_->GetDescriptor().sessionTag_ == "external_audio") {
2687                 SLOGI("HandleEventHandlerCallBack this is an external audio");
2688             } else {
2689                 auto keyEvent = MMI::KeyEvent::Create();
2690                 CHECK_AND_RETURN_LOG(keyEvent != nullptr, "handle event keyevent is null");
2691                 CheckSessionHandleKeyEvent(true, cmd, *keyEvent, topSession_);
2692             }
2693         }
2694     }
2695     if (shouldColdPlay) {
2696         HandleSystemKeyColdStart(cmd);
2697     }
2698     pressCount_ = 0;
2699     isFirstPress_ = true;
2700 }
2701 // LCOV_EXCL_STOP
2702 
IsAncoValid()2703 bool AVSessionService::IsAncoValid()
2704 {
2705     std::lock_guard lockGuard(sessionServiceLock_);
2706     return ancoSession_ != nullptr && ancoSession_->IsActive();
2707 }
2708 
CheckSessionHandleKeyEvent(bool procCmd,AVControlCommand cmd,const MMI::KeyEvent & keyEvent,sptr<AVSessionItem> session)2709 bool AVSessionService::CheckSessionHandleKeyEvent(bool procCmd, AVControlCommand cmd,
2710     const MMI::KeyEvent& keyEvent, sptr<AVSessionItem> session)
2711 {
2712     CHECK_AND_RETURN_RET_LOG(session != nullptr, false, "handlevent session is null");
2713     sptr<AVSessionItem> procSession = nullptr;
2714     if (ancoSession_ == nullptr || !ancoSession_->IsActive()) {
2715         procSession = session;
2716     } else {
2717         procSession = session->GetPlayingTime() > ancoSession_->GetPlayingTime() ? session : ancoSession_;
2718     }
2719     CHECK_AND_RETURN_RET_LOG(procSession != nullptr, false, "handlevent session is null");
2720     SLOGI("CheckSessionHandleKeyEvent procSession:%{public}s", procSession->GetBundleName().c_str());
2721     if (procCmd) {
2722         procSession->ExecuteControllerCommand(cmd);
2723         SLOGI("CheckSessionHandleKeyEvent proc cmd:%{public}d", cmd.GetCommand());
2724     } else {
2725         procSession->HandleMediaKeyEvent(keyEvent);
2726         SLOGI("CheckSessionHandleKeyEvent proc event:%{public}d", keyEvent.GetKeyCode());
2727     }
2728     return true;
2729 }
2730 
HandleKeyEvent(const MMI::KeyEvent & keyEvent)2731 int32_t AVSessionService::HandleKeyEvent(const MMI::KeyEvent& keyEvent)
2732 {
2733     if (keyEvent.GetKeyCode() != MMI::KeyEvent::KEYCODE_HEADSETHOOK &&
2734         keyEvent.GetKeyCode() != MMI::KeyEvent::KEYCODE_MEDIA_PLAY_PAUSE) {
2735         std::lock_guard lockGuard(keyEventListLock_);
2736         std::shared_ptr<std::list<sptr<AVSessionItem>>> keyEventList = GetCurKeyEventSessionList();
2737         CHECK_AND_RETURN_RET_LOG(keyEventList != nullptr, AVSESSION_ERROR, "keyEventList ptr nullptr!");
2738         for (const auto& session : *keyEventList) {
2739             session->HandleMediaKeyEvent(keyEvent);
2740             return AVSESSION_SUCCESS;
2741         }
2742     }
2743     if (CheckIfOtherAudioPlaying()) {
2744         SLOGE("control block for OtherAudioPlaying for key:%{public}d", keyEvent.GetKeyCode());
2745         return AVSESSION_SUCCESS;
2746     }
2747     {
2748         std::lock_guard lockGuard(sessionServiceLock_);
2749         if (keyEvent.GetKeyCode() == MMI::KeyEvent::KEYCODE_HEADSETHOOK ||
2750             keyEvent.GetKeyCode() == MMI::KeyEvent::KEYCODE_MEDIA_PLAY_PAUSE) {
2751             pressCount_++;
2752             SLOGI("isFirstPress_=%{public}d", isFirstPress_);
2753             if (isFirstPress_) {
2754                 auto ret = AVSessionEventHandler::GetInstance().AVSessionPostTask([this]() {
2755                     HandleEventHandlerCallBack();
2756                 }, "SendSystemAVKeyEvent", CLICK_TIMEOUT);
2757                 CHECK_AND_RETURN_RET_LOG(ret, AVSESSION_ERROR, "init eventHandler failed");
2758                 isFirstPress_ = false;
2759             }
2760             return AVSESSION_SUCCESS;
2761         }
2762     }
2763 
2764     {
2765         std::lock_guard lockGuard(sessionServiceLock_);
2766         AVControlCommand cmd;
2767         if (topSession_ != nullptr && CheckSessionHandleKeyEvent(false, cmd, keyEvent, topSession_)) {
2768             return AVSESSION_SUCCESS;
2769         }
2770     }
2771     return AVSESSION_CONTINUE;
2772 }
2773 
SendSystemAVKeyEvent(const MMI::KeyEvent & keyEvent,const AAFwk::Want & wantParam)2774 int32_t AVSessionService::SendSystemAVKeyEvent(const MMI::KeyEvent& keyEvent, const AAFwk::Want &wantParam)
2775 {
2776     SLOGI("SendSystemAVKeyEvent get key=%{public}d.", keyEvent.GetKeyCode());
2777     std::string deviceId = wantParam.GetStringParam("deviceId");
2778     int32_t ret = HandleKeyEvent(keyEvent);
2779     if (ret != AVSESSION_CONTINUE) {
2780         return ret;
2781     }
2782     {
2783         int cmd = ConvertKeyCodeToCommand(keyEvent.GetKeyCode());
2784         AVControlCommand controlCommand;
2785         controlCommand.SetCommand(cmd);
2786         SLOGI("topSession get nullptr, check if cold start for cmd %{public}d forRemoteDevice", cmd);
2787         HandleSystemKeyColdStart(controlCommand, deviceId);
2788     }
2789     return AVSESSION_SUCCESS;
2790 }
2791 
SendSystemAVKeyEvent(const MMI::KeyEvent & keyEvent)2792 int32_t AVSessionService::SendSystemAVKeyEvent(const MMI::KeyEvent& keyEvent)
2793 {
2794     SLOGI("SendSystemAVKeyEvent get key=%{public}d.", keyEvent.GetKeyCode());
2795     int32_t ret = HandleKeyEvent(keyEvent);
2796     if (ret != AVSESSION_CONTINUE) {
2797         return ret;
2798     }
2799     {
2800         int cmd = ConvertKeyCodeToCommand(keyEvent.GetKeyCode());
2801         AVControlCommand controlCommand;
2802         controlCommand.SetCommand(cmd);
2803         SLOGI("topSession get nullptr, check if cold start for cmd %{public}d", cmd);
2804         HandleSystemKeyColdStart(controlCommand);
2805     }
2806     return AVSESSION_SUCCESS;
2807 }
2808 
ConvertKeyCodeToCommand(int keyCode)2809 int32_t AVSessionService::ConvertKeyCodeToCommand(int keyCode)
2810 {
2811     auto iter = keyCodeToCommandMap_.find(keyCode);
2812     if (iter != keyCodeToCommandMap_.end()) {
2813         return iter->second;
2814     } else {
2815         return AVControlCommand::SESSION_CMD_PLAY;
2816     }
2817 }
2818 
HandleSystemKeyColdStart(const AVControlCommand & command,const std::string deviceId)2819 void AVSessionService::HandleSystemKeyColdStart(const AVControlCommand &command, const std::string deviceId)
2820 {
2821     SLOGI("cmd=%{public}d with no topsession", command.GetCommand());
2822     // try proc command for first front session
2823     {
2824         std::lock_guard lockGuard(sessionServiceLock_);
2825         std::lock_guard frontLockGuard(sessionFrontLock_);
2826         std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront();
2827         CHECK_AND_RETURN_LOG(sessionListForFront != nullptr, "sessionListForFront ptr nullptr!");
2828         for (const auto& session : *sessionListForFront) {
2829             CHECK_AND_CONTINUE(session != nullptr);
2830             if (session->GetSessionType() != "voice_call" && session->GetSessionType() != "video_call") {
2831                 auto keyEvent = MMI::KeyEvent::Create();
2832                 CHECK_AND_RETURN_LOG(keyEvent != nullptr, "handle event keyevent is null");
2833                 CheckSessionHandleKeyEvent(true, command, *keyEvent, session);
2834                 SLOGI("ExecuteCommand %{public}d for front session: %{public}s", command.GetCommand(),
2835                       session->GetBundleName().c_str());
2836                 return;
2837             }
2838         }
2839     }
2840 
2841     if (IsAncoValid()) {
2842         SLOGI("ExecuteCommand %{public}d for anco_audio without top and frontlist", command.GetCommand());
2843         ancoSession_->ExecuteControllerCommand(command);
2844         return;
2845     }
2846 
2847     std::vector<AVSessionDescriptor> coldStartDescriptors;
2848     GetColdStartSessionDescriptors(coldStartDescriptors);
2849     CHECK_AND_RETURN_LOG(coldStartDescriptors.size() > 0, "get coldStartDescriptors empty");
2850     // try start play for first history session
2851     if (command.GetCommand() == AVControlCommand::SESSION_CMD_PLAY ||
2852         command.GetCommand() == AVControlCommand::SESSION_CMD_PLAY_NEXT ||
2853         command.GetCommand() == AVControlCommand::SESSION_CMD_PLAY_PREVIOUS) {
2854         sptr<IRemoteObject> object;
2855         int32_t ret = 0;
2856         std::string bundleName = coldStartDescriptors[0].elementName_.GetBundleName();
2857         if (deviceId.length() == 0) {
2858             ret = StartAVPlayback(bundleName, "");
2859         } else {
2860             ret = StartAVPlayback(bundleName, "", deviceId);
2861         }
2862         SLOGI("Cold play %{public}s ret=%{public}d", bundleName.c_str(), ret);
2863     } else {
2864         SLOGI("Cold start command=%{public}d, coldStartDescriptorsSize=%{public}d return", command.GetCommand(),
2865               static_cast<int>(coldStartDescriptors.size()));
2866     }
2867 }
2868 
CheckIfOtherAudioPlaying()2869 bool AVSessionService::CheckIfOtherAudioPlaying()
2870 {
2871     std::vector<int> audioPlayingUids = focusSessionStrategy_.GetAudioPlayingUids();
2872     CHECK_AND_RETURN_RET_LOG(!audioPlayingUids.empty(), false, "no other audio playing quit.");
2873     std::lock_guard lockGuard(sessionServiceLock_);
2874     std::lock_guard frontLockGuard(sessionFrontLock_);
2875     std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront();
2876     CHECK_AND_RETURN_RET_LOG(sessionListForFront != nullptr, false, "sessionListForFront ptr nullptr quit");
2877     CHECK_AND_RETURN_RET_LOG(!sessionListForFront->empty() || topSession_ != nullptr || IsAncoValid(), true,
2878         "sessionListForFront and top empty but audio playing, control block");
2879     for (int uid : audioPlayingUids) {
2880         if (GetUsersManager().GetContainerFromAll().UidHasSession(uid)) {
2881             SLOGI("audioplaying but session alive:%{public}d", uid);
2882             return false;
2883         }
2884         std::string bundleNamePlaying = BundleStatusAdapter::GetInstance().GetBundleNameFromUid(uid);
2885         CHECK_AND_RETURN_RET_LOG(topSession_ == nullptr || bundleNamePlaying != topSession_->GetBundleName(),
2886             false, "audioplaying but topBundle alive:%{public}s", bundleNamePlaying.c_str());
2887         for (const auto& session : *sessionListForFront) {
2888             CHECK_AND_CONTINUE(session != nullptr);
2889             if (bundleNamePlaying == session->GetBundleName()) {
2890                 SLOGE("audioplaying but bundle alive:%{public}s", bundleNamePlaying.c_str());
2891                 return false;
2892             }
2893         }
2894         SLOGI("audioPlaying and no session:%{public}d", uid);
2895     }
2896     return true;
2897 }
2898 
SendSystemControlCommand(const AVControlCommand & command)2899 int32_t AVSessionService::SendSystemControlCommand(const AVControlCommand &command)
2900 {
2901     if (CheckIfOtherAudioPlaying()) {
2902         SLOGE("control block for OtherAudioPlaying with cmd:%{public}d", command.GetCommand());
2903         return AVSESSION_SUCCESS;
2904     }
2905     {
2906         std::lock_guard lockGuard(sessionServiceLock_);
2907         SLOGI("SendSystemControlCommand with cmd:%{public}d, topSession alive:%{public}d",
2908               command.GetCommand(), static_cast<int>(topSession_ != nullptr));
2909         if (topSession_) {
2910             CHECK_AND_RETURN_RET_LOG(CommandSendLimit::GetInstance().IsCommandSendEnable(GetCallingPid()),
2911                 ERR_COMMAND_SEND_EXCEED_MAX, "command excuted number exceed max");
2912             auto keyEvent = MMI::KeyEvent::Create();
2913             CHECK_AND_RETURN_RET_LOG(keyEvent != nullptr, AVSESSION_SUCCESS, "handle event keyevent is null");
2914             CheckSessionHandleKeyEvent(true, command, *keyEvent, topSession_);
2915             return AVSESSION_SUCCESS;
2916         }
2917     }
2918     HandleSystemKeyColdStart(command);
2919     return AVSESSION_SUCCESS;
2920 }
2921 
AddClientDeathObserver(pid_t pid,const sptr<IClientDeath> & observer,const sptr<ClientDeathRecipient> recipient)2922 void AVSessionService::AddClientDeathObserver(pid_t pid, const sptr<IClientDeath>& observer,
2923     const sptr<ClientDeathRecipient> recipient)
2924 {
2925     std::lock_guard lockGuard(clientDeathLock_);
2926     clientDeathObservers_[pid] = observer;
2927     clientDeathRecipients_[pid] = recipient;
2928 }
2929 
RemoveClientDeathObserver(pid_t pid)2930 void AVSessionService::RemoveClientDeathObserver(pid_t pid)
2931 {
2932     std::lock_guard lockGuard(clientDeathLock_);
2933     sptr<IClientDeath> observer = clientDeathObservers_[pid];
2934     sptr<ClientDeathRecipient> recipient = clientDeathRecipients_[pid];
2935     if (observer && recipient) {
2936         SLOGI("remove clientDeath recipient for %{public}d", static_cast<int>(pid));
2937         observer->AsObject()->RemoveDeathRecipient(recipient);
2938     }
2939     clientDeathObservers_.erase(pid);
2940     clientDeathRecipients_.erase(pid);
2941 }
2942 
RegisterClientDeathObserver(const sptr<IClientDeath> & observer)2943 int32_t AVSessionService::RegisterClientDeathObserver(const sptr<IClientDeath>& observer)
2944 {
2945     auto pid = GetCallingPid();
2946     auto uid = GetCallingUid();
2947     SLOGI("enter ClientDeathObserver register with recipient point for pid:%{public}d", static_cast<int>(pid));
2948     sptr<ClientDeathRecipient> recipient =
2949         new(std::nothrow) ClientDeathRecipient([this, pid, uid]() { OnClientDied(pid, uid); });
2950     if (recipient == nullptr) {
2951         SLOGE("New ClientDeathRecipient failed.");
2952         HISYSEVENT_FAULT("CONTROL_COMMAND_FAILED", "ERROR_TYPE", "RGS_CLIENT_DEATH_OBSERVER_FAILED",
2953             "ERROR_INFO", "avsession service register client death observer malloc failed");
2954         return AVSESSION_ERROR;
2955     }
2956 
2957     if (!observer->AsObject()->AddDeathRecipient(recipient)) {
2958         SLOGE("add death recipient failed for %{public}d failed", pid);
2959         HISYSEVENT_FAULT("CONTROL_COMMAND_FAILED", "ERROR_TYPE", "RGS_CLIENT_DEATH_FAILED", "CALLING_PID", pid,
2960             "ERROR_INFO", "avsession service register client death observer, add death recipient failed");
2961         return AVSESSION_ERROR;
2962     }
2963 
2964     AddClientDeathObserver(pid, observer, recipient);
2965     return AVSESSION_SUCCESS;
2966 }
2967 
ClearClientResources(pid_t pid,bool continuePlay)2968 void AVSessionService::ClearClientResources(pid_t pid, bool continuePlay)
2969 {
2970     RemoveSessionListener(pid);
2971     {
2972         std::lock_guard lockGuard(sessionServiceLock_);
2973         ClearSessionForClientDiedNoLock(pid, continuePlay);
2974         ClearControllerForClientDiedNoLock(pid);
2975     }
2976     RemoveClientDeathObserver(pid);
2977 }
2978 
Close(void)2979 int32_t AVSessionService::Close(void)
2980 {
2981     auto pid = GetCallingPid();
2982     ClearClientResources(pid, false);
2983     return AVSESSION_SUCCESS;
2984 }
2985 
OnClientDied(pid_t pid,pid_t uid)2986 void AVSessionService::OnClientDied(pid_t pid, pid_t uid)
2987 {
2988     ClearClientResources(pid, true);
2989 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
2990     AVRouter::GetInstance().IsStopCastDiscovery(pid);
2991     if (BundleStatusAdapter::GetInstance().GetBundleNameFromUid(uid) == MEDIA_CONTROL_BUNDLENAME) {
2992         SLOGI("mediacontroller on client die");
2993     }
2994 #endif // CASTPLUS_CAST_ENGINE_ENABLE
2995 #ifdef ENABLE_AVSESSION_SYSEVENT_CONTROL
2996     AVSessionSysEvent::GetInstance().ReportPlayingState(
2997         BundleStatusAdapter::GetInstance().GetBundleNameFromUid(uid));
2998 #endif
2999 }
3000 
3001 // LCOV_EXCL_START
DeleteHistoricalRecord(const std::string & bundleName,int32_t userId)3002 void AVSessionService::DeleteHistoricalRecord(const std::string& bundleName, int32_t userId)
3003 {
3004     std::lock_guard sortFileLockGuard(sessionFileLock_);
3005     userId = userId <= 0 ? GetUsersManager().GetCurrentUserId() : userId;
3006     if (!CheckUserDirValid(userId)) {
3007         SLOGE("DeleteHistoricalRecord target user:%{public}d not valid, return", userId);
3008         return;
3009     }
3010     SLOGI("delete historical record, bundleName=%{public}s, userId=%{public}d", bundleName.c_str(), userId);
3011     std::string oldContent;
3012     if (!LoadStringFromFileEx(GetAVSortDir(userId), oldContent)) {
3013         SLOGE("LoadStringFromFile failed, filename=%{public}s", SORT_FILE_NAME);
3014         return;
3015     }
3016     cJSON* valuesArray = cJSON_Parse(oldContent.c_str());
3017     CHECK_AND_RETURN_LOG(valuesArray != nullptr, "cjson parse nullptr");
3018     if (cJSON_IsInvalid(valuesArray) || !cJSON_IsArray(valuesArray)) {
3019         SLOGE("parse json invalid");
3020         cJSON_Delete(valuesArray);
3021         return;
3022     }
3023     int arraySize = cJSON_GetArraySize(valuesArray);
3024     for (int i = arraySize - 1; i >= 0; i--) {
3025         cJSON* valueItem = cJSON_GetArrayItem(valuesArray, i);
3026         CHECK_AND_CONTINUE(valueItem != nullptr && !cJSON_IsInvalid(valueItem));
3027         cJSON* bundleNameItem = cJSON_GetObjectItem(valueItem, "bundleName");
3028         cJSON* abilityNameItem = cJSON_GetObjectItem(valueItem, "abilityName");
3029         if (bundleNameItem == nullptr || cJSON_IsInvalid(bundleNameItem) || !cJSON_IsString(bundleNameItem) ||
3030             abilityNameItem == nullptr || cJSON_IsInvalid(abilityNameItem) || !cJSON_IsString(abilityNameItem)) {
3031             SLOGI("not contain bundleName or abilityName, pass");
3032             continue;
3033         }
3034         if (strcmp(bundleName.c_str(), bundleNameItem->valuestring) == 0) {
3035             cJSON_DeleteItemFromArray(valuesArray, i);
3036             break;
3037         }
3038     }
3039     char* newContent = cJSON_Print(valuesArray);
3040     if (newContent == nullptr) {
3041         SLOGE("newContent print fail");
3042     } else {
3043         std::string newContentStr(newContent);
3044         if (!SaveStringToFileEx(GetAVSortDir(userId), newContentStr)) {
3045             SLOGE("SaveStringToFileEx failed when refresh focus session sort!");
3046         }
3047         cJSON_free(newContent);
3048     }
3049     cJSON_Delete(valuesArray);
3050 }
3051 // LCOV_EXCL_STOP
3052 
3053 // LCOV_EXCL_START
DeleteAVQueueInfoRecordFromCJSON(std::string & sortContent,const std::string & bundleName,int32_t userId)3054 void AVSessionService::DeleteAVQueueInfoRecordFromCJSON(std::string& sortContent,
3055     const std::string& bundleName, int32_t userId)
3056 {
3057     cJSON* valuesArray = cJSON_Parse(sortContent.c_str());
3058     CHECK_AND_RETURN_LOG(valuesArray != nullptr, "cjson parse nullptr");
3059     if (cJSON_IsInvalid(valuesArray) || !cJSON_IsArray(valuesArray)) {
3060         SLOGE("parse json invalid");
3061         cJSON_Delete(valuesArray);
3062         return;
3063     }
3064     int arraySize = cJSON_GetArraySize(valuesArray);
3065     for (int i = arraySize - 1; i >= 0; i--) {
3066         cJSON* valueItem = cJSON_GetArrayItem(valuesArray, i);
3067         CHECK_AND_CONTINUE(valueItem != nullptr && !cJSON_IsInvalid(valueItem));
3068         cJSON* bundleNameItem = cJSON_GetObjectItem(valueItem, "bundleName");
3069         if (bundleNameItem == nullptr || cJSON_IsInvalid(bundleNameItem) || !cJSON_IsString(bundleNameItem)) {
3070             SLOGI("bundleName from json not valid");
3071             continue;
3072         }
3073         if (strcmp(bundleName.c_str(), bundleNameItem->valuestring) == 0) {
3074             cJSON* avQueueIdItem = cJSON_GetObjectItem(valueItem, "avQueueId");
3075             if (avQueueIdItem == nullptr || cJSON_IsInvalid(avQueueIdItem) || !cJSON_IsString(avQueueIdItem)) {
3076                 SLOGI("avQueueId from json not valid");
3077                 continue;
3078             }
3079             std::string avQueueId(avQueueIdItem->valuestring);
3080             std::string fileName = AVSessionUtils::GetFixedPathName(userId) + bundleName + "_" +
3081                 avQueueId + AVSessionUtils::GetFileSuffix();
3082             AVSessionUtils::DeleteFile(fileName);
3083             cJSON_DeleteItemFromArray(valuesArray, i);
3084         }
3085     }
3086     char* newContent = cJSON_Print(valuesArray);
3087     if (newContent == nullptr) {
3088         SLOGE("newContent print fail");
3089     } else {
3090         std::string newContentStr(newContent);
3091         if (!SaveStringToFileEx(GetAVQueueDir(userId), newContentStr)) {
3092             SLOGE("SaveStringToFile failed, filename=%{public}s", AVQUEUE_FILE_NAME);
3093         }
3094         cJSON_free(newContent);
3095     }
3096     cJSON_Delete(valuesArray);
3097 }
3098 // LCOV_EXCL_STOP
3099 
3100 // LCOV_EXCL_START
DeleteAVQueueInfoRecord(const std::string & bundleName,int32_t userId)3101 void AVSessionService::DeleteAVQueueInfoRecord(const std::string& bundleName, int32_t userId)
3102 {
3103     std::lock_guard avQueueFileLockGuard(avQueueFileLock_);
3104     if (userId <= 0) {
3105         userId = GetUsersManager().GetCurrentUserId();
3106     }
3107     if (!CheckUserDirValid(userId)) {
3108         SLOGE("DeleteAVQueueInfoRecord target user:%{public}d not valid, return", userId);
3109         return;
3110     }
3111     SLOGI("DeleteAVQueueInfoRecord, bundleName=%{public}s, userId=%{public}d", bundleName.c_str(), userId);
3112     std::string oldContent;
3113     std::string newContent;
3114     if (!LoadStringFromFileEx(GetAVQueueDir(userId), oldContent)) {
3115         SLOGE("LoadStringFromFile failed, filename=%{public}s", AVQUEUE_FILE_NAME);
3116         return;
3117     }
3118     DeleteAVQueueInfoRecordFromCJSON(oldContent, bundleName, userId);
3119 }
3120 // LCOV_EXCL_STOP
3121 
3122 
HandleOtherSessionPlaying(sptr<AVSessionItem> & session)3123 void AVSessionService::HandleOtherSessionPlaying(sptr<AVSessionItem>& session)
3124 {
3125     CHECK_AND_RETURN_LOG(session != nullptr, "No other sessions are currently playing");
3126     UpdateTopSession(session);
3127     CHECK_AND_RETURN_LOG(topSession_ != nullptr, "topSession is nullptr, update topSession fail!");
3128     bool updateOrderResult = UpdateOrder(session);
3129     CHECK_AND_RETURN_LOG(updateOrderResult, "UpdateOrder fail");
3130     if (session->GetSessionType() == "audio" || session->GetSessionType() == "video") {
3131         AVSessionService::NotifySystemUI(nullptr, true, IsCapsuleNeeded(), false);
3132     }
3133 }
3134 
GetOtherPlayingSession(int32_t userId,std::string bundleName)3135 sptr <AVSessionItem> AVSessionService::GetOtherPlayingSession(int32_t userId, std::string bundleName)
3136 {
3137     std::lock_guard frontLockGuard(sessionFrontLock_);
3138     std::shared_ptr<std::list<sptr<AVSessionItem>>> sessionListForFront = GetCurSessionListForFront(userId);
3139     CHECK_AND_RETURN_RET_LOG(sessionListForFront != nullptr, nullptr, "sessionListForFront ptr nullptr!");
3140     for (const auto& session : *sessionListForFront) {
3141         CHECK_AND_CONTINUE(session != nullptr);
3142         if (AudioAdapter::GetInstance().GetRendererRunning(session->GetUid(), session->GetPid()) &&
3143             (session->GetSessionType() != "voice_call" && session->GetSessionType() != "video_call") &&
3144             session->GetBundleName() != bundleName && !session->IsCasting()) {
3145             SLOGI("find other playing session, uid:%{public}d, pid:%{public}d, bundleName %{public}s",
3146                 session->GetUid(), session->GetPid(), session->GetBundleName().c_str());
3147             return session;
3148         }
3149     }
3150     if (!bundleName.empty()) {
3151         sptr<AVSessionItem> firstSession = sessionListForFront->front();
3152         CHECK_AND_RETURN_RET_LOG(firstSession != nullptr, nullptr, "firstSession is nullptr!");
3153         if (firstSession->IsCasting() &&
3154             firstSession->GetCastAVPlaybackState().GetState() == AVPlaybackState::PLAYBACK_STATE_PLAY) {
3155             SLOGI("find casting session, uid:%{public}d", firstSession->GetUid());
3156             return firstSession;
3157         }
3158     }
3159     return nullptr;
3160 }
3161 
HandleTopSessionRelease(int32_t userId,sptr<AVSessionItem> & sessionItem)3162 void AVSessionService::HandleTopSessionRelease(int32_t userId, sptr<AVSessionItem>& sessionItem)
3163 {
3164     if (GetUsersManager().GetTopSession(userId).GetRefPtr() == sessionItem.GetRefPtr()) {
3165         sptr<AVSessionItem> result = GetOtherPlayingSession(userId, sessionItem->GetBundleName());
3166         if (result != nullptr) {
3167             HandleOtherSessionPlaying(result);
3168         } else {
3169             UpdateTopSession(nullptr, userId);
3170             hasMediaCapsule_ = false;
3171             int32_t ret = Notification::NotificationHelper::CancelNotification(std::to_string(userId), 0);
3172             SLOGI("CancelNotification with userId:%{public}d, ret=%{public}d", userId, ret);
3173         }
3174     }
3175 }
3176 
HandleSessionRelease(std::string sessionId,bool continuePlay)3177 void AVSessionService::HandleSessionRelease(std::string sessionId, bool continuePlay)
3178 {
3179     SLOGI("HandleSessionRelease, sessionId=%{public}s", AVSessionUtils::GetAnonySessionId(sessionId).c_str());
3180     {
3181         std::lock_guard lockGuard(sessionServiceLock_);
3182         std::lock_guard frontLockGuard(sessionFrontLock_);
3183         sptr<AVSessionItem> sessionItem = GetUsersManager().GetContainerFromAll().GetSessionById(sessionId);
3184         CHECK_AND_RETURN_LOG(sessionItem != nullptr, "Session item is nullptr");
3185         int32_t userId = sessionItem->GetUserId();
3186         userId = userId < 0 ? GetUsersManager().GetCurrentUserId() : userId;
3187         SLOGD("HandleSessionRelease with userId:%{public}d", userId);
3188 #ifdef ENABLE_AVSESSION_SYSEVENT_CONTROL
3189         ReportSessionState(sessionItem, SessionState::STATE_RELEASE);
3190 #endif
3191         NotifySessionRelease(sessionItem->GetDescriptor());
3192         if (sessionItem->GetUid() == ancoUid) {
3193             ancoSession_ = nullptr;
3194         }
3195         sessionItem->DestroyTask(continuePlay);
3196         HandleTopSessionRelease(userId, sessionItem);
3197         if (sessionItem->GetRemoteSource() != nullptr) {
3198             int32_t ret = CancelCastAudioForClientExit(sessionItem->GetPid(), sessionItem);
3199             SLOGI("CancelCastAudioForClientExit ret is %{public}d", ret);
3200         }
3201         HISYSEVENT_ADD_LIFE_CYCLE_INFO(sessionItem->GetDescriptor().elementName_.GetBundleName(),
3202             AppManagerAdapter::GetInstance().IsAppBackground(GetCallingUid(), GetCallingPid()),
3203             sessionItem->GetDescriptor().sessionType_, false);
3204         GetUsersManager().RemoveSessionForAllUser(sessionItem->GetPid(), sessionItem->GetAbilityName());
3205         UpdateFrontSession(sessionItem, false);
3206         {
3207             std::lock_guard lockGuard(keyEventListLock_);
3208             std::shared_ptr<std::list<sptr<AVSessionItem>>> keyEventList = GetCurKeyEventSessionList();
3209             CHECK_AND_RETURN_LOG(keyEventList != nullptr, "keyEventList ptr nullptr!");
3210             auto it = std::find(keyEventList->begin(), keyEventList->end(), sessionItem);
3211             if (it != keyEventList->end()) {
3212                 SLOGI("keyEventList remove %{public}s", sessionItem->GetBundleName().c_str());
3213                 keyEventList->erase(it);
3214             }
3215         }
3216     }
3217     HandleSessionReleaseInner();
3218 }
3219 
HandleSessionReleaseInner()3220 void AVSessionService::HandleSessionReleaseInner()
3221 {
3222 #ifdef START_STOP_ON_DEMAND_ENABLE
3223     if (GetUsersManager().GetContainerFromAll().GetAllSessions().size() == 0) {
3224         PublishEvent(mediaPlayStateFalse);
3225     }
3226 #endif
3227 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
3228     if ((GetUsersManager().GetContainerFromAll().GetAllSessions().size() == 0 ||
3229         (GetUsersManager().GetContainerFromAll().GetAllSessions().size() == 1 &&
3230         CheckAncoAudio())) && !is2in1_) {
3231         SLOGI("call disable cast for no session alive, after session release task");
3232         checkEnableCast(false);
3233     }
3234 #endif
3235 }
3236 
HandleControllerRelease(AVControllerItem & controller)3237 void AVSessionService::HandleControllerRelease(AVControllerItem& controller)
3238 {
3239     auto pid = controller.GetPid();
3240     std::lock_guard lockGuard(sessionServiceLock_);
3241     auto it = controllers_.find(pid);
3242     if (it == controllers_.end()) {
3243         return;
3244     }
3245     it->second.remove(&controller);
3246     if (it->second.empty()) {
3247         controllers_.erase(pid);
3248     }
3249 }
3250 
Dump(std::int32_t fd,const std::vector<std::u16string> & args)3251 std::int32_t AVSessionService::Dump(std::int32_t fd, const std::vector<std::u16string>& args)
3252 {
3253     if (fd < 0) {
3254         SLOGE("dump fd invalid");
3255         return ERR_INVALID_PARAM;
3256     }
3257 
3258     if (dumpHelper_ == nullptr) {
3259         SLOGE("dumpHelper_ is nullptr!");
3260         return ERR_INVALID_PARAM;
3261     }
3262 
3263     std::vector<std::string> argsInStr;
3264     for (const auto& arg : args) {
3265         SLOGI("Dump args: %s", Str16ToStr8(arg).c_str());
3266         argsInStr.emplace_back(Str16ToStr8(arg));
3267     }
3268 
3269     std::string result;
3270     dumpHelper_->Dump(argsInStr, result, *this);
3271     std::int32_t ret = dprintf(fd, "%s", result.c_str());
3272     if (ret < 0) {
3273         SLOGI("dprintf to dump fd failed");
3274         return ERR_INVALID_PARAM;
3275     }
3276     return AVSESSION_SUCCESS;
3277 }
3278 
GetService(const std::string & deviceId)3279 __attribute__((no_sanitize("cfi"))) std::shared_ptr<RemoteSessionCommandProcess> AVSessionService::GetService(
3280     const std::string& deviceId)
3281 {
3282     SLOGI("Enter GetService.");
3283     auto mgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
3284     if (mgr == nullptr) {
3285         SLOGE("GetService failed when GetSystemAbilityManager.");
3286         return nullptr;
3287     }
3288     auto object = mgr->GetSystemAbility(AVSESSION_SERVICE_ID, deviceId);
3289     if (object == nullptr) {
3290         SLOGE("GetService failed to get AVSESSION_SERVICE_ID object.");
3291         return nullptr;
3292     }
3293     std::shared_ptr<RemoteSessionCommandProcess> remoteService = std::make_shared<RemoteSessionCommandProcess>(object);
3294     return remoteService;
3295 }
3296 
IsLocalDevice(const std::string & networkId)3297 bool AVSessionService::IsLocalDevice(const std::string& networkId)
3298 {
3299     std::string localNetworkId;
3300     CHECK_AND_RETURN_RET_LOG(GetLocalNetworkId(localNetworkId) == AVSESSION_SUCCESS, AVSESSION_ERROR,
3301                              "GetLocalNetworkId error");
3302     if (networkId == localNetworkId || networkId == "LocalDevice") {
3303         SLOGI("This networkId is local device.");
3304         return true;
3305     }
3306     SLOGI("This networkId is not local device.");
3307     return false;
3308 }
3309 
GetLocalNetworkId(std::string & networkId)3310 int32_t AVSessionService::GetLocalNetworkId(std::string& networkId)
3311 {
3312     DistributedHardware::DmDeviceInfo deviceInfo;
3313     int32_t ret = DistributedHardware::DeviceManager::GetInstance().GetLocalDeviceInfo("av_session", deviceInfo);
3314     CHECK_AND_RETURN_RET_LOG(ret == 0, ret, "get local deviceInfo failed");
3315     networkId = deviceInfo.networkId;
3316     return AVSESSION_SUCCESS;
3317 }
3318 
GetTrustedDeviceName(const std::string & networkId,std::string & deviceName)3319 int32_t AVSessionService::GetTrustedDeviceName(const std::string& networkId, std::string& deviceName)
3320 {
3321     std::vector<OHOS::DistributedHardware::DmDeviceInfo> deviceList {};
3322     if (IsLocalDevice(networkId)) {
3323         deviceName = "LocalDevice";
3324         return AVSESSION_SUCCESS;
3325     }
3326     int32_t ret = GetTrustedDevicesInfo(deviceList);
3327     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "get devicesInfo failed");
3328     for (const auto& device : deviceList) {
3329         ret = strcmp(device.networkId, networkId.c_str());
3330         if (ret == 0) {
3331             deviceName = device.deviceName;
3332             return AVSESSION_SUCCESS;
3333         }
3334     }
3335     SLOGI("GetTrustedDeviceName is not find this device %{public}.6s", networkId.c_str());
3336     return AVSESSION_ERROR;
3337 }
3338 
GetTrustedDevicesInfo(std::vector<OHOS::DistributedHardware::DmDeviceInfo> & deviceList)3339 int32_t AVSessionService::GetTrustedDevicesInfo(std::vector<OHOS::DistributedHardware::DmDeviceInfo>& deviceList)
3340 {
3341     int32_t ret = DistributedHardware::DeviceManager::GetInstance().GetTrustedDeviceList("av_session", "", deviceList);
3342     CHECK_AND_RETURN_RET_LOG(ret == 0, ret, "get trusted device list failed");
3343     return AVSESSION_SUCCESS;
3344 }
3345 
SetBasicInfo(std::string & sessionInfo)3346 int32_t AVSessionService::SetBasicInfo(std::string& sessionInfo)
3347 {
3348     AVSessionBasicInfo basicInfo;
3349     basicInfo.metaDataCap_ = AVMetaData::localCapability;
3350     basicInfo.playBackStateCap_ = AVPlaybackState::localCapability;
3351     basicInfo.controlCommandCap_ = AVControlCommand::localCapability;
3352     int32_t ret = GetLocalNetworkId(basicInfo.networkId_);
3353     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, AVSESSION_ERROR, "GetLocalNetworkId failed");
3354 
3355     ret = JsonUtils::SetSessionBasicInfo(sessionInfo, basicInfo);
3356     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, AVSESSION_ERROR, "SetDeviceId failed");
3357     return AVSESSION_SUCCESS;
3358 }
3359 
SetDeviceInfo(const std::vector<AudioStandard::AudioDeviceDescriptor> & castAudioDescriptors,sptr<AVSessionItem> & session)3360 void AVSessionService::SetDeviceInfo(const std::vector<AudioStandard::AudioDeviceDescriptor>& castAudioDescriptors,
3361     sptr <AVSessionItem>& session)
3362 {
3363     CHECK_AND_RETURN_LOG(session != nullptr && castAudioDescriptors.size() > 0, "invalid argument");
3364 
3365     OutputDeviceInfo outputDeviceInfo;
3366     outputDeviceInfo.deviceInfos_.clear();
3367     int32_t castCategory = AVCastCategory::CATEGORY_LOCAL;
3368     if (!IsLocalDevice(castAudioDescriptors[0].networkId_)) {
3369         castCategory = AVCastCategory::CATEGORY_REMOTE;
3370     }
3371     for (const auto &audioDescriptor : castAudioDescriptors) {
3372         DeviceInfo deviceInfo;
3373         deviceInfo.castCategory_ = castCategory;
3374         deviceInfo.deviceId_ = std::to_string(audioDescriptor.deviceId_);
3375         deviceInfo.deviceName_ = audioDescriptor.deviceName_;
3376         SLOGI("SetDeviceInfo the deviceName is %{public}s", audioDescriptor.deviceName_.c_str());
3377         outputDeviceInfo.deviceInfos_.emplace_back(deviceInfo);
3378     }
3379     session->SetOutputDevice(outputDeviceInfo);
3380 }
3381 
GetAudioDescriptorByDeviceId(const std::vector<std::shared_ptr<AudioStandard::AudioDeviceDescriptor>> & descriptors,const std::string & deviceId,AudioStandard::AudioDeviceDescriptor & audioDescriptor)3382 bool AVSessionService::GetAudioDescriptorByDeviceId(
3383     const std::vector<std::shared_ptr<AudioStandard::AudioDeviceDescriptor>>& descriptors,
3384     const std::string& deviceId,
3385     AudioStandard::AudioDeviceDescriptor& audioDescriptor)
3386 {
3387     for (const auto& descriptor : descriptors) {
3388         if (std::to_string(descriptor->deviceId_) == deviceId) {
3389             audioDescriptor = *descriptor;
3390             return true;
3391         }
3392     }
3393     SLOGI("GetAudioDescriptorByDeviceId deviceId:%{public}s is not found in all audio descriptors", deviceId.c_str());
3394     return false;
3395 }
3396 
GetDeviceInfo(const sptr<AVSessionItem> & session,const std::vector<AudioStandard::AudioDeviceDescriptor> & descriptors,std::vector<AudioStandard::AudioDeviceDescriptor> & castSinkDescriptors,std::vector<AudioStandard::AudioDeviceDescriptor> & cancelSinkDescriptors)3397 void AVSessionService::GetDeviceInfo(const sptr <AVSessionItem>& session,
3398     const std::vector<AudioStandard::AudioDeviceDescriptor>& descriptors,
3399     std::vector<AudioStandard::AudioDeviceDescriptor>& castSinkDescriptors,
3400     std::vector<AudioStandard::AudioDeviceDescriptor>& cancelSinkDescriptors)
3401 {
3402     if (descriptors.size() != 1) {
3403         SLOGI("descriptor size is %{public}d, not support", static_cast<int32_t>(descriptors.size()));
3404         return;
3405     }
3406     castSinkDescriptors.push_back(descriptors[0]);
3407     OutputDeviceInfo tempOutputDeviceInfo;
3408     session->GetOutputDevice(tempOutputDeviceInfo);
3409     // If not in remote, return directly
3410     if (tempOutputDeviceInfo.deviceInfos_.size() == 0 || tempOutputDeviceInfo.deviceInfos_[0].castCategory_ == 1) {
3411         SLOGI("castCategory is %{public}d, no need to cancel", tempOutputDeviceInfo.deviceInfos_[0].castCategory_);
3412         return;
3413     }
3414     int32_t ret = GetAudioDescriptor(session->GetDescriptor().outputDeviceInfo_.deviceInfos_[0].deviceId_,
3415                                      cancelSinkDescriptors);
3416     CHECK_AND_RETURN_LOG(ret == AVSESSION_SUCCESS, "get cancelSinkDescriptors failed");
3417 }
3418 
SelectOutputDevice(const int32_t uid,const AudioDeviceDescriptor & descriptor)3419 int32_t AVSessionService::SelectOutputDevice(const int32_t uid, const AudioDeviceDescriptor& descriptor)
3420 {
3421     sptr <AudioStandard::AudioRendererFilter> audioFilter = new(std::nothrow) AudioRendererFilter();
3422     CHECK_AND_RETURN_RET_LOG(audioFilter != nullptr, ERR_NO_MEMORY, "new AudioRendererFilter failed");
3423     audioFilter->uid = uid;
3424     audioFilter->rendererInfo.contentType = ContentType::CONTENT_TYPE_MUSIC;
3425     audioFilter->rendererInfo.streamUsage = StreamUsage::STREAM_USAGE_MEDIA;
3426 
3427     std::vector<std::shared_ptr<AudioDeviceDescriptor>> audioDescriptor;
3428     auto audioDeviceDescriptor = std::make_shared<AudioDeviceDescriptor>(descriptor);
3429     CHECK_AND_RETURN_RET_LOG(audioDeviceDescriptor != nullptr, ERR_NO_MEMORY, "audioDeviceDescriptor is nullptr");
3430     audioDescriptor.push_back(audioDeviceDescriptor);
3431     SLOGI("select the device %{public}s role is %{public}d, networkId is %{public}.6s",
3432         descriptor.deviceName_.c_str(), static_cast<int32_t>(descriptor.deviceRole_), descriptor.networkId_.c_str());
3433 
3434     AudioSystemManager *audioSystemMgr = AudioSystemManager::GetInstance();
3435     CHECK_AND_RETURN_RET_LOG(audioSystemMgr != nullptr, AVSESSION_ERROR, "get AudioSystemManager instance failed");
3436     int32_t ret = audioSystemMgr->SelectOutputDevice(audioFilter, audioDescriptor);
3437     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, AVSESSION_ERROR, "SelectOutputDevice failed");
3438 
3439     return AVSESSION_SUCCESS;
3440 }
3441 
CastAudio(const SessionToken & token,const std::vector<AudioStandard::AudioDeviceDescriptor> & sinkAudioDescriptors)3442 int32_t AVSessionService::CastAudio(const SessionToken& token,
3443                                     const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkAudioDescriptors)
3444 {
3445     std::string sourceSessionInfo;
3446     int32_t ret = SetBasicInfo(sourceSessionInfo);
3447     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetBasicInfo failed");
3448     sptr<AVSessionItem> session = GetContainer().GetSessionById(token.sessionId);
3449     CHECK_AND_RETURN_RET_LOG(session != nullptr, ERR_SESSION_NOT_EXIST, "session %{public}s not exist",
3450                              AVSessionUtils::GetAnonySessionId(token.sessionId).c_str());
3451     ret = JsonUtils::SetSessionDescriptor(sourceSessionInfo, session->GetDescriptor());
3452     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetDescriptorInfo failed");
3453     ret = CastAudioProcess(sinkAudioDescriptors, sourceSessionInfo, session);
3454     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudioProcess failed");
3455     return AVSESSION_SUCCESS;
3456 }
3457 
CastAudioProcess(const std::vector<AudioStandard::AudioDeviceDescriptor> & descriptors,const std::string & sourceSessionInfo,sptr<AVSessionItem> & session)3458 int32_t AVSessionService::CastAudioProcess(const std::vector<AudioStandard::AudioDeviceDescriptor>& descriptors,
3459                                            const std::string& sourceSessionInfo,
3460                                            sptr <AVSessionItem>& session)
3461 {
3462     std::vector<AudioDeviceDescriptor> castSinkDescriptors;
3463     std::vector<AudioDeviceDescriptor> cancelSinkDescriptors;
3464     GetDeviceInfo(session, descriptors, castSinkDescriptors, cancelSinkDescriptors);
3465 
3466     if (cancelSinkDescriptors.size() > 0) {
3467         int32_t ret = CancelCastAudioInner(cancelSinkDescriptors, sourceSessionInfo, session);
3468         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CancelCastAudioInner failed");
3469     }
3470 
3471     if (castSinkDescriptors.size() > 0) {
3472         int32_t ret = CastAudioInner(castSinkDescriptors, sourceSessionInfo, session);
3473         if (ret != AVSESSION_SUCCESS) {
3474             SLOGE("CastAudioInner failed, try cancel it. ret is %{public}d",
3475                 CancelCastAudioInner(castSinkDescriptors, sourceSessionInfo, session));
3476             return ret;
3477         }
3478     }
3479 
3480     SetDeviceInfo(descriptors, session);
3481     return AVSESSION_SUCCESS;
3482 }
3483 
CastAudioInner(const std::vector<AudioStandard::AudioDeviceDescriptor> & sinkAudioDescriptors,const std::string & sourceSessionInfo,const sptr<AVSessionItem> & session)3484 int32_t AVSessionService::CastAudioInner(const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkAudioDescriptors,
3485                                          const std::string& sourceSessionInfo,
3486                                          const sptr <AVSessionItem>& session)
3487 {
3488     CHECK_AND_RETURN_RET_LOG(sinkAudioDescriptors.size() > 0, AVSESSION_ERROR, "sinkDescriptors is empty");
3489     std::string sourceDevice;
3490     CHECK_AND_RETURN_RET_LOG(GetLocalNetworkId(sourceDevice) == AVSESSION_SUCCESS, AVSESSION_ERROR,
3491                              "GetLocalNetworkId failed");
3492     SLOGI("networkId_: %{public}.6s, role %{public}d", sinkAudioDescriptors[0].networkId_.c_str(),
3493           static_cast<int32_t>(sinkAudioDescriptors[0].deviceRole_));
3494     if (IsLocalDevice(sinkAudioDescriptors[0].networkId_)) {
3495         int32_t ret = SelectOutputDevice(session->GetUid(), sinkAudioDescriptors[0]);
3496         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "selectOutputDevice failed");
3497         return AVSESSION_SUCCESS;
3498     }
3499 
3500     SLOGI("sinkAudioDescriptors size is %{public}d", static_cast<int32_t>(sinkAudioDescriptors.size()));
3501     for (const auto& sinkAudioDescriptor : sinkAudioDescriptors) {
3502         std::string sinkSessionInfo;
3503         auto service = GetService(sinkAudioDescriptor.networkId_);
3504         CHECK_AND_RETURN_RET_LOG(service != nullptr, AVSESSION_ERROR, "GetService %{public}s failed",
3505                                  sinkAudioDescriptor.networkId_.c_str());
3506         int32_t ret = service->ProcessCastAudioCommand(RemoteServiceCommand::COMMAND_CAST_AUDIO, sourceSessionInfo,
3507                                                        sinkSessionInfo);
3508         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "ProcessCastAudioCommand failed");
3509         std::string sinkCapability;
3510         ret = JsonUtils::GetAllCapability(sinkSessionInfo, sinkCapability);
3511         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetAllCapability failed");
3512         ret = session->CastAudioToRemote(sourceDevice, sinkAudioDescriptor.networkId_, sinkCapability);
3513         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudioToRemote failed");
3514         HISYSEVENT_BEHAVIOR("SESSION_CAST",
3515             "BUNDLE_NAME", session->GetDescriptor().elementName_.GetBundleName(),
3516             "MODULE_NAME", session->GetDescriptor().elementName_.GetModuleName(),
3517             "ABILITY_NAME", session->GetDescriptor().elementName_.GetAbilityName(),
3518             "SESSION_PID", session->GetDescriptor().pid_,
3519             "SESSION_UID", session->GetDescriptor().uid_,
3520             "SESSION_ID", session->GetDescriptor().sessionId_,
3521             "SESSION_TAG", session->GetDescriptor().sessionTag_,
3522             "SESSION_TYPE", session->GetDescriptor().sessionType_,
3523             "CAST_TYPE", 0,
3524             "DEST_DEVICE_TYPE", sinkAudioDescriptor.deviceType_,
3525             "DEST_DEVICE_NAME", sinkAudioDescriptor.deviceName_.c_str(),
3526             "DEST_DEVICE_ID", sinkAudioDescriptor.deviceId_,
3527             "DETAILED_MSG", "avsession service cast audio");
3528         ret = SelectOutputDevice(session->GetUid(), sinkAudioDescriptor);
3529         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "selectOutputDevice failed");
3530     }
3531     SLOGI("success");
3532     return AVSESSION_SUCCESS;
3533 }
3534 
CancelCastAudioInner(const std::vector<AudioStandard::AudioDeviceDescriptor> & sinkDevices,const std::string & sourceSessionInfo,const sptr<AVSessionItem> & session)3535 int32_t AVSessionService::CancelCastAudioInner(const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkDevices,
3536                                                const std::string& sourceSessionInfo,
3537                                                const sptr <AVSessionItem>& session)
3538 {
3539     SLOGI("cancel sinkDevices size is %{public}d", static_cast<int32_t>(sinkDevices.size()));
3540     CHECK_AND_RETURN_RET_LOG(!sinkDevices.empty(), AVSESSION_ERROR, "sinkDevices is empty");
3541     for (const auto& sinkDevice : sinkDevices) {
3542         if (IsLocalDevice(sinkDevice.networkId_)) {
3543             SLOGI("cancel Local device %{public}.6s", sinkDevice.networkId_.c_str());
3544             continue;
3545         }
3546         std::string sinkSessionInfo;
3547         SLOGI("cancel sinkDevices sinkDevice.networkId_ is %{public}.6s", sinkDevice.networkId_.c_str());
3548         auto service = GetService(sinkDevice.networkId_);
3549         CHECK_AND_RETURN_RET_LOG(service != nullptr, AVSESSION_ERROR, "GetService %{public}s failed",
3550                                  sinkDevice.networkId_.c_str());
3551         int32_t ret = service->ProcessCastAudioCommand(RemoteServiceCommand::COMMAND_CANCEL_CAST_AUDIO,
3552                                                        sourceSessionInfo, sinkSessionInfo);
3553         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "ProcessCastAudioCommand failed");
3554         ret = session->SourceCancelCastAudio(sinkDevice.networkId_);
3555         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SourceCancelCastAudio failed");
3556     }
3557     return AVSESSION_SUCCESS;
3558 }
3559 
CastAudioForNewSession(const sptr<AVSessionItem> & session)3560 int32_t AVSessionService::CastAudioForNewSession(const sptr<AVSessionItem>& session)
3561 {
3562     SLOGI("new sessionId is %{public}s", AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str());
3563     SessionToken token;
3564     token.sessionId = session->GetSessionId();
3565     token.pid = session->GetPid();
3566     token.uid = session->GetUid();
3567 
3568     int32_t ret = AVSESSION_SUCCESS;
3569     std::vector<AudioStandard::AudioDeviceDescriptor> castSinkDevices;
3570     {
3571         std::lock_guard lockGuard(outputDeviceIdLock_);
3572         ret = GetAudioDescriptor(outputDeviceId_, castSinkDevices);
3573         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetAudioDescriptor failed");
3574     }
3575 
3576     ret = CastAudio(token, castSinkDevices);
3577     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudio error, session Id is %{public}s",
3578                              AVSessionUtils::GetAnonySessionId(token.sessionId).c_str());
3579 
3580     SLOGI("success");
3581     return AVSESSION_SUCCESS;
3582 }
3583 
CastAudioForAll(const std::vector<AudioStandard::AudioDeviceDescriptor> & sinkAudioDescriptors)3584 int32_t AVSessionService::CastAudioForAll(const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkAudioDescriptors)
3585 {
3586     CHECK_AND_RETURN_RET_LOG(sinkAudioDescriptors.size() > 0, ERR_INVALID_PARAM, "sinkAudioDescriptors is empty");
3587     {
3588         std::lock_guard lockGuard(isAllSessionCastLock_);
3589         isAllSessionCast_ = false;
3590         if (!IsLocalDevice(sinkAudioDescriptors[0].networkId_)) {
3591             isAllSessionCast_ = true;
3592         }
3593     }
3594     for (const auto& session : GetContainer().GetAllSessions()) {
3595         SessionToken token;
3596         token.sessionId = session->GetSessionId();
3597         token.pid = session->GetPid();
3598         token.uid = session->GetUid();
3599         SLOGI("cast session %{public}s", AVSessionUtils::GetAnonySessionId(token.sessionId).c_str());
3600         int32_t ret = CastAudio(token, sinkAudioDescriptors);
3601         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudio session %{public}s failed",
3602                                  AVSessionUtils::GetAnonySessionId(token.sessionId).c_str());
3603         {
3604             std::lock_guard lockGuard(outputDeviceIdLock_);
3605             outputDeviceId_ = session->GetDescriptor().outputDeviceInfo_.deviceInfos_[0].deviceId_;
3606         }
3607     }
3608 
3609     return AVSESSION_SUCCESS;
3610 }
3611 
ProcessCastAudioCommand(const RemoteServiceCommand command,const std::string & input,std::string & output)3612 int32_t AVSessionService::ProcessCastAudioCommand(const RemoteServiceCommand command, const std::string& input,
3613                                                   std::string& output)
3614 {
3615     SLOGI("ProcessCastAudioCommand command is %{public}d", static_cast<int32_t>(command));
3616     CHECK_AND_RETURN_RET_LOG(command > COMMAND_INVALID && command < COMMAND_MAX, AVSESSION_ERROR, "invalid command");
3617     if (command == COMMAND_CAST_AUDIO) {
3618         int ret = RemoteCastAudioInner(input, output);
3619         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "RemoteCastAudioInner error");
3620         return AVSESSION_SUCCESS;
3621     }
3622 
3623     int ret = RemoteCancelCastAudioInner(input);
3624     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "RemoteCancelCastAudioInner error");
3625     return AVSESSION_SUCCESS;
3626 }
3627 
RemoteCastAudioInner(const std::string & sourceSessionInfo,std::string & sinkSessionInfo)3628 int32_t AVSessionService::RemoteCastAudioInner(const std::string& sourceSessionInfo, std::string& sinkSessionInfo)
3629 {
3630     SLOGI("sourceInfo : %{public}s", sourceSessionInfo.c_str());
3631     AVSessionDescriptor sourceDescriptor;
3632     int32_t ret = JsonUtils::GetSessionDescriptor(sourceSessionInfo, sourceDescriptor);
3633     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetSessionDescriptor failed");
3634 
3635     ret = SetBasicInfo(sinkSessionInfo);
3636     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, AVSESSION_ERROR, "SetBasicInfo failed");
3637     AVSessionBasicInfo sinkDeviceInfo;
3638     ret = JsonUtils::GetSessionBasicInfo(sinkSessionInfo, sinkDeviceInfo);
3639     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetBasicInfo failed");
3640 
3641     sptr <AVSessionItem> session;
3642     auto res = CreateSessionInner(sourceDescriptor.sessionTag_, sourceDescriptor.sessionType_,
3643                                   sourceDescriptor.isThirdPartyApp_, sourceDescriptor.elementName_, session);
3644     CHECK_AND_RETURN_RET_LOG(res == AVSESSION_SUCCESS, res, "CreateSession failed");
3645 
3646     {
3647         std::lock_guard lockGuard(castAudioSessionMapLock_);
3648         castAudioSessionMap_[sourceDescriptor.sessionId_] = session->GetSessionId();
3649     }
3650 
3651     AVSessionBasicInfo sourceDeviceInfo;
3652     ret = JsonUtils::GetSessionBasicInfo(sourceSessionInfo, sourceDeviceInfo);
3653     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetBasicInfo failed");
3654     std::string sourceCapability;
3655     ret = JsonUtils::GetAllCapability(sourceSessionInfo, sourceCapability);
3656     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetAllCapability failed");
3657     ret = session->CastAudioFromRemote(sourceDescriptor.sessionId_, sourceDeviceInfo.networkId_,
3658                                        sinkDeviceInfo.networkId_, sourceCapability);
3659     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudioFromRemote failed");
3660     JsonUtils::SetSessionDescriptor(sinkSessionInfo, session->GetDescriptor());
3661     return AVSESSION_SUCCESS;
3662 }
3663 
RemoteCancelCastAudioInner(const std::string & sessionInfo)3664 int32_t AVSessionService::RemoteCancelCastAudioInner(const std::string& sessionInfo)
3665 {
3666     SLOGI("sessionInfo is %{public}s", sessionInfo.c_str());
3667     AVSessionBasicInfo sourceDeviceInfo;
3668     int32_t ret = JsonUtils::GetSessionBasicInfo(sessionInfo, sourceDeviceInfo);
3669     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetBasicInfo failed");
3670     AVSessionDescriptor sourceDescriptor;
3671     ret = JsonUtils::GetSessionDescriptor(sessionInfo, sourceDescriptor);
3672     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetSessionDescriptor failed");
3673 
3674     std::lock_guard lockGuard(castAudioSessionMapLock_);
3675     auto iter = castAudioSessionMap_.find(sourceDescriptor.sessionId_);
3676     CHECK_AND_RETURN_RET_LOG(iter != castAudioSessionMap_.end(), AVSESSION_ERROR, "no source session %{public}s",
3677                              AVSessionUtils::GetAnonySessionId(sourceDescriptor.sessionId_).c_str());
3678     auto session = GetContainer().GetSessionById(iter->second);
3679     CHECK_AND_RETURN_RET_LOG(session != nullptr, AVSESSION_ERROR, "no sink session %{public}s",
3680         AVSessionUtils::GetAnonySessionId(iter->second).c_str());
3681 
3682     ret = session->SinkCancelCastAudio();
3683     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SinkCancelCastAudio failed");
3684     HandleSessionRelease(session->GetSessionId());
3685     castAudioSessionMap_.erase(sourceDescriptor.sessionId_);
3686     SLOGI("cancel source session %{public}s success",
3687         AVSessionUtils::GetAnonySessionId(sourceDescriptor.sessionId_).c_str());
3688     return AVSESSION_SUCCESS;
3689 }
3690 
CancelCastAudioForClientExit(pid_t pid,const sptr<AVSessionItem> & session)3691 int32_t AVSessionService::CancelCastAudioForClientExit(pid_t pid, const sptr<AVSessionItem>& session)
3692 {
3693     CHECK_AND_RETURN_RET_LOG(session != nullptr, AVSESSION_ERROR, "session is nullptr");
3694     SLOGI("pid is %{public}d, sessionId is %{public}s", static_cast<int32_t>(pid),
3695         AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str());
3696     std::string sourceSessionInfo;
3697     int32_t ret = SetBasicInfo(sourceSessionInfo);
3698     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetBasicInfo failed");
3699     ret = JsonUtils::SetSessionDescriptor(sourceSessionInfo, session->GetDescriptor());
3700     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetDescriptorInfo failed");
3701 
3702     std::vector<AudioStandard::AudioDeviceDescriptor> cancelSinkDevices;
3703     ret = GetAudioDescriptor(session->GetDescriptor().outputDeviceInfo_.deviceInfos_[0].deviceId_, cancelSinkDevices);
3704     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetAudioDescriptor failed");
3705 
3706     ret = CancelCastAudioInner(cancelSinkDevices, sourceSessionInfo, session);
3707     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CancelCastAudioInner failed");
3708     return AVSESSION_SUCCESS;
3709 }
3710 
GetAudioDescriptor(const std::string deviceId,std::vector<AudioStandard::AudioDeviceDescriptor> & audioDeviceDescriptors)3711 int32_t AVSessionService::GetAudioDescriptor(const std::string deviceId,
3712                                              std::vector<AudioStandard::AudioDeviceDescriptor>& audioDeviceDescriptors)
3713 {
3714     auto audioDescriptors = AudioSystemManager::GetInstance()->GetDevices(ALL_L_D_DEVICES_FLAG);
3715     AudioDeviceDescriptor audioDescriptor;
3716     if (GetAudioDescriptorByDeviceId(audioDescriptors, deviceId, audioDescriptor)) {
3717         audioDeviceDescriptors.push_back(audioDescriptor);
3718         SLOGI("get audio networkId_ is %{public}.6s", audioDescriptor.networkId_.c_str());
3719         return AVSESSION_SUCCESS;
3720     }
3721     SLOGI("can not get deviceId %{public}s info", deviceId.c_str());
3722     return AVSESSION_ERROR;
3723 }
3724 
ClearSessionForClientDiedNoLock(pid_t pid,bool continuePlay)3725 void AVSessionService::ClearSessionForClientDiedNoLock(pid_t pid, bool continuePlay)
3726 {
3727     SLOGI("clear session in ");
3728     auto sessions = GetUsersManager().GetContainerFromAll().GetSessionsByPid(pid);
3729     for (const auto& session : sessions) {
3730         SLOGI("check session release task for id %{public}s",
3731             AVSessionUtils::GetAnonySessionId(session->GetSessionId()).c_str());
3732         HandleSessionRelease(session->GetSessionId(), continuePlay);
3733     }
3734 }
3735 
ClearControllerForClientDiedNoLock(pid_t pid)3736 void AVSessionService::ClearControllerForClientDiedNoLock(pid_t pid)
3737 {
3738     auto it = controllers_.find(pid);
3739     CHECK_AND_RETURN_LOG(it != controllers_.end(), "no find controller");
3740     auto controllers = std::move(it->second);
3741     SLOGI("remove controllers size=%{public}d", static_cast<int>(controllers.size()));
3742     if (!controllers.empty()) {
3743         for (const auto& controller : controllers) {
3744             controller->DestroyWithoutReply();
3745         }
3746     }
3747     it = controllers_.find(pid);
3748     CHECK_AND_RETURN_LOG(it != controllers_.end(), "no find controller");
3749     controllers_.erase(pid);
3750 }
3751 
ClientDeathRecipient(const std::function<void ()> & callback)3752 ClientDeathRecipient::ClientDeathRecipient(const std::function<void()>& callback)
3753     : callback_(callback)
3754 {
3755     SLOGD("construct");
3756 }
3757 
OnRemoteDied(const wptr<IRemoteObject> & object)3758 void ClientDeathRecipient::OnRemoteDied(const wptr<IRemoteObject>& object)
3759 {
3760     if (callback_) {
3761         callback_();
3762     }
3763 }
3764 
CheckUserDirValid(int32_t userId)3765 bool AVSessionService::CheckUserDirValid(int32_t userId)
3766 {
3767     std::string filePath = GetUsersManager().GetDirForCurrentUser(userId);
3768     filesystem::path directory(filePath);
3769     std::error_code errCode;
3770     if (!filesystem::exists(directory, errCode)) {
3771         SLOGE("check user dir not exsit %{public}s for user %{public}d, errCode %{public}d",
3772             filePath.c_str(), userId, static_cast<int>(errCode.value()));
3773         return false;
3774     }
3775     return true;
3776 }
3777 
CheckAndCreateDir(const string & filePath)3778 bool AVSessionService::CheckAndCreateDir(const string& filePath)
3779 {
3780     CHECK_AND_RETURN_RET_LOG(CheckUserDirValid(), false, "check userDir err!");
3781     filesystem::path directory = filesystem::path(filePath).parent_path();
3782     if (!filesystem::exists(directory)) {
3783         SLOGI("check file not exist:%{public}s", filePath.c_str());
3784         return false;
3785     }
3786     return true;
3787 }
3788 
FillFileWithEmptyContentEx(ofstream & fileWrite)3789 bool AVSessionService::FillFileWithEmptyContentEx(ofstream& fileWrite)
3790 {
3791     cJSON* emptyValueArray = cJSON_CreateArray();
3792     CHECK_AND_RETURN_RET_LOG(emptyValueArray != nullptr, false, "emptyValueArray create nullptr");
3793     if (cJSON_IsInvalid(emptyValueArray) || !cJSON_IsArray(emptyValueArray)) {
3794         SLOGE("create emptyValueArray invalid");
3795         cJSON_Delete(emptyValueArray);
3796         return false;
3797     }
3798     char* emptyContent = cJSON_Print(emptyValueArray);
3799     if (emptyContent == nullptr) {
3800         SLOGE("newValueArray print fail nullptr");
3801         cJSON_Delete(emptyValueArray);
3802         return false;
3803     }
3804     std::string emptyContentStr(emptyContent);
3805     SLOGD("LoadStringFromFileEx::Dump json object finished");
3806     fileWrite.write(emptyContentStr.c_str(), emptyContentStr.length());
3807     if (fileWrite.fail()) {
3808         SLOGE("file empty init json fail !");
3809         cJSON_free(emptyContent);
3810         cJSON_Delete(emptyValueArray);
3811         return false;
3812     }
3813     cJSON_free(emptyContent);
3814     cJSON_Delete(emptyValueArray);
3815     return true;
3816 }
3817 
LoadStringFromFileEx(const string & filePath,string & content)3818 bool AVSessionService::LoadStringFromFileEx(const string& filePath, string& content)
3819 {
3820     SLOGD("file load in for path: %{public}s", filePath.c_str());
3821     CheckAndCreateDir(filePath);
3822     ifstream file(filePath.c_str());
3823     if (!file.is_open()) {
3824         SLOGD("file not open! try open first ! ");
3825         file.open(filePath.c_str(), ios::out | ios::app);
3826         if (!file.is_open()) {
3827             SLOGE("open file again fail !");
3828             return false;
3829         }
3830     }
3831     file.seekg(0, ios::end);
3832     const long fileLength = file.tellg();
3833     SLOGD("get file length(%{public}ld)!", fileLength);
3834     if (fileLength > maxFileLength) {
3835         SLOGE("invalid file length(%{public}ld)!", fileLength);
3836         return false;
3837     }
3838     if (fileLength <= 0) {
3839         SLOGD("file new create empty ! try set init json ");
3840         ofstream fileWrite;
3841         fileWrite.open(filePath.c_str(), ios::out | ios::trunc);
3842         if (!fileWrite.is_open()) {
3843             SLOGE("open file in create new failed!");
3844             file.close();
3845             return false;
3846         }
3847         if (!FillFileWithEmptyContentEx(fileWrite)) {
3848             SLOGE("file empty init json fail !");
3849             file.close();
3850             fileWrite.close();
3851             return false;
3852         }
3853         fileWrite.close();
3854     }
3855     content.clear();
3856     file.seekg(0, ios::beg);
3857     copy(istreambuf_iterator<char>(file), istreambuf_iterator<char>(), back_inserter(content));
3858     file.close();
3859     return CheckStringAndCleanFile(filePath);
3860 }
3861 
SaveStringToFileEx(const std::string & filePath,const std::string & content)3862 bool AVSessionService::SaveStringToFileEx(const std::string& filePath, const std::string& content)
3863 {
3864     SLOGI("file save in for path:%{public}s, content:%{public}s", filePath.c_str(), content.c_str());
3865     cJSON* checkValuesItem = cJSON_Parse(content.c_str());
3866     CHECK_AND_RETURN_RET_LOG(checkValuesItem != nullptr, false, "cjson parse nullptr");
3867     if (cJSON_IsInvalid(checkValuesItem)) {
3868         SLOGE("cjson parse invalid");
3869         cJSON_Delete(checkValuesItem);
3870         return false;
3871     }
3872     cJSON_Delete(checkValuesItem);
3873 
3874     ofstream file;
3875     file.open(filePath.c_str(), ios::out | ios::trunc);
3876     if (!file.is_open()) {
3877         SLOGE("open file in save failed!");
3878         return false;
3879     }
3880     if (content.empty()) {
3881         SLOGE("write content is empty, no need to do write!");
3882         file.close();
3883         return true;
3884     }
3885     file.write(content.c_str(), content.length());
3886     if (file.fail()) {
3887         SLOGE("write content to file failed!");
3888         file.close();
3889         return false;
3890     }
3891     file.close();
3892     return CheckStringAndCleanFile(filePath);
3893 }
3894 
CheckStringAndCleanFile(const std::string & filePath)3895 bool AVSessionService::CheckStringAndCleanFile(const std::string& filePath)
3896 {
3897     SLOGD("file check for path:%{public}s", filePath.c_str());
3898     string content {};
3899     ifstream fileRead(filePath.c_str());
3900     if (!fileRead.is_open()) {
3901         SLOGD("file not open! try open first ! ");
3902         fileRead.open(filePath.c_str(), ios::app);
3903         if (!fileRead.is_open()) {
3904             SLOGE("open file again fail !");
3905             return false;
3906         }
3907     }
3908     content.clear();
3909     fileRead.seekg(0, ios::beg);
3910     copy(istreambuf_iterator<char>(fileRead), istreambuf_iterator<char>(), back_inserter(content));
3911     SLOGD("check content pre clean it: %{public}s", content.c_str());
3912     cJSON* checkValuesItem = cJSON_Parse(content.c_str());
3913     bool isJsonDiscarded = false;
3914     if (checkValuesItem == nullptr) {
3915         isJsonDiscarded = true;
3916     } else {
3917         if (cJSON_IsInvalid(checkValuesItem)) {
3918             isJsonDiscarded = true;
3919             cJSON_Delete(checkValuesItem);
3920         }
3921     }
3922     if (isJsonDiscarded) {
3923         SLOGE("check content discarded! content %{public}s", content.c_str());
3924         ofstream fileWrite;
3925         fileWrite.open(filePath.c_str(), ios::out | ios::trunc);
3926         if (!fileWrite.is_open()) {
3927             SLOGE("open file in create new failed!");
3928             fileRead.close();
3929             return false;
3930         }
3931         if (!FillFileWithEmptyContentEx(fileWrite)) {
3932             SLOGE("file empty init json fail! content %{public}s", content.c_str());
3933             fileRead.close();
3934             fileWrite.close();
3935             return false;
3936         }
3937         fileWrite.close();
3938     }
3939     fileRead.close();
3940     return true;
3941 }
3942 
CreateWantAgent(const AVSessionDescriptor * histroyDescriptor)3943 std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> AVSessionService::CreateWantAgent(
3944     const AVSessionDescriptor* histroyDescriptor)
3945 {
3946     if (histroyDescriptor == nullptr && topSession_ == nullptr) {
3947         SLOGE("CreateWantAgent error, histroyDescriptor and topSession_ null");
3948         return nullptr;
3949     }
3950     std::vector<AbilityRuntime::WantAgent::WantAgentConstant::Flags> flags;
3951     flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG);
3952     std::vector<std::shared_ptr<AAFwk::Want>> wants;
3953     std::shared_ptr<AAFwk::Want> want = std::make_shared<AAFwk::Want>();
3954     std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> launWantAgent;
3955     string bundleName = DEFAULT_BUNDLE_NAME;
3956     string abilityName = DEFAULT_ABILITY_NAME;
3957     auto uid = -1;
3958     auto isCustomer = false;
3959     if (topSession_ != nullptr) {
3960         bundleName = topSession_->GetBundleName();
3961         abilityName = topSession_->GetAbilityName();
3962         uid = topSession_->GetUid();
3963         launWantAgent = std::make_shared<AbilityRuntime::WantAgent::WantAgent>(topSession_->GetLaunchAbility());
3964         auto res = AbilityRuntime::WantAgent::WantAgentHelper::GetWant(launWantAgent, want);
3965         isCustomer = (res == AVSESSION_SUCCESS) && (bundleName == want->GetElement().GetBundleName());
3966         SLOGI("CreateWantAgent GetWant res=%{public}d", res);
3967     }
3968     if (histroyDescriptor != nullptr) {
3969         SLOGI("CreateWantAgent with historyDescriptor");
3970         bundleName = histroyDescriptor->elementName_.GetBundleName();
3971         abilityName = histroyDescriptor->elementName_.GetAbilityName();
3972         uid = histroyDescriptor->uid_;
3973         isCustomer = false;
3974     }
3975     SLOGI("CreateWantAgent bundleName %{public}s, abilityName %{public}s, isCustomer %{public}d",
3976         bundleName.c_str(), abilityName.c_str(), isCustomer);
3977     if (!isCustomer) {
3978         AppExecFwk::ElementName element("", bundleName, abilityName);
3979         want->SetElement(element);
3980     }
3981     wants.push_back(want);
3982     AbilityRuntime::WantAgent::WantAgentInfo wantAgentInfo(
3983         0,
3984         AbilityRuntime::WantAgent::WantAgentConstant::OperationType::START_ABILITY,
3985         flags,
3986         wants,
3987         nullptr
3988     );
3989     return AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, uid);
3990 }
3991 
RemoveExpired(std::list<std::chrono::system_clock::time_point> & list,const std::chrono::system_clock::time_point & now,int32_t time)3992 void AVSessionService::RemoveExpired(std::list<std::chrono::system_clock::time_point> &list,
3993     const std::chrono::system_clock::time_point &now, int32_t time)
3994 {
3995     auto iter = list.begin();
3996     while (iter != list.end()) {
3997         auto duration = now - static_cast<std::chrono::system_clock::time_point>(*iter);
3998         int32_t durationInSeconds = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
3999         if (std::abs(durationInSeconds) > time) {
4000             iter = list.erase(iter);
4001         } else {
4002             break;
4003         }
4004     }
4005 }
4006 
PublishEvent(int32_t mediaPlayState)4007 void AVSessionService::PublishEvent(int32_t mediaPlayState)
4008 {
4009     OHOS::AAFwk::Want want;
4010     want.SetAction(MEDIA_CONTROL_STATE);
4011     want.SetParam(MEDIA_PLAY_STATE, mediaPlayState);
4012     EventFwk::CommonEventData data;
4013     data.SetWant(want);
4014     EventFwk::CommonEventPublishInfo publishInfo;
4015     int ret = EventFwk::CommonEventManager::NewPublishCommonEvent(data, publishInfo);
4016     SLOGI("NewPublishCommonEvent:%{public}d return %{public}d", mediaPlayState, ret);
4017 }
4018 
GetDefaultImageStr()4019 std::string GetDefaultImageStr()
4020 {
4021     std::string imgStr = "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQuMDAwMDAwIiBoZWlnaHQ9IjI0LjAwMDAwMCIgd"
4022     "mlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5r"
4023     "PSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj4KCTxkZXNjPgoJCQlDcmVhdGVkIHdpdGggUGl4c28uCgk8L2Rlc2M+Cgk8ZGV"
4024     "mcy8+Cgk8ZyBvcGFjaXR5PSIwLjMwMDAwMCI+CgkJPGNpcmNsZSBpZD0i6JKZ54mIIiByPSIxMi4wMDAwMDAiIHRyYW5zZm9ybT0ibW"
4025     "F0cml4KDAgMSAtMSAwIDEyIDEyKSIgZmlsbD0iI0ZGRkZGRiIgZmlsbC1vcGFjaXR5PSIxLjAwMDAwMCIvPgoJCTxjaXJjbGUgaWQ9I"
4026     "uiSmeeJiCIgcj0iMTEuNTAwMDAwIiB0cmFuc2Zvcm09Im1hdHJpeCgwIDEgLTEgMCAxMiAxMikiIHN0cm9rZT0iI0ZGRkZGRiIgc3Ry"
4027     "b2tlLW9wYWNpdHk9IjAiIHN0cm9rZS13aWR0aD0iMS4wMDAwMDAiLz4KCTwvZz4KCTxtYXNrIGlkPSJtYXNrXzE1M183OTU5IiBmaWx"
4028     "sPSJ3aGl0ZSI+CgkJPHBhdGggaWQ9IuW9oueKtue7k+WQiCIgZD0iTTE3LjY0MzYgNi42NTM5OUMxNy42NTM1IDYuNzE2OCAxNy42Nj"
4029     "AxIDYuNzgwMDkgMTcuNjYzNCA2Ljg0MzUxTDE3LjY2NTkgNi45Mzg4NEwxNy42NjY2IDE0LjE2NjZDMTcuNjY2NiAxNC4xNzk3IDE3L"
4030     "jY2NjIgMTQuMTkyNiAxNy42NjU1IDE0LjIwNTVDMTcuNjYxNiAxNC44NjgzIDE3LjY1NDYgMTUuMTgzNyAxNy41MTE0IDE1LjcxNDlD"
4031     "MTcuMzY1OCAxNi4yNTQzIDE3LjA4MDkgMTYuNzYyMSAxNi41MTMyIDE3LjA4OTRDMTUuNDggMTcuNjg0OCAxNC4yMjggMTcuNDUwOSA"
4032     "xMy43MTY3IDE2LjU2NjlDMTMuMjA1NCAxNS42ODI5IDEzLjYyODUgMTQuNDgzNSAxNC42NjE2IDEzLjg4ODFDMTUuMDg2MSAxMy42ND"
4033     "M0IDE1LjYyNTcgMTMuNDI3MSAxNS45OTg5IDEzLjA4NTVDMTYuMjIzIDEyLjg4MDQgMTYuMzMyMiAxMi41ODU1IDE2LjMzMjIgMTEuO"
4034     "TE4OEMxNi4zMzIyIDExLjkwMDQgMTYuMzMyNSAxMS44ODI0IDE2LjMzMyAxMS44NjUxTDE2LjMzMjcgOC41MDk4OUw5LjY2NjU2IDku"
4035     "Njg2MjhMOS42NjY1NiAxNS4xMzEyQzkuNjY3MyAxNS4yNzA4IDkuNjY3MjQgMTUuNDExMyA5LjY2NjU2IDE1LjU1MDNMOS42NjY1NiA"
4036     "xNS42NjY3QzkuNjY2NTYgMTUuNjc4MyA5LjY2NjI2IDE1LjY4OTggOS42NjU2NSAxNS43MDE0QzkuNjYxNSAxNi4zMDk2IDkuNjQ5Mz"
4037     "UgMTYuNjIwNCA5LjUxMjA4IDE3LjEyOTVDOS4zNjY1OCAxNy42Njg4IDkuMDgxNiAxOC4xNzY3IDguNTEzOTIgMTguNTAzOUM3LjQ4M"
4038     "DcxIDE5LjA5OTQgNi4yMjg3IDE4Ljg2NTQgNS43MTc0MSAxNy45ODE0QzUuMjA2MTIgMTcuMDk3NCA1LjYyOTIxIDE1Ljg5OCA2LjY2"
4039     "MjM1IDE1LjMwMjZDNy4wODY3OSAxNS4wNTggNy42MjY0IDE0Ljg0MTcgNy45OTk2MyAxNC41QzguMjIzNjkgMTQuMjk0OSA4LjMzMjk"
4040     "1IDE0IDguMzMyOTUgMTMuMzMzM0M4LjMzMjk1IDEzLjMyMjcgOC4zMzMwNyAxMy4zMTIyIDguMzMzMjUgMTMuMzAxOUw4LjMzMzI1ID"
4041     "cuODMwNzVDOC4zMzMyNSA2Ljk2NzUzIDguOTM0MTQgNi4yMjcwNSA5Ljc2NjYgNi4wNDE1Nkw5Ljg4MTUzIDYuMDE5NzFMMTUuNTQ3N"
4042     "SA1LjEyNzk5QzE2LjU0NzcgNC45NzA1MiAxNy40ODYyIDUuNjUzNzUgMTcuNjQzNiA2LjY1Mzk5WiIgY2xpcC1ydWxlPSJldmVub2Rk"
4043     "IiBmaWxsPSIiIGZpbGwtb3BhY2l0eT0iMS4wMDAwMDAiIGZpbGwtcnVsZT0iZXZlbm9kZCIvPgoJPC9tYXNrPgoJPHBhdGggaWQ9IuW"
4044     "9oueKtue7k+WQiCIgZD0iTTE3LjY0MzYgNi42NTM5OUMxNy42NTM1IDYuNzE2OCAxNy42NjAxIDYuNzgwMDkgMTcuNjYzNCA2Ljg0Mz"
4045     "UxTDE3LjY2NTkgNi45Mzg4NEwxNy42NjY2IDE0LjE2NjZDMTcuNjY2NiAxNC4xNzk3IDE3LjY2NjIgMTQuMTkyNiAxNy42NjU1IDE0L"
4046     "jIwNTVDMTcuNjYxNiAxNC44NjgzIDE3LjY1NDYgMTUuMTgzNyAxNy41MTE0IDE1LjcxNDlDMTcuMzY1OCAxNi4yNTQzIDE3LjA4MDkg"
4047     "MTYuNzYyMSAxNi41MTMyIDE3LjA4OTRDMTUuNDggMTcuNjg0OCAxNC4yMjggMTcuNDUwOSAxMy43MTY3IDE2LjU2NjlDMTMuMjA1NCA"
4048     "xNS42ODI5IDEzLjYyODUgMTQuNDgzNSAxNC42NjE2IDEzLjg4ODFDMTUuMDg2MSAxMy42NDM0IDE1LjYyNTcgMTMuNDI3MSAxNS45OT"
4049     "g5IDEzLjA4NTVDMTYuMjIzIDEyLjg4MDQgMTYuMzMyMiAxMi41ODU1IDE2LjMzMjIgMTEuOTE4OEMxNi4zMzIyIDExLjkwMDQgMTYuM"
4050     "zMyNSAxMS44ODI0IDE2LjMzMyAxMS44NjUxTDE2LjMzMjcgOC41MDk4OUw5LjY2NjU2IDkuNjg2MjhMOS42NjY1NiAxNS4xMzEyQzku"
4051     "NjY3MyAxNS4yNzA4IDkuNjY3MjQgMTUuNDExMyA5LjY2NjU2IDE1LjU1MDNMOS42NjY1NiAxNS42NjY3QzkuNjY2NTYgMTUuNjc4MyA"
4052     "5LjY2NjI2IDE1LjY4OTggOS42NjU2NSAxNS43MDE0QzkuNjYxNSAxNi4zMDk2IDkuNjQ5MzUgMTYuNjIwNCA5LjUxMjA4IDE3LjEyOT"
4053     "VDOS4zNjY1OCAxNy42Njg4IDkuMDgxNiAxOC4xNzY3IDguNTEzOTIgMTguNTAzOUM3LjQ4MDcxIDE5LjA5OTQgNi4yMjg3IDE4Ljg2N"
4054     "TQgNS43MTc0MSAxNy45ODE0QzUuMjA2MTIgMTcuMDk3NCA1LjYyOTIxIDE1Ljg5OCA2LjY2MjM1IDE1LjMwMjZDNy4wODY3OSAxNS4w"
4055     "NTggNy42MjY0IDE0Ljg0MTcgNy45OTk2MyAxNC41QzguMjIzNjkgMTQuMjk0OSA4LjMzMjk1IDE0IDguMzMyOTUgMTMuMzMzM0M4LjM"
4056     "zMjk1IDEzLjMyMjcgOC4zMzMwNyAxMy4zMTIyIDguMzMzMjUgMTMuMzAxOUw4LjMzMzI1IDcuODMwNzVDOC4zMzMyNSA2Ljk2NzUzID"
4057     "guOTM0MTQgNi4yMjcwNSA5Ljc2NjYgNi4wNDE1Nkw5Ljg4MTUzIDYuMDE5NzFMMTUuNTQ3NSA1LjEyNzk5QzE2LjU0NzcgNC45NzA1M"
4058     "iAxNy40ODYyIDUuNjUzNzUgMTcuNjQzNiA2LjY1Mzk5WiIgY2xpcC1ydWxlPSJldmVub2RkIiBmaWxsPSIjMDAwMDAwIiBmaWxsLW9w"
4059     "YWNpdHk9IjAuNDAwMDAwIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIG1hc2s9InVybCgjbWFza18xNTNfNzk1OSkiLz4KCTxwYXRoIGlkPSL"
4060     "lvaLnirbnu5PlkIgiIGQ9IiIgY2xpcC1ydWxlPSJldmVub2RkIiBmaWxsPSIjMDAwMDAwIiBmaWxsLW9wYWNpdHk9IjAuMDAwMDAwIi"
4061     "BmaWxsLXJ1bGU9ImV2ZW5vZGQiLz4KPC9zdmc+Cg==";
4062     return imgStr;
4063 }
4064 
ConvertDefaultImage()4065 std::shared_ptr<Media::PixelMap> ConvertDefaultImage()
4066 {
4067     if (g_defaultMediaImage) {
4068         return g_defaultMediaImage;
4069     }
4070 
4071     std::string image = GetDefaultImageStr();
4072     uint32_t errorCode = 0;
4073     Media::SourceOptions opts;
4074     auto imageSource = Media::ImageSource::CreateImageSource(reinterpret_cast<const uint8_t*>(image.c_str()),
4075         image.length(), opts, errorCode);
4076     if (imageSource != nullptr) {
4077         Media::DecodeOptions dOpts;
4078         dOpts.allocatorType = Media::AllocatorType::HEAP_ALLOC;
4079         g_defaultMediaImage = imageSource->CreatePixelMap(dOpts, errorCode);
4080         if (g_defaultMediaImage != nullptr) {
4081             SLOGI("ConvertDefaultImage CreatePixelMap success");
4082             return g_defaultMediaImage;
4083         }
4084     } else {
4085         SLOGE("ConvertDefaultImage createImageSource fail");
4086     }
4087     return nullptr;
4088 }
4089 
4090 
AddCapsule(std::string title,bool isCapsuleUpdate,std::shared_ptr<AVSessionPixelMap> innerPixelMap,std::shared_ptr<Notification::NotificationLocalLiveViewContent> content,Notification::NotificationRequest * request)4091 void AddCapsule(std::string title, bool isCapsuleUpdate, std::shared_ptr<AVSessionPixelMap> innerPixelMap,
4092     std::shared_ptr<Notification::NotificationLocalLiveViewContent> content,
4093     Notification::NotificationRequest* request)
4094 {
4095     const float scaleSize = 0.3;
4096     std::shared_ptr<Media::PixelMap> pixelMap = AVSessionPixelMapAdapter::ConvertFromInner(innerPixelMap);
4097     if (pixelMap == nullptr) {
4098         SLOGI("AddCapsule ConvertDefaultImage");
4099         pixelMap = ConvertDefaultImage();
4100     } else {
4101         pixelMap->scale(scaleSize, scaleSize, Media::AntiAliasingOption::HIGH);
4102     }
4103     auto capsule = Notification::NotificationCapsule();
4104     capsule.SetIcon(pixelMap);
4105     capsule.SetTitle(title);
4106     if (isCapsuleUpdate) {
4107         std::shared_ptr<AAFwk::WantParams> wantParam = std::make_shared<AAFwk::WantParams>();
4108         wantParam->SetParam("hw_capsule_icon_animation_type", OHOS::AAFwk::Integer::Box(1));
4109         SLOGI("MediaCapsule CapsuleUpdate");
4110         request->SetAdditionalData(wantParam);
4111     }
4112 
4113     if (!g_isCapsuleLive2) {
4114         capsule.SetBackgroundColor("#2E3033");
4115     }
4116 
4117     content->SetCapsule(capsule);
4118     content->addFlag(Notification::NotificationLocalLiveViewContent::LiveViewContentInner::CAPSULE);
4119     SLOGI("PublishNotification with MediaCapsule");
4120 }
4121 
NotifyFlowControl()4122 bool AVSessionService::NotifyFlowControl()
4123 {
4124     // flow control
4125     std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
4126     RemoveExpired(flowControlPublishTimestampList_, now);
4127     if (flowControlPublishTimestampList_.size() >= MAX_NOTIFICATION_NUM) {
4128         SLOGE("PublishNotification Exeed MAX_NOTIFICATION_NUM");
4129         return true;
4130     }
4131     flowControlPublishTimestampList_.push_back(now);
4132     return false;
4133 }
4134 
CreateNftRemoveWant(int32_t uid)4135 std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> AVSessionService::CreateNftRemoveWant(int32_t uid)
4136 {
4137     std::vector<std::shared_ptr<AAFwk::Want>> wants;
4138     std::shared_ptr<AAFwk::Want> want = std::make_shared<AAFwk::Want>();
4139     want->SetAction("EVENT_REMOVE_MEDIACONTROLLER_LIVEVIEW");
4140     wants.push_back(want);
4141     AbilityRuntime::WantAgent::WantAgentInfo wantAgentInfo(
4142         0,
4143         AbilityRuntime::WantAgent::WantAgentConstant::OperationType::SEND_COMMON_EVENT,
4144         AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG,
4145         wants,
4146         nullptr
4147     );
4148     return AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, uid);
4149 }
4150 
GetLocalTitle()4151 std::string AVSessionService::GetLocalTitle()
4152 {
4153     AVMetaData meta = topSession_->GetMetaData();
4154     bool isTitleLyric = (topSession_->GetBundleName() == DEFAULT_BUNDLE_NAME) && !meta.GetDescription().empty();
4155     bool isAncoLyric = (topSession_->GetUid() == audioBrokerUid && meta.GetArtist().find("-") != std::string::npos);
4156     std::string songName;
4157     if (isTitleLyric) {
4158         std::string description = meta.GetDescription();
4159         size_t pos = description.find(";");
4160         if (pos != std::string::npos) {
4161             songName = description.substr(0, pos);
4162         }
4163         SLOGI("GetLocalTitle description:%{public}s, title:%{public}s", description.c_str(), songName.c_str());
4164     } else if (isAncoLyric) {
4165         std::string ancoTitle = meta.GetArtist();
4166         size_t posi = ancoTitle.find("-");
4167         if (posi != std::string::npos) {
4168             songName = ancoTitle.substr(0, posi);
4169         }
4170         SLOGI("GetLocalTitle isAncoLyric title:%{public}s", songName.c_str());
4171     }
4172     std::string localTitle = isTitleLyric || isAncoLyric ? songName : meta.GetTitle();
4173     SLOGI("GetLocalTitle localTitle:%{public}s", localTitle.c_str());
4174     return localTitle;
4175 }
4176 
4177 // LCOV_EXCL_START
NotifySystemUI(const AVSessionDescriptor * historyDescriptor,bool isActiveSession,bool addCapsule,bool isCapsuleUpdate)4178 void AVSessionService::NotifySystemUI(const AVSessionDescriptor* historyDescriptor, bool isActiveSession,
4179     bool addCapsule, bool isCapsuleUpdate)
4180 {
4181     CHECK_AND_RETURN_LOG(!is2in1_, "2in1 not support.");
4182     int32_t result = Notification::NotificationHelper::SubscribeLocalLiveViewNotification(NOTIFICATION_SUBSCRIBER);
4183     CHECK_AND_RETURN_LOG(result == ERR_OK, "create notification subscriber error %{public}d", result);
4184     SLOGI("NotifySystemUI isActiveNtf %{public}d addCapsule %{public}d isCapsuleUpdate %{public}d",
4185         isActiveSession, addCapsule, isCapsuleUpdate);
4186     hasMediaCapsule_ = addCapsule;
4187     Notification::NotificationRequest request;
4188     std::shared_ptr<Notification::NotificationLocalLiveViewContent> localLiveViewContent =
4189         std::make_shared<Notification::NotificationLocalLiveViewContent>();
4190     CHECK_AND_RETURN_LOG(localLiveViewContent != nullptr, "avsession item local live view content nullptr error");
4191     localLiveViewContent->SetType(SYSTEMUI_LIVEVIEW_TYPECODE_MDEDIACONTROLLER);
4192     localLiveViewContent->SetTitle(historyDescriptor && !isActiveSession ? "" : "AVSession NotifySystemUI");
4193     localLiveViewContent->SetText(historyDescriptor && !isActiveSession ? "" : "AVSession NotifySystemUI");
4194 
4195     std::shared_ptr<Notification::NotificationContent> content =
4196         std::make_shared<Notification::NotificationContent>(localLiveViewContent);
4197     CHECK_AND_RETURN_LOG(content != nullptr, "avsession item notification content nullptr error");
4198     int32_t userId = historyDescriptor ? historyDescriptor->userId_ : GetUsersManager().GetCurrentUserId();
4199     SLOGD("get historyDescriptor %{public}d with userId:%{public}d",
4200         static_cast<int>(historyDescriptor != nullptr), userId);
4201     if (addCapsule && topSession_) {
4202         std::shared_ptr<AVSessionPixelMap> iPixelMap = std::make_shared<AVSessionPixelMap>();
4203         topSession_->ReadMetaDataImg(iPixelMap);
4204         AVQueueItem item;
4205         topSession_->GetCurrentCastItem(item);
4206         std::string notifyText = item.GetDescription() && item.GetDescription()->GetPcmSrc() ?
4207             item.GetDescription()->GetTitle() : GetLocalTitle();
4208         AddCapsule(notifyText, isCapsuleUpdate, iPixelMap, localLiveViewContent, &(request));
4209         AVSessionEventHandler::GetInstance().AVSessionRemoveTask("CheckCardStateChangeStop");
4210         hasCardStateChangeStopTask_ = false;
4211     }
4212 
4213     auto uid = topSession_ ? (topSession_->GetUid() == audioBrokerUid ?
4214         BundleStatusAdapter::GetInstance().GetUidFromBundleName(topSession_->GetBundleName(), userId) :
4215         topSession_->GetUid()) : (historyDescriptor ? historyDescriptor->uid_ : -1);
4216     bool isBroker = topSession_ != nullptr && topSession_->GetUid() == audioBrokerUid;
4217     request.SetSlotType(Notification::NotificationConstant::SlotType::LIVE_VIEW);
4218     request.SetNotificationId(0);
4219     request.SetContent(content);
4220     request.SetCreatorUid(avSessionUid);
4221     request.SetUnremovable(true);
4222     request.SetInProgress(true);
4223     request.SetOwnerUid(uid);
4224     request.SetIsAgentNotification(true);
4225     if (isBroker) {
4226         request.SetOwnerUserId(defaultUserId);
4227     }
4228     std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> wantAgent = CreateWantAgent(historyDescriptor);
4229     CHECK_AND_RETURN_LOG(wantAgent != nullptr, "wantAgent nullptr error");
4230     request.SetWantAgent(wantAgent);
4231     request.SetLabel(std::to_string(userId));
4232     if (topSession_) {
4233         if (topSession_->IsNotShowNotification()) {
4234             std::shared_ptr<AAFwk::WantParams> want = std::make_shared<AAFwk::WantParams>();
4235             want->SetParam("hw_live_view_hidden_when_keyguard", OHOS::AAFwk::Boolean::Box(true));
4236             SLOGI("PublishNotification with hw_live_view_hidden_when_keyguard uid: %{public}d", uid);
4237             request.SetAdditionalData(want);
4238         }
4239     }
4240     std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> removeWantAgent = CreateNftRemoveWant(uid);
4241     request.SetRemovalWantAgent(removeWantAgent);
4242     {
4243         std::lock_guard lockGuard(notifyLock_);
4244         g_NotifyRequest = request;
4245     }
4246     AVSessionEventHandler::GetInstance().AVSessionRemoveTask("NotifyFlowControl");
4247     Notification::NotificationHelper::SetHashCodeRule(1);
4248     if (NotifyFlowControl()) {
4249         AVSessionEventHandler::GetInstance().AVSessionPostTask(
4250             [this, uid, isBroker]() {
4251                 bool isTopSessionNtf = false;
4252                 {
4253                     std::lock_guard lockGuard(sessionServiceLock_);
4254                     isTopSessionNtf = topSession_ != nullptr && (topSession_->GetUid() == uid ||
4255                         (isBroker && topSession_->GetUid() == audioBrokerUid));
4256                 }
4257                 std::lock_guard lockGuard(notifyLock_);
4258                 hasRemoveEvent_ = false;
4259                 if (isTopSessionNtf) {
4260                     auto ret = Notification::NotificationHelper::PublishNotification(g_NotifyRequest);
4261                     SLOGI("WaitPublish uid %{public}d, isTop %{public}d result %{public}d", uid, isTopSessionNtf, ret);
4262                 }
4263             }, "NotifyFlowControl", CLICK_TIMEOUT);
4264     } else {
4265         hasRemoveEvent_ = false;
4266         result = Notification::NotificationHelper::PublishNotification(request);
4267         SLOGI("PublishNotification uid %{public}d, user id %{public}d, result %{public}d", uid, userId, result);
4268     }
4269 }
4270 // LCOV_EXCL_STOP
4271 
NotifyRemoteDistributedSessionControllersChanged(const std::vector<sptr<IRemoteObject>> & sessionControllers)4272 void AVSessionService::NotifyRemoteDistributedSessionControllersChanged(
4273     const std::vector<sptr<IRemoteObject>>& sessionControllers)
4274 {
4275     SLOGI("NotifyRemoteDistributedSessionControllersChanged size: %{public}d", (int) sessionControllers.size());
4276     std::lock_guard lockGuard(sessionListenersLock_);
4277     std::map<pid_t, sptr<ISessionListener>> listenerMap = GetUsersManager().GetSessionListener();
4278     for (const auto& [pid, listener] : listenerMap) {
4279         AVSESSION_TRACE_SYNC_START("AVSessionService::OnSessionCreate");
4280         if (listener != nullptr) {
4281             listener->OnRemoteDistributedSessionChange(sessionControllers);
4282         }
4283     }
4284     std::map<pid_t, sptr<ISessionListener>> listenerMapForAll = GetUsersManager().GetSessionListenerForAllUsers();
4285     for (const auto& [pid, listener] : listenerMapForAll) {
4286         AVSESSION_TRACE_SYNC_START("AVSessionService::OnSessionCreate");
4287         if (listener != nullptr) {
4288             listener->OnRemoteDistributedSessionChange(sessionControllers);
4289         }
4290     }
4291 
4292     {
4293         std::lock_guard lockGuard(migrateListenersLock_);
4294         for (const auto& listener : innerSessionListeners_) {
4295             if (listener != nullptr) {
4296                 listener->OnRemoteDistributedSessionChange(sessionControllers);
4297             }
4298         }
4299     }
4300 }
4301 
InitRadarBMS()4302 void AVSessionService::InitRadarBMS()
4303 {
4304     AVSessionRadar::GetInstance().InitBMS();
4305 }
4306 
GetAllowedPlaybackCallbackFunc()4307 std::function<bool(int32_t, int32_t)> AVSessionService::GetAllowedPlaybackCallbackFunc()
4308 {
4309     return [](int32_t uid, int32_t pid) -> bool {
4310         auto mgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
4311         CHECK_AND_RETURN_RET_LOG(mgr != nullptr, true, "SystemAbilityManager is null");
4312         auto object = mgr->CheckSystemAbility(APP_MGR_SERVICE_ID);
4313         CHECK_AND_RETURN_RET_LOG(object != nullptr, true, "APP_MAGR_SERVICE is null");
4314         bool hasSession = GetContainer().PidHasSession(pid);
4315         bool isBack = AppManagerAdapter::GetInstance().IsAppBackground(uid, pid);
4316         bool isSystem = PermissionChecker::GetInstance().CheckSystemPermissionByUid(uid);
4317         auto ret = hasSession || isSystem || !isBack;
4318         SLOGI("avsession uid=%{public}d pid=%{public}d hasSession=%{public}d isBack=%{public}d isSystem=%{public}d",
4319             uid, pid, hasSession, isBack, isSystem);
4320         return ret;
4321     };
4322 }
4323 
4324 #ifdef ENABLE_AVSESSION_SYSEVENT_CONTROL
GetVersionName(const std::string & bundleName)4325 static std::string GetVersionName(const std::string& bundleName)
4326 {
4327     std::string versionName = "";
4328     auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
4329     if (samgr == nullptr) {
4330         SLOGE("Get ability manager failed");
4331         return versionName;
4332     }
4333 
4334     sptr<IRemoteObject> object = samgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
4335     if (object == nullptr) {
4336         SLOGE("object is NULL.");
4337         return versionName;
4338     }
4339 
4340     sptr<OHOS::AppExecFwk::IBundleMgr> bms = iface_cast<OHOS::AppExecFwk::IBundleMgr>(object);
4341     if (bms == nullptr) {
4342         SLOGE("bundle manager service is NULL.");
4343         return versionName;
4344     }
4345 
4346     AppExecFwk::BundleInfo bundleInfo;
4347     if (!bms->GetBundleInfo(bundleName,
4348         static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION),
4349         bundleInfo, AppExecFwk::Constants::ALL_USERID)) {
4350             SLOGE("GetBundleInfo=%{public}s fail", bundleName.c_str());
4351             return versionName;
4352     }
4353     versionName = bundleInfo.versionName;
4354     if (versionName.empty()) {
4355         SLOGE("get versionName form application failed.");
4356         return versionName;
4357     }
4358     return versionName;
4359 }
4360 
ReportSessionState(const sptr<AVSessionItem> & session,SessionState state)4361 void AVSessionService::ReportSessionState(const sptr<AVSessionItem>& session, SessionState state)
4362 {
4363     if (session == nullptr) {
4364         SLOGE("ReportSessionState session is null");
4365         return;
4366     }
4367     AVSessionSysEvent::GetInstance().UpdateState(session->GetBundleName(),
4368         GetVersionName(session->GetBundleName()), state);
4369 }
4370 
ReportSessionControl(const std::string & bundleName,int32_t cmd)4371 void AVSessionService::ReportSessionControl(const std::string& bundleName, int32_t cmd)
4372 {
4373     if (cmd == AVControlCommand::SESSION_CMD_PLAY ||
4374         cmd == AVControlCommand::SESSION_CMD_PAUSE ||
4375         cmd == CONTROL_COLD_START) {
4376         AVSessionSysEvent::GetInstance().UpdateControl(bundleName, cmd,
4377             BundleStatusAdapter::GetInstance().GetBundleNameFromUid(GetCallingUid()));
4378     }
4379 }
4380 
4381 #endif // ENABLE_AVSESSION_SYSEVENT_CONTROL
4382 } // namespace OHOS::AVSession
4383