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 <sys/types.h> 20 #include <unistd.h> 21 22 #include <map> 23 #include <vector> 24 25 #include <android-base/stringprintf.h> 26 #include <audiomanager/AudioManager.h> 27 #include <media/AudioProductStrategy.h> 28 #include <policy.h> 29 #include <system/audio.h> 30 #include <utils/Errors.h> 31 #include <utils/KeyedVector.h> 32 #include <utils/RefBase.h> 33 #include <utils/String8.h> 34 #include <Volume.h> 35 #include "AudioPatch.h" 36 #include "EffectDescriptor.h" 37 38 namespace android { 39 40 class AudioPolicyMix; 41 class DeviceDescriptor; 42 class HwAudioOutputDescriptor; 43 class SwAudioOutputDescriptor; 44 45 class ClientDescriptor: public RefBase 46 { 47 public: 48 ClientDescriptor(audio_port_handle_t portId, uid_t uid, audio_session_t sessionId, 49 audio_attributes_t attributes, audio_config_base_t config, 50 audio_port_handle_t preferredDeviceId, 51 bool isPreferredDeviceForExclusiveUse = false) : mPortId(portId)52 mPortId(portId), mUid(uid), mSessionId(sessionId), mAttributes(attributes), 53 mConfig(config), mPreferredDeviceId(preferredDeviceId), mActive(false), 54 mPreferredDeviceForExclusiveUse(isPreferredDeviceForExclusiveUse){} 55 ~ClientDescriptor() override = default; 56 57 virtual void dump(String8 *dst, int spaces) const; 58 virtual std::string toShortString() const; 59 /** 60 * @brief isInternal 61 * @return true if the client corresponds to an audio patch created from createAudioPatch API or 62 * for call audio routing, or false if the client corresponds to an AudioTrack, AudioRecord or 63 * HW Audio Source. 64 */ isInternal()65 virtual bool isInternal() const { return false; } isCallRx()66 virtual bool isCallRx() const { return false; } isCallTx()67 virtual bool isCallTx() const { return false; } portId()68 audio_port_handle_t portId() const { return mPortId; } uid()69 uid_t uid() const { return mUid; } session()70 audio_session_t session() const { return mSessionId; }; attributes()71 audio_attributes_t attributes() const { return mAttributes; } config()72 audio_config_base_t config() const { return mConfig; } preferredDeviceId()73 audio_port_handle_t preferredDeviceId() const { return mPreferredDeviceId; }; setPreferredDeviceId(audio_port_handle_t preferredDeviceId)74 void setPreferredDeviceId(audio_port_handle_t preferredDeviceId) { 75 mPreferredDeviceId = preferredDeviceId; 76 } isPreferredDeviceForExclusiveUse()77 bool isPreferredDeviceForExclusiveUse() const { return mPreferredDeviceForExclusiveUse; } setActive(bool active)78 virtual void setActive(bool active) { mActive = active; } active()79 bool active() const { return mActive; } 80 /** 81 * @brief hasPreferredDevice Note that as internal clients use preferred device for convenience, 82 * we do hide this internal behavior to prevent from regression (like invalidating track for 83 * clients following same strategies...) 84 * @param activeOnly 85 * @return 86 */ 87 bool hasPreferredDevice(bool activeOnly = false) const { 88 return !isInternal() && 89 mPreferredDeviceId != AUDIO_PORT_HANDLE_NONE && (!activeOnly || mActive); 90 } 91 92 private: 93 const audio_port_handle_t mPortId; // unique Id for this client 94 const uid_t mUid; // client UID 95 const audio_session_t mSessionId; // audio session ID 96 const audio_attributes_t mAttributes; // usage... 97 const audio_config_base_t mConfig; 98 audio_port_handle_t mPreferredDeviceId; // selected input device port ID 99 bool mActive; 100 bool mPreferredDeviceForExclusiveUse = false; 101 }; 102 103 class TrackClientDescriptor: public ClientDescriptor 104 { 105 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)106 TrackClientDescriptor(audio_port_handle_t portId, uid_t uid, audio_session_t sessionId, 107 audio_attributes_t attributes, audio_config_base_t config, 108 audio_port_handle_t preferredDeviceId, audio_stream_type_t stream, 109 product_strategy_t strategy, VolumeSource volumeSource, 110 audio_output_flags_t flags, 111 bool isPreferredDeviceForExclusiveUse, 112 std::vector<wp<SwAudioOutputDescriptor>> secondaryOutputs, 113 wp<AudioPolicyMix> primaryMix) : 114 ClientDescriptor(portId, uid, sessionId, attributes, config, preferredDeviceId, 115 isPreferredDeviceForExclusiveUse), 116 mStream(stream), mStrategy(strategy), mVolumeSource(volumeSource), mFlags(flags), 117 mSecondaryOutputs(std::move(secondaryOutputs)), mPrimaryMix(primaryMix) {} 118 ~TrackClientDescriptor() override = default; 119 120 using ClientDescriptor::dump; 121 void dump(String8 *dst, int spaces) const override; 122 std::string toShortString() const override; 123 flags()124 audio_output_flags_t flags() const { return mFlags; } stream()125 audio_stream_type_t stream() const { return mStream; } strategy()126 product_strategy_t strategy() const { return mStrategy; } getSecondaryOutputs()127 const std::vector<wp<SwAudioOutputDescriptor>>& getSecondaryOutputs() const { 128 return mSecondaryOutputs; 129 }; setSecondaryOutputs(std::vector<wp<SwAudioOutputDescriptor>> && secondaryOutputs)130 void setSecondaryOutputs(std::vector<wp<SwAudioOutputDescriptor>>&& secondaryOutputs) { 131 mSecondaryOutputs = std::move(secondaryOutputs); 132 } volumeSource()133 VolumeSource volumeSource() const { return mVolumeSource; } getPrimaryMix()134 const sp<AudioPolicyMix> getPrimaryMix() const { 135 return mPrimaryMix.promote(); 136 }; hasLostPrimaryMix()137 bool hasLostPrimaryMix() const { 138 return mPrimaryMix.unsafe_get() && !mPrimaryMix.promote(); 139 } 140 setActive(bool active)141 void setActive(bool active) override 142 { 143 int delta = active ? 1 : -1; 144 changeActivityCount(delta); 145 } changeActivityCount(int delta)146 void changeActivityCount(int delta) 147 { 148 if (delta > 0) { 149 mActivityCount += delta; 150 } else { 151 LOG_ALWAYS_FATAL_IF(!mActivityCount, "%s(%s) invalid delta %d, inactive client", 152 __func__, toShortString().c_str(), delta); 153 LOG_ALWAYS_FATAL_IF(static_cast<int>(mActivityCount) < -delta, 154 "%s(%s) invalid delta %d, active client count %d", 155 __func__, toShortString().c_str(), delta, mActivityCount); 156 mActivityCount += delta; 157 } 158 ClientDescriptor::setActive(mActivityCount > 0); 159 } getActivityCount()160 uint32_t getActivityCount() const { return mActivityCount; } 161 isInvalid()162 bool isInvalid() const { 163 return mIsInvalid; 164 } 165 setIsInvalid()166 void setIsInvalid() { 167 mIsInvalid = true; 168 } 169 getInternalMute()170 bool getInternalMute() const { return mInternalMute; } 171 172 /** 173 * Set the internal mute for a client. Return true if the existing value is different from 174 * the given value. 175 */ setInternalMute(bool muted)176 bool setInternalMute(bool muted) { 177 const bool result = (mInternalMute != muted); 178 mInternalMute = muted; 179 return result; 180 } 181 182 private: 183 const audio_stream_type_t mStream; 184 const product_strategy_t mStrategy; 185 const VolumeSource mVolumeSource; 186 const audio_output_flags_t mFlags; 187 std::vector<wp<SwAudioOutputDescriptor>> mSecondaryOutputs; 188 const wp<AudioPolicyMix> mPrimaryMix; 189 /** 190 * required for duplicating thread, prevent from removing active client from an output 191 * involved in a duplication. 192 */ 193 uint32_t mActivityCount = 0; 194 bool mIsInvalid = false; 195 bool mInternalMute = false; 196 }; 197 198 class RecordClientDescriptor: public ClientDescriptor 199 { 200 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)201 RecordClientDescriptor(audio_port_handle_t portId, audio_unique_id_t riid, uid_t uid, 202 audio_session_t sessionId, audio_attributes_t attributes, 203 audio_config_base_t config, audio_port_handle_t preferredDeviceId, 204 audio_source_t source, audio_input_flags_t flags, bool isSoundTrigger) : 205 ClientDescriptor(portId, uid, sessionId, attributes, config, preferredDeviceId), 206 mRIId(riid), mSource(source), mFlags(flags), mIsSoundTrigger(isSoundTrigger), 207 mAppState(APP_STATE_IDLE) {} 208 ~RecordClientDescriptor() override = default; 209 210 using ClientDescriptor::dump; 211 void dump(String8 *dst, int spaces) const override; 212 riid()213 audio_unique_id_t riid() const { return mRIId; } source()214 audio_source_t source() const { return mSource; } flags()215 audio_input_flags_t flags() const { return mFlags; } isSoundTrigger()216 bool isSoundTrigger() const { return mIsSoundTrigger; } isLowLevel()217 bool isLowLevel() const { return mRIId == RECORD_RIID_INVALID; } setAppState(app_state_t appState)218 void setAppState(app_state_t appState) { mAppState = appState; } appState()219 app_state_t appState() { return mAppState; } isSilenced()220 bool isSilenced() const { return mAppState == APP_STATE_IDLE; } 221 void trackEffectEnabled(const sp<EffectDescriptor> &effect, bool enabled); getEnabledEffects()222 EffectDescriptorCollection getEnabledEffects() const { return mEnabledEffects; } 223 224 private: 225 const audio_unique_id_t mRIId; 226 const audio_source_t mSource; 227 const audio_input_flags_t mFlags; 228 const bool mIsSoundTrigger; 229 app_state_t mAppState; 230 EffectDescriptorCollection mEnabledEffects; 231 }; 232 233 class SourceClientDescriptor: public TrackClientDescriptor 234 { 235 public: 236 SourceClientDescriptor(audio_port_handle_t portId, uid_t uid, audio_attributes_t attributes, 237 const struct audio_port_config &config, 238 const sp<DeviceDescriptor>& srcDevice, 239 audio_stream_type_t stream, product_strategy_t strategy, 240 VolumeSource volumeSource, 241 bool isInternal, bool isCallRx, bool isCallTx); 242 243 ~SourceClientDescriptor() override = default; 244 connect(audio_patch_handle_t patchHandle,const sp<DeviceDescriptor> & sinkDevice)245 void connect(audio_patch_handle_t patchHandle, const sp<DeviceDescriptor>& sinkDevice) { 246 mPatchHandle = patchHandle; 247 mSinkDevice = sinkDevice; 248 } disconnect()249 void disconnect() { 250 mPatchHandle = AUDIO_PATCH_HANDLE_NONE; 251 mSinkDevice = nullptr; 252 } belongsToOutput(const sp<SwAudioOutputDescriptor> & swOutput)253 bool belongsToOutput(const sp<SwAudioOutputDescriptor> &swOutput) const { 254 return swOutput != nullptr && mSwOutput.promote() == swOutput; 255 } setUseSwBridge()256 void setUseSwBridge() { mUseSwBridge = true; } useSwBridge()257 bool useSwBridge() const { return mUseSwBridge; } canCloseOutput()258 bool canCloseOutput() const { return mCloseOutput; } isConnected()259 bool isConnected() const { return mPatchHandle != AUDIO_PATCH_HANDLE_NONE; } getPatchHandle()260 audio_patch_handle_t getPatchHandle() const { return mPatchHandle; } srcDevice()261 sp<DeviceDescriptor> srcDevice() const { return mSrcDevice; } sinkDevice()262 sp<DeviceDescriptor> sinkDevice() const { return mSinkDevice; } swOutput()263 wp<SwAudioOutputDescriptor> swOutput() const { return mSwOutput; } 264 void setSwOutput(const sp<SwAudioOutputDescriptor>& swOutput, bool closeOutput = false); hwOutput()265 wp<HwAudioOutputDescriptor> hwOutput() const { return mHwOutput; } 266 void setHwOutput(const sp<HwAudioOutputDescriptor>& hwOutput); isInternal()267 bool isInternal() const override { return mIsInternal; } isCallRx()268 bool isCallRx() const override { return mIsCallRx; } isCallTx()269 bool isCallTx() const override { return mIsCallTx; } 270 271 using ClientDescriptor::dump; 272 void dump(String8 *dst, int spaces) const override; 273 274 private: 275 audio_patch_handle_t mPatchHandle = AUDIO_PATCH_HANDLE_NONE; 276 const sp<DeviceDescriptor> mSrcDevice; 277 sp<DeviceDescriptor> mSinkDevice; 278 wp<SwAudioOutputDescriptor> mSwOutput; 279 wp<HwAudioOutputDescriptor> mHwOutput; 280 bool mUseSwBridge = false; 281 /** 282 * For either HW bridge associated to a SwOutput for activity / volume or SwBridge for also 283 * sample rendering / activity & volume, an existing playback thread may be reused (e.g. 284 * not already opened at APM startup or Direct Output). 285 * If reusing an already opened output, when this output is not used anymore, the AudioFlinger 286 * patch must be updated to refine the output device(s) information and ensure the right 287 * behavior of AudioDeviceCallback. 288 */ 289 bool mCloseOutput = false; 290 /** 291 * True for specialized Client Descriptor for either a raw patch created from 292 * @see createAudioPatch API or for internal audio patches managed by APM 293 * (e.g. phone call patches). 294 * Whatever the bridge created (software or hardware), we need a client to track the activity 295 * and manage volumes. 296 * The Audio Patch requested sink is expressed as a preferred device which allows to route 297 * the SwOutput. Then APM will performs checks on the UID (against UID of Audioserver) of the 298 * requester to prevent rerouting SwOutput involved in raw patches. 299 */ 300 bool mIsInternal = false; 301 bool mIsCallRx = false; 302 bool mIsCallTx = false; 303 }; 304 305 class SourceClientCollection : 306 public DefaultKeyedVector< audio_port_handle_t, sp<SourceClientDescriptor> > 307 { 308 public: 309 void dump(String8 *dst) const; 310 }; 311 312 typedef std::vector< sp<TrackClientDescriptor> > TrackClientVector; 313 typedef std::vector< sp<RecordClientDescriptor> > RecordClientVector; 314 315 // A Map that associates a portId with a client (type T) 316 // which is either TrackClientDescriptor or RecordClientDescriptor. 317 318 template<typename T> 319 class ClientMapHandler { 320 public: 321 virtual ~ClientMapHandler() = default; 322 323 // Track client management addClient(const sp<T> & client)324 virtual void addClient(const sp<T> &client) { 325 const audio_port_handle_t portId = client->portId(); 326 LOG_ALWAYS_FATAL_IF(!mClients.emplace(portId, client).second, 327 "%s(%d): attempting to add client that already exists", __func__, portId); 328 } getClient(audio_port_handle_t portId)329 sp<T> getClient(audio_port_handle_t portId) const { 330 auto it = mClients.find(portId); 331 if (it == mClients.end()) return nullptr; 332 return it->second; 333 } removeClient(audio_port_handle_t portId)334 virtual void removeClient(audio_port_handle_t portId) { 335 auto it = mClients.find(portId); 336 LOG_ALWAYS_FATAL_IF(it == mClients.end(), 337 "%s(%d): client does not exist", __func__, portId); 338 LOG_ALWAYS_FATAL_IF(it->second->active(), 339 "%s(%d): removing client still active!", __func__, portId); 340 (void)mClients.erase(it); 341 } getClientCount()342 size_t getClientCount() const { 343 return mClients.size(); 344 } 345 virtual void dump(String8 *dst, int spaces, const char* extraInfo = nullptr) const { 346 (void)extraInfo; 347 size_t index = 0; 348 for (const auto& client: getClientIterable()) { 349 const std::string prefix = base::StringPrintf("%*s %zu. ", spaces, "", ++index); 350 dst->appendFormat("%s", prefix.c_str()); 351 client->dump(dst, prefix.size()); 352 } 353 } 354 355 // helper types 356 using ClientMap = std::map<audio_port_handle_t, sp<T>>; 357 using ClientMapIterator = typename ClientMap::const_iterator; // ClientMap is const qualified 358 class ClientIterable { 359 public: ClientIterable(const ClientMapHandler<T> & ref)360 explicit ClientIterable(const ClientMapHandler<T> &ref) : mClientMapHandler(ref) { } 361 362 class iterator { 363 public: 364 // traits 365 using iterator_category = std::forward_iterator_tag; 366 using value_type = sp<T>; 367 using difference_type = ptrdiff_t; 368 using pointer = const sp<T>*; // Note: const 369 using reference = const sp<T>&; // Note: const 370 371 // implementation iterator(const ClientMapIterator & it)372 explicit iterator(const ClientMapIterator &it) : mIt(it) { } 373 iterator& operator++() /* prefix */ { ++mIt; return *this; } 374 reference operator* () const { return mIt->second; } 375 reference operator->() const { return mIt->second; } // as if sp<> 376 difference_type operator-(const iterator& rhs) {return mIt - rhs.mIt; } 377 bool operator==(const iterator& rhs) const { return mIt == rhs.mIt; } 378 bool operator!=(const iterator& rhs) const { return mIt != rhs.mIt; } 379 private: 380 ClientMapIterator mIt; 381 }; 382 begin()383 iterator begin() const { return iterator{mClientMapHandler.mClients.begin()}; } end()384 iterator end() const { return iterator{mClientMapHandler.mClients.end()}; } 385 386 private: 387 const ClientMapHandler<T>& mClientMapHandler; // iterating does not modify map. 388 }; 389 390 // return an iterable object that can be used in a range-based-for to enumerate clients. 391 // this iterable does not allow modification, it should be used as a temporary. getClientIterable()392 ClientIterable getClientIterable() const { 393 return ClientIterable{*this}; 394 } 395 396 private: 397 // ClientMap maps a portId to a client descriptor (both uniquely identify each other). 398 ClientMap mClients; 399 }; 400 401 } // namespace android 402