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