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