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