AudioPolicyManager.h 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  1. /*
  2. * Copyright (C) 2009 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. #pragma once
  17. #include <atomic>
  18. #include <functional>
  19. #include <memory>
  20. #include <unordered_set>
  21. #include <stdint.h>
  22. #include <sys/types.h>
  23. #include <cutils/config_utils.h>
  24. #include <cutils/misc.h>
  25. #include <utils/Timers.h>
  26. #include <utils/Errors.h>
  27. #include <utils/KeyedVector.h>
  28. #include <utils/SortedVector.h>
  29. #include <media/AudioParameter.h>
  30. #include <media/AudioPolicy.h>
  31. #include <media/PatchBuilder.h>
  32. #include "AudioPolicyInterface.h"
  33. #include <AudioPolicyManagerInterface.h>
  34. #include <AudioPolicyManagerObserver.h>
  35. #include <AudioGain.h>
  36. #include <AudioPolicyConfig.h>
  37. #include <AudioPort.h>
  38. #include <AudioPatch.h>
  39. #include <AudioProfile.h>
  40. #include <DeviceDescriptor.h>
  41. #include <IOProfile.h>
  42. #include <HwModule.h>
  43. #include <AudioInputDescriptor.h>
  44. #include <AudioOutputDescriptor.h>
  45. #include <AudioPolicyMix.h>
  46. #include <EffectDescriptor.h>
  47. #include <SoundTriggerSession.h>
  48. #include "TypeConverter.h"
  49. namespace android {
  50. // ----------------------------------------------------------------------------
  51. // Attenuation applied to STRATEGY_SONIFICATION streams when a headset is connected: 6dB
  52. #define SONIFICATION_HEADSET_VOLUME_FACTOR_DB (-6)
  53. // Min volume for STRATEGY_SONIFICATION streams when limited by music volume: -36dB
  54. #define SONIFICATION_HEADSET_VOLUME_MIN_DB (-36)
  55. // Max volume difference on A2DP between playing media and STRATEGY_SONIFICATION streams: 12dB
  56. #define SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB (12)
  57. // Time in milliseconds during which we consider that music is still active after a music
  58. // track was stopped - see computeVolume()
  59. #define SONIFICATION_HEADSET_MUSIC_DELAY 5000
  60. // Time in milliseconds during witch some streams are muted while the audio path
  61. // is switched
  62. #define MUTE_TIME_MS 2000
  63. // multiplication factor applied to output latency when calculating a safe mute delay when
  64. // invalidating tracks
  65. #define LATENCY_MUTE_FACTOR 4
  66. #define NUM_TEST_OUTPUTS 5
  67. #define NUM_VOL_CURVE_KNEES 2
  68. // Default minimum length allowed for offloading a compressed track
  69. // Can be overridden by the audio.offload.min.duration.secs property
  70. #define OFFLOAD_DEFAULT_MIN_DURATION_SECS 60
  71. // ----------------------------------------------------------------------------
  72. // AudioPolicyManager implements audio policy manager behavior common to all platforms.
  73. // ----------------------------------------------------------------------------
  74. class AudioPolicyManager : public AudioPolicyInterface, public AudioPolicyManagerObserver
  75. {
  76. public:
  77. explicit AudioPolicyManager(AudioPolicyClientInterface *clientInterface);
  78. virtual ~AudioPolicyManager();
  79. // AudioPolicyInterface
  80. virtual status_t setDeviceConnectionState(audio_devices_t device,
  81. audio_policy_dev_state_t state,
  82. const char *device_address,
  83. const char *device_name,
  84. audio_format_t encodedFormat);
  85. virtual audio_policy_dev_state_t getDeviceConnectionState(audio_devices_t device,
  86. const char *device_address);
  87. virtual status_t handleDeviceConfigChange(audio_devices_t device,
  88. const char *device_address,
  89. const char *device_name,
  90. audio_format_t encodedFormat);
  91. virtual void setPhoneState(audio_mode_t state);
  92. virtual void setForceUse(audio_policy_force_use_t usage,
  93. audio_policy_forced_cfg_t config);
  94. virtual audio_policy_forced_cfg_t getForceUse(audio_policy_force_use_t usage);
  95. virtual void setSystemProperty(const char* property, const char* value);
  96. virtual status_t initCheck();
  97. virtual audio_io_handle_t getOutput(audio_stream_type_t stream);
  98. status_t getOutputForAttr(const audio_attributes_t *attr,
  99. audio_io_handle_t *output,
  100. audio_session_t session,
  101. audio_stream_type_t *stream,
  102. uid_t uid,
  103. const audio_config_t *config,
  104. audio_output_flags_t *flags,
  105. audio_port_handle_t *selectedDeviceId,
  106. audio_port_handle_t *portId,
  107. std::vector<audio_io_handle_t> *secondaryOutputs) override;
  108. virtual status_t startOutput(audio_port_handle_t portId);
  109. virtual status_t stopOutput(audio_port_handle_t portId);
  110. virtual void releaseOutput(audio_port_handle_t portId);
  111. virtual status_t getInputForAttr(const audio_attributes_t *attr,
  112. audio_io_handle_t *input,
  113. audio_unique_id_t riid,
  114. audio_session_t session,
  115. uid_t uid,
  116. const audio_config_base_t *config,
  117. audio_input_flags_t flags,
  118. audio_port_handle_t *selectedDeviceId,
  119. input_type_t *inputType,
  120. audio_port_handle_t *portId);
  121. // indicates to the audio policy manager that the input starts being used.
  122. virtual status_t startInput(audio_port_handle_t portId);
  123. // indicates to the audio policy manager that the input stops being used.
  124. virtual status_t stopInput(audio_port_handle_t portId);
  125. virtual void releaseInput(audio_port_handle_t portId);
  126. virtual void checkCloseInputs();
  127. /**
  128. * @brief initStreamVolume: even if the engine volume files provides min and max, keep this
  129. * api for compatibility reason.
  130. * AudioServer will get the min and max and may overwrite them if:
  131. * -using property (highest priority)
  132. * -not defined (-1 by convention), case when still using apm volume tables XML files
  133. * @param stream to be considered
  134. * @param indexMin to set
  135. * @param indexMax to set
  136. */
  137. virtual void initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax);
  138. virtual status_t setStreamVolumeIndex(audio_stream_type_t stream,
  139. int index,
  140. audio_devices_t device);
  141. virtual status_t getStreamVolumeIndex(audio_stream_type_t stream,
  142. int *index,
  143. audio_devices_t device);
  144. virtual status_t setVolumeIndexForAttributes(const audio_attributes_t &attr,
  145. int index,
  146. audio_devices_t device);
  147. virtual status_t getVolumeIndexForAttributes(const audio_attributes_t &attr,
  148. int &index,
  149. audio_devices_t device);
  150. virtual status_t getMaxVolumeIndexForAttributes(const audio_attributes_t &attr, int &index);
  151. virtual status_t getMinVolumeIndexForAttributes(const audio_attributes_t &attr, int &index);
  152. status_t setVolumeCurveIndex(int index,
  153. audio_devices_t device,
  154. IVolumeCurves &volumeCurves);
  155. status_t getVolumeIndex(const IVolumeCurves &curves, int &index,
  156. audio_devices_t device) const;
  157. // return the strategy corresponding to a given stream type
  158. virtual uint32_t getStrategyForStream(audio_stream_type_t stream)
  159. {
  160. return streamToStrategy(stream);
  161. }
  162. product_strategy_t streamToStrategy(audio_stream_type_t stream) const
  163. {
  164. auto attributes = mEngine->getAttributesForStreamType(stream);
  165. return mEngine->getProductStrategyForAttributes(attributes);
  166. }
  167. // return the enabled output devices for the given stream type
  168. virtual audio_devices_t getDevicesForStream(audio_stream_type_t stream);
  169. virtual audio_io_handle_t getOutputForEffect(const effect_descriptor_t *desc = NULL);
  170. virtual status_t registerEffect(const effect_descriptor_t *desc,
  171. audio_io_handle_t io,
  172. uint32_t strategy,
  173. int session,
  174. int id);
  175. virtual status_t unregisterEffect(int id);
  176. virtual status_t setEffectEnabled(int id, bool enabled);
  177. status_t moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io) override;
  178. virtual bool isStreamActive(audio_stream_type_t stream, uint32_t inPastMs = 0) const;
  179. // return whether a stream is playing remotely, override to change the definition of
  180. // local/remote playback, used for instance by notification manager to not make
  181. // media players lose audio focus when not playing locally
  182. // For the base implementation, "remotely" means playing during screen mirroring which
  183. // uses an output for playback with a non-empty, non "0" address.
  184. virtual bool isStreamActiveRemotely(audio_stream_type_t stream,
  185. uint32_t inPastMs = 0) const;
  186. virtual bool isSourceActive(audio_source_t source) const;
  187. // helpers for dump(int fd)
  188. void dumpManualSurroundFormats(String8 *dst) const;
  189. void dump(String8 *dst) const;
  190. status_t dump(int fd) override;
  191. status_t setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy) override;
  192. virtual bool isOffloadSupported(const audio_offload_info_t& offloadInfo);
  193. virtual bool isDirectOutputSupported(const audio_config_base_t& config,
  194. const audio_attributes_t& attributes);
  195. virtual status_t listAudioPorts(audio_port_role_t role,
  196. audio_port_type_t type,
  197. unsigned int *num_ports,
  198. struct audio_port *ports,
  199. unsigned int *generation);
  200. virtual status_t getAudioPort(struct audio_port *port);
  201. virtual status_t createAudioPatch(const struct audio_patch *patch,
  202. audio_patch_handle_t *handle,
  203. uid_t uid);
  204. virtual status_t releaseAudioPatch(audio_patch_handle_t handle,
  205. uid_t uid);
  206. virtual status_t listAudioPatches(unsigned int *num_patches,
  207. struct audio_patch *patches,
  208. unsigned int *generation);
  209. virtual status_t setAudioPortConfig(const struct audio_port_config *config);
  210. virtual void releaseResourcesForUid(uid_t uid);
  211. virtual status_t acquireSoundTriggerSession(audio_session_t *session,
  212. audio_io_handle_t *ioHandle,
  213. audio_devices_t *device);
  214. virtual status_t releaseSoundTriggerSession(audio_session_t session)
  215. {
  216. return mSoundTriggerSessions.releaseSession(session);
  217. }
  218. virtual status_t registerPolicyMixes(const Vector<AudioMix>& mixes);
  219. virtual status_t unregisterPolicyMixes(Vector<AudioMix> mixes);
  220. virtual status_t setUidDeviceAffinities(uid_t uid,
  221. const Vector<AudioDeviceTypeAddr>& devices);
  222. virtual status_t removeUidDeviceAffinities(uid_t uid);
  223. virtual status_t startAudioSource(const struct audio_port_config *source,
  224. const audio_attributes_t *attributes,
  225. audio_port_handle_t *portId,
  226. uid_t uid);
  227. virtual status_t stopAudioSource(audio_port_handle_t portId);
  228. virtual status_t setMasterMono(bool mono);
  229. virtual status_t getMasterMono(bool *mono);
  230. virtual float getStreamVolumeDB(
  231. audio_stream_type_t stream, int index, audio_devices_t device);
  232. virtual status_t getSurroundFormats(unsigned int *numSurroundFormats,
  233. audio_format_t *surroundFormats,
  234. bool *surroundFormatsEnabled,
  235. bool reported);
  236. virtual status_t setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled);
  237. virtual status_t getHwOffloadEncodingFormatsSupportedForA2DP(
  238. std::vector<audio_format_t> *formats);
  239. virtual void setAppState(uid_t uid, app_state_t state);
  240. virtual bool isHapticPlaybackSupported();
  241. virtual status_t listAudioProductStrategies(AudioProductStrategyVector &strategies)
  242. {
  243. return mEngine->listAudioProductStrategies(strategies);
  244. }
  245. virtual status_t getProductStrategyFromAudioAttributes(const AudioAttributes &aa,
  246. product_strategy_t &productStrategy)
  247. {
  248. productStrategy = mEngine->getProductStrategyForAttributes(aa.getAttributes());
  249. return productStrategy != PRODUCT_STRATEGY_NONE ? NO_ERROR : BAD_VALUE;
  250. }
  251. virtual status_t listAudioVolumeGroups(AudioVolumeGroupVector &groups)
  252. {
  253. return mEngine->listAudioVolumeGroups(groups);
  254. }
  255. virtual status_t getVolumeGroupFromAudioAttributes(const AudioAttributes &aa,
  256. volume_group_t &volumeGroup)
  257. {
  258. volumeGroup = mEngine->getVolumeGroupForAttributes(aa.getAttributes());
  259. return volumeGroup != VOLUME_GROUP_NONE ? NO_ERROR : BAD_VALUE;
  260. }
  261. protected:
  262. // A constructor that allows more fine-grained control over initialization process,
  263. // used in automatic tests.
  264. AudioPolicyManager(AudioPolicyClientInterface *clientInterface, bool forTesting);
  265. // These methods should be used when finer control over APM initialization
  266. // is needed, e.g. in tests. Must be used in conjunction with the constructor
  267. // that only performs fields initialization. The public constructor comprises
  268. // these steps in the following sequence:
  269. // - field initializing constructor;
  270. // - loadConfig;
  271. // - initialize.
  272. AudioPolicyConfig& getConfig() { return mConfig; }
  273. void loadConfig();
  274. status_t initialize();
  275. // From AudioPolicyManagerObserver
  276. virtual const AudioPatchCollection &getAudioPatches() const
  277. {
  278. return mAudioPatches;
  279. }
  280. virtual const SoundTriggerSessionCollection &getSoundTriggerSessionCollection() const
  281. {
  282. return mSoundTriggerSessions;
  283. }
  284. virtual const AudioPolicyMixCollection &getAudioPolicyMixCollection() const
  285. {
  286. return mPolicyMixes;
  287. }
  288. virtual const SwAudioOutputCollection &getOutputs() const
  289. {
  290. return mOutputs;
  291. }
  292. virtual const AudioInputCollection &getInputs() const
  293. {
  294. return mInputs;
  295. }
  296. virtual const DeviceVector getAvailableOutputDevices() const
  297. {
  298. return mAvailableOutputDevices.filterForEngine();
  299. }
  300. virtual const DeviceVector getAvailableInputDevices() const
  301. {
  302. // legacy and non-legacy remote-submix are managed by the engine, do not filter
  303. return mAvailableInputDevices;
  304. }
  305. virtual const sp<DeviceDescriptor> &getDefaultOutputDevice() const
  306. {
  307. return mDefaultOutputDevice;
  308. }
  309. std::vector<volume_group_t> getVolumeGroups() const
  310. {
  311. return mEngine->getVolumeGroups();
  312. }
  313. VolumeSource toVolumeSource(volume_group_t volumeGroup) const
  314. {
  315. return static_cast<VolumeSource>(volumeGroup);
  316. }
  317. VolumeSource toVolumeSource(const audio_attributes_t &attributes) const
  318. {
  319. return toVolumeSource(mEngine->getVolumeGroupForAttributes(attributes));
  320. }
  321. VolumeSource toVolumeSource(audio_stream_type_t stream) const
  322. {
  323. return toVolumeSource(mEngine->getVolumeGroupForStreamType(stream));
  324. }
  325. IVolumeCurves &getVolumeCurves(VolumeSource volumeSource)
  326. {
  327. auto *curves = mEngine->getVolumeCurvesForVolumeGroup(
  328. static_cast<volume_group_t>(volumeSource));
  329. ALOG_ASSERT(curves != nullptr, "No curves for volume source %d", volumeSource);
  330. return *curves;
  331. }
  332. IVolumeCurves &getVolumeCurves(const audio_attributes_t &attr)
  333. {
  334. auto *curves = mEngine->getVolumeCurvesForAttributes(attr);
  335. ALOG_ASSERT(curves != nullptr, "No curves for attributes %s", toString(attr).c_str());
  336. return *curves;
  337. }
  338. IVolumeCurves &getVolumeCurves(audio_stream_type_t stream)
  339. {
  340. auto *curves = mEngine->getVolumeCurvesForStreamType(stream);
  341. ALOG_ASSERT(curves != nullptr, "No curves for stream %s", toString(stream).c_str());
  342. return *curves;
  343. }
  344. void addOutput(audio_io_handle_t output, const sp<SwAudioOutputDescriptor>& outputDesc);
  345. void removeOutput(audio_io_handle_t output);
  346. void addInput(audio_io_handle_t input, const sp<AudioInputDescriptor>& inputDesc);
  347. // change the route of the specified output. Returns the number of ms we have slept to
  348. // allow new routing to take effect in certain cases.
  349. uint32_t setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
  350. const DeviceVector &device,
  351. bool force = false,
  352. int delayMs = 0,
  353. audio_patch_handle_t *patchHandle = NULL,
  354. bool requiresMuteCheck = true);
  355. status_t resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
  356. int delayMs = 0,
  357. audio_patch_handle_t *patchHandle = NULL);
  358. status_t setInputDevice(audio_io_handle_t input,
  359. const sp<DeviceDescriptor> &device,
  360. bool force = false,
  361. audio_patch_handle_t *patchHandle = NULL);
  362. status_t resetInputDevice(audio_io_handle_t input,
  363. audio_patch_handle_t *patchHandle = NULL);
  364. // compute the actual volume for a given stream according to the requested index and a particular
  365. // device
  366. virtual float computeVolume(IVolumeCurves &curves,
  367. VolumeSource volumeSource,
  368. int index,
  369. audio_devices_t device);
  370. // rescale volume index from srcStream within range of dstStream
  371. int rescaleVolumeIndex(int srcIndex,
  372. VolumeSource fromVolumeSource,
  373. VolumeSource toVolumeSource);
  374. // check that volume change is permitted, compute and send new volume to audio hardware
  375. virtual status_t checkAndSetVolume(IVolumeCurves &curves,
  376. VolumeSource volumeSource, int index,
  377. const sp<AudioOutputDescriptor>& outputDesc,
  378. audio_devices_t device,
  379. int delayMs = 0, bool force = false);
  380. // apply all stream volumes to the specified output and device
  381. void applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
  382. audio_devices_t device, int delayMs = 0, bool force = false);
  383. /**
  384. * @brief setStrategyMute Mute or unmute all active clients on the considered output
  385. * following the given strategy.
  386. * @param strategy to be considered
  387. * @param on true for mute, false for unmute
  388. * @param outputDesc to be considered
  389. * @param delayMs
  390. * @param device
  391. */
  392. void setStrategyMute(product_strategy_t strategy,
  393. bool on,
  394. const sp<AudioOutputDescriptor>& outputDesc,
  395. int delayMs = 0,
  396. audio_devices_t device = AUDIO_DEVICE_NONE);
  397. /**
  398. * @brief setVolumeSourceMute Mute or unmute the volume source on the specified output
  399. * @param volumeSource to be muted/unmute (may host legacy streams or by extension set of
  400. * audio attributes)
  401. * @param on true to mute, false to umute
  402. * @param outputDesc on which the client following the volume group shall be muted/umuted
  403. * @param delayMs
  404. * @param device
  405. */
  406. void setVolumeSourceMute(VolumeSource volumeSource,
  407. bool on,
  408. const sp<AudioOutputDescriptor>& outputDesc,
  409. int delayMs = 0,
  410. audio_devices_t device = AUDIO_DEVICE_NONE);
  411. audio_mode_t getPhoneState();
  412. // true if device is in a telephony or VoIP call
  413. virtual bool isInCall();
  414. // true if given state represents a device in a telephony or VoIP call
  415. virtual bool isStateInCall(int state);
  416. // when a device is connected, checks if an open output can be routed
  417. // to this device. If none is open, tries to open one of the available outputs.
  418. // Returns an output suitable to this device or 0.
  419. // when a device is disconnected, checks if an output is not used any more and
  420. // returns its handle if any.
  421. // transfers the audio tracks and effects from one output thread to another accordingly.
  422. status_t checkOutputsForDevice(const sp<DeviceDescriptor>& device,
  423. audio_policy_dev_state_t state,
  424. SortedVector<audio_io_handle_t>& outputs);
  425. status_t checkInputsForDevice(const sp<DeviceDescriptor>& device,
  426. audio_policy_dev_state_t state);
  427. // close an output and its companion duplicating output.
  428. void closeOutput(audio_io_handle_t output);
  429. // close an input.
  430. void closeInput(audio_io_handle_t input);
  431. // runs all the checks required for accomodating changes in devices and outputs
  432. // if 'onOutputsChecked' callback is provided, it is executed after the outputs
  433. // check via 'checkOutputForAllStrategies'. If the callback returns 'true',
  434. // A2DP suspend status is rechecked.
  435. void checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked = nullptr);
  436. /**
  437. * @brief checkOutputForAttributes checks and if necessary changes outputs used for the
  438. * given audio attributes.
  439. * must be called every time a condition that affects the output choice for a given
  440. * attributes changes: connected device, phone state, force use...
  441. * Must be called before updateDevicesAndOutputs()
  442. * @param attr to be considered
  443. */
  444. void checkOutputForAttributes(const audio_attributes_t &attr);
  445. bool followsSameRouting(const audio_attributes_t &lAttr,
  446. const audio_attributes_t &rAttr) const;
  447. /**
  448. * @brief checkOutputForAllStrategies Same as @see checkOutputForAttributes()
  449. * but for a all product strategies in order of priority
  450. */
  451. void checkOutputForAllStrategies();
  452. // Same as checkOutputForStrategy but for secondary outputs. Make sure if a secondary
  453. // output condition changes, the track is properly rerouted
  454. void checkSecondaryOutputs();
  455. // manages A2DP output suspend/restore according to phone state and BT SCO usage
  456. void checkA2dpSuspend();
  457. // selects the most appropriate device on output for current state
  458. // must be called every time a condition that affects the device choice for a given output is
  459. // changed: connected device, phone state, force use, output start, output stop..
  460. // see getDeviceForStrategy() for the use of fromCache parameter
  461. DeviceVector getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
  462. bool fromCache);
  463. /**
  464. * @brief updateDevicesAndOutputs: updates cache of devices of the engine
  465. * must be called every time a condition that affects the device choice is changed:
  466. * connected device, phone state, force use...
  467. * cached values are used by getOutputDevicesForStream()/getDevicesForAttributes if
  468. * parameter fromCache is true.
  469. * Must be called after checkOutputForAllStrategies()
  470. */
  471. void updateDevicesAndOutputs();
  472. // selects the most appropriate device on input for current state
  473. sp<DeviceDescriptor> getNewInputDevice(const sp<AudioInputDescriptor>& inputDesc);
  474. virtual uint32_t getMaxEffectsCpuLoad()
  475. {
  476. return mEffects.getMaxEffectsCpuLoad();
  477. }
  478. virtual uint32_t getMaxEffectsMemory()
  479. {
  480. return mEffects.getMaxEffectsMemory();
  481. }
  482. SortedVector<audio_io_handle_t> getOutputsForDevices(
  483. const DeviceVector &devices, const SwAudioOutputCollection& openOutputs);
  484. /**
  485. * @brief checkDeviceMuteStrategies mute/unmute strategies
  486. * using an incompatible device combination.
  487. * if muting, wait for the audio in pcm buffer to be drained before proceeding
  488. * if unmuting, unmute only after the specified delay
  489. * @param outputDesc
  490. * @param prevDevice
  491. * @param delayMs
  492. * @return the number of ms waited
  493. */
  494. virtual uint32_t checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
  495. const DeviceVector &prevDevices,
  496. uint32_t delayMs);
  497. audio_io_handle_t selectOutput(const SortedVector<audio_io_handle_t>& outputs,
  498. audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE,
  499. audio_format_t format = AUDIO_FORMAT_INVALID,
  500. audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE,
  501. uint32_t samplingRate = 0);
  502. // samplingRate, format, channelMask are in/out and so may be modified
  503. sp<IOProfile> getInputProfile(const sp<DeviceDescriptor> & device,
  504. uint32_t& samplingRate,
  505. audio_format_t& format,
  506. audio_channel_mask_t& channelMask,
  507. audio_input_flags_t flags);
  508. /**
  509. * @brief getProfileForOutput
  510. * @param devices vector of descriptors, may be empty if ignoring the device is required
  511. * @param samplingRate
  512. * @param format
  513. * @param channelMask
  514. * @param flags
  515. * @param directOnly
  516. * @return IOProfile to be used if found, nullptr otherwise
  517. */
  518. sp<IOProfile> getProfileForOutput(const DeviceVector &devices,
  519. uint32_t samplingRate,
  520. audio_format_t format,
  521. audio_channel_mask_t channelMask,
  522. audio_output_flags_t flags,
  523. bool directOnly);
  524. audio_io_handle_t selectOutputForMusicEffects();
  525. virtual status_t addAudioPatch(audio_patch_handle_t handle, const sp<AudioPatch>& patch)
  526. {
  527. return mAudioPatches.addAudioPatch(handle, patch);
  528. }
  529. virtual status_t removeAudioPatch(audio_patch_handle_t handle)
  530. {
  531. return mAudioPatches.removeAudioPatch(handle);
  532. }
  533. bool isPrimaryModule(const sp<HwModule> &module) const
  534. {
  535. if (module == 0 || !hasPrimaryOutput()) {
  536. return false;
  537. }
  538. return module->getHandle() == mPrimaryOutput->getModuleHandle();
  539. }
  540. DeviceVector availablePrimaryOutputDevices() const
  541. {
  542. if (!hasPrimaryOutput()) {
  543. return DeviceVector();
  544. }
  545. return mAvailableOutputDevices.filter(mPrimaryOutput->supportedDevices());
  546. }
  547. DeviceVector availablePrimaryModuleInputDevices() const
  548. {
  549. if (!hasPrimaryOutput()) {
  550. return DeviceVector();
  551. }
  552. return mAvailableInputDevices.getDevicesFromHwModule(
  553. mPrimaryOutput->getModuleHandle());
  554. }
  555. /**
  556. * @brief getFirstDeviceId of the Device Vector
  557. * @return if the collection is not empty, it returns the first device Id,
  558. * otherwise AUDIO_PORT_HANDLE_NONE
  559. */
  560. audio_port_handle_t getFirstDeviceId(const DeviceVector &devices) const
  561. {
  562. return (devices.size() > 0) ? devices.itemAt(0)->getId() : AUDIO_PORT_HANDLE_NONE;
  563. }
  564. String8 getFirstDeviceAddress(const DeviceVector &devices) const
  565. {
  566. return (devices.size() > 0) ? devices.itemAt(0)->address() : String8("");
  567. }
  568. uint32_t updateCallRouting(const DeviceVector &rxDevices, uint32_t delayMs = 0);
  569. sp<AudioPatch> createTelephonyPatch(bool isRx, const sp<DeviceDescriptor> &device,
  570. uint32_t delayMs);
  571. sp<DeviceDescriptor> findDevice(
  572. const DeviceVector& devices, audio_devices_t device) const;
  573. audio_devices_t getModuleDeviceTypes(
  574. const DeviceVector& devices, const char *moduleId) const;
  575. bool isDeviceOfModule(const sp<DeviceDescriptor>& devDesc, const char *moduleId) const;
  576. status_t startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
  577. const sp<TrackClientDescriptor>& client,
  578. uint32_t *delayMs);
  579. status_t stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
  580. const sp<TrackClientDescriptor>& client);
  581. void clearAudioPatches(uid_t uid);
  582. void clearSessionRoutes(uid_t uid);
  583. /**
  584. * @brief checkStrategyRoute: when an output is beeing rerouted, reconsider each output
  585. * that may host a strategy playing on the considered output.
  586. * @param ps product strategy that initiated the rerouting
  587. * @param ouptutToSkip output that initiated the rerouting
  588. */
  589. void checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip);
  590. status_t hasPrimaryOutput() const { return mPrimaryOutput != 0; }
  591. status_t connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc);
  592. status_t disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc);
  593. sp<SourceClientDescriptor> getSourceForAttributesOnOutput(audio_io_handle_t output,
  594. const audio_attributes_t &attr);
  595. void cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc);
  596. void clearAudioSources(uid_t uid);
  597. static bool streamsMatchForvolume(audio_stream_type_t stream1,
  598. audio_stream_type_t stream2);
  599. void closeActiveClients(const sp<AudioInputDescriptor>& input);
  600. void closeClient(audio_port_handle_t portId);
  601. const uid_t mUidCached; // AID_AUDIOSERVER
  602. AudioPolicyClientInterface *mpClientInterface; // audio policy client interface
  603. sp<SwAudioOutputDescriptor> mPrimaryOutput; // primary output descriptor
  604. // list of descriptors for outputs currently opened
  605. SwAudioOutputCollection mOutputs;
  606. // copy of mOutputs before setDeviceConnectionState() opens new outputs
  607. // reset to mOutputs when updateDevicesAndOutputs() is called.
  608. SwAudioOutputCollection mPreviousOutputs;
  609. AudioInputCollection mInputs; // list of input descriptors
  610. DeviceVector mAvailableOutputDevices; // all available output devices
  611. DeviceVector mAvailableInputDevices; // all available input devices
  612. bool mLimitRingtoneVolume; // limit ringtone volume to music volume if headset connected
  613. float mLastVoiceVolume; // last voice volume value sent to audio HAL
  614. bool mA2dpSuspended; // true if A2DP output is suspended
  615. EffectDescriptorCollection mEffects; // list of registered audio effects
  616. sp<DeviceDescriptor> mDefaultOutputDevice; // output device selected by default at boot time
  617. HwModuleCollection mHwModules; // contains only modules that have been loaded successfully
  618. HwModuleCollection mHwModulesAll; // normally not needed, used during construction and for
  619. // dumps
  620. AudioPolicyConfig mConfig;
  621. std::atomic<uint32_t> mAudioPortGeneration;
  622. AudioPatchCollection mAudioPatches;
  623. SoundTriggerSessionCollection mSoundTriggerSessions;
  624. sp<AudioPatch> mCallTxPatch;
  625. sp<AudioPatch> mCallRxPatch;
  626. HwAudioOutputCollection mHwOutputs;
  627. SourceClientCollection mAudioSources;
  628. // for supporting "beacon" streams, i.e. streams that only play on speaker, and never
  629. // when something other than STREAM_TTS (a.k.a. "Transmitted Through Speaker") is playing
  630. enum {
  631. STARTING_OUTPUT,
  632. STARTING_BEACON,
  633. STOPPING_OUTPUT,
  634. STOPPING_BEACON
  635. };
  636. uint32_t mBeaconMuteRefCount; // ref count for stream that would mute beacon
  637. uint32_t mBeaconPlayingRefCount;// ref count for the playing beacon streams
  638. bool mBeaconMuted; // has STREAM_TTS been muted
  639. bool mTtsOutputAvailable; // true if a dedicated output for TTS stream is available
  640. bool mMasterMono; // true if we wish to force all outputs to mono
  641. AudioPolicyMixCollection mPolicyMixes; // list of registered mixes
  642. audio_io_handle_t mMusicEffectOutput; // output selected for music effects
  643. uint32_t nextAudioPortGeneration();
  644. // Audio Policy Engine Interface.
  645. AudioPolicyManagerInterface *mEngine;
  646. // Surround formats that are enabled manually. Taken into account when
  647. // "encoded surround" is forced into "manual" mode.
  648. std::unordered_set<audio_format_t> mManualSurroundFormats;
  649. std::unordered_map<uid_t, audio_flags_mask_t> mAllowedCapturePolicies;
  650. private:
  651. // Add or remove AC3 DTS encodings based on user preferences.
  652. void modifySurroundFormats(const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr);
  653. void modifySurroundChannelMasks(ChannelsVector *channelMasksPtr);
  654. // Support for Multi-Stream Decoder (MSD) module
  655. sp<DeviceDescriptor> getMsdAudioInDevice() const;
  656. DeviceVector getMsdAudioOutDevices() const;
  657. const AudioPatchCollection getMsdPatches() const;
  658. status_t getBestMsdAudioProfileFor(const sp<DeviceDescriptor> &outputDevice,
  659. bool hwAvSync,
  660. audio_port_config *sourceConfig,
  661. audio_port_config *sinkConfig) const;
  662. PatchBuilder buildMsdPatch(const sp<DeviceDescriptor> &outputDevice) const;
  663. status_t setMsdPatch(const sp<DeviceDescriptor> &outputDevice = nullptr);
  664. // If any, resolve any "dynamic" fields of an Audio Profiles collection
  665. void updateAudioProfiles(const sp<DeviceDescriptor>& devDesc, audio_io_handle_t ioHandle,
  666. AudioProfileVector &profiles);
  667. // Notify the policy client of any change of device state with AUDIO_IO_HANDLE_NONE,
  668. // so that the client interprets it as global to audio hardware interfaces.
  669. // It can give a chance to HAL implementer to retrieve dynamic capabilities associated
  670. // to this device for example.
  671. // TODO avoid opening stream to retrieve capabilities of a profile.
  672. void broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
  673. audio_policy_dev_state_t state);
  674. // updates device caching and output for streams that can influence the
  675. // routing of notifications
  676. void handleNotificationRoutingForStream(audio_stream_type_t stream);
  677. uint32_t curAudioPortGeneration() const { return mAudioPortGeneration; }
  678. // internal method, get audio_attributes_t from either a source audio_attributes_t
  679. // or audio_stream_type_t, respectively.
  680. status_t getAudioAttributes(audio_attributes_t *dstAttr,
  681. const audio_attributes_t *srcAttr,
  682. audio_stream_type_t srcStream);
  683. // internal method, called by getOutputForAttr() and connectAudioSource.
  684. status_t getOutputForAttrInt(audio_attributes_t *resultAttr,
  685. audio_io_handle_t *output,
  686. audio_session_t session,
  687. const audio_attributes_t *attr,
  688. audio_stream_type_t *stream,
  689. uid_t uid,
  690. const audio_config_t *config,
  691. audio_output_flags_t *flags,
  692. audio_port_handle_t *selectedDeviceId,
  693. bool *isRequestedDeviceForExclusiveUse,
  694. std::vector<sp<SwAudioOutputDescriptor>> *secondaryDescs);
  695. // internal method to return the output handle for the given device and format
  696. audio_io_handle_t getOutputForDevices(
  697. const DeviceVector &devices,
  698. audio_session_t session,
  699. audio_stream_type_t stream,
  700. const audio_config_t *config,
  701. audio_output_flags_t *flags,
  702. bool forceMutingHaptic = false);
  703. /**
  704. * @brief getInputForDevice selects an input handle for a given input device and
  705. * requester context
  706. * @param device to be used by requester, selected by policy mix rules or engine
  707. * @param session requester session id
  708. * @param uid requester uid
  709. * @param attributes requester audio attributes (e.g. input source and tags matter)
  710. * @param config requester audio configuration (e.g. sample rate, format, channel mask).
  711. * @param flags requester input flags
  712. * @param policyMix may be null, policy rules to be followed by the requester
  713. * @return input io handle aka unique input identifier selected for this device.
  714. */
  715. audio_io_handle_t getInputForDevice(const sp<DeviceDescriptor> &device,
  716. audio_session_t session,
  717. const audio_attributes_t &attributes,
  718. const audio_config_base_t *config,
  719. audio_input_flags_t flags,
  720. const sp<AudioPolicyMix> &policyMix);
  721. // event is one of STARTING_OUTPUT, STARTING_BEACON, STOPPING_OUTPUT, STOPPING_BEACON
  722. // returns 0 if no mute/unmute event happened, the largest latency of the device where
  723. // the mute/unmute happened
  724. uint32_t handleEventForBeacon(int event);
  725. uint32_t setBeaconMute(bool mute);
  726. bool isValidAttributes(const audio_attributes_t *paa);
  727. // Called by setDeviceConnectionState().
  728. status_t setDeviceConnectionStateInt(audio_devices_t deviceType,
  729. audio_policy_dev_state_t state,
  730. const char *device_address,
  731. const char *device_name,
  732. audio_format_t encodedFormat);
  733. void setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
  734. audio_policy_dev_state_t state);
  735. void updateMono(audio_io_handle_t output) {
  736. AudioParameter param;
  737. param.addInt(String8(AudioParameter::keyMonoOutput), (int)mMasterMono);
  738. mpClientInterface->setParameters(output, param.toString());
  739. }
  740. status_t installPatch(const char *caller,
  741. audio_patch_handle_t *patchHandle,
  742. AudioIODescriptorInterface *ioDescriptor,
  743. const struct audio_patch *patch,
  744. int delayMs);
  745. status_t installPatch(const char *caller,
  746. ssize_t index,
  747. audio_patch_handle_t *patchHandle,
  748. const struct audio_patch *patch,
  749. int delayMs,
  750. uid_t uid,
  751. sp<AudioPatch> *patchDescPtr);
  752. void cleanUpEffectsForIo(audio_io_handle_t io);
  753. };
  754. };