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