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