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