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