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