1 /*
2  * Copyright (c) 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 ST_AUDIO_SESSION_SERVICE_H
17 #define ST_AUDIO_SESSION_SERVICE_H
18 
19 #include <mutex>
20 
21 #include "audio_session.h"
22 #include "audio_session_timer.h"
23 
24 namespace OHOS {
25 namespace AudioStandard {
26 class SessionTimeOutCallback {
27 public:
28     virtual ~SessionTimeOutCallback() = default;
29 
30     virtual void OnSessionTimeout(const int32_t pid) = 0; // 超时释放
31 };
32 
33 class AudioSessionService : public AudioSessionTimerCallback, public std::enable_shared_from_this<AudioSessionService> {
34 public:
35     AudioSessionService();
36     ~AudioSessionService() override;
37 
38     // Audio session manager interfaces
39     int32_t ActivateAudioSession(const int32_t callerPid, const AudioSessionStrategy &strategy);
40     int32_t DeactivateAudioSession(const int32_t callerPid);
41     bool IsAudioSessionActivated(const int32_t callerPid);
42 
43     // Audio session timer callback
44     void OnAudioSessionTimeOut(const int32_t callerPid) override;
45 
46     // other public interfaces
47     void Init();
48     int32_t SetSessionTimeOutCallback(const std::shared_ptr<SessionTimeOutCallback> &timeOutCallback);
49     std::shared_ptr<AudioSession> GetAudioSessionByPid(const int32_t callerPid);
50 
51     static bool IsSameTypeForAudioSession(const AudioStreamType incomingType, const AudioStreamType existedType);
52 
53 private:
54     int32_t DeactivateAudioSessionInternal(const int32_t callerPid, bool isSessionTimeout = false);
55 
56     std::mutex sessionServiceMutex_;
57     std::shared_ptr<AudioSessionTimer> sessionTimer_;
58     std::unordered_map<int32_t, std::shared_ptr<AudioSession>> sessionMap_;
59     std::weak_ptr<SessionTimeOutCallback> timeOutCallback_;
60 };
61 } // namespace AudioStandard
62 } // namespace OHOS
63 
64 #endif // ST_AUDIO_SESSION_SERVICE_H