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