• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef OHOS_AVSESSION_SERVICE_H
17 #define OHOS_AVSESSION_SERVICE_H
18 
19 #include <atomic>
20 #include <mutex>
21 #include <map>
22 
23 #include "iremote_stub.h"
24 #include "system_ability.h"
25 #include "audio_info.h"
26 #include "avsession_service_stub.h"
27 #include "avsession_item.h"
28 #include "avcontroller_item.h"
29 #include "session_container.h"
30 #include "iclient_death.h"
31 #include "isession_listener.h"
32 #include "focus_session_strategy.h"
33 #include "background_audio_controller.h"
34 #include "ability_manager_adapter.h"
35 #include "device_manager.h"
36 #include "dm_device_info.h"
37 #include "audio_adapter.h"
38 #include "remote_session_command_process.h"
39 #include "i_avsession_service_listener.h"
40 #include "avqueue_info.h"
41 #include "migrate/migrate_avsession_server.h"
42 
43 #include "common_event_manager.h"
44 #include "common_event_subscribe_info.h"
45 #include "common_event_subscriber.h"
46 #include "common_event_support.h"
47 #include "matching_skills.h"
48 
49 #include "avsession_users_manager.h"
50 
51 namespace OHOS::AVSession {
52 class AVSessionDumper;
53 
54 class ClientDeathRecipient : public IRemoteObject::DeathRecipient {
55 public:
56     explicit ClientDeathRecipient(const std::function<void()>& callback);
57 
58     void OnRemoteDied(const wptr<IRemoteObject>& object) override;
59 
60 private:
61     std::function<void()> callback_;
62 };
63 
64 class AVSessionInitDMCallback : public OHOS::DistributedHardware::DmInitCallback {
65 public:
66     AVSessionInitDMCallback() = default;
67     ~AVSessionInitDMCallback() override = default;
OnRemoteDied()68     void OnRemoteDied() override {};
69 };
70 
71 class EventSubscriber : public EventFwk::CommonEventSubscriber {
72 public:
73     EventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscriberInfo, AVSessionService *ptr);
74     virtual ~EventSubscriber() = default;
75     void OnReceiveEvent(const EventFwk::CommonEventData &eventData) override;
76 private:
77     AVSessionService *servicePtr_ = nullptr;
78 };
79 
80 class AVSessionService : public SystemAbility, public AVSessionServiceStub, public IAVSessionServiceListener {
81     DECLARE_SYSTEM_ABILITY(AVSessionService);
82 
83 public:
84     DISALLOW_COPY_AND_MOVE(AVSessionService);
85 
86     explicit AVSessionService(int32_t systemAbilityId, bool runOnCreate = true);
87 
88     ~AVSessionService() override;
89 
90     void OnDump() override;
91 
92     void OnStart() override;
93 
94     void OnStop() override;
95 
96     void PullMigrateStub();
97 
98     void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override;
99 
100     void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override;
101 
102     sptr<IRemoteObject> CreateSessionInner(const std::string& tag, int32_t type,
103                                            const AppExecFwk::ElementName& elementName) override;
104 
105     int32_t CreateSessionInner(const std::string& tag, int32_t type, const AppExecFwk::ElementName& elementName,
106                                sptr<IRemoteObject>& object) override;
107 
108     int32_t GetAllSessionDescriptors(std::vector<AVSessionDescriptor>& descriptors) override;
109 
110     int32_t GetSessionDescriptorsBySessionId(const std::string& sessionId, AVSessionDescriptor& descriptor) override;
111 
112     int32_t GetHistoricalSessionDescriptors(int32_t maxSize, std::vector<AVSessionDescriptor>& descriptors) override;
113 
114     int32_t GetHistoricalAVQueueInfos(int32_t maxSize, int32_t maxAppSize,
115                                       std::vector<AVQueueInfo>& avQueueInfos) override;
116 
117     int32_t StartAVPlayback(const std::string& bundleName, const std::string& assetId) override;
118 
119     int32_t CreateControllerInner(const std::string& sessionId, sptr<IRemoteObject>& object) override;
120 
121 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
122     int32_t GetAVCastControllerInner(const std::string& sessionId, sptr<IRemoteObject>& object) override;
123 #endif
124 
125     int32_t RegisterSessionListener(const sptr<ISessionListener>& listener) override;
126 
127     int32_t RegisterSessionListenerForAllUsers(const sptr<ISessionListener>& listener) override;
128 
129     int32_t SendSystemAVKeyEvent(const MMI::KeyEvent& keyEvent) override;
130 
131     int32_t SendSystemControlCommand(const AVControlCommand& command) override;
132 
133     int32_t RegisterClientDeathObserver(const sptr<IClientDeath>& observer) override;
134 
135     void OnClientDied(pid_t pid);
136 
137     void HandleSessionRelease(std::string sessionId, bool continuePlay = false);
138 
139     void HandleCallStartEvent();
140 
141 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
142     __attribute__((no_sanitize("cfi"))) int32_t MirrorToStreamCast(sptr<AVSessionItem>& session);
143 
144     void SplitExtraInfo(std::string info);
145 #endif
146 
147     void HandleControllerRelease(AVControllerItem& controller);
148 
149     std::int32_t Dump(std::int32_t fd, const std::vector<std::u16string>& args) override;
150 
151     int32_t CastAudio(const SessionToken& token,
152                       const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkAudioDescriptors) override;
153 
154     int32_t CastAudioForAll(const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkAudioDescriptors) override;
155 
NotifyAudioSessionCheckTrigger(const int32_t uid)156     void NotifyAudioSessionCheckTrigger(const int32_t uid)
157     {
158         return NotifyAudioSessionCheck(uid);
159     }
160 
161     void SuperLauncher(std::string deviceId, std::string serviceName,
162         std::string extraInfo, const std::string& state);
163 
164 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
165     void ReleaseCastSession() override;
166 
167     void CreateSessionByCast(const int64_t castHandle) override;
168 
169     void NotifyDeviceAvailable(const OutputDeviceInfo& castOutputDeviceInfo) override;
170 
171     void NotifyDeviceLogEvent(const DeviceLogEventCode eventId, const int64_t param) override;
172 
173     void NotifyDeviceOffline(const std::string& deviceId) override;
174 
175     void NotifyMirrorToStreamCast();
176 
177     int32_t StartCast(const SessionToken& sessionToken, const OutputDeviceInfo& outputDeviceInfo) override;
178 
179     int32_t StopCast(const SessionToken& sessionToken) override;
180 
181     int32_t checkEnableCast(bool enable) override;
182 
183     void setInCast(bool isInCast) override;
184 #endif
185 
186     int32_t Close(void) override;
187 
188     void AddAvQueueInfoToFile(AVSessionItem& session);
189 
190     std::string GetAVQueueDir(int32_t userId = 0);
191 
192     std::string GetAVSortDir(int32_t userId = 0);
193 
194     void HandleUserEvent(const std::string &type, const int &userId);
195 
196     void RegisterBundleDeleteEventForHistory(int32_t userId = 0);
197 
198     void NotifyMigrateStop(const std::string &deviceId);
199 
200 private:
201     void CheckInitCast();
202 
203     void NotifyProcessStatus(bool isStart);
204 
205     static SessionContainer& GetContainer();
206     static AVSessionUsersManager& GetUsersManager();
207 
208     std::string AllocSessionId();
209 
210     bool AbilityHasSession(pid_t pid);
211 
212     sptr<AVControllerItem> GetPresentController(pid_t pid, const std::string& sessionId);
213 
214     void NotifySessionCreate(const AVSessionDescriptor& descriptor);
215     void NotifySessionRelease(const AVSessionDescriptor& descriptor);
216     void NotifyTopSessionChanged(const AVSessionDescriptor& descriptor);
217     void NotifyAudioSessionCheck(const int32_t uid);
218     void NotifySystemUI(const AVSessionDescriptor* historyDescriptor, bool isActiveSession);
219     void NotifyDeviceChange(const DeviceChangeAction& deviceChangeAction);
220 
221     void AddClientDeathObserver(pid_t pid, const sptr<IClientDeath>& observer,
222         const sptr<ClientDeathRecipient> recipient);
223     void RemoveClientDeathObserver(pid_t pid);
224 
225     void AddSessionListener(pid_t pid, const sptr<ISessionListener>& listener);
226     void AddSessionListenerForAllUsers(pid_t pid, const sptr<ISessionListener>& listener);
227     void RemoveSessionListener(pid_t pid);
228 
229     void AddInnerSessionListener(SessionListener* listener);
230     void RemoveInnerSessionListener(SessionListener* listener);
231 
232     sptr<AVSessionItem> SelectSessionByUid(const AudioStandard::AudioRendererChangeInfo& info);
233 
234     void OutputDeviceChangeListener(const AudioRendererChangeInfos& infos);
235 
236     sptr<AVSessionItem> CreateSessionInner(const std::string& tag, int32_t type, bool thirdPartyApp,
237                                            const AppExecFwk::ElementName& elementName);
238 
239     int32_t CreateSessionInner(const std::string& tag, int32_t type, bool thirdPartyApp,
240                                const AppExecFwk::ElementName& elementName, sptr<AVSessionItem>& sessionItem);
241 
242     void ServiceCallback(sptr<AVSessionItem>& sessionItem);
243 
244     sptr<AVSessionItem> CreateNewSession(const std::string& tag, int32_t type, bool thirdPartyApp,
245                                          const AppExecFwk::ElementName& elementName);
246 
247     sptr<AVControllerItem> CreateNewControllerForSession(pid_t pid, sptr<AVSessionItem>& session);
248 
249     int32_t CancelCastAudioForClientExit(pid_t pid, const sptr<AVSessionItem>& session);
250 
251     void ClearSessionForClientDiedNoLock(pid_t pid, bool continuePlay);
252 
253     void ClearControllerForClientDiedNoLock(pid_t pid);
254 
255     void InitKeyEvent();
256 
257     void InitAudio();
258 
259     void InitAMS();
260 
261     void InitDM();
262 
263     void InitBMS();
264 
265     void InitRadarBMS();
266 
267     void InitAccountMgr();
268 
269     void InitCommonEventService();
270 
271     bool SelectFocusSession(const FocusSessionStrategy::FocusSessionChangeInfo& info);
272 
273     void RefreshFocusSessionSort(sptr<AVSessionItem> &session);
274 
275     void UpdateTopSession(const sptr<AVSessionItem>& newTopSession);
276 
277     void HandleFocusSession(const FocusSessionStrategy::FocusSessionChangeInfo& info);
278 
279     void HandleDeviceChange(const AudioStandard::DeviceChangeAction& deviceChangeAction);
280 
281     __attribute__((no_sanitize("cfi"))) std::shared_ptr<RemoteSessionCommandProcess> GetService(
282         const std::string& deviceId);
283 
284     int32_t CastAudioProcess(const std::vector<AudioStandard::AudioDeviceDescriptor>& descriptors,
285                              const std::string& sourceSessionInfo,
286                              sptr<AVSessionItem>& session);
287 
288     int32_t CastAudioInner(const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkAudioDescriptors,
289                            const std::string& sourceSessionInfo,
290                            const sptr<AVSessionItem>& session);
291 
292     int32_t CancelCastAudioInner(const std::vector<AudioStandard::AudioDeviceDescriptor>& sinkDevices,
293                                  const std::string& sourceSessionInfo,
294                                  const sptr<AVSessionItem>& session);
295 
296     int32_t RemoteCastAudioInner(const std::string& sourceSessionInfo, std::string& sinkSessionInfo);
297 
298     int32_t RemoteCancelCastAudioInner(const std::string& sessionInfo);
299 
300     int32_t ProcessCastAudioCommand(const RemoteServiceCommand command, const std::string& input,
301                                     std::string& output) override;
302 
303     int32_t CastAudioForNewSession(const sptr<AVSessionItem>& session);
304 
305     bool IsLocalDevice(const std::string& networkId);
306 
307     int32_t GetLocalNetworkId(std::string& networkId);
308 
309     int32_t GetTrustedDeviceName(const std::string& networkId, std::string& deviceName);
310 
311     int32_t GetTrustedDevicesInfo(std::vector<OHOS::DistributedHardware::DmDeviceInfo>& deviceList);
312 
313     int32_t SetBasicInfo(std::string& sessionInfo);
314 
315     void SetDeviceInfo(const std::vector<AudioStandard::AudioDeviceDescriptor>& castAudioDescriptors,
316                            sptr<AVSessionItem>& session);
317 
318     int32_t GetAudioDescriptor(const std::string deviceId,
319                                std::vector<AudioStandard::AudioDeviceDescriptor>& audioDeviceDescriptors);
320 
321     bool GetAudioDescriptorByDeviceId(const std::vector<sptr<AudioStandard::AudioDeviceDescriptor>>& descriptors,
322                                       const std::string& deviceId,
323                                       AudioStandard::AudioDeviceDescriptor& audioDescriptor);
324 
325     void GetDeviceInfo(const sptr<AVSessionItem>& session,
326                            const std::vector<AudioStandard::AudioDeviceDescriptor>& descriptors,
327                            std::vector<AudioStandard::AudioDeviceDescriptor>& castSinkDescriptors,
328                            std::vector<AudioStandard::AudioDeviceDescriptor>& cancelSinkDescriptors);
329 
330     int32_t SelectOutputDevice(const int32_t uid, const AudioStandard::AudioDeviceDescriptor& descriptor);
331 
332     int32_t StartDefaultAbilityByCall(std::string& sessionId);
333 
334     int32_t StartAbilityByCall(const std::string& sessionIdNeeded, std::string& sessionId);
335 
336     void HandleEventHandlerCallBack();
337 
338     bool IsHistoricalSession(const std::string& sessionId);
339 
340     void DeleteHistoricalRecord(const std::string& bundleName, int32_t userId = 0);
341 
342     void DeleteAVQueueInfoRecord(const std::string& bundleName, int32_t userId = 0);
343 
344     bool SaveAvQueueInfo(std::string& oldContent, const std::string &bundleName, AVSessionItem& session);
345 
346     const nlohmann::json& GetSubNode(const nlohmann::json& node, const std::string& name);
347 
348     void refreshSortFileOnCreateSession(const std::string& sessionId, const std::string& sessionType,
349         const AppExecFwk::ElementName& elementName);
350 
351     bool CheckAndCreateDir(const std::string& filePath);
352 
353     bool CheckUserDirValid(int32_t userId = 0);
354 
355     bool LoadStringFromFileEx(const std::string& filePath, std::string& content);
356 
357     bool SaveStringToFileEx(const std::string& filePath, const std::string& content);
358 
359     bool CheckStringAndCleanFile(const std::string& filePath);
360 
361     void ClearClientResources(pid_t pid, bool continuePlay);
362 
363     bool SaveAvQueueInfo(std::string& oldContent, const std::string &bundleName,
364         const AVMetaData& meta, const int32_t userId);
365 
366     int32_t GetHistoricalSessionDescriptorsFromFile(std::vector<AVSessionDescriptor>& descriptors);
367 
368     void ReportStartCastBegin(std::string func, const OutputDeviceInfo& outputDeviceInfo, int32_t uid);
369 
370     void ReportStartCastEnd(std::string func, const OutputDeviceInfo &outputDeviceInfo, int32_t uid, int ret);
371 
372     void HandleAppStateChange(int uid, int state);
373 
374     bool IsMediaStream(AudioStandard::StreamUsage usage);
375 
376     void UpdateFrontSession(sptr<AVSessionItem>& sessionItem, bool isAdd);
377 
378     std::shared_ptr<AbilityRuntime::WantAgent::WantAgent> CreateWantAgent(
379         const AVSessionDescriptor* histroyDescriptor);
380 
381     void DoMetadataImgClean(AVMetaData& data);
382 
383     void HandleSystemKeyColdStart(const AVControlCommand &command);
384 
385     bool SubscribeCommonEvent();
386 
387     bool UnSubscribeCommonEvent();
388 
389     void ReportSessionInfo(const sptr <AVSessionItem>& session, int res);
390 
391     bool CheckAncoAudio();
392 
393     int32_t ConvertKeyCodeToCommand(int keyCode);
394 
395     std::shared_ptr<std::list<sptr<AVSessionItem>>> GetCurSessionListForFront();
396 
397     void RemoveExpired(std::list<std::chrono::system_clock::time_point> &list,
398         const std::chrono::system_clock::time_point &now, int32_t time = 1);
399 
400     std::atomic<uint32_t> sessionSeqNum_ {};
401 
402     std::recursive_mutex sessionAndControllerLock_;
403     sptr<AVSessionItem> topSession_;
404     std::map<pid_t, std::list<sptr<AVControllerItem>>> controllers_;
405     std::recursive_mutex sessionFrontLock_;
406 
407     std::recursive_mutex clientDeathObserversLock_;
408     std::map<pid_t, sptr<IClientDeath>> clientDeathObservers_;
409     std::map<pid_t, sptr<ClientDeathRecipient>> clientDeathRecipients_;
410 
411     std::recursive_mutex sessionListenersLock_;
412     std::list<SessionListener*> innerSessionListeners_;
413 
414     std::recursive_mutex abilityManagerLock_;
415     std::map<std::string, std::shared_ptr<AbilityManagerAdapter>> abilityManager_;
416 
417     FocusSessionStrategy focusSessionStrategy_;
418     BackgroundAudioController backgroundAudioController_;
419 
420     std::recursive_mutex castAudioSessionMapLock_;
421     std::map<std::string, std::string> castAudioSessionMap_;
422 
423     std::recursive_mutex isAllSessionCastLock_;
424     bool isAllSessionCast_ {};
425 
426     std::recursive_mutex outputDeviceIdLock_;
427     std::string outputDeviceId_;
428 
429     std::unique_ptr<AVSessionDumper> dumpHelper_ {};
430     friend class AVSessionDumper;
431 
432     std::recursive_mutex sortFileReadWriteLock_;
433     std::recursive_mutex avQueueFileReadWriteLock_;
434     std::recursive_mutex fileCheckLock_;
435 
436     std::recursive_mutex migrateListenersLock_;
437     std::shared_ptr<MigrateAVSessionServer> migrateAVSession_;
438     std::map<int32_t, bool> sessionPublishedMap_;
439 
440     std::shared_ptr<EventSubscriber> subscriber_;
441     std::recursive_mutex screenStateLock_;
442     bool screenOn = false;
443     bool screenLocked = true;
444 
445     std::list<std::chrono::system_clock::time_point> flowControlPublishTimestampList_;
446 
447 #ifdef CASTPLUS_CAST_ENGINE_ENABLE
448     std::map<std::string, std::string> castServiceNameMapState_;
449     const std::string deviceStateConnection = "CONNECT_SUCC";
450     const std::string deviceStateDisconnection = "IDLE";
451     const std::string seperator = ",";
452     int appState = -1;
453     bool isSupportMirrorToStream_ = false;
454     std::string castDeviceId_ = "0";
455     std::string castDeviceName_ = " ";
456     int32_t castDeviceType_ = 0;
457     const int32_t beginAddPos = 3;
458     const int32_t endDecPos = 4;
459     const int32_t typeAddPos = 2;
460 #endif
461 
462     static constexpr const char *SORT_FILE_NAME = "sortinfo";
463     static constexpr const char *DEFAULT_SESSION_ID = "default";
464     static constexpr const char *DEFAULT_BUNDLE_NAME = "com.example.himusicdemo";
465     static constexpr const char *DEFAULT_ABILITY_NAME = "MainAbility";
466     static constexpr const int32_t SYSTEMUI_LIVEVIEW_TYPECODE_MDEDIACONTROLLER = 2;
467     static constexpr const char *AVQUEUE_FILE_NAME = "avqueueinfo";
468 
469     const std::string MEDIA_CONTROL_BUNDLENAME = "com.ohos.mediacontroller";
470     const std::string MEDIA_CONTROL_ABILITYNAME =
471         "com.ohos.mediacontroller.avplayer.mainability";
472 
473     int32_t pressCount_ {};
474     int32_t maxHistoryNums = 10;
475     int uidForAppStateChange_ = 0;
476     bool isFirstPress_ = true;
477     bool isSourceInCast_ = false;
478     bool isInCast_ = false;
479     bool is2in1_ = false;
480 
481     void *migrateStubFuncHandle_ = nullptr;
482 
483     const int32_t ONE_CLICK = 1;
484     const int32_t DOUBLE_CLICK = 2;
485     const int32_t THREE_CLICK = 3;
486     const int32_t unSetHistoryNum = 3;
487     const int32_t CLICK_TIMEOUT = 500;
488     const int32_t defMaxHistoryNum = 10;
489     const int32_t maxFileLength = 32 * 1024 * 1024;
490     const int32_t maxAVQueueInfoLen = 99;
491     const int32_t allocSpace = 2;
492     const int32_t avSessionUid = 6700;
493     const int32_t ancoUid = 1041;
494     const int32_t saType = 1;
495     const int32_t MAX_NOTIFICATION_NUM = 3;
496     const int32_t NOTIFICATION_CONTROL_TIME = 1000;
497 };
498 } // namespace OHOS::AVSession
499 #endif // OHOS_AVSESSION_SERVICE_H
500