GoogleGit

blob: 5774db2a3813613efba86745a95f9bc72ff0a28d [file] [log] [blame]
  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. #define LOG_TAG "AudioPolicyManagerBase"
  17. //#define LOG_NDEBUG 0
  18. //#define VERY_VERBOSE_LOGGING
  19. #ifdef VERY_VERBOSE_LOGGING
  20. #define ALOGVV ALOGV
  21. #else
  22. #define ALOGVV(a...) do { } while(0)
  23. #endif
  24. // A device mask for all audio input devices that are considered "virtual" when evaluating
  25. // active inputs in getActiveInput()
  26. #define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL AUDIO_DEVICE_IN_REMOTE_SUBMIX
  27. // A device mask for all audio output devices that are considered "remote" when evaluating
  28. // active output devices in isStreamActiveRemotely()
  29. #define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
  30. #include <inttypes.h>
  31. #include <math.h>
  32. #include <cutils/properties.h>
  33. #include <utils/Log.h>
  34. #include <utils/Timers.h>
  35. #include <hardware/audio.h>
  36. #include <hardware/audio_effect.h>
  37. #include <hardware_legacy/audio_policy_conf.h>
  38. #include <hardware_legacy/AudioPolicyManagerBase.h>
  39. namespace android_audio_legacy {
  40. // ----------------------------------------------------------------------------
  41. // AudioPolicyInterface implementation
  42. // ----------------------------------------------------------------------------
  43. status_t AudioPolicyManagerBase::setDeviceConnectionState(audio_devices_t device,
  44. AudioSystem::device_connection_state state,
  45. const char *device_address)
  46. {
  47. // device_address can be NULL and should be handled as an empty string in this case,
  48. // and it is not checked by AudioPolicyInterfaceImpl.cpp
  49. if (device_address == NULL) {
  50. device_address = "";
  51. }
  52. ALOGV("setDeviceConnectionState() device: 0x%X, state %d, address %s", device, state, device_address);
  53. // connect/disconnect only 1 device at a time
  54. if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
  55. if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
  56. ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
  57. return BAD_VALUE;
  58. }
  59. // handle output devices
  60. if (audio_is_output_device(device)) {
  61. SortedVector <audio_io_handle_t> outputs;
  62. if (!mHasA2dp && audio_is_a2dp_out_device(device)) {
  63. ALOGE("setDeviceConnectionState() invalid A2DP device: %x", device);
  64. return BAD_VALUE;
  65. }
  66. if (!mHasUsb && audio_is_usb_out_device(device)) {
  67. ALOGE("setDeviceConnectionState() invalid USB audio device: %x", device);
  68. return BAD_VALUE;
  69. }
  70. if (!mHasRemoteSubmix && audio_is_remote_submix_device((audio_devices_t)device)) {
  71. ALOGE("setDeviceConnectionState() invalid remote submix audio device: %x", device);
  72. return BAD_VALUE;
  73. }
  74. // save a copy of the opened output descriptors before any output is opened or closed
  75. // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
  76. mPreviousOutputs = mOutputs;
  77. String8 paramStr;
  78. switch (state)
  79. {
  80. // handle output device connection
  81. case AudioSystem::DEVICE_STATE_AVAILABLE:
  82. if (mAvailableOutputDevices & device) {
  83. ALOGW("setDeviceConnectionState() device already connected: %x", device);
  84. return INVALID_OPERATION;
  85. }
  86. ALOGV("setDeviceConnectionState() connecting device %x", device);
  87. if (mHasA2dp && audio_is_a2dp_out_device(device)) {
  88. // handle A2DP device connection
  89. AudioParameter param;
  90. param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
  91. paramStr = param.toString();
  92. } else if (mHasUsb && audio_is_usb_out_device(device)) {
  93. // handle USB device connection
  94. paramStr = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
  95. }
  96. if (checkOutputsForDevice(device, state, outputs, paramStr) != NO_ERROR) {
  97. return INVALID_OPERATION;
  98. }
  99. ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
  100. outputs.size());
  101. // register new device as available
  102. mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
  103. if (mHasA2dp && audio_is_a2dp_out_device(device)) {
  104. // handle A2DP device connection
  105. mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
  106. mA2dpSuspended = false;
  107. } else if (audio_is_bluetooth_sco_device(device)) {
  108. // handle SCO device connection
  109. mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
  110. } else if (mHasUsb && audio_is_usb_out_device(device)) {
  111. // handle USB device connection
  112. mUsbOutCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
  113. }
  114. break;
  115. // handle output device disconnection
  116. case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
  117. if (!(mAvailableOutputDevices & device)) {
  118. ALOGW("setDeviceConnectionState() device not connected: %x", device);
  119. return INVALID_OPERATION;
  120. }
  121. ALOGV("setDeviceConnectionState() disconnecting device %x", device);
  122. // remove device from available output devices
  123. mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
  124. checkOutputsForDevice(device, state, outputs, paramStr);
  125. if (mHasA2dp && audio_is_a2dp_out_device(device)) {
  126. // handle A2DP device disconnection
  127. mA2dpDeviceAddress = "";
  128. mA2dpSuspended = false;
  129. } else if (audio_is_bluetooth_sco_device(device)) {
  130. // handle SCO device disconnection
  131. mScoDeviceAddress = "";
  132. } else if (mHasUsb && audio_is_usb_out_device(device)) {
  133. // handle USB device disconnection
  134. mUsbOutCardAndDevice = "";
  135. }
  136. // not currently handling multiple simultaneous submixes: ignoring remote submix
  137. // case and address
  138. } break;
  139. default:
  140. ALOGE("setDeviceConnectionState() invalid state: %x", state);
  141. return BAD_VALUE;
  142. }
  143. checkA2dpSuspend();
  144. checkOutputForAllStrategies();
  145. // outputs must be closed after checkOutputForAllStrategies() is executed
  146. if (!outputs.isEmpty()) {
  147. for (size_t i = 0; i < outputs.size(); i++) {
  148. AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
  149. // close unused outputs after device disconnection or direct outputs that have been
  150. // opened by checkOutputsForDevice() to query dynamic parameters
  151. if ((state == AudioSystem::DEVICE_STATE_UNAVAILABLE) ||
  152. (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
  153. (desc->mDirectOpenCount == 0))) {
  154. closeOutput(outputs[i]);
  155. }
  156. }
  157. }
  158. updateDevicesAndOutputs();
  159. for (size_t i = 0; i < mOutputs.size(); i++) {
  160. // do not force device change on duplicated output because if device is 0, it will
  161. // also force a device 0 for the two outputs it is duplicated to which may override
  162. // a valid device selection on those outputs.
  163. setOutputDevice(mOutputs.keyAt(i),
  164. getNewDevice(mOutputs.keyAt(i), true /*fromCache*/),
  165. !mOutputs.valueAt(i)->isDuplicated(),
  166. 0);
  167. }
  168. return NO_ERROR;
  169. } // end if is output device
  170. // handle input devices
  171. if (audio_is_input_device(device)) {
  172. SortedVector <audio_io_handle_t> inputs;
  173. String8 paramStr;
  174. switch (state)
  175. {
  176. // handle input device connection
  177. case AudioSystem::DEVICE_STATE_AVAILABLE: {
  178. if (mAvailableInputDevices & device) {
  179. ALOGW("setDeviceConnectionState() device already connected: %d", device);
  180. return INVALID_OPERATION;
  181. }
  182. if (mHasUsb && audio_is_usb_in_device(device)) {
  183. // handle USB device connection
  184. paramStr = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
  185. } else if (mHasA2dp && audio_is_a2dp_in_device(device)) {
  186. // handle A2DP device connection
  187. AudioParameter param;
  188. param.add(String8(AUDIO_PARAMETER_A2DP_SOURCE_ADDRESS), String8(device_address));
  189. paramStr = param.toString();
  190. }
  191. if (checkInputsForDevice(device, state, inputs, paramStr) != NO_ERROR) {
  192. return INVALID_OPERATION;
  193. }
  194. mAvailableInputDevices = mAvailableInputDevices | (device & ~AUDIO_DEVICE_BIT_IN);
  195. }
  196. break;
  197. // handle input device disconnection
  198. case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
  199. if (!(mAvailableInputDevices & device)) {
  200. ALOGW("setDeviceConnectionState() device not connected: %d", device);
  201. return INVALID_OPERATION;
  202. }
  203. checkInputsForDevice(device, state, inputs, paramStr);
  204. mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
  205. } break;
  206. default:
  207. ALOGE("setDeviceConnectionState() invalid state: %x", state);
  208. return BAD_VALUE;
  209. }
  210. closeAllInputs();
  211. return NO_ERROR;
  212. } // end if is input device
  213. ALOGW("setDeviceConnectionState() invalid device: %x", device);
  214. return BAD_VALUE;
  215. }
  216. AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(audio_devices_t device,
  217. const char *device_address)
  218. {
  219. // similar to setDeviceConnectionState
  220. if (device_address == NULL) {
  221. device_address = "";
  222. }
  223. AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
  224. String8 address = String8(device_address);
  225. if (audio_is_output_device(device)) {
  226. if (device & mAvailableOutputDevices) {
  227. if (audio_is_a2dp_out_device(device) &&
  228. (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) {
  229. return state;
  230. }
  231. if (audio_is_bluetooth_sco_device(device) &&
  232. address != "" && mScoDeviceAddress != address) {
  233. return state;
  234. }
  235. if (audio_is_usb_out_device(device) &&
  236. (!mHasUsb || (address != "" && mUsbOutCardAndDevice != address))) {
  237. ALOGE("getDeviceConnectionState() invalid device: %x", device);
  238. return state;
  239. }
  240. if (audio_is_remote_submix_device((audio_devices_t)device) && !mHasRemoteSubmix) {
  241. return state;
  242. }
  243. state = AudioSystem::DEVICE_STATE_AVAILABLE;
  244. }
  245. } else if (audio_is_input_device(device)) {
  246. if (device & mAvailableInputDevices) {
  247. state = AudioSystem::DEVICE_STATE_AVAILABLE;
  248. }
  249. }
  250. return state;
  251. }
  252. void AudioPolicyManagerBase::setPhoneState(int state)
  253. {
  254. ALOGV("setPhoneState() state %d", state);
  255. audio_devices_t newDevice = AUDIO_DEVICE_NONE;
  256. if (state < 0 || state >= AudioSystem::NUM_MODES) {
  257. ALOGW("setPhoneState() invalid state %d", state);
  258. return;
  259. }
  260. if (state == mPhoneState ) {
  261. ALOGW("setPhoneState() setting same state %d", state);
  262. return;
  263. }
  264. // if leaving call state, handle special case of active streams
  265. // pertaining to sonification strategy see handleIncallSonification()
  266. if (isInCall()) {
  267. ALOGV("setPhoneState() in call state management: new state is %d", state);
  268. for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
  269. handleIncallSonification(stream, false, true);
  270. }
  271. }
  272. // store previous phone state for management of sonification strategy below
  273. int oldState = mPhoneState;
  274. mPhoneState = state;
  275. bool force = false;
  276. // are we entering or starting a call
  277. if (!isStateInCall(oldState) && isStateInCall(state)) {
  278. ALOGV(" Entering call in setPhoneState()");
  279. // force routing command to audio hardware when starting a call
  280. // even if no device change is needed
  281. force = true;
  282. for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
  283. mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
  284. sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
  285. }
  286. } else if (isStateInCall(oldState) && !isStateInCall(state)) {
  287. ALOGV(" Exiting call in setPhoneState()");
  288. // force routing command to audio hardware when exiting a call
  289. // even if no device change is needed
  290. force = true;
  291. for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
  292. mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
  293. sVolumeProfiles[AUDIO_STREAM_DTMF][j];
  294. }
  295. } else if (isStateInCall(state) && (state != oldState)) {
  296. ALOGV(" Switching between telephony and VoIP in setPhoneState()");
  297. // force routing command to audio hardware when switching between telephony and VoIP
  298. // even if no device change is needed
  299. force = true;
  300. }
  301. // check for device and output changes triggered by new phone state
  302. newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
  303. checkA2dpSuspend();
  304. checkOutputForAllStrategies();
  305. updateDevicesAndOutputs();
  306. AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
  307. // force routing command to audio hardware when ending call
  308. // even if no device change is needed
  309. if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
  310. newDevice = hwOutputDesc->device();
  311. }
  312. int delayMs = 0;
  313. if (isStateInCall(state)) {
  314. nsecs_t sysTime = systemTime();
  315. for (size_t i = 0; i < mOutputs.size(); i++) {
  316. AudioOutputDescriptor *desc = mOutputs.valueAt(i);
  317. // mute media and sonification strategies and delay device switch by the largest
  318. // latency of any output where either strategy is active.
  319. // This avoid sending the ring tone or music tail into the earpiece or headset.
  320. if ((desc->isStrategyActive(STRATEGY_MEDIA,
  321. SONIFICATION_HEADSET_MUSIC_DELAY,
  322. sysTime) ||
  323. desc->isStrategyActive(STRATEGY_SONIFICATION,
  324. SONIFICATION_HEADSET_MUSIC_DELAY,
  325. sysTime)) &&
  326. (delayMs < (int)desc->mLatency*2)) {
  327. delayMs = desc->mLatency*2;
  328. }
  329. setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
  330. setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
  331. getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
  332. setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
  333. setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
  334. getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
  335. }
  336. }
  337. // change routing is necessary
  338. setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
  339. // if entering in call state, handle special case of active streams
  340. // pertaining to sonification strategy see handleIncallSonification()
  341. if (isStateInCall(state)) {
  342. ALOGV("setPhoneState() in call state management: new state is %d", state);
  343. for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
  344. handleIncallSonification(stream, true, true);
  345. }
  346. }
  347. // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
  348. if (state == AudioSystem::MODE_RINGTONE &&
  349. isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
  350. mLimitRingtoneVolume = true;
  351. } else {
  352. mLimitRingtoneVolume = false;
  353. }
  354. }
  355. void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
  356. {
  357. ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
  358. bool forceVolumeReeval = false;
  359. switch(usage) {
  360. case AudioSystem::FOR_COMMUNICATION:
  361. if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
  362. config != AudioSystem::FORCE_NONE) {
  363. ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
  364. return;
  365. }
  366. forceVolumeReeval = true;
  367. mForceUse[usage] = config;
  368. break;
  369. case AudioSystem::FOR_MEDIA:
  370. if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
  371. config != AudioSystem::FORCE_WIRED_ACCESSORY &&
  372. config != AudioSystem::FORCE_ANALOG_DOCK &&
  373. config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE &&
  374. config != AudioSystem::FORCE_NO_BT_A2DP) {
  375. ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
  376. return;
  377. }
  378. mForceUse[usage] = config;
  379. break;
  380. case AudioSystem::FOR_RECORD:
  381. if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
  382. config != AudioSystem::FORCE_NONE) {
  383. ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
  384. return;
  385. }
  386. mForceUse[usage] = config;
  387. break;
  388. case AudioSystem::FOR_DOCK:
  389. if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
  390. config != AudioSystem::FORCE_BT_DESK_DOCK &&
  391. config != AudioSystem::FORCE_WIRED_ACCESSORY &&
  392. config != AudioSystem::FORCE_ANALOG_DOCK &&
  393. config != AudioSystem::FORCE_DIGITAL_DOCK) {
  394. ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
  395. }
  396. forceVolumeReeval = true;
  397. mForceUse[usage] = config;
  398. break;
  399. case AudioSystem::FOR_SYSTEM:
  400. if (config != AudioSystem::FORCE_NONE &&
  401. config != AudioSystem::FORCE_SYSTEM_ENFORCED) {
  402. ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
  403. }
  404. forceVolumeReeval = true;
  405. mForceUse[usage] = config;
  406. break;
  407. default:
  408. ALOGW("setForceUse() invalid usage %d", usage);
  409. break;
  410. }
  411. // check for device and output changes triggered by new force usage
  412. checkA2dpSuspend();
  413. checkOutputForAllStrategies();
  414. updateDevicesAndOutputs();
  415. for (size_t i = 0; i < mOutputs.size(); i++) {
  416. audio_io_handle_t output = mOutputs.keyAt(i);
  417. audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
  418. setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
  419. if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
  420. applyStreamVolumes(output, newDevice, 0, true);
  421. }
  422. }
  423. audio_io_handle_t activeInput = getActiveInput();
  424. if (activeInput != 0) {
  425. AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
  426. audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
  427. if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
  428. ALOGV("setForceUse() changing device from %x to %x for input %d",
  429. inputDesc->mDevice, newDevice, activeInput);
  430. inputDesc->mDevice = newDevice;
  431. AudioParameter param = AudioParameter();
  432. param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
  433. mpClientInterface->setParameters(activeInput, param.toString());
  434. }
  435. }
  436. }
  437. AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
  438. {
  439. return mForceUse[usage];
  440. }
  441. void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
  442. {
  443. ALOGV("setSystemProperty() property %s, value %s", property, value);
  444. }
  445. // Find a direct output profile compatible with the parameters passed, even if the input flags do
  446. // not explicitly request a direct output
  447. AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getProfileForDirectOutput(
  448. audio_devices_t device,
  449. uint32_t samplingRate,
  450. audio_format_t format,
  451. audio_channel_mask_t channelMask,
  452. audio_output_flags_t flags)
  453. {
  454. for (size_t i = 0; i < mHwModules.size(); i++) {
  455. if (mHwModules[i]->mHandle == 0) {
  456. continue;
  457. }
  458. for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
  459. IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
  460. if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
  461. if (profile->isCompatibleProfile(device, samplingRate, format,
  462. channelMask,
  463. AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
  464. if (mAvailableOutputDevices & profile->mSupportedDevices) {
  465. return mHwModules[i]->mOutputProfiles[j];
  466. }
  467. }
  468. } else {
  469. if (profile->isCompatibleProfile(device, samplingRate, format,
  470. channelMask,
  471. AUDIO_OUTPUT_FLAG_DIRECT)) {
  472. if (mAvailableOutputDevices & profile->mSupportedDevices) {
  473. return mHwModules[i]->mOutputProfiles[j];
  474. }
  475. }
  476. }
  477. }
  478. }
  479. return 0;
  480. }
  481. audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
  482. uint32_t samplingRate,
  483. audio_format_t format,
  484. audio_channel_mask_t channelMask,
  485. AudioSystem::output_flags flags,
  486. const audio_offload_info_t *offloadInfo)
  487. {
  488. audio_io_handle_t output = 0;
  489. uint32_t latency = 0;
  490. routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
  491. audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
  492. ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
  493. device, stream, samplingRate, format, channelMask, flags);
  494. #ifdef AUDIO_POLICY_TEST
  495. if (mCurOutput != 0) {
  496. ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
  497. mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
  498. if (mTestOutputs[mCurOutput] == 0) {
  499. ALOGV("getOutput() opening test output");
  500. AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
  501. outputDesc->mDevice = mTestDevice;
  502. outputDesc->mSamplingRate = mTestSamplingRate;
  503. outputDesc->mFormat = mTestFormat;
  504. outputDesc->mChannelMask = mTestChannels;
  505. outputDesc->mLatency = mTestLatencyMs;
  506. outputDesc->mFlags = (audio_output_flags_t)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
  507. outputDesc->mRefCount[stream] = 0;
  508. mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
  509. &outputDesc->mSamplingRate,
  510. &outputDesc->mFormat,
  511. &outputDesc->mChannelMask,
  512. &outputDesc->mLatency,
  513. outputDesc->mFlags,
  514. offloadInfo);
  515. if (mTestOutputs[mCurOutput]) {
  516. AudioParameter outputCmd = AudioParameter();
  517. outputCmd.addInt(String8("set_id"),mCurOutput);
  518. mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
  519. addOutput(mTestOutputs[mCurOutput], outputDesc);
  520. }
  521. }
  522. return mTestOutputs[mCurOutput];
  523. }
  524. #endif //AUDIO_POLICY_TEST
  525. // open a direct output if required by specified parameters
  526. //force direct flag if offload flag is set: offloading implies a direct output stream
  527. // and all common behaviors are driven by checking only the direct flag
  528. // this should normally be set appropriately in the policy configuration file
  529. if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
  530. flags = (AudioSystem::output_flags)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
  531. }
  532. // Do not allow offloading if one non offloadable effect is enabled. This prevents from
  533. // creating an offloaded track and tearing it down immediately after start when audioflinger
  534. // detects there is an active non offloadable effect.
  535. // FIXME: We should check the audio session here but we do not have it in this context.
  536. // This may prevent offloading in rare situations where effects are left active by apps
  537. // in the background.
  538. IOProfile *profile = NULL;
  539. if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
  540. !isNonOffloadableEffectEnabled()) {
  541. profile = getProfileForDirectOutput(device,
  542. samplingRate,
  543. format,
  544. channelMask,
  545. (audio_output_flags_t)flags);
  546. }
  547. if (profile != NULL) {
  548. AudioOutputDescriptor *outputDesc = NULL;
  549. for (size_t i = 0; i < mOutputs.size(); i++) {
  550. AudioOutputDescriptor *desc = mOutputs.valueAt(i);
  551. if (!desc->isDuplicated() && (profile == desc->mProfile)) {
  552. outputDesc = desc;
  553. // reuse direct output if currently open and configured with same parameters
  554. if ((samplingRate == outputDesc->mSamplingRate) &&
  555. (format == outputDesc->mFormat) &&
  556. (channelMask == outputDesc->mChannelMask)) {
  557. outputDesc->mDirectOpenCount++;
  558. ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
  559. return mOutputs.keyAt(i);
  560. }
  561. }
  562. }
  563. // close direct output if currently open and configured with different parameters
  564. if (outputDesc != NULL) {
  565. closeOutput(outputDesc->mId);
  566. }
  567. outputDesc = new AudioOutputDescriptor(profile);
  568. outputDesc->mDevice = device;
  569. outputDesc->mSamplingRate = samplingRate;
  570. outputDesc->mFormat = format;
  571. outputDesc->mChannelMask = channelMask;
  572. outputDesc->mLatency = 0;
  573. outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
  574. outputDesc->mRefCount[stream] = 0;
  575. outputDesc->mStopTime[stream] = 0;
  576. outputDesc->mDirectOpenCount = 1;
  577. output = mpClientInterface->openOutput(profile->mModule->mHandle,
  578. &outputDesc->mDevice,
  579. &outputDesc->mSamplingRate,
  580. &outputDesc->mFormat,
  581. &outputDesc->mChannelMask,
  582. &outputDesc->mLatency,
  583. outputDesc->mFlags,
  584. offloadInfo);
  585. // only accept an output with the requested parameters
  586. if (output == 0 ||
  587. (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
  588. (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
  589. (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
  590. ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
  591. "format %d %d, channelMask %04x %04x", output, samplingRate,
  592. outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
  593. outputDesc->mChannelMask);
  594. if (output != 0) {
  595. mpClientInterface->closeOutput(output);
  596. }
  597. delete outputDesc;
  598. return 0;
  599. }
  600. audio_io_handle_t srcOutput = getOutputForEffect();
  601. addOutput(output, outputDesc);
  602. audio_io_handle_t dstOutput = getOutputForEffect();
  603. if (dstOutput == output) {
  604. mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
  605. }
  606. mPreviousOutputs = mOutputs;
  607. ALOGV("getOutput() returns new direct output %d", output);
  608. return output;
  609. }
  610. // ignoring channel mask due to downmix capability in mixer
  611. // open a non direct output
  612. // for non direct outputs, only PCM is supported
  613. if (audio_is_linear_pcm(format)) {
  614. // get which output is suitable for the specified stream. The actual
  615. // routing change will happen when startOutput() will be called
  616. SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
  617. output = selectOutput(outputs, flags);
  618. }
  619. ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
  620. "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
  621. ALOGV("getOutput() returns output %d", output);
  622. return output;
  623. }
  624. audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
  625. AudioSystem::output_flags flags)
  626. {
  627. // select one output among several that provide a path to a particular device or set of
  628. // devices (the list was previously build by getOutputsForDevice()).
  629. // The priority is as follows:
  630. // 1: the output with the highest number of requested policy flags
  631. // 2: the primary output
  632. // 3: the first output in the list
  633. if (outputs.size() == 0) {
  634. return 0;
  635. }
  636. if (outputs.size() == 1) {
  637. return outputs[0];
  638. }
  639. int maxCommonFlags = 0;
  640. audio_io_handle_t outputFlags = 0;
  641. audio_io_handle_t outputPrimary = 0;
  642. for (size_t i = 0; i < outputs.size(); i++) {
  643. AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
  644. if (!outputDesc->isDuplicated()) {
  645. int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags);
  646. if (commonFlags > maxCommonFlags) {
  647. outputFlags = outputs[i];
  648. maxCommonFlags = commonFlags;
  649. ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
  650. }
  651. if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
  652. outputPrimary = outputs[i];
  653. }
  654. }
  655. }
  656. if (outputFlags != 0) {
  657. return outputFlags;
  658. }
  659. if (outputPrimary != 0) {
  660. return outputPrimary;
  661. }
  662. return outputs[0];
  663. }
  664. status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
  665. AudioSystem::stream_type stream,
  666. int session)
  667. {
  668. ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
  669. ssize_t index = mOutputs.indexOfKey(output);
  670. if (index < 0) {
  671. ALOGW("startOutput() unknown output %d", output);
  672. return BAD_VALUE;
  673. }
  674. AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
  675. // increment usage count for this stream on the requested output:
  676. // NOTE that the usage count is the same for duplicated output and hardware output which is
  677. // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
  678. outputDesc->changeRefCount(stream, 1);
  679. if (outputDesc->mRefCount[stream] == 1) {
  680. audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
  681. routing_strategy strategy = getStrategy(stream);
  682. bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
  683. (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
  684. uint32_t waitMs = 0;
  685. bool force = false;
  686. for (size_t i = 0; i < mOutputs.size(); i++) {
  687. AudioOutputDescriptor *desc = mOutputs.valueAt(i);
  688. if (desc != outputDesc) {
  689. // force a device change if any other output is managed by the same hw
  690. // module and has a current device selection that differs from selected device.
  691. // In this case, the audio HAL must receive the new device selection so that it can
  692. // change the device currently selected by the other active output.
  693. if (outputDesc->sharesHwModuleWith(desc) &&
  694. desc->device() != newDevice) {
  695. force = true;
  696. }
  697. // wait for audio on other active outputs to be presented when starting
  698. // a notification so that audio focus effect can propagate.
  699. uint32_t latency = desc->latency();
  700. if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
  701. waitMs = latency;
  702. }
  703. }
  704. }
  705. uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
  706. // handle special case for sonification while in call
  707. if (isInCall()) {
  708. handleIncallSonification(stream, true, false);
  709. }
  710. // apply volume rules for current stream and device if necessary
  711. checkAndSetVolume(stream,
  712. mStreams[stream].getVolumeIndex(newDevice),
  713. output,
  714. newDevice);
  715. // update the outputs if starting an output with a stream that can affect notification
  716. // routing
  717. handleNotificationRoutingForStream(stream);
  718. if (waitMs > muteWaitMs) {
  719. usleep((waitMs - muteWaitMs) * 2 * 1000);
  720. }
  721. }
  722. return NO_ERROR;
  723. }
  724. status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
  725. AudioSystem::stream_type stream,
  726. int session)
  727. {
  728. ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
  729. ssize_t index = mOutputs.indexOfKey(output);
  730. if (index < 0) {
  731. ALOGW("stopOutput() unknown output %d", output);
  732. return BAD_VALUE;
  733. }
  734. AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
  735. // handle special case for sonification while in call
  736. if (isInCall()) {
  737. handleIncallSonification(stream, false, false);
  738. }
  739. if (outputDesc->mRefCount[stream] > 0) {
  740. // decrement usage count of this stream on the output
  741. outputDesc->changeRefCount(stream, -1);
  742. // store time at which the stream was stopped - see isStreamActive()
  743. if (outputDesc->mRefCount[stream] == 0) {
  744. outputDesc->mStopTime[stream] = systemTime();
  745. audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
  746. // delay the device switch by twice the latency because stopOutput() is executed when
  747. // the track stop() command is received and at that time the audio track buffer can
  748. // still contain data that needs to be drained. The latency only covers the audio HAL
  749. // and kernel buffers. Also the latency does not always include additional delay in the
  750. // audio path (audio DSP, CODEC ...)
  751. setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
  752. // force restoring the device selection on other active outputs if it differs from the
  753. // one being selected for this output
  754. for (size_t i = 0; i < mOutputs.size(); i++) {
  755. audio_io_handle_t curOutput = mOutputs.keyAt(i);
  756. AudioOutputDescriptor *desc = mOutputs.valueAt(i);
  757. if (curOutput != output &&
  758. desc->isActive() &&
  759. outputDesc->sharesHwModuleWith(desc) &&
  760. (newDevice != desc->device())) {
  761. setOutputDevice(curOutput,
  762. getNewDevice(curOutput, false /*fromCache*/),
  763. true,
  764. outputDesc->mLatency*2);
  765. }
  766. }
  767. // update the outputs if stopping one with a stream that can affect notification routing
  768. handleNotificationRoutingForStream(stream);
  769. }
  770. return NO_ERROR;
  771. } else {
  772. ALOGW("stopOutput() refcount is already 0 for output %d", output);
  773. return INVALID_OPERATION;
  774. }
  775. }
  776. void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
  777. {
  778. ALOGV("releaseOutput() %d", output);
  779. ssize_t index = mOutputs.indexOfKey(output);
  780. if (index < 0) {
  781. ALOGW("releaseOutput() releasing unknown output %d", output);
  782. return;
  783. }
  784. #ifdef AUDIO_POLICY_TEST
  785. int testIndex = testOutputIndex(output);
  786. if (testIndex != 0) {
  787. AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
  788. if (outputDesc->isActive()) {
  789. mpClientInterface->closeOutput(output);
  790. delete mOutputs.valueAt(index);
  791. mOutputs.removeItem(output);
  792. mTestOutputs[testIndex] = 0;
  793. }
  794. return;
  795. }
  796. #endif //AUDIO_POLICY_TEST
  797. AudioOutputDescriptor *desc = mOutputs.valueAt(index);
  798. if (desc->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
  799. if (desc->mDirectOpenCount <= 0) {
  800. ALOGW("releaseOutput() invalid open count %d for output %d",
  801. desc->mDirectOpenCount, output);
  802. return;
  803. }
  804. if (--desc->mDirectOpenCount == 0) {
  805. closeOutput(output);
  806. // If effects where present on the output, audioflinger moved them to the primary
  807. // output by default: move them back to the appropriate output.
  808. audio_io_handle_t dstOutput = getOutputForEffect();
  809. if (dstOutput != mPrimaryOutput) {
  810. mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
  811. }
  812. }
  813. }
  814. }
  815. audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
  816. uint32_t samplingRate,
  817. audio_format_t format,
  818. audio_channel_mask_t channelMask,
  819. AudioSystem::audio_in_acoustics acoustics)
  820. {
  821. audio_io_handle_t input = 0;
  822. audio_devices_t device = getDeviceForInputSource(inputSource);
  823. ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
  824. inputSource, samplingRate, format, channelMask, acoustics);
  825. if (device == AUDIO_DEVICE_NONE) {
  826. ALOGW("getInput() could not find device for inputSource %d", inputSource);
  827. return 0;
  828. }
  829. // adapt channel selection to input source
  830. switch(inputSource) {
  831. case AUDIO_SOURCE_VOICE_UPLINK:
  832. channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
  833. break;
  834. case AUDIO_SOURCE_VOICE_DOWNLINK:
  835. channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
  836. break;
  837. case AUDIO_SOURCE_VOICE_CALL:
  838. channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
  839. break;
  840. default:
  841. break;
  842. }
  843. IOProfile *profile = getInputProfile(device,
  844. samplingRate,
  845. format,
  846. channelMask);
  847. if (profile == NULL) {
  848. ALOGW("getInput() could not find profile for device 0x%X, samplingRate %d, format %d, "
  849. "channelMask 0x%X",
  850. device, samplingRate, format, channelMask);
  851. return 0;
  852. }
  853. if (profile->mModule->mHandle == 0) {
  854. ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
  855. return 0;
  856. }
  857. AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
  858. inputDesc->mInputSource = inputSource;
  859. inputDesc->mDevice = device;
  860. inputDesc->mSamplingRate = samplingRate;
  861. inputDesc->mFormat = format;
  862. inputDesc->mChannelMask = channelMask;
  863. inputDesc->mRefCount = 0;
  864. input = mpClientInterface->openInput(profile->mModule->mHandle,
  865. &inputDesc->mDevice,
  866. &inputDesc->mSamplingRate,
  867. &inputDesc->mFormat,
  868. &inputDesc->mChannelMask);
  869. // only accept input with the exact requested set of parameters
  870. if (input == 0 ||
  871. (samplingRate != inputDesc->mSamplingRate) ||
  872. (format != inputDesc->mFormat) ||
  873. (channelMask != inputDesc->mChannelMask)) {
  874. ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask 0x%X",
  875. samplingRate, format, channelMask);
  876. if (input != 0) {
  877. mpClientInterface->closeInput(input);
  878. }
  879. delete inputDesc;
  880. return 0;
  881. }
  882. addInput(input, inputDesc);
  883. return input;
  884. }
  885. status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
  886. {
  887. ALOGV("startInput() input %d", input);
  888. ssize_t index = mInputs.indexOfKey(input);
  889. if (index < 0) {
  890. ALOGW("startInput() unknown input %d", input);
  891. return BAD_VALUE;
  892. }
  893. AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
  894. #ifdef AUDIO_POLICY_TEST
  895. if (mTestInput == 0)
  896. #endif //AUDIO_POLICY_TEST
  897. {
  898. // refuse 2 active AudioRecord clients at the same time except if the active input
  899. // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
  900. audio_io_handle_t activeInput = getActiveInput();
  901. if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
  902. AudioInputDescriptor *activeDesc = mInputs.valueFor(activeInput);
  903. if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
  904. ALOGW("startInput() preempting already started low-priority input %d", activeInput);
  905. stopInput(activeInput);
  906. releaseInput(activeInput);
  907. } else {
  908. ALOGW("startInput() input %d failed: other input already started", input);
  909. return INVALID_OPERATION;
  910. }
  911. }
  912. }
  913. audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
  914. if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
  915. inputDesc->mDevice = newDevice;
  916. }
  917. // automatically enable the remote submix output when input is started
  918. if (audio_is_remote_submix_device(inputDesc->mDevice)) {
  919. setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
  920. AudioSystem::DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
  921. }
  922. AudioParameter param = AudioParameter();
  923. param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
  924. int aliasSource = (inputDesc->mInputSource == AUDIO_SOURCE_HOTWORD) ?
  925. AUDIO_SOURCE_VOICE_RECOGNITION : inputDesc->mInputSource;
  926. param.addInt(String8(AudioParameter::keyInputSource), aliasSource);
  927. ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
  928. mpClientInterface->setParameters(input, param.toString());
  929. inputDesc->mRefCount = 1;
  930. return NO_ERROR;
  931. }
  932. status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
  933. {
  934. ALOGV("stopInput() input %d", input);
  935. ssize_t index = mInputs.indexOfKey(input);
  936. if (index < 0) {
  937. ALOGW("stopInput() unknown input %d", input);
  938. return BAD_VALUE;
  939. }
  940. AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
  941. if (inputDesc->mRefCount == 0) {
  942. ALOGW("stopInput() input %d already stopped", input);
  943. return INVALID_OPERATION;
  944. } else {
  945. // automatically disable the remote submix output when input is stopped
  946. if (audio_is_remote_submix_device(inputDesc->mDevice)) {
  947. setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
  948. AudioSystem::DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
  949. }
  950. AudioParameter param = AudioParameter();
  951. param.addInt(String8(AudioParameter::keyRouting), 0);
  952. mpClientInterface->setParameters(input, param.toString());
  953. inputDesc->mRefCount = 0;
  954. return NO_ERROR;
  955. }
  956. }
  957. void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
  958. {
  959. ALOGV("releaseInput() %d", input);
  960. ssize_t index = mInputs.indexOfKey(input);
  961. if (index < 0) {
  962. ALOGW("releaseInput() releasing unknown input %d", input);
  963. return;
  964. }
  965. mpClientInterface->closeInput(input);
  966. delete mInputs.valueAt(index);
  967. mInputs.removeItem(input);
  968. ALOGV("releaseInput() exit");
  969. }
  970. void AudioPolicyManagerBase::closeAllInputs() {
  971. for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
  972. mpClientInterface->closeInput(mInputs.keyAt(input_index));
  973. }
  974. mInputs.clear();
  975. }
  976. void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
  977. int indexMin,
  978. int indexMax)
  979. {
  980. ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
  981. if (indexMin < 0 || indexMin >= indexMax) {
  982. ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
  983. return;
  984. }
  985. mStreams[stream].mIndexMin = indexMin;
  986. mStreams[stream].mIndexMax = indexMax;
  987. }
  988. status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
  989. int index,
  990. audio_devices_t device)
  991. {
  992. if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
  993. return BAD_VALUE;
  994. }
  995. if (!audio_is_output_device(device)) {
  996. return BAD_VALUE;
  997. }
  998. // Force max volume if stream cannot be muted
  999. if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
  1000. ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
  1001. stream, device, index);
  1002. // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
  1003. // clear all device specific values
  1004. if (device == AUDIO_DEVICE_OUT_DEFAULT) {
  1005. mStreams[stream].mIndexCur.clear();
  1006. }
  1007. mStreams[stream].mIndexCur.add(device, index);
  1008. // compute and apply stream volume on all outputs according to connected device
  1009. status_t status = NO_ERROR;
  1010. for (size_t i = 0; i < mOutputs.size(); i++) {
  1011. audio_devices_t curDevice =
  1012. getDeviceForVolume(mOutputs.valueAt(i)->device());
  1013. if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
  1014. status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
  1015. if (volStatus != NO_ERROR) {
  1016. status = volStatus;
  1017. }
  1018. }
  1019. }
  1020. return status;
  1021. }
  1022. status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream,
  1023. int *index,
  1024. audio_devices_t device)
  1025. {
  1026. if (index == NULL) {
  1027. return BAD_VALUE;
  1028. }
  1029. if (!audio_is_output_device(device)) {
  1030. return BAD_VALUE;
  1031. }
  1032. // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
  1033. // the strategy the stream belongs to.
  1034. if (device == AUDIO_DEVICE_OUT_DEFAULT) {
  1035. device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
  1036. }
  1037. device = getDeviceForVolume(device);
  1038. *index = mStreams[stream].getVolumeIndex(device);
  1039. ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
  1040. return NO_ERROR;
  1041. }
  1042. audio_io_handle_t AudioPolicyManagerBase::selectOutputForEffects(
  1043. const SortedVector<audio_io_handle_t>& outputs)
  1044. {
  1045. // select one output among several suitable for global effects.
  1046. // The priority is as follows:
  1047. // 1: An offloaded output. If the effect ends up not being offloadable,
  1048. // AudioFlinger will invalidate the track and the offloaded output
  1049. // will be closed causing the effect to be moved to a PCM output.
  1050. // 2: A deep buffer output
  1051. // 3: the first output in the list
  1052. if (outputs.size() == 0) {
  1053. return 0;
  1054. }
  1055. audio_io_handle_t outputOffloaded = 0;
  1056. audio_io_handle_t outputDeepBuffer = 0;
  1057. for (size_t i = 0; i < outputs.size(); i++) {
  1058. AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
  1059. ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
  1060. if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
  1061. outputOffloaded = outputs[i];
  1062. }
  1063. if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
  1064. outputDeepBuffer = outputs[i];
  1065. }
  1066. }
  1067. ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
  1068. outputOffloaded, outputDeepBuffer);
  1069. if (outputOffloaded != 0) {
  1070. return outputOffloaded;
  1071. }
  1072. if (outputDeepBuffer != 0) {
  1073. return outputDeepBuffer;
  1074. }
  1075. return outputs[0];
  1076. }
  1077. audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(const effect_descriptor_t *desc)
  1078. {
  1079. // apply simple rule where global effects are attached to the same output as MUSIC streams
  1080. routing_strategy strategy = getStrategy(AudioSystem::MUSIC);
  1081. audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
  1082. SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
  1083. audio_io_handle_t output = selectOutputForEffects(dstOutputs);
  1084. ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
  1085. output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
  1086. return output;
  1087. }
  1088. status_t AudioPolicyManagerBase::registerEffect(const effect_descriptor_t *desc,
  1089. audio_io_handle_t io,
  1090. uint32_t strategy,
  1091. int session,
  1092. int id)
  1093. {
  1094. ssize_t index = mOutputs.indexOfKey(io);
  1095. if (index < 0) {
  1096. index = mInputs.indexOfKey(io);
  1097. if (index < 0) {
  1098. ALOGW("registerEffect() unknown io %d", io);
  1099. return INVALID_OPERATION;
  1100. }
  1101. }
  1102. if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
  1103. ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
  1104. desc->name, desc->memoryUsage);
  1105. return INVALID_OPERATION;
  1106. }
  1107. mTotalEffectsMemory += desc->memoryUsage;
  1108. ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
  1109. desc->name, io, strategy, session, id);
  1110. ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
  1111. EffectDescriptor *pDesc = new EffectDescriptor();
  1112. memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
  1113. pDesc->mIo = io;
  1114. pDesc->mStrategy = (routing_strategy)strategy;
  1115. pDesc->mSession = session;
  1116. pDesc->mEnabled = false;
  1117. mEffects.add(id, pDesc);
  1118. return NO_ERROR;
  1119. }
  1120. status_t AudioPolicyManagerBase::unregisterEffect(int id)
  1121. {
  1122. ssize_t index = mEffects.indexOfKey(id);
  1123. if (index < 0) {
  1124. ALOGW("unregisterEffect() unknown effect ID %d", id);
  1125. return INVALID_OPERATION;
  1126. }
  1127. EffectDescriptor *pDesc = mEffects.valueAt(index);
  1128. setEffectEnabled(pDesc, false);
  1129. if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
  1130. ALOGW("unregisterEffect() memory %d too big for total %d",
  1131. pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
  1132. pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
  1133. }
  1134. mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
  1135. ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
  1136. pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
  1137. mEffects.removeItem(id);
  1138. delete pDesc;
  1139. return NO_ERROR;
  1140. }
  1141. status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
  1142. {
  1143. ssize_t index = mEffects.indexOfKey(id);
  1144. if (index < 0) {
  1145. ALOGW("unregisterEffect() unknown effect ID %d", id);
  1146. return INVALID_OPERATION;
  1147. }
  1148. return setEffectEnabled(mEffects.valueAt(index), enabled);
  1149. }
  1150. status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
  1151. {
  1152. if (enabled == pDesc->mEnabled) {
  1153. ALOGV("setEffectEnabled(%s) effect already %s",
  1154. enabled?"true":"false", enabled?"enabled":"disabled");
  1155. return INVALID_OPERATION;
  1156. }
  1157. if (enabled) {
  1158. if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
  1159. ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
  1160. pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
  1161. return INVALID_OPERATION;
  1162. }
  1163. mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
  1164. ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
  1165. } else {
  1166. if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
  1167. ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
  1168. pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
  1169. pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
  1170. }
  1171. mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
  1172. ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
  1173. }
  1174. pDesc->mEnabled = enabled;
  1175. return NO_ERROR;
  1176. }
  1177. bool AudioPolicyManagerBase::isNonOffloadableEffectEnabled()
  1178. {
  1179. for (size_t i = 0; i < mEffects.size(); i++) {
  1180. const EffectDescriptor * const pDesc = mEffects.valueAt(i);
  1181. if (pDesc->mEnabled && (pDesc->mStrategy == STRATEGY_MEDIA) &&
  1182. ((pDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
  1183. ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
  1184. pDesc->mDesc.name, pDesc->mSession);
  1185. return true;
  1186. }
  1187. }
  1188. return false;
  1189. }
  1190. bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
  1191. {
  1192. nsecs_t sysTime = systemTime();
  1193. for (size_t i = 0; i < mOutputs.size(); i++) {
  1194. const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
  1195. if (outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
  1196. return true;
  1197. }
  1198. }
  1199. return false;
  1200. }
  1201. bool AudioPolicyManagerBase::isStreamActiveRemotely(int stream, uint32_t inPastMs) const
  1202. {
  1203. nsecs_t sysTime = systemTime();
  1204. for (size_t i = 0; i < mOutputs.size(); i++) {
  1205. const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
  1206. if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
  1207. outputDesc->isStreamActive((AudioSystem::stream_type)stream, inPastMs, sysTime)) {
  1208. return true;
  1209. }
  1210. }
  1211. return false;
  1212. }
  1213. bool AudioPolicyManagerBase::isSourceActive(audio_source_t source) const
  1214. {
  1215. for (size_t i = 0; i < mInputs.size(); i++) {
  1216. const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
  1217. if ((inputDescriptor->mInputSource == (int)source ||
  1218. (source == (audio_source_t)AUDIO_SOURCE_VOICE_RECOGNITION &&
  1219. inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
  1220. && (inputDescriptor->mRefCount > 0)) {
  1221. return true;
  1222. }
  1223. }
  1224. return false;
  1225. }
  1226. status_t AudioPolicyManagerBase::dump(int fd)
  1227. {
  1228. const size_t SIZE = 256;
  1229. char buffer[SIZE];
  1230. String8 result;
  1231. snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
  1232. result.append(buffer);
  1233. snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
  1234. result.append(buffer);
  1235. snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
  1236. result.append(buffer);
  1237. snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
  1238. result.append(buffer);
  1239. snprintf(buffer, SIZE, " USB audio ALSA %s\n", mUsbOutCardAndDevice.string());
  1240. result.append(buffer);
  1241. snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
  1242. result.append(buffer);
  1243. snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
  1244. result.append(buffer);
  1245. snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
  1246. result.append(buffer);
  1247. snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
  1248. result.append(buffer);
  1249. snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
  1250. result.append(buffer);
  1251. snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
  1252. result.append(buffer);
  1253. snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
  1254. result.append(buffer);
  1255. snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AudioSystem::FOR_SYSTEM]);
  1256. result.append(buffer);
  1257. write(fd, result.string(), result.size());
  1258. snprintf(buffer, SIZE, "\nHW Modules dump:\n");
  1259. write(fd, buffer, strlen(buffer));
  1260. for (size_t i = 0; i < mHwModules.size(); i++) {
  1261. snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
  1262. write(fd, buffer, strlen(buffer));
  1263. mHwModules[i]->dump(fd);
  1264. }
  1265. snprintf(buffer, SIZE, "\nOutputs dump:\n");
  1266. write(fd, buffer, strlen(buffer));
  1267. for (size_t i = 0; i < mOutputs.size(); i++) {
  1268. snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
  1269. write(fd, buffer, strlen(buffer));
  1270. mOutputs.valueAt(i)->dump(fd);
  1271. }
  1272. snprintf(buffer, SIZE, "\nInputs dump:\n");
  1273. write(fd, buffer, strlen(buffer));
  1274. for (size_t i = 0; i < mInputs.size(); i++) {
  1275. snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
  1276. write(fd, buffer, strlen(buffer));
  1277. mInputs.valueAt(i)->dump(fd);
  1278. }
  1279. snprintf(buffer, SIZE, "\nStreams dump:\n");
  1280. write(fd, buffer, strlen(buffer));
  1281. snprintf(buffer, SIZE,
  1282. " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
  1283. write(fd, buffer, strlen(buffer));
  1284. for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
  1285. snprintf(buffer, SIZE, " %02zu ", i);
  1286. write(fd, buffer, strlen(buffer));
  1287. mStreams[i].dump(fd);
  1288. }
  1289. snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
  1290. (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
  1291. write(fd, buffer, strlen(buffer));
  1292. snprintf(buffer, SIZE, "Registered effects:\n");
  1293. write(fd, buffer, strlen(buffer));
  1294. for (size_t i = 0; i < mEffects.size(); i++) {
  1295. snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
  1296. write(fd, buffer, strlen(buffer));
  1297. mEffects.valueAt(i)->dump(fd);
  1298. }
  1299. return NO_ERROR;
  1300. }
  1301. // This function checks for the parameters which can be offloaded.
  1302. // This can be enhanced depending on the capability of the DSP and policy
  1303. // of the system.
  1304. bool AudioPolicyManagerBase::isOffloadSupported(const audio_offload_info_t& offloadInfo)
  1305. {
  1306. ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
  1307. " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
  1308. offloadInfo.sample_rate, offloadInfo.channel_mask,
  1309. offloadInfo.format,
  1310. offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
  1311. offloadInfo.has_video);
  1312. // Check if offload has been disabled
  1313. char propValue[PROPERTY_VALUE_MAX];
  1314. if (property_get("audio.offload.disable", propValue, "0")) {
  1315. if (atoi(propValue) != 0) {
  1316. ALOGV("offload disabled by audio.offload.disable=%s", propValue );
  1317. return false;
  1318. }
  1319. }
  1320. // Check if stream type is music, then only allow offload as of now.
  1321. if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
  1322. {
  1323. ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
  1324. return false;
  1325. }
  1326. //TODO: enable audio offloading with video when ready
  1327. if (offloadInfo.has_video)
  1328. {
  1329. ALOGV("isOffloadSupported: has_video == true, returning false");
  1330. return false;
  1331. }
  1332. //If duration is less than minimum value defined in property, return false
  1333. if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
  1334. if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
  1335. ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
  1336. return false;
  1337. }
  1338. } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
  1339. ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
  1340. return false;
  1341. }
  1342. // Do not allow offloading if one non offloadable effect is enabled. This prevents from
  1343. // creating an offloaded track and tearing it down immediately after start when audioflinger
  1344. // detects there is an active non offloadable effect.
  1345. // FIXME: We should check the audio session here but we do not have it in this context.
  1346. // This may prevent offloading in rare situations where effects are left active by apps
  1347. // in the background.
  1348. if (isNonOffloadableEffectEnabled()) {
  1349. return false;
  1350. }
  1351. // See if there is a profile to support this.
  1352. // AUDIO_DEVICE_NONE
  1353. IOProfile *profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
  1354. offloadInfo.sample_rate,
  1355. offloadInfo.format,
  1356. offloadInfo.channel_mask,
  1357. AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
  1358. ALOGV("isOffloadSupported() profile %sfound", profile != NULL ? "" : "NOT ");
  1359. return (profile != NULL);
  1360. }
  1361. // ----------------------------------------------------------------------------
  1362. // AudioPolicyManagerBase
  1363. // ----------------------------------------------------------------------------
  1364. AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
  1365. :
  1366. #ifdef AUDIO_POLICY_TEST
  1367. Thread(false),
  1368. #endif //AUDIO_POLICY_TEST
  1369. mPrimaryOutput((audio_io_handle_t)0),
  1370. mAvailableOutputDevices(AUDIO_DEVICE_NONE),
  1371. mPhoneState(AudioSystem::MODE_NORMAL),
  1372. mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
  1373. mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
  1374. mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false), mHasRemoteSubmix(false),
  1375. mSpeakerDrcEnabled(false)
  1376. {
  1377. mpClientInterface = clientInterface;
  1378. for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
  1379. mForceUse[i] = AudioSystem::FORCE_NONE;
  1380. }
  1381. mA2dpDeviceAddress = String8("");
  1382. mScoDeviceAddress = String8("");
  1383. mUsbOutCardAndDevice = String8("");
  1384. if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
  1385. if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
  1386. ALOGE("could not load audio policy configuration file, setting defaults");
  1387. defaultAudioPolicyConfig();
  1388. }
  1389. }
  1390. // must be done after reading the policy
  1391. initializeVolumeCurves();
  1392. // open all output streams needed to access attached devices
  1393. for (size_t i = 0; i < mHwModules.size(); i++) {
  1394. mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
  1395. if (mHwModules[i]->mHandle == 0) {
  1396. ALOGW("could not open HW module %s", mHwModules[i]->mName);
  1397. continue;
  1398. }
  1399. // open all output streams needed to access attached devices
  1400. // except for direct output streams that are only opened when they are actually
  1401. // required by an app.
  1402. for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
  1403. {
  1404. const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
  1405. if ((outProfile->mSupportedDevices & mAttachedOutputDevices) &&
  1406. ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
  1407. AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
  1408. outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice &
  1409. outProfile->mSupportedDevices);
  1410. audio_io_handle_t output = mpClientInterface->openOutput(
  1411. outProfile->mModule->mHandle,
  1412. &outputDesc->mDevice,
  1413. &outputDesc->mSamplingRate,
  1414. &outputDesc->mFormat,
  1415. &outputDesc->mChannelMask,
  1416. &outputDesc->mLatency,
  1417. outputDesc->mFlags);
  1418. if (output == 0) {
  1419. delete outputDesc;
  1420. } else {
  1421. mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices |
  1422. (outProfile->mSupportedDevices & mAttachedOutputDevices));
  1423. if (mPrimaryOutput == 0 &&
  1424. outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
  1425. mPrimaryOutput = output;
  1426. }
  1427. addOutput(output, outputDesc);
  1428. setOutputDevice(output,
  1429. (audio_devices_t)(mDefaultOutputDevice &
  1430. outProfile->mSupportedDevices),
  1431. true);
  1432. }
  1433. }
  1434. }
  1435. }
  1436. ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),
  1437. "Not output found for attached devices %08x",
  1438. (mAttachedOutputDevices & ~mAvailableOutputDevices));
  1439. ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
  1440. updateDevicesAndOutputs();
  1441. #ifdef AUDIO_POLICY_TEST
  1442. if (mPrimaryOutput != 0) {
  1443. AudioParameter outputCmd = AudioParameter();
  1444. outputCmd.addInt(String8("set_id"), 0);
  1445. mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
  1446. mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
  1447. mTestSamplingRate = 44100;
  1448. mTestFormat = AudioSystem::PCM_16_BIT;
  1449. mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
  1450. mTestLatencyMs = 0;
  1451. mCurOutput = 0;
  1452. mDirectOutput = false;
  1453. for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
  1454. mTestOutputs[i] = 0;
  1455. }
  1456. const size_t SIZE = 256;
  1457. char buffer[SIZE];
  1458. snprintf(buffer, SIZE, "AudioPolicyManagerTest");
  1459. run(buffer, ANDROID_PRIORITY_AUDIO);
  1460. }
  1461. #endif //AUDIO_POLICY_TEST
  1462. }
  1463. AudioPolicyManagerBase::~AudioPolicyManagerBase()
  1464. {
  1465. #ifdef AUDIO_POLICY_TEST
  1466. exit();
  1467. #endif //AUDIO_POLICY_TEST
  1468. for (size_t i = 0; i < mOutputs.size(); i++) {
  1469. mpClientInterface->closeOutput(mOutputs.keyAt(i));
  1470. delete mOutputs.valueAt(i);
  1471. }
  1472. for (size_t i = 0; i < mInputs.size(); i++) {
  1473. mpClientInterface->closeInput(mInputs.keyAt(i));
  1474. delete mInputs.valueAt(i);
  1475. }
  1476. for (size_t i = 0; i < mHwModules.size(); i++) {
  1477. delete mHwModules[i];
  1478. }
  1479. }
  1480. status_t AudioPolicyManagerBase::initCheck()
  1481. {
  1482. return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
  1483. }
  1484. #ifdef AUDIO_POLICY_TEST
  1485. bool AudioPolicyManagerBase::threadLoop()
  1486. {
  1487. ALOGV("entering threadLoop()");
  1488. while (!exitPending())
  1489. {
  1490. String8 command;
  1491. int valueInt;
  1492. String8 value;
  1493. Mutex::Autolock _l(mLock);
  1494. mWaitWorkCV.waitRelative(mLock, milliseconds(50));
  1495. command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
  1496. AudioParameter param = AudioParameter(command);
  1497. if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
  1498. valueInt != 0) {
  1499. ALOGV("Test command %s received", command.string());
  1500. String8 target;
  1501. if (param.get(String8("target"), target) != NO_ERROR) {
  1502. target = "Manager";
  1503. }
  1504. if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
  1505. param.remove(String8("test_cmd_policy_output"));
  1506. mCurOutput = valueInt;
  1507. }
  1508. if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
  1509. param.remove(String8("test_cmd_policy_direct"));
  1510. if (value == "false") {
  1511. mDirectOutput = false;
  1512. } else if (value == "true") {
  1513. mDirectOutput = true;
  1514. }
  1515. }
  1516. if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
  1517. param.remove(String8("test_cmd_policy_input"));
  1518. mTestInput = valueInt;
  1519. }
  1520. if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
  1521. param.remove(String8("test_cmd_policy_format"));
  1522. int format = AudioSystem::INVALID_FORMAT;
  1523. if (value == "PCM 16 bits") {
  1524. format = AudioSystem::PCM_16_BIT;
  1525. } else if (value == "PCM 8 bits") {
  1526. format = AudioSystem::PCM_8_BIT;
  1527. } else if (value == "Compressed MP3") {
  1528. format = AudioSystem::MP3;
  1529. }
  1530. if (format != AudioSystem::INVALID_FORMAT) {
  1531. if (target == "Manager") {
  1532. mTestFormat = format;
  1533. } else if (mTestOutputs[mCurOutput] != 0) {
  1534. AudioParameter outputParam = AudioParameter();
  1535. outputParam.addInt(String8("format"), format);
  1536. mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
  1537. }
  1538. }
  1539. }
  1540. if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
  1541. param.remove(String8("test_cmd_policy_channels"));
  1542. int channels = 0;
  1543. if (value == "Channels Stereo") {
  1544. channels = AudioSystem::CHANNEL_OUT_STEREO;
  1545. } else if (value == "Channels Mono") {
  1546. channels = AudioSystem::CHANNEL_OUT_MONO;
  1547. }
  1548. if (channels != 0) {
  1549. if (target == "Manager") {
  1550. mTestChannels = channels;
  1551. } else if (mTestOutputs[mCurOutput] != 0) {
  1552. AudioParameter outputParam = AudioParameter();
  1553. outputParam.addInt(String8("channels"), channels);
  1554. mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
  1555. }
  1556. }
  1557. }
  1558. if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
  1559. param.remove(String8("test_cmd_policy_sampleRate"));
  1560. if (valueInt >= 0 && valueInt <= 96000) {
  1561. int samplingRate = valueInt;
  1562. if (target == "Manager") {
  1563. mTestSamplingRate = samplingRate;
  1564. } else if (mTestOutputs[mCurOutput] != 0) {
  1565. AudioParameter outputParam = AudioParameter();
  1566. outputParam.addInt(String8("sampling_rate"), samplingRate);
  1567. mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
  1568. }
  1569. }
  1570. }
  1571. if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
  1572. param.remove(String8("test_cmd_policy_reopen"));
  1573. AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
  1574. mpClientInterface->closeOutput(mPrimaryOutput);
  1575. audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
  1576. delete mOutputs.valueFor(mPrimaryOutput);
  1577. mOutputs.removeItem(mPrimaryOutput);
  1578. AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
  1579. outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
  1580. mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
  1581. &outputDesc->mDevice,
  1582. &outputDesc->mSamplingRate,
  1583. &outputDesc->mFormat,
  1584. &outputDesc->mChannelMask,
  1585. &outputDesc->mLatency,
  1586. outputDesc->mFlags);
  1587. if (mPrimaryOutput == 0) {
  1588. ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
  1589. outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
  1590. } else {
  1591. AudioParameter outputCmd = AudioParameter();
  1592. outputCmd.addInt(String8("set_id"), 0);
  1593. mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
  1594. addOutput(mPrimaryOutput, outputDesc);
  1595. }
  1596. }
  1597. mpClientInterface->setParameters(0, String8("test_cmd_policy="));
  1598. }
  1599. }
  1600. return false;
  1601. }
  1602. void AudioPolicyManagerBase::exit()
  1603. {
  1604. {
  1605. AutoMutex _l(mLock);
  1606. requestExit();
  1607. mWaitWorkCV.signal();
  1608. }
  1609. requestExitAndWait();
  1610. }
  1611. int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
  1612. {
  1613. for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
  1614. if (output == mTestOutputs[i]) return i;
  1615. }
  1616. return 0;
  1617. }
  1618. #endif //AUDIO_POLICY_TEST
  1619. // ---
  1620. void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
  1621. {
  1622. outputDesc->mId = id;
  1623. mOutputs.add(id, outputDesc);
  1624. }
  1625. void AudioPolicyManagerBase::addInput(audio_io_handle_t id, AudioInputDescriptor *inputDesc)
  1626. {
  1627. inputDesc->mId = id;
  1628. mInputs.add(id, inputDesc);
  1629. }
  1630. status_t AudioPolicyManagerBase::checkOutputsForDevice(audio_devices_t device,
  1631. AudioSystem::device_connection_state state,
  1632. SortedVector<audio_io_handle_t>& outputs,
  1633. const String8 paramStr)
  1634. {
  1635. AudioOutputDescriptor *desc;
  1636. if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
  1637. // first list already open outputs that can be routed to this device
  1638. for (size_t i = 0; i < mOutputs.size(); i++) {
  1639. desc = mOutputs.valueAt(i);
  1640. if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices & device)) {
  1641. ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
  1642. outputs.add(mOutputs.keyAt(i));
  1643. }
  1644. }
  1645. // then look for output profiles that can be routed to this device
  1646. SortedVector<IOProfile *> profiles;
  1647. for (size_t i = 0; i < mHwModules.size(); i++)
  1648. {
  1649. if (mHwModules[i]->mHandle == 0) {
  1650. continue;
  1651. }
  1652. for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
  1653. {
  1654. if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) {
  1655. ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
  1656. profiles.add(mHwModules[i]->mOutputProfiles[j]);
  1657. }
  1658. }
  1659. }
  1660. if (profiles.isEmpty() && outputs.isEmpty()) {
  1661. ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
  1662. return BAD_VALUE;
  1663. }
  1664. // open outputs for matching profiles if needed. Direct outputs are also opened to
  1665. // query for dynamic parameters and will be closed later by setDeviceConnectionState()
  1666. for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
  1667. IOProfile *profile = profiles[profile_index];
  1668. // nothing to do if one output is already opened for this profile
  1669. size_t j;
  1670. for (j = 0; j < mOutputs.size(); j++) {
  1671. desc = mOutputs.valueAt(j);
  1672. if (!desc->isDuplicated() && desc->mProfile == profile) {
  1673. break;
  1674. }
  1675. }
  1676. if (j != mOutputs.size()) {
  1677. continue;
  1678. }
  1679. ALOGV("opening output for device %08x with params %s", device, paramStr.string());
  1680. desc = new AudioOutputDescriptor(profile);
  1681. desc->mDevice = device;
  1682. audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
  1683. offloadInfo.sample_rate = desc->mSamplingRate;
  1684. offloadInfo.format = desc->mFormat;
  1685. offloadInfo.channel_mask = desc->mChannelMask;
  1686. audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
  1687. &desc->mDevice,
  1688. &desc->mSamplingRate,
  1689. &desc->mFormat,
  1690. &desc->mChannelMask,
  1691. &desc->mLatency,
  1692. desc->mFlags,
  1693. &offloadInfo);
  1694. if (output != 0) {
  1695. if (!paramStr.isEmpty()) {
  1696. // Here is where the out_set_parameters() for card & device gets called
  1697. mpClientInterface->setParameters(output, paramStr);
  1698. }
  1699. // Here is where we step through and resolve any "dynamic" fields
  1700. String8 reply;
  1701. char *value;
  1702. if (profile->mSamplingRates[0] == 0) {
  1703. reply = mpClientInterface->getParameters(output,
  1704. String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
  1705. ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
  1706. reply.string());
  1707. value = strpbrk((char *)reply.string(), "=");
  1708. if (value != NULL) {
  1709. loadSamplingRates(value + 1, profile);
  1710. }
  1711. }
  1712. if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
  1713. reply = mpClientInterface->getParameters(output,
  1714. String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
  1715. ALOGV("checkOutputsForDevice() direct output sup formats %s",
  1716. reply.string());
  1717. value = strpbrk((char *)reply.string(), "=");
  1718. if (value != NULL) {
  1719. loadFormats(value + 1, profile);
  1720. }
  1721. }
  1722. if (profile->mChannelMasks[0] == 0) {
  1723. reply = mpClientInterface->getParameters(output,
  1724. String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
  1725. ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
  1726. reply.string());
  1727. value = strpbrk((char *)reply.string(), "=");
  1728. if (value != NULL) {
  1729. loadOutChannels(value + 1, profile);
  1730. }
  1731. }
  1732. if (((profile->mSamplingRates[0] == 0) &&
  1733. (profile->mSamplingRates.size() < 2)) ||
  1734. ((profile->mFormats[0] == 0) &&
  1735. (profile->mFormats.size() < 2)) ||
  1736. ((profile->mChannelMasks[0] == 0) &&
  1737. (profile->mChannelMasks.size() < 2))) {
  1738. ALOGW("checkOutputsForDevice() direct output missing param");
  1739. mpClientInterface->closeOutput(output);
  1740. output = 0;
  1741. } else if (profile->mSamplingRates[0] == 0) {
  1742. mpClientInterface->closeOutput(output);
  1743. desc->mSamplingRate = profile->mSamplingRates[1];
  1744. offloadInfo.sample_rate = desc->mSamplingRate;
  1745. output = mpClientInterface->openOutput(
  1746. profile->mModule->mHandle,
  1747. &desc->mDevice,
  1748. &desc->mSamplingRate,
  1749. &desc->mFormat,
  1750. &desc->mChannelMask,
  1751. &desc->mLatency,
  1752. desc->mFlags,
  1753. &offloadInfo);
  1754. }
  1755. if (output != 0) {
  1756. addOutput(output, desc);
  1757. if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
  1758. audio_io_handle_t duplicatedOutput = 0;
  1759. // set initial stream volume for device
  1760. applyStreamVolumes(output, device, 0, true);
  1761. //TODO: configure audio effect output stage here
  1762. // open a duplicating output thread for the new output and the primary output
  1763. duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
  1764. mPrimaryOutput);
  1765. if (duplicatedOutput != 0) {
  1766. // add duplicated output descriptor
  1767. AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
  1768. dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
  1769. dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
  1770. dupOutputDesc->mSamplingRate = desc->mSamplingRate;
  1771. dupOutputDesc->mFormat = desc->mFormat;
  1772. dupOutputDesc->mChannelMask = desc->mChannelMask;
  1773. dupOutputDesc->mLatency = desc->mLatency;
  1774. addOutput(duplicatedOutput, dupOutputDesc);
  1775. applyStreamVolumes(duplicatedOutput, device, 0, true);
  1776. } else {
  1777. ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
  1778. mPrimaryOutput, output);
  1779. mpClientInterface->closeOutput(output);
  1780. mOutputs.removeItem(output);
  1781. output = 0;
  1782. }
  1783. }
  1784. }
  1785. }
  1786. if (output == 0) {
  1787. ALOGW("checkOutputsForDevice() could not open output for device %x", device);
  1788. delete desc;
  1789. profiles.removeAt(profile_index);
  1790. profile_index--;
  1791. } else {
  1792. outputs.add(output);
  1793. ALOGV("checkOutputsForDevice(): adding output %d", output);
  1794. }
  1795. }
  1796. if (profiles.isEmpty()) {
  1797. ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
  1798. return BAD_VALUE;
  1799. }
  1800. } else { // Disconnect
  1801. // check if one opened output is not needed any more after disconnecting one device
  1802. for (size_t i = 0; i < mOutputs.size(); i++) {
  1803. desc = mOutputs.valueAt(i);
  1804. if (!desc->isDuplicated() &&
  1805. !(desc->mProfile->mSupportedDevices & mAvailableOutputDevices)) {
  1806. ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
  1807. outputs.add(mOutputs.keyAt(i));
  1808. }
  1809. }
  1810. // Clear any profiles associated with the disconnected device.
  1811. for (size_t i = 0; i < mHwModules.size(); i++)
  1812. {
  1813. if (mHwModules[i]->mHandle == 0) {
  1814. continue;
  1815. }
  1816. for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
  1817. {
  1818. IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
  1819. if (profile->mSupportedDevices & device) {
  1820. ALOGV("checkOutputsForDevice(): clearing direct output profile %zu on module %zu",
  1821. j, i);
  1822. if (profile->mSamplingRates[0] == 0) {
  1823. profile->mSamplingRates.clear();
  1824. profile->mSamplingRates.add(0);
  1825. }
  1826. if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
  1827. profile->mFormats.clear();
  1828. profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
  1829. }
  1830. if (profile->mChannelMasks[0] == 0) {
  1831. profile->mChannelMasks.clear();
  1832. profile->mChannelMasks.add(0);
  1833. }
  1834. }
  1835. }
  1836. }
  1837. }
  1838. return NO_ERROR;
  1839. }
  1840. status_t AudioPolicyManagerBase::checkInputsForDevice(audio_devices_t device,
  1841. AudioSystem::device_connection_state state,
  1842. SortedVector<audio_io_handle_t>& inputs,
  1843. const String8 paramStr)
  1844. {
  1845. AudioInputDescriptor *desc;
  1846. if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
  1847. // first list already open inputs that can be routed to this device
  1848. for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
  1849. desc = mInputs.valueAt(input_index);
  1850. if (desc->mProfile->mSupportedDevices & (device & ~AUDIO_DEVICE_BIT_IN)) {
  1851. ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
  1852. inputs.add(mInputs.keyAt(input_index));
  1853. }
  1854. }
  1855. // then look for input profiles that can be routed to this device
  1856. SortedVector<IOProfile *> profiles;
  1857. for (size_t module_index = 0; module_index < mHwModules.size(); module_index++)
  1858. {
  1859. if (mHwModules[module_index]->mHandle == 0) {
  1860. continue;
  1861. }
  1862. for (size_t profile_index = 0;
  1863. profile_index < mHwModules[module_index]->mInputProfiles.size();
  1864. profile_index++)
  1865. {
  1866. if (mHwModules[module_index]->mInputProfiles[profile_index]->mSupportedDevices
  1867. & (device & ~AUDIO_DEVICE_BIT_IN)) {
  1868. ALOGV("checkInputsForDevice(): adding profile %d from module %d",
  1869. profile_index, module_index);
  1870. profiles.add(mHwModules[module_index]->mInputProfiles[profile_index]);
  1871. }
  1872. }
  1873. }
  1874. if (profiles.isEmpty() && inputs.isEmpty()) {
  1875. ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
  1876. return BAD_VALUE;
  1877. }
  1878. // open inputs for matching profiles if needed. Direct inputs are also opened to
  1879. // query for dynamic parameters and will be closed later by setDeviceConnectionState()
  1880. for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
  1881. IOProfile *profile = profiles[profile_index];
  1882. // nothing to do if one input is already opened for this profile
  1883. size_t input_index;
  1884. for (input_index = 0; input_index < mInputs.size(); input_index++) {
  1885. desc = mInputs.valueAt(input_index);
  1886. if (desc->mProfile == profile) {
  1887. break;
  1888. }
  1889. }
  1890. if (input_index != mInputs.size()) {
  1891. continue;
  1892. }
  1893. ALOGV("opening input for device 0x%X with params %s", device, paramStr.string());
  1894. desc = new AudioInputDescriptor(profile);
  1895. desc->mDevice = device;
  1896. audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
  1897. &desc->mDevice,
  1898. &desc->mSamplingRate,
  1899. &desc->mFormat,
  1900. &desc->mChannelMask);
  1901. if (input != 0) {
  1902. if (!paramStr.isEmpty()) {
  1903. mpClientInterface->setParameters(input, paramStr);
  1904. }
  1905. // Here is where we step through and resolve any "dynamic" fields
  1906. String8 reply;
  1907. char *value;
  1908. if (profile->mSamplingRates[0] == 0) {
  1909. reply = mpClientInterface->getParameters(input,
  1910. String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
  1911. ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
  1912. reply.string());
  1913. value = strpbrk((char *)reply.string(), "=");
  1914. if (value != NULL) {
  1915. loadSamplingRates(value + 1, profile);
  1916. }
  1917. }
  1918. if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
  1919. reply = mpClientInterface->getParameters(input,
  1920. String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
  1921. ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
  1922. value = strpbrk((char *)reply.string(), "=");
  1923. if (value != NULL) {
  1924. loadFormats(value + 1, profile);
  1925. }
  1926. }
  1927. if (profile->mChannelMasks[0] == 0) {
  1928. reply = mpClientInterface->getParameters(input,
  1929. String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
  1930. ALOGV("checkInputsForDevice() direct input sup channel masks %s",
  1931. reply.string());
  1932. value = strpbrk((char *)reply.string(), "=");
  1933. if (value != NULL) {
  1934. loadInChannels(value + 1, profile);
  1935. }
  1936. }
  1937. if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
  1938. ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
  1939. ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
  1940. ALOGW("checkInputsForDevice() direct input missing param");
  1941. mpClientInterface->closeInput(input);
  1942. input = 0;
  1943. }
  1944. if (input != 0) {
  1945. addInput(input, desc);
  1946. }
  1947. } // endif input != 0
  1948. if (input == 0) {
  1949. ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
  1950. delete desc;
  1951. profiles.removeAt(profile_index);
  1952. profile_index--;
  1953. } else {
  1954. inputs.add(input);
  1955. ALOGV("checkInputsForDevice(): adding input %d", input);
  1956. }
  1957. } // end scan profiles
  1958. if (profiles.isEmpty()) {
  1959. ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
  1960. return BAD_VALUE;
  1961. }
  1962. } else {
  1963. // Disconnect
  1964. // check if one opened input is not needed any more after disconnecting one device
  1965. for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
  1966. desc = mInputs.valueAt(input_index);
  1967. if (!(desc->mProfile->mSupportedDevices & mAvailableInputDevices)) {
  1968. ALOGV("checkInputsForDevice(): disconnecting adding input %d",
  1969. mInputs.keyAt(input_index));
  1970. inputs.add(mInputs.keyAt(input_index));
  1971. }
  1972. }
  1973. // Clear any profiles associated with the disconnected device.
  1974. for (size_t module_index = 0; module_index < mHwModules.size(); module_index++)
  1975. {
  1976. if (mHwModules[module_index]->mHandle == 0) {
  1977. continue;
  1978. }
  1979. for (size_t profile_index = 0;
  1980. profile_index < mHwModules[module_index]->mInputProfiles.size();
  1981. profile_index++)
  1982. {
  1983. IOProfile *profile = mHwModules[module_index]->mInputProfiles[profile_index];
  1984. if (profile->mSupportedDevices & device) {
  1985. ALOGV("checkInputsForDevice(): clearing direct input profile %d on module %d",
  1986. profile_index, module_index);
  1987. if (profile->mSamplingRates[0] == 0) {
  1988. profile->mSamplingRates.clear();
  1989. profile->mSamplingRates.add(0);
  1990. }
  1991. if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
  1992. profile->mFormats.clear();
  1993. profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
  1994. }
  1995. if (profile->mChannelMasks[0] == 0) {
  1996. profile->mChannelMasks.clear();
  1997. profile->mChannelMasks.add(0);
  1998. }
  1999. }
  2000. }
  2001. }
  2002. } // end disconnect
  2003. return NO_ERROR;
  2004. }
  2005. void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output)
  2006. {
  2007. ALOGV("closeOutput(%d)", output);
  2008. AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
  2009. if (outputDesc == NULL) {
  2010. ALOGW("closeOutput() unknown output %d", output);
  2011. return;
  2012. }
  2013. // look for duplicated outputs connected to the output being removed.
  2014. for (size_t i = 0; i < mOutputs.size(); i++) {
  2015. AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
  2016. if (dupOutputDesc->isDuplicated() &&
  2017. (dupOutputDesc->mOutput1 == outputDesc ||
  2018. dupOutputDesc->mOutput2 == outputDesc)) {
  2019. AudioOutputDescriptor *outputDesc2;
  2020. if (dupOutputDesc->mOutput1 == outputDesc) {
  2021. outputDesc2 = dupOutputDesc->mOutput2;
  2022. } else {
  2023. outputDesc2 = dupOutputDesc->mOutput1;
  2024. }
  2025. // As all active tracks on duplicated output will be deleted,
  2026. // and as they were also referenced on the other output, the reference
  2027. // count for their stream type must be adjusted accordingly on
  2028. // the other output.
  2029. for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) {
  2030. int refCount = dupOutputDesc->mRefCount[j];
  2031. outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount);
  2032. }
  2033. audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
  2034. ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
  2035. mpClientInterface->closeOutput(duplicatedOutput);
  2036. delete mOutputs.valueFor(duplicatedOutput);
  2037. mOutputs.removeItem(duplicatedOutput);
  2038. }
  2039. }
  2040. AudioParameter param;
  2041. param.add(String8("closing"), String8("true"));
  2042. mpClientInterface->setParameters(output, param.toString());
  2043. mpClientInterface->closeOutput(output);
  2044. delete outputDesc;
  2045. mOutputs.removeItem(output);
  2046. mPreviousOutputs = mOutputs;
  2047. }
  2048. SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device,
  2049. DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
  2050. {
  2051. SortedVector<audio_io_handle_t> outputs;
  2052. ALOGVV("getOutputsForDevice() device %04x", device);
  2053. for (size_t i = 0; i < openOutputs.size(); i++) {
  2054. ALOGVV("output %d isDuplicated=%d device=%04x",
  2055. i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
  2056. if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
  2057. ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
  2058. outputs.add(openOutputs.keyAt(i));
  2059. }
  2060. }
  2061. return outputs;
  2062. }
  2063. bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
  2064. SortedVector<audio_io_handle_t>& outputs2)
  2065. {
  2066. if (outputs1.size() != outputs2.size()) {
  2067. return false;
  2068. }
  2069. for (size_t i = 0; i < outputs1.size(); i++) {
  2070. if (outputs1[i] != outputs2[i]) {
  2071. return false;
  2072. }
  2073. }
  2074. return true;
  2075. }
  2076. void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
  2077. {
  2078. audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
  2079. audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
  2080. SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
  2081. SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
  2082. if (!vectorsEqual(srcOutputs,dstOutputs)) {
  2083. ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
  2084. strategy, srcOutputs[0], dstOutputs[0]);
  2085. // mute strategy while moving tracks from one output to another
  2086. for (size_t i = 0; i < srcOutputs.size(); i++) {
  2087. AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
  2088. if (desc->isStrategyActive(strategy)) {
  2089. setStrategyMute(strategy, true, srcOutputs[i]);
  2090. setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
  2091. }
  2092. }
  2093. // Move effects associated to this strategy from previous output to new output
  2094. if (strategy == STRATEGY_MEDIA) {
  2095. audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
  2096. SortedVector<audio_io_handle_t> moved;
  2097. for (size_t i = 0; i < mEffects.size(); i++) {
  2098. EffectDescriptor *desc = mEffects.valueAt(i);
  2099. if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
  2100. desc->mIo != fxOutput) {
  2101. if (moved.indexOf(desc->mIo) < 0) {
  2102. ALOGV("checkOutputForStrategy() moving effect %d to output %d",
  2103. mEffects.keyAt(i), fxOutput);
  2104. mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
  2105. fxOutput);
  2106. moved.add(desc->mIo);
  2107. }
  2108. desc->mIo = fxOutput;
  2109. }
  2110. }
  2111. }
  2112. // Move tracks associated to this strategy from previous output to new output
  2113. for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
  2114. if (getStrategy((AudioSystem::stream_type)i) == strategy) {
  2115. mpClientInterface->invalidateStream((AudioSystem::stream_type)i);
  2116. }
  2117. }
  2118. }
  2119. }
  2120. void AudioPolicyManagerBase::checkOutputForAllStrategies()
  2121. {
  2122. checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
  2123. checkOutputForStrategy(STRATEGY_PHONE);
  2124. checkOutputForStrategy(STRATEGY_SONIFICATION);
  2125. checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
  2126. checkOutputForStrategy(STRATEGY_MEDIA);
  2127. checkOutputForStrategy(STRATEGY_DTMF);
  2128. }
  2129. audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
  2130. {
  2131. if (!mHasA2dp) {
  2132. return 0;
  2133. }
  2134. for (size_t i = 0; i < mOutputs.size(); i++) {
  2135. AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
  2136. if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
  2137. return mOutputs.keyAt(i);
  2138. }
  2139. }
  2140. return 0;
  2141. }
  2142. void AudioPolicyManagerBase::checkA2dpSuspend()
  2143. {
  2144. if (!mHasA2dp) {
  2145. return;
  2146. }
  2147. audio_io_handle_t a2dpOutput = getA2dpOutput();
  2148. if (a2dpOutput == 0) {
  2149. return;
  2150. }
  2151. // suspend A2DP output if:
  2152. // (NOT already suspended) &&
  2153. // ((SCO device is connected &&
  2154. // (forced usage for communication || for record is SCO))) ||
  2155. // (phone state is ringing || in call)
  2156. //
  2157. // restore A2DP output if:
  2158. // (Already suspended) &&
  2159. // ((SCO device is NOT connected ||
  2160. // (forced usage NOT for communication && NOT for record is SCO))) &&
  2161. // (phone state is NOT ringing && NOT in call)
  2162. //
  2163. if (mA2dpSuspended) {
  2164. if (((mScoDeviceAddress == "") ||
  2165. ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
  2166. (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
  2167. ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
  2168. (mPhoneState != AudioSystem::MODE_RINGTONE))) {
  2169. mpClientInterface->restoreOutput(a2dpOutput);
  2170. mA2dpSuspended = false;
  2171. }
  2172. } else {
  2173. if (((mScoDeviceAddress != "") &&
  2174. ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
  2175. (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
  2176. ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
  2177. (mPhoneState == AudioSystem::MODE_RINGTONE))) {
  2178. mpClientInterface->suspendOutput(a2dpOutput);
  2179. mA2dpSuspended = true;
  2180. }
  2181. }
  2182. }
  2183. audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
  2184. {
  2185. audio_devices_t device = AUDIO_DEVICE_NONE;
  2186. AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
  2187. // check the following by order of priority to request a routing change if necessary:
  2188. // 1: the strategy enforced audible is active on the output:
  2189. // use device for strategy enforced audible
  2190. // 2: we are in call or the strategy phone is active on the output:
  2191. // use device for strategy phone
  2192. // 3: the strategy sonification is active on the output:
  2193. // use device for strategy sonification
  2194. // 4: the strategy "respectful" sonification is active on the output:
  2195. // use device for strategy "respectful" sonification
  2196. // 5: the strategy media is active on the output:
  2197. // use device for strategy media
  2198. // 6: the strategy DTMF is active on the output:
  2199. // use device for strategy DTMF
  2200. if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
  2201. device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
  2202. } else if (isInCall() ||
  2203. outputDesc->isStrategyActive(STRATEGY_PHONE)) {
  2204. device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
  2205. } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
  2206. device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
  2207. } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
  2208. device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
  2209. } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
  2210. device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
  2211. } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
  2212. device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
  2213. }
  2214. ALOGV("getNewDevice() selected device %x", device);
  2215. return device;
  2216. }
  2217. uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
  2218. return (uint32_t)getStrategy(stream);
  2219. }
  2220. audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
  2221. audio_devices_t devices;
  2222. // By checking the range of stream before calling getStrategy, we avoid
  2223. // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
  2224. // and then return STRATEGY_MEDIA, but we want to return the empty set.
  2225. if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
  2226. devices = AUDIO_DEVICE_NONE;
  2227. } else {
  2228. AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
  2229. devices = getDeviceForStrategy(strategy, true /*fromCache*/);
  2230. }
  2231. return devices;
  2232. }
  2233. AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
  2234. AudioSystem::stream_type stream) {
  2235. // stream to strategy mapping
  2236. switch (stream) {
  2237. case AudioSystem::VOICE_CALL:
  2238. case AudioSystem::BLUETOOTH_SCO:
  2239. return STRATEGY_PHONE;
  2240. case AudioSystem::RING:
  2241. case AudioSystem::ALARM:
  2242. return STRATEGY_SONIFICATION;
  2243. case AudioSystem::NOTIFICATION:
  2244. return STRATEGY_SONIFICATION_RESPECTFUL;
  2245. case AudioSystem::DTMF:
  2246. return STRATEGY_DTMF;
  2247. default:
  2248. ALOGE("unknown stream type");
  2249. case AudioSystem::SYSTEM:
  2250. // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
  2251. // while key clicks are played produces a poor result
  2252. case AudioSystem::TTS:
  2253. case AudioSystem::MUSIC:
  2254. return STRATEGY_MEDIA;
  2255. case AudioSystem::ENFORCED_AUDIBLE:
  2256. return STRATEGY_ENFORCED_AUDIBLE;
  2257. }
  2258. }
  2259. void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
  2260. switch(stream) {
  2261. case AudioSystem::MUSIC:
  2262. checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
  2263. updateDevicesAndOutputs();
  2264. break;
  2265. default:
  2266. break;
  2267. }
  2268. }
  2269. audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
  2270. bool fromCache)
  2271. {
  2272. uint32_t device = AUDIO_DEVICE_NONE;
  2273. if (fromCache) {
  2274. ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
  2275. strategy, mDeviceForStrategy[strategy]);
  2276. return mDeviceForStrategy[strategy];
  2277. }
  2278. switch (strategy) {
  2279. case STRATEGY_SONIFICATION_RESPECTFUL:
  2280. if (isInCall()) {
  2281. device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
  2282. } else if (isStreamActiveRemotely(AudioSystem::MUSIC,
  2283. SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
  2284. // while media is playing on a remote device, use the the sonification behavior.
  2285. // Note that we test this usecase before testing if media is playing because
  2286. // the isStreamActive() method only informs about the activity of a stream, not
  2287. // if it's for local playback. Note also that we use the same delay between both tests
  2288. device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
  2289. } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
  2290. // while media is playing (or has recently played), use the same device
  2291. device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
  2292. } else {
  2293. // when media is not playing anymore, fall back on the sonification behavior
  2294. device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
  2295. }
  2296. break;
  2297. case STRATEGY_DTMF:
  2298. if (!isInCall()) {
  2299. // when off call, DTMF strategy follows the same rules as MEDIA strategy
  2300. device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
  2301. break;
  2302. }
  2303. // when in call, DTMF and PHONE strategies follow the same rules
  2304. // FALL THROUGH
  2305. case STRATEGY_PHONE:
  2306. // for phone strategy, we first consider the forced use and then the available devices by order
  2307. // of priority
  2308. switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
  2309. case AudioSystem::FORCE_BT_SCO:
  2310. if (!isInCall() || strategy != STRATEGY_DTMF) {
  2311. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
  2312. if (device) break;
  2313. }
  2314. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
  2315. if (device) break;
  2316. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
  2317. if (device) break;
  2318. // if SCO device is requested but no SCO device is available, fall back to default case
  2319. // FALL THROUGH
  2320. default: // FORCE_NONE
  2321. // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
  2322. if (mHasA2dp && !isInCall() &&
  2323. (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
  2324. (getA2dpOutput() != 0) && !mA2dpSuspended) {
  2325. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
  2326. if (device) break;
  2327. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
  2328. if (device) break;
  2329. }
  2330. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
  2331. if (device) break;
  2332. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
  2333. if (device) break;
  2334. if (mPhoneState != AudioSystem::MODE_IN_CALL) {
  2335. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
  2336. if (device) break;
  2337. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
  2338. if (device) break;
  2339. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
  2340. if (device) break;
  2341. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
  2342. if (device) break;
  2343. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
  2344. if (device) break;
  2345. }
  2346. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_EARPIECE;
  2347. if (device) break;
  2348. device = mDefaultOutputDevice;
  2349. if (device == AUDIO_DEVICE_NONE) {
  2350. ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
  2351. }
  2352. break;
  2353. case AudioSystem::FORCE_SPEAKER:
  2354. // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
  2355. // A2DP speaker when forcing to speaker output
  2356. if (mHasA2dp && !isInCall() &&
  2357. (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
  2358. (getA2dpOutput() != 0) && !mA2dpSuspended) {
  2359. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
  2360. if (device) break;
  2361. }
  2362. if (mPhoneState != AudioSystem::MODE_IN_CALL) {
  2363. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
  2364. if (device) break;
  2365. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
  2366. if (device) break;
  2367. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
  2368. if (device) break;
  2369. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
  2370. if (device) break;
  2371. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
  2372. if (device) break;
  2373. }
  2374. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
  2375. if (device) break;
  2376. device = mDefaultOutputDevice;
  2377. if (device == AUDIO_DEVICE_NONE) {
  2378. ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
  2379. }
  2380. break;
  2381. }
  2382. break;
  2383. case STRATEGY_SONIFICATION:
  2384. // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
  2385. // handleIncallSonification().
  2386. if (isInCall()) {
  2387. device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
  2388. break;
  2389. }
  2390. // FALL THROUGH
  2391. case STRATEGY_ENFORCED_AUDIBLE:
  2392. // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
  2393. // except:
  2394. // - when in call where it doesn't default to STRATEGY_PHONE behavior
  2395. // - in countries where not enforced in which case it follows STRATEGY_MEDIA
  2396. if ((strategy == STRATEGY_SONIFICATION) ||
  2397. (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_SYSTEM_ENFORCED)) {
  2398. device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
  2399. if (device == AUDIO_DEVICE_NONE) {
  2400. ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
  2401. }
  2402. }
  2403. // The second device used for sonification is the same as the device used by media strategy
  2404. // FALL THROUGH
  2405. case STRATEGY_MEDIA: {
  2406. uint32_t device2 = AUDIO_DEVICE_NONE;
  2407. if (strategy != STRATEGY_SONIFICATION) {
  2408. // no sonification on remote submix (e.g. WFD)
  2409. device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
  2410. }
  2411. if ((device2 == AUDIO_DEVICE_NONE) &&
  2412. mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
  2413. (getA2dpOutput() != 0) && !mA2dpSuspended) {
  2414. device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
  2415. if (device2 == AUDIO_DEVICE_NONE) {
  2416. device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
  2417. }
  2418. if (device2 == AUDIO_DEVICE_NONE) {
  2419. device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
  2420. }
  2421. }
  2422. if (device2 == AUDIO_DEVICE_NONE) {
  2423. device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
  2424. }
  2425. if (device2 == AUDIO_DEVICE_NONE) {
  2426. device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
  2427. }
  2428. if (device2 == AUDIO_DEVICE_NONE) {
  2429. device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
  2430. }
  2431. if (device2 == AUDIO_DEVICE_NONE) {
  2432. device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
  2433. }
  2434. if (device2 == AUDIO_DEVICE_NONE) {
  2435. device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
  2436. }
  2437. if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
  2438. // no sonification on aux digital (e.g. HDMI)
  2439. device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
  2440. }
  2441. if ((device2 == AUDIO_DEVICE_NONE) &&
  2442. (mForceUse[AudioSystem::FOR_DOCK] == AudioSystem::FORCE_ANALOG_DOCK)) {
  2443. device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
  2444. }
  2445. if (device2 == AUDIO_DEVICE_NONE) {
  2446. device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
  2447. }
  2448. // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
  2449. // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
  2450. device |= device2;
  2451. if (device) break;
  2452. device = mDefaultOutputDevice;
  2453. if (device == AUDIO_DEVICE_NONE) {
  2454. ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
  2455. }
  2456. } break;
  2457. default:
  2458. ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
  2459. break;
  2460. }
  2461. ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
  2462. return device;
  2463. }
  2464. void AudioPolicyManagerBase::updateDevicesAndOutputs()
  2465. {
  2466. for (int i = 0; i < NUM_STRATEGIES; i++) {
  2467. mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
  2468. }
  2469. mPreviousOutputs = mOutputs;
  2470. }
  2471. uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
  2472. audio_devices_t prevDevice,
  2473. uint32_t delayMs)
  2474. {
  2475. // mute/unmute strategies using an incompatible device combination
  2476. // if muting, wait for the audio in pcm buffer to be drained before proceeding
  2477. // if unmuting, unmute only after the specified delay
  2478. if (outputDesc->isDuplicated()) {
  2479. return 0;
  2480. }
  2481. uint32_t muteWaitMs = 0;
  2482. audio_devices_t device = outputDesc->device();
  2483. bool shouldMute = outputDesc->isActive() && (AudioSystem::popCount(device) >= 2);
  2484. // temporary mute output if device selection changes to avoid volume bursts due to
  2485. // different per device volumes
  2486. bool tempMute = outputDesc->isActive() && (device != prevDevice);
  2487. for (size_t i = 0; i < NUM_STRATEGIES; i++) {
  2488. audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
  2489. bool mute = shouldMute && (curDevice & device) && (curDevice != device);
  2490. bool doMute = false;
  2491. if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
  2492. doMute = true;
  2493. outputDesc->mStrategyMutedByDevice[i] = true;
  2494. } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
  2495. doMute = true;
  2496. outputDesc->mStrategyMutedByDevice[i] = false;
  2497. }
  2498. if (doMute || tempMute) {
  2499. for (size_t j = 0; j < mOutputs.size(); j++) {
  2500. AudioOutputDescriptor *desc = mOutputs.valueAt(j);
  2501. // skip output if it does not share any device with current output
  2502. if ((desc->supportedDevices() & outputDesc->supportedDevices())
  2503. == AUDIO_DEVICE_NONE) {
  2504. continue;
  2505. }
  2506. audio_io_handle_t curOutput = mOutputs.keyAt(j);
  2507. ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
  2508. mute ? "muting" : "unmuting", i, curDevice, curOutput);
  2509. setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
  2510. if (desc->isStrategyActive((routing_strategy)i)) {
  2511. // do tempMute only for current output
  2512. if (tempMute && (desc == outputDesc)) {
  2513. setStrategyMute((routing_strategy)i, true, curOutput);
  2514. setStrategyMute((routing_strategy)i, false, curOutput,
  2515. desc->latency() * 2, device);
  2516. }
  2517. if ((tempMute && (desc == outputDesc)) || mute) {
  2518. if (muteWaitMs < desc->latency()) {
  2519. muteWaitMs = desc->latency();
  2520. }
  2521. }
  2522. }
  2523. }
  2524. }
  2525. }
  2526. // FIXME: should not need to double latency if volume could be applied immediately by the
  2527. // audioflinger mixer. We must account for the delay between now and the next time
  2528. // the audioflinger thread for this output will process a buffer (which corresponds to
  2529. // one buffer size, usually 1/2 or 1/4 of the latency).
  2530. muteWaitMs *= 2;
  2531. // wait for the PCM output buffers to empty before proceeding with the rest of the command
  2532. if (muteWaitMs > delayMs) {
  2533. muteWaitMs -= delayMs;
  2534. usleep(muteWaitMs * 1000);
  2535. return muteWaitMs;
  2536. }
  2537. return 0;
  2538. }
  2539. uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
  2540. audio_devices_t device,
  2541. bool force,
  2542. int delayMs)
  2543. {
  2544. ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
  2545. AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
  2546. AudioParameter param;
  2547. uint32_t muteWaitMs;
  2548. if (outputDesc->isDuplicated()) {
  2549. muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
  2550. muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
  2551. return muteWaitMs;
  2552. }
  2553. // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
  2554. // output profile
  2555. if ((device != AUDIO_DEVICE_NONE) &&
  2556. ((device & outputDesc->mProfile->mSupportedDevices) == 0)) {
  2557. return 0;
  2558. }
  2559. // filter devices according to output selected
  2560. device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
  2561. audio_devices_t prevDevice = outputDesc->mDevice;
  2562. ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
  2563. if (device != AUDIO_DEVICE_NONE) {
  2564. outputDesc->mDevice = device;
  2565. // Force routing if previously asked for this output
  2566. if (outputDesc->mForceRouting) {
  2567. ALOGV("Force routing to current device as previous device was null for this output");
  2568. force = true;
  2569. // Request consumed. Reset mForceRouting to false
  2570. outputDesc->mForceRouting = false;
  2571. }
  2572. }
  2573. else {
  2574. // Device is null and does not reflect the routing. Save the necessity to force
  2575. // re-routing upon next attempt to select a non-null device for this output
  2576. outputDesc->mForceRouting = true;
  2577. }
  2578. muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
  2579. // Do not change the routing if:
  2580. // - the requested device is AUDIO_DEVICE_NONE
  2581. // - the requested device is the same as current device and force is not specified.
  2582. // Doing this check here allows the caller to call setOutputDevice() without conditions
  2583. if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
  2584. ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
  2585. return muteWaitMs;
  2586. }
  2587. ALOGV("setOutputDevice() changing device");
  2588. // do the routing
  2589. param.addInt(String8(AudioParameter::keyRouting), (int)device);
  2590. mpClientInterface->setParameters(output, param.toString(), delayMs);
  2591. // update stream volumes according to new device
  2592. applyStreamVolumes(output, device, delayMs);
  2593. return muteWaitMs;
  2594. }
  2595. AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
  2596. uint32_t samplingRate,
  2597. audio_format_t format,
  2598. audio_channel_mask_t channelMask)
  2599. {
  2600. // Choose an input profile based on the requested capture parameters: select the first available
  2601. // profile supporting all requested parameters.
  2602. for (size_t i = 0; i < mHwModules.size(); i++)
  2603. {
  2604. if (mHwModules[i]->mHandle == 0) {
  2605. continue;
  2606. }
  2607. for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
  2608. {
  2609. IOProfile *profile = mHwModules[i]->mInputProfiles[j];
  2610. // profile->log();
  2611. if (profile->isCompatibleProfile(device, samplingRate, format,
  2612. channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
  2613. return profile;
  2614. }
  2615. }
  2616. }
  2617. return NULL;
  2618. }
  2619. audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
  2620. {
  2621. uint32_t device = AUDIO_DEVICE_NONE;
  2622. switch (inputSource) {
  2623. case AUDIO_SOURCE_VOICE_UPLINK:
  2624. if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
  2625. device = AUDIO_DEVICE_IN_VOICE_CALL;
  2626. break;
  2627. }
  2628. // FALL THROUGH
  2629. case AUDIO_SOURCE_DEFAULT:
  2630. case AUDIO_SOURCE_MIC:
  2631. if (mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
  2632. device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
  2633. break;
  2634. }
  2635. // FALL THROUGH
  2636. case AUDIO_SOURCE_VOICE_RECOGNITION:
  2637. case AUDIO_SOURCE_HOTWORD:
  2638. case AUDIO_SOURCE_VOICE_COMMUNICATION:
  2639. if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
  2640. mAvailableInputDevices & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
  2641. device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
  2642. } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_WIRED_HEADSET) {
  2643. device = AUDIO_DEVICE_IN_WIRED_HEADSET;
  2644. } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_USB_DEVICE) {
  2645. device = AUDIO_DEVICE_IN_USB_DEVICE;
  2646. } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
  2647. device = AUDIO_DEVICE_IN_BUILTIN_MIC;
  2648. }
  2649. break;
  2650. case AUDIO_SOURCE_CAMCORDER:
  2651. if (mAvailableInputDevices & AUDIO_DEVICE_IN_BACK_MIC) {
  2652. device = AUDIO_DEVICE_IN_BACK_MIC;
  2653. } else if (mAvailableInputDevices & AUDIO_DEVICE_IN_BUILTIN_MIC) {
  2654. device = AUDIO_DEVICE_IN_BUILTIN_MIC;
  2655. }
  2656. break;
  2657. case AUDIO_SOURCE_VOICE_DOWNLINK:
  2658. case AUDIO_SOURCE_VOICE_CALL:
  2659. if (mAvailableInputDevices & AUDIO_DEVICE_IN_VOICE_CALL) {
  2660. device = AUDIO_DEVICE_IN_VOICE_CALL;
  2661. }
  2662. break;
  2663. case AUDIO_SOURCE_REMOTE_SUBMIX:
  2664. if (mAvailableInputDevices & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
  2665. device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
  2666. }
  2667. break;
  2668. default:
  2669. ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
  2670. break;
  2671. }
  2672. ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
  2673. return device;
  2674. }
  2675. bool AudioPolicyManagerBase::isVirtualInputDevice(audio_devices_t device)
  2676. {
  2677. if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
  2678. device &= ~AUDIO_DEVICE_BIT_IN;
  2679. if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
  2680. return true;
  2681. }
  2682. return false;
  2683. }
  2684. audio_io_handle_t AudioPolicyManagerBase::getActiveInput(bool ignoreVirtualInputs)
  2685. {
  2686. for (size_t i = 0; i < mInputs.size(); i++) {
  2687. const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
  2688. if ((input_descriptor->mRefCount > 0)
  2689. && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
  2690. return mInputs.keyAt(i);
  2691. }
  2692. }
  2693. return 0;
  2694. }
  2695. audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
  2696. {
  2697. if (device == AUDIO_DEVICE_NONE) {
  2698. // this happens when forcing a route update and no track is active on an output.
  2699. // In this case the returned category is not important.
  2700. device = AUDIO_DEVICE_OUT_SPEAKER;
  2701. } else if (AudioSystem::popCount(device) > 1) {
  2702. // Multiple device selection is either:
  2703. // - speaker + one other device: give priority to speaker in this case.
  2704. // - one A2DP device + another device: happens with duplicated output. In this case
  2705. // retain the device on the A2DP output as the other must not correspond to an active
  2706. // selection if not the speaker.
  2707. if (device & AUDIO_DEVICE_OUT_SPEAKER) {
  2708. device = AUDIO_DEVICE_OUT_SPEAKER;
  2709. } else {
  2710. device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
  2711. }
  2712. }
  2713. ALOGW_IF(AudioSystem::popCount(device) != 1,
  2714. "getDeviceForVolume() invalid device combination: %08x",
  2715. device);
  2716. return device;
  2717. }
  2718. AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
  2719. {
  2720. switch(getDeviceForVolume(device)) {
  2721. case AUDIO_DEVICE_OUT_EARPIECE:
  2722. return DEVICE_CATEGORY_EARPIECE;
  2723. case AUDIO_DEVICE_OUT_WIRED_HEADSET:
  2724. case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
  2725. case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
  2726. case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
  2727. case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
  2728. case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
  2729. return DEVICE_CATEGORY_HEADSET;
  2730. case AUDIO_DEVICE_OUT_SPEAKER:
  2731. case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
  2732. case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
  2733. case AUDIO_DEVICE_OUT_AUX_DIGITAL:
  2734. case AUDIO_DEVICE_OUT_USB_ACCESSORY:
  2735. case AUDIO_DEVICE_OUT_USB_DEVICE:
  2736. case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
  2737. default:
  2738. return DEVICE_CATEGORY_SPEAKER;
  2739. }
  2740. }
  2741. float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
  2742. int indexInUi)
  2743. {
  2744. device_category deviceCategory = getDeviceCategory(device);
  2745. const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
  2746. // the volume index in the UI is relative to the min and max volume indices for this stream type
  2747. int nbSteps = 1 + curve[VOLMAX].mIndex -
  2748. curve[VOLMIN].mIndex;
  2749. int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
  2750. (streamDesc.mIndexMax - streamDesc.mIndexMin);
  2751. // find what part of the curve this index volume belongs to, or if it's out of bounds
  2752. int segment = 0;
  2753. if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
  2754. return 0.0f;
  2755. } else if (volIdx < curve[VOLKNEE1].mIndex) {
  2756. segment = 0;
  2757. } else if (volIdx < curve[VOLKNEE2].mIndex) {
  2758. segment = 1;
  2759. } else if (volIdx <= curve[VOLMAX].mIndex) {
  2760. segment = 2;
  2761. } else { // out of bounds
  2762. return 1.0f;
  2763. }
  2764. // linear interpolation in the attenuation table in dB
  2765. float decibels = curve[segment].mDBAttenuation +
  2766. ((float)(volIdx - curve[segment].mIndex)) *
  2767. ( (curve[segment+1].mDBAttenuation -
  2768. curve[segment].mDBAttenuation) /
  2769. ((float)(curve[segment+1].mIndex -
  2770. curve[segment].mIndex)) );
  2771. float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
  2772. ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
  2773. curve[segment].mIndex, volIdx,
  2774. curve[segment+1].mIndex,
  2775. curve[segment].mDBAttenuation,
  2776. decibels,
  2777. curve[segment+1].mDBAttenuation,
  2778. amplification);
  2779. return amplification;
  2780. }
  2781. const AudioPolicyManagerBase::VolumeCurvePoint
  2782. AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
  2783. {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
  2784. };
  2785. const AudioPolicyManagerBase::VolumeCurvePoint
  2786. AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
  2787. {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
  2788. };
  2789. const AudioPolicyManagerBase::VolumeCurvePoint
  2790. AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
  2791. {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
  2792. };
  2793. const AudioPolicyManagerBase::VolumeCurvePoint
  2794. AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
  2795. {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
  2796. };
  2797. const AudioPolicyManagerBase::VolumeCurvePoint
  2798. AudioPolicyManagerBase::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManagerBase::VOLCNT] = {
  2799. {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
  2800. };
  2801. // AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
  2802. // AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
  2803. // AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
  2804. // The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
  2805. const AudioPolicyManagerBase::VolumeCurvePoint
  2806. AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
  2807. {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
  2808. };
  2809. const AudioPolicyManagerBase::VolumeCurvePoint
  2810. AudioPolicyManagerBase::sDefaultSystemVolumeCurveDrc[AudioPolicyManagerBase::VOLCNT] = {
  2811. {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
  2812. };
  2813. const AudioPolicyManagerBase::VolumeCurvePoint
  2814. AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
  2815. {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
  2816. };
  2817. const AudioPolicyManagerBase::VolumeCurvePoint
  2818. AudioPolicyManagerBase::sDefaultVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
  2819. {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
  2820. };
  2821. const AudioPolicyManagerBase::VolumeCurvePoint
  2822. AudioPolicyManagerBase::sSpeakerVoiceVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
  2823. {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
  2824. };
  2825. const AudioPolicyManagerBase::VolumeCurvePoint
  2826. *AudioPolicyManagerBase::sVolumeProfiles[AudioSystem::NUM_STREAM_TYPES]
  2827. [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
  2828. { // AUDIO_STREAM_VOICE_CALL
  2829. sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
  2830. sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
  2831. sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
  2832. },
  2833. { // AUDIO_STREAM_SYSTEM
  2834. sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
  2835. sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
  2836. sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
  2837. },
  2838. { // AUDIO_STREAM_RING
  2839. sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
  2840. sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
  2841. sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
  2842. },
  2843. { // AUDIO_STREAM_MUSIC
  2844. sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
  2845. sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
  2846. sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
  2847. },
  2848. { // AUDIO_STREAM_ALARM
  2849. sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
  2850. sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
  2851. sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
  2852. },
  2853. { // AUDIO_STREAM_NOTIFICATION
  2854. sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
  2855. sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
  2856. sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
  2857. },
  2858. { // AUDIO_STREAM_BLUETOOTH_SCO
  2859. sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
  2860. sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
  2861. sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
  2862. },
  2863. { // AUDIO_STREAM_ENFORCED_AUDIBLE
  2864. sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
  2865. sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
  2866. sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
  2867. },
  2868. { // AUDIO_STREAM_DTMF
  2869. sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
  2870. sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
  2871. sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
  2872. },
  2873. { // AUDIO_STREAM_TTS
  2874. sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
  2875. sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
  2876. sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
  2877. },
  2878. };
  2879. void AudioPolicyManagerBase::initializeVolumeCurves()
  2880. {
  2881. for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
  2882. for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
  2883. mStreams[i].mVolumeCurve[j] =
  2884. sVolumeProfiles[i][j];
  2885. }
  2886. }
  2887. // Check availability of DRC on speaker path: if available, override some of the speaker curves
  2888. if (mSpeakerDrcEnabled) {
  2889. mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
  2890. sDefaultSystemVolumeCurveDrc;
  2891. mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
  2892. sSpeakerSonificationVolumeCurveDrc;
  2893. mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
  2894. sSpeakerSonificationVolumeCurveDrc;
  2895. mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
  2896. sSpeakerSonificationVolumeCurveDrc;
  2897. }
  2898. }
  2899. float AudioPolicyManagerBase::computeVolume(int stream,
  2900. int index,
  2901. audio_io_handle_t output,
  2902. audio_devices_t device)
  2903. {
  2904. float volume = 1.0;
  2905. AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
  2906. StreamDescriptor &streamDesc = mStreams[stream];
  2907. if (device == AUDIO_DEVICE_NONE) {
  2908. device = outputDesc->device();
  2909. }
  2910. // if volume is not 0 (not muted), force media volume to max on digital output
  2911. if (stream == AudioSystem::MUSIC &&
  2912. index != mStreams[stream].mIndexMin &&
  2913. (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
  2914. device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET)) {
  2915. return 1.0;
  2916. }
  2917. volume = volIndexToAmpl(device, streamDesc, index);
  2918. // if a headset is connected, apply the following rules to ring tones and notifications
  2919. // to avoid sound level bursts in user's ears:
  2920. // - always attenuate ring tones and notifications volume by 6dB
  2921. // - if music is playing, always limit the volume to current music volume,
  2922. // with a minimum threshold at -36dB so that notification is always perceived.
  2923. const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
  2924. if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
  2925. AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
  2926. AUDIO_DEVICE_OUT_WIRED_HEADSET |
  2927. AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
  2928. ((stream_strategy == STRATEGY_SONIFICATION)
  2929. || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
  2930. || (stream == AudioSystem::SYSTEM)
  2931. || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
  2932. (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) &&
  2933. streamDesc.mCanBeMuted) {
  2934. volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
  2935. // when the phone is ringing we must consider that music could have been paused just before
  2936. // by the music application and behave as if music was active if the last music track was
  2937. // just stopped
  2938. if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
  2939. mLimitRingtoneVolume) {
  2940. audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
  2941. float musicVol = computeVolume(AudioSystem::MUSIC,
  2942. mStreams[AudioSystem::MUSIC].getVolumeIndex(musicDevice),
  2943. output,
  2944. musicDevice);
  2945. float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
  2946. musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
  2947. if (volume > minVol) {
  2948. volume = minVol;
  2949. ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
  2950. }
  2951. }
  2952. }
  2953. return volume;
  2954. }
  2955. status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
  2956. int index,
  2957. audio_io_handle_t output,
  2958. audio_devices_t device,
  2959. int delayMs,
  2960. bool force)
  2961. {
  2962. // do not change actual stream volume if the stream is muted
  2963. if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
  2964. ALOGVV("checkAndSetVolume() stream %d muted count %d",
  2965. stream, mOutputs.valueFor(output)->mMuteCount[stream]);
  2966. return NO_ERROR;
  2967. }
  2968. // do not change in call volume if bluetooth is connected and vice versa
  2969. if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
  2970. (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
  2971. ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
  2972. stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
  2973. return INVALID_OPERATION;
  2974. }
  2975. float volume = computeVolume(stream, index, output, device);
  2976. // We actually change the volume if:
  2977. // - the float value returned by computeVolume() changed
  2978. // - the force flag is set
  2979. if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
  2980. force) {
  2981. mOutputs.valueFor(output)->mCurVolume[stream] = volume;
  2982. ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
  2983. // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
  2984. // enabled
  2985. if (stream == AudioSystem::BLUETOOTH_SCO) {
  2986. mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
  2987. }
  2988. mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
  2989. }
  2990. if (stream == AudioSystem::VOICE_CALL ||
  2991. stream == AudioSystem::BLUETOOTH_SCO) {
  2992. float voiceVolume;
  2993. // Force voice volume to max for bluetooth SCO as volume is managed by the headset
  2994. if (stream == AudioSystem::VOICE_CALL) {
  2995. voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
  2996. } else {
  2997. voiceVolume = 1.0;
  2998. }
  2999. if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
  3000. mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
  3001. mLastVoiceVolume = voiceVolume;
  3002. }
  3003. }
  3004. return NO_ERROR;
  3005. }
  3006. void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
  3007. audio_devices_t device,
  3008. int delayMs,
  3009. bool force)
  3010. {
  3011. ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
  3012. for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
  3013. checkAndSetVolume(stream,
  3014. mStreams[stream].getVolumeIndex(device),
  3015. output,
  3016. device,
  3017. delayMs,
  3018. force);
  3019. }
  3020. }
  3021. void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy,
  3022. bool on,
  3023. audio_io_handle_t output,
  3024. int delayMs,
  3025. audio_devices_t device)
  3026. {
  3027. ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
  3028. for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
  3029. if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
  3030. setStreamMute(stream, on, output, delayMs, device);
  3031. }
  3032. }
  3033. }
  3034. void AudioPolicyManagerBase::setStreamMute(int stream,
  3035. bool on,
  3036. audio_io_handle_t output,
  3037. int delayMs,
  3038. audio_devices_t device)
  3039. {
  3040. StreamDescriptor &streamDesc = mStreams[stream];
  3041. AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
  3042. if (device == AUDIO_DEVICE_NONE) {
  3043. device = outputDesc->device();
  3044. }
  3045. ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
  3046. stream, on, output, outputDesc->mMuteCount[stream], device);
  3047. if (on) {
  3048. if (outputDesc->mMuteCount[stream] == 0) {
  3049. if (streamDesc.mCanBeMuted &&
  3050. ((stream != AudioSystem::ENFORCED_AUDIBLE) ||
  3051. (mForceUse[AudioSystem::FOR_SYSTEM] == AudioSystem::FORCE_NONE))) {
  3052. checkAndSetVolume(stream, 0, output, device, delayMs);
  3053. }
  3054. }
  3055. // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
  3056. outputDesc->mMuteCount[stream]++;
  3057. } else {
  3058. if (outputDesc->mMuteCount[stream] == 0) {
  3059. ALOGV("setStreamMute() unmuting non muted stream!");
  3060. return;
  3061. }
  3062. if (--outputDesc->mMuteCount[stream] == 0) {
  3063. checkAndSetVolume(stream,
  3064. streamDesc.getVolumeIndex(device),
  3065. output,
  3066. device,
  3067. delayMs);
  3068. }
  3069. }
  3070. }
  3071. void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
  3072. {
  3073. // if the stream pertains to sonification strategy and we are in call we must
  3074. // mute the stream if it is low visibility. If it is high visibility, we must play a tone
  3075. // in the device used for phone strategy and play the tone if the selected device does not
  3076. // interfere with the device used for phone strategy
  3077. // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
  3078. // many times as there are active tracks on the output
  3079. const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
  3080. if ((stream_strategy == STRATEGY_SONIFICATION) ||
  3081. ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
  3082. AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
  3083. ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
  3084. stream, starting, outputDesc->mDevice, stateChange);
  3085. if (outputDesc->mRefCount[stream]) {
  3086. int muteCount = 1;
  3087. if (stateChange) {
  3088. muteCount = outputDesc->mRefCount[stream];
  3089. }
  3090. if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
  3091. ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
  3092. for (int i = 0; i < muteCount; i++) {
  3093. setStreamMute(stream, starting, mPrimaryOutput);
  3094. }
  3095. } else {
  3096. ALOGV("handleIncallSonification() high visibility");
  3097. if (outputDesc->device() &
  3098. getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
  3099. ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
  3100. for (int i = 0; i < muteCount; i++) {
  3101. setStreamMute(stream, starting, mPrimaryOutput);
  3102. }
  3103. }
  3104. if (starting) {
  3105. mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
  3106. } else {
  3107. mpClientInterface->stopTone();
  3108. }
  3109. }
  3110. }
  3111. }
  3112. }
  3113. bool AudioPolicyManagerBase::isInCall()
  3114. {
  3115. return isStateInCall(mPhoneState);
  3116. }
  3117. bool AudioPolicyManagerBase::isStateInCall(int state) {
  3118. return ((state == AudioSystem::MODE_IN_CALL) ||
  3119. (state == AudioSystem::MODE_IN_COMMUNICATION));
  3120. }
  3121. uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
  3122. {
  3123. return MAX_EFFECTS_CPU_LOAD;
  3124. }
  3125. uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
  3126. {
  3127. return MAX_EFFECTS_MEMORY;
  3128. }
  3129. // --- AudioOutputDescriptor class implementation
  3130. AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
  3131. const IOProfile *profile)
  3132. : mId(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT),
  3133. mChannelMask(0), mLatency(0),
  3134. mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE),
  3135. mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0),
  3136. mForceRouting(false)
  3137. {
  3138. // clear usage count for all stream types
  3139. for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
  3140. mRefCount[i] = 0;
  3141. mCurVolume[i] = -1.0;
  3142. mMuteCount[i] = 0;
  3143. mStopTime[i] = 0;
  3144. }
  3145. for (int i = 0; i < NUM_STRATEGIES; i++) {
  3146. mStrategyMutedByDevice[i] = false;
  3147. }
  3148. if (profile != NULL) {
  3149. mSamplingRate = profile->mSamplingRates[0];
  3150. mFormat = profile->mFormats[0];
  3151. mChannelMask = profile->mChannelMasks[0];
  3152. mFlags = profile->mFlags;
  3153. }
  3154. }
  3155. audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device() const
  3156. {
  3157. if (isDuplicated()) {
  3158. return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
  3159. } else {
  3160. return mDevice;
  3161. }
  3162. }
  3163. uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
  3164. {
  3165. if (isDuplicated()) {
  3166. return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
  3167. } else {
  3168. return mLatency;
  3169. }
  3170. }
  3171. bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
  3172. const AudioOutputDescriptor *outputDesc)
  3173. {
  3174. if (isDuplicated()) {
  3175. return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
  3176. } else if (outputDesc->isDuplicated()){
  3177. return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
  3178. } else {
  3179. return (mProfile->mModule == outputDesc->mProfile->mModule);
  3180. }
  3181. }
  3182. void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
  3183. {
  3184. // forward usage count change to attached outputs
  3185. if (isDuplicated()) {
  3186. mOutput1->changeRefCount(stream, delta);
  3187. mOutput2->changeRefCount(stream, delta);
  3188. }
  3189. if ((delta + (int)mRefCount[stream]) < 0) {
  3190. ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
  3191. mRefCount[stream] = 0;
  3192. return;
  3193. }
  3194. mRefCount[stream] += delta;
  3195. ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
  3196. }
  3197. audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
  3198. {
  3199. if (isDuplicated()) {
  3200. return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
  3201. } else {
  3202. return mProfile->mSupportedDevices ;
  3203. }
  3204. }
  3205. bool AudioPolicyManagerBase::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
  3206. {
  3207. return isStrategyActive(NUM_STRATEGIES, inPastMs);
  3208. }
  3209. bool AudioPolicyManagerBase::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
  3210. uint32_t inPastMs,
  3211. nsecs_t sysTime) const
  3212. {
  3213. if ((sysTime == 0) && (inPastMs != 0)) {
  3214. sysTime = systemTime();
  3215. }
  3216. for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
  3217. if (((getStrategy((AudioSystem::stream_type)i) == strategy) ||
  3218. (NUM_STRATEGIES == strategy)) &&
  3219. isStreamActive((AudioSystem::stream_type)i, inPastMs, sysTime)) {
  3220. return true;
  3221. }
  3222. }
  3223. return false;
  3224. }
  3225. bool AudioPolicyManagerBase::AudioOutputDescriptor::isStreamActive(AudioSystem::stream_type stream,
  3226. uint32_t inPastMs,
  3227. nsecs_t sysTime) const
  3228. {
  3229. if (mRefCount[stream] != 0) {
  3230. return true;
  3231. }
  3232. if (inPastMs == 0) {
  3233. return false;
  3234. }
  3235. if (sysTime == 0) {
  3236. sysTime = systemTime();
  3237. }
  3238. if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
  3239. return true;
  3240. }
  3241. return false;
  3242. }
  3243. status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
  3244. {
  3245. const size_t SIZE = 256;
  3246. char buffer[SIZE];
  3247. String8 result;
  3248. snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
  3249. result.append(buffer);
  3250. snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
  3251. result.append(buffer);
  3252. snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
  3253. result.append(buffer);
  3254. snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
  3255. result.append(buffer);
  3256. snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
  3257. result.append(buffer);
  3258. snprintf(buffer, SIZE, " Devices %08x\n", device());
  3259. result.append(buffer);
  3260. snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
  3261. result.append(buffer);
  3262. for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
  3263. snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
  3264. result.append(buffer);
  3265. }
  3266. write(fd, result.string(), result.size());
  3267. return NO_ERROR;
  3268. }
  3269. // --- AudioInputDescriptor class implementation
  3270. AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
  3271. : mId(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT), mChannelMask(0),
  3272. mDevice(AUDIO_DEVICE_NONE), mRefCount(0),
  3273. mInputSource(0), mProfile(profile)
  3274. {
  3275. if (profile != NULL) {
  3276. mSamplingRate = profile->mSamplingRates[0];
  3277. mFormat = profile->mFormats[0];
  3278. mChannelMask = profile->mChannelMasks[0];
  3279. }
  3280. }
  3281. status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
  3282. {
  3283. const size_t SIZE = 256;
  3284. char buffer[SIZE];
  3285. String8 result;
  3286. snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
  3287. result.append(buffer);
  3288. snprintf(buffer, SIZE, " Format: %d\n", mFormat);
  3289. result.append(buffer);
  3290. snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
  3291. result.append(buffer);
  3292. snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
  3293. result.append(buffer);
  3294. snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
  3295. result.append(buffer);
  3296. write(fd, result.string(), result.size());
  3297. return NO_ERROR;
  3298. }
  3299. // --- StreamDescriptor class implementation
  3300. AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
  3301. : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
  3302. {
  3303. mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
  3304. }
  3305. int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
  3306. {
  3307. device = AudioPolicyManagerBase::getDeviceForVolume(device);
  3308. // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
  3309. if (mIndexCur.indexOfKey(device) < 0) {
  3310. device = AUDIO_DEVICE_OUT_DEFAULT;
  3311. }
  3312. return mIndexCur.valueFor(device);
  3313. }
  3314. void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
  3315. {
  3316. const size_t SIZE = 256;
  3317. char buffer[SIZE];
  3318. String8 result;
  3319. snprintf(buffer, SIZE, "%s %02d %02d ",
  3320. mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
  3321. result.append(buffer);
  3322. for (size_t i = 0; i < mIndexCur.size(); i++) {
  3323. snprintf(buffer, SIZE, "%04x : %02d, ",
  3324. mIndexCur.keyAt(i),
  3325. mIndexCur.valueAt(i));
  3326. result.append(buffer);
  3327. }
  3328. result.append("\n");
  3329. write(fd, result.string(), result.size());
  3330. }
  3331. // --- EffectDescriptor class implementation
  3332. status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
  3333. {
  3334. const size_t SIZE = 256;
  3335. char buffer[SIZE];
  3336. String8 result;
  3337. snprintf(buffer, SIZE, " I/O: %d\n", mIo);
  3338. result.append(buffer);
  3339. snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
  3340. result.append(buffer);
  3341. snprintf(buffer, SIZE, " Session: %d\n", mSession);
  3342. result.append(buffer);
  3343. snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
  3344. result.append(buffer);
  3345. snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
  3346. result.append(buffer);
  3347. write(fd, result.string(), result.size());
  3348. return NO_ERROR;
  3349. }
  3350. // --- IOProfile class implementation
  3351. AudioPolicyManagerBase::HwModule::HwModule(const char *name)
  3352. : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
  3353. {
  3354. }
  3355. AudioPolicyManagerBase::HwModule::~HwModule()
  3356. {
  3357. for (size_t i = 0; i < mOutputProfiles.size(); i++) {
  3358. delete mOutputProfiles[i];
  3359. }
  3360. for (size_t i = 0; i < mInputProfiles.size(); i++) {
  3361. delete mInputProfiles[i];
  3362. }
  3363. free((void *)mName);
  3364. }
  3365. void AudioPolicyManagerBase::HwModule::dump(int fd)
  3366. {
  3367. const size_t SIZE = 256;
  3368. char buffer[SIZE];
  3369. String8 result;
  3370. snprintf(buffer, SIZE, " - name: %s\n", mName);
  3371. result.append(buffer);
  3372. snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
  3373. result.append(buffer);
  3374. write(fd, result.string(), result.size());
  3375. if (mOutputProfiles.size()) {
  3376. write(fd, " - outputs:\n", strlen(" - outputs:\n"));
  3377. for (size_t i = 0; i < mOutputProfiles.size(); i++) {
  3378. snprintf(buffer, SIZE, " output %zu:\n", i);
  3379. write(fd, buffer, strlen(buffer));
  3380. mOutputProfiles[i]->dump(fd);
  3381. }
  3382. }
  3383. if (mInputProfiles.size()) {
  3384. write(fd, " - inputs:\n", strlen(" - inputs:\n"));
  3385. for (size_t i = 0; i < mInputProfiles.size(); i++) {
  3386. snprintf(buffer, SIZE, " input %zu:\n", i);
  3387. write(fd, buffer, strlen(buffer));
  3388. mInputProfiles[i]->dump(fd);
  3389. }
  3390. }
  3391. }
  3392. AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module)
  3393. : mFlags((audio_output_flags_t)0), mModule(module)
  3394. {
  3395. }
  3396. AudioPolicyManagerBase::IOProfile::~IOProfile()
  3397. {
  3398. }
  3399. // checks if the IO profile is compatible with specified parameters.
  3400. // Sampling rate, format and channel mask must be specified in order to
  3401. // get a valid a match
  3402. bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device,
  3403. uint32_t samplingRate,
  3404. audio_format_t format,
  3405. audio_channel_mask_t channelMask,
  3406. audio_output_flags_t flags) const
  3407. {
  3408. if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
  3409. return false;
  3410. }
  3411. if ((mSupportedDevices & device) != device) {
  3412. return false;
  3413. }
  3414. if ((mFlags & flags) != flags) {
  3415. return false;
  3416. }
  3417. size_t i;
  3418. for (i = 0; i < mSamplingRates.size(); i++)
  3419. {
  3420. if (mSamplingRates[i] == samplingRate) {
  3421. break;
  3422. }
  3423. }
  3424. if (i == mSamplingRates.size()) {
  3425. return false;
  3426. }
  3427. for (i = 0; i < mFormats.size(); i++)
  3428. {
  3429. if (mFormats[i] == format) {
  3430. break;
  3431. }
  3432. }
  3433. if (i == mFormats.size()) {
  3434. return false;
  3435. }
  3436. for (i = 0; i < mChannelMasks.size(); i++)
  3437. {
  3438. if (mChannelMasks[i] == channelMask) {
  3439. break;
  3440. }
  3441. }
  3442. if (i == mChannelMasks.size()) {
  3443. return false;
  3444. }
  3445. return true;
  3446. }
  3447. void AudioPolicyManagerBase::IOProfile::dump(int fd)
  3448. {
  3449. const size_t SIZE = 256;
  3450. char buffer[SIZE];
  3451. String8 result;
  3452. snprintf(buffer, SIZE, " - sampling rates: ");
  3453. result.append(buffer);
  3454. for (size_t i = 0; i < mSamplingRates.size(); i++) {
  3455. snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
  3456. result.append(buffer);
  3457. result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
  3458. }
  3459. snprintf(buffer, SIZE, " - channel masks: ");
  3460. result.append(buffer);
  3461. for (size_t i = 0; i < mChannelMasks.size(); i++) {
  3462. snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
  3463. result.append(buffer);
  3464. result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
  3465. }
  3466. snprintf(buffer, SIZE, " - formats: ");
  3467. result.append(buffer);
  3468. for (size_t i = 0; i < mFormats.size(); i++) {
  3469. snprintf(buffer, SIZE, "0x%08x", mFormats[i]);
  3470. result.append(buffer);
  3471. result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
  3472. }
  3473. snprintf(buffer, SIZE, " - devices: 0x%04x\n", mSupportedDevices);
  3474. result.append(buffer);
  3475. snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
  3476. result.append(buffer);
  3477. write(fd, result.string(), result.size());
  3478. }
  3479. void AudioPolicyManagerBase::IOProfile::log()
  3480. {
  3481. const size_t SIZE = 256;
  3482. char buffer[SIZE];
  3483. String8 result;
  3484. ALOGV(" - sampling rates: ");
  3485. for (size_t i = 0; i < mSamplingRates.size(); i++) {
  3486. ALOGV(" %d", mSamplingRates[i]);
  3487. }
  3488. ALOGV(" - channel masks: ");
  3489. for (size_t i = 0; i < mChannelMasks.size(); i++) {
  3490. ALOGV(" 0x%04x", mChannelMasks[i]);
  3491. }
  3492. ALOGV(" - formats: ");
  3493. for (size_t i = 0; i < mFormats.size(); i++) {
  3494. ALOGV(" 0x%08x", mFormats[i]);
  3495. }
  3496. ALOGV(" - devices: 0x%04x\n", mSupportedDevices);
  3497. ALOGV(" - flags: 0x%04x\n", mFlags);
  3498. }
  3499. // --- audio_policy.conf file parsing
  3500. struct StringToEnum {
  3501. const char *name;
  3502. uint32_t value;
  3503. };
  3504. #define STRING_TO_ENUM(string) { #string, string }
  3505. #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
  3506. const struct StringToEnum sDeviceNameToEnumTable[] = {
  3507. STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
  3508. STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
  3509. STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
  3510. STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
  3511. STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
  3512. STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
  3513. STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
  3514. STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
  3515. STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
  3516. STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
  3517. STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
  3518. STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
  3519. STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
  3520. STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
  3521. STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
  3522. STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
  3523. STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
  3524. STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
  3525. STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
  3526. STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
  3527. STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
  3528. STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
  3529. STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
  3530. STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
  3531. STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
  3532. };
  3533. const struct StringToEnum sFlagNameToEnumTable[] = {
  3534. STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
  3535. STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
  3536. STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
  3537. STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
  3538. STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
  3539. STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
  3540. };
  3541. const struct StringToEnum sFormatNameToEnumTable[] = {
  3542. STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
  3543. STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
  3544. STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
  3545. STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
  3546. STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
  3547. STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
  3548. STRING_TO_ENUM(AUDIO_FORMAT_MP3),
  3549. STRING_TO_ENUM(AUDIO_FORMAT_AAC),
  3550. STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
  3551. STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
  3552. STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
  3553. STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
  3554. STRING_TO_ENUM(AUDIO_FORMAT_AC3),
  3555. STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
  3556. };
  3557. const struct StringToEnum sOutChannelsNameToEnumTable[] = {
  3558. STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
  3559. STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
  3560. STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
  3561. STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
  3562. };
  3563. const struct StringToEnum sInChannelsNameToEnumTable[] = {
  3564. STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
  3565. STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
  3566. STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
  3567. };
  3568. uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
  3569. size_t size,
  3570. const char *name)
  3571. {
  3572. for (size_t i = 0; i < size; i++) {
  3573. if (strcmp(table[i].name, name) == 0) {
  3574. ALOGV("stringToEnum() found %s", table[i].name);
  3575. return table[i].value;
  3576. }
  3577. }
  3578. return 0;
  3579. }
  3580. bool AudioPolicyManagerBase::stringToBool(const char *value)
  3581. {
  3582. return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
  3583. }
  3584. audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
  3585. {
  3586. uint32_t flag = 0;
  3587. // it is OK to cast name to non const here as we are not going to use it after
  3588. // strtok() modifies it
  3589. char *flagName = strtok(name, "|");
  3590. while (flagName != NULL) {
  3591. if (strlen(flagName) != 0) {
  3592. flag |= stringToEnum(sFlagNameToEnumTable,
  3593. ARRAY_SIZE(sFlagNameToEnumTable),
  3594. flagName);
  3595. }
  3596. flagName = strtok(NULL, "|");
  3597. }
  3598. //force direct flag if offload flag is set: offloading implies a direct output stream
  3599. // and all common behaviors are driven by checking only the direct flag
  3600. // this should normally be set appropriately in the policy configuration file
  3601. if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
  3602. flag |= AUDIO_OUTPUT_FLAG_DIRECT;
  3603. }
  3604. return (audio_output_flags_t)flag;
  3605. }
  3606. audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
  3607. {
  3608. uint32_t device = 0;
  3609. char *devName = strtok(name, "|");
  3610. while (devName != NULL) {
  3611. if (strlen(devName) != 0) {
  3612. device |= stringToEnum(sDeviceNameToEnumTable,
  3613. ARRAY_SIZE(sDeviceNameToEnumTable),
  3614. devName);
  3615. }
  3616. devName = strtok(NULL, "|");
  3617. }
  3618. return device;
  3619. }
  3620. void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
  3621. {
  3622. char *str = strtok(name, "|");
  3623. // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
  3624. // rates should be read from the output stream after it is opened for the first time
  3625. if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
  3626. profile->mSamplingRates.add(0);
  3627. return;
  3628. }
  3629. while (str != NULL) {
  3630. uint32_t rate = atoi(str);
  3631. if (rate != 0) {
  3632. ALOGV("loadSamplingRates() adding rate %d", rate);
  3633. profile->mSamplingRates.add(rate);
  3634. }
  3635. str = strtok(NULL, "|");
  3636. }
  3637. return;
  3638. }
  3639. void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
  3640. {
  3641. char *str = strtok(name, "|");
  3642. // by convention, "0' in the first entry in mFormats indicates the supported formats
  3643. // should be read from the output stream after it is opened for the first time
  3644. if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
  3645. profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
  3646. return;
  3647. }
  3648. while (str != NULL) {
  3649. audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
  3650. ARRAY_SIZE(sFormatNameToEnumTable),
  3651. str);
  3652. if (format != AUDIO_FORMAT_DEFAULT) {
  3653. profile->mFormats.add(format);
  3654. }
  3655. str = strtok(NULL, "|");
  3656. }
  3657. return;
  3658. }
  3659. void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
  3660. {
  3661. const char *str = strtok(name, "|");
  3662. ALOGV("loadInChannels() %s", name);
  3663. if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
  3664. profile->mChannelMasks.add(0);
  3665. return;
  3666. }
  3667. while (str != NULL) {
  3668. audio_channel_mask_t channelMask =
  3669. (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
  3670. ARRAY_SIZE(sInChannelsNameToEnumTable),
  3671. str);
  3672. if (channelMask != 0) {
  3673. ALOGV("loadInChannels() adding channelMask %04x", channelMask);
  3674. profile->mChannelMasks.add(channelMask);
  3675. }
  3676. str = strtok(NULL, "|");
  3677. }
  3678. return;
  3679. }
  3680. void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
  3681. {
  3682. const char *str = strtok(name, "|");
  3683. ALOGV("loadOutChannels() %s", name);
  3684. // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
  3685. // masks should be read from the output stream after it is opened for the first time
  3686. if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
  3687. profile->mChannelMasks.add(0);
  3688. return;
  3689. }
  3690. while (str != NULL) {
  3691. audio_channel_mask_t channelMask =
  3692. (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
  3693. ARRAY_SIZE(sOutChannelsNameToEnumTable),
  3694. str);
  3695. if (channelMask != 0) {
  3696. profile->mChannelMasks.add(channelMask);
  3697. }
  3698. str = strtok(NULL, "|");
  3699. }
  3700. return;
  3701. }
  3702. status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module)
  3703. {
  3704. cnode *node = root->first_child;
  3705. IOProfile *profile = new IOProfile(module);
  3706. while (node) {
  3707. if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
  3708. loadSamplingRates((char *)node->value, profile);
  3709. } else if (strcmp(node->name, FORMATS_TAG) == 0) {
  3710. loadFormats((char *)node->value, profile);
  3711. } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
  3712. loadInChannels((char *)node->value, profile);
  3713. } else if (strcmp(node->name, DEVICES_TAG) == 0) {
  3714. profile->mSupportedDevices = parseDeviceNames((char *)node->value);
  3715. }
  3716. node = node->next;
  3717. }
  3718. ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
  3719. "loadInput() invalid supported devices");
  3720. ALOGW_IF(profile->mChannelMasks.size() == 0,
  3721. "loadInput() invalid supported channel masks");
  3722. ALOGW_IF(profile->mSamplingRates.size() == 0,
  3723. "loadInput() invalid supported sampling rates");
  3724. ALOGW_IF(profile->mFormats.size() == 0,
  3725. "loadInput() invalid supported formats");
  3726. if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
  3727. (profile->mChannelMasks.size() != 0) &&
  3728. (profile->mSamplingRates.size() != 0) &&
  3729. (profile->mFormats.size() != 0)) {
  3730. ALOGV("loadInput() adding input mSupportedDevices 0x%X", profile->mSupportedDevices);
  3731. module->mInputProfiles.add(profile);
  3732. return NO_ERROR;
  3733. } else {
  3734. delete profile;
  3735. return BAD_VALUE;
  3736. }
  3737. }
  3738. status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module)
  3739. {
  3740. cnode *node = root->first_child;
  3741. IOProfile *profile = new IOProfile(module);
  3742. while (node) {
  3743. if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
  3744. loadSamplingRates((char *)node->value, profile);
  3745. } else if (strcmp(node->name, FORMATS_TAG) == 0) {
  3746. loadFormats((char *)node->value, profile);
  3747. } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
  3748. loadOutChannels((char *)node->value, profile);
  3749. } else if (strcmp(node->name, DEVICES_TAG) == 0) {
  3750. profile->mSupportedDevices = parseDeviceNames((char *)node->value);
  3751. } else if (strcmp(node->name, FLAGS_TAG) == 0) {
  3752. profile->mFlags = parseFlagNames((char *)node->value);
  3753. }
  3754. node = node->next;
  3755. }
  3756. ALOGW_IF(profile->mSupportedDevices == AUDIO_DEVICE_NONE,
  3757. "loadOutput() invalid supported devices");
  3758. ALOGW_IF(profile->mChannelMasks.size() == 0,
  3759. "loadOutput() invalid supported channel masks");
  3760. ALOGW_IF(profile->mSamplingRates.size() == 0,
  3761. "loadOutput() invalid supported sampling rates");
  3762. ALOGW_IF(profile->mFormats.size() == 0,
  3763. "loadOutput() invalid supported formats");
  3764. if ((profile->mSupportedDevices != AUDIO_DEVICE_NONE) &&
  3765. (profile->mChannelMasks.size() != 0) &&
  3766. (profile->mSamplingRates.size() != 0) &&
  3767. (profile->mFormats.size() != 0)) {
  3768. ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
  3769. profile->mSupportedDevices, profile->mFlags);
  3770. module->mOutputProfiles.add(profile);
  3771. return NO_ERROR;
  3772. } else {
  3773. delete profile;
  3774. return BAD_VALUE;
  3775. }
  3776. }
  3777. void AudioPolicyManagerBase::loadHwModule(cnode *root)
  3778. {
  3779. cnode *node = config_find(root, OUTPUTS_TAG);
  3780. status_t status = NAME_NOT_FOUND;
  3781. HwModule *module = new HwModule(root->name);
  3782. if (node != NULL) {
  3783. if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
  3784. mHasA2dp = true;
  3785. } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
  3786. mHasUsb = true;
  3787. } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX) == 0) {
  3788. mHasRemoteSubmix = true;
  3789. }
  3790. node = node->first_child;
  3791. while (node) {
  3792. ALOGV("loadHwModule() loading output %s", node->name);
  3793. status_t tmpStatus = loadOutput(node, module);
  3794. if (status == NAME_NOT_FOUND || status == NO_ERROR) {
  3795. status = tmpStatus;
  3796. }
  3797. node = node->next;
  3798. }
  3799. }
  3800. node = config_find(root, INPUTS_TAG);
  3801. if (node != NULL) {
  3802. node = node->first_child;
  3803. while (node) {
  3804. ALOGV("loadHwModule() loading input %s", node->name);
  3805. status_t tmpStatus = loadInput(node, module);
  3806. if (status == NAME_NOT_FOUND || status == NO_ERROR) {
  3807. status = tmpStatus;
  3808. }
  3809. node = node->next;
  3810. }
  3811. }
  3812. if (status == NO_ERROR) {
  3813. mHwModules.add(module);
  3814. } else {
  3815. delete module;
  3816. }
  3817. }
  3818. void AudioPolicyManagerBase::loadHwModules(cnode *root)
  3819. {
  3820. cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
  3821. if (node == NULL) {
  3822. return;
  3823. }
  3824. node = node->first_child;
  3825. while (node) {
  3826. ALOGV("loadHwModules() loading module %s", node->name);
  3827. loadHwModule(node);
  3828. node = node->next;
  3829. }
  3830. }
  3831. void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
  3832. {
  3833. cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
  3834. if (node == NULL) {
  3835. return;
  3836. }
  3837. node = node->first_child;
  3838. while (node) {
  3839. if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
  3840. mAttachedOutputDevices = parseDeviceNames((char *)node->value);
  3841. ALOGW_IF(mAttachedOutputDevices == AUDIO_DEVICE_NONE,
  3842. "loadGlobalConfig() no attached output devices");
  3843. ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
  3844. } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
  3845. mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
  3846. ARRAY_SIZE(sDeviceNameToEnumTable),
  3847. (char *)node->value);
  3848. ALOGW_IF(mDefaultOutputDevice == AUDIO_DEVICE_NONE,
  3849. "loadGlobalConfig() default device not specified");
  3850. ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
  3851. } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
  3852. mAvailableInputDevices = parseDeviceNames((char *)node->value) & ~AUDIO_DEVICE_BIT_IN;
  3853. ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
  3854. } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
  3855. mSpeakerDrcEnabled = stringToBool((char *)node->value);
  3856. ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
  3857. }
  3858. node = node->next;
  3859. }
  3860. }
  3861. status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
  3862. {
  3863. cnode *root;
  3864. char *data;
  3865. data = (char *)load_file(path, NULL);
  3866. if (data == NULL) {
  3867. return -ENODEV;
  3868. }
  3869. root = config_node("", "");
  3870. config_load(root, data);
  3871. loadGlobalConfig(root);
  3872. loadHwModules(root);
  3873. config_free(root);
  3874. free(root);
  3875. free(data);
  3876. ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
  3877. return NO_ERROR;
  3878. }
  3879. void AudioPolicyManagerBase::defaultAudioPolicyConfig(void)
  3880. {
  3881. HwModule *module;
  3882. IOProfile *profile;
  3883. mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER;
  3884. mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER;
  3885. mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC & ~AUDIO_DEVICE_BIT_IN;
  3886. module = new HwModule("primary");
  3887. profile = new IOProfile(module);
  3888. profile->mSamplingRates.add(44100);
  3889. profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
  3890. profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
  3891. profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER;
  3892. profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
  3893. module->mOutputProfiles.add(profile);
  3894. profile = new IOProfile(module);
  3895. profile->mSamplingRates.add(8000);
  3896. profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
  3897. profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
  3898. profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
  3899. module->mInputProfiles.add(profile);
  3900. mHwModules.add(module);
  3901. }
  3902. }; // namespace android