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