1 /* 2 * Copyright (C) 2015 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 #define __STDC_LIMIT_MACROS 20 #include <inttypes.h> 21 22 #include <sys/types.h> 23 24 #include <media/AudioContainers.h> 25 #include <utils/Errors.h> 26 #include <utils/Timers.h> 27 #include <utils/KeyedVector.h> 28 #include <system/audio.h> 29 #include "AudioIODescriptorInterface.h" 30 #include "ClientDescriptor.h" 31 #include "DeviceDescriptor.h" 32 #include "PolicyAudioPort.h" 33 #include <vector> 34 35 namespace android { 36 37 class IOProfile; 38 class AudioPolicyMix; 39 class AudioPolicyClientInterface; 40 41 class ActivityTracking 42 { 43 public: 44 virtual ~ActivityTracking() = default; 45 bool isActive(uint32_t inPastMs = 0, nsecs_t sysTime = 0) const 46 { 47 if (mActivityCount > 0) { 48 return true; 49 } 50 if (inPastMs == 0) { 51 return false; 52 } 53 if (sysTime == 0) { 54 sysTime = systemTime(); 55 } 56 if (ns2ms(sysTime - mStopTime) < inPastMs) { 57 return true; 58 } 59 return false; 60 } changeActivityCount(int delta)61 void changeActivityCount(int delta) 62 { 63 if ((delta + (int)mActivityCount) < 0) { 64 LOG_ALWAYS_FATAL("%s: invalid delta %d, refCount %d", __func__, delta, mActivityCount); 65 } 66 mActivityCount += delta; 67 if (!mActivityCount) { 68 setStopTime(systemTime()); 69 } 70 } getActivityCount()71 uint32_t getActivityCount() const { return mActivityCount; } getStopTime()72 nsecs_t getStopTime() const { return mStopTime; } setStopTime(nsecs_t stopTime)73 void setStopTime(nsecs_t stopTime) { mStopTime = stopTime; } 74 dump(String8 * dst,int spaces)75 virtual void dump(String8 *dst, int spaces) const 76 { 77 dst->appendFormat("%*s- ActivityCount: %d, StopTime: %" PRId64 ", ", spaces, "", 78 getActivityCount(), getStopTime()); 79 } 80 private: 81 uint32_t mActivityCount = 0; 82 nsecs_t mStopTime = 0; 83 }; 84 85 /** 86 * @brief VolumeActivity: it tracks the activity for volume policy (volume index, mute, 87 * memorize previous stop, and store mute if incompatible device with another strategy. 88 */ 89 class VolumeActivity : public ActivityTracking 90 { 91 public: isMuted()92 bool isMuted() const { return mMuteCount > 0; } getMuteCount()93 int getMuteCount() const { return mMuteCount; } incMuteCount()94 int incMuteCount() { return ++mMuteCount; } decMuteCount()95 int decMuteCount() { return mMuteCount > 0 ? --mMuteCount : -1; } 96 dump(String8 * dst,int spaces)97 void dump(String8 *dst, int spaces) const override 98 { 99 ActivityTracking::dump(dst, spaces); 100 dst->appendFormat(", Volume: %.03f, MuteCount: %02d\n", mCurVolumeDb, mMuteCount); 101 } setVolume(float volumeDb)102 void setVolume(float volumeDb) { mCurVolumeDb = volumeDb; } getVolume()103 float getVolume() const { return mCurVolumeDb; } 104 105 private: 106 int mMuteCount = 0; /**< mute request counter */ 107 float mCurVolumeDb = NAN; /**< current volume in dB. */ 108 }; 109 /** 110 * Note: volume activities shall be indexed by CurvesId if we want to allow multiple 111 * curves per volume source, inferring a mute management or volume balancing between HW and SW is 112 * done 113 */ 114 using VolumeActivities = std::map<VolumeSource, VolumeActivity>; 115 116 /** 117 * @brief The Activity class: it tracks the activity for volume policy (volume index, mute, 118 * memorize previous stop, and store mute if incompatible device with another strategy. 119 * Having this class prevents from looping on all attributes (legacy streams) of the strategy 120 */ 121 class RoutingActivity : public ActivityTracking 122 { 123 public: setMutedByDevice(bool isMuted)124 void setMutedByDevice( bool isMuted) { mIsMutedByDevice = isMuted; } isMutedByDevice()125 bool isMutedByDevice() const { return mIsMutedByDevice; } 126 dump(String8 * dst,int spaces)127 void dump(String8 *dst, int spaces) const override { 128 ActivityTracking::dump(dst, spaces); 129 dst->appendFormat("\n"); 130 } 131 private: 132 /** 133 * strategies muted because of incompatible device selection. 134 * See AudioPolicyManager::checkDeviceMuteStrategies() 135 */ 136 bool mIsMutedByDevice = false; 137 }; 138 using RoutingActivities = std::map<product_strategy_t, RoutingActivity>; 139 140 // descriptor for audio outputs. Used to maintain current configuration of each opened audio output 141 // and keep track of the usage of this output by each audio stream type. 142 class AudioOutputDescriptor: public AudioPortConfig, 143 public PolicyAudioPortConfig, 144 public AudioIODescriptorInterface, 145 public ClientMapHandler<TrackClientDescriptor> 146 { 147 public: 148 AudioOutputDescriptor(const sp<PolicyAudioPort>& policyAudioPort, 149 AudioPolicyClientInterface *clientInterface); ~AudioOutputDescriptor()150 virtual ~AudioOutputDescriptor() {} 151 152 void dump(String8 *dst) const override; 153 void log(const char* indent); 154 devices()155 virtual DeviceVector devices() const { return mDevices; } 156 bool sharesHwModuleWith(const sp<AudioOutputDescriptor>& outputDesc); supportedDevices()157 virtual DeviceVector supportedDevices() const { return mDevices; } isDuplicated()158 virtual bool isDuplicated() const { return false; } latency()159 virtual uint32_t latency() { return 0; } 160 virtual bool isFixedVolume(const DeviceTypeSet& deviceTypes); 161 virtual bool setVolume(float volumeDb, 162 VolumeSource volumeSource, const StreamTypeVector &streams, 163 const DeviceTypeSet& deviceTypes, 164 uint32_t delayMs, 165 bool force); 166 167 /** 168 * @brief setStopTime set the stop time due to the client stoppage or a re routing of this 169 * client 170 * @param client to be considered 171 * @param sysTime when the client stopped/was rerouted 172 */ 173 void setStopTime(const sp<TrackClientDescriptor>& client, nsecs_t sysTime); 174 175 /** 176 * Changes the client->active() state and the output descriptor's global active count, 177 * along with the stream active count and mActiveClients. 178 * The client must be previously added by the base class addClient(). 179 * In case of duplicating thread, client shall be added on the duplicated thread, not on the 180 * involved outputs but setClientActive will be called on all output to track strategy and 181 * active client for a given output. 182 * Active ref count of the client will be incremented/decremented through setActive API 183 */ 184 virtual void setClientActive(const sp<TrackClientDescriptor>& client, bool active); 185 186 bool isActive(uint32_t inPastMs) const; 187 bool isActive(VolumeSource volumeSource = VOLUME_SOURCE_NONE, 188 uint32_t inPastMs = 0, 189 nsecs_t sysTime = 0) const; 190 bool isAnyActive(VolumeSource volumeSourceToIgnore) const; 191 getActiveVolumeSources()192 std::vector<VolumeSource> getActiveVolumeSources() const { 193 std::vector<VolumeSource> activeList; 194 for (const auto &iter : mVolumeActivities) { 195 if (iter.second.isActive()) { 196 activeList.push_back(iter.first); 197 } 198 } 199 return activeList; 200 } getActivityCount(VolumeSource vs)201 uint32_t getActivityCount(VolumeSource vs) const 202 { 203 return mVolumeActivities.find(vs) != std::end(mVolumeActivities)? 204 mVolumeActivities.at(vs).getActivityCount() : 0; 205 } isMuted(VolumeSource vs)206 bool isMuted(VolumeSource vs) const 207 { 208 return mVolumeActivities.find(vs) != std::end(mVolumeActivities)? 209 mVolumeActivities.at(vs).isMuted() : false; 210 } getMuteCount(VolumeSource vs)211 int getMuteCount(VolumeSource vs) const 212 { 213 return mVolumeActivities.find(vs) != std::end(mVolumeActivities)? 214 mVolumeActivities.at(vs).getMuteCount() : 0; 215 } incMuteCount(VolumeSource vs)216 int incMuteCount(VolumeSource vs) 217 { 218 return mVolumeActivities[vs].incMuteCount(); 219 } decMuteCount(VolumeSource vs)220 int decMuteCount(VolumeSource vs) 221 { 222 return mVolumeActivities[vs].decMuteCount(); 223 } setCurVolume(VolumeSource vs,float volumeDb)224 void setCurVolume(VolumeSource vs, float volumeDb) 225 { 226 // Even if not activity for this source registered, need to create anyway 227 mVolumeActivities[vs].setVolume(volumeDb); 228 } getCurVolume(VolumeSource vs)229 float getCurVolume(VolumeSource vs) const 230 { 231 return mVolumeActivities.find(vs) != std::end(mVolumeActivities) ? 232 mVolumeActivities.at(vs).getVolume() : NAN; 233 } 234 235 bool isStrategyActive(product_strategy_t ps, uint32_t inPastMs = 0, nsecs_t sysTime = 0) const 236 { 237 return mRoutingActivities.find(ps) != std::end(mRoutingActivities)? 238 mRoutingActivities.at(ps).isActive(inPastMs, sysTime) : false; 239 } isStrategyMutedByDevice(product_strategy_t ps)240 bool isStrategyMutedByDevice(product_strategy_t ps) const 241 { 242 return mRoutingActivities.find(ps) != std::end(mRoutingActivities)? 243 mRoutingActivities.at(ps).isMutedByDevice() : false; 244 } setStrategyMutedByDevice(product_strategy_t ps,bool isMuted)245 void setStrategyMutedByDevice(product_strategy_t ps, bool isMuted) 246 { 247 mRoutingActivities[ps].setMutedByDevice(isMuted); 248 } 249 250 // PolicyAudioPortConfig getPolicyAudioPort()251 virtual sp<PolicyAudioPort> getPolicyAudioPort() const 252 { 253 return mPolicyAudioPort; 254 } 255 256 // AudioPortConfig 257 virtual status_t applyAudioPortConfig(const struct audio_port_config *config, 258 struct audio_port_config *backupConfig = NULL); 259 virtual void toAudioPortConfig(struct audio_port_config *dstConfig, 260 const struct audio_port_config *srcConfig = NULL) const; getAudioPort()261 virtual sp<AudioPort> getAudioPort() const { return mPolicyAudioPort->asAudioPort(); } 262 263 virtual void toAudioPort(struct audio_port *port) const; 264 265 audio_module_handle_t getModuleHandle() const; 266 267 // implementation of AudioIODescriptorInterface 268 audio_config_base_t getConfig() const override; 269 audio_patch_handle_t getPatchHandle() const override; 270 void setPatchHandle(audio_patch_handle_t handle) override; 271 272 TrackClientVector clientsList(bool activeOnly = false, 273 product_strategy_t strategy = PRODUCT_STRATEGY_NONE, 274 bool preferredDeviceOnly = false) const; 275 276 // override ClientMapHandler to abort when removing a client when active. removeClient(audio_port_handle_t portId)277 void removeClient(audio_port_handle_t portId) override { 278 auto client = getClient(portId); 279 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, 280 "%s(%d): nonexistent client portId %d", __func__, mId, portId); 281 // it is possible that when a client is removed, we could remove its 282 // associated active count by calling changeStreamActiveCount(), 283 // but that would be hiding a problem, so we log fatal instead. 284 auto clientIter = std::find(begin(mActiveClients), end(mActiveClients), client); 285 LOG_ALWAYS_FATAL_IF(clientIter != mActiveClients.end(), 286 "%s(%d) removing client portId %d which is active (count %d)", 287 __func__, mId, portId, client->getActivityCount()); 288 ClientMapHandler<TrackClientDescriptor>::removeClient(portId); 289 } 290 getActiveClients()291 const TrackClientVector& getActiveClients() const { 292 return mActiveClients; 293 } 294 useHwGain()295 bool useHwGain() const 296 { 297 return !devices().isEmpty() ? devices().itemAt(0)->hasGainController() : false; 298 } 299 300 DeviceVector mDevices; /**< current devices this output is routed to */ 301 wp<AudioPolicyMix> mPolicyMix; // non NULL when used by a dynamic policy 302 303 protected: 304 const sp<PolicyAudioPort> mPolicyAudioPort; 305 AudioPolicyClientInterface * const mClientInterface; 306 uint32_t mGlobalActiveCount = 0; // non-client-specific active count 307 audio_patch_handle_t mPatchHandle = AUDIO_PATCH_HANDLE_NONE; 308 309 // The ActiveClients shows the clients that contribute to the @VolumeSource counts 310 // and may include upstream clients from a duplicating thread. 311 // Compare with the ClientMap (mClients) which are external AudioTrack clients of the 312 // output descriptor (and do not count internal PatchTracks). 313 TrackClientVector mActiveClients; 314 315 RoutingActivities mRoutingActivities; /**< track routing activity on this ouput.*/ 316 317 VolumeActivities mVolumeActivities; /**< track volume activity on this ouput.*/ 318 }; 319 320 // Audio output driven by a software mixer in audio flinger. 321 class SwAudioOutputDescriptor: public AudioOutputDescriptor 322 { 323 public: 324 SwAudioOutputDescriptor(const sp<IOProfile>& profile, 325 AudioPolicyClientInterface *clientInterface); ~SwAudioOutputDescriptor()326 virtual ~SwAudioOutputDescriptor() {} 327 328 void dump(String8 *dst) const override; 329 virtual DeviceVector devices() const; setDevices(const DeviceVector & devices)330 void setDevices(const DeviceVector &devices) { mDevices = devices; } 331 bool sharesHwModuleWith(const sp<SwAudioOutputDescriptor>& outputDesc); 332 virtual DeviceVector supportedDevices() const; 333 virtual bool devicesSupportEncodedFormats(const DeviceTypeSet& deviceTypes); 334 virtual uint32_t latency(); isDuplicated()335 virtual bool isDuplicated() const { return (mOutput1 != NULL && mOutput2 != NULL); } 336 virtual bool isFixedVolume(const DeviceTypeSet& deviceTypes); subOutput1()337 sp<SwAudioOutputDescriptor> subOutput1() { return mOutput1; } subOutput2()338 sp<SwAudioOutputDescriptor> subOutput2() { return mOutput2; } 339 void setClientActive(const sp<TrackClientDescriptor>& client, bool active) override; setAllClientsInactive()340 void setAllClientsInactive() 341 { 342 for (const auto &client : clientsList(true)) { 343 setClientActive(client, false); 344 } 345 } 346 virtual bool setVolume(float volumeDb, 347 VolumeSource volumeSource, const StreamTypeVector &streams, 348 const DeviceTypeSet& device, 349 uint32_t delayMs, 350 bool force); 351 352 virtual void toAudioPortConfig(struct audio_port_config *dstConfig, 353 const struct audio_port_config *srcConfig = NULL) const; 354 virtual void toAudioPort(struct audio_port *port) const; 355 356 status_t open(const audio_config_t *config, 357 const DeviceVector &devices, 358 audio_stream_type_t stream, 359 audio_output_flags_t flags, 360 audio_io_handle_t *output); 361 362 // Called when a stream is about to be started 363 // Note: called before setClientActive(true); 364 status_t start(); 365 // Called after a stream is stopped. 366 // Note: called after setClientActive(false); 367 void stop(); 368 void close(); 369 status_t openDuplicating(const sp<SwAudioOutputDescriptor>& output1, 370 const sp<SwAudioOutputDescriptor>& output2, 371 audio_io_handle_t *ioHandle); 372 373 /** 374 * @brief supportsDevice 375 * @param device to be checked against 376 * @return true if the device is supported by type (for non bus / remote submix devices), 377 * true if the device is supported (both type and address) for bus / remote submix 378 * false otherwise 379 */ 380 bool supportsDevice(const sp<DeviceDescriptor> &device) const; 381 382 /** 383 * @brief supportsAllDevices 384 * @param devices to be checked against 385 * @return true if the device is weakly supported by type (e.g. for non bus / rsubmix devices), 386 * true if the device is supported (both type and address) for bus / remote submix 387 * false otherwise 388 */ 389 bool supportsAllDevices(const DeviceVector &devices) const; 390 391 /** 392 * @brief filterSupportedDevices takes a vector of devices and filters them according to the 393 * device supported by this output (the profile from which this output derives from) 394 * @param devices reference device vector to be filtered 395 * @return vector of devices filtered from the supported devices of this output (weakly or not 396 * depending on the device type) 397 */ 398 DeviceVector filterSupportedDevices(const DeviceVector &devices) const; 399 400 const sp<IOProfile> mProfile; // I/O profile this output derives from 401 audio_io_handle_t mIoHandle; // output handle 402 uint32_t mLatency; // 403 audio_output_flags_t mFlags; // 404 sp<SwAudioOutputDescriptor> mOutput1; // used by duplicated outputs: first output 405 sp<SwAudioOutputDescriptor> mOutput2; // used by duplicated outputs: second output 406 uint32_t mDirectOpenCount; // number of clients using this output (direct outputs only) 407 audio_session_t mDirectClientSession; // session id of the direct output client 408 }; 409 410 // Audio output driven by an input device directly. 411 class HwAudioOutputDescriptor: public AudioOutputDescriptor 412 { 413 public: 414 HwAudioOutputDescriptor(const sp<SourceClientDescriptor>& source, 415 AudioPolicyClientInterface *clientInterface); ~HwAudioOutputDescriptor()416 virtual ~HwAudioOutputDescriptor() {} 417 418 void dump(String8 *dst) const override; 419 420 virtual bool setVolume(float volumeDb, 421 VolumeSource volumeSource, const StreamTypeVector &streams, 422 const DeviceTypeSet& deviceTypes, 423 uint32_t delayMs, 424 bool force); 425 426 virtual void toAudioPortConfig(struct audio_port_config *dstConfig, 427 const struct audio_port_config *srcConfig = NULL) const; 428 virtual void toAudioPort(struct audio_port *port) const; 429 430 const sp<SourceClientDescriptor> mSource; 431 432 }; 433 434 class SwAudioOutputCollection : 435 public DefaultKeyedVector< audio_io_handle_t, sp<SwAudioOutputDescriptor> > 436 { 437 public: 438 bool isActive(VolumeSource volumeSource, uint32_t inPastMs = 0) const; 439 440 /** 441 * return whether any source contributing to VolumeSource is playing remotely, override 442 * to change the definition of 443 * local/remote playback, used for instance by notification manager to not make 444 * media players lose audio focus when not playing locally 445 * For the base implementation, "remotely" means playing during screen mirroring which 446 * uses an output for playback with a non-empty, non "0" address. 447 */ 448 bool isActiveRemotely(VolumeSource volumeSource, uint32_t inPastMs = 0) const; 449 450 /** 451 * return whether any source contributing to VolumeSource is playing, but not on a "remote" 452 * device. 453 * Override to change the definition of a local/remote playback. 454 * Used for instance by policy manager to alter the speaker playback ("speaker safe" behavior) 455 * when media plays or not locally. 456 * For the base implementation, "remotely" means playing during screen mirroring. 457 */ 458 bool isActiveLocally(VolumeSource volumeSource, uint32_t inPastMs = 0) const; 459 460 /** 461 * @brief isStrategyActiveOnSameModule checks if the given strategy is active (or was active 462 * in the past) on the given output and all the outputs belonging to the same HW Module 463 * the same module than the given output 464 * @param outputDesc to be considered 465 * @param ps product strategy to be checked upon activity status 466 * @param inPastMs if 0, check currently, otherwise, check in the past 467 * @param sysTime shall be set if request is done for the past activity. 468 * @return true if an output following the strategy is active on the same module than desc, 469 * false otherwise 470 */ 471 bool isStrategyActiveOnSameModule(product_strategy_t ps, 472 const sp<SwAudioOutputDescriptor>& desc, 473 uint32_t inPastMs = 0, nsecs_t sysTime = 0) const; 474 475 /** 476 * @brief clearSessionRoutesForDevice: when a device is disconnected, and if this device has 477 * been chosen as the preferred device by any client, the policy manager shall 478 * prevent from using this device any more by clearing all the session routes involving this 479 * device. 480 * In other words, the preferred device port id of these clients will be resetted to NONE. 481 * @param disconnectedDevice device to be disconnected 482 */ 483 void clearSessionRoutesForDevice(const sp<DeviceDescriptor> &disconnectedDevice); 484 485 /** 486 * returns the A2DP output handle if it is open or 0 otherwise 487 */ 488 audio_io_handle_t getA2dpOutput() const; 489 490 /** 491 * returns true if primary HAL supports A2DP Offload 492 */ 493 bool isA2dpOffloadedOnPrimary() const; 494 495 /** 496 * returns true if A2DP is supported (either via hardware offload or software encoding) 497 */ 498 bool isA2dpSupported() const; 499 500 sp<SwAudioOutputDescriptor> getOutputFromId(audio_port_handle_t id) const; 501 502 sp<SwAudioOutputDescriptor> getPrimaryOutput() const; 503 504 /** 505 * @brief isAnyOutputActive checks if any output is active (aka playing) except the one(s) that 506 * hold the volume source to be ignored 507 * @param volumeSourceToIgnore source not to be considered in the activity detection 508 * @return true if any output is active for any volume source except the one to be ignored 509 */ isAnyOutputActive(VolumeSource volumeSourceToIgnore)510 bool isAnyOutputActive(VolumeSource volumeSourceToIgnore) const 511 { 512 for (size_t i = 0; i < size(); i++) { 513 const sp<AudioOutputDescriptor> &outputDesc = valueAt(i); 514 if (outputDesc->isAnyActive(volumeSourceToIgnore)) { 515 return true; 516 } 517 } 518 return false; 519 } 520 521 audio_devices_t getSupportedDevices(audio_io_handle_t handle) const; 522 523 sp<SwAudioOutputDescriptor> getOutputForClient(audio_port_handle_t portId); 524 525 void dump(String8 *dst) const; 526 }; 527 528 class HwAudioOutputCollection : 529 public DefaultKeyedVector< audio_io_handle_t, sp<HwAudioOutputDescriptor> > 530 { 531 public: 532 bool isActive(VolumeSource volumeSource, uint32_t inPastMs = 0) const; 533 534 /** 535 * @brief isAnyOutputActive checks if any output is active (aka playing) except the one(s) that 536 * hold the volume source to be ignored 537 * @param volumeSourceToIgnore source not to be considered in the activity detection 538 * @return true if any output is active for any volume source except the one to be ignored 539 */ isAnyOutputActive(VolumeSource volumeSourceToIgnore)540 bool isAnyOutputActive(VolumeSource volumeSourceToIgnore) const 541 { 542 for (size_t i = 0; i < size(); i++) { 543 const sp<AudioOutputDescriptor> &outputDesc = valueAt(i); 544 if (outputDesc->isAnyActive(volumeSourceToIgnore)) { 545 return true; 546 } 547 } 548 return false; 549 } 550 551 void dump(String8 *dst) const; 552 }; 553 554 555 } // namespace android 556