GoogleGit

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