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