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 "AudioPolicyManager"
18 //#define LOG_NDEBUG 0
19 #include <utils/Log.h>
20 #include "AudioPolicyManager.h"
21 #include <media/mediarecorder.h>
22
23 namespace android {
24
25
26 // ----------------------------------------------------------------------------
27 // AudioPolicyInterface implementation
28 // ----------------------------------------------------------------------------
29
30
setDeviceConnectionState(AudioSystem::audio_devices device,AudioSystem::device_connection_state state,const char * device_address)31 status_t AudioPolicyManager::setDeviceConnectionState(AudioSystem::audio_devices device,
32 AudioSystem::device_connection_state state,
33 const char *device_address)
34 {
35
36 LOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
37
38 // connect/disconnect only 1 device at a time
39 if (AudioSystem::popCount(device) != 1) return BAD_VALUE;
40
41 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
42 LOGE("setDeviceConnectionState() invalid address: %s", device_address);
43 return BAD_VALUE;
44 }
45
46 // handle output devices
47 if (AudioSystem::isOutputDevice(device)) {
48
49 #ifndef WITH_A2DP
50 if (AudioSystem::isA2dpDevice(device)) {
51 LOGE("setDeviceConnectionState() invalid device: %x", device);
52 return BAD_VALUE;
53 }
54 #endif
55
56 switch (state)
57 {
58 // handle output device connection
59 case AudioSystem::DEVICE_STATE_AVAILABLE:
60 if (mAvailableOutputDevices & device) {
61 LOGW("setDeviceConnectionState() device already connected: %x", device);
62 return INVALID_OPERATION;
63 }
64 LOGW_IF((getOutputForDevice((uint32_t)device) != 0), "setDeviceConnectionState(): output using unconnected device %x", device);
65
66 LOGV("setDeviceConnectionState() connecting device %x", device);
67
68 // register new device as available
69 mAvailableOutputDevices |= device;
70
71 #ifdef WITH_A2DP
72 // handle A2DP device connection
73 if (AudioSystem::isA2dpDevice(device)) {
74 // when an A2DP device is connected, open an A2DP and a duplicated output
75 LOGV("opening A2DP output for device %s", device_address);
76 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
77 outputDesc->mDevice = device;
78 mA2dpOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
79 &outputDesc->mSamplingRate,
80 &outputDesc->mFormat,
81 &outputDesc->mChannels,
82 &outputDesc->mLatency,
83 outputDesc->mFlags);
84 if (mA2dpOutput) {
85 // add A2DP output descriptor
86 mOutputs.add(mA2dpOutput, outputDesc);
87 // set initial stream volume for A2DP device
88 applyStreamVolumes(mA2dpOutput, device);
89 mDuplicatedOutput = mpClientInterface->openDuplicateOutput(mA2dpOutput, mHardwareOutput);
90 if (mDuplicatedOutput != 0) {
91 // If both A2DP and duplicated outputs are open, send device address to A2DP hardware
92 // interface
93 AudioParameter param;
94 param.add(String8("a2dp_sink_address"), String8(device_address));
95 mpClientInterface->setParameters(mA2dpOutput, param.toString());
96 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
97
98 // add duplicated output descriptor
99 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor();
100 dupOutputDesc->mOutput1 = mOutputs.valueFor(mHardwareOutput);
101 dupOutputDesc->mOutput2 = mOutputs.valueFor(mA2dpOutput);
102 dupOutputDesc->mSamplingRate = outputDesc->mSamplingRate;
103 dupOutputDesc->mFormat = outputDesc->mFormat;
104 dupOutputDesc->mChannels = outputDesc->mChannels;
105 dupOutputDesc->mLatency = outputDesc->mLatency;
106 mOutputs.add(mDuplicatedOutput, dupOutputDesc);
107 applyStreamVolumes(mDuplicatedOutput, device);
108 } else {
109 LOGW("getOutput() could not open duplicated output for %d and %d",
110 mHardwareOutput, mA2dpOutput);
111 mAvailableOutputDevices &= ~device;
112 delete outputDesc;
113 return NO_INIT;
114 }
115 } else {
116 LOGW("setDeviceConnectionState() could not open A2DP output for device %x", device);
117 mAvailableOutputDevices &= ~device;
118 delete outputDesc;
119 return NO_INIT;
120 }
121 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
122
123 if (mA2dpDeviceAddress == mScoDeviceAddress) {
124 // It is normal to suspend twice if we are both in call,
125 // and have the hardware audio output routed to BT SCO
126 if (mPhoneState != AudioSystem::MODE_NORMAL) {
127 mpClientInterface->suspendOutput(mA2dpOutput);
128 }
129 if (AudioSystem::isBluetoothScoDevice((AudioSystem::audio_devices)hwOutputDesc->device())) {
130 mpClientInterface->suspendOutput(mA2dpOutput);
131 }
132 }
133
134 // move streams pertaining to STRATEGY_MEDIA to the newly opened A2DP output
135 if (getDeviceForStrategy(STRATEGY_MEDIA) & device) {
136 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
137 if (getStrategy((AudioSystem::stream_type)i) == STRATEGY_MEDIA) {
138 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, mA2dpOutput);
139 outputDesc->mRefCount[i] = hwOutputDesc->mRefCount[i];
140 hwOutputDesc->mRefCount[i] = 0;
141 }
142 }
143
144 }
145 // move streams pertaining to STRATEGY_DTMF to the newly opened A2DP output
146 if (getDeviceForStrategy(STRATEGY_DTMF) & device) {
147 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
148 if (getStrategy((AudioSystem::stream_type)i) == STRATEGY_DTMF) {
149 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, mA2dpOutput);
150 outputDesc->mRefCount[i] = hwOutputDesc->mRefCount[i];
151 hwOutputDesc->mRefCount[i] = 0;
152 }
153 }
154
155 }
156 // move streams pertaining to STRATEGY_SONIFICATION to the newly opened duplicated output
157 if (getDeviceForStrategy(STRATEGY_SONIFICATION) & device) {
158 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
159 if (getStrategy((AudioSystem::stream_type)i) == STRATEGY_SONIFICATION) {
160 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, mDuplicatedOutput);
161 outputDesc->mRefCount[i] =
162 hwOutputDesc->mRefCount[i];
163 mOutputs.valueFor(mDuplicatedOutput)->mRefCount[i] =
164 hwOutputDesc->mRefCount[i];
165 }
166 }
167 }
168 } else
169 #endif
170 // handle wired and SCO device connection (accessed via hardware output)
171 {
172
173 uint32_t newDevice = 0;
174 if (AudioSystem::isBluetoothScoDevice(device)) {
175 LOGV("setDeviceConnectionState() BT SCO device, address %s", device_address);
176 // keep track of SCO device address
177 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
178 // if in call and connecting SCO device, check if we must reroute hardware output
179 if (mPhoneState == AudioSystem::MODE_IN_CALL &&
180 getDeviceForStrategy(STRATEGY_PHONE) == device) {
181 newDevice = device;
182 } else if (mOutputs.valueFor(mHardwareOutput)->isUsedByStrategy(STRATEGY_DTMF) &&
183 getDeviceForStrategy(STRATEGY_DTMF) == device) {
184 newDevice = device;
185 }
186 if ((mA2dpDeviceAddress == mScoDeviceAddress) &&
187 (mPhoneState != AudioSystem::MODE_NORMAL)) {
188 mpClientInterface->suspendOutput(mA2dpOutput);
189 }
190 } else if (device == AudioSystem::DEVICE_OUT_WIRED_HEADSET ||
191 device == AudioSystem::DEVICE_OUT_WIRED_HEADPHONE) {
192 LOGV("setDeviceConnectionState() wired headset device");
193 // if connecting a wired headset, we check the following by order of priority
194 // to request a routing change if necessary:
195 // 1: we are in call or the strategy phone is active on the hardware output:
196 // use device for strategy phone
197 // 2: the strategy sonification is active on the hardware output:
198 // use device for strategy sonification
199 // 3: the strategy media is active on the hardware output:
200 // use device for strategy media
201 // 4: the strategy DTMF is active on the hardware output:
202 // use device for strategy DTMF
203 if (getDeviceForStrategy(STRATEGY_PHONE) == device &&
204 (mPhoneState == AudioSystem::MODE_IN_CALL ||
205 mOutputs.valueFor(mHardwareOutput)->isUsedByStrategy(STRATEGY_PHONE))) {
206 newDevice = device;
207 } else if ((getDeviceForStrategy(STRATEGY_SONIFICATION) & device) &&
208 mOutputs.valueFor(mHardwareOutput)->isUsedByStrategy(STRATEGY_SONIFICATION)){
209 newDevice = getDeviceForStrategy(STRATEGY_SONIFICATION);
210 } else if ((getDeviceForStrategy(STRATEGY_MEDIA) == device) &&
211 mOutputs.valueFor(mHardwareOutput)->isUsedByStrategy(STRATEGY_MEDIA)){
212 newDevice = device;
213 } else if (getDeviceForStrategy(STRATEGY_DTMF) == device &&
214 mOutputs.valueFor(mHardwareOutput)->isUsedByStrategy(STRATEGY_DTMF)) {
215 newDevice = device;
216 }
217 }
218 // request routing change if necessary
219 setOutputDevice(mHardwareOutput, newDevice);
220 }
221 break;
222 // handle output device disconnection
223 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
224 if (!(mAvailableOutputDevices & device)) {
225 LOGW("setDeviceConnectionState() device not connected: %x", device);
226 return INVALID_OPERATION;
227 }
228
229 uint32_t newDevice = 0;
230 // get usage of disconnected device by all strategies
231 bool wasUsedForMedia = (getDeviceForStrategy(STRATEGY_MEDIA) & device) != 0;
232 bool wasUsedForSonification = (getDeviceForStrategy(STRATEGY_SONIFICATION) & device) != 0;
233 bool wasUsedforPhone = (getDeviceForStrategy(STRATEGY_PHONE) & device) != 0;
234 bool wasUsedforDtmf = (getDeviceForStrategy(STRATEGY_DTMF) & device) != 0;
235 LOGV("setDeviceConnectionState() disconnecting device %x used by media %d, sonification %d, phone %d",
236 device, wasUsedForMedia, wasUsedForSonification, wasUsedforPhone);
237 // remove device from available output devices
238 mAvailableOutputDevices &= ~device;
239
240 #ifdef WITH_A2DP
241 // handle A2DP device disconnection
242 if (AudioSystem::isA2dpDevice(device)) {
243 if (mA2dpOutput == 0 || mDuplicatedOutput == 0) {
244 LOGW("setDeviceConnectionState() disconnecting A2DP and no A2DP output!");
245 mAvailableOutputDevices |= device;
246 return INVALID_OPERATION;
247 }
248
249 if (mA2dpDeviceAddress != device_address) {
250 LOGW("setDeviceConnectionState() disconnecting unknow A2DP sink address %s", device_address);
251 mAvailableOutputDevices |= device;
252 return INVALID_OPERATION;
253 }
254
255 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
256 AudioOutputDescriptor *a2dpOutputDesc = mOutputs.valueFor(mA2dpOutput);
257
258 // mute media during 2 seconds to avoid outputing sound on hardware output while music stream
259 // is switched from A2DP output and before music is paused by music application
260 setStrategyMute(STRATEGY_MEDIA, true, mHardwareOutput);
261 setStrategyMute(STRATEGY_MEDIA, false, mHardwareOutput, 2000);
262
263 // If the A2DP device was used by DTMF strategy, move all streams pertaining to DTMF strategy to
264 // hardware output
265 if (wasUsedforDtmf) {
266 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
267 if (getStrategy((AudioSystem::stream_type)i) == STRATEGY_DTMF) {
268 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, mHardwareOutput);
269 hwOutputDesc->changeRefCount((AudioSystem::stream_type)i,
270 a2dpOutputDesc->mRefCount[i]);
271 }
272 }
273 if (a2dpOutputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
274 newDevice = getDeviceForStrategy(STRATEGY_DTMF);
275 }
276 }
277
278 // If the A2DP device was used by media strategy, move all streams pertaining to media strategy to
279 // hardware output
280 if (wasUsedForMedia) {
281 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
282 if (getStrategy((AudioSystem::stream_type)i) == STRATEGY_MEDIA) {
283 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, mHardwareOutput);
284 hwOutputDesc->changeRefCount((AudioSystem::stream_type)i,
285 a2dpOutputDesc->mRefCount[i]);
286 }
287 }
288 if (a2dpOutputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
289 newDevice = getDeviceForStrategy(STRATEGY_MEDIA);
290 }
291 }
292
293 // If the A2DP device was used by sonification strategy, move all streams pertaining to
294 // sonification strategy to hardware output.
295 // Note that newDevice is overwritten here giving sonification strategy a higher priority than
296 // media strategy.
297 if (wasUsedForSonification) {
298 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
299 if (getStrategy((AudioSystem::stream_type)i) == STRATEGY_SONIFICATION) {
300 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, mHardwareOutput);
301 }
302 }
303 if (a2dpOutputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
304 newDevice = getDeviceForStrategy(STRATEGY_SONIFICATION);
305 }
306 }
307
308 // close A2DP and duplicated outputs
309 AudioParameter param;
310 param.add(String8("closing"), String8("true"));
311 mpClientInterface->setParameters(mA2dpOutput, param.toString());
312
313 LOGW("setDeviceConnectionState() closing A2DP and duplicated output!");
314 mpClientInterface->closeOutput(mDuplicatedOutput);
315 delete mOutputs.valueFor(mDuplicatedOutput);
316 mOutputs.removeItem(mDuplicatedOutput);
317 mDuplicatedOutput = 0;
318 mpClientInterface->closeOutput(mA2dpOutput);
319 delete mOutputs.valueFor(mA2dpOutput);
320 mOutputs.removeItem(mA2dpOutput);
321 mA2dpOutput = 0;
322 } else
323 #endif
324 {
325 if (AudioSystem::isBluetoothScoDevice(device)) {
326 // handle SCO device disconnection
327 if (wasUsedforPhone &&
328 mPhoneState == AudioSystem::MODE_IN_CALL) {
329 // if in call, find new suitable device for phone strategy
330 newDevice = getDeviceForStrategy(STRATEGY_PHONE);
331 } else if (wasUsedforDtmf &&
332 mOutputs.valueFor(mHardwareOutput)->isUsedByStrategy(STRATEGY_DTMF)) {
333 newDevice = getDeviceForStrategy(STRATEGY_DTMF);
334 }
335 if ((mA2dpDeviceAddress == mScoDeviceAddress) &&
336 (mPhoneState != AudioSystem::MODE_NORMAL)) {
337 mpClientInterface->restoreOutput(mA2dpOutput);
338 }
339 } else if (device == AudioSystem::DEVICE_OUT_WIRED_HEADSET ||
340 device == AudioSystem::DEVICE_OUT_WIRED_HEADPHONE) {
341 // if disconnecting a wired headset, we check the following by order of priority
342 // to request a routing change if necessary:
343 // 1: we are in call or the strategy phone is active on the hardware output:
344 // use device for strategy phone
345 // 2: the strategy sonification is active on the hardware output:
346 // use device for strategy sonification
347 // 3: the strategy media is active on the hardware output:
348 // use device for strategy media
349 // 4: the strategy DTMF is active on the hardware output:
350 // use device for strategy DTMF
351 if (wasUsedforPhone &&
352 (mPhoneState == AudioSystem::MODE_IN_CALL ||
353 mOutputs.valueFor(mHardwareOutput)->isUsedByStrategy(STRATEGY_PHONE))) {
354 newDevice = getDeviceForStrategy(STRATEGY_PHONE);
355 } else if (wasUsedForSonification &&
356 mOutputs.valueFor(mHardwareOutput)->isUsedByStrategy(STRATEGY_SONIFICATION)){
357 newDevice = getDeviceForStrategy(STRATEGY_SONIFICATION);
358 } else if (wasUsedForMedia &&
359 mOutputs.valueFor(mHardwareOutput)->isUsedByStrategy(STRATEGY_MEDIA)){
360 newDevice = getDeviceForStrategy(STRATEGY_MEDIA);
361 } else if (wasUsedforDtmf &&
362 mOutputs.valueFor(mHardwareOutput)->isUsedByStrategy(STRATEGY_DTMF)){
363 newDevice = getDeviceForStrategy(STRATEGY_DTMF);
364 }
365 }
366 }
367 // request routing change if necessary
368 setOutputDevice(mHardwareOutput, newDevice);
369
370 // clear A2DP and SCO device address if necessary
371 #ifdef WITH_A2DP
372 if (AudioSystem::isA2dpDevice(device)) {
373 mA2dpDeviceAddress = "";
374 }
375 #endif
376 if (AudioSystem::isBluetoothScoDevice(device)) {
377 mScoDeviceAddress = "";
378 }
379 } break;
380
381 default:
382 LOGE("setDeviceConnectionState() invalid state: %x", state);
383 return BAD_VALUE;
384 }
385
386 if (device == AudioSystem::DEVICE_OUT_WIRED_HEADSET) {
387 device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
388 } else if (device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO ||
389 device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
390 device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
391 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
392 } else {
393 return NO_ERROR;
394 }
395 }
396 // handle input devices
397 if (AudioSystem::isInputDevice(device)) {
398
399 switch (state)
400 {
401 // handle input device connection
402 case AudioSystem::DEVICE_STATE_AVAILABLE: {
403 if (mAvailableInputDevices & device) {
404 LOGW("setDeviceConnectionState() device already connected: %d", device);
405 return INVALID_OPERATION;
406 }
407 mAvailableInputDevices |= device;
408 }
409 break;
410
411 // handle input device disconnection
412 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
413 if (!(mAvailableInputDevices & device)) {
414 LOGW("setDeviceConnectionState() device not connected: %d", device);
415 return INVALID_OPERATION;
416 }
417 mAvailableInputDevices &= ~device;
418 } break;
419
420 default:
421 LOGE("setDeviceConnectionState() invalid state: %x", state);
422 return BAD_VALUE;
423 }
424
425 audio_io_handle_t activeInput = getActiveInput();
426 if (activeInput != 0) {
427 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
428 uint32_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
429 if (newDevice != inputDesc->mDevice) {
430 LOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
431 inputDesc->mDevice, newDevice, activeInput);
432 inputDesc->mDevice = newDevice;
433 AudioParameter param = AudioParameter();
434 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
435 mpClientInterface->setParameters(activeInput, param.toString());
436 }
437 }
438
439 return NO_ERROR;
440 }
441
442 LOGW("setDeviceConnectionState() invalid device: %x", device);
443 return BAD_VALUE;
444 }
445
getDeviceConnectionState(AudioSystem::audio_devices device,const char * device_address)446 AudioSystem::device_connection_state AudioPolicyManager::getDeviceConnectionState(AudioSystem::audio_devices device,
447 const char *device_address)
448 {
449 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
450 String8 address = String8(device_address);
451 if (AudioSystem::isOutputDevice(device)) {
452 if (device & mAvailableOutputDevices) {
453 #ifdef WITH_A2DP
454 if (AudioSystem::isA2dpDevice(device) &&
455 address != "" && mA2dpDeviceAddress != address) {
456 return state;
457 }
458 #endif
459 if (AudioSystem::isBluetoothScoDevice(device) &&
460 address != "" && mScoDeviceAddress != address) {
461 return state;
462 }
463 state = AudioSystem::DEVICE_STATE_AVAILABLE;
464 }
465 } else if (AudioSystem::isInputDevice(device)) {
466 if (device & mAvailableInputDevices) {
467 state = AudioSystem::DEVICE_STATE_AVAILABLE;
468 }
469 }
470
471 return state;
472 }
473
setPhoneState(int state)474 void AudioPolicyManager::setPhoneState(int state)
475 {
476 LOGV("setPhoneState() state %d", state);
477 uint32_t newDevice = 0;
478 if (state < 0 || state >= AudioSystem::NUM_MODES) {
479 LOGW("setPhoneState() invalid state %d", state);
480 return;
481 }
482
483 if (state == mPhoneState ) {
484 LOGW("setPhoneState() setting same state %d", state);
485 return;
486 }
487
488 // if leaving call state, handle special case of active streams
489 // pertaining to sonification strategy see handleIncallSonification()
490 if (mPhoneState == AudioSystem::MODE_IN_CALL) {
491 LOGV("setPhoneState() in call state management: new state is %d", state);
492 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
493 handleIncallSonification(stream, false, true);
494 }
495 }
496
497 // store previous phone state for management of sonification strategy below
498 int oldState = mPhoneState;
499 uint32_t oldDtmfDevice = getDeviceForStrategy(STRATEGY_DTMF);
500 uint32_t oldSonificationDevice = getDeviceForStrategy(STRATEGY_SONIFICATION) & ~AudioSystem::DEVICE_OUT_SPEAKER;
501 mPhoneState = state;
502 bool force = false;
503 // check if a routing change is required for hardware output in the following
504 // order of priority:
505 // 1: a stream pertaining to sonification strategy is active
506 // 2: new state is incall
507 // 3: a stream pertaining to media strategy is active
508 // 4: a stream pertaining to DTMF strategy is active
509 if (mOutputs.valueFor(mHardwareOutput)->isUsedByStrategy(STRATEGY_SONIFICATION)) {
510 newDevice = getDeviceForStrategy(STRATEGY_SONIFICATION);
511 } else if (mPhoneState == AudioSystem::MODE_IN_CALL) {
512 newDevice = getDeviceForStrategy(STRATEGY_PHONE);
513 // force routing command to audio hardware when starting call
514 // even if no device change is needed
515 force = true;
516 } else if (mOutputs.valueFor(mHardwareOutput)->isUsedByStrategy(STRATEGY_MEDIA)) {
517 newDevice = getDeviceForStrategy(STRATEGY_MEDIA);
518 } else if (mOutputs.valueFor(mHardwareOutput)->isUsedByStrategy(STRATEGY_DTMF)) {
519 newDevice = getDeviceForStrategy(STRATEGY_DTMF);
520 }
521
522
523 if (mA2dpOutput != 0) {
524 // If entering or exiting in call state, switch DTMF streams to/from A2DP output
525 // if necessary
526 uint32_t newDtmfDevice = getDeviceForStrategy(STRATEGY_DTMF);
527 uint32_t newSonificationDevice = getDeviceForStrategy(STRATEGY_SONIFICATION) & ~AudioSystem::DEVICE_OUT_SPEAKER;
528 if (state == AudioSystem::MODE_IN_CALL) { // entering in call mode
529 // move DTMF streams from A2DP output to hardware output if necessary
530 if (AudioSystem::isA2dpDevice((AudioSystem::audio_devices)oldDtmfDevice) &&
531 !AudioSystem::isA2dpDevice((AudioSystem::audio_devices)newDtmfDevice)) {
532 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
533 if (getStrategy((AudioSystem::stream_type)i) == STRATEGY_DTMF) {
534 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, mHardwareOutput);
535 int refCount = mOutputs.valueFor(mA2dpOutput)->mRefCount[i];
536 mOutputs.valueFor(mHardwareOutput)->changeRefCount((AudioSystem::stream_type)i,
537 refCount);
538 mOutputs.valueFor(mA2dpOutput)->changeRefCount((AudioSystem::stream_type)i,-refCount);
539 }
540 }
541 if (newDevice == 0 && mOutputs.valueFor(mA2dpOutput)->isUsedByStrategy(STRATEGY_DTMF)) {
542 newDevice = newDtmfDevice;
543 }
544 }
545 // move SONIFICATION streams from duplicated output to hardware output if necessary
546 if (AudioSystem::isA2dpDevice((AudioSystem::audio_devices)oldSonificationDevice) &&
547 !AudioSystem::isA2dpDevice((AudioSystem::audio_devices)newSonificationDevice)) {
548 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
549 if (getStrategy((AudioSystem::stream_type)i) == STRATEGY_SONIFICATION) {
550 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, mHardwareOutput);
551 int refCount = mOutputs.valueFor(mDuplicatedOutput)->mRefCount[i];
552 mOutputs.valueFor(mHardwareOutput)->changeRefCount((AudioSystem::stream_type)i,
553 refCount);
554 mOutputs.valueFor(mDuplicatedOutput)->changeRefCount((AudioSystem::stream_type)i,-refCount);
555 }
556 }
557 }
558 } else { // exiting in call mode
559 // move DTMF streams from hardware output to A2DP output if necessary
560 if (!AudioSystem::isA2dpDevice((AudioSystem::audio_devices)oldDtmfDevice) &&
561 AudioSystem::isA2dpDevice((AudioSystem::audio_devices)newDtmfDevice)) {
562 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
563 if (getStrategy((AudioSystem::stream_type)i) == STRATEGY_DTMF) {
564 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, mA2dpOutput);
565 int refCount = mOutputs.valueFor(mHardwareOutput)->mRefCount[i];
566 mOutputs.valueFor(mA2dpOutput)->changeRefCount((AudioSystem::stream_type)i, refCount);
567 mOutputs.valueFor(mHardwareOutput)->changeRefCount((AudioSystem::stream_type)i, -refCount);
568 }
569 }
570 }
571 // move SONIFICATION streams from hardware output to A2DP output if necessary
572 if (!AudioSystem::isA2dpDevice((AudioSystem::audio_devices)oldSonificationDevice) &&
573 AudioSystem::isA2dpDevice((AudioSystem::audio_devices)newSonificationDevice)) {
574 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
575 if (getStrategy((AudioSystem::stream_type)i) == STRATEGY_SONIFICATION) {
576 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, mDuplicatedOutput);
577 int refCount = mOutputs.valueFor(mHardwareOutput)->mRefCount[i];
578 mOutputs.valueFor(mDuplicatedOutput)->changeRefCount((AudioSystem::stream_type)i, refCount);
579 mOutputs.valueFor(mHardwareOutput)->changeRefCount((AudioSystem::stream_type)i, -refCount);
580 }
581 }
582 }
583 }
584 // suspend A2DP output if SCO device address is the same as A2DP device address.
585 // no need to check that a SCO device is actually connected as mScoDeviceAddress == ""
586 // if none is connected and the test below will fail.
587 if (mA2dpDeviceAddress == mScoDeviceAddress) {
588 if (oldState == AudioSystem::MODE_NORMAL) {
589 mpClientInterface->suspendOutput(mA2dpOutput);
590 } else if (state == AudioSystem::MODE_NORMAL) {
591 mpClientInterface->restoreOutput(mA2dpOutput);
592 }
593 }
594 }
595
596 // force routing command to audio hardware when ending call
597 // even if no device change is needed
598 if (oldState == AudioSystem::MODE_IN_CALL) {
599 if (newDevice == 0) {
600 newDevice = mOutputs.valueFor(mHardwareOutput)->device();
601 }
602 force = true;
603 }
604 // change routing is necessary
605 setOutputDevice(mHardwareOutput, newDevice, force);
606
607 // if entering in call state, handle special case of active streams
608 // pertaining to sonification strategy see handleIncallSonification()
609 if (state == AudioSystem::MODE_IN_CALL) {
610 LOGV("setPhoneState() in call state management: new state is %d", state);
611 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
612 handleIncallSonification(stream, true, true);
613 }
614 }
615 }
616
setRingerMode(uint32_t mode,uint32_t mask)617 void AudioPolicyManager::setRingerMode(uint32_t mode, uint32_t mask)
618 {
619 LOGV("setRingerMode() mode %x, mask %x", mode, mask);
620
621 mRingerMode = mode;
622 }
623
setForceUse(AudioSystem::force_use usage,AudioSystem::forced_config config)624 void AudioPolicyManager::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
625 {
626 LOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
627
628 switch(usage) {
629 case AudioSystem::FOR_COMMUNICATION:
630 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
631 config != AudioSystem::FORCE_NONE) {
632 LOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
633 return;
634 }
635 mForceUse[usage] = config;
636 // update hardware output routing immediately if in call, or if there is an active
637 // VOICE_CALL stream, as would be the case with an application that uses this stream
638 // for it to behave like in a telephony app (e.g. voicemail app that plays audio files
639 // streamed or downloaded to the device)
640 if ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
641 (mOutputs.valueFor(mHardwareOutput)->isUsedByStream(AudioSystem::VOICE_CALL))) {
642 uint32_t device = getDeviceForStrategy(STRATEGY_PHONE);
643 setOutputDevice(mHardwareOutput, device);
644 }
645 break;
646 case AudioSystem::FOR_MEDIA:
647 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
648 config != AudioSystem::FORCE_WIRED_ACCESSORY && config != AudioSystem::FORCE_NONE) {
649 LOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
650 return;
651 }
652 mForceUse[usage] = config;
653 break;
654 case AudioSystem::FOR_RECORD:
655 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
656 config != AudioSystem::FORCE_NONE) {
657 LOGW("setForceUse() invalid config %d for FOR_RECORD", config);
658 return;
659 }
660 mForceUse[usage] = config;
661 break;
662 default:
663 LOGW("setForceUse() invalid usage %d", usage);
664 break;
665 }
666 }
667
getForceUse(AudioSystem::force_use usage)668 AudioSystem::forced_config AudioPolicyManager::getForceUse(AudioSystem::force_use usage)
669 {
670 return mForceUse[usage];
671 }
672
setSystemProperty(const char * property,const char * value)673 void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
674 {
675 LOGV("setSystemProperty() property %s, value %s", property, value);
676 if (strcmp(property, "ro.camera.sound.forced") == 0) {
677 if (atoi(value)) {
678 LOGV("ENFORCED_AUDIBLE cannot be muted");
679 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = false;
680 } else {
681 LOGV("ENFORCED_AUDIBLE can be muted");
682 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = true;
683 }
684 }
685 }
686
getOutput(AudioSystem::stream_type stream,uint32_t samplingRate,uint32_t format,uint32_t channels,AudioSystem::output_flags flags)687 audio_io_handle_t AudioPolicyManager::getOutput(AudioSystem::stream_type stream,
688 uint32_t samplingRate,
689 uint32_t format,
690 uint32_t channels,
691 AudioSystem::output_flags flags)
692 {
693 audio_io_handle_t output = 0;
694 uint32_t latency = 0;
695 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
696 uint32_t device = getDeviceForStrategy(strategy);
697 LOGV("getOutput() stream %d, samplingRate %d, format %d, channels %x, flags %x", stream, samplingRate, format, channels, flags);
698
699
700 // open a direct output if:
701 // 1 a direct output is explicitely requested
702 // 2 the audio format is compressed
703 if ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
704 (format !=0 && !AudioSystem::isLinearPCM(format))) {
705
706 LOGV("getOutput() opening direct output device %x", device);
707 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
708 outputDesc->mDevice = device;
709 outputDesc->mSamplingRate = samplingRate;
710 outputDesc->mFormat = format;
711 outputDesc->mChannels = channels;
712 outputDesc->mLatency = 0;
713 outputDesc->mFlags = (AudioSystem::output_flags)(flags | AudioSystem::OUTPUT_FLAG_DIRECT);
714 outputDesc->mRefCount[stream] = 1;
715 output = mpClientInterface->openOutput(&outputDesc->mDevice,
716 &outputDesc->mSamplingRate,
717 &outputDesc->mFormat,
718 &outputDesc->mChannels,
719 &outputDesc->mLatency,
720 outputDesc->mFlags);
721
722 // only accept an output with the requeted parameters
723 if ((samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
724 (format != 0 && format != outputDesc->mFormat) ||
725 (channels != 0 && channels != outputDesc->mChannels)) {
726 LOGV("getOutput() failed opening direct output: samplingRate %d, format %d, channels %d",
727 samplingRate, format, channels);
728 mpClientInterface->closeOutput(output);
729 delete outputDesc;
730 return 0;
731 }
732 mOutputs.add(output, outputDesc);
733 return output;
734 }
735
736 if (channels != 0 && channels != AudioSystem::CHANNEL_OUT_MONO &&
737 channels != AudioSystem::CHANNEL_OUT_STEREO) {
738 return 0;
739 }
740 // open a non direct output
741
742 // get which output is suitable for the specified stream. The actual routing change will happen
743 // when startOutput() will be called
744 uint32_t device2 = device & ~AudioSystem::DEVICE_OUT_SPEAKER;
745 if (AudioSystem::popCount((AudioSystem::audio_devices)device) == 2) {
746 #ifdef WITH_A2DP
747 if (AudioSystem::isA2dpDevice((AudioSystem::audio_devices)device2)) {
748 // if playing on 2 devices among which one is A2DP, use duplicated output
749 LOGV("getOutput() using duplicated output");
750 LOGW_IF((mA2dpOutput == 0), "getOutput() A2DP device in multiple %x selected but A2DP output not opened", device);
751 output = mDuplicatedOutput;
752 } else
753 #endif
754 {
755 // if playing on 2 devices among which none is A2DP, use hardware output
756 output = mHardwareOutput;
757 }
758 LOGV("getOutput() using output %d for 2 devices %x", output, device);
759 } else {
760 #ifdef WITH_A2DP
761 if (AudioSystem::isA2dpDevice((AudioSystem::audio_devices)device2)) {
762 // if playing on A2DP device, use a2dp output
763 LOGW_IF((mA2dpOutput == 0), "getOutput() A2DP device %x selected but A2DP output not opened", device);
764 output = mA2dpOutput;
765 } else
766 #endif
767 {
768 // if playing on not A2DP device, use hardware output
769 output = mHardwareOutput;
770 }
771 }
772
773
774 LOGW_IF((output ==0), "getOutput() could not find output for stream %d, samplingRate %d, format %d, channels %x, flags %x",
775 stream, samplingRate, format, channels, flags);
776
777 return output;
778 }
779
startOutput(audio_io_handle_t output,AudioSystem::stream_type stream)780 status_t AudioPolicyManager::startOutput(audio_io_handle_t output, AudioSystem::stream_type stream)
781 {
782 LOGV("startOutput() output %d, stream %d", output, stream);
783 ssize_t index = mOutputs.indexOfKey(output);
784 if (index < 0) {
785 LOGW("startOutput() unknow output %d", output);
786 return BAD_VALUE;
787 }
788
789 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
790 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
791 uint32_t device = getDeviceForStrategy(strategy);
792
793 if (!outputDesc->isUsedByStrategy(strategy)) {
794 // if the stream started is the first active stream in its strategy, check if routing change
795 // must be done on hardware output
796 uint32_t newDevice = 0;
797 if (AudioSystem::popCount((AudioSystem::audio_devices)device) == 2) {
798 #ifdef WITH_A2DP
799 uint32_t device2 = device & ~AudioSystem::DEVICE_OUT_SPEAKER;
800 if (AudioSystem::isA2dpDevice((AudioSystem::audio_devices)device2)) {
801 // if one device is A2DP, selected the second device for hardware output
802 device &= ~device2;
803 } else
804 #endif
805 {
806 // we only support speaker + headset and speaker + headphone combinations on hardware output.
807 // other combinations will leave device = 0 and no routing will happen.
808 if (device != (AudioSystem::DEVICE_OUT_SPEAKER | AudioSystem::DEVICE_OUT_WIRED_HEADSET) &&
809 device != (AudioSystem::DEVICE_OUT_SPEAKER | AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) {
810 device = AudioSystem::DEVICE_OUT_SPEAKER;
811 }
812 }
813 }
814
815 // By order of priority
816 // 1 apply routing for phone strategy in any case
817 // 2 apply routing for notification strategy if no stream pertaining to
818 // phone strategies is playing
819 // 3 apply routing for media strategy is not incall and neither phone nor sonification
820 // strategies is active.
821 // 4 apply routing for DTMF strategy if no stream pertaining to
822 // neither phone, sonification nor media strategy is playing
823 if (strategy == STRATEGY_PHONE) {
824 newDevice = device;
825 } else if (!mOutputs.valueFor(mHardwareOutput)->isUsedByStrategy(STRATEGY_PHONE)) {
826 if (strategy == STRATEGY_SONIFICATION) {
827 newDevice = device;
828 } else if (!mOutputs.valueFor(mHardwareOutput)->isUsedByStrategy(STRATEGY_SONIFICATION)) {
829 if (strategy == STRATEGY_MEDIA) {
830 newDevice = device;
831 } else if (!mOutputs.valueFor(mHardwareOutput)->isUsedByStrategy(STRATEGY_MEDIA)) {
832 // strategy == STRATEGY_DTMF
833 newDevice = device;
834 }
835 }
836 }
837
838 // TODO: maybe mute stream is selected device was refused
839 setOutputDevice(mHardwareOutput, newDevice);
840 }
841
842 // incremenent usage count for this stream on the requested output:
843 // NOTE that the usage count is the same for duplicated output and hardware output which is
844 // necassary for a correct control of hardware output routing by startOutput() and stopOutput()
845 outputDesc->changeRefCount(stream, 1);
846
847 // handle special case for sonification while in call
848 if (mPhoneState == AudioSystem::MODE_IN_CALL) {
849 handleIncallSonification(stream, true, false);
850 }
851
852 // apply volume rules for current stream and device if necessary
853 checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, outputDesc->device());
854
855 return NO_ERROR;
856 }
857
stopOutput(audio_io_handle_t output,AudioSystem::stream_type stream)858 status_t AudioPolicyManager::stopOutput(audio_io_handle_t output, AudioSystem::stream_type stream)
859 {
860 LOGV("stopOutput() output %d, stream %d", output, stream);
861 ssize_t index = mOutputs.indexOfKey(output);
862 if (index < 0) {
863 LOGW("stopOutput() unknow output %d", output);
864 return BAD_VALUE;
865 }
866
867 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
868 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
869
870 // handle special case for sonification while in call
871 if (mPhoneState == AudioSystem::MODE_IN_CALL) {
872 handleIncallSonification(stream, false, false);
873 }
874
875 if (outputDesc->isUsedByStrategy(strategy)) {
876 // decrement usage count of this stream on the output
877 outputDesc->changeRefCount(stream, -1);
878 if (!outputDesc->isUsedByStrategy(strategy)) {
879 // if the stream is the last of its strategy to use this output, change routing
880 // in the following order or priority:
881 // PHONE > SONIFICATION > MEDIA > DTMF
882 uint32_t newDevice = 0;
883 if (outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
884 newDevice = getDeviceForStrategy(STRATEGY_PHONE);
885 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
886 newDevice = getDeviceForStrategy(STRATEGY_SONIFICATION);
887 } else if (mPhoneState == AudioSystem::MODE_IN_CALL) {
888 newDevice = getDeviceForStrategy(STRATEGY_PHONE);
889 } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
890 newDevice = getDeviceForStrategy(STRATEGY_MEDIA);
891 } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
892 newDevice = getDeviceForStrategy(STRATEGY_DTMF);
893 }
894
895 // apply routing change if necessary.
896 // insert a delay of 2 times the audio hardware latency to ensure PCM
897 // buffers in audio flinger and audio hardware are emptied before the
898 // routing change is executed.
899 setOutputDevice(mHardwareOutput, newDevice, false, mOutputs.valueFor(mHardwareOutput)->mLatency*2);
900 }
901 // store time at which the last music track was stopped - see computeVolume()
902 if (stream == AudioSystem::MUSIC) {
903 mMusicStopTime = systemTime();
904 }
905 return NO_ERROR;
906 } else {
907 LOGW("stopOutput() refcount is already 0 for output %d", output);
908 return INVALID_OPERATION;
909 }
910 }
911
releaseOutput(audio_io_handle_t output)912 void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
913 {
914 LOGV("releaseOutput() %d", output);
915 ssize_t index = mOutputs.indexOfKey(output);
916 if (index < 0) {
917 LOGW("releaseOutput() releasing unknown output %d", output);
918 return;
919 }
920 if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
921 mpClientInterface->closeOutput(output);
922 delete mOutputs.valueAt(index);
923 mOutputs.removeItem(output);
924 }
925 }
926
getInput(int inputSource,uint32_t samplingRate,uint32_t format,uint32_t channels,AudioSystem::audio_in_acoustics acoustics)927 audio_io_handle_t AudioPolicyManager::getInput(int inputSource,
928 uint32_t samplingRate,
929 uint32_t format,
930 uint32_t channels,
931 AudioSystem::audio_in_acoustics acoustics)
932 {
933 audio_io_handle_t input = 0;
934 uint32_t device = getDeviceForInputSource(inputSource);
935
936 LOGV("getInput() inputSource %d, samplingRate %d, format %d, channels %x, acoustics %x", inputSource, samplingRate, format, channels, acoustics);
937
938 if (device == 0) {
939 return 0;
940 }
941
942 // adapt channel selection to input source
943 switch(inputSource) {
944 case AUDIO_SOURCE_VOICE_UPLINK:
945 channels = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
946 break;
947 case AUDIO_SOURCE_VOICE_DOWNLINK:
948 channels = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
949 break;
950 case AUDIO_SOURCE_VOICE_CALL:
951 channels = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
952 break;
953 default:
954 break;
955 }
956
957 AudioInputDescriptor *inputDesc = new AudioInputDescriptor();
958
959 inputDesc->mInputSource = inputSource;
960 inputDesc->mDevice = device;
961 inputDesc->mSamplingRate = samplingRate;
962 inputDesc->mFormat = format;
963 inputDesc->mChannels = channels;
964 inputDesc->mAcoustics = acoustics;
965 inputDesc->mRefCount = 0;
966 input = mpClientInterface->openInput(&inputDesc->mDevice,
967 &inputDesc->mSamplingRate,
968 &inputDesc->mFormat,
969 &inputDesc->mChannels,
970 inputDesc->mAcoustics);
971
972 // only accept input with the exact requested set of parameters
973 if ((samplingRate != inputDesc->mSamplingRate) ||
974 (format != inputDesc->mFormat) ||
975 (channels != inputDesc->mChannels)) {
976 LOGV("getOutput() failed opening input: samplingRate %d, format %d, channels %d",
977 samplingRate, format, channels);
978 mpClientInterface->closeInput(input);
979 delete inputDesc;
980 return 0;
981 }
982 mInputs.add(input, inputDesc);
983 return input;
984 }
985
startInput(audio_io_handle_t input)986 status_t AudioPolicyManager::startInput(audio_io_handle_t input)
987 {
988 LOGV("startInput() input %d", input);
989 ssize_t index = mInputs.indexOfKey(input);
990 if (index < 0) {
991 LOGW("startInput() unknow input %d", input);
992 return BAD_VALUE;
993 }
994 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
995
996 // refuse 2 active AudioRecord clients at the same time
997 if (getActiveInput() != 0) {
998 LOGW("startInput() input %d failed: other input already started", input);
999 return INVALID_OPERATION;
1000 }
1001
1002 AudioParameter param = AudioParameter();
1003 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
1004 mpClientInterface->setParameters(input, param.toString());
1005
1006 inputDesc->mRefCount = 1;
1007 return NO_ERROR;
1008 }
1009
stopInput(audio_io_handle_t input)1010 status_t AudioPolicyManager::stopInput(audio_io_handle_t input)
1011 {
1012 LOGV("stopInput() input %d", input);
1013 ssize_t index = mInputs.indexOfKey(input);
1014 if (index < 0) {
1015 LOGW("stopInput() unknow input %d", input);
1016 return BAD_VALUE;
1017 }
1018 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1019
1020 if (inputDesc->mRefCount == 0) {
1021 LOGW("stopInput() input %d already stopped", input);
1022 return INVALID_OPERATION;
1023 } else {
1024 AudioParameter param = AudioParameter();
1025 param.addInt(String8(AudioParameter::keyRouting), 0);
1026 mpClientInterface->setParameters(input, param.toString());
1027 inputDesc->mRefCount = 0;
1028 return NO_ERROR;
1029 }
1030 }
1031
releaseInput(audio_io_handle_t input)1032 void AudioPolicyManager::releaseInput(audio_io_handle_t input)
1033 {
1034 LOGV("releaseInput() %d", input);
1035 ssize_t index = mInputs.indexOfKey(input);
1036 if (index < 0) {
1037 LOGW("releaseInput() releasing unknown input %d", input);
1038 return;
1039 }
1040 mpClientInterface->closeInput(input);
1041 delete mInputs.valueAt(index);
1042 mInputs.removeItem(input);
1043 LOGV("releaseInput() exit");
1044 }
1045
1046
1047
initStreamVolume(AudioSystem::stream_type stream,int indexMin,int indexMax)1048 void AudioPolicyManager::initStreamVolume(AudioSystem::stream_type stream,
1049 int indexMin,
1050 int indexMax)
1051 {
1052 LOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1053 if (indexMin < 0 || indexMin >= indexMax) {
1054 LOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1055 return;
1056 }
1057 mStreams[stream].mIndexMin = indexMin;
1058 mStreams[stream].mIndexMax = indexMax;
1059 }
1060
setStreamVolumeIndex(AudioSystem::stream_type stream,int index)1061 status_t AudioPolicyManager::setStreamVolumeIndex(AudioSystem::stream_type stream, int index)
1062 {
1063
1064 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1065 return BAD_VALUE;
1066 }
1067
1068 LOGV("setStreamVolumeIndex() stream %d, index %d", stream, index);
1069 mStreams[stream].mIndexCur = index;
1070
1071 // compute and apply stream volume on all outputs according to connected device
1072 status_t status = NO_ERROR;
1073 for (size_t i = 0; i < mOutputs.size(); i++) {
1074 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), mOutputs.valueAt(i)->device());
1075 if (volStatus != NO_ERROR) {
1076 status = volStatus;
1077 }
1078 }
1079 return status;
1080 }
1081
getStreamVolumeIndex(AudioSystem::stream_type stream,int * index)1082 status_t AudioPolicyManager::getStreamVolumeIndex(AudioSystem::stream_type stream, int *index)
1083 {
1084 if (index == 0) {
1085 return BAD_VALUE;
1086 }
1087 LOGV("getStreamVolumeIndex() stream %d", stream);
1088 *index = mStreams[stream].mIndexCur;
1089 return NO_ERROR;
1090 }
1091
dump(int fd)1092 status_t AudioPolicyManager::dump(int fd)
1093 {
1094 const size_t SIZE = 256;
1095 char buffer[SIZE];
1096 String8 result;
1097
1098 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1099 result.append(buffer);
1100 snprintf(buffer, SIZE, " Hardware Output: %d\n", mHardwareOutput);
1101 result.append(buffer);
1102 snprintf(buffer, SIZE, " A2DP Output: %d\n", mA2dpOutput);
1103 result.append(buffer);
1104 snprintf(buffer, SIZE, " Duplicated Output: %d\n", mDuplicatedOutput);
1105 result.append(buffer);
1106 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
1107 result.append(buffer);
1108 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
1109 result.append(buffer);
1110 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
1111 result.append(buffer);
1112 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
1113 result.append(buffer);
1114 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1115 result.append(buffer);
1116 snprintf(buffer, SIZE, " Ringer mode: %d\n", mRingerMode);
1117 result.append(buffer);
1118 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1119 result.append(buffer);
1120 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1121 result.append(buffer);
1122 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1123 result.append(buffer);
1124 write(fd, result.string(), result.size());
1125
1126 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1127 write(fd, buffer, strlen(buffer));
1128 for (size_t i = 0; i < mOutputs.size(); i++) {
1129 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1130 write(fd, buffer, strlen(buffer));
1131 mOutputs.valueAt(i)->dump(fd);
1132 }
1133
1134 snprintf(buffer, SIZE, "\nInputs dump:\n");
1135 write(fd, buffer, strlen(buffer));
1136 for (size_t i = 0; i < mInputs.size(); i++) {
1137 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1138 write(fd, buffer, strlen(buffer));
1139 mInputs.valueAt(i)->dump(fd);
1140 }
1141
1142 snprintf(buffer, SIZE, "\nStreams dump:\n");
1143 write(fd, buffer, strlen(buffer));
1144 snprintf(buffer, SIZE, " Stream Index Min Index Max Index Cur Mute Count Can be muted\n");
1145 write(fd, buffer, strlen(buffer));
1146 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1147 snprintf(buffer, SIZE, " %02d", i);
1148 mStreams[i].dump(buffer + 3, SIZE);
1149 write(fd, buffer, strlen(buffer));
1150 }
1151
1152 return NO_ERROR;
1153 }
1154
1155 // ----------------------------------------------------------------------------
1156 // AudioPolicyManager
1157 // ----------------------------------------------------------------------------
1158
1159 // --- class factory
1160
1161
createAudioPolicyManager(AudioPolicyClientInterface * clientInterface)1162 extern "C" AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
1163 {
1164 return new AudioPolicyManager(clientInterface);
1165 }
1166
destroyAudioPolicyManager(AudioPolicyInterface * interface)1167 extern "C" void destroyAudioPolicyManager(AudioPolicyInterface *interface)
1168 {
1169 delete interface;
1170 }
1171
AudioPolicyManager(AudioPolicyClientInterface * clientInterface)1172 AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
1173 : mPhoneState(AudioSystem::MODE_NORMAL), mRingerMode(0), mMusicStopTime(0)
1174 {
1175 mpClientInterface = clientInterface;
1176
1177 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1178 mForceUse[i] = AudioSystem::FORCE_NONE;
1179 }
1180
1181 // devices available by default are speaker, ear piece and microphone
1182 mAvailableOutputDevices = AudioSystem::DEVICE_OUT_EARPIECE |
1183 AudioSystem::DEVICE_OUT_SPEAKER;
1184 mAvailableInputDevices = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1185
1186 mA2dpDeviceAddress = String8("");
1187 mScoDeviceAddress = String8("");
1188
1189 // open hardware output
1190 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1191 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1192 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1193 &outputDesc->mSamplingRate,
1194 &outputDesc->mFormat,
1195 &outputDesc->mChannels,
1196 &outputDesc->mLatency,
1197 outputDesc->mFlags);
1198
1199 if (mHardwareOutput == 0) {
1200 LOGE("Failed to initialize hardware output stream, samplingRate: %d, format %d, channels %d",
1201 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
1202 } else {
1203 mOutputs.add(mHardwareOutput, outputDesc);
1204 setOutputDevice(mHardwareOutput, (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER, true);
1205 }
1206
1207 mA2dpOutput = 0;
1208 mDuplicatedOutput = 0;
1209 }
1210
~AudioPolicyManager()1211 AudioPolicyManager::~AudioPolicyManager()
1212 {
1213 for (size_t i = 0; i < mOutputs.size(); i++) {
1214 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1215 delete mOutputs.valueAt(i);
1216 }
1217 mOutputs.clear();
1218 for (size_t i = 0; i < mInputs.size(); i++) {
1219 mpClientInterface->closeInput(mInputs.keyAt(i));
1220 delete mInputs.valueAt(i);
1221 }
1222 mInputs.clear();
1223 }
1224
1225 // ---
1226
getOutputForDevice(uint32_t device)1227 audio_io_handle_t AudioPolicyManager::getOutputForDevice(uint32_t device)
1228 {
1229 audio_io_handle_t output = 0;
1230 uint32_t lDevice;
1231
1232 for (size_t i = 0; i < mOutputs.size(); i++) {
1233 lDevice = mOutputs.valueAt(i)->device();
1234 LOGV("getOutputForDevice() output %d devices %x", mOutputs.keyAt(i), lDevice);
1235
1236 // We are only considering outputs connected to a mixer here => exclude direct outputs
1237 if ((lDevice == device) &&
1238 !(mOutputs.valueAt(i)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT)) {
1239 output = mOutputs.keyAt(i);
1240 LOGV("getOutputForDevice() found output %d for device %x", output, device);
1241 break;
1242 }
1243 }
1244 return output;
1245 }
1246
getStrategy(AudioSystem::stream_type stream)1247 AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(AudioSystem::stream_type stream)
1248 {
1249 // stream to strategy mapping
1250 switch (stream) {
1251 case AudioSystem::VOICE_CALL:
1252 case AudioSystem::BLUETOOTH_SCO:
1253 return STRATEGY_PHONE;
1254 case AudioSystem::RING:
1255 case AudioSystem::NOTIFICATION:
1256 case AudioSystem::ALARM:
1257 case AudioSystem::ENFORCED_AUDIBLE:
1258 return STRATEGY_SONIFICATION;
1259 case AudioSystem::DTMF:
1260 return STRATEGY_DTMF;
1261 default:
1262 LOGE("unknown stream type");
1263 case AudioSystem::SYSTEM:
1264 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
1265 // while key clicks are played produces a poor result
1266 case AudioSystem::TTS:
1267 case AudioSystem::MUSIC:
1268 return STRATEGY_MEDIA;
1269 }
1270 }
1271
getDeviceForStrategy(routing_strategy strategy)1272 uint32_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy)
1273 {
1274 uint32_t device = 0;
1275
1276 switch (strategy) {
1277 case STRATEGY_DTMF:
1278 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
1279 // when off call, DTMF strategy follows the same rules as MEDIA strategy
1280 device = getDeviceForStrategy(STRATEGY_MEDIA);
1281 break;
1282 }
1283 // when in call, DTMF and PHONE strategies follow the same rules
1284 // FALL THROUGH
1285
1286 case STRATEGY_PHONE:
1287 // for phone strategy, we first consider the forced use and then the available devices by order
1288 // of priority
1289 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
1290 case AudioSystem::FORCE_BT_SCO:
1291 if (mPhoneState != AudioSystem::MODE_IN_CALL || strategy != STRATEGY_DTMF) {
1292 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
1293 if (device) break;
1294 }
1295 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
1296 if (device) break;
1297 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO;
1298 if (device) break;
1299 // if SCO device is requested but no SCO device is available, fall back to default case
1300 // FALL THROUGH
1301
1302 default: // FORCE_NONE
1303 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
1304 if (device) break;
1305 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1306 if (device) break;
1307 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_EARPIECE;
1308 if (device == 0) {
1309 LOGE("getDeviceForStrategy() earpiece device not found");
1310 }
1311 break;
1312
1313 case AudioSystem::FORCE_SPEAKER:
1314 if (mPhoneState != AudioSystem::MODE_IN_CALL || strategy != STRATEGY_DTMF) {
1315 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
1316 if (device) break;
1317 }
1318 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1319 if (device == 0) {
1320 LOGE("getDeviceForStrategy() speaker device not found");
1321 }
1322 break;
1323 }
1324 break;
1325
1326 case STRATEGY_SONIFICATION:
1327
1328 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
1329 // handleIncallSonification().
1330 if (mPhoneState == AudioSystem::MODE_IN_CALL) {
1331 device = getDeviceForStrategy(STRATEGY_PHONE);
1332 break;
1333 }
1334 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1335 if (device == 0) {
1336 LOGE("getDeviceForStrategy() speaker device not found");
1337 }
1338 // The second device used for sonification is the same as the device used by media strategy
1339 // FALL THROUGH
1340
1341 case STRATEGY_MEDIA: {
1342 uint32_t device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1343 if (device2 == 0) {
1344 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1345 if (device2 == 0) {
1346 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1347 if (device2 == 0) {
1348 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1349 if (device2 == 0) {
1350 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
1351 if (device2 == 0) {
1352 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1353 if (device2 == 0) {
1354 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1355 if (device == 0) {
1356 LOGE("getDeviceForStrategy() speaker device not found");
1357 }
1358 }
1359 }
1360 }
1361 }
1362 }
1363 }
1364 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION, 0 otherwise
1365 device |= device2;
1366 // Do not play media stream if in call and the requested device would change the hardware
1367 // output routing
1368 if (mPhoneState == AudioSystem::MODE_IN_CALL &&
1369 !AudioSystem::isA2dpDevice((AudioSystem::audio_devices)device) &&
1370 device != getDeviceForStrategy(STRATEGY_PHONE)) {
1371 device = 0;
1372 LOGV("getDeviceForStrategy() incompatible media and phone devices");
1373 }
1374 } break;
1375
1376 default:
1377 LOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
1378 break;
1379 }
1380
1381 LOGV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
1382 return device;
1383 }
1384
setOutputDevice(audio_io_handle_t output,uint32_t device,bool force,int delayMs)1385 void AudioPolicyManager::setOutputDevice(audio_io_handle_t output, uint32_t device, bool force, int delayMs)
1386 {
1387 LOGV("setOutputDevice() output %d device %x delayMs %d", output, device, delayMs);
1388 if (mOutputs.indexOfKey(output) < 0) {
1389 LOGW("setOutputDevice() unknown output %d", output);
1390 return;
1391 }
1392 #ifdef WITH_A2DP
1393 if (output == mHardwareOutput) {
1394 // clear A2DP devices from device bit field here so that the caller does not have to
1395 // do it in case of multiple device selections
1396 uint32_t device2 = device & ~AudioSystem::DEVICE_OUT_SPEAKER;
1397 if (AudioSystem::isA2dpDevice((AudioSystem::audio_devices)device2)) {
1398 LOGV("setOutputDevice() removing A2DP device");
1399 device &= ~device2;
1400 }
1401 } else if (output == mA2dpOutput) {
1402 // clear hardware devices from device bit field here so that the caller does not have to
1403 // do it in case of multiple device selections (the second device is always DEVICE_OUT_SPEAKER)
1404 // in this case
1405 device &= ~AudioSystem::DEVICE_OUT_SPEAKER;
1406 }
1407 #endif
1408
1409 // doing this check here allows the caller to call setOutputDevice() without conditions
1410 if (device == 0) return;
1411
1412 uint32_t oldDevice = (uint32_t)mOutputs.valueFor(output)->device();
1413 // Do not change the routing if the requested device is the same as current device. Doing this check
1414 // here allows the caller to call setOutputDevice() without conditions
1415 if (device == oldDevice && !force) {
1416 LOGV("setOutputDevice() setting same device %x for output %d", device, output);
1417 return;
1418 }
1419
1420 mOutputs.valueFor(output)->mDevice = device;
1421 // mute media streams if both speaker and headset are selected
1422 if (device == (AudioSystem::DEVICE_OUT_SPEAKER | AudioSystem::DEVICE_OUT_WIRED_HEADSET) ||
1423 device == (AudioSystem::DEVICE_OUT_SPEAKER | AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) {
1424 setStrategyMute(STRATEGY_MEDIA, true, output);
1425 // wait for the PCM output buffers to empty before proceeding with the rest of the command
1426 usleep(mOutputs.valueFor(output)->mLatency*2*1000);
1427 }
1428 // suspend A2D output if SCO device is selected
1429 if (AudioSystem::isBluetoothScoDevice((AudioSystem::audio_devices)device)) {
1430 if (mA2dpOutput && mScoDeviceAddress == mA2dpDeviceAddress) {
1431 mpClientInterface->suspendOutput(mA2dpOutput);
1432 }
1433 }
1434 // do the routing
1435 AudioParameter param = AudioParameter();
1436 param.addInt(String8(AudioParameter::keyRouting), (int)device);
1437 mpClientInterface->setParameters(mHardwareOutput, param.toString(), delayMs);
1438 // update stream volumes according to new device
1439 applyStreamVolumes(output, device, delayMs);
1440
1441 // if disconnecting SCO device, restore A2DP output
1442 if (AudioSystem::isBluetoothScoDevice((AudioSystem::audio_devices)oldDevice)) {
1443 if (mA2dpOutput && mScoDeviceAddress == mA2dpDeviceAddress) {
1444 LOGV("restore A2DP output");
1445 mpClientInterface->restoreOutput(mA2dpOutput);
1446 }
1447 }
1448 // if changing from a combined headset + speaker route, unmute media streams
1449 if (oldDevice == (AudioSystem::DEVICE_OUT_SPEAKER | AudioSystem::DEVICE_OUT_WIRED_HEADSET) ||
1450 oldDevice == (AudioSystem::DEVICE_OUT_SPEAKER | AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) {
1451 setStrategyMute(STRATEGY_MEDIA, false, output, delayMs);
1452 }
1453 }
1454
getDeviceForInputSource(int inputSource)1455 uint32_t AudioPolicyManager::getDeviceForInputSource(int inputSource)
1456 {
1457 uint32_t device;
1458
1459 switch(inputSource) {
1460 case AUDIO_SOURCE_DEFAULT:
1461 case AUDIO_SOURCE_MIC:
1462 case AUDIO_SOURCE_VOICE_RECOGNITION:
1463 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
1464 mAvailableInputDevices & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
1465 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
1466 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_WIRED_HEADSET) {
1467 device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
1468 } else {
1469 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1470 }
1471 break;
1472 case AUDIO_SOURCE_CAMCORDER:
1473 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1474 break;
1475 case AUDIO_SOURCE_VOICE_UPLINK:
1476 case AUDIO_SOURCE_VOICE_DOWNLINK:
1477 case AUDIO_SOURCE_VOICE_CALL:
1478 device = AudioSystem::DEVICE_IN_VOICE_CALL;
1479 break;
1480 default:
1481 LOGW("getInput() invalid input source %d", inputSource);
1482 device = 0;
1483 break;
1484 }
1485 return device;
1486 }
1487
getActiveInput()1488 audio_io_handle_t AudioPolicyManager::getActiveInput()
1489 {
1490 for (size_t i = 0; i < mInputs.size(); i++) {
1491 if (mInputs.valueAt(i)->mRefCount > 0) {
1492 return mInputs.keyAt(i);
1493 }
1494 }
1495 return 0;
1496 }
1497
computeVolume(int stream,int index,audio_io_handle_t output,uint32_t device)1498 float AudioPolicyManager::computeVolume(int stream, int index, audio_io_handle_t output, uint32_t device)
1499 {
1500 float volume = 1.0;
1501 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1502 StreamDescriptor &streamDesc = mStreams[stream];
1503
1504 // Force max volume if stream cannot be muted
1505 if (!streamDesc.mCanBeMuted) index = streamDesc.mIndexMax;
1506
1507 if (device == 0) {
1508 device = outputDesc->device();
1509 }
1510
1511 int volInt = (100 * (index - streamDesc.mIndexMin)) / (streamDesc.mIndexMax - streamDesc.mIndexMin);
1512 volume = AudioSystem::linearToLog(volInt);
1513
1514 // if a heaset is connected, apply the following rules to ring tones and notifications
1515 // to avoid sound level bursts in user's ears:
1516 // - always attenuate ring tones and notifications volume by 6dB
1517 // - if music is playing, always limit the volume to current music volume,
1518 // with a minimum threshold at -36dB so that notification is always perceived.
1519 if ((device &
1520 (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP |
1521 AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
1522 AudioSystem::DEVICE_OUT_WIRED_HEADSET |
1523 AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) &&
1524 (getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION)) {
1525 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
1526 // when the phone is ringing we must consider that music could have been paused just before
1527 // by the music application and behave as if music was active if the last music track was
1528 // just stopped
1529 if (outputDesc->isUsedByStream(AudioSystem::MUSIC) ||
1530 ((mPhoneState == AudioSystem::MODE_RINGTONE) &&
1531 (systemTime() - mMusicStopTime < seconds(SONIFICATION_HEADSET_MUSIC_DELAY)))) {
1532 float musicVol = computeVolume(AudioSystem::MUSIC, mStreams[AudioSystem::MUSIC].mIndexCur, output, device);
1533 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ? musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
1534 if (volume > minVol) {
1535 volume = minVol;
1536 LOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
1537 }
1538 }
1539 }
1540
1541 return volume;
1542 }
1543
checkAndSetVolume(int stream,int index,audio_io_handle_t output,uint32_t device,int delayMs,bool force)1544 status_t AudioPolicyManager::checkAndSetVolume(int stream, int index, audio_io_handle_t output, uint32_t device, int delayMs, bool force)
1545 {
1546
1547 // do not change actual stream volume if the stream is muted
1548 if (mStreams[stream].mMuteCount != 0) {
1549 LOGV("checkAndSetVolume() stream %d muted count %d", stream, mStreams[stream].mMuteCount);
1550 return NO_ERROR;
1551 }
1552
1553 // do not change in call volume if bluetooth is connected and vice versa
1554 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1555 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
1556 LOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
1557 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
1558 return INVALID_OPERATION;
1559 }
1560
1561 float volume = computeVolume(stream, index, output, device || force);
1562 // do not set volume if the float value did not change
1563 if (volume != mOutputs.valueFor(output)->mCurVolume[stream]) {
1564 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
1565 LOGV("setStreamVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
1566 if (stream == AudioSystem::VOICE_CALL ||
1567 stream == AudioSystem::DTMF ||
1568 stream == AudioSystem::BLUETOOTH_SCO) {
1569 float voiceVolume = -1.0;
1570 // offset value to reflect actual hardware volume that never reaches 0
1571 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
1572 volume = 0.01 + 0.99 * volume;
1573 if (stream == AudioSystem::VOICE_CALL) {
1574 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
1575 } else if (stream == AudioSystem::BLUETOOTH_SCO) {
1576 voiceVolume = 1.0;
1577 }
1578 if (voiceVolume >= 0 && output == mHardwareOutput) {
1579 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
1580 }
1581 }
1582 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
1583 }
1584
1585 return NO_ERROR;
1586 }
1587
applyStreamVolumes(audio_io_handle_t output,uint32_t device,int delayMs)1588 void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output, uint32_t device, int delayMs)
1589 {
1590 LOGV("applyStreamVolumes() for output %d and device %x", output, device);
1591
1592 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
1593 checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, device, delayMs);
1594 }
1595 }
1596
setStrategyMute(routing_strategy strategy,bool on,audio_io_handle_t output,int delayMs)1597 void AudioPolicyManager::setStrategyMute(routing_strategy strategy, bool on, audio_io_handle_t output, int delayMs)
1598 {
1599 LOGV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
1600 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
1601 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
1602 setStreamMute(stream, on, output, delayMs);
1603 }
1604 }
1605 }
1606
setStreamMute(int stream,bool on,audio_io_handle_t output,int delayMs)1607 void AudioPolicyManager::setStreamMute(int stream, bool on, audio_io_handle_t output, int delayMs)
1608 {
1609 StreamDescriptor &streamDesc = mStreams[stream];
1610 uint32_t device = mOutputs.valueFor(output)->mDevice;
1611
1612 LOGV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d", stream, on, output, streamDesc.mMuteCount);
1613
1614 if (on) {
1615 if (streamDesc.mMuteCount == 0) {
1616 if (streamDesc.mCanBeMuted) {
1617 checkAndSetVolume(stream, 0, output, device, delayMs);
1618 }
1619 }
1620 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
1621 streamDesc.mMuteCount++;
1622 } else {
1623 if (streamDesc.mMuteCount == 0) {
1624 LOGW("setStreamMute() unmuting non muted stream!");
1625 return;
1626 }
1627 if (--streamDesc.mMuteCount == 0) {
1628 checkAndSetVolume(stream, streamDesc.mIndexCur, output, device, delayMs);
1629 }
1630 }
1631 }
1632
handleIncallSonification(int stream,bool starting,bool stateChange)1633 void AudioPolicyManager::handleIncallSonification(int stream, bool starting, bool stateChange)
1634 {
1635 // if the stream pertains to sonification strategy and we are in call we must
1636 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
1637 // in the device used for phone strategy and play the tone if the selected device does not
1638 // interfere with the device used for phone strategy
1639 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
1640 // many times as there are active tracks on the output
1641
1642 if (getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) {
1643 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mHardwareOutput);
1644 LOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
1645 stream, starting, outputDesc->mDevice, stateChange);
1646 if (outputDesc->isUsedByStream((AudioSystem::stream_type)stream)) {
1647 int muteCount = 1;
1648 if (stateChange) {
1649 muteCount = outputDesc->mRefCount[stream];
1650 }
1651 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
1652 LOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
1653 for (int i = 0; i < muteCount; i++) {
1654 setStreamMute(stream, starting, mHardwareOutput);
1655 }
1656 } else {
1657 LOGV("handleIncallSonification() high visibility ");
1658 if (outputDesc->mDevice & getDeviceForStrategy(STRATEGY_PHONE)) {
1659 LOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
1660 for (int i = 0; i < muteCount; i++) {
1661 setStreamMute(stream, starting, mHardwareOutput);
1662 }
1663 }
1664 if (starting) {
1665 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
1666 } else {
1667 mpClientInterface->stopTone();
1668 }
1669 }
1670 }
1671 }
1672 }
1673
1674
1675 // --- AudioOutputDescriptor class implementation
1676
AudioOutputDescriptor()1677 AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor()
1678 : mSamplingRate(0), mFormat(0), mChannels(0), mLatency(0),
1679 mFlags((AudioSystem::output_flags)0), mDevice(0), mOutput1(0), mOutput2(0)
1680 {
1681 // clear usage count for all stream types
1682 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1683 mRefCount[i] = 0;
1684 mCurVolume[i] = -1.0;
1685 }
1686 }
1687
device()1688 uint32_t AudioPolicyManager::AudioOutputDescriptor::device()
1689 {
1690 uint32_t device = 0;
1691 if (isDuplicated()) {
1692 device = mOutput1->mDevice | mOutput2->mDevice;
1693 } else {
1694 device = mDevice;
1695 }
1696 return device;
1697 }
1698
changeRefCount(AudioSystem::stream_type stream,int delta)1699 void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
1700 {
1701 // forward usage count change to attached outputs
1702 if (isDuplicated()) {
1703 mOutput1->changeRefCount(stream, delta);
1704 mOutput2->changeRefCount(stream, delta);
1705 }
1706 if ((delta + (int)mRefCount[stream]) < 0) {
1707 LOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
1708 mRefCount[stream] = 0;
1709 return;
1710 }
1711 mRefCount[stream] += delta;
1712 LOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
1713 }
1714
isUsedByStrategy(routing_strategy strategy)1715 bool AudioPolicyManager::AudioOutputDescriptor::isUsedByStrategy(routing_strategy strategy)
1716 {
1717 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1718 if (AudioPolicyManager::getStrategy((AudioSystem::stream_type)i) == strategy &&
1719 isUsedByStream((AudioSystem::stream_type)i)) {
1720 return true;
1721 }
1722 }
1723 return false;
1724 }
1725
dump(int fd)1726 status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
1727 {
1728 const size_t SIZE = 256;
1729 char buffer[SIZE];
1730 String8 result;
1731
1732 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
1733 result.append(buffer);
1734 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
1735 result.append(buffer);
1736 snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
1737 result.append(buffer);
1738 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
1739 result.append(buffer);
1740 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
1741 result.append(buffer);
1742 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
1743 result.append(buffer);
1744 snprintf(buffer, SIZE, " Stream volume refCount\n");
1745 result.append(buffer);
1746 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1747 snprintf(buffer, SIZE, " %02d %.03f %d\n", i, mCurVolume[i], mRefCount[i]);
1748 result.append(buffer);
1749 }
1750 write(fd, result.string(), result.size());
1751
1752 return NO_ERROR;
1753 }
1754
1755 // --- AudioInputDescriptor class implementation
1756
AudioInputDescriptor()1757 AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor()
1758 : mSamplingRate(0), mFormat(0), mChannels(0),
1759 mAcoustics((AudioSystem::audio_in_acoustics)0), mDevice(0), mRefCount(0)
1760 {
1761 }
1762
dump(int fd)1763 status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
1764 {
1765 const size_t SIZE = 256;
1766 char buffer[SIZE];
1767 String8 result;
1768
1769 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
1770 result.append(buffer);
1771 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
1772 result.append(buffer);
1773 snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
1774 result.append(buffer);
1775 snprintf(buffer, SIZE, " Acoustics %08x\n", mAcoustics);
1776 result.append(buffer);
1777 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
1778 result.append(buffer);
1779 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
1780 result.append(buffer);
1781 write(fd, result.string(), result.size());
1782
1783 return NO_ERROR;
1784 }
1785
1786 // --- StreamDescriptor class implementation
1787
dump(char * buffer,size_t size)1788 void AudioPolicyManager::StreamDescriptor::dump(char* buffer, size_t size)
1789 {
1790 snprintf(buffer, size, " %02d %02d %02d %02d %d\n",
1791 mIndexMin,
1792 mIndexMax,
1793 mIndexCur,
1794 mMuteCount,
1795 mCanBeMuted);
1796 }
1797
1798
1799 }; // namespace android
1800