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