blob: 1d87c0d5a3c948377f77c1d109c22b4f8c744677 [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
Eric Laurentde070132010-07-13 04:45:46 -0700541status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
542 AudioSystem::stream_type stream,
543 int session)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700544{
Eric Laurentde070132010-07-13 04:45:46 -0700545 LOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700546 ssize_t index = mOutputs.indexOfKey(output);
547 if (index < 0) {
548 LOGW("startOutput() unknow output %d", output);
549 return BAD_VALUE;
550 }
551
552 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
553 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
554
555#ifdef WITH_A2DP
556 if (mA2dpOutput != 0 && !a2dpUsedForSonification() && strategy == STRATEGY_SONIFICATION) {
557 setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput);
558 }
559#endif
560
561 // incremenent usage count for this stream on the requested output:
562 // NOTE that the usage count is the same for duplicated output and hardware output which is
563 // necassary for a correct control of hardware output routing by startOutput() and stopOutput()
564 outputDesc->changeRefCount(stream, 1);
565
566 setOutputDevice(output, getNewDevice(output));
567
568 // handle special case for sonification while in call
569 if (mPhoneState == AudioSystem::MODE_IN_CALL) {
570 handleIncallSonification(stream, true, false);
571 }
572
573 // apply volume rules for current stream and device if necessary
574 checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, outputDesc->device());
575
576 return NO_ERROR;
577}
578
Eric Laurentde070132010-07-13 04:45:46 -0700579status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
580 AudioSystem::stream_type stream,
581 int session)
Mathias Agopian65ab4712010-07-14 17:59:35 -0700582{
Eric Laurentde070132010-07-13 04:45:46 -0700583 LOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700584 ssize_t index = mOutputs.indexOfKey(output);
585 if (index < 0) {
586 LOGW("stopOutput() unknow output %d", output);
587 return BAD_VALUE;
588 }
589
590 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
591 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
592
593 // handle special case for sonification while in call
594 if (mPhoneState == AudioSystem::MODE_IN_CALL) {
595 handleIncallSonification(stream, false, false);
596 }
597
598 if (outputDesc->mRefCount[stream] > 0) {
599 // decrement usage count of this stream on the output
600 outputDesc->changeRefCount(stream, -1);
601 // store time at which the last music track was stopped - see computeVolume()
602 if (stream == AudioSystem::MUSIC) {
603 mMusicStopTime = systemTime();
604 }
605
606 setOutputDevice(output, getNewDevice(output));
607
608#ifdef WITH_A2DP
Eric Laurentde070132010-07-13 04:45:46 -0700609 if (mA2dpOutput != 0 && !a2dpUsedForSonification() &&
610 strategy == STRATEGY_SONIFICATION) {
611 setStrategyMute(STRATEGY_MEDIA,
612 false,
613 mA2dpOutput,
614 mOutputs.valueFor(mHardwareOutput)->mLatency*2);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700615 }
616#endif
617 if (output != mHardwareOutput) {
618 setOutputDevice(mHardwareOutput, getNewDevice(mHardwareOutput), true);
619 }
620 return NO_ERROR;
621 } else {
622 LOGW("stopOutput() refcount is already 0 for output %d", output);
623 return INVALID_OPERATION;
624 }
625}
626
627void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
628{
629 LOGV("releaseOutput() %d", output);
630 ssize_t index = mOutputs.indexOfKey(output);
631 if (index < 0) {
632 LOGW("releaseOutput() releasing unknown output %d", output);
633 return;
634 }
635
636#ifdef AUDIO_POLICY_TEST
637 int testIndex = testOutputIndex(output);
638 if (testIndex != 0) {
639 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
640 if (outputDesc->refCount() == 0) {
641 mpClientInterface->closeOutput(output);
642 delete mOutputs.valueAt(index);
643 mOutputs.removeItem(output);
644 mTestOutputs[testIndex] = 0;
645 }
646 return;
647 }
648#endif //AUDIO_POLICY_TEST
649
650 if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
651 mpClientInterface->closeOutput(output);
652 delete mOutputs.valueAt(index);
653 mOutputs.removeItem(output);
654 }
655}
656
657audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
658 uint32_t samplingRate,
659 uint32_t format,
660 uint32_t channels,
661 AudioSystem::audio_in_acoustics acoustics)
662{
663 audio_io_handle_t input = 0;
664 uint32_t device = getDeviceForInputSource(inputSource);
665
666 LOGV("getInput() inputSource %d, samplingRate %d, format %d, channels %x, acoustics %x", inputSource, samplingRate, format, channels, acoustics);
667
668 if (device == 0) {
669 return 0;
670 }
671
672 // adapt channel selection to input source
673 switch(inputSource) {
674 case AUDIO_SOURCE_VOICE_UPLINK:
675 channels = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
676 break;
677 case AUDIO_SOURCE_VOICE_DOWNLINK:
678 channels = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
679 break;
680 case AUDIO_SOURCE_VOICE_CALL:
681 channels = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
682 break;
683 default:
684 break;
685 }
686
687 AudioInputDescriptor *inputDesc = new AudioInputDescriptor();
688
689 inputDesc->mInputSource = inputSource;
690 inputDesc->mDevice = device;
691 inputDesc->mSamplingRate = samplingRate;
692 inputDesc->mFormat = format;
693 inputDesc->mChannels = channels;
694 inputDesc->mAcoustics = acoustics;
695 inputDesc->mRefCount = 0;
696 input = mpClientInterface->openInput(&inputDesc->mDevice,
697 &inputDesc->mSamplingRate,
698 &inputDesc->mFormat,
699 &inputDesc->mChannels,
700 inputDesc->mAcoustics);
701
702 // only accept input with the exact requested set of parameters
703 if (input == 0 ||
704 (samplingRate != inputDesc->mSamplingRate) ||
705 (format != inputDesc->mFormat) ||
706 (channels != inputDesc->mChannels)) {
707 LOGV("getInput() failed opening input: samplingRate %d, format %d, channels %d",
708 samplingRate, format, channels);
709 if (input != 0) {
710 mpClientInterface->closeInput(input);
711 }
712 delete inputDesc;
713 return 0;
714 }
715 mInputs.add(input, inputDesc);
716 return input;
717}
718
719status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
720{
721 LOGV("startInput() input %d", input);
722 ssize_t index = mInputs.indexOfKey(input);
723 if (index < 0) {
724 LOGW("startInput() unknow input %d", input);
725 return BAD_VALUE;
726 }
727 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
728
729#ifdef AUDIO_POLICY_TEST
730 if (mTestInput == 0)
731#endif //AUDIO_POLICY_TEST
732 {
733 // refuse 2 active AudioRecord clients at the same time
734 if (getActiveInput() != 0) {
735 LOGW("startInput() input %d failed: other input already started", input);
736 return INVALID_OPERATION;
737 }
738 }
739
740 AudioParameter param = AudioParameter();
741 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
742
743 // use Voice Recognition mode or not for this input based on input source
744 int vr_enabled = inputDesc->mInputSource == AUDIO_SOURCE_VOICE_RECOGNITION ? 1 : 0;
745 param.addInt(String8("vr_mode"), vr_enabled);
746 LOGV("AudioPolicyManager::startInput(%d), setting vr_mode to %d", inputDesc->mInputSource, vr_enabled);
747
748 mpClientInterface->setParameters(input, param.toString());
749
750 inputDesc->mRefCount = 1;
751 return NO_ERROR;
752}
753
754status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
755{
756 LOGV("stopInput() input %d", input);
757 ssize_t index = mInputs.indexOfKey(input);
758 if (index < 0) {
759 LOGW("stopInput() unknow input %d", input);
760 return BAD_VALUE;
761 }
762 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
763
764 if (inputDesc->mRefCount == 0) {
765 LOGW("stopInput() input %d already stopped", input);
766 return INVALID_OPERATION;
767 } else {
768 AudioParameter param = AudioParameter();
769 param.addInt(String8(AudioParameter::keyRouting), 0);
770 mpClientInterface->setParameters(input, param.toString());
771 inputDesc->mRefCount = 0;
772 return NO_ERROR;
773 }
774}
775
776void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
777{
778 LOGV("releaseInput() %d", input);
779 ssize_t index = mInputs.indexOfKey(input);
780 if (index < 0) {
781 LOGW("releaseInput() releasing unknown input %d", input);
782 return;
783 }
784 mpClientInterface->closeInput(input);
785 delete mInputs.valueAt(index);
786 mInputs.removeItem(input);
787 LOGV("releaseInput() exit");
788}
789
790void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
791 int indexMin,
792 int indexMax)
793{
794 LOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
795 if (indexMin < 0 || indexMin >= indexMax) {
796 LOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
797 return;
798 }
799 mStreams[stream].mIndexMin = indexMin;
800 mStreams[stream].mIndexMax = indexMax;
801}
802
803status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream, int index)
804{
805
806 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
807 return BAD_VALUE;
808 }
809
810 // Force max volume if stream cannot be muted
811 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
812
813 LOGV("setStreamVolumeIndex() stream %d, index %d", stream, index);
814 mStreams[stream].mIndexCur = index;
815
816 // compute and apply stream volume on all outputs according to connected device
817 status_t status = NO_ERROR;
818 for (size_t i = 0; i < mOutputs.size(); i++) {
819 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), mOutputs.valueAt(i)->device());
820 if (volStatus != NO_ERROR) {
821 status = volStatus;
822 }
823 }
824 return status;
825}
826
827status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream, int *index)
828{
829 if (index == 0) {
830 return BAD_VALUE;
831 }
832 LOGV("getStreamVolumeIndex() stream %d", stream);
833 *index = mStreams[stream].mIndexCur;
834 return NO_ERROR;
835}
836
Eric Laurentde070132010-07-13 04:45:46 -0700837audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(effect_descriptor_t *desc)
838{
839 LOGV("getOutputForEffect()");
840 // apply simple rule where global effects are attached to the same output as MUSIC streams
841 return getOutput(AudioSystem::MUSIC);
842}
843
844status_t AudioPolicyManagerBase::registerEffect(effect_descriptor_t *desc,
845 audio_io_handle_t output,
846 uint32_t strategy,
847 int session,
848 int id)
849{
850 ssize_t index = mOutputs.indexOfKey(output);
851 if (index < 0) {
852 LOGW("registerEffect() unknown output %d", output);
853 return INVALID_OPERATION;
854 }
855
856 if (mTotalEffectsCpuLoad + desc->cpuLoad > getMaxEffectsCpuLoad()) {
857 LOGW("registerEffect() CPU Load limit exceeded for Fx %s, CPU %f MIPS",
858 desc->name, (float)desc->cpuLoad/10);
859 return INVALID_OPERATION;
860 }
861 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
862 LOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
863 desc->name, desc->memoryUsage);
864 return INVALID_OPERATION;
865 }
866 mTotalEffectsCpuLoad += desc->cpuLoad;
867 mTotalEffectsMemory += desc->memoryUsage;
868 LOGV("registerEffect() effect %s, output %d, strategy %d session %d id %d",
869 desc->name, output, strategy, session, id);
870
871 LOGV("registerEffect() CPU %d, memory %d", desc->cpuLoad, desc->memoryUsage);
872 LOGV(" total CPU %d, total memory %d", mTotalEffectsCpuLoad, mTotalEffectsMemory);
873
874 EffectDescriptor *pDesc = new EffectDescriptor();
875 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
876 pDesc->mOutput = output;
877 pDesc->mStrategy = (routing_strategy)strategy;
878 pDesc->mSession = session;
879 mEffects.add(id, pDesc);
880
881 return NO_ERROR;
882}
883
884status_t AudioPolicyManagerBase::unregisterEffect(int id)
885{
886 ssize_t index = mEffects.indexOfKey(id);
887 if (index < 0) {
888 LOGW("unregisterEffect() unknown effect ID %d", id);
889 return INVALID_OPERATION;
890 }
891
892 EffectDescriptor *pDesc = mEffects.valueAt(index);
893
894 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
895 LOGW("unregisterEffect() CPU load %d too high for total %d",
896 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
897 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
898 }
899 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
900 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
901 LOGW("unregisterEffect() memory %d too big for total %d",
902 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
903 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
904 }
905 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
906 LOGV("unregisterEffect() effect %s, ID %d, CPU %d, memory %d",
907 pDesc->mDesc.name, id, pDesc->mDesc.cpuLoad, pDesc->mDesc.memoryUsage);
908 LOGV(" total CPU %d, total memory %d", mTotalEffectsCpuLoad, mTotalEffectsMemory);
909
910 mEffects.removeItem(id);
911 delete pDesc;
912
913 return NO_ERROR;
914}
915
Mathias Agopian65ab4712010-07-14 17:59:35 -0700916status_t AudioPolicyManagerBase::dump(int fd)
917{
918 const size_t SIZE = 256;
919 char buffer[SIZE];
920 String8 result;
921
922 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
923 result.append(buffer);
924 snprintf(buffer, SIZE, " Hardware Output: %d\n", mHardwareOutput);
925 result.append(buffer);
926#ifdef WITH_A2DP
927 snprintf(buffer, SIZE, " A2DP Output: %d\n", mA2dpOutput);
928 result.append(buffer);
929 snprintf(buffer, SIZE, " Duplicated Output: %d\n", mDuplicatedOutput);
930 result.append(buffer);
931 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
932 result.append(buffer);
933#endif
934 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
935 result.append(buffer);
936 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
937 result.append(buffer);
938 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
939 result.append(buffer);
940 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
941 result.append(buffer);
942 snprintf(buffer, SIZE, " Ringer mode: %d\n", mRingerMode);
943 result.append(buffer);
944 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
945 result.append(buffer);
946 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
947 result.append(buffer);
948 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
949 result.append(buffer);
950 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
951 result.append(buffer);
952 write(fd, result.string(), result.size());
953
954 snprintf(buffer, SIZE, "\nOutputs dump:\n");
955 write(fd, buffer, strlen(buffer));
956 for (size_t i = 0; i < mOutputs.size(); i++) {
957 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
958 write(fd, buffer, strlen(buffer));
959 mOutputs.valueAt(i)->dump(fd);
960 }
961
962 snprintf(buffer, SIZE, "\nInputs dump:\n");
963 write(fd, buffer, strlen(buffer));
964 for (size_t i = 0; i < mInputs.size(); i++) {
965 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
966 write(fd, buffer, strlen(buffer));
967 mInputs.valueAt(i)->dump(fd);
968 }
969
970 snprintf(buffer, SIZE, "\nStreams dump:\n");
971 write(fd, buffer, strlen(buffer));
972 snprintf(buffer, SIZE, " Stream Index Min Index Max Index Cur Can be muted\n");
973 write(fd, buffer, strlen(buffer));
974 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
975 snprintf(buffer, SIZE, " %02d", i);
976 mStreams[i].dump(buffer + 3, SIZE);
977 write(fd, buffer, strlen(buffer));
978 }
979
Eric Laurentde070132010-07-13 04:45:46 -0700980 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
981 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
982 write(fd, buffer, strlen(buffer));
983
984 snprintf(buffer, SIZE, "Registered effects:\n");
985 write(fd, buffer, strlen(buffer));
986 for (size_t i = 0; i < mEffects.size(); i++) {
987 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
988 write(fd, buffer, strlen(buffer));
989 mEffects.valueAt(i)->dump(fd);
990 }
991
992
Mathias Agopian65ab4712010-07-14 17:59:35 -0700993 return NO_ERROR;
994}
995
996// ----------------------------------------------------------------------------
997// AudioPolicyManagerBase
998// ----------------------------------------------------------------------------
999
1000AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1001 :
1002#ifdef AUDIO_POLICY_TEST
1003 Thread(false),
1004#endif //AUDIO_POLICY_TEST
Eric Laurentde070132010-07-13 04:45:46 -07001005 mPhoneState(AudioSystem::MODE_NORMAL), mRingerMode(0), mMusicStopTime(0),
1006 mLimitRingtoneVolume(false), mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0)
Mathias Agopian65ab4712010-07-14 17:59:35 -07001007{
1008 mpClientInterface = clientInterface;
1009
1010 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1011 mForceUse[i] = AudioSystem::FORCE_NONE;
1012 }
1013
1014 // devices available by default are speaker, ear piece and microphone
1015 mAvailableOutputDevices = AudioSystem::DEVICE_OUT_EARPIECE |
1016 AudioSystem::DEVICE_OUT_SPEAKER;
1017 mAvailableInputDevices = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1018
1019#ifdef WITH_A2DP
1020 mA2dpOutput = 0;
1021 mDuplicatedOutput = 0;
1022 mA2dpDeviceAddress = String8("");
1023#endif
1024 mScoDeviceAddress = String8("");
1025
1026 // open hardware output
1027 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1028 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1029 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1030 &outputDesc->mSamplingRate,
1031 &outputDesc->mFormat,
1032 &outputDesc->mChannels,
1033 &outputDesc->mLatency,
1034 outputDesc->mFlags);
1035
1036 if (mHardwareOutput == 0) {
1037 LOGE("Failed to initialize hardware output stream, samplingRate: %d, format %d, channels %d",
1038 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
1039 } else {
1040 addOutput(mHardwareOutput, outputDesc);
1041 setOutputDevice(mHardwareOutput, (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER, true);
Eric Laurentde070132010-07-13 04:45:46 -07001042 //TODO: configure audio effect output stage here
Mathias Agopian65ab4712010-07-14 17:59:35 -07001043 }
1044
1045 updateDeviceForStrategy();
1046#ifdef AUDIO_POLICY_TEST
1047 AudioParameter outputCmd = AudioParameter();
1048 outputCmd.addInt(String8("set_id"), 0);
1049 mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString());
1050
1051 mTestDevice = AudioSystem::DEVICE_OUT_SPEAKER;
1052 mTestSamplingRate = 44100;
1053 mTestFormat = AudioSystem::PCM_16_BIT;
1054 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1055 mTestLatencyMs = 0;
1056 mCurOutput = 0;
1057 mDirectOutput = false;
1058 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1059 mTestOutputs[i] = 0;
1060 }
1061
1062 const size_t SIZE = 256;
1063 char buffer[SIZE];
1064 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1065 run(buffer, ANDROID_PRIORITY_AUDIO);
1066#endif //AUDIO_POLICY_TEST
1067}
1068
1069AudioPolicyManagerBase::~AudioPolicyManagerBase()
1070{
1071#ifdef AUDIO_POLICY_TEST
1072 exit();
1073#endif //AUDIO_POLICY_TEST
1074 for (size_t i = 0; i < mOutputs.size(); i++) {
1075 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1076 delete mOutputs.valueAt(i);
1077 }
1078 mOutputs.clear();
1079 for (size_t i = 0; i < mInputs.size(); i++) {
1080 mpClientInterface->closeInput(mInputs.keyAt(i));
1081 delete mInputs.valueAt(i);
1082 }
1083 mInputs.clear();
1084}
1085
1086#ifdef AUDIO_POLICY_TEST
1087bool AudioPolicyManagerBase::threadLoop()
1088{
1089 LOGV("entering threadLoop()");
1090 while (!exitPending())
1091 {
1092 String8 command;
1093 int valueInt;
1094 String8 value;
1095
1096 Mutex::Autolock _l(mLock);
1097 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1098
1099 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1100 AudioParameter param = AudioParameter(command);
1101
1102 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1103 valueInt != 0) {
1104 LOGV("Test command %s received", command.string());
1105 String8 target;
1106 if (param.get(String8("target"), target) != NO_ERROR) {
1107 target = "Manager";
1108 }
1109 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1110 param.remove(String8("test_cmd_policy_output"));
1111 mCurOutput = valueInt;
1112 }
1113 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1114 param.remove(String8("test_cmd_policy_direct"));
1115 if (value == "false") {
1116 mDirectOutput = false;
1117 } else if (value == "true") {
1118 mDirectOutput = true;
1119 }
1120 }
1121 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1122 param.remove(String8("test_cmd_policy_input"));
1123 mTestInput = valueInt;
1124 }
1125
1126 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1127 param.remove(String8("test_cmd_policy_format"));
1128 int format = AudioSystem::INVALID_FORMAT;
1129 if (value == "PCM 16 bits") {
1130 format = AudioSystem::PCM_16_BIT;
1131 } else if (value == "PCM 8 bits") {
1132 format = AudioSystem::PCM_8_BIT;
1133 } else if (value == "Compressed MP3") {
1134 format = AudioSystem::MP3;
1135 }
1136 if (format != AudioSystem::INVALID_FORMAT) {
1137 if (target == "Manager") {
1138 mTestFormat = format;
1139 } else if (mTestOutputs[mCurOutput] != 0) {
1140 AudioParameter outputParam = AudioParameter();
1141 outputParam.addInt(String8("format"), format);
1142 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1143 }
1144 }
1145 }
1146 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1147 param.remove(String8("test_cmd_policy_channels"));
1148 int channels = 0;
1149
1150 if (value == "Channels Stereo") {
1151 channels = AudioSystem::CHANNEL_OUT_STEREO;
1152 } else if (value == "Channels Mono") {
1153 channels = AudioSystem::CHANNEL_OUT_MONO;
1154 }
1155 if (channels != 0) {
1156 if (target == "Manager") {
1157 mTestChannels = channels;
1158 } else if (mTestOutputs[mCurOutput] != 0) {
1159 AudioParameter outputParam = AudioParameter();
1160 outputParam.addInt(String8("channels"), channels);
1161 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1162 }
1163 }
1164 }
1165 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1166 param.remove(String8("test_cmd_policy_sampleRate"));
1167 if (valueInt >= 0 && valueInt <= 96000) {
1168 int samplingRate = valueInt;
1169 if (target == "Manager") {
1170 mTestSamplingRate = samplingRate;
1171 } else if (mTestOutputs[mCurOutput] != 0) {
1172 AudioParameter outputParam = AudioParameter();
1173 outputParam.addInt(String8("sampling_rate"), samplingRate);
1174 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1175 }
1176 }
1177 }
1178
1179 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1180 param.remove(String8("test_cmd_policy_reopen"));
1181
1182 mpClientInterface->closeOutput(mHardwareOutput);
1183 delete mOutputs.valueFor(mHardwareOutput);
1184 mOutputs.removeItem(mHardwareOutput);
1185
1186 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1187 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1188 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1189 &outputDesc->mSamplingRate,
1190 &outputDesc->mFormat,
1191 &outputDesc->mChannels,
1192 &outputDesc->mLatency,
1193 outputDesc->mFlags);
1194 if (mHardwareOutput == 0) {
1195 LOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1196 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
1197 } else {
1198 AudioParameter outputCmd = AudioParameter();
1199 outputCmd.addInt(String8("set_id"), 0);
1200 mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString());
1201 addOutput(mHardwareOutput, outputDesc);
1202 }
1203 }
1204
1205
1206 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1207 }
1208 }
1209 return false;
1210}
1211
1212void AudioPolicyManagerBase::exit()
1213{
1214 {
1215 AutoMutex _l(mLock);
1216 requestExit();
1217 mWaitWorkCV.signal();
1218 }
1219 requestExitAndWait();
1220}
1221
1222int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1223{
1224 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1225 if (output == mTestOutputs[i]) return i;
1226 }
1227 return 0;
1228}
1229#endif //AUDIO_POLICY_TEST
1230
1231// ---
1232
1233void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1234{
1235 outputDesc->mId = id;
1236 mOutputs.add(id, outputDesc);
1237}
1238
1239
1240#ifdef WITH_A2DP
1241status_t AudioPolicyManagerBase::handleA2dpConnection(AudioSystem::audio_devices device,
1242 const char *device_address)
1243{
1244 // when an A2DP device is connected, open an A2DP and a duplicated output
1245 LOGV("opening A2DP output for device %s", device_address);
1246 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1247 outputDesc->mDevice = device;
1248 mA2dpOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1249 &outputDesc->mSamplingRate,
1250 &outputDesc->mFormat,
1251 &outputDesc->mChannels,
1252 &outputDesc->mLatency,
1253 outputDesc->mFlags);
1254 if (mA2dpOutput) {
1255 // add A2DP output descriptor
1256 addOutput(mA2dpOutput, outputDesc);
Eric Laurentde070132010-07-13 04:45:46 -07001257
1258 //TODO: configure audio effect output stage here
1259
Mathias Agopian65ab4712010-07-14 17:59:35 -07001260 // set initial stream volume for A2DP device
1261 applyStreamVolumes(mA2dpOutput, device);
1262 if (a2dpUsedForSonification()) {
1263 mDuplicatedOutput = mpClientInterface->openDuplicateOutput(mA2dpOutput, mHardwareOutput);
1264 }
1265 if (mDuplicatedOutput != 0 ||
1266 !a2dpUsedForSonification()) {
1267 // If both A2DP and duplicated outputs are open, send device address to A2DP hardware
1268 // interface
1269 AudioParameter param;
1270 param.add(String8("a2dp_sink_address"), String8(device_address));
1271 mpClientInterface->setParameters(mA2dpOutput, param.toString());
1272 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
1273
1274 if (a2dpUsedForSonification()) {
1275 // add duplicated output descriptor
1276 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor();
1277 dupOutputDesc->mOutput1 = mOutputs.valueFor(mHardwareOutput);
1278 dupOutputDesc->mOutput2 = mOutputs.valueFor(mA2dpOutput);
1279 dupOutputDesc->mSamplingRate = outputDesc->mSamplingRate;
1280 dupOutputDesc->mFormat = outputDesc->mFormat;
1281 dupOutputDesc->mChannels = outputDesc->mChannels;
1282 dupOutputDesc->mLatency = outputDesc->mLatency;
1283 addOutput(mDuplicatedOutput, dupOutputDesc);
1284 applyStreamVolumes(mDuplicatedOutput, device);
1285 }
1286 } else {
1287 LOGW("getOutput() could not open duplicated output for %d and %d",
1288 mHardwareOutput, mA2dpOutput);
1289 mpClientInterface->closeOutput(mA2dpOutput);
1290 mOutputs.removeItem(mA2dpOutput);
1291 mA2dpOutput = 0;
1292 delete outputDesc;
1293 return NO_INIT;
1294 }
1295 } else {
1296 LOGW("setDeviceConnectionState() could not open A2DP output for device %x", device);
1297 delete outputDesc;
1298 return NO_INIT;
1299 }
1300 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
1301
1302 if (mScoDeviceAddress != "") {
1303 // It is normal to suspend twice if we are both in call,
1304 // and have the hardware audio output routed to BT SCO
1305 if (mPhoneState != AudioSystem::MODE_NORMAL) {
1306 mpClientInterface->suspendOutput(mA2dpOutput);
1307 }
1308 if (AudioSystem::isBluetoothScoDevice((AudioSystem::audio_devices)hwOutputDesc->device())) {
1309 mpClientInterface->suspendOutput(mA2dpOutput);
1310 }
1311 }
1312
1313 if (!a2dpUsedForSonification()) {
1314 // mute music on A2DP output if a notification or ringtone is playing
1315 uint32_t refCount = hwOutputDesc->strategyRefCount(STRATEGY_SONIFICATION);
1316 for (uint32_t i = 0; i < refCount; i++) {
1317 setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput);
1318 }
1319 }
1320 return NO_ERROR;
1321}
1322
1323status_t AudioPolicyManagerBase::handleA2dpDisconnection(AudioSystem::audio_devices device,
1324 const char *device_address)
1325{
1326 if (mA2dpOutput == 0) {
1327 LOGW("setDeviceConnectionState() disconnecting A2DP and no A2DP output!");
1328 return INVALID_OPERATION;
1329 }
1330
1331 if (mA2dpDeviceAddress != device_address) {
1332 LOGW("setDeviceConnectionState() disconnecting unknow A2DP sink address %s", device_address);
1333 return INVALID_OPERATION;
1334 }
1335
1336 // mute media strategy to avoid outputting sound on hardware output while music stream
1337 // is switched from A2DP output and before music is paused by music application
1338 setStrategyMute(STRATEGY_MEDIA, true, mHardwareOutput);
1339 setStrategyMute(STRATEGY_MEDIA, false, mHardwareOutput, MUTE_TIME_MS);
1340
1341 if (!a2dpUsedForSonification()) {
1342 // unmute music on A2DP output if a notification or ringtone is playing
1343 uint32_t refCount = mOutputs.valueFor(mHardwareOutput)->strategyRefCount(STRATEGY_SONIFICATION);
1344 for (uint32_t i = 0; i < refCount; i++) {
1345 setStrategyMute(STRATEGY_MEDIA, false, mA2dpOutput);
1346 }
1347 }
1348 mA2dpDeviceAddress = "";
1349 return NO_ERROR;
1350}
1351
1352void AudioPolicyManagerBase::closeA2dpOutputs()
1353{
1354 LOGV("setDeviceConnectionState() closing A2DP and duplicated output!");
1355
1356 if (mDuplicatedOutput != 0) {
1357 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueFor(mDuplicatedOutput);
1358 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
1359 // As all active tracks on duplicated output will be deleted,
1360 // and as they were also referenced on hardware output, the reference
1361 // count for their stream type must be adjusted accordingly on
1362 // hardware output.
1363 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1364 int refCount = dupOutputDesc->mRefCount[i];
1365 hwOutputDesc->changeRefCount((AudioSystem::stream_type)i,-refCount);
1366 }
1367
1368 mpClientInterface->closeOutput(mDuplicatedOutput);
1369 delete mOutputs.valueFor(mDuplicatedOutput);
1370 mOutputs.removeItem(mDuplicatedOutput);
1371 mDuplicatedOutput = 0;
1372 }
1373 if (mA2dpOutput != 0) {
1374 AudioParameter param;
1375 param.add(String8("closing"), String8("true"));
1376 mpClientInterface->setParameters(mA2dpOutput, param.toString());
Eric Laurentde070132010-07-13 04:45:46 -07001377
Mathias Agopian65ab4712010-07-14 17:59:35 -07001378 mpClientInterface->closeOutput(mA2dpOutput);
1379 delete mOutputs.valueFor(mA2dpOutput);
1380 mOutputs.removeItem(mA2dpOutput);
1381 mA2dpOutput = 0;
1382 }
1383}
1384
1385void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy, uint32_t &newDevice)
1386{
1387 uint32_t prevDevice = getDeviceForStrategy(strategy);
1388 uint32_t curDevice = getDeviceForStrategy(strategy, false);
1389 bool a2dpWasUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(prevDevice & ~AudioSystem::DEVICE_OUT_SPEAKER));
1390 bool a2dpIsUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(curDevice & ~AudioSystem::DEVICE_OUT_SPEAKER));
Eric Laurentde070132010-07-13 04:45:46 -07001391 audio_io_handle_t srcOutput = 0;
1392 audio_io_handle_t dstOutput = 0;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001393
1394 if (a2dpWasUsed && !a2dpIsUsed) {
1395 bool dupUsed = a2dpUsedForSonification() && a2dpWasUsed && (AudioSystem::popCount(prevDevice) == 2);
Eric Laurentde070132010-07-13 04:45:46 -07001396 dstOutput = mHardwareOutput;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001397 if (dupUsed) {
Eric Laurentde070132010-07-13 04:45:46 -07001398 LOGV("checkOutputForStrategy() moving strategy %d from duplicated", strategy);
1399 srcOutput = mDuplicatedOutput;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001400 } else {
Eric Laurentde070132010-07-13 04:45:46 -07001401 LOGV("checkOutputForStrategy() moving strategy %d from a2dp", strategy);
1402 srcOutput = mA2dpOutput;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001403 }
1404
Mathias Agopian65ab4712010-07-14 17:59:35 -07001405 // do not change newDevice if it was already set before this call by a previous call to
1406 // getNewDevice() or checkOutputForStrategy() for a strategy with higher priority
Eric Laurentde070132010-07-13 04:45:46 -07001407 if (newDevice == 0 && mOutputs.valueFor(mHardwareOutput)->isUsedByStrategy(strategy)) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001408 newDevice = getDeviceForStrategy(strategy, false);
1409 }
1410 }
1411 if (a2dpIsUsed && !a2dpWasUsed) {
1412 bool dupUsed = a2dpUsedForSonification() && a2dpIsUsed && (AudioSystem::popCount(curDevice) == 2);
Eric Laurentde070132010-07-13 04:45:46 -07001413 srcOutput = mHardwareOutput;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001414 if (dupUsed) {
Eric Laurentde070132010-07-13 04:45:46 -07001415 LOGV("checkOutputForStrategy() moving strategy %d to duplicated", strategy);
1416 dstOutput = mDuplicatedOutput;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001417 } else {
Eric Laurentde070132010-07-13 04:45:46 -07001418 LOGV("checkOutputForStrategy() moving strategy %d to a2dp", strategy);
1419 dstOutput = mA2dpOutput;
Mathias Agopian65ab4712010-07-14 17:59:35 -07001420 }
Eric Laurentde070132010-07-13 04:45:46 -07001421 }
Mathias Agopian65ab4712010-07-14 17:59:35 -07001422
Eric Laurentde070132010-07-13 04:45:46 -07001423 if (srcOutput != 0 && dstOutput != 0) {
1424 // Move effects associated to this strategy from previous output to new output
1425 for (size_t i = 0; i < mEffects.size(); i++) {
1426 EffectDescriptor *desc = mEffects.valueAt(i);
1427 if (desc->mSession != AudioSystem::SESSION_OUTPUT_STAGE &&
1428 desc->mStrategy == strategy &&
1429 desc->mOutput == srcOutput) {
1430 LOGV("checkOutputForStrategy() moving effect %d to output %d", mEffects.keyAt(i), dstOutput);
1431 mpClientInterface->moveEffects(desc->mSession, srcOutput, dstOutput);
1432 desc->mOutput = dstOutput;
1433 }
1434 }
1435 // Move tracks associated to this strategy from previous output to new output
Mathias Agopian65ab4712010-07-14 17:59:35 -07001436 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1437 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
Eric Laurentde070132010-07-13 04:45:46 -07001438 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, dstOutput);
Mathias Agopian65ab4712010-07-14 17:59:35 -07001439 }
1440 }
1441 }
1442}
1443
1444void AudioPolicyManagerBase::checkOutputForAllStrategies(uint32_t &newDevice)
1445{
1446 // Check strategies in order of priority so that once newDevice is set
1447 // for a given strategy it is not modified by subsequent calls to
1448 // checkOutputForStrategy()
1449 checkOutputForStrategy(STRATEGY_PHONE, newDevice);
1450 checkOutputForStrategy(STRATEGY_SONIFICATION, newDevice);
1451 checkOutputForStrategy(STRATEGY_MEDIA, newDevice);
1452 checkOutputForStrategy(STRATEGY_DTMF, newDevice);
1453}
1454
1455#endif
1456
1457uint32_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
1458{
1459 uint32_t device = 0;
1460
1461 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1462 // check the following by order of priority to request a routing change if necessary:
1463 // 1: we are in call or the strategy phone is active on the hardware output:
1464 // use device for strategy phone
1465 // 2: the strategy sonification is active on the hardware output:
1466 // use device for strategy sonification
1467 // 3: the strategy media is active on the hardware output:
1468 // use device for strategy media
1469 // 4: the strategy DTMF is active on the hardware output:
1470 // use device for strategy DTMF
1471 if (mPhoneState == AudioSystem::MODE_IN_CALL ||
1472 outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
1473 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
1474 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
1475 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
1476 } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
1477 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
1478 } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
1479 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
1480 }
1481
1482 LOGV("getNewDevice() selected device %x", device);
1483 return device;
1484}
1485
Eric Laurentde070132010-07-13 04:45:46 -07001486uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
1487 return (uint32_t)getStrategy(stream);
1488}
1489
1490AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
1491 AudioSystem::stream_type stream) {
Mathias Agopian65ab4712010-07-14 17:59:35 -07001492 // stream to strategy mapping
1493 switch (stream) {
1494 case AudioSystem::VOICE_CALL:
1495 case AudioSystem::BLUETOOTH_SCO:
1496 return STRATEGY_PHONE;
1497 case AudioSystem::RING:
1498 case AudioSystem::NOTIFICATION:
1499 case AudioSystem::ALARM:
1500 case AudioSystem::ENFORCED_AUDIBLE:
1501 return STRATEGY_SONIFICATION;
1502 case AudioSystem::DTMF:
1503 return STRATEGY_DTMF;
1504 default:
1505 LOGE("unknown stream type");
1506 case AudioSystem::SYSTEM:
1507 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
1508 // while key clicks are played produces a poor result
1509 case AudioSystem::TTS:
1510 case AudioSystem::MUSIC:
1511 return STRATEGY_MEDIA;
1512 }
1513}
1514
1515uint32_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy, bool fromCache)
1516{
1517 uint32_t device = 0;
1518
1519 if (fromCache) {
1520 LOGV("getDeviceForStrategy() from cache strategy %d, device %x", strategy, mDeviceForStrategy[strategy]);
1521 return mDeviceForStrategy[strategy];
1522 }
1523
1524 switch (strategy) {
1525 case STRATEGY_DTMF:
1526 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
1527 // when off call, DTMF strategy follows the same rules as MEDIA strategy
1528 device = getDeviceForStrategy(STRATEGY_MEDIA, false);
1529 break;
1530 }
1531 // when in call, DTMF and PHONE strategies follow the same rules
1532 // FALL THROUGH
1533
1534 case STRATEGY_PHONE:
1535 // for phone strategy, we first consider the forced use and then the available devices by order
1536 // of priority
1537 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
1538 case AudioSystem::FORCE_BT_SCO:
1539 if (mPhoneState != AudioSystem::MODE_IN_CALL || strategy != STRATEGY_DTMF) {
1540 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
1541 if (device) break;
1542 }
1543 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
1544 if (device) break;
1545 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO;
1546 if (device) break;
1547 // if SCO device is requested but no SCO device is available, fall back to default case
1548 // FALL THROUGH
1549
1550 default: // FORCE_NONE
1551 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
1552 if (device) break;
1553 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1554 if (device) break;
1555#ifdef WITH_A2DP
1556 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
1557 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
1558 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1559 if (device) break;
1560 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1561 if (device) break;
1562 }
1563#endif
1564 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_EARPIECE;
1565 if (device == 0) {
1566 LOGE("getDeviceForStrategy() earpiece device not found");
1567 }
1568 break;
1569
1570 case AudioSystem::FORCE_SPEAKER:
1571 if (mPhoneState != AudioSystem::MODE_IN_CALL || strategy != STRATEGY_DTMF) {
1572 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
1573 if (device) break;
1574 }
1575#ifdef WITH_A2DP
1576 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
1577 // A2DP speaker when forcing to speaker output
1578 if (mPhoneState != AudioSystem::MODE_IN_CALL) {
1579 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1580 if (device) break;
1581 }
1582#endif
1583 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1584 if (device == 0) {
1585 LOGE("getDeviceForStrategy() speaker device not found");
1586 }
1587 break;
1588 }
1589 break;
1590
1591 case STRATEGY_SONIFICATION:
1592
1593 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
1594 // handleIncallSonification().
1595 if (mPhoneState == AudioSystem::MODE_IN_CALL) {
1596 device = getDeviceForStrategy(STRATEGY_PHONE, false);
1597 break;
1598 }
1599 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1600 if (device == 0) {
1601 LOGE("getDeviceForStrategy() speaker device not found");
1602 }
1603 // The second device used for sonification is the same as the device used by media strategy
1604 // FALL THROUGH
1605
1606 case STRATEGY_MEDIA: {
1607 uint32_t device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1608 if (device2 == 0) {
1609 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
1610 }
1611 if (device2 == 0) {
1612 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1613 }
1614#ifdef WITH_A2DP
1615 if (mA2dpOutput != 0) {
1616 if (strategy == STRATEGY_SONIFICATION && !a2dpUsedForSonification()) {
1617 break;
1618 }
1619 if (device2 == 0) {
1620 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1621 }
1622 if (device2 == 0) {
1623 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1624 }
1625 if (device2 == 0) {
1626 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1627 }
1628 }
1629#endif
1630 if (device2 == 0) {
1631 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1632 }
1633
1634 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION, 0 otherwise
1635 device |= device2;
1636 if (device == 0) {
1637 LOGE("getDeviceForStrategy() speaker device not found");
1638 }
1639 } break;
1640
1641 default:
1642 LOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
1643 break;
1644 }
1645
1646 LOGV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
1647 return device;
1648}
1649
1650void AudioPolicyManagerBase::updateDeviceForStrategy()
1651{
1652 for (int i = 0; i < NUM_STRATEGIES; i++) {
1653 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false);
1654 }
1655}
1656
1657void AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output, uint32_t device, bool force, int delayMs)
1658{
1659 LOGV("setOutputDevice() output %d device %x delayMs %d", output, device, delayMs);
1660 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1661
1662
1663 if (outputDesc->isDuplicated()) {
1664 setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
1665 setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
1666 return;
1667 }
1668#ifdef WITH_A2DP
1669 // filter devices according to output selected
1670 if (output == mA2dpOutput) {
1671 device &= AudioSystem::DEVICE_OUT_ALL_A2DP;
1672 } else {
1673 device &= ~AudioSystem::DEVICE_OUT_ALL_A2DP;
1674 }
1675#endif
1676
1677 uint32_t prevDevice = (uint32_t)outputDesc->device();
1678 // Do not change the routing if:
1679 // - the requestede device is 0
1680 // - the requested device is the same as current device and force is not specified.
1681 // Doing this check here allows the caller to call setOutputDevice() without conditions
1682 if ((device == 0 || device == prevDevice) && !force) {
1683 LOGV("setOutputDevice() setting same device %x or null device for output %d", device, output);
1684 return;
1685 }
1686
1687 outputDesc->mDevice = device;
1688 // mute media streams if both speaker and headset are selected
1689 if (output == mHardwareOutput && AudioSystem::popCount(device) == 2) {
1690 setStrategyMute(STRATEGY_MEDIA, true, output);
1691 // wait for the PCM output buffers to empty before proceeding with the rest of the command
1692 usleep(outputDesc->mLatency*2*1000);
1693 }
1694#ifdef WITH_A2DP
1695 // suspend A2DP output if SCO device is selected
1696 if (AudioSystem::isBluetoothScoDevice((AudioSystem::audio_devices)device)) {
1697 if (mA2dpOutput != 0) {
1698 mpClientInterface->suspendOutput(mA2dpOutput);
1699 }
1700 }
1701#endif
1702 // do the routing
1703 AudioParameter param = AudioParameter();
1704 param.addInt(String8(AudioParameter::keyRouting), (int)device);
1705 mpClientInterface->setParameters(mHardwareOutput, param.toString(), delayMs);
1706 // update stream volumes according to new device
1707 applyStreamVolumes(output, device, delayMs);
1708
1709#ifdef WITH_A2DP
1710 // if disconnecting SCO device, restore A2DP output
1711 if (AudioSystem::isBluetoothScoDevice((AudioSystem::audio_devices)prevDevice)) {
1712 if (mA2dpOutput != 0) {
1713 LOGV("restore A2DP output");
1714 mpClientInterface->restoreOutput(mA2dpOutput);
1715 }
1716 }
1717#endif
1718 // if changing from a combined headset + speaker route, unmute media streams
1719 if (output == mHardwareOutput && AudioSystem::popCount(prevDevice) == 2) {
1720 setStrategyMute(STRATEGY_MEDIA, false, output, delayMs);
1721 }
1722}
1723
1724uint32_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
1725{
1726 uint32_t device;
1727
1728 switch(inputSource) {
1729 case AUDIO_SOURCE_DEFAULT:
1730 case AUDIO_SOURCE_MIC:
1731 case AUDIO_SOURCE_VOICE_RECOGNITION:
1732 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
1733 mAvailableInputDevices & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
1734 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
1735 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_WIRED_HEADSET) {
1736 device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
1737 } else {
1738 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1739 }
1740 break;
1741 case AUDIO_SOURCE_CAMCORDER:
1742 if (hasBackMicrophone()) {
1743 device = AudioSystem::DEVICE_IN_BACK_MIC;
1744 } else {
1745 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1746 }
1747 break;
1748 case AUDIO_SOURCE_VOICE_UPLINK:
1749 case AUDIO_SOURCE_VOICE_DOWNLINK:
1750 case AUDIO_SOURCE_VOICE_CALL:
1751 device = AudioSystem::DEVICE_IN_VOICE_CALL;
1752 break;
1753 default:
1754 LOGW("getInput() invalid input source %d", inputSource);
1755 device = 0;
1756 break;
1757 }
1758 LOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
1759 return device;
1760}
1761
1762audio_io_handle_t AudioPolicyManagerBase::getActiveInput()
1763{
1764 for (size_t i = 0; i < mInputs.size(); i++) {
1765 if (mInputs.valueAt(i)->mRefCount > 0) {
1766 return mInputs.keyAt(i);
1767 }
1768 }
1769 return 0;
1770}
1771
1772float AudioPolicyManagerBase::computeVolume(int stream, int index, audio_io_handle_t output, uint32_t device)
1773{
1774 float volume = 1.0;
1775 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1776 StreamDescriptor &streamDesc = mStreams[stream];
1777
1778 if (device == 0) {
1779 device = outputDesc->device();
1780 }
1781
1782 int volInt = (100 * (index - streamDesc.mIndexMin)) / (streamDesc.mIndexMax - streamDesc.mIndexMin);
1783 volume = AudioSystem::linearToLog(volInt);
1784
1785 // if a headset is connected, apply the following rules to ring tones and notifications
1786 // to avoid sound level bursts in user's ears:
1787 // - always attenuate ring tones and notifications volume by 6dB
1788 // - if music is playing, always limit the volume to current music volume,
1789 // with a minimum threshold at -36dB so that notification is always perceived.
1790 if ((device &
1791 (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP |
1792 AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
1793 AudioSystem::DEVICE_OUT_WIRED_HEADSET |
1794 AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) &&
1795 (getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) &&
1796 streamDesc.mCanBeMuted) {
1797 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
1798 // when the phone is ringing we must consider that music could have been paused just before
1799 // by the music application and behave as if music was active if the last music track was
1800 // just stopped
1801 if (outputDesc->mRefCount[AudioSystem::MUSIC] || mLimitRingtoneVolume) {
1802 float musicVol = computeVolume(AudioSystem::MUSIC, mStreams[AudioSystem::MUSIC].mIndexCur, output, device);
1803 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ? musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
1804 if (volume > minVol) {
1805 volume = minVol;
1806 LOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
1807 }
1808 }
1809 }
1810
1811 return volume;
1812}
1813
1814status_t AudioPolicyManagerBase::checkAndSetVolume(int stream, int index, audio_io_handle_t output, uint32_t device, int delayMs, bool force)
1815{
1816
1817 // do not change actual stream volume if the stream is muted
1818 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
1819 LOGV("checkAndSetVolume() stream %d muted count %d", stream, mOutputs.valueFor(output)->mMuteCount[stream]);
1820 return NO_ERROR;
1821 }
1822
1823 // do not change in call volume if bluetooth is connected and vice versa
1824 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1825 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
1826 LOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
1827 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
1828 return INVALID_OPERATION;
1829 }
1830
1831 float volume = computeVolume(stream, index, output, device);
1832 // do not set volume if the float value did not change
1833 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] || force) {
1834 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
1835 LOGV("setStreamVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
1836 if (stream == AudioSystem::VOICE_CALL ||
1837 stream == AudioSystem::DTMF ||
1838 stream == AudioSystem::BLUETOOTH_SCO) {
1839 float voiceVolume = -1.0;
1840 // offset value to reflect actual hardware volume that never reaches 0
1841 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
1842 volume = 0.01 + 0.99 * volume;
1843 if (stream == AudioSystem::VOICE_CALL) {
1844 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
1845 } else if (stream == AudioSystem::BLUETOOTH_SCO) {
1846 voiceVolume = 1.0;
1847 }
1848 if (voiceVolume >= 0 && output == mHardwareOutput) {
1849 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
1850 }
1851 }
1852 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
1853 }
1854
1855 return NO_ERROR;
1856}
1857
1858void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output, uint32_t device, int delayMs)
1859{
1860 LOGV("applyStreamVolumes() for output %d and device %x", output, device);
1861
1862 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
1863 checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, device, delayMs);
1864 }
1865}
1866
1867void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy, bool on, audio_io_handle_t output, int delayMs)
1868{
1869 LOGV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
1870 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
1871 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
1872 setStreamMute(stream, on, output, delayMs);
1873 }
1874 }
1875}
1876
1877void AudioPolicyManagerBase::setStreamMute(int stream, bool on, audio_io_handle_t output, int delayMs)
1878{
1879 StreamDescriptor &streamDesc = mStreams[stream];
1880 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1881
1882 LOGV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d", stream, on, output, outputDesc->mMuteCount[stream]);
1883
1884 if (on) {
1885 if (outputDesc->mMuteCount[stream] == 0) {
1886 if (streamDesc.mCanBeMuted) {
1887 checkAndSetVolume(stream, 0, output, outputDesc->device(), delayMs);
1888 }
1889 }
1890 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
1891 outputDesc->mMuteCount[stream]++;
1892 } else {
1893 if (outputDesc->mMuteCount[stream] == 0) {
1894 LOGW("setStreamMute() unmuting non muted stream!");
1895 return;
1896 }
1897 if (--outputDesc->mMuteCount[stream] == 0) {
1898 checkAndSetVolume(stream, streamDesc.mIndexCur, output, outputDesc->device(), delayMs);
1899 }
1900 }
1901}
1902
1903void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
1904{
1905 // if the stream pertains to sonification strategy and we are in call we must
1906 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
1907 // in the device used for phone strategy and play the tone if the selected device does not
1908 // interfere with the device used for phone strategy
1909 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
1910 // many times as there are active tracks on the output
1911
1912 if (getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) {
1913 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mHardwareOutput);
1914 LOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
1915 stream, starting, outputDesc->mDevice, stateChange);
1916 if (outputDesc->mRefCount[stream]) {
1917 int muteCount = 1;
1918 if (stateChange) {
1919 muteCount = outputDesc->mRefCount[stream];
1920 }
1921 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
1922 LOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
1923 for (int i = 0; i < muteCount; i++) {
1924 setStreamMute(stream, starting, mHardwareOutput);
1925 }
1926 } else {
1927 LOGV("handleIncallSonification() high visibility");
1928 if (outputDesc->device() & getDeviceForStrategy(STRATEGY_PHONE)) {
1929 LOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
1930 for (int i = 0; i < muteCount; i++) {
1931 setStreamMute(stream, starting, mHardwareOutput);
1932 }
1933 }
1934 if (starting) {
1935 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
1936 } else {
1937 mpClientInterface->stopTone();
1938 }
1939 }
1940 }
1941 }
1942}
1943
1944bool AudioPolicyManagerBase::needsDirectOuput(AudioSystem::stream_type stream,
1945 uint32_t samplingRate,
1946 uint32_t format,
1947 uint32_t channels,
1948 AudioSystem::output_flags flags,
1949 uint32_t device)
1950{
1951 return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
1952 (format !=0 && !AudioSystem::isLinearPCM(format)));
1953}
1954
Eric Laurentde070132010-07-13 04:45:46 -07001955uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
1956{
1957 return MAX_EFFECTS_CPU_LOAD;
1958}
1959
1960uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
1961{
1962 return MAX_EFFECTS_MEMORY;
1963}
1964
Mathias Agopian65ab4712010-07-14 17:59:35 -07001965// --- AudioOutputDescriptor class implementation
1966
1967AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor()
1968 : mId(0), mSamplingRate(0), mFormat(0), mChannels(0), mLatency(0),
1969 mFlags((AudioSystem::output_flags)0), mDevice(0), mOutput1(0), mOutput2(0)
1970{
1971 // clear usage count for all stream types
1972 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1973 mRefCount[i] = 0;
1974 mCurVolume[i] = -1.0;
1975 mMuteCount[i] = 0;
1976 }
1977}
1978
1979uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::device()
1980{
1981 uint32_t device = 0;
1982 if (isDuplicated()) {
1983 device = mOutput1->mDevice | mOutput2->mDevice;
1984 } else {
1985 device = mDevice;
1986 }
1987 return device;
1988}
1989
1990void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
1991{
1992 // forward usage count change to attached outputs
1993 if (isDuplicated()) {
1994 mOutput1->changeRefCount(stream, delta);
1995 mOutput2->changeRefCount(stream, delta);
1996 }
1997 if ((delta + (int)mRefCount[stream]) < 0) {
1998 LOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
1999 mRefCount[stream] = 0;
2000 return;
2001 }
2002 mRefCount[stream] += delta;
2003 LOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
2004}
2005
2006uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount()
2007{
2008 uint32_t refcount = 0;
2009 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2010 refcount += mRefCount[i];
2011 }
2012 return refcount;
2013}
2014
2015uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy)
2016{
2017 uint32_t refCount = 0;
2018 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2019 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2020 refCount += mRefCount[i];
2021 }
2022 }
2023 return refCount;
2024}
2025
2026
2027status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
2028{
2029 const size_t SIZE = 256;
2030 char buffer[SIZE];
2031 String8 result;
2032
2033 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2034 result.append(buffer);
2035 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2036 result.append(buffer);
2037 snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
2038 result.append(buffer);
2039 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
2040 result.append(buffer);
2041 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
2042 result.append(buffer);
2043 snprintf(buffer, SIZE, " Devices %08x\n", device());
2044 result.append(buffer);
2045 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
2046 result.append(buffer);
2047 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2048 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
2049 result.append(buffer);
2050 }
2051 write(fd, result.string(), result.size());
2052
2053 return NO_ERROR;
2054}
2055
2056// --- AudioInputDescriptor class implementation
2057
2058AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor()
2059 : mSamplingRate(0), mFormat(0), mChannels(0),
2060 mAcoustics((AudioSystem::audio_in_acoustics)0), mDevice(0), mRefCount(0)
2061{
2062}
2063
2064status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
2065{
2066 const size_t SIZE = 256;
2067 char buffer[SIZE];
2068 String8 result;
2069
2070 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2071 result.append(buffer);
2072 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2073 result.append(buffer);
2074 snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
2075 result.append(buffer);
2076 snprintf(buffer, SIZE, " Acoustics %08x\n", mAcoustics);
2077 result.append(buffer);
2078 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
2079 result.append(buffer);
2080 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
2081 result.append(buffer);
2082 write(fd, result.string(), result.size());
2083
2084 return NO_ERROR;
2085}
2086
2087// --- StreamDescriptor class implementation
2088
2089void AudioPolicyManagerBase::StreamDescriptor::dump(char* buffer, size_t size)
2090{
2091 snprintf(buffer, size, " %02d %02d %02d %d\n",
2092 mIndexMin,
2093 mIndexMax,
2094 mIndexCur,
2095 mCanBeMuted);
2096}
2097
Eric Laurentde070132010-07-13 04:45:46 -07002098// --- EffectDescriptor class implementation
2099
2100status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
2101{
2102 const size_t SIZE = 256;
2103 char buffer[SIZE];
2104 String8 result;
2105
2106 snprintf(buffer, SIZE, " Output: %d\n", mOutput);
2107 result.append(buffer);
2108 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
2109 result.append(buffer);
2110 snprintf(buffer, SIZE, " Session: %d\n", mSession);
2111 result.append(buffer);
2112 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
2113 result.append(buffer);
2114 write(fd, result.string(), result.size());
2115
2116 return NO_ERROR;
2117}
2118
2119
Mathias Agopian65ab4712010-07-14 17:59:35 -07002120
2121}; // namespace android