1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <vector>
20 #include <map>
21 #include <unistd.h>
22 #include <sys/types.h>
23 
24 #include <system/audio.h>
25 #include <audiomanager/AudioManager.h>
26 #include <media/AudioProductStrategy.h>
27 #include <utils/Errors.h>
28 #include <utils/KeyedVector.h>
29 #include <utils/RefBase.h>
30 #include <utils/String8.h>
31 #include <policy.h>
32 #include <Volume.h>
33 #include "AudioPatch.h"
34 #include "EffectDescriptor.h"
35 
36 namespace android {
37 
38 class AudioPolicyMix;
39 class DeviceDescriptor;
40 class HwAudioOutputDescriptor;
41 class SwAudioOutputDescriptor;
42 
43 class ClientDescriptor: public RefBase
44 {
45 public:
46     ClientDescriptor(audio_port_handle_t portId, uid_t uid, audio_session_t sessionId,
47                      audio_attributes_t attributes, audio_config_base_t config,
48                      audio_port_handle_t preferredDeviceId,
49                      bool isPreferredDeviceForExclusiveUse = false) :
mPortId(portId)50         mPortId(portId), mUid(uid), mSessionId(sessionId), mAttributes(attributes),
51         mConfig(config), mPreferredDeviceId(preferredDeviceId), mActive(false),
52         mPreferredDeviceForExclusiveUse(isPreferredDeviceForExclusiveUse){}
53     ~ClientDescriptor() override = default;
54 
55     virtual void dump(String8 *dst, int spaces, int index) const;
56     virtual std::string toShortString() const;
57 
portId()58     audio_port_handle_t portId() const { return mPortId; }
uid()59     uid_t uid() const { return mUid; }
session()60     audio_session_t session() const { return mSessionId; };
attributes()61     audio_attributes_t attributes() const { return mAttributes; }
config()62     audio_config_base_t config() const { return mConfig; }
preferredDeviceId()63     audio_port_handle_t preferredDeviceId() const { return mPreferredDeviceId; };
setPreferredDeviceId(audio_port_handle_t preferredDeviceId)64     void setPreferredDeviceId(audio_port_handle_t preferredDeviceId) {
65         mPreferredDeviceId = preferredDeviceId;
66     }
isPreferredDeviceForExclusiveUse()67     bool isPreferredDeviceForExclusiveUse() const { return mPreferredDeviceForExclusiveUse; }
setActive(bool active)68     virtual void setActive(bool active) { mActive = active; }
active()69     bool active() const { return mActive; }
70     bool hasPreferredDevice(bool activeOnly = false) const {
71         return mPreferredDeviceId != AUDIO_PORT_HANDLE_NONE && (!activeOnly || mActive);
72     }
73 
74 private:
75     const audio_port_handle_t mPortId;  // unique Id for this client
76     const uid_t mUid;                     // client UID
77     const audio_session_t mSessionId;       // audio session ID
78     const audio_attributes_t mAttributes; // usage...
79     const audio_config_base_t mConfig;
80           audio_port_handle_t mPreferredDeviceId;  // selected input device port ID
81           bool mActive;
82           bool mPreferredDeviceForExclusiveUse = false;
83 };
84 
85 class TrackClientDescriptor: public ClientDescriptor
86 {
87 public:
TrackClientDescriptor(audio_port_handle_t portId,uid_t uid,audio_session_t sessionId,audio_attributes_t attributes,audio_config_base_t config,audio_port_handle_t preferredDeviceId,audio_stream_type_t stream,product_strategy_t strategy,VolumeSource volumeSource,audio_output_flags_t flags,bool isPreferredDeviceForExclusiveUse,std::vector<wp<SwAudioOutputDescriptor>> secondaryOutputs,wp<AudioPolicyMix> primaryMix)88     TrackClientDescriptor(audio_port_handle_t portId, uid_t uid, audio_session_t sessionId,
89                           audio_attributes_t attributes, audio_config_base_t config,
90                           audio_port_handle_t preferredDeviceId, audio_stream_type_t stream,
91                           product_strategy_t strategy, VolumeSource volumeSource,
92                           audio_output_flags_t flags,
93                           bool isPreferredDeviceForExclusiveUse,
94                           std::vector<wp<SwAudioOutputDescriptor>> secondaryOutputs,
95                           wp<AudioPolicyMix> primaryMix) :
96         ClientDescriptor(portId, uid, sessionId, attributes, config, preferredDeviceId,
97                          isPreferredDeviceForExclusiveUse),
98         mStream(stream), mStrategy(strategy), mVolumeSource(volumeSource), mFlags(flags),
99         mSecondaryOutputs(std::move(secondaryOutputs)), mPrimaryMix(primaryMix) {}
100     ~TrackClientDescriptor() override = default;
101 
102     using ClientDescriptor::dump;
103     void dump(String8 *dst, int spaces, int index) const override;
104     std::string toShortString() const override;
105 
flags()106     audio_output_flags_t flags() const { return mFlags; }
stream()107     audio_stream_type_t stream() const { return mStream; }
strategy()108     product_strategy_t strategy() const { return mStrategy; }
getSecondaryOutputs()109     const std::vector<wp<SwAudioOutputDescriptor>>& getSecondaryOutputs() const {
110         return mSecondaryOutputs;
111     };
volumeSource()112     VolumeSource volumeSource() const { return mVolumeSource; }
getPrimaryMix()113     const sp<AudioPolicyMix> getPrimaryMix() const {
114         return mPrimaryMix.promote();
115     };
116 
setActive(bool active)117     void setActive(bool active) override
118     {
119         int delta = active ? 1 : -1;
120         changeActivityCount(delta);
121     }
changeActivityCount(int delta)122     void changeActivityCount(int delta)
123     {
124         if (delta > 0) {
125             mActivityCount += delta;
126         } else {
127             LOG_ALWAYS_FATAL_IF(!mActivityCount, "%s(%s) invalid delta %d, inactive client",
128                                  __func__, toShortString().c_str(), delta);
129             LOG_ALWAYS_FATAL_IF(static_cast<int>(mActivityCount) < -delta,
130                                 "%s(%s) invalid delta %d, active client count %d",
131                                  __func__, toShortString().c_str(), delta, mActivityCount);
132             mActivityCount += delta;
133         }
134         ClientDescriptor::setActive(mActivityCount > 0);
135     }
getActivityCount()136     uint32_t getActivityCount() const { return mActivityCount; }
137 
138 private:
139     const audio_stream_type_t mStream;
140     const product_strategy_t mStrategy;
141     const VolumeSource mVolumeSource;
142     const audio_output_flags_t mFlags;
143     const std::vector<wp<SwAudioOutputDescriptor>> mSecondaryOutputs;
144     const wp<AudioPolicyMix> mPrimaryMix;
145     /**
146      * required for duplicating thread, prevent from removing active client from an output
147      * involved in a duplication.
148      */
149     uint32_t mActivityCount = 0;
150 };
151 
152 class RecordClientDescriptor: public ClientDescriptor
153 {
154 public:
RecordClientDescriptor(audio_port_handle_t portId,audio_unique_id_t riid,uid_t uid,audio_session_t sessionId,audio_attributes_t attributes,audio_config_base_t config,audio_port_handle_t preferredDeviceId,audio_source_t source,audio_input_flags_t flags,bool isSoundTrigger)155     RecordClientDescriptor(audio_port_handle_t portId, audio_unique_id_t riid, uid_t uid,
156                         audio_session_t sessionId, audio_attributes_t attributes,
157                         audio_config_base_t config, audio_port_handle_t preferredDeviceId,
158                         audio_source_t source, audio_input_flags_t flags, bool isSoundTrigger) :
159         ClientDescriptor(portId, uid, sessionId, attributes, config, preferredDeviceId),
160         mRIId(riid), mSource(source), mFlags(flags), mIsSoundTrigger(isSoundTrigger),
161         mAppState(APP_STATE_IDLE) {}
162     ~RecordClientDescriptor() override = default;
163 
164     using ClientDescriptor::dump;
165     void dump(String8 *dst, int spaces, int index) const override;
166 
riid()167     audio_unique_id_t riid() const { return mRIId; }
source()168     audio_source_t source() const { return mSource; }
flags()169     audio_input_flags_t flags() const { return mFlags; }
isSoundTrigger()170     bool isSoundTrigger() const { return mIsSoundTrigger; }
isLowLevel()171     bool isLowLevel() const { return mRIId == RECORD_RIID_INVALID; }
setAppState(app_state_t appState)172     void setAppState(app_state_t appState) { mAppState = appState; }
appState()173     app_state_t appState() { return mAppState; }
isSilenced()174     bool isSilenced() const { return mAppState == APP_STATE_IDLE; }
175     void trackEffectEnabled(const sp<EffectDescriptor> &effect, bool enabled);
getEnabledEffects()176     EffectDescriptorCollection getEnabledEffects() const { return mEnabledEffects; }
177 
178 private:
179     const audio_unique_id_t mRIId;
180     const audio_source_t mSource;
181     const audio_input_flags_t mFlags;
182     const bool mIsSoundTrigger;
183           app_state_t mAppState;
184     EffectDescriptorCollection mEnabledEffects;
185 };
186 
187 class SourceClientDescriptor: public TrackClientDescriptor
188 {
189 public:
190     SourceClientDescriptor(audio_port_handle_t portId, uid_t uid, audio_attributes_t attributes,
191                            const struct audio_port_config &config,
192                            const sp<DeviceDescriptor>& srcDevice,
193                            audio_stream_type_t stream, product_strategy_t strategy,
194                            VolumeSource volumeSource);
195 
196     ~SourceClientDescriptor() override = default;
197 
getPatchHandle()198     audio_patch_handle_t getPatchHandle() const { return mPatchHandle; }
setPatchHandle(audio_patch_handle_t patchHandle)199     void setPatchHandle(audio_patch_handle_t patchHandle) { mPatchHandle = patchHandle; }
200 
srcDevice()201     sp<DeviceDescriptor> srcDevice() const { return mSrcDevice; }
swOutput()202     wp<SwAudioOutputDescriptor> swOutput() const { return mSwOutput; }
203     void setSwOutput(const sp<SwAudioOutputDescriptor>& swOutput);
hwOutput()204     wp<HwAudioOutputDescriptor> hwOutput() const { return mHwOutput; }
205     void setHwOutput(const sp<HwAudioOutputDescriptor>& hwOutput);
206 
207     using ClientDescriptor::dump;
208     void dump(String8 *dst, int spaces, int index) const override;
209 
210  private:
211     audio_patch_handle_t mPatchHandle = AUDIO_PATCH_HANDLE_NONE;
212     const sp<DeviceDescriptor> mSrcDevice;
213     wp<SwAudioOutputDescriptor> mSwOutput;
214     wp<HwAudioOutputDescriptor> mHwOutput;
215 };
216 
217 class SourceClientCollection :
218     public DefaultKeyedVector< audio_port_handle_t, sp<SourceClientDescriptor> >
219 {
220 public:
221     void dump(String8 *dst) const;
222 };
223 
224 typedef std::vector< sp<TrackClientDescriptor> > TrackClientVector;
225 typedef std::vector< sp<RecordClientDescriptor> > RecordClientVector;
226 
227 // A Map that associates a portId with a client (type T)
228 // which is either TrackClientDescriptor or RecordClientDescriptor.
229 
230 template<typename T>
231 class ClientMapHandler {
232 public:
233     virtual ~ClientMapHandler() = default;
234 
235     // Track client management
addClient(const sp<T> & client)236     virtual void addClient(const sp<T> &client) {
237         const audio_port_handle_t portId = client->portId();
238         LOG_ALWAYS_FATAL_IF(!mClients.emplace(portId, client).second,
239                 "%s(%d): attempting to add client that already exists", __func__, portId);
240     }
getClient(audio_port_handle_t portId)241     sp<T> getClient(audio_port_handle_t portId) const {
242         auto it = mClients.find(portId);
243         if (it == mClients.end()) return nullptr;
244         return it->second;
245     }
removeClient(audio_port_handle_t portId)246     virtual void removeClient(audio_port_handle_t portId) {
247         auto it = mClients.find(portId);
248         LOG_ALWAYS_FATAL_IF(it == mClients.end(),
249                 "%s(%d): client does not exist", __func__, portId);
250         LOG_ALWAYS_FATAL_IF(it->second->active(),
251                 "%s(%d): removing client still active!", __func__, portId);
252         (void)mClients.erase(it);
253     }
getClientCount()254     size_t getClientCount() const {
255         return mClients.size();
256     }
dump(String8 * dst)257     virtual void dump(String8 *dst) const {
258         size_t index = 0;
259         for (const auto& client: getClientIterable()) {
260             client->dump(dst, 2, index++);
261         }
262     }
263 
264     // helper types
265     using ClientMap = std::map<audio_port_handle_t, sp<T>>;
266     using ClientMapIterator = typename ClientMap::const_iterator;  // ClientMap is const qualified
267     class ClientIterable {
268     public:
ClientIterable(const ClientMapHandler<T> & ref)269         explicit ClientIterable(const ClientMapHandler<T> &ref) : mClientMapHandler(ref) { }
270 
271         class iterator {
272         public:
273             // traits
274             using iterator_category = std::forward_iterator_tag;
275             using value_type = sp<T>;
276             using difference_type = ptrdiff_t;
277             using pointer = const sp<T>*;    // Note: const
278             using reference = const sp<T>&;  // Note: const
279 
280             // implementation
iterator(const ClientMapIterator & it)281             explicit iterator(const ClientMapIterator &it) : mIt(it) { }
282             iterator& operator++()    /* prefix */     { ++mIt; return *this; }
283             reference operator* () const               { return mIt->second; }
284             reference operator->() const               { return mIt->second; } // as if sp<>
285             difference_type operator-(const iterator& rhs) {return mIt - rhs.mIt; }
286             bool operator==(const iterator& rhs) const { return mIt == rhs.mIt; }
287             bool operator!=(const iterator& rhs) const { return mIt != rhs.mIt; }
288         private:
289             ClientMapIterator mIt;
290         };
291 
begin()292         iterator begin() const { return iterator{mClientMapHandler.mClients.begin()}; }
end()293         iterator end() const { return iterator{mClientMapHandler.mClients.end()}; }
294 
295     private:
296         const ClientMapHandler<T>& mClientMapHandler; // iterating does not modify map.
297     };
298 
299     // return an iterable object that can be used in a range-based-for to enumerate clients.
300     // this iterable does not allow modification, it should be used as a temporary.
getClientIterable()301     ClientIterable getClientIterable() const {
302         return ClientIterable{*this};
303     }
304 
305 private:
306     // ClientMap maps a portId to a client descriptor (both uniquely identify each other).
307     ClientMap mClients;
308 };
309 
310 } // namespace android
311