blob: 549d66118302bd4b89e5142402a956223612b612 [file] [log] [blame]
Eric Laurentcef3cd72009-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 Laurentf1451082010-01-28 13:42:59 -080018//#define LOG_NDEBUG 0
Eric Laurentcef3cd72009-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 Laurentce3e0382010-02-24 11:51:43 -080085 if (mA2dpOutput != 0 &&
86 mPhoneState != AudioSystem::MODE_NORMAL) {
Eric Laurentcef3cd72009-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 Laurentce3e0382010-02-24 11:51:43 -0800119 if (mA2dpOutput != 0 &&
120 mPhoneState != AudioSystem::MODE_NORMAL) {
Eric Laurentcef3cd72009-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 Laurentce3e0382010-02-24 11:51:43 -0800278 // suspend A2DP output if a SCO device is present.
279 if (mA2dpOutput != 0 && mScoDeviceAddress != "") {
Eric Laurentcef3cd72009-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 Laurent22e1ca32010-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 Laurentcef3cd72009-12-10 01:03:50 -0800309 // change routing is necessary
Eric Laurent22e1ca32010-02-23 09:48:31 -0800310 setOutputDevice(mHardwareOutput, newDevice, force, delayMs);
Eric Laurentcef3cd72009-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 Laurent22e1ca32010-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 Laurentcef3cd72009-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 Trivi758559e2010-03-09 09:26:08 -0800347 bool forceVolumeReeval = false;
Eric Laurentcef3cd72009-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 Trivi758559e2010-03-09 09:26:08 -0800378 forceVolumeReeval = true;
Eric Laurentcef3cd72009-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 Trivi758559e2010-03-09 09:26:08 -0800393 if (forceVolumeReeval) {
394 applyStreamVolumes(mHardwareOutput, newDevice);
395 }
Eric Laurentcef3cd72009-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
Eric Laurentef9500f2010-03-11 14:47:00 -0800461 // open a direct output if required by specified parameters
462 if (needsDirectOuput(stream, samplingRate, format, channels, flags, device)) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800463
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);
Eric Laurentef9500f2010-03-11 14:47:00 -0800472 outputDesc->mRefCount[stream] = 0;
Eric Laurentcef3cd72009-12-10 01:03:50 -0800473 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
Eric Laurentef9500f2010-03-11 14:47:00 -0800609 if (output != mHardwareOutput) {
610 setOutputDevice(mHardwareOutput, getNewDevice(mHardwareOutput), true);
611 }
Eric Laurentcef3cd72009-12-10 01:03:50 -0800612 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
Eric Laurentcc9c4242010-05-25 09:31:59 -0700905 mPhoneState(AudioSystem::MODE_NORMAL), mRingerMode(0), mMusicStopTime(0), mLimitRingtoneVolume(false),
906 mLastVoiceVolume(-1.0f)
Eric Laurentcef3cd72009-12-10 01:03:50 -0800907{
908 mpClientInterface = clientInterface;
909
910 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
911 mForceUse[i] = AudioSystem::FORCE_NONE;
912 }
913
914 // devices available by default are speaker, ear piece and microphone
915 mAvailableOutputDevices = AudioSystem::DEVICE_OUT_EARPIECE |
916 AudioSystem::DEVICE_OUT_SPEAKER;
917 mAvailableInputDevices = AudioSystem::DEVICE_IN_BUILTIN_MIC;
918
919#ifdef WITH_A2DP
920 mA2dpOutput = 0;
921 mDuplicatedOutput = 0;
922 mA2dpDeviceAddress = String8("");
923#endif
924 mScoDeviceAddress = String8("");
925
926 // open hardware output
927 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
928 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
929 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
930 &outputDesc->mSamplingRate,
931 &outputDesc->mFormat,
932 &outputDesc->mChannels,
933 &outputDesc->mLatency,
934 outputDesc->mFlags);
935
936 if (mHardwareOutput == 0) {
937 LOGE("Failed to initialize hardware output stream, samplingRate: %d, format %d, channels %d",
938 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
939 } else {
940 addOutput(mHardwareOutput, outputDesc);
941 setOutputDevice(mHardwareOutput, (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER, true);
942 }
943
944 updateDeviceForStrategy();
945#ifdef AUDIO_POLICY_TEST
946 AudioParameter outputCmd = AudioParameter();
947 outputCmd.addInt(String8("set_id"), 0);
948 mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString());
949
950 mTestDevice = AudioSystem::DEVICE_OUT_SPEAKER;
951 mTestSamplingRate = 44100;
952 mTestFormat = AudioSystem::PCM_16_BIT;
953 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
954 mTestLatencyMs = 0;
955 mCurOutput = 0;
956 mDirectOutput = false;
957 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
958 mTestOutputs[i] = 0;
959 }
960
961 const size_t SIZE = 256;
962 char buffer[SIZE];
963 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
964 run(buffer, ANDROID_PRIORITY_AUDIO);
965#endif //AUDIO_POLICY_TEST
966}
967
968AudioPolicyManagerBase::~AudioPolicyManagerBase()
969{
970#ifdef AUDIO_POLICY_TEST
971 exit();
972#endif //AUDIO_POLICY_TEST
973 for (size_t i = 0; i < mOutputs.size(); i++) {
974 mpClientInterface->closeOutput(mOutputs.keyAt(i));
975 delete mOutputs.valueAt(i);
976 }
977 mOutputs.clear();
978 for (size_t i = 0; i < mInputs.size(); i++) {
979 mpClientInterface->closeInput(mInputs.keyAt(i));
980 delete mInputs.valueAt(i);
981 }
982 mInputs.clear();
983}
984
985#ifdef AUDIO_POLICY_TEST
986bool AudioPolicyManagerBase::threadLoop()
987{
988 LOGV("entering threadLoop()");
989 while (!exitPending())
990 {
991 String8 command;
992 int valueInt;
993 String8 value;
994
995 Mutex::Autolock _l(mLock);
996 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
997
998 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
999 AudioParameter param = AudioParameter(command);
1000
1001 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1002 valueInt != 0) {
1003 LOGV("Test command %s received", command.string());
1004 String8 target;
1005 if (param.get(String8("target"), target) != NO_ERROR) {
1006 target = "Manager";
1007 }
1008 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1009 param.remove(String8("test_cmd_policy_output"));
1010 mCurOutput = valueInt;
1011 }
1012 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1013 param.remove(String8("test_cmd_policy_direct"));
1014 if (value == "false") {
1015 mDirectOutput = false;
1016 } else if (value == "true") {
1017 mDirectOutput = true;
1018 }
1019 }
1020 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1021 param.remove(String8("test_cmd_policy_input"));
1022 mTestInput = valueInt;
1023 }
1024
1025 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1026 param.remove(String8("test_cmd_policy_format"));
1027 int format = AudioSystem::INVALID_FORMAT;
1028 if (value == "PCM 16 bits") {
1029 format = AudioSystem::PCM_16_BIT;
1030 } else if (value == "PCM 8 bits") {
1031 format = AudioSystem::PCM_8_BIT;
1032 } else if (value == "Compressed MP3") {
1033 format = AudioSystem::MP3;
1034 }
1035 if (format != AudioSystem::INVALID_FORMAT) {
1036 if (target == "Manager") {
1037 mTestFormat = format;
1038 } else if (mTestOutputs[mCurOutput] != 0) {
1039 AudioParameter outputParam = AudioParameter();
1040 outputParam.addInt(String8("format"), format);
1041 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1042 }
1043 }
1044 }
1045 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1046 param.remove(String8("test_cmd_policy_channels"));
1047 int channels = 0;
1048
1049 if (value == "Channels Stereo") {
1050 channels = AudioSystem::CHANNEL_OUT_STEREO;
1051 } else if (value == "Channels Mono") {
1052 channels = AudioSystem::CHANNEL_OUT_MONO;
1053 }
1054 if (channels != 0) {
1055 if (target == "Manager") {
1056 mTestChannels = channels;
1057 } else if (mTestOutputs[mCurOutput] != 0) {
1058 AudioParameter outputParam = AudioParameter();
1059 outputParam.addInt(String8("channels"), channels);
1060 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1061 }
1062 }
1063 }
1064 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1065 param.remove(String8("test_cmd_policy_sampleRate"));
1066 if (valueInt >= 0 && valueInt <= 96000) {
1067 int samplingRate = valueInt;
1068 if (target == "Manager") {
1069 mTestSamplingRate = samplingRate;
1070 } else if (mTestOutputs[mCurOutput] != 0) {
1071 AudioParameter outputParam = AudioParameter();
1072 outputParam.addInt(String8("sampling_rate"), samplingRate);
1073 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1074 }
1075 }
1076 }
1077
1078 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1079 param.remove(String8("test_cmd_policy_reopen"));
1080
1081 mpClientInterface->closeOutput(mHardwareOutput);
1082 delete mOutputs.valueFor(mHardwareOutput);
1083 mOutputs.removeItem(mHardwareOutput);
1084
1085 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1086 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1087 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1088 &outputDesc->mSamplingRate,
1089 &outputDesc->mFormat,
1090 &outputDesc->mChannels,
1091 &outputDesc->mLatency,
1092 outputDesc->mFlags);
1093 if (mHardwareOutput == 0) {
1094 LOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1095 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
1096 } else {
1097 AudioParameter outputCmd = AudioParameter();
1098 outputCmd.addInt(String8("set_id"), 0);
1099 mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString());
1100 addOutput(mHardwareOutput, outputDesc);
1101 }
1102 }
1103
1104
1105 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1106 }
1107 }
1108 return false;
1109}
1110
1111void AudioPolicyManagerBase::exit()
1112{
1113 {
1114 AutoMutex _l(mLock);
1115 requestExit();
1116 mWaitWorkCV.signal();
1117 }
1118 requestExitAndWait();
1119}
1120
1121int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1122{
1123 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1124 if (output == mTestOutputs[i]) return i;
1125 }
1126 return 0;
1127}
1128#endif //AUDIO_POLICY_TEST
1129
1130// ---
1131
1132void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1133{
1134 outputDesc->mId = id;
1135 mOutputs.add(id, outputDesc);
1136}
1137
1138
1139#ifdef WITH_A2DP
1140status_t AudioPolicyManagerBase::handleA2dpConnection(AudioSystem::audio_devices device,
1141 const char *device_address)
1142{
1143 // when an A2DP device is connected, open an A2DP and a duplicated output
1144 LOGV("opening A2DP output for device %s", device_address);
1145 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1146 outputDesc->mDevice = device;
1147 mA2dpOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1148 &outputDesc->mSamplingRate,
1149 &outputDesc->mFormat,
1150 &outputDesc->mChannels,
1151 &outputDesc->mLatency,
1152 outputDesc->mFlags);
1153 if (mA2dpOutput) {
1154 // add A2DP output descriptor
1155 addOutput(mA2dpOutput, outputDesc);
1156 // set initial stream volume for A2DP device
1157 applyStreamVolumes(mA2dpOutput, device);
1158 if (a2dpUsedForSonification()) {
1159 mDuplicatedOutput = mpClientInterface->openDuplicateOutput(mA2dpOutput, mHardwareOutput);
1160 }
1161 if (mDuplicatedOutput != 0 ||
1162 !a2dpUsedForSonification()) {
1163 // If both A2DP and duplicated outputs are open, send device address to A2DP hardware
1164 // interface
1165 AudioParameter param;
1166 param.add(String8("a2dp_sink_address"), String8(device_address));
1167 mpClientInterface->setParameters(mA2dpOutput, param.toString());
1168 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
1169
1170 if (a2dpUsedForSonification()) {
1171 // add duplicated output descriptor
1172 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor();
1173 dupOutputDesc->mOutput1 = mOutputs.valueFor(mHardwareOutput);
1174 dupOutputDesc->mOutput2 = mOutputs.valueFor(mA2dpOutput);
1175 dupOutputDesc->mSamplingRate = outputDesc->mSamplingRate;
1176 dupOutputDesc->mFormat = outputDesc->mFormat;
1177 dupOutputDesc->mChannels = outputDesc->mChannels;
1178 dupOutputDesc->mLatency = outputDesc->mLatency;
1179 addOutput(mDuplicatedOutput, dupOutputDesc);
1180 applyStreamVolumes(mDuplicatedOutput, device);
1181 }
1182 } else {
1183 LOGW("getOutput() could not open duplicated output for %d and %d",
1184 mHardwareOutput, mA2dpOutput);
1185 mpClientInterface->closeOutput(mA2dpOutput);
1186 mOutputs.removeItem(mA2dpOutput);
1187 mA2dpOutput = 0;
1188 delete outputDesc;
1189 return NO_INIT;
1190 }
1191 } else {
1192 LOGW("setDeviceConnectionState() could not open A2DP output for device %x", device);
1193 delete outputDesc;
1194 return NO_INIT;
1195 }
1196 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
1197
Eric Laurentce3e0382010-02-24 11:51:43 -08001198 if (mScoDeviceAddress != "") {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001199 // It is normal to suspend twice if we are both in call,
1200 // and have the hardware audio output routed to BT SCO
1201 if (mPhoneState != AudioSystem::MODE_NORMAL) {
1202 mpClientInterface->suspendOutput(mA2dpOutput);
1203 }
1204 if (AudioSystem::isBluetoothScoDevice((AudioSystem::audio_devices)hwOutputDesc->device())) {
1205 mpClientInterface->suspendOutput(mA2dpOutput);
1206 }
1207 }
1208
1209 if (!a2dpUsedForSonification()) {
1210 // mute music on A2DP output if a notification or ringtone is playing
1211 uint32_t refCount = hwOutputDesc->strategyRefCount(STRATEGY_SONIFICATION);
1212 for (uint32_t i = 0; i < refCount; i++) {
1213 setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput);
1214 }
1215 }
1216 return NO_ERROR;
1217}
1218
1219status_t AudioPolicyManagerBase::handleA2dpDisconnection(AudioSystem::audio_devices device,
1220 const char *device_address)
1221{
1222 if (mA2dpOutput == 0) {
1223 LOGW("setDeviceConnectionState() disconnecting A2DP and no A2DP output!");
1224 return INVALID_OPERATION;
1225 }
1226
1227 if (mA2dpDeviceAddress != device_address) {
1228 LOGW("setDeviceConnectionState() disconnecting unknow A2DP sink address %s", device_address);
1229 return INVALID_OPERATION;
1230 }
1231
Eric Laurent22e1ca32010-02-23 09:48:31 -08001232 // mute media strategy to avoid outputting sound on hardware output while music stream
Eric Laurentcef3cd72009-12-10 01:03:50 -08001233 // is switched from A2DP output and before music is paused by music application
1234 setStrategyMute(STRATEGY_MEDIA, true, mHardwareOutput);
Eric Laurent22e1ca32010-02-23 09:48:31 -08001235 setStrategyMute(STRATEGY_MEDIA, false, mHardwareOutput, MUTE_TIME_MS);
Eric Laurentcef3cd72009-12-10 01:03:50 -08001236
1237 if (!a2dpUsedForSonification()) {
1238 // unmute music on A2DP output if a notification or ringtone is playing
1239 uint32_t refCount = mOutputs.valueFor(mHardwareOutput)->strategyRefCount(STRATEGY_SONIFICATION);
1240 for (uint32_t i = 0; i < refCount; i++) {
1241 setStrategyMute(STRATEGY_MEDIA, false, mA2dpOutput);
1242 }
1243 }
1244 mA2dpDeviceAddress = "";
1245 return NO_ERROR;
1246}
1247
1248void AudioPolicyManagerBase::closeA2dpOutputs()
1249{
1250 LOGV("setDeviceConnectionState() closing A2DP and duplicated output!");
1251
1252 if (mDuplicatedOutput != 0) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001253 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueFor(mDuplicatedOutput);
1254 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
1255 // As all active tracks on duplicated output will be deleted,
1256 // and as they were also referenced on hardware output, the reference
1257 // count for their stream type must be adjusted accordingly on
1258 // hardware output.
1259 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1260 int refCount = dupOutputDesc->mRefCount[i];
1261 hwOutputDesc->changeRefCount((AudioSystem::stream_type)i,-refCount);
1262 }
1263
Eric Laurentcef3cd72009-12-10 01:03:50 -08001264 mpClientInterface->closeOutput(mDuplicatedOutput);
1265 delete mOutputs.valueFor(mDuplicatedOutput);
1266 mOutputs.removeItem(mDuplicatedOutput);
1267 mDuplicatedOutput = 0;
1268 }
1269 if (mA2dpOutput != 0) {
1270 AudioParameter param;
1271 param.add(String8("closing"), String8("true"));
1272 mpClientInterface->setParameters(mA2dpOutput, param.toString());
1273 mpClientInterface->closeOutput(mA2dpOutput);
1274 delete mOutputs.valueFor(mA2dpOutput);
1275 mOutputs.removeItem(mA2dpOutput);
1276 mA2dpOutput = 0;
1277 }
1278}
1279
1280void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy, uint32_t &newDevice)
1281{
1282 uint32_t prevDevice = getDeviceForStrategy(strategy);
1283 uint32_t curDevice = getDeviceForStrategy(strategy, false);
1284 bool a2dpWasUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(prevDevice & ~AudioSystem::DEVICE_OUT_SPEAKER));
1285 bool a2dpIsUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(curDevice & ~AudioSystem::DEVICE_OUT_SPEAKER));
1286 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
1287 AudioOutputDescriptor *a2dpOutputDesc;
1288
1289 if (a2dpWasUsed && !a2dpIsUsed) {
1290 bool dupUsed = a2dpUsedForSonification() && a2dpWasUsed && (AudioSystem::popCount(prevDevice) == 2);
1291
1292 if (dupUsed) {
1293 LOGV("checkOutputForStrategy() moving strategy %d to duplicated", strategy);
1294 a2dpOutputDesc = mOutputs.valueFor(mDuplicatedOutput);
1295 } else {
1296 LOGV("checkOutputForStrategy() moving strategy %d to a2dp", strategy);
1297 a2dpOutputDesc = mOutputs.valueFor(mA2dpOutput);
1298 }
1299
1300 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1301 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
1302 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, mHardwareOutput);
Eric Laurentcef3cd72009-12-10 01:03:50 -08001303 }
1304 }
Eric Laurentfe2e0752010-03-06 15:46:31 -08001305 // do not change newDevice if it was already set before this call by a previous call to
Eric Laurentcef3cd72009-12-10 01:03:50 -08001306 // getNewDevice() or checkOutputForStrategy() for a strategy with higher priority
1307 if (newDevice == 0 && hwOutputDesc->isUsedByStrategy(strategy)) {
1308 newDevice = getDeviceForStrategy(strategy, false);
1309 }
1310 }
1311 if (a2dpIsUsed && !a2dpWasUsed) {
1312 bool dupUsed = a2dpUsedForSonification() && a2dpIsUsed && (AudioSystem::popCount(curDevice) == 2);
1313 audio_io_handle_t a2dpOutput;
1314
1315 if (dupUsed) {
1316 LOGV("checkOutputForStrategy() moving strategy %d from duplicated", strategy);
1317 a2dpOutputDesc = mOutputs.valueFor(mDuplicatedOutput);
1318 a2dpOutput = mDuplicatedOutput;
1319 } else {
1320 LOGV("checkOutputForStrategy() moving strategy %d from a2dp", strategy);
1321 a2dpOutputDesc = mOutputs.valueFor(mA2dpOutput);
1322 a2dpOutput = mA2dpOutput;
1323 }
1324
1325 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1326 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
1327 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, a2dpOutput);
Eric Laurentcef3cd72009-12-10 01:03:50 -08001328 }
1329 }
1330 }
1331}
1332
1333void AudioPolicyManagerBase::checkOutputForAllStrategies(uint32_t &newDevice)
1334{
1335 // Check strategies in order of priority so that once newDevice is set
1336 // for a given strategy it is not modified by subsequent calls to
1337 // checkOutputForStrategy()
1338 checkOutputForStrategy(STRATEGY_PHONE, newDevice);
1339 checkOutputForStrategy(STRATEGY_SONIFICATION, newDevice);
1340 checkOutputForStrategy(STRATEGY_MEDIA, newDevice);
1341 checkOutputForStrategy(STRATEGY_DTMF, newDevice);
1342}
1343
1344#endif
1345
1346uint32_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
1347{
1348 uint32_t device = 0;
1349
1350 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1351 // check the following by order of priority to request a routing change if necessary:
1352 // 1: we are in call or the strategy phone is active on the hardware output:
1353 // use device for strategy phone
1354 // 2: the strategy sonification is active on the hardware output:
1355 // use device for strategy sonification
1356 // 3: the strategy media is active on the hardware output:
1357 // use device for strategy media
1358 // 4: the strategy DTMF is active on the hardware output:
1359 // use device for strategy DTMF
1360 if (mPhoneState == AudioSystem::MODE_IN_CALL ||
1361 outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
1362 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
1363 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
1364 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
1365 } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
1366 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
1367 } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
1368 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
1369 }
1370
1371 LOGV("getNewDevice() selected device %x", device);
1372 return device;
1373}
1374
1375AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(AudioSystem::stream_type stream)
1376{
1377 // stream to strategy mapping
1378 switch (stream) {
1379 case AudioSystem::VOICE_CALL:
1380 case AudioSystem::BLUETOOTH_SCO:
1381 return STRATEGY_PHONE;
1382 case AudioSystem::RING:
1383 case AudioSystem::NOTIFICATION:
1384 case AudioSystem::ALARM:
1385 case AudioSystem::ENFORCED_AUDIBLE:
1386 return STRATEGY_SONIFICATION;
1387 case AudioSystem::DTMF:
1388 return STRATEGY_DTMF;
1389 default:
1390 LOGE("unknown stream type");
1391 case AudioSystem::SYSTEM:
1392 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
1393 // while key clicks are played produces a poor result
1394 case AudioSystem::TTS:
1395 case AudioSystem::MUSIC:
1396 return STRATEGY_MEDIA;
1397 }
1398}
1399
1400uint32_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy, bool fromCache)
1401{
1402 uint32_t device = 0;
1403
1404 if (fromCache) {
1405 LOGV("getDeviceForStrategy() from cache strategy %d, device %x", strategy, mDeviceForStrategy[strategy]);
1406 return mDeviceForStrategy[strategy];
1407 }
1408
1409 switch (strategy) {
1410 case STRATEGY_DTMF:
1411 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
1412 // when off call, DTMF strategy follows the same rules as MEDIA strategy
1413 device = getDeviceForStrategy(STRATEGY_MEDIA, false);
1414 break;
1415 }
1416 // when in call, DTMF and PHONE strategies follow the same rules
1417 // FALL THROUGH
1418
1419 case STRATEGY_PHONE:
1420 // for phone strategy, we first consider the forced use and then the available devices by order
1421 // of priority
1422 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
1423 case AudioSystem::FORCE_BT_SCO:
1424 if (mPhoneState != AudioSystem::MODE_IN_CALL || strategy != STRATEGY_DTMF) {
1425 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
1426 if (device) break;
1427 }
1428 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
1429 if (device) break;
1430 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO;
1431 if (device) break;
1432 // if SCO device is requested but no SCO device is available, fall back to default case
1433 // FALL THROUGH
1434
1435 default: // FORCE_NONE
1436 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
1437 if (device) break;
1438 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1439 if (device) break;
Jean-Michel Trivie4b8c422010-03-13 12:33:15 -08001440#ifdef WITH_A2DP
1441 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
1442 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
1443 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1444 if (device) break;
1445 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1446 if (device) break;
1447 }
1448#endif
Eric Laurentcef3cd72009-12-10 01:03:50 -08001449 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_EARPIECE;
1450 if (device == 0) {
1451 LOGE("getDeviceForStrategy() earpiece device not found");
1452 }
1453 break;
1454
1455 case AudioSystem::FORCE_SPEAKER:
1456 if (mPhoneState != AudioSystem::MODE_IN_CALL || strategy != STRATEGY_DTMF) {
1457 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
1458 if (device) break;
1459 }
Jean-Michel Trivie4b8c422010-03-13 12:33:15 -08001460#ifdef WITH_A2DP
1461 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
1462 // A2DP speaker when forcing to speaker output
1463 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
1464 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1465 if (device) break;
1466 }
1467#endif
Eric Laurentcef3cd72009-12-10 01:03:50 -08001468 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1469 if (device == 0) {
1470 LOGE("getDeviceForStrategy() speaker device not found");
1471 }
1472 break;
1473 }
1474 break;
1475
1476 case STRATEGY_SONIFICATION:
1477
1478 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
1479 // handleIncallSonification().
1480 if (mPhoneState == AudioSystem::MODE_IN_CALL) {
1481 device = getDeviceForStrategy(STRATEGY_PHONE, false);
1482 break;
1483 }
1484 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1485 if (device == 0) {
1486 LOGE("getDeviceForStrategy() speaker device not found");
1487 }
1488 // The second device used for sonification is the same as the device used by media strategy
1489 // FALL THROUGH
1490
1491 case STRATEGY_MEDIA: {
1492 uint32_t device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
Eric Laurentfe2e0752010-03-06 15:46:31 -08001493 if (device2 == 0) {
1494 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
1495 }
1496 if (device2 == 0) {
1497 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1498 }
Eric Laurentcef3cd72009-12-10 01:03:50 -08001499#ifdef WITH_A2DP
1500 if (mA2dpOutput != 0) {
1501 if (strategy == STRATEGY_SONIFICATION && !a2dpUsedForSonification()) {
1502 break;
1503 }
1504 if (device2 == 0) {
1505 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1506 }
1507 if (device2 == 0) {
1508 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1509 }
1510 if (device2 == 0) {
1511 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1512 }
1513 }
1514#endif
1515 if (device2 == 0) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001516 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1517 }
1518
1519 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION, 0 otherwise
1520 device |= device2;
1521 if (device == 0) {
1522 LOGE("getDeviceForStrategy() speaker device not found");
1523 }
1524 } break;
1525
1526 default:
1527 LOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
1528 break;
1529 }
1530
1531 LOGV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
1532 return device;
1533}
1534
1535void AudioPolicyManagerBase::updateDeviceForStrategy()
1536{
1537 for (int i = 0; i < NUM_STRATEGIES; i++) {
1538 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false);
1539 }
1540}
1541
1542void AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output, uint32_t device, bool force, int delayMs)
1543{
1544 LOGV("setOutputDevice() output %d device %x delayMs %d", output, device, delayMs);
1545 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1546
1547
1548 if (outputDesc->isDuplicated()) {
1549 setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
1550 setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
1551 return;
1552 }
1553#ifdef WITH_A2DP
1554 // filter devices according to output selected
Eric Laurentef9500f2010-03-11 14:47:00 -08001555 if (output == mA2dpOutput) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001556 device &= AudioSystem::DEVICE_OUT_ALL_A2DP;
Eric Laurentef9500f2010-03-11 14:47:00 -08001557 } else {
1558 device &= ~AudioSystem::DEVICE_OUT_ALL_A2DP;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001559 }
1560#endif
1561
1562 uint32_t prevDevice = (uint32_t)outputDesc->device();
1563 // Do not change the routing if:
1564 // - the requestede device is 0
1565 // - the requested device is the same as current device and force is not specified.
1566 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentef9500f2010-03-11 14:47:00 -08001567 if ((device == 0 || device == prevDevice) && !force) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001568 LOGV("setOutputDevice() setting same device %x or null device for output %d", device, output);
1569 return;
1570 }
1571
1572 outputDesc->mDevice = device;
1573 // mute media streams if both speaker and headset are selected
1574 if (output == mHardwareOutput && AudioSystem::popCount(device) == 2) {
1575 setStrategyMute(STRATEGY_MEDIA, true, output);
1576 // wait for the PCM output buffers to empty before proceeding with the rest of the command
1577 usleep(outputDesc->mLatency*2*1000);
1578 }
1579#ifdef WITH_A2DP
Eric Laurentce3e0382010-02-24 11:51:43 -08001580 // suspend A2DP output if SCO device is selected
Eric Laurentcef3cd72009-12-10 01:03:50 -08001581 if (AudioSystem::isBluetoothScoDevice((AudioSystem::audio_devices)device)) {
Eric Laurentce3e0382010-02-24 11:51:43 -08001582 if (mA2dpOutput != 0) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001583 mpClientInterface->suspendOutput(mA2dpOutput);
1584 }
1585 }
1586#endif
1587 // do the routing
1588 AudioParameter param = AudioParameter();
1589 param.addInt(String8(AudioParameter::keyRouting), (int)device);
1590 mpClientInterface->setParameters(mHardwareOutput, param.toString(), delayMs);
1591 // update stream volumes according to new device
1592 applyStreamVolumes(output, device, delayMs);
1593
1594#ifdef WITH_A2DP
1595 // if disconnecting SCO device, restore A2DP output
1596 if (AudioSystem::isBluetoothScoDevice((AudioSystem::audio_devices)prevDevice)) {
Eric Laurentce3e0382010-02-24 11:51:43 -08001597 if (mA2dpOutput != 0) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001598 LOGV("restore A2DP output");
1599 mpClientInterface->restoreOutput(mA2dpOutput);
1600 }
1601 }
1602#endif
1603 // if changing from a combined headset + speaker route, unmute media streams
1604 if (output == mHardwareOutput && AudioSystem::popCount(prevDevice) == 2) {
1605 setStrategyMute(STRATEGY_MEDIA, false, output, delayMs);
1606 }
1607}
1608
1609uint32_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
1610{
1611 uint32_t device;
1612
1613 switch(inputSource) {
1614 case AUDIO_SOURCE_DEFAULT:
1615 case AUDIO_SOURCE_MIC:
1616 case AUDIO_SOURCE_VOICE_RECOGNITION:
1617 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
1618 mAvailableInputDevices & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
1619 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
1620 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_WIRED_HEADSET) {
1621 device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
1622 } else {
1623 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1624 }
1625 break;
1626 case AUDIO_SOURCE_CAMCORDER:
1627 if (hasBackMicrophone()) {
1628 device = AudioSystem::DEVICE_IN_BACK_MIC;
1629 } else {
1630 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1631 }
1632 break;
1633 case AUDIO_SOURCE_VOICE_UPLINK:
1634 case AUDIO_SOURCE_VOICE_DOWNLINK:
1635 case AUDIO_SOURCE_VOICE_CALL:
1636 device = AudioSystem::DEVICE_IN_VOICE_CALL;
1637 break;
1638 default:
1639 LOGW("getInput() invalid input source %d", inputSource);
1640 device = 0;
1641 break;
1642 }
1643 LOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
1644 return device;
1645}
1646
1647audio_io_handle_t AudioPolicyManagerBase::getActiveInput()
1648{
1649 for (size_t i = 0; i < mInputs.size(); i++) {
1650 if (mInputs.valueAt(i)->mRefCount > 0) {
1651 return mInputs.keyAt(i);
1652 }
1653 }
1654 return 0;
1655}
1656
1657float AudioPolicyManagerBase::computeVolume(int stream, int index, audio_io_handle_t output, uint32_t device)
1658{
1659 float volume = 1.0;
1660 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1661 StreamDescriptor &streamDesc = mStreams[stream];
1662
1663 if (device == 0) {
1664 device = outputDesc->device();
1665 }
1666
1667 int volInt = (100 * (index - streamDesc.mIndexMin)) / (streamDesc.mIndexMax - streamDesc.mIndexMin);
1668 volume = AudioSystem::linearToLog(volInt);
1669
Eric Laurentef9500f2010-03-11 14:47:00 -08001670 // if a headset is connected, apply the following rules to ring tones and notifications
Eric Laurentcef3cd72009-12-10 01:03:50 -08001671 // to avoid sound level bursts in user's ears:
1672 // - always attenuate ring tones and notifications volume by 6dB
1673 // - if music is playing, always limit the volume to current music volume,
1674 // with a minimum threshold at -36dB so that notification is always perceived.
1675 if ((device &
1676 (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP |
1677 AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
1678 AudioSystem::DEVICE_OUT_WIRED_HEADSET |
1679 AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) &&
1680 (getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) &&
1681 streamDesc.mCanBeMuted) {
1682 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
1683 // when the phone is ringing we must consider that music could have been paused just before
1684 // by the music application and behave as if music was active if the last music track was
1685 // just stopped
1686 if (outputDesc->mRefCount[AudioSystem::MUSIC] || mLimitRingtoneVolume) {
1687 float musicVol = computeVolume(AudioSystem::MUSIC, mStreams[AudioSystem::MUSIC].mIndexCur, output, device);
1688 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ? musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
1689 if (volume > minVol) {
1690 volume = minVol;
1691 LOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
1692 }
1693 }
1694 }
1695
1696 return volume;
1697}
1698
1699status_t AudioPolicyManagerBase::checkAndSetVolume(int stream, int index, audio_io_handle_t output, uint32_t device, int delayMs, bool force)
1700{
1701
1702 // do not change actual stream volume if the stream is muted
1703 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
1704 LOGV("checkAndSetVolume() stream %d muted count %d", stream, mOutputs.valueFor(output)->mMuteCount[stream]);
1705 return NO_ERROR;
1706 }
1707
1708 // do not change in call volume if bluetooth is connected and vice versa
1709 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1710 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
1711 LOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
1712 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
1713 return INVALID_OPERATION;
1714 }
1715
1716 float volume = computeVolume(stream, index, output, device);
Eric Laurentcc9c4242010-05-25 09:31:59 -07001717 // We actually change the volume if:
1718 // - the float value returned by computeVolume() changed
1719 // - the force flag is set
1720 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
1721 force) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001722 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
1723 LOGV("setStreamVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
1724 if (stream == AudioSystem::VOICE_CALL ||
1725 stream == AudioSystem::DTMF ||
1726 stream == AudioSystem::BLUETOOTH_SCO) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001727 // offset value to reflect actual hardware volume that never reaches 0
1728 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
1729 volume = 0.01 + 0.99 * volume;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001730 }
1731 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
1732 }
1733
Eric Laurentcc9c4242010-05-25 09:31:59 -07001734 if (stream == AudioSystem::VOICE_CALL ||
1735 stream == AudioSystem::BLUETOOTH_SCO) {
1736 float voiceVolume;
1737 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
1738 if (stream == AudioSystem::VOICE_CALL) {
1739 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
1740 } else {
1741 voiceVolume = 1.0;
1742 }
1743 if (voiceVolume != mLastVoiceVolume && output == mHardwareOutput) {
1744 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
1745 mLastVoiceVolume = voiceVolume;
1746 }
1747 }
1748
Eric Laurentcef3cd72009-12-10 01:03:50 -08001749 return NO_ERROR;
1750}
1751
1752void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output, uint32_t device, int delayMs)
1753{
1754 LOGV("applyStreamVolumes() for output %d and device %x", output, device);
1755
1756 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
1757 checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, device, delayMs);
1758 }
1759}
1760
1761void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy, bool on, audio_io_handle_t output, int delayMs)
1762{
1763 LOGV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
1764 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
1765 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
1766 setStreamMute(stream, on, output, delayMs);
1767 }
1768 }
1769}
1770
1771void AudioPolicyManagerBase::setStreamMute(int stream, bool on, audio_io_handle_t output, int delayMs)
1772{
1773 StreamDescriptor &streamDesc = mStreams[stream];
1774 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1775
1776 LOGV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d", stream, on, output, outputDesc->mMuteCount[stream]);
1777
1778 if (on) {
1779 if (outputDesc->mMuteCount[stream] == 0) {
1780 if (streamDesc.mCanBeMuted) {
1781 checkAndSetVolume(stream, 0, output, outputDesc->device(), delayMs);
1782 }
1783 }
1784 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
1785 outputDesc->mMuteCount[stream]++;
1786 } else {
1787 if (outputDesc->mMuteCount[stream] == 0) {
1788 LOGW("setStreamMute() unmuting non muted stream!");
1789 return;
1790 }
1791 if (--outputDesc->mMuteCount[stream] == 0) {
1792 checkAndSetVolume(stream, streamDesc.mIndexCur, output, outputDesc->device(), delayMs);
1793 }
1794 }
1795}
1796
1797void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
1798{
1799 // if the stream pertains to sonification strategy and we are in call we must
1800 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
1801 // in the device used for phone strategy and play the tone if the selected device does not
1802 // interfere with the device used for phone strategy
1803 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
1804 // many times as there are active tracks on the output
1805
1806 if (getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) {
1807 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mHardwareOutput);
1808 LOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
1809 stream, starting, outputDesc->mDevice, stateChange);
1810 if (outputDesc->mRefCount[stream]) {
1811 int muteCount = 1;
1812 if (stateChange) {
1813 muteCount = outputDesc->mRefCount[stream];
1814 }
1815 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
1816 LOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
1817 for (int i = 0; i < muteCount; i++) {
1818 setStreamMute(stream, starting, mHardwareOutput);
1819 }
1820 } else {
1821 LOGV("handleIncallSonification() high visibility");
1822 if (outputDesc->device() & getDeviceForStrategy(STRATEGY_PHONE)) {
1823 LOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
1824 for (int i = 0; i < muteCount; i++) {
1825 setStreamMute(stream, starting, mHardwareOutput);
1826 }
1827 }
1828 if (starting) {
1829 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
1830 } else {
1831 mpClientInterface->stopTone();
1832 }
1833 }
1834 }
1835 }
1836}
1837
Eric Laurentef9500f2010-03-11 14:47:00 -08001838bool AudioPolicyManagerBase::needsDirectOuput(AudioSystem::stream_type stream,
1839 uint32_t samplingRate,
1840 uint32_t format,
1841 uint32_t channels,
1842 AudioSystem::output_flags flags,
1843 uint32_t device)
1844{
1845 return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
1846 (format !=0 && !AudioSystem::isLinearPCM(format)));
1847}
1848
Eric Laurentcef3cd72009-12-10 01:03:50 -08001849// --- AudioOutputDescriptor class implementation
1850
1851AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor()
1852 : mId(0), mSamplingRate(0), mFormat(0), mChannels(0), mLatency(0),
1853 mFlags((AudioSystem::output_flags)0), mDevice(0), mOutput1(0), mOutput2(0)
1854{
1855 // clear usage count for all stream types
1856 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1857 mRefCount[i] = 0;
1858 mCurVolume[i] = -1.0;
1859 mMuteCount[i] = 0;
1860 }
1861}
1862
1863uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::device()
1864{
1865 uint32_t device = 0;
1866 if (isDuplicated()) {
1867 device = mOutput1->mDevice | mOutput2->mDevice;
1868 } else {
1869 device = mDevice;
1870 }
1871 return device;
1872}
1873
1874void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
1875{
1876 // forward usage count change to attached outputs
1877 if (isDuplicated()) {
1878 mOutput1->changeRefCount(stream, delta);
1879 mOutput2->changeRefCount(stream, delta);
1880 }
1881 if ((delta + (int)mRefCount[stream]) < 0) {
1882 LOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
1883 mRefCount[stream] = 0;
1884 return;
1885 }
1886 mRefCount[stream] += delta;
1887 LOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
1888}
1889
1890uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount()
1891{
1892 uint32_t refcount = 0;
1893 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1894 refcount += mRefCount[i];
1895 }
1896 return refcount;
1897}
1898
1899uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy)
1900{
1901 uint32_t refCount = 0;
1902 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1903 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
1904 refCount += mRefCount[i];
1905 }
1906 }
1907 return refCount;
1908}
1909
1910
1911status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
1912{
1913 const size_t SIZE = 256;
1914 char buffer[SIZE];
1915 String8 result;
1916
1917 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
1918 result.append(buffer);
1919 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
1920 result.append(buffer);
1921 snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
1922 result.append(buffer);
1923 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
1924 result.append(buffer);
1925 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
1926 result.append(buffer);
1927 snprintf(buffer, SIZE, " Devices %08x\n", device());
1928 result.append(buffer);
1929 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
1930 result.append(buffer);
1931 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1932 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
1933 result.append(buffer);
1934 }
1935 write(fd, result.string(), result.size());
1936
1937 return NO_ERROR;
1938}
1939
1940// --- AudioInputDescriptor class implementation
1941
1942AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor()
1943 : mSamplingRate(0), mFormat(0), mChannels(0),
1944 mAcoustics((AudioSystem::audio_in_acoustics)0), mDevice(0), mRefCount(0)
1945{
1946}
1947
1948status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
1949{
1950 const size_t SIZE = 256;
1951 char buffer[SIZE];
1952 String8 result;
1953
1954 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
1955 result.append(buffer);
1956 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
1957 result.append(buffer);
1958 snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
1959 result.append(buffer);
1960 snprintf(buffer, SIZE, " Acoustics %08x\n", mAcoustics);
1961 result.append(buffer);
1962 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
1963 result.append(buffer);
1964 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
1965 result.append(buffer);
1966 write(fd, result.string(), result.size());
1967
1968 return NO_ERROR;
1969}
1970
1971// --- StreamDescriptor class implementation
1972
1973void AudioPolicyManagerBase::StreamDescriptor::dump(char* buffer, size_t size)
1974{
1975 snprintf(buffer, size, " %02d %02d %02d %d\n",
1976 mIndexMin,
1977 mIndexMax,
1978 mIndexCur,
1979 mCanBeMuted);
1980}
1981
1982
1983}; // namespace android