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