GoogleGit

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