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 "audio_manager_proxy.h"
17 #include "av_router.h"
18 #include "avsession_service.h"
19 #include "avcontroller_item.h"
20 #include "avsession_log.h"
21 #include "avsession_errors.h"
22 #include "avsession_descriptor.h"
23 #include "avsession_trace.h"
24 #include "avsession_sysevent.h"
25 #include "avsession_utils.h"
26 #include "remote_session_sink.h"
27 #include "remote_session_source.h"
28 #include "remote_session_source_proxy.h"
29 #include "remote_session_sink_proxy.h"
30 #include "permission_checker.h"
31 #include "session_xcollie.h"
32 #include "avsession_item.h"
33 #include "avsession_radar.h"
34 #include "avsession_event_handler.h"
35 #include "bundle_status_adapter.h"
36 #include "want_agent_helper.h"
37 #include "array_wrapper.h"
38 #include "string_wrapper.h"
39 
40 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
41 #include "avcast_controller_proxy.h"
42 #include "avcast_controller_item.h"
43 #include "collaboration_manager.h"
44 #endif
45 
46 #if !defined(WINDOWS_PLATFORM) and !defined(MAC_PLATFORM) and !defined(IOS_PLATFORM)
47 #include <malloc.h>
48 #include <string>
49 #include <openssl/crypto.h>
50 #endif
51 
52 using namespace OHOS::AudioStandard;
53 
54 namespace OHOS::AVSession {
55 
56 static const std::string AVSESSION_DYNAMIC_DISPLAY_LIBRARY_PATH = std::string("libavsession_dynamic_display.z.so");
57 
58 const std::map<int32_t, string> sessionTypeMap_ = {
59     {AVSession::SESSION_TYPE_VIDEO, "video"},
60     {AVSession::SESSION_TYPE_VOICE_CALL, "voice_call"},
61     {AVSession::SESSION_TYPE_VIDEO_CALL, "video_call"},
62 };
63 
AVSessionItem(const AVSessionDescriptor& descriptor, int32_t userId)64 AVSessionItem::AVSessionItem(const AVSessionDescriptor& descriptor, int32_t userId)
65     : descriptor_(descriptor), userId_(userId)
66 {
67     SLOGI("constructor session id=%{public}s, userId=%{public}d",
68         AVSessionUtils::GetAnonySessionId(descriptor_.sessionId_).c_str(), userId_);
69 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
70     cssListener_ = std::make_shared<CssListener>(this);
71 #endif
72     dynamicLoader_ = std::make_unique<AVSessionDynamicLoader>();
73     avsessionDisaplayIntf_ = nullptr;
74 }
75 
~AVSessionItem()76 AVSessionItem::~AVSessionItem()
77 {
78     SLOGI("destroy with activeCheck session id=%{public}s, userId=%{public}d",
79         AVSessionUtils::GetAnonySessionId(descriptor_.sessionId_).c_str(), userId_);
80     if (IsActive()) {
81         Deactivate();
82     }
83     if (avsessionDisaplayIntf_) {
84         delete avsessionDisaplayIntf_;
85         avsessionDisaplayIntf_ = nullptr;
86     }
87 }
88 
89 // LCOV_EXCL_START
GetSessionId()90 std::string AVSessionItem::GetSessionId()
91 {
92     return descriptor_.sessionId_;
93 }
94 
GetSessionType()95 std::string AVSessionItem::GetSessionType()
96 {
97     auto iter = sessionTypeMap_.find(descriptor_.sessionType_);
98     if (iter != sessionTypeMap_.end()) {
99         return iter->second;
100     } else {
101         return "audio";
102     }
103 }
104 // LCOV_EXCL_STOP
105 
Destroy()106 int32_t AVSessionItem::Destroy()
107 {
108     SLOGI("AVSessionItem send service destroy event to service, check serviceCallback exist");
109     HISYSEVENT_BEHAVIOR("SESSION_API_BEHAVIOR",
110         "API_NAME", "Destroy",
111         "BUNDLE_NAME", GetBundleName(),
112         "SESSION_ID", AVSessionUtils::GetAnonySessionId(GetSessionId()),
113         "SESSION_TAG", descriptor_.sessionTag_,
114         "SESSION_TYPE", GetSessionType(),
115         "ERROR_CODE", AVSESSION_SUCCESS,
116         "ERROR_MSG", "SUCCESS");
117     if (serviceCallback_) {
118         SLOGI("AVSessionItem send service destroy event to service");
119         serviceCallback_(*this);
120     }
121     return AVSESSION_SUCCESS;
122 }
123 
DestroyTask()124 int32_t AVSessionItem::DestroyTask()
125 {
126     {
127         std::lock_guard lockGuard(destroyLock_);
128         if (isDestroyed_) {
129             SLOGI("session is already destroyed");
130             return AVSESSION_SUCCESS;
131         }
132         isDestroyed_ = true;
133     }
134 
135     std::string sessionId = descriptor_.sessionId_;
136     std::string fileName = AVSessionUtils::GetCachePathName(userId_) + sessionId + AVSessionUtils::GetFileSuffix();
137     AVSessionUtils::DeleteFile(fileName);
138     {
139         std::lock_guard controllerLockGuard(controllersLock_);
140         for (auto it = controllers_.begin(); it != controllers_.end();) {
141             if (it->second) {
142                 (it->second)->HandleSessionDestroy();
143             }
144             it = controllers_.erase(it);
145         }
146     }
147     {
148         std::lock_guard lockGuard(callbackLock_);
149         if (callback_) {
150             callback_.clear();
151         }
152     }
153 
154 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
155     SLOGI("Session destroy with castHandle: %{public}ld", castHandle_);
156     ReleaseAVCastControllerInner();
157     if (descriptor_.sessionTag_ != "RemoteCast" && castHandle_ > 0) {
158         if (!collaborationNeedNetworkId_.empty()) {
159             CollaborationManager::GetInstance().PublishServiceState(collaborationNeedNetworkId_.c_str(),
160                 ServiceCollaborationManagerBussinessStatus::SCM_IDLE);
161         }
162         AVRouter::GetInstance().UnRegisterCallback(castHandle_, cssListener_);
163         ReleaseCast();
164     }
165     StopCastDisplayListener();
166 #endif
167     return AVSESSION_SUCCESS;
168 }
169 
SetAVCallMetaData(const AVCallMetaData& avCallMetaData)170 int32_t AVSessionItem::SetAVCallMetaData(const AVCallMetaData& avCallMetaData)
171 {
172     std::lock_guard lockGuard(avsessionItemLock_);
173     CHECK_AND_RETURN_RET_LOG(avCallMetaData_.CopyFrom(avCallMetaData), AVSESSION_ERROR, "AVCallMetaData set error");
174     std::shared_ptr<AVSessionPixelMap> innerPixelMap = avCallMetaData_.GetMediaImage();
175     if (innerPixelMap != nullptr) {
176         std::string sessionId = GetSessionId();
177         std::string fileDir = AVSessionUtils::GetCachePathName(userId_);
178         AVSessionUtils::WriteImageToFile(innerPixelMap, fileDir, sessionId + AVSessionUtils::GetFileSuffix());
179         innerPixelMap->Clear();
180         avCallMetaData_.SetMediaImage(innerPixelMap);
181     }
182 
183     {
184         std::lock_guard controllerLockGuard(controllersLock_);
185         for (const auto& [pid, controller] : controllers_) {
186             if (controller != nullptr) {
187                 controller->HandleAVCallMetaDataChange(avCallMetaData);
188             }
189         }
190     }
191     return AVSESSION_SUCCESS;
192 }
193 
194 // LCOV_EXCL_START
SetAVCallState(const AVCallState& avCallState)195 int32_t AVSessionItem::SetAVCallState(const AVCallState& avCallState)
196 {
197     {
198         std::lock_guard lockGuard(avsessionItemLock_);
199         CHECK_AND_RETURN_RET_LOG(avCallState_.CopyFrom(avCallState), AVSESSION_ERROR, "AVCallState set error");
200     }
201 
202     {
203         std::lock_guard controllerLockGuard(controllersLock_);
204         for (const auto& [pid, controller] : controllers_) {
205             if (controller != nullptr) {
206                 controller->HandleAVCallStateChange(avCallState);
207             }
208         }
209     }
210     return AVSESSION_SUCCESS;
211 }
212 // LCOV_EXCL_STOP
213 
GetAVMetaData(AVMetaData& meta)214 int32_t AVSessionItem::GetAVMetaData(AVMetaData& meta)
215 {
216     std::lock_guard lockGuard(avsessionItemLock_);
217     SessionXCollie sessionXCollie("avsession::GetAVMetaData");
218     std::string sessionId = GetSessionId();
219     std::string fileDir = AVSessionUtils::GetCachePathName(userId_);
220     std::string fileName = sessionId + AVSessionUtils::GetFileSuffix();
221     std::shared_ptr<AVSessionPixelMap> innerPixelMap = metaData_.GetMediaImage();
222     AVSessionUtils::ReadImageFromFile(innerPixelMap, fileDir, fileName);
223 
224     std::string avQueueFileDir = AVSessionUtils::GetFixedPathName();
225     std::string avQueueFileName = GetBundleName() + "_" + metaData_.GetAVQueueId() + AVSessionUtils::GetFileSuffix();
226     std::shared_ptr<AVSessionPixelMap> avQueuePixelMap = metaData_.GetAVQueueImage();
227     AVSessionUtils::ReadImageFromFile(avQueuePixelMap, avQueueFileDir, avQueueFileName);
228 
229     meta = metaData_;
230     return AVSESSION_SUCCESS;
231 }
232 
233 // LCOV_EXCL_START
ProcessFrontSession(const std::string& source)234 int32_t AVSessionItem::ProcessFrontSession(const std::string& source)
235 {
236     SLOGI("ProcessFrontSession with directly handle %{public}s ", source.c_str());
237     HandleFrontSession();
238     return AVSESSION_SUCCESS;
239 }
240 
HandleFrontSession()241 void AVSessionItem::HandleFrontSession()
242 {
243     bool isMetaEmpty;
244     {
245         std::lock_guard lockGuard(avsessionItemLock_);
246         isMetaEmpty = metaData_.GetTitle().empty() && metaData_.GetMediaImage() == nullptr &&
247             metaData_.GetMediaImageUri().empty();
248     }
249     SLOGI("frontSession bundle=%{public}s metaEmpty=%{public}d Cmd=%{public}d castCmd=%{public}d firstAdd=%{public}d",
250         GetBundleName().c_str(), isMetaEmpty, static_cast<int32_t>(supportedCmd_.size()),
251         static_cast<int32_t>(supportedCastCmds_.size()), isFirstAddToFront_);
252     if (isMetaEmpty || (supportedCmd_.size() == 0 && supportedCastCmds_.size() == 0)) {
253         if (!isFirstAddToFront_ && serviceCallbackForUpdateSession_) {
254             serviceCallbackForUpdateSession_(GetSessionId(), false);
255             isFirstAddToFront_ = true;
256         }
257     } else {
258         if (isFirstAddToFront_ && serviceCallbackForUpdateSession_) {
259             serviceCallbackForUpdateSession_(GetSessionId(), true);
260             isFirstAddToFront_ = false;
261         }
262     }
263 }
264 
HasAvQueueInfo()265 bool AVSessionItem::HasAvQueueInfo()
266 {
267     std::lock_guard lockGuard(avsessionItemLock_);
268     if (metaData_.GetAVQueueName().empty() || metaData_.GetAVQueueId().empty()) {
269         SLOGD("avqueuename or avqueueid is empty");
270         return false;
271     }
272     if (metaData_.GetAVQueueImage() == nullptr && metaData_.GetAVQueueImageUri().empty()) {
273         SLOGD("avqueue img is empty");
274         return false;
275     }
276     if (playbackState_.GetState() != AVPlaybackState::PLAYBACK_STATE_PLAY) {
277         SLOGD("current avqueueinfo is not playing");
278         return false;
279     }
280 
281     return true;
282 }
283 
ReportSetAVMetaDataInfo(const AVMetaData& meta)284 void AVSessionItem::ReportSetAVMetaDataInfo(const AVMetaData& meta)
285 {
286     std::string mediaImage = "false";
287     std::string avQueueImage = "false";
288     if (meta.GetMediaImage() != nullptr || !(meta.GetMediaImageUri().empty())) {
289         mediaImage = "true";
290     }
291     if (meta.GetAVQueueImage() != nullptr || !(meta.GetAVQueueImageUri().empty())) {
292         avQueueImage = "true";
293     }
294     std::string API_PARAM_STRING = "assetId: " + meta.GetAssetId() + ", "
295                                     + "artist: " + meta.GetArtist() + ", "
296                                     + "title: " + meta.GetTitle() + ", "
297                                     + "subtitle: " + meta.GetSubTitle() + ", "
298                                     + "avQueueId: " + meta.GetAVQueueId() + ", "
299                                     + "duration: " + std::to_string(meta.GetDuration()) + ", "
300                                     + "avQueueName: " + meta.GetAVQueueName() + ", "
301                                     + "mediaImage: " + mediaImage + ", "
302                                     + "avqueueImage: " + avQueueImage;
303     HISYSEVENT_BEHAVIOR("SESSION_API_BEHAVIOR", "API_NAME", "SetAVMetaData",
304         "BUNDLE_NAME", GetBundleName(), "SESSION_ID", AVSessionUtils::GetAnonySessionId(GetSessionId()),
305         "SESSION_TAG", descriptor_.sessionTag_, "SESSION_TYPE", GetSessionType(), "API_PARAM", API_PARAM_STRING,
306         "ERROR_CODE", AVSESSION_SUCCESS, "ERROR_MSG", "SUCCESS");
307 }
308 
SetAVMetaData(const AVMetaData& meta)309 int32_t AVSessionItem::SetAVMetaData(const AVMetaData& meta)
310 {
311     {
312         std::lock_guard lockGuard(avsessionItemLock_);
313         SessionXCollie sessionXCollie("avsession::SetAVMetaData");
314         ReportSetAVMetaDataInfo(meta);
315         CHECK_AND_RETURN_RET_LOG(metaData_.CopyFrom(meta), AVSESSION_ERROR, "AVMetaData set error");
316         std::shared_ptr<AVSessionPixelMap> innerPixelMap = metaData_.GetMediaImage();
317         if (innerPixelMap != nullptr) {
318             std::string sessionId = GetSessionId();
319             std::string fileDir = AVSessionUtils::GetCachePathName(userId_);
320             AVSessionUtils::WriteImageToFile(innerPixelMap, fileDir, sessionId + AVSessionUtils::GetFileSuffix());
321             innerPixelMap->Clear();
322             metaData_.SetMediaImage(innerPixelMap);
323         }
324     }
325     ProcessFrontSession("SetAVMetaData");
326     if (HasAvQueueInfo() && serviceCallbackForAddAVQueueInfo_) {
327         serviceCallbackForAddAVQueueInfo_(*this);
328     }
329     SLOGI("send metadata change event to controllers with title %{public}s", meta.GetTitle().c_str());
330     AVSessionEventHandler::GetInstance().AVSessionPostTask([this, meta]() {
331         SLOGI("HandleMetaDataChange in postTask with title %{public}s and size %{public}d",
332             meta.GetTitle().c_str(), static_cast<int>(controllers_.size()));
333         std::lock_guard controllerLockGuard(controllersLock_);
334         CHECK_AND_RETURN_LOG(controllers_.size() > 0, "handle with no controller, return");
335         for (const auto& [pid, controller] : controllers_) {
336             if (controller != nullptr) {
337                 controller->HandleMetaDataChange(meta);
338             }
339         }
340         }, "HandleMetaDataChange", 0);
341 
342     std::lock_guard remoteSourceLockGuard(remoteSourceLock_);
343     if (remoteSource_ != nullptr) {
344         SLOGI("set remote AVMetaData");
345         auto ret = remoteSource_->SetAVMetaData(meta);
346         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetAVMetaData failed");
347     }
348     return AVSESSION_SUCCESS;
349 }
350 
GetAVQueueItems(std::vector<AVQueueItem>& items)351 int32_t AVSessionItem::GetAVQueueItems(std::vector<AVQueueItem>& items)
352 {
353     std::lock_guard lock_guard(avsessionItemLock_);
354     items = queueItems_;
355     return AVSESSION_SUCCESS;
356 }
357 
SetAVQueueItems(const std::vector<AVQueueItem>& items)358 int32_t AVSessionItem::SetAVQueueItems(const std::vector<AVQueueItem>& items)
359 {
360     {
361         std::lock_guard lock_guard(avsessionItemLock_);
362         queueItems_ = items;
363     }
364 
365     {
366         std::lock_guard controllerLockGuard(controllersLock_);
367         for (const auto& [pid, controller] : controllers_) {
368             if (controller != nullptr) {
369                 controller->HandleQueueItemsChange(items);
370             }
371         }
372     }
373 
374     std::lock_guard remoteSourceLockGuard(remoteSourceLock_);
375     if (remoteSource_ != nullptr) {
376         auto ret = remoteSource_->SetAVQueueItems(items);
377         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetAVQueueItems failed");
378     }
379     return AVSESSION_SUCCESS;
380 }
381 
GetAVQueueTitle(std::string& title)382 int32_t AVSessionItem::GetAVQueueTitle(std::string& title)
383 {
384     std::lock_guard lockGuard(avsessionItemLock_);
385     title = queueTitle_;
386     return AVSESSION_SUCCESS;
387 }
388 
SetAVQueueTitle(const std::string& title)389 int32_t AVSessionItem::SetAVQueueTitle(const std::string& title)
390 {
391     {
392         std::lock_guard lockGuard(avsessionItemLock_);
393         queueTitle_ = title;
394     }
395 
396     {
397         std::lock_guard controllerLockGuard(controllersLock_);
398         for (const auto& [pid, controller] : controllers_) {
399             if (controller != nullptr) {
400                 controller->HandleQueueTitleChange(title);
401             }
402         }
403     }
404     std::lock_guard remoteSourceLockGuard(remoteSourceLock_);
405     if (remoteSource_ != nullptr) {
406         auto ret = remoteSource_->SetAVQueueTitle(title);
407         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetAVQueueTitle failed");
408     }
409     return AVSESSION_SUCCESS;
410 }
411 
SetAVPlaybackState(const AVPlaybackState& state)412 int32_t AVSessionItem::SetAVPlaybackState(const AVPlaybackState& state)
413 {
414     {
415         std::lock_guard lockGuard(avsessionItemLock_);
416         CHECK_AND_RETURN_RET_LOG(playbackState_.CopyFrom(state), AVSESSION_ERROR, "AVPlaybackState set error");
417     }
418     if (HasAvQueueInfo() && serviceCallbackForAddAVQueueInfo_) {
419         serviceCallbackForAddAVQueueInfo_(*this);
420     }
421     {
422         std::lock_guard controllerLockGuard(controllersLock_);
423         for (const auto& [pid, controller] : controllers_) {
424             if (controller != nullptr) {
425                 controller->HandlePlaybackStateChange(state);
426             }
427         }
428     }
429 
430     std::string isFavor = state.GetFavorite()? "true" : "false";
431     std::string API_PARAM_STRING = "state: " + std::to_string(state.GetState()) + ", "
432                                     + "elapsedTime: " + std::to_string(state.GetPosition().elapsedTime_) + ", "
433                                     + "updateTime: " + std::to_string(state.GetPosition().updateTime_) + ", "
434                                     + "loopMode: " + std::to_string(state.GetLoopMode()) + ", "
435                                     + "isFavorite: " + isFavor;
436     HISYSEVENT_BEHAVIOR("SESSION_API_BEHAVIOR",
437         "API_NAME", "SetAVPlaybackState",
438         "BUNDLE_NAME", GetBundleName(),
439         "SESSION_ID", AVSessionUtils::GetAnonySessionId(GetSessionId()),
440         "SESSION_TAG", descriptor_.sessionTag_,
441         "SESSION_TYPE", GetSessionType(),
442         "API_PARAM", API_PARAM_STRING,
443         "ERROR_CODE", AVSESSION_SUCCESS,
444         "ERROR_MSG", "SUCCESS");
445     std::lock_guard remoteSourceLockGuard(remoteSourceLock_);
446     if (remoteSource_ != nullptr) {
447         remoteSource_->SetAVPlaybackState(state);
448     }
449     return AVSESSION_SUCCESS;
450 }
451 
GetAVPlaybackState(AVPlaybackState& state)452 int32_t AVSessionItem::GetAVPlaybackState(AVPlaybackState& state)
453 {
454     std::lock_guard lockGuard(avsessionItemLock_);
455     state = playbackState_;
456     return AVSESSION_SUCCESS;
457 }
458 // LCOV_EXCL_STOP
459 
SetLaunchAbility(const AbilityRuntime::WantAgent::WantAgent& ability)460 int32_t AVSessionItem::SetLaunchAbility(const AbilityRuntime::WantAgent::WantAgent& ability)
461 {
462     launchAbility_ = ability;
463     std::shared_ptr<AAFwk::Want> want = std::make_shared<AAFwk::Want>();
464     std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> launWantAgent =
465         std::make_shared<AbilityRuntime::WantAgent::WantAgent>(ability);
466     int res = AVSESSION_SUCCESS;
467     if (want != nullptr && launWantAgent != nullptr) {
468         res = AbilityRuntime::WantAgent::WantAgentHelper::GetWant(launWantAgent, want);
469     }
470     std::string errMsg = "Get want failed.";
471     std::string bundleName = "";
472     std::string abilityName = "";
473     std::string moduleName = "";
474     if (res == AVSESSION_SUCCESS) {
475         bundleName = want->GetElement().GetBundleName().c_str();
476         abilityName = want->GetElement().GetAbilityName().c_str();
477         moduleName = want->GetElement().GetModuleName().c_str();
478         errMsg = "SUCCESS";
479     }
480     std::string API_PARAM_STRING = "bundleName: " + bundleName + ", "
481                                     + "moduleName: " + moduleName + ", "
482                                     + "abilityName: " + abilityName;
483     HISYSEVENT_BEHAVIOR("SESSION_API_BEHAVIOR",
484         "API_NAME", "SetLaunchAbility",
485         "BUNDLE_NAME", GetBundleName(),
486         "SESSION_ID", AVSessionUtils::GetAnonySessionId(GetSessionId()),
487         "SESSION_TAG", descriptor_.sessionTag_,
488         "SESSION_TYPE", GetSessionType(),
489         "API_PARAM", API_PARAM_STRING,
490         "ERROR_CODE", res,
491         "ERROR_MSG", errMsg);
492     return AVSESSION_SUCCESS;
493 }
494 
495 // LCOV_EXCL_START
GetExtras(AAFwk::WantParams& extras)496 int32_t AVSessionItem::GetExtras(AAFwk::WantParams& extras)
497 {
498     std::lock_guard lockGuard(avsessionItemLock_);
499     extras = extras_;
500     return AVSESSION_SUCCESS;
501 }
502 
SetExtras(const AAFwk::WantParams& extras)503 int32_t AVSessionItem::SetExtras(const AAFwk::WantParams& extras)
504 {
505     {
506         std::lock_guard lockGuard(avsessionItemLock_);
507         extras_ = extras;
508     }
509 
510 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
511     if (extras.HasParam("requireAbilityList")) {
512         auto value = extras.GetParam("requireAbilityList");
513         AAFwk::IArray* list = AAFwk::IArray::Query(value);
514         if (list != nullptr && AAFwk::Array::IsStringArray(list)) {
515             SetExtrasInner(list);
516         }
517     }
518 #endif
519     {
520         std::lock_guard controllerLockGuard(controllersLock_);
521         for (const auto& [pid, controller] : controllers_) {
522             if (controller != nullptr) {
523                 controller->HandleExtrasChange(extras);
524             }
525         }
526     }
527 
528     std::lock_guard remoteSourceLockGuard(remoteSourceLock_);
529     if (remoteSource_ != nullptr) {
530         auto ret = remoteSource_->SetExtrasRemote(extras);
531         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetRemoteExtras failed");
532     }
533     return AVSESSION_SUCCESS;
534 }
535 
GetControllerInner()536 sptr<IRemoteObject> AVSessionItem::GetControllerInner()
537 {
538     std::lock_guard controllerLockGuard(controllersLock_);
539     auto iter = controllers_.find(GetPid());
540     if (iter != controllers_.end()) {
541         return iter->second;
542     }
543 
544     sptr<AVSessionItem> session(this);
545     sptr<AVControllerItem> result = new(std::nothrow) AVControllerItem(GetPid(), session, userId_);
546     CHECK_AND_RETURN_RET_LOG(result != nullptr, nullptr, "malloc controller failed");
547     result->isFromSession_ = true;
548     SLOGI("New controller from sessionItem when get controller.");
549     controllers_.insert({GetPid(), result});
550     return result;
551 }
552 
553 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
InitAVCastControllerProxy()554 void AVSessionItem::InitAVCastControllerProxy()
555 {
556     if (castControllerProxy_ == nullptr) {
557         SLOGI("CastControllerProxy is null, start get new proxy");
558         {
559             std::lock_guard lockGuard(castHandleLock_);
560             castControllerProxy_ = AVRouter::GetInstance().GetRemoteController(castHandle_);
561         }
562     }
563 }
564 
ReportAVCastControllerInfo()565 void AVSessionItem::ReportAVCastControllerInfo()
566 {
567     HISYSEVENT_BEHAVIOR("SESSION_API_BEHAVIOR",
568         "API_NAME", "getAVCastController",
569         "BUNDLE_NAME", GetBundleName(),
570         "SESSION_ID", AVSessionUtils::GetAnonySessionId(GetSessionId()),
571         "SESSION_TAG", descriptor_.sessionTag_,
572         "SESSION_TYPE", GetSessionType(),
573         "ERROR_CODE", AVSESSION_SUCCESS,
574         "ERROR_MSG", "SUCCESS");
575 }
576 
GetAVCastControllerInner()577 sptr<IRemoteObject> AVSessionItem::GetAVCastControllerInner()
578 {
579     InitAVCastControllerProxy();
580     CHECK_AND_RETURN_RET_LOG(castControllerProxy_ != nullptr, nullptr,
581         "castControllerProxy_ is null when get avCastController");
582     sptr<AVCastControllerItem> castController = new (std::nothrow) AVCastControllerItem();
583     CHECK_AND_RETURN_RET_LOG(castController != nullptr, nullptr, "malloc avCastController failed");
584     std::shared_ptr<AVCastControllerItem> sharedPtr = std::shared_ptr<AVCastControllerItem>(castController.GetRefPtr(),
585         [holder = castController](const auto*) {});
586     CHECK_AND_RETURN_RET_LOG(sharedPtr != nullptr, nullptr, "malloc AVCastControllerItem failed");
587     ReportAVCastControllerInfo();
588 
589     auto callback = [this](int32_t cmd, std::vector<int32_t>& supportedCastCmds) {
590         std::lock_guard lockGuard(avsessionItemLock_);
591         SLOGI("process cast valid cmd: %{public}d", cmd);
592         if (cmd == AVCastControlCommand::CAST_CONTROL_CMD_INVALID) {
593             supportedCastCmds_.clear();
594             supportedCastCmds = supportedCastCmds_;
595             HandleCastValidCommandChange(supportedCastCmds_);
596             return;
597         }
598         if (cmd == AVCastControlCommand::CAST_CONTROL_CMD_MAX) {
599             supportedCastCmds = supportedCastCmds_;
600             return;
601         }
602         if (descriptor_.sessionTag_ == "RemoteCast") {
603             SLOGI("sink session should not modify valid cmds");
604             supportedCastCmds = {};
605             return;
606         }
607         if (cmd > removeCmdStep_) {
608             DeleteSupportCastCommand(cmd - removeCmdStep_);
609         } else {
610             AddSupportCastCommand(cmd);
611         }
612         supportedCastCmds = supportedCastCmds_;
613         return;
614     }
615 
616     sharedPtr->Init(castControllerProxy_, callback);
617     {
618         std::lock_guard lockGuard(castControllersLock_);
619         castControllers_.emplace_back(sharedPtr);
620     }
621     sptr<IRemoteObject> remoteObject = castController;
622 
623     sharedPtr->SetSessionTag(descriptor_.sessionTag_);
624     InitializeCastCommands();
625     return remoteObject;
626 }
627 
ReleaseAVCastControllerInner()628 void AVSessionItem::ReleaseAVCastControllerInner()
629 {
630     SLOGI("Release AVCastControllerInner");
631     std::lock_guard lockGuard(castControllersLock_);
632     for (auto controller : castControllers_) {
633         if (controller != nullptr) {
634             controller->Destroy();
635         }
636     }
637     castControllerProxy_ = nullptr;
638 }
639 #endif
640 
RegisterCallbackInner(const sptr<IAVSessionCallback>& callback)641 int32_t AVSessionItem::RegisterCallbackInner(const sptr<IAVSessionCallback>& callback)
642 {
643     std::lock_guard callbackLockGuard(callbackLock_);
644     callback_ = callback;
645     return AVSESSION_SUCCESS;
646 }
647 // LCOV_EXCL_STOP
648 
Activate()649 int32_t AVSessionItem::Activate()
650 {
651     descriptor_.isActive_ = true;
652     std::lock_guard controllerLockGuard(controllersLock_);
653     HISYSEVENT_BEHAVIOR("SESSION_API_BEHAVIOR",
654         "API_NAME", "Activate",
655         "BUNDLE_NAME", GetBundleName(),
656         "SESSION_ID", AVSessionUtils::GetAnonySessionId(GetSessionId()),
657         "SESSION_TAG", descriptor_.sessionTag_,
658         "SESSION_TYPE", GetSessionType(),
659         "ERROR_CODE", AVSESSION_SUCCESS,
660         "ERROR_MSG", "SUCCESS");
661     for (const auto& [pid, controller] : controllers_) {
662         if (controller != nullptr) {
663             controller->HandleActiveStateChange(true);
664         }
665     }
666     if (descriptor_.sessionType_ == AVSession::SESSION_TYPE_VOICE_CALL ||
667         descriptor_.sessionType_ == AVSession::SESSION_TYPE_VIDEO_CALL) {
668         SLOGI("set audio scene for voip start");
669         AudioSystemManager *audioManager = AudioSystemManager::GetInstance();
670         AudioScene audioScene = AudioScene::AUDIO_SCENE_CALL_START;
671         if (audioManager != nullptr) {
672             audioManager->SetAudioScene(audioScene);
673         }
674     }
675 
676     return AVSESSION_SUCCESS;
677 }
678 
679 // LCOV_EXCL_START
Deactivate()680 int32_t AVSessionItem::Deactivate()
681 {
682     descriptor_.isActive_ = false;
683     std::lock_guard controllerLockGuard(controllersLock_);
684     HISYSEVENT_BEHAVIOR("SESSION_API_BEHAVIOR",
685         "API_NAME", "Deactivate",
686         "BUNDLE_NAME", GetBundleName(),
687         "SESSION_ID", AVSessionUtils::GetAnonySessionId(GetSessionId()),
688         "SESSION_TAG", descriptor_.sessionTag_,
689         "SESSION_TYPE", GetSessionType(),
690         "ERROR_CODE", AVSESSION_SUCCESS,
691         "ERROR_MSG", "SUCCESS");
692     for (const auto& [pid, controller] : controllers_) {
693         if (controller != nullptr) {
694             controller->HandleActiveStateChange(false);
695         }
696     }
697     if (descriptor_.sessionType_ == AVSession::SESSION_TYPE_VOICE_CALL ||
698         descriptor_.sessionType_ == AVSession::SESSION_TYPE_VIDEO_CALL) {
699         SLOGI("set audio scene for voip end");
700         AudioSystemManager *audioManager = AudioSystemManager::GetInstance();
701         AudioScene audioScene = AudioScene::AUDIO_SCENE_CALL_END;
702         if (audioManager != nullptr) {
703             audioManager->SetAudioScene(audioScene);
704         }
705     }
706 
707     return AVSESSION_SUCCESS;
708 }
709 // LCOV_EXCL_STOP
710 
IsActive()711 bool AVSessionItem::IsActive()
712 {
713     return descriptor_.isActive_;
714 }
715 
716 // LCOV_EXCL_START
AddSupportCommand(int32_t cmd)717 int32_t AVSessionItem::AddSupportCommand(int32_t cmd)
718 {
719     CHECK_AND_RETURN_RET_LOG(cmd > AVControlCommand::SESSION_CMD_INVALID, AVSESSION_ERROR, "invalid cmd");
720     CHECK_AND_RETURN_RET_LOG(cmd < AVControlCommand::SESSION_CMD_MAX, AVSESSION_ERROR, "invalid cmd");
721     SLOGI("AddSupportCommand=%{public}d", cmd);
722     if (cmd == AVControlCommand::SESSION_CMD_MEDIA_KEY_SUPPORT) {
723         SLOGI("enable media key event listen");
724         isMediaKeySupport = true;
725         return AVSESSION_SUCCESS;
726     }
727     auto iter = std::find(supportedCmd_.begin(), supportedCmd_.end(), cmd);
728     CHECK_AND_RETURN_RET_LOG(iter == supportedCmd_.end(), AVSESSION_SUCCESS, "cmd already been added");
729     {
730         std::lock_guard lockGuard(avsessionItemLock_);
731         supportedCmd_.push_back(cmd);
732     }
733     std::string API_PARAM_STRING = "cmd :" + std::to_string(cmd);
734     HISYSEVENT_BEHAVIOR("SESSION_API_BEHAVIOR",
735         "API_NAME", "OnEvent",
736         "BUNDLE_NAME", GetBundleName(),
737         "SESSION_ID", AVSessionUtils::GetAnonySessionId(GetSessionId()),
738         "SESSION_TAG", descriptor_.sessionTag_,
739         "SESSION_TYPE", GetSessionType(),
740         "API_PARAM", API_PARAM_STRING,
741         "ERROR_CODE", AVSESSION_SUCCESS,
742         "ERROR_MSG", "SUCCESS");
743     ProcessFrontSession("AddSupportCommand");
744 
745     {
746         std::lock_guard controllerLockGuard(controllersLock_);
747         SLOGI("send add command event to controller, size:%{public}d", static_cast<int>(controllers_.size()));
748         for (const auto& [pid, controller] : controllers_) {
749             if (controller != nullptr) {
750                 controller->HandleValidCommandChange(supportedCmd_);
751             }
752         }
753     }
754 
755 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
756     AddSessionCommandToCast(cmd);
757 #endif
758     return AVSESSION_SUCCESS;
759 }
760 
761 int32_t AVSessionItem::DeleteSupportCommand(int32_t cmd)
762 {
763     CHECK_AND_RETURN_RET_LOG(cmd > AVControlCommand::SESSION_CMD_INVALID, AVSESSION_ERROR, "invalid cmd");
764     CHECK_AND_RETURN_RET_LOG(cmd < AVControlCommand::SESSION_CMD_MAX, AVSESSION_ERROR, "invalid cmd");
765     SLOGI("DeleteSupportCommand=%{public}d", cmd);
766     if (cmd == AVControlCommand::SESSION_CMD_MEDIA_KEY_SUPPORT) {
767         SLOGI("disable media key event listen");
768         isMediaKeySupport = false;
769         return AVSESSION_SUCCESS;
770     }
771     auto iter = std::remove(supportedCmd_.begin(), supportedCmd_.end(), cmd);
772     {
773         std::lock_guard lockGuard(avsessionItemLock_);
774         supportedCmd_.erase(iter, supportedCmd_.end());
775     }
776     std::string API_PARAM_STRING = "cmd :" + std::to_string(cmd);
777     HISYSEVENT_BEHAVIOR("SESSION_API_BEHAVIOR",
778         "API_NAME", "OffEvent",
779         "BUNDLE_NAME", GetBundleName(),
780         "SESSION_ID", AVSessionUtils::GetAnonySessionId(GetSessionId()),
781         "SESSION_TAG", descriptor_.sessionTag_,
782         "SESSION_TYPE", GetSessionType(),
783         "API_PARAM", API_PARAM_STRING,
784         "ERROR_CODE", AVSESSION_SUCCESS,
785         "ERROR_MSG", "SUCCESS");
786     ProcessFrontSession("DeleteSupportCommand");
787 
788     {
789         SLOGI("send delete command event to controller, size:%{public}d", static_cast<int>(controllers_.size()));
790         std::lock_guard controllerLockGuard(controllersLock_);
791         for (const auto& [pid, controller] : controllers_) {
792             if (controller != nullptr) {
793                 controller->HandleValidCommandChange(supportedCmd_);
794             }
795         }
796     }
797 
798 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
799     RemoveSessionCommandFromCast(cmd);
800 #endif
801     return AVSESSION_SUCCESS;
802 }
803 // LCOV_EXCL_STOP
804 
805 int32_t AVSessionItem::SetSessionEvent(const std::string& event, const AAFwk::WantParams& args)
806 {
807     {
808         std::lock_guard controllerLockGuard(controllersLock_);
809         for (const auto& [pid, controller] : controllers_) {
810             if (controller != nullptr) {
811                 controller->HandleSetSessionEvent(event, args);
812             }
813         }
814     }
815     std::lock_guard remoteSourceLockGuard(remoteSourceLock_);
816     if (remoteSource_ != nullptr) {
817         auto ret = remoteSource_->SetSessionEventRemote(event, args);
818         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetSessionEvent failed");
819     }
820     return AVSESSION_SUCCESS;
821 }
822 
823 std::string AVSessionItem::GetAnonymousDeviceId(std::string deviceId)
824 {
825     if (deviceId.empty() || deviceId.length() < DEVICE_ID_MIN_LEN) {
826         return "unknown";
827     }
828     const uint32_t half = DEVICE_ID_MIN_LEN / 2;
829     return deviceId.substr(0, half) + "**" + deviceId.substr(deviceId.length() - half);
830 }
831 
832 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
833 int32_t AVSessionItem::RegisterListenerStreamToCast(const std::map<std::string, std::string>& serviceNameMapState,
834     DeviceInfo deviceInfo)
835 {
836     if (castHandle_ > 0) {
837         return AVSESSION_ERROR;
838     }
839     {
840         std::lock_guard displayListenerLockGuard(mirrorToStreamLock_);
841         mirrorToStreamFlag_ = true;
842     }
843     std::lock_guard lockGuard(castHandleLock_);
844     castServiceNameMapState_ = serviceNameMapState;
845     OutputDeviceInfo outputDeviceInfo;
846     outputDeviceInfo.deviceInfos_.emplace_back(deviceInfo);
847     int64_t castHandle = AVRouter::GetInstance().StartCast(outputDeviceInfo, castServiceNameMapState_);
848     castHandle_ = castHandle;
849     castHandleDeviceId_ = deviceInfo.deviceId_;
850     SLOGI("RegisterListenerStreamToCast check handle set to %{public}ld", castHandle_);
851     CHECK_AND_RETURN_RET_LOG(castHandle != AVSESSION_ERROR, AVSESSION_ERROR, "StartCast failed");
852     counter_ = firstStep;
853     AVRouter::GetInstance().RegisterCallback(castHandle, cssListener_);
854     AVRouter::GetInstance().SetServiceAllConnectState(castHandle, deviceInfo);
855     counter_ = secondStep;
856     UpdateCastDeviceMap(deviceInfo);
857 
858     DoContinuousTaskRegister();
859     HISYSEVENT_BEHAVIOR("SESSION_CAST_CONTROL",
860         "CONTROL_TYPE", "MirrorTostreamCast",
861         "PEER_DEVICE_ID", GetAnonymousDeviceId(deviceInfo.deviceId_),
862         "PEER_DEVICE_NAME", deviceInfo.deviceName_,
863         "PEER_DEVICE_TYPE", deviceInfo.deviceType_,
864         "PEER_NETWORK_ID", GetAnonymousDeviceId(deviceInfo.networkId_),
865         "PEER_SUPPORTED_PROTOCOL", deviceInfo.supportedProtocols_,
866         "BUNDLE_NAME", GetBundleName());
867     return AVSESSION_SUCCESS;
868 }
869 
870 // LCOV_EXCL_START
871 void AVSessionItem::InitializeCastCommands()
872 {
873     std::lock_guard lockGuard(avsessionItemLock_);
874     // always support setVolume command
875     auto iter = std::find(supportedCastCmds_.begin(), supportedCastCmds_.end(),
876         AVCastControlCommand::CAST_CONTROL_CMD_SET_VOLUME);
877     if (iter == supportedCastCmds_.end()) {
878         supportedCastCmds_.push_back(AVCastControlCommand::CAST_CONTROL_CMD_SET_VOLUME);
879     }
880 
881     iter = std::find(supportedCastCmds_.begin(), supportedCastCmds_.end(),
882         AVCastControlCommand::CAST_CONTROL_CMD_SET_SPEED);
883     if (iter == supportedCastCmds_.end()) {
884         supportedCastCmds_.push_back(AVCastControlCommand::CAST_CONTROL_CMD_SET_SPEED);
885     }
886 
887     iter = std::find(supportedCastCmds_.begin(), supportedCastCmds_.end(),
888         AVCastControlCommand::CAST_CONTROL_CMD_SEEK);
889     if (iter == supportedCastCmds_.end()) {
890         supportedCastCmds_.push_back(AVCastControlCommand::CAST_CONTROL_CMD_SEEK);
891         supportedCastCmds_.push_back(AVCastControlCommand::CAST_CONTROL_CMD_FAST_FORWARD);
892         supportedCastCmds_.push_back(AVCastControlCommand::CAST_CONTROL_CMD_REWIND);
893     }
894 
895     iter = std::find(supportedCmd_.begin(), supportedCmd_.end(), AVControlCommand::SESSION_CMD_SET_LOOP_MODE);
896     if (iter != supportedCmd_.end()) {
897         AddSessionCommandToCast(AVControlCommand::SESSION_CMD_SET_LOOP_MODE);
898     }
899 }
900 
901 int32_t AVSessionItem::SessionCommandToCastCommand(int32_t cmd)
902 {
903     if (cmd == AVControlCommand::SESSION_CMD_SET_LOOP_MODE) {
904         return AVCastControlCommand::CAST_CONTROL_CMD_SET_LOOP_MODE;
905     }
906     return AVCastControlCommand::CAST_CONTROL_CMD_INVALID;
907 }
908 
909 void AVSessionItem::AddSessionCommandToCast(int32_t cmd)
910 {
911     if (cmd != AVControlCommand::SESSION_CMD_SET_LOOP_MODE) {
912         return;
913     }
914 
915     if (castControllerProxy_ != nullptr) {
916         int32_t castCmd = SessionCommandToCastCommand(cmd);
917         std::lock_guard lockGuard(avsessionItemLock_);
918         auto iter = std::find(supportedCastCmds_.begin(), supportedCastCmds_.end(), castCmd);
919         if (iter != supportedCastCmds_.end()) {
920             SLOGI("castCmd have already been added, cmd:%{public}d", castCmd);
921             return;
922         }
923         supportedCastCmds_.push_back(castCmd);
924         HandleCastValidCommandChange(supportedCastCmds_);
925     }
926 }
927 
928 void AVSessionItem::RemoveSessionCommandFromCast(int32_t cmd)
929 {
930     if (cmd != AVControlCommand::SESSION_CMD_SET_LOOP_MODE) {
931         return;
932     }
933 
934     if (castControllerProxy_ != nullptr) {
935         int32_t castCmd = SessionCommandToCastCommand(cmd);
936         std::lock_guard lockGuard(avsessionItemLock_);
937         SLOGI("remove castcmd:%{public}d", castCmd);
938         auto iter = std::remove(supportedCastCmds_.begin(), supportedCastCmds_.end(), castCmd);
939         supportedCastCmds_.erase(iter, supportedCastCmds_.end());
940         HandleCastValidCommandChange(supportedCastCmds_);
941     }
942 }
943 
944 int32_t AVSessionItem::AddSupportCastCommand(int32_t cmd)
945 {
946     if (cmd <= AVCastControlCommand::CAST_CONTROL_CMD_INVALID ||
947         cmd >= AVCastControlCommand::CAST_CONTROL_CMD_MAX) {
948         SLOGI("add invalid cmd: %{public}d", cmd);
949         return AVSESSION_ERROR;
950     }
951     std::lock_guard lockGuard(avsessionItemLock_);
952     if (cmd == AVCastControlCommand::CAST_CONTROL_CMD_PLAY_STATE_CHANGE) {
953         auto iter = std::find(
954             supportedCastCmds_.begin(), supportedCastCmds_.end(), AVCastControlCommand::CAST_CONTROL_CMD_PLAY);
955         CHECK_AND_RETURN_RET_LOG(iter == supportedCastCmds_.end(), AVSESSION_SUCCESS, "cmd already been added");
956         supportedCastCmds_.push_back(AVCastControlCommand::CAST_CONTROL_CMD_PLAY);
957         supportedCastCmds_.push_back(AVCastControlCommand::CAST_CONTROL_CMD_PAUSE);
958         supportedCastCmds_.push_back(AVCastControlCommand::CAST_CONTROL_CMD_STOP);
959     } else if (cmd == AVCastControlCommand::CAST_CONTROL_CMD_SEEK) {
960         auto iter = std::find(supportedCastCmds_.begin(), supportedCastCmds_.end(), cmd);
961         CHECK_AND_RETURN_RET_LOG(iter == supportedCastCmds_.end(), AVSESSION_SUCCESS, "cmd already been added");
962         supportedCastCmds_.push_back(cmd);
963         supportedCastCmds_.push_back(AVCastControlCommand::CAST_CONTROL_CMD_FAST_FORWARD);
964         supportedCastCmds_.push_back(AVCastControlCommand::CAST_CONTROL_CMD_REWIND);
965     } else {
966         auto iter = std::find(supportedCastCmds_.begin(), supportedCastCmds_.end(), cmd);
967         CHECK_AND_RETURN_RET_LOG(iter == supportedCastCmds_.end(), AVSESSION_SUCCESS, "cmd already been added");
968         supportedCastCmds_.push_back(cmd);
969     }
970     ProcessFrontSession("AddSupportCastCommand");
971     HandleCastValidCommandChange(supportedCastCmds_);
972     return AVSESSION_SUCCESS;
973 }
974 
975 int32_t AVSessionItem::DeleteSupportCastCommand(int32_t cmd)
976 {
977     if (cmd <= AVCastControlCommand::CAST_CONTROL_CMD_INVALID ||
978         cmd >= AVCastControlCommand::CAST_CONTROL_CMD_MAX) {
979         SLOGI("delete invalid cmd: %{public}d", cmd);
980         return AVSESSION_ERROR;
981     }
982     std::lock_guard lockGuard(avsessionItemLock_);
983     if (cmd == AVCastControlCommand::CAST_CONTROL_CMD_PLAY_STATE_CHANGE) {
984         auto iter = std::remove(
985             supportedCastCmds_.begin(), supportedCastCmds_.end(), AVCastControlCommand::CAST_CONTROL_CMD_PLAY);
986         supportedCastCmds_.erase(iter, supportedCastCmds_.end());
987 
988         iter = std::remove(
989             supportedCastCmds_.begin(), supportedCastCmds_.end(), AVCastControlCommand::CAST_CONTROL_CMD_PAUSE);
990         supportedCastCmds_.erase(iter, supportedCastCmds_.end());
991 
992         iter = std::remove(
993             supportedCastCmds_.begin(), supportedCastCmds_.end(), AVCastControlCommand::CAST_CONTROL_CMD_STOP);
994         supportedCastCmds_.erase(iter, supportedCastCmds_.end());
995     } else if (cmd == AVCastControlCommand::CAST_CONTROL_CMD_SEEK) {
996         auto iter = std::remove(supportedCastCmds_.begin(), supportedCastCmds_.end(), cmd);
997         supportedCastCmds_.erase(iter, supportedCastCmds_.end());
998 
999         iter = std::remove(
1000             supportedCastCmds_.begin(), supportedCastCmds_.end(), AVCastControlCommand::CAST_CONTROL_CMD_FAST_FORWARD);
1001         supportedCastCmds_.erase(iter, supportedCastCmds_.end());
1002 
1003         iter = std::remove(
1004             supportedCastCmds_.begin(), supportedCastCmds_.end(), AVCastControlCommand::CAST_CONTROL_CMD_REWIND);
1005         supportedCastCmds_.erase(iter, supportedCastCmds_.end());
1006     } else {
1007         auto iter = std::remove(supportedCastCmds_.begin(), supportedCastCmds_.end(), cmd);
1008         supportedCastCmds_.erase(iter, supportedCastCmds_.end());
1009     }
1010     ProcessFrontSession("DeleteSupportCastCommand");
1011     HandleCastValidCommandChange(supportedCastCmds_);
1012     return AVSESSION_SUCCESS;
1013 }
1014 
1015 void AVSessionItem::HandleCastValidCommandChange(std::vector<int32_t> &cmds)
1016 {
1017     std::lock_guard lockGuard(castControllersLock_);
1018     SLOGI("send command change event to controller, controller size: %{public}d, cmds size is: %{public}d,",
1019         static_cast<int>(castControllers_.size()), cmds.size());
1020     for (auto controller : castControllers_) {
1021         if (controller != nullptr) {
1022             controller->HandleCastValidCommandChange(cmds);
1023         }
1024     }
1025 }
1026 
1027 int32_t AVSessionItem::ReleaseCast()
1028 {
1029     HISYSEVENT_BEHAVIOR("SESSION_API_BEHAVIOR",
1030         "API_NAME", "StopCasting",
1031         "BUNDLE_NAME", GetBundleName(),
1032         "SESSION_ID", AVSessionUtils::GetAnonySessionId(GetSessionId()),
1033         "SESSION_TAG", descriptor_.sessionTag_,
1034         "SESSION_TYPE", GetSessionType(),
1035         "ERROR_CODE", AVSESSION_SUCCESS,
1036         "ERROR_MSG", "SUCCESS");
1037     return StopCast();
1038 }
1039 
1040 int32_t AVSessionItem::CastAddToCollaboration(const OutputDeviceInfo& outputDeviceInfo)
1041 {
1042     SLOGI("enter CastAddToCollaboration");
1043     if (castDeviceInfoMap_.count(outputDeviceInfo.deviceInfos_[0].deviceId_) != 1) {
1044         SLOGE("deviceId map deviceinfo is not exit");
1045         return AVSESSION_ERROR;
1046     }
1047     ListenCollaborationRejectToStopCast();
1048     DeviceInfo cacheDeviceInfo = castDeviceInfoMap_[outputDeviceInfo.deviceInfos_[0].deviceId_];
1049     if (cacheDeviceInfo.networkId_.empty()) {
1050         SLOGI("untrusted device, networkId is empty, then input deviceId to ApplyAdvancedResource");
1051         collaborationNeedNetworkId_ = cacheDeviceInfo.deviceId_;
1052         networkIdIsEmpty_ = true;
1053     } else {
1054         collaborationNeedNetworkId_= cacheDeviceInfo.networkId_;
1055     }
1056     CollaborationManager::GetInstance().ApplyAdvancedResource(collaborationNeedNetworkId_.c_str());
1057     //wait collaboration callback 10s
1058     std::unique_lock <std::mutex> applyResultLock(collaborationApplyResultMutex_);
1059     bool flag = connectWaitCallbackCond_.wait_for(applyResultLock, std::chrono::seconds(collaborationCallbackTimeOut_),
1060         [this]() {
1061             return applyResultFlag_;
1062     });
1063     //wait user decision collaboration callback 60s
1064     if (waitUserDecisionFlag_) {
1065         flag = connectWaitCallbackCond_.wait_for(applyResultLock,
1066             std::chrono::seconds(collaborationUserCallbackTimeOut_),
1067         [this]() {
1068             return applyUserResultFlag_;
1069         });
1070     }
1071     applyResultFlag_ = false;
1072     applyUserResultFlag_ = false;
1073     waitUserDecisionFlag_ = false;
1074     CHECK_AND_RETURN_RET_LOG(flag, ERR_WAIT_ALLCONNECT_TIMEOUT, "collaboration callback timeout");
1075     if (collaborationRejectFlag_) {
1076         collaborationRejectFlag_ = false;
1077         SLOGE("collaboration callback reject");
1078         return ERR_ALLCONNECT_CAST_REJECT;
1079     }
1080     return AVSESSION_SUCCESS;
1081 }
1082 
1083 int32_t AVSessionItem::StartCast(const OutputDeviceInfo& outputDeviceInfo)
1084 {
1085     std::lock_guard lockGuard(castHandleLock_);
1086 
1087     // unregister pre castSession callback to avoid previous session timeout disconnect influence current session
1088     if (castHandle_ > 0) {
1089         if (castHandleDeviceId_ == outputDeviceInfo.deviceInfos_[0].deviceId_) {
1090             SLOGI("repeat startcast %{public}ld", castHandle_);
1091             return AVSESSION_ERROR;
1092         } else {
1093             SLOGI("cast check with pre cast alive %{public}ld, unregister callback", castHandle_);
1094             AVRouter::GetInstance().UnRegisterCallback(castHandle_, cssListener_);
1095         }
1096     }
1097     int32_t flag = CastAddToCollaboration(outputDeviceInfo);
1098     CHECK_AND_RETURN_RET_LOG(flag == AVSESSION_SUCCESS, AVSESSION_ERROR, "collaboration to start cast fail");
1099     int64_t castHandle = AVRouter::GetInstance().StartCast(outputDeviceInfo, castServiceNameMapState_);
1100     CHECK_AND_RETURN_RET_LOG(castHandle != AVSESSION_ERROR, AVSESSION_ERROR, "StartCast failed");
1101 
1102     castHandle_ = castHandle;
1103     SLOGI("start cast check handle set to %{public}ld", castHandle_);
1104     int32_t ret = AddDevice(static_cast<int32_t>(castHandle), outputDeviceInfo);
1105     if (ret == AVSESSION_SUCCESS) {
1106         castHandleDeviceId_ = outputDeviceInfo.deviceInfos_[0].deviceId_;
1107     }
1108     DoContinuousTaskRegister();
1109     return ret;
1110 }
1111 
1112 int32_t AVSessionItem::AddDevice(const int64_t castHandle, const OutputDeviceInfo& outputDeviceInfo)
1113 {
1114     SLOGI("Add device process");
1115     std::lock_guard lockGuard(castHandleLock_);
1116     AVRouter::GetInstance().RegisterCallback(castHandle_, cssListener_);
1117     int32_t castId = static_cast<int32_t>(castHandle_);
1118     int32_t ret = AVRouter::GetInstance().AddDevice(castId, outputDeviceInfo);
1119     SLOGI("Add device process with ret %{public}d", ret);
1120     return ret;
1121 }
1122 
1123 void AVSessionItem::DealCastState(int32_t castState)
1124 {
1125     if (newCastState == castState) {
1126         isUpdate = false;
1127     } else {
1128         if (counter_ == firstStep) {
1129             newCastState = virtualDeviceStateConnection;
1130         } else {
1131             newCastState = castState;
1132         }
1133         isUpdate = true;
1134     }
1135 }
1136 
1137 void AVSessionItem::DealDisconnect(DeviceInfo deviceInfo)
1138 {
1139     SLOGI("Is remotecast, received disconnect event for castHandle_: %{public}ld", castHandle_);
1140     AVRouter::GetInstance().UnRegisterCallback(castHandle_, cssListener_);
1141     AVRouter::GetInstance().StopCastSession(castHandle_);
1142     castHandle_ = -1;
1143     castHandleDeviceId_ = "-100";
1144     DoContinuousTaskUnregister();
1145     castControllerProxy_ = nullptr;
1146     {
1147         std::lock_guard lockGuard(avsessionItemLock_);
1148         supportedCastCmds_.clear();
1149     }
1150     SaveLocalDeviceInfo();
1151     ReportStopCastFinish("AVSessionItem::OnCastStateChange", deviceInfo);
1152 }
1153 
1154 void AVSessionItem::DealCollaborationPublishState(int32_t castState, DeviceInfo deviceInfo)
1155 {
1156     SLOGI("enter DealCollaborationPublishState");
1157     std::lock_guard displayListenerLockGuard(mirrorToStreamLock_);
1158     if (mirrorToStreamFlag_) {
1159         mirrorToStreamFlag_ = false;
1160         SLOGI("cast not add to collaboration when mirror to stream cast");
1161         return;
1162     }
1163     if (castState == castConnectStateForConnected_) { // 6 is connected status (stream)
1164         if (networkIdIsEmpty_) {
1165             SLOGI("untrusted device, networkId is empty, get netwokId from castplus");
1166             AVRouter::GetInstance().GetRemoteNetWorkId(
1167                 castHandle_, deviceInfo.deviceId_, collaborationNeedNetworkId_);
1168             networkIdIsEmpty_ = false;
1169         }
1170         if (collaborationNeedNetworkId_.empty()) {
1171             SLOGI("cast add to collaboration in peer, get netwokId from castplus");
1172             AVRouter::GetInstance().GetRemoteNetWorkId(
1173                 castHandle_, deviceInfo.deviceId_, collaborationNeedNetworkId_);
1174         }
1175         CollaborationManager::GetInstance().PublishServiceState(collaborationNeedNetworkId_.c_str(),
1176             ServiceCollaborationManagerBussinessStatus::SCM_CONNECTED);
1177     }
1178     if (castState == castConnectStateForDisconnect_) { // 5 is disconnected status
1179         CollaborationManager::GetInstance().PublishServiceState(collaborationNeedNetworkId_.c_str(),
1180             ServiceCollaborationManagerBussinessStatus::SCM_IDLE);
1181     }
1182 }
1183 
1184 void AVSessionItem::OnCastStateChange(int32_t castState, DeviceInfo deviceInfo)
1185 {
1186     SLOGI("OnCastStateChange in with state: %{public}d | id: %{public}s", static_cast<int32_t>(castState),
1187         deviceInfo.deviceId_.c_str());
1188     DealCollaborationPublishState(castState, deviceInfo);
1189     DealCastState(castState);
1190     if (castState == streamStateConnection && counter_ == secondStep) {
1191         SLOGI("interception of one devicestate=6 transmission");
1192         counter_ = 0;
1193         return;
1194     }
1195     OutputDeviceInfo outputDeviceInfo;
1196     if (castDeviceInfoMap_.count(deviceInfo.deviceId_) > 0) {
1197         outputDeviceInfo.deviceInfos_.emplace_back(castDeviceInfoMap_[deviceInfo.deviceId_]);
1198     } else {
1199         outputDeviceInfo.deviceInfos_.emplace_back(deviceInfo);
1200     }
1201     if (castState == castConnectStateForConnected_) { // 6 is connected status (stream)
1202         castState = 1; // 1 is connected status (local)
1203         descriptor_.outputDeviceInfo_ = outputDeviceInfo;
1204         ReportConnectFinish("AVSessionItem::OnCastStateChange", deviceInfo);
1205         if (callStartCallback_) {
1206             SLOGI("AVSessionItem send callStart event to service for connected");
1207             callStartCallback_(*this);
1208         }
1209     }
1210     if (castState == castConnectStateForDisconnect_) { // 5 is disconnected status
1211         castState = 6; // 6 is disconnected status of AVSession
1212         DealDisconnect(deviceInfo);
1213     }
1214     HandleOutputDeviceChange(castState, outputDeviceInfo);
1215     {
1216         std::lock_guard controllersLockGuard(controllersLock_);
1217         for (const auto& controller : controllers_) {
1218             if (controller.second != nullptr) {
1219                 controller.second->HandleOutputDeviceChange(castState, outputDeviceInfo);
1220             }
1221         }
1222     }
1223     {
1224         std::lock_guard lockGuard(destroyLock_);
1225         if (castState == ConnectionState::STATE_DISCONNECTED &&
1226             descriptor_.sessionTag_ == "RemoteCast" && !isDestroyed_) {
1227             SLOGI("Sink cast session is disconnected, avsession item need be destroyed.");
1228             Destroy();
1229         }
1230     }
1231 }
1232 
1233 void AVSessionItem::OnCastEventRecv(int32_t errorCode, std::string& errorMsg)
1234 {
1235     SLOGI("OnCastEventRecv in with code and msg %{public}dm %{public}s", errorCode, errorMsg.c_str());
1236     std::lock_guard lockGuard(castControllersLock_);
1237     for (auto controller : castControllers_) {
1238         controller->OnPlayerError(errorCode, errorMsg);
1239     }
1240 }
1241 
1242 void AVSessionItem::OnRemoveCastEngine()
1243 {
1244     SLOGI("enter OnRemoveCastEngine");
1245     if (!collaborationNeedNetworkId_.empty()) {
1246         if (descriptor_.sessionTag_ != "RemoteCast" && castHandle_ > 0) {
1247             CollaborationManager::GetInstance().PublishServiceState(collaborationNeedNetworkId_.c_str(),
1248                 ServiceCollaborationManagerBussinessStatus::SCM_IDLE);
1249         }
1250     }
1251 }
1252 
1253 void AVSessionItem::ListenCollaborationRejectToStopCast()
1254 {
1255     CollaborationManager::GetInstance().SendRejectStateToStopCast([this](const int32_t code) {
1256         std::unique_lock <std::mutex> applyResultLock(collaborationApplyResultMutex_);
1257         if (code == ServiceCollaborationManagerResultCode::ONSTOP && newCastState == castConnectStateForConnected_) {
1258             SLOGI("onstop to stop cast");
1259             StopCast();
1260         }
1261         if (code == ServiceCollaborationManagerResultCode::PASS && newCastState != castConnectStateForConnected_) {
1262             SLOGI("ApplyResult can cast");
1263             applyResultFlag_ = true;
1264             applyUserResultFlag_ = true;
1265             connectWaitCallbackCond_.notify_one();
1266         }
1267         if (code == ServiceCollaborationManagerResultCode::REJECT && newCastState != castConnectStateForConnected_) {
1268             SLOGI("ApplyResult can not cast");
1269             collaborationRejectFlag_ = true;
1270             applyResultFlag_ = true;
1271             applyUserResultFlag_ = true;
1272             connectWaitCallbackCond_.notify_one();
1273         }
1274         if (code == ServiceCollaborationManagerResultCode::USERTIP && newCastState != castConnectStateForConnected_) {
1275             SLOGI("ApplyResult user tip");
1276             applyResultFlag_ = true;
1277             waitUserDecisionFlag_ = true;
1278             connectWaitCallbackCond_.notify_one();
1279         }
1280         if (code == ServiceCollaborationManagerResultCode::USERAGREE && newCastState != castConnectStateForConnected_) {
1281             SLOGI("ApplyResult user agree cast");
1282         }
1283     });
1284 }
1285 
1286 int32_t AVSessionItem::StopCast()
1287 {
1288     std::lock_guard lockGuard(castHandleLock_);
1289     if (descriptor_.sessionTag_ == "RemoteCast") {
1290         AVRouter::GetInstance().UnRegisterCallback(castHandle_, cssListener_);
1291         int32_t ret = AVRouter::GetInstance().StopCastSession(castHandle_);
1292         castHandle_ = -1;
1293         castHandleDeviceId_ = "-100";
1294         SLOGI("Unregister and Stop cast process for sink with ret %{public}d", ret);
1295         return ret;
1296     }
1297     SLOGI("Stop cast process");
1298     removeTimes = 1;
1299     if (isUpdate && newCastState == streamStateConnection) {
1300         SLOGE("removeTimes = 0");
1301         removeTimes = 0;
1302     }
1303     {
1304         CHECK_AND_RETURN_RET_LOG(castHandle_ != 0, AVSESSION_SUCCESS, "Not cast session, return");
1305         AVSessionRadarInfo info("AVSessionItem::StopCast");
1306         AVSessionRadar::GetInstance().StopCastBegin(descriptor_.outputDeviceInfo_, info);
1307         int64_t ret = AVRouter::GetInstance().StopCast(castHandle_, removeTimes);
1308         AVSessionRadar::GetInstance().StopCastEnd(descriptor_.outputDeviceInfo_, info);
1309         SLOGI("StopCast with unchange castHandle is %{public}ld", castHandle_);
1310         CHECK_AND_RETURN_RET_LOG(ret != AVSESSION_ERROR, AVSESSION_ERROR, "StopCast failed");
1311         removeTimes = 1;
1312     }
1313 
1314     if (castServiceNameMapState_["HuaweiCast"] != deviceStateConnection &&
1315         castServiceNameMapState_["HuaweiCast-Dual"] != deviceStateConnection) {
1316         OutputDeviceInfo outputDeviceInfo;
1317         DeviceInfo deviceInfo;
1318         deviceInfo.castCategory_ = AVCastCategory::CATEGORY_LOCAL;
1319         deviceInfo.deviceId_ = "0";
1320         deviceInfo.deviceName_ = "LocalDevice";
1321         outputDeviceInfo.deviceInfos_.emplace_back(deviceInfo);
1322         SetOutputDevice(outputDeviceInfo);
1323     }
1324 
1325     return AVSESSION_SUCCESS;
1326 }
1327 
1328 void AVSessionItem::SetCastHandle(const int64_t castHandle)
1329 {
1330     castHandle_ = castHandle;
1331 }
1332 
1333 void AVSessionItem::RegisterDeviceStateCallback()
1334 {
1335     OutputDeviceInfo localDevice;
1336     DeviceInfo localInfo;
1337     localInfo.castCategory_ = AVCastCategory::CATEGORY_LOCAL;
1338     localInfo.deviceId_ = "0";
1339     localInfo.deviceName_ = "LocalDevice";
1340     localDevice.deviceInfos_.emplace_back(localInfo);
1341     descriptor_.outputDeviceInfo_ = localDevice;
1342     AVRouter::GetInstance().RegisterCallback(castHandle_, cssListener_);
1343     SLOGI("register callback for device state change done");
1344 }
1345 
1346 void AVSessionItem::UnRegisterDeviceStateCallback()
1347 {
1348     AVRouter::GetInstance().UnRegisterCallback(castHandle_, cssListener_);
1349 }
1350 
1351 void AVSessionItem::StopCastSession()
1352 {
1353     SLOGI("Stop cast session process with castHandle: %{public}ld", castHandle_);
1354     int64_t ret = AVRouter::GetInstance().StopCastSession(castHandle_);
1355     DoContinuousTaskUnregister();
1356     if (ret != AVSESSION_ERROR) {
1357         castHandle_ = -1;
1358         castHandleDeviceId_ = "-100";
1359     } else {
1360         SLOGE("Stop cast session process error");
1361     }
1362 }
1363 
1364 AVSessionDisplayIntf* AVSessionItem::GetAVSessionDisplayIntf()
1365 {
1366     if (avsessionDisaplayIntf_ == nullptr) {
1367         typedef AVSessionDisplayIntf *(*CreateAVSessionDisplayIntfFunc)();
1368         CreateAVSessionDisplayIntfFunc createAVSessionDisplayIntf =
1369             reinterpret_cast<CreateAVSessionDisplayIntfFunc>(dynamicLoader_->GetFuntion(
1370                 AVSESSION_DYNAMIC_DISPLAY_LIBRARY_PATH, "createAVSessionDisplayIntf"));
1371         if (createAVSessionDisplayIntf) {
1372             avsessionDisaplayIntf_ = (*createAVSessionDisplayIntf)();
1373         }
1374     }
1375     return avsessionDisaplayIntf_;
1376 }
1377 
1378 int32_t AVSessionItem::StartCastDisplayListener()
1379 {
1380     SLOGI("StartCastDisplayListener in");
1381     HISYSEVENT_BEHAVIOR("SESSION_API_BEHAVIOR",
1382         "API_NAME", "onCastDisplayChange",
1383         "BUNDLE_NAME", GetBundleName(),
1384         "SESSION_ID", AVSessionUtils::GetAnonySessionId(GetSessionId()),
1385         "SESSION_TAG", descriptor_.sessionTag_,
1386         "SESSION_TYPE", GetSessionType(),
1387         "ERROR_CODE", AVSESSION_SUCCESS,
1388         "ERROR_MSG", "SUCCESS");
1389     sptr<IAVSessionCallback> callback;
1390     {
1391         std::lock_guard callbackLockGuard(callbackLock_);
1392         CHECK_AND_RETURN_RET_LOG(callback_ != nullptr, AVSESSION_ERROR, "callback_ is nullptr");
1393         callback = callback_;
1394     }
1395     GetDisplayListener(callback);
1396     return AVSESSION_SUCCESS;
1397 }
1398 
1399 int32_t AVSessionItem::StopCastDisplayListener()
1400 {
1401     HISYSEVENT_BEHAVIOR("SESSION_API_BEHAVIOR",
1402         "API_NAME", "offCastDisplayChange",
1403         "BUNDLE_NAME", GetBundleName(),
1404         "SESSION_ID", AVSessionUtils::GetAnonySessionId(GetSessionId()),
1405         "SESSION_TAG", descriptor_.sessionTag_,
1406         "SESSION_TYPE", GetSessionType(),
1407         "ERROR_CODE", AVSESSION_SUCCESS,
1408         "ERROR_MSG", "SUCCESS");
1409     SLOGI("StopCastDisplayListener in");
1410     std::lock_guard displayListenerLockGuard(displayListenerLock_);
1411     CHECK_AND_RETURN_RET_LOG(displayListener_ != nullptr, AVSESSION_ERROR, "displayListener_ is nullptr");
1412     Rosen::DMError ret = Rosen::ScreenManager::GetInstance().UnregisterScreenListener(displayListener_);
1413     if (ret != Rosen::DMError::DM_OK) {
1414         SLOGE("UnregisterScreenListener failed, ret: %{public}d.", ret);
1415     }
1416     displayListener_ = nullptr;
1417     return AVSESSION_SUCCESS;
1418 }
1419 
1420 void AVSessionItem::GetDisplayListener(sptr<IAVSessionCallback> callback)
1421 {
1422     SLOGI("GetDisplayListener in");
1423     std::lock_guard displayListenerLockGuard(displayListenerLock_);
1424     if (displayListener_ == nullptr) {
1425         SLOGI("displayListener_ is null, try to create new listener");
1426         displayListener_ = new HwCastDisplayListener(callback);
1427         if (displayListener_ == nullptr) {
1428             SLOGI("Create displayListener failed");
1429             return;
1430         }
1431         SLOGI("Start to register display listener");
1432         Rosen::DMError ret = Rosen::ScreenManager::GetInstance().RegisterScreenListener(displayListener_);
1433         if (ret != Rosen::DMError::DM_OK) {
1434             SLOGE("UnregisterScreenListener failed, ret: %{public}d.", ret);
1435         }
1436     }
1437     return;
1438 }
1439 
1440 int32_t AVSessionItem::GetAllCastDisplays(std::vector<CastDisplayInfo>& castDisplays)
1441 {
1442     SLOGI("GetAllCastDisplays in");
1443     std::vector<sptr<Rosen::Screen>> allDisplays;
1444     Rosen::ScreenManager::GetInstance().GetAllScreens(allDisplays);
1445     std::vector<CastDisplayInfo> displays;
1446     for (auto &display : allDisplays) {
1447         SLOGI("GetAllCastDisplays name: %{public}s, id: %{public}lu", display->GetName().c_str(), display->GetId());
1448         auto flag = Rosen::ScreenManager::GetInstance().GetVirtualScreenFlag(display->GetId());
1449         if (flag == Rosen::VirtualScreenFlag::CAST) {
1450             SLOGI("ReportCastDisplay start in");
1451             CastDisplayInfo castDisplayInfo;
1452             castDisplayInfo.displayState = CastDisplayState::STATE_ON;
1453             castDisplayInfo.displayId = display->GetId();
1454             castDisplayInfo.name = display->GetName();
1455             castDisplayInfo.width = display->GetWidth();
1456             castDisplayInfo.height = display->GetHeight();
1457             displays.push_back(castDisplayInfo);
1458             std::lock_guard displayListenerLockGuard(displayListenerLock_);
1459             if (displayListener_ != nullptr) {
1460                 displayListener_->SetDisplayInfo(display);
1461             }
1462         }
1463     }
1464     castDisplays = displays;
1465     return AVSESSION_SUCCESS;
1466 }
1467 
1468 void AVSessionItem::SetExtrasInner(AAFwk::IArray* list)
1469 {
1470     auto func = [&](AAFwk::IInterface* object) {
1471         if (object != nullptr) {
1472             AAFwk::IString* stringValue = AAFwk::IString::Query(object);
1473             if (stringValue != nullptr && AAFwk::String::Unbox(stringValue) == "url-cast" &&
1474                 descriptor_.sessionType_ == AVSession::SESSION_TYPE_VIDEO && serviceCallbackForStream_) {
1475                 SLOGI("AVSessionItem send mirrortostream event to service");
1476                 serviceCallbackForStream_(GetSessionId());
1477             }
1478         }
1479     };
1480     AAFwk::Array::ForEach(list, func);
1481 }
1482 
1483 void AVSessionItem::SetServiceCallbackForStream(const std::function<void(std::string)>& callback)
1484 {
1485     SLOGI("SetServiceCallbackForStream in");
1486     serviceCallbackForStream_ = callback;
1487 }
1488 #endif
1489 
1490 AVSessionDescriptor AVSessionItem::GetDescriptor()
1491 {
1492     return descriptor_;
1493 }
1494 
1495 AVCallState AVSessionItem::GetAVCallState()
1496 {
1497     std::lock_guard lockGuard(avsessionItemLock_);
1498     return avCallState_;
1499 }
1500 
1501 AVCallMetaData AVSessionItem::GetAVCallMetaData()
1502 {
1503     std::lock_guard lockGuard(avsessionItemLock_);
1504     std::string sessionId = GetSessionId();
1505     std::string fileDir = AVSessionUtils::GetCachePathName(userId_);
1506     std::string fileName = sessionId + AVSessionUtils::GetFileSuffix();
1507     std::shared_ptr<AVSessionPixelMap> innerPixelMap = avCallMetaData_.GetMediaImage();
1508     AVSessionUtils::ReadImageFromFile(innerPixelMap, fileDir, fileName);
1509     return avCallMetaData_;
1510 }
1511 
1512 
1513 AVPlaybackState AVSessionItem::GetPlaybackState()
1514 {
1515     std::lock_guard lockGuard(avsessionItemLock_);
1516     return playbackState_;
1517 }
1518 
1519 AVMetaData AVSessionItem::GetMetaData()
1520 {
1521     std::lock_guard lockGuard(avsessionItemLock_);
1522     std::string sessionId = GetSessionId();
1523     std::string fileDir = AVSessionUtils::GetCachePathName(userId_);
1524     std::string fileName = sessionId + AVSessionUtils::GetFileSuffix();
1525     std::shared_ptr<AVSessionPixelMap> innerPixelMap = metaData_.GetMediaImage();
1526     AVSessionUtils::ReadImageFromFile(innerPixelMap, fileDir, fileName);
1527 
1528     std::string avQueueFileDir = AVSessionUtils::GetFixedPathName();
1529     std::string avQueueFileName = GetBundleName() + "_" + metaData_.GetAVQueueId() + AVSessionUtils::GetFileSuffix();
1530     std::shared_ptr<AVSessionPixelMap> avQueuePixelMap = metaData_.GetAVQueueImage();
1531     AVSessionUtils::ReadImageFromFile(avQueuePixelMap, avQueueFileDir, avQueueFileName);
1532     return metaData_;
1533 }
1534 
1535 std::vector<AVQueueItem> AVSessionItem::GetQueueItems()
1536 {
1537     std::lock_guard lock_guard(avsessionItemLock_);
1538     return queueItems_;
1539 }
1540 
1541 std::string AVSessionItem::GetQueueTitle()
1542 {
1543     std::lock_guard lockGuard(avsessionItemLock_);
1544     return queueTitle_;
1545 }
1546 
1547 std::vector<int32_t> AVSessionItem::GetSupportCommand()
1548 {
1549     std::lock_guard lockGuard(avsessionItemLock_);
1550     if (descriptor_.elementName_.GetBundleName() == "castBundleName"
1551         && descriptor_.elementName_.GetAbilityName() == "castAbilityName") {
1552         std::vector<int32_t> supportedCmdForCastSession {
1553             AVControlCommand::SESSION_CMD_PLAY,
1554             AVControlCommand::SESSION_CMD_PAUSE,
1555             AVControlCommand::SESSION_CMD_STOP,
1556             AVControlCommand::SESSION_CMD_PLAY_NEXT,
1557             AVControlCommand::SESSION_CMD_PLAY_PREVIOUS,
1558             AVControlCommand::SESSION_CMD_SEEK
1559         };
1560         return supportedCmdForCastSession;
1561     }
1562     return supportedCmd_;
1563 }
1564 
1565 AbilityRuntime::WantAgent::WantAgent AVSessionItem::GetLaunchAbility()
1566 {
1567     return launchAbility_;
1568 }
1569 
1570 AAFwk::WantParams AVSessionItem::GetExtras()
1571 {
1572     std::lock_guard lockGuard(avsessionItemLock_);
1573     return extras_;
1574 }
1575 
1576 void AVSessionItem::HandleMediaKeyEvent(const MMI::KeyEvent& keyEvent)
1577 {
1578     AVSESSION_TRACE_SYNC_START("AVSessionItem::OnMediaKeyEvent");
1579     CHECK_AND_RETURN_LOG(descriptor_.isActive_, "session is deactive");
1580     SLOGI("HandleMediaKeyEvent check isMediaKeySupport %{public}d for %{public}d",
1581         static_cast<int>(isMediaKeySupport), static_cast<int>(keyEvent.GetKeyCode()));
1582     if (!isMediaKeySupport && keyEventCaller_.count(keyEvent.GetKeyCode()) > 0) {
1583         AVControlCommand cmd;
1584         cmd.SetRewindTime(metaData_.GetSkipIntervals());
1585         cmd.SetForwardTime(metaData_.GetSkipIntervals());
1586         keyEventCaller_[keyEvent.GetKeyCode()](cmd);
1587     } else {
1588         std::lock_guard callbackLockGuard(callbackLock_);
1589         if (callback_ != nullptr) {
1590             callback_->OnMediaKeyEvent(keyEvent);
1591         }
1592     }
1593 }
1594 
1595 void AVSessionItem::ExecuteControllerCommand(const AVControlCommand& cmd)
1596 {
1597     HISYSEVENT_ADD_OPERATION_COUNT(Operation::OPT_ALL_CTRL_COMMAND);
1598     int32_t code = cmd.GetCommand();
1599     if (code < 0 || code >= SESSION_CMD_MAX) {
1600         SLOGE("controlCommand invalid");
1601         return;
1602     }
1603     SLOGI("ExecuteControllerCommand code %{public}d from pid %{public}d to pid %{public}d",
1604         code, static_cast<int>(GetCallingPid()), static_cast<int>(GetPid()));
1605     {
1606         std::lock_guard remoteSinkLockGuard(remoteSinkLock_);
1607         if (remoteSink_ != nullptr) {
1608             SLOGI("set remote ControlCommand");
1609             CHECK_AND_RETURN_LOG(remoteSink_->SetControlCommand(cmd) == AVSESSION_SUCCESS, "SetControlCommand failed");
1610         }
1611     }
1612     CHECK_AND_RETURN_LOG(callback_ != nullptr, "callback_ is nullptr");
1613     CHECK_AND_RETURN_LOG(descriptor_.isActive_, "session is deactivate");
1614 
1615     HISYSEVENT_ADD_OPERATION_COUNT(static_cast<Operation>(cmd.GetCommand()));
1616     HISYSEVENT_ADD_OPERATION_COUNT(Operation::OPT_SUCCESS_CTRL_COMMAND);
1617     HISYSEVENT_ADD_CONTROLLER_COMMAND_INFO(descriptor_.elementName_.GetBundleName(), GetPid(),
1618         cmd.GetCommand(), descriptor_.sessionType_);
1619     return cmdHandlers[code](cmd);
1620 
1621     HISYSEVENT_FAULT("CONTROL_COMMAND_FAILED", "ERROR_TYPE", "INVALID_COMMAND", "CMD", code,
1622         "ERROR_INFO", "avsessionitem executecontrollercommand, invaild command");
1623 }
1624 // LCOV_EXCL_STOP
1625 
1626 void AVSessionItem::ExecueCommonCommand(const std::string& commonCommand, const AAFwk::WantParams& commandArgs)
1627 {
1628     AVSESSION_TRACE_SYNC_START("AVSessionItem::ExecueCommonCommand");
1629     {
1630         std::lock_guard callbackLockGuard(callbackLock_);
1631         CHECK_AND_RETURN_LOG(callback_ != nullptr, "callback_ is nullptr");
1632         callback_->OnCommonCommand(commonCommand, commandArgs);
1633     }
1634 
1635     std::lock_guard remoteSourceLockGuard(remoteSourceLock_);
1636     if (remoteSink_ != nullptr) {
1637         CHECK_AND_RETURN_LOG(remoteSink_->SetCommonCommand(commonCommand, commandArgs) == AVSESSION_SUCCESS,
1638             "SetCommonCommand failed");
1639     }
1640 }
1641 
1642 // LCOV_EXCL_START
1643 void AVSessionItem::HandleSkipToQueueItem(const int32_t& itemId)
1644 {
1645     AVSESSION_TRACE_SYNC_START("AVSessionItem::OnSkipToQueueItem");
1646     std::lock_guard callbackLockGuard(callbackLock_);
1647     CHECK_AND_RETURN_LOG(callback_ != nullptr, "callback_ is nullptr");
1648     callback_->OnSkipToQueueItem(itemId);
1649 }
1650 
1651 void AVSessionItem::HandleOnAVCallAnswer(const AVControlCommand& cmd)
1652 {
1653     AVSESSION_TRACE_SYNC_START("AVSessionItem::OnAVCallAnswer");
1654     std::lock_guard callbackLockGuard(callbackLock_);
1655     CHECK_AND_RETURN_LOG(callback_ != nullptr, "callback_ is nullptr");
1656     callback_->OnAVCallAnswer();
1657 }
1658 
1659 void AVSessionItem::HandleOnAVCallHangUp(const AVControlCommand& cmd)
1660 {
1661     AVSESSION_TRACE_SYNC_START("AVSessionItem::OnAVCallHangUp");
1662     std::lock_guard callbackLockGuard(callbackLock_);
1663     CHECK_AND_RETURN_LOG(callback_ != nullptr, "callback_ is nullptr");
1664     callback_->OnAVCallHangUp();
1665 }
1666 
1667 void AVSessionItem::HandleOnAVCallToggleCallMute(const AVControlCommand& cmd)
1668 {
1669     AVSESSION_TRACE_SYNC_START("AVSessionItem::OnAVCallToggleCallMute");
1670     std::lock_guard callbackLockGuard(callbackLock_);
1671     CHECK_AND_RETURN_LOG(callback_ != nullptr, "callback_ is nullptr");
1672     callback_->OnAVCallToggleCallMute();
1673 }
1674 
1675 void AVSessionItem::HandleOnPlay(const AVControlCommand& cmd)
1676 {
1677     AVSESSION_TRACE_SYNC_START("AVSessionItem::OnPlay");
1678     std::lock_guard callbackLockGuard(callbackLock_);
1679     CHECK_AND_RETURN_LOG(callback_ != nullptr, "callback_ is nullptr");
1680     callback_->OnPlay();
1681 }
1682 
1683 void AVSessionItem::HandleOnPause(const AVControlCommand& cmd)
1684 {
1685     AVSESSION_TRACE_SYNC_START("AVSessionItem::OnPause");
1686     std::lock_guard callbackLockGuard(callbackLock_);
1687     CHECK_AND_RETURN_LOG(callback_ != nullptr, "callback_ is nullptr");
1688     callback_->OnPause();
1689 }
1690 
1691 void AVSessionItem::HandleOnPlayOrPause(const AVControlCommand& cmd)
1692 {
1693     std::lock_guard lockGuard(avsessionItemLock_);
1694     SLOGI("check current playstate : %{public}d", playbackState_.GetState());
1695     if (playbackState_.GetState() == AVPlaybackState::PLAYBACK_STATE_PLAY) {
1696         HandleOnPause(cmd);
1697     } else {
1698         HandleOnPlay(cmd);
1699     }
1700 }
1701 
1702 void AVSessionItem::HandleOnStop(const AVControlCommand& cmd)
1703 {
1704     AVSESSION_TRACE_SYNC_START("AVSessionItem::OnStop");
1705     std::lock_guard callbackLockGuard(callbackLock_);
1706     CHECK_AND_RETURN_LOG(callback_ != nullptr, "callback_ is nullptr");
1707     callback_->OnStop();
1708 }
1709 
1710 void AVSessionItem::HandleOnPlayNext(const AVControlCommand& cmd)
1711 {
1712     AVSESSION_TRACE_SYNC_START("AVSessionItem::OnPlayNext");
1713     std::lock_guard callbackLockGuard(callbackLock_);
1714     CHECK_AND_RETURN_LOG(callback_ != nullptr, "callback_ is nullptr");
1715     callback_->OnPlayNext();
1716 }
1717 
1718 void AVSessionItem::HandleOnPlayPrevious(const AVControlCommand& cmd)
1719 {
1720     AVSESSION_TRACE_SYNC_START("AVSessionItem::OnPlayPrevious");
1721     std::lock_guard callbackLockGuard(callbackLock_);
1722     CHECK_AND_RETURN_LOG(callback_ != nullptr, "callback_ is nullptr");
1723     callback_->OnPlayPrevious();
1724 }
1725 
1726 void AVSessionItem::HandleOnFastForward(const AVControlCommand& cmd)
1727 {
1728     AVSESSION_TRACE_SYNC_START("AVSessionItem::OnFastForward");
1729     std::lock_guard callbackLockGuard(callbackLock_);
1730     CHECK_AND_RETURN_LOG(callback_ != nullptr, "callback_ is nullptr");
1731     int64_t time = 0;
1732     CHECK_AND_RETURN_LOG(cmd.GetForwardTime(time) == AVSESSION_SUCCESS, "GetForwardTime failed");
1733     callback_->OnFastForward(time);
1734 }
1735 
1736 void AVSessionItem::HandleOnRewind(const AVControlCommand& cmd)
1737 {
1738     AVSESSION_TRACE_SYNC_START("AVSessionItem::OnRewind");
1739     std::lock_guard callbackLockGuard(callbackLock_);
1740     CHECK_AND_RETURN_LOG(callback_ != nullptr, "callback_ is nullptr");
1741     int64_t time = 0;
1742     CHECK_AND_RETURN_LOG(cmd.GetRewindTime(time) == AVSESSION_SUCCESS, "GetForwardTime failed");
1743     callback_->OnRewind(time);
1744 }
1745 
1746 void AVSessionItem::HandleOnSeek(const AVControlCommand& cmd)
1747 {
1748     AVSESSION_TRACE_SYNC_START("AVSessionItem::OnSeek");
1749     std::lock_guard callbackLockGuard(callbackLock_);
1750     CHECK_AND_RETURN_LOG(callback_ != nullptr, "callback_ is nullptr");
1751     int64_t time = 0;
1752     CHECK_AND_RETURN_LOG(cmd.GetSeekTime(time) == AVSESSION_SUCCESS, "GetSeekTime failed");
1753     callback_->OnSeek(time);
1754 }
1755 
1756 void AVSessionItem::HandleOnSetSpeed(const AVControlCommand& cmd)
1757 {
1758     AVSESSION_TRACE_SYNC_START("AVSessionItem::OnSetSpeed");
1759     std::lock_guard callbackLockGuard(callbackLock_);
1760     CHECK_AND_RETURN_LOG(callback_ != nullptr, "callback_ is nullptr");
1761     double speed = 0.0;
1762     CHECK_AND_RETURN_LOG(cmd.GetSpeed(speed) == AVSESSION_SUCCESS, "GetSpeed failed");
1763     callback_->OnSetSpeed(speed);
1764 }
1765 
1766 void AVSessionItem::HandleOnSetLoopMode(const AVControlCommand& cmd)
1767 {
1768     AVSESSION_TRACE_SYNC_START("AVSessionItem::OnSetLoopMode");
1769     std::lock_guard callbackLockGuard(callbackLock_);
1770     CHECK_AND_RETURN_LOG(callback_ != nullptr, "callback_ is nullptr");
1771     int32_t loopMode = AVSESSION_ERROR;
1772     CHECK_AND_RETURN_LOG(cmd.GetLoopMode(loopMode) == AVSESSION_SUCCESS, "GetLoopMode failed");
1773     callback_->OnSetLoopMode(loopMode);
1774 }
1775 
1776 void AVSessionItem::HandleOnToggleFavorite(const AVControlCommand& cmd)
1777 {
1778     AVSESSION_TRACE_SYNC_START("AVSessionItem::OnToggleFavorite");
1779     std::lock_guard callbackLockGuard(callbackLock_);
1780     CHECK_AND_RETURN_LOG(callback_ != nullptr, "callback_ is nullptr");
1781     std::string assetId;
1782     CHECK_AND_RETURN_LOG(cmd.GetAssetId(assetId) == AVSESSION_SUCCESS, "GetMediaId failed");
1783     callback_->OnToggleFavorite(assetId);
1784 }
1785 
1786 void AVSessionItem::HandleOnPlayFromAssetId(const AVControlCommand& cmd)
1787 {
1788     AVSESSION_TRACE_SYNC_START("AVSessionItem::OnPlayFromAssetId");
1789     std::lock_guard callbackLockGuard(callbackLock_);
1790     CHECK_AND_RETURN_LOG(callback_ != nullptr, "callback_ is nullptr");
1791     int64_t assetId = 0;
1792     CHECK_AND_RETURN_LOG(cmd.GetPlayFromAssetId(assetId) == AVSESSION_SUCCESS, "Get playFromAssetId failed");
1793     callback_->OnPlayFromAssetId(assetId);
1794 }
1795 // LCOV_EXCL_STOP
1796 
1797 int32_t AVSessionItem::AddController(pid_t pid, sptr<AVControllerItem>& controller)
1798 {
1799     std::lock_guard controllersLockGuard(controllersLock_);
1800     SLOGI("handle controller newup for pid: %{public}d", static_cast<int>(pid));
1801     controllers_.insert({pid, controller});
1802     return AVSESSION_SUCCESS;
1803 }
1804 
1805 void AVSessionItem::SetPid(pid_t pid)
1806 {
1807     descriptor_.pid_ = pid;
1808 }
1809 
1810 void AVSessionItem::SetUid(pid_t uid)
1811 {
1812     descriptor_.uid_ = uid;
1813 }
1814 
1815 pid_t AVSessionItem::GetPid() const
1816 {
1817     return descriptor_.pid_;
1818 }
1819 
1820 pid_t AVSessionItem::GetUid() const
1821 {
1822     return descriptor_.uid_;
1823 }
1824 
1825 int32_t AVSessionItem::GetUserId() const
1826 {
1827     return userId_;
1828 }
1829 
1830 std::string AVSessionItem::GetAbilityName() const
1831 {
1832     return descriptor_.elementName_.GetAbilityName();
1833 }
1834 
1835 // LCOV_EXCL_START
1836 std::string AVSessionItem::GetBundleName() const
1837 {
1838     return descriptor_.elementName_.GetBundleName();
1839 }
1840 // LCOV_EXCL_STOP
1841 
1842 void AVSessionItem::SetTop(bool top)
1843 {
1844     descriptor_.isTopSession_ = top;
1845 }
1846 
1847 std::shared_ptr<RemoteSessionSource> AVSessionItem::GetRemoteSource()
1848 {
1849     return remoteSource_;
1850 }
1851 
1852 void AVSessionItem::HandleControllerRelease(pid_t pid)
1853 {
1854     std::lock_guard controllersLockGuard(controllersLock_);
1855     SLOGI("handle controller release for pid: %{public}d", static_cast<int>(pid));
1856     controllers_.erase(pid);
1857 }
1858 
1859 void AVSessionItem::SetServiceCallbackForRelease(const std::function<void(AVSessionItem&)>& callback)
1860 {
1861     SLOGI("SetServiceCallbackForRelease in");
1862     serviceCallback_ = callback;
1863 }
1864 
1865 void AVSessionItem::SetServiceCallbackForAVQueueInfo(const std::function<void(AVSessionItem&)>& callback)
1866 {
1867     SLOGI("SetServiceCallbackForAVQueueInfo in");
1868     serviceCallbackForAddAVQueueInfo_ = callback;
1869 }
1870 
1871 void AVSessionItem::SetServiceCallbackForCallStart(const std::function<void(AVSessionItem&)>& callback)
1872 {
1873     SLOGI("SetServiceCallbackForCallStart in");
1874     callStartCallback_ = callback;
1875 }
1876 
1877 void AVSessionItem::SetServiceCallbackForUpdateSession(const std::function<void(std::string, bool)>& callback)
1878 {
1879     SLOGI("SetServiceCallbackForUpdateSession in");
1880     serviceCallbackForUpdateSession_ = callback;
1881 }
1882 
1883 void AVSessionItem::HandleOutputDeviceChange(const int32_t connectionState, const OutputDeviceInfo& outputDeviceInfo)
1884 {
1885     SLOGI("output device change, connection state is %{public}d", connectionState);
1886     AVSESSION_TRACE_SYNC_START("AVSessionItem::OnOutputDeviceChange");
1887     std::lock_guard callbackLockGuard(callbackLock_);
1888     CHECK_AND_RETURN_LOG(callback_ != nullptr, "callback_ is nullptr");
1889     callback_->OnOutputDeviceChange(connectionState, outputDeviceInfo);
1890 }
1891 
1892 void AVSessionItem::SetOutputDevice(const OutputDeviceInfo& info)
1893 {
1894     descriptor_.outputDeviceInfo_ = info;
1895     int32_t connectionStateConnected = 1;
1896     HandleOutputDeviceChange(connectionStateConnected, descriptor_.outputDeviceInfo_);
1897     std::lock_guard controllersLockGuard(controllersLock_);
1898     for (const auto& controller : controllers_) {
1899         if (controller.second != nullptr) {
1900             (controller.second)->HandleOutputDeviceChange(connectionStateConnected, descriptor_.outputDeviceInfo_);
1901         }
1902     }
1903     SLOGI("OutputDeviceInfo device size is %{public}d", static_cast<int32_t>(info.deviceInfos_.size()));
1904 }
1905 
1906 // LCOV_EXCL_START
1907 void AVSessionItem::GetOutputDevice(OutputDeviceInfo& info)
1908 {
1909     info = GetDescriptor().outputDeviceInfo_;
1910 }
1911 
1912 int32_t AVSessionItem::CastAudioToRemote(const std::string& sourceDevice, const std::string& sinkDevice,
1913                                          const std::string& sinkCapability)
1914 {
1915     SLOGI("start cast audio to remote");
1916     std::lock_guard remoteSourceLockGuard(remoteSourceLock_);
1917     remoteSource_ = std::make_shared<RemoteSessionSourceProxy>();
1918     CHECK_AND_RETURN_RET_LOG(remoteSource_ != nullptr, AVSESSION_ERROR, "remoteSource_ is nullptr");
1919     int32_t ret = remoteSource_->CastSessionToRemote(this, sourceDevice, sinkDevice, sinkCapability);
1920     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastSessionToRemote failed");
1921     ret = remoteSource_->SetAVMetaData(GetMetaData());
1922     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetAVMetaData failed");
1923     ret = remoteSource_->SetAVPlaybackState(GetPlaybackState());
1924     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "SetAVPlaybackState failed");
1925     return AVSESSION_SUCCESS;
1926 }
1927 
1928 int32_t AVSessionItem::SourceCancelCastAudio(const std::string& sinkDevice)
1929 {
1930     SLOGI("start cancel cast audio");
1931     std::lock_guard remoteSourceLockGuard(remoteSourceLock_);
1932     CHECK_AND_RETURN_RET_LOG(remoteSource_ != nullptr, AVSESSION_ERROR, "remoteSource_ is nullptr");
1933     int32_t ret = remoteSource_->CancelCastAudio(sinkDevice);
1934     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastAudioToLocal failed");
1935     return AVSESSION_SUCCESS;
1936 }
1937 
1938 int32_t AVSessionItem::CastAudioFromRemote(const std::string& sourceSessionId, const std::string& sourceDevice,
1939                                            const std::string& sinkDevice, const std::string& sourceCapability)
1940 {
1941     SLOGI("start cast audio from remote");
1942     std::lock_guard remoteSinkLockGuard(remoteSinkLock_);
1943     remoteSink_ = std::make_shared<RemoteSessionSinkProxy>();
1944     CHECK_AND_RETURN_RET_LOG(remoteSink_ != nullptr, AVSESSION_ERROR, "remoteSink_ is nullptr");
1945     int32_t ret = remoteSink_->CastSessionFromRemote(this, sourceSessionId, sourceDevice, sinkDevice,
1946         sourceCapability);
1947     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CastSessionFromRemote failed");
1948 
1949     OutputDeviceInfo outputDeviceInfo;
1950     GetOutputDevice(outputDeviceInfo);
1951     int32_t castCategoryStreaming = ProtocolType::TYPE_CAST_PLUS_STREAM;
1952     for (size_t i = 0; i < outputDeviceInfo.deviceInfos_.size(); i++) {
1953         outputDeviceInfo.deviceInfos_[i].castCategory_ = castCategoryStreaming;
1954     }
1955     SetOutputDevice(outputDeviceInfo);
1956 
1957     CHECK_AND_RETURN_RET_LOG(Activate() == AVSESSION_SUCCESS, AVSESSION_ERROR, "Activate failed");
1958 
1959     std::vector<std::vector<int32_t>> value(SESSION_DATA_CATEGORY_MAX);
1960     ret = JsonUtils::GetVectorCapability(sourceCapability, value);
1961     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "GetVectorCapability error");
1962     for (auto cmd : value[SESSION_DATA_CONTROL_COMMAND]) {
1963         ret = AddSupportCommand(cmd);
1964         CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "AddSupportCommand failed");
1965     }
1966     return AVSESSION_SUCCESS;
1967 }
1968 
1969 int32_t AVSessionItem::SinkCancelCastAudio()
1970 {
1971     std::lock_guard remoteSinkLockGuard(remoteSinkLock_);
1972     CHECK_AND_RETURN_RET_LOG(remoteSink_ != nullptr, AVSESSION_ERROR, "remoteSink_ is nullptr");
1973     int32_t ret = remoteSink_->CancelCastSession();
1974     CHECK_AND_RETURN_RET_LOG(ret == AVSESSION_SUCCESS, ret, "CancelCastSession failed");
1975     GetDescriptor().outputDeviceInfo_.deviceInfos_.clear();
1976     DeviceInfo deviceInfo;
1977     GetDescriptor().outputDeviceInfo_.deviceInfos_.emplace_back(deviceInfo);
1978     SLOGI("SinkCancelCastAudio");
1979     return AVSESSION_SUCCESS;
1980 }
1981 
1982 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
1983 void AVSessionItem::UpdateCastDeviceMap(DeviceInfo deviceInfo)
1984 {
1985     SLOGI("UpdateCastDeviceMap with id: %{public}s", deviceInfo.deviceid_.c_str());
1986     castDeviceInfoMap_[deviceInfo.deviceId_] = deviceInfo;
1987 
1988     if (descriptor_.outputDeviceInfo_.deviceInfos_.size() > 0 &&
1989         descriptor_.outputDeviceInfo_.deviceInfos_[0].deviceId_ == deviceInfo.deviceId_) {
1990         OutputDeviceInfo outputDeviceInfo;
1991         outputDeviceInfo.deviceInfos_.emplace_back(deviceInfo);
1992         descriptor_.outputDeviceInfo_ = outputDeviceInfo;
1993     }
1994 }
1995 #endif
1996 
1997 void AVSessionItem::ReportConnectFinish(const std::string func, const DeviceInfo &deviceInfo)
1998 {
1999 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
2000     AVSessionRadarInfo info(func);
2001     if (castDeviceInfoMap_.count(deviceInfo.deviceId_) > 0) {
2002         DeviceInfo cacheDeviceInfo = castDeviceInfoMap_[deviceInfo.deviceId_];
2003         AVSessionRadar::GetInstance().ConnectFinish(cacheDeviceInfo, info);
2004     } else {
2005         AVSessionRadar::GetInstance().ConnectFinish(deviceInfo, info);
2006     }
2007 #endif
2008 }
2009 
2010 void AVSessionItem::ReportStopCastFinish(const std::string func, const DeviceInfo &deviceInfo)
2011 {
2012 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
2013     AVSessionRadarInfo info(func);
2014     if (castDeviceInfoMap_.count(deviceInfo.deviceId_) > 0) {
2015         DeviceInfo cacheDeviceInfo = castDeviceInfoMap_[deviceInfo.deviceId_];
2016         AVSessionRadar::GetInstance().StopCastFinish(cacheDeviceInfo, info);
2017     } else {
2018         AVSessionRadar::GetInstance().StopCastFinish(deviceInfo, info);
2019     }
2020 #endif
2021 }
2022 
2023 void AVSessionItem::SaveLocalDeviceInfo()
2024 {
2025     OutputDeviceInfo localDevice;
2026     DeviceInfo localInfo;
2027     localInfo.castCategory_ = AVCastCategory::CATEGORY_LOCAL;
2028     localInfo.deviceId_ = "0";
2029     localInfo.deviceName_ = "LocalDevice";
2030     localDevice.deviceInfos_.emplace_back(localInfo);
2031     descriptor_.outputDeviceInfo_ = localDevice;
2032 }
2033 
2034 int32_t AVSessionItem::DoContinuousTaskRegister()
2035 {
2036 #ifdef EFFICIENCY_MANAGER_ENABLE
2037     if (descriptor_.sessionTag_ == "RemoteCast") {
2038         SLOGI("sink session no need to register continuousTask");
2039         return AVSESSION_SUCCESS;
2040     }
2041     int32_t uid = GetUid();
2042     int32_t pid = GetPid();
2043     std::string bundleName = BundleStatusAdapter::GetInstance().GetBundleNameFromUid(uid);
2044     CHECK_AND_RETURN_RET_LOG(bundleName != "", AVSESSION_ERROR, "GetBundleNameFromUid failed");
2045 
2046     void *handle_ = dlopen("libsuspend_manager_client.z.so", RTLD_NOW);
2047     if (handle_ == nullptr) {
2048         SLOGE("failed to open library libsuspend_manager_client reaseon %{public}s", dlerror());
2049         return AVSESSION_ERROR;
2050     }
2051     typedef ErrCode (*handler) (int32_t eventType, int32_t uid, int32_t pid,
2052         const std::string bundleName, int32_t taskState, int32_t serviceId);
2053     handler reportContinuousTaskEventEx = reinterpret_cast<handler>(dlsym(handle_, "ReportContinuousTaskEventEx"));
2054     ErrCode errCode = reportContinuousTaskEventEx(0, uid, pid, bundleName, 1, AVSESSION_SERVICE_ID);
2055     SLOGI("reportContinuousTaskEventEx done, result: %{public}d", errCode);
2056 #ifndef TEST_COVERAGE
2057     if (handle_ != nullptr) {
2058         OPENSSL_thread_stop();
2059     }
2060     dlclose(handle_);
2061 #endif
2062 #endif
2063     return AVSESSION_SUCCESS;
2064 }
2065 
2066 int32_t AVSessionItem::DoContinuousTaskUnregister()
2067 {
2068 #ifdef EFFICIENCY_MANAGER_ENABLE
2069     if (descriptor_.sessionTag_ == "RemoteCast") {
2070         SLOGI("sink session should not unregister ContinuousTask");
2071         return AVSESSION_SUCCESS;
2072     }
2073     int32_t uid = GetUid();
2074     int32_t pid = GetPid();
2075     std::string bundleName = BundleStatusAdapter::GetInstance().GetBundleNameFromUid(uid);
2076     CHECK_AND_RETURN_RET_LOG(bundleName != "", AVSESSION_ERROR, "GetBundleNameFromUid failed");
2077 
2078     void *handle_ = dlopen("libsuspend_manager_client.z.so", RTLD_NOW);
2079     if (handle_ == nullptr) {
2080         SLOGE("failed to open library libsuspend_manager_client when stop cast, reaseon %{public}s", dlerror());
2081         return AVSESSION_ERROR;
2082     }
2083     typedef ErrCode (*handler) (int32_t eventType, int32_t uid, int32_t pid,
2084         const std::string bundleName, int32_t taskState, int32_t serviceId);
2085     handler reportContinuousTaskEventEx = reinterpret_cast<handler>(dlsym(handle_, "ReportContinuousTaskEventEx"));
2086     ErrCode errCode = reportContinuousTaskEventEx(0, uid, pid, bundleName, 2, AVSESSION_SERVICE_ID);
2087     SLOGI("reportContinuousTaskEventEx done when stop cast, result: %{public}d", errCode);
2088 #ifndef TEST_COVERAGE
2089     if (handle_ != nullptr) {
2090         OPENSSL_thread_stop();
2091     }
2092     dlclose(handle_);
2093 #endif
2094 #endif
2095     return AVSESSION_SUCCESS;
2096 }
2097 // LCOV_EXCL_STOP
2098 } // namespace OHOS::AVSession
2099