blob: f5e7343c1e6b97652eb4ea073665a738209761a6 [file] [log] [blame]
Eric Laurentcef3cd72009-12-10 01:03:50 -08001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "AudioPolicyManagerBase"
Eric Laurentf1451082010-01-28 13:42:59 -080018//#define LOG_NDEBUG 0
Eric Laurentcef3cd72009-12-10 01:03:50 -080019#include <utils/Log.h>
20#include <hardware_legacy/AudioPolicyManagerBase.h>
21#include <media/mediarecorder.h>
Jean-Michel Trivi3aab0582011-01-24 15:28:26 -080022#include <math.h>
Eric Laurentcef3cd72009-12-10 01:03:50 -080023
24namespace android {
25
26
27// ----------------------------------------------------------------------------
28// AudioPolicyInterface implementation
29// ----------------------------------------------------------------------------
30
31
32status_t AudioPolicyManagerBase::setDeviceConnectionState(AudioSystem::audio_devices device,
33 AudioSystem::device_connection_state state,
34 const char *device_address)
35{
36
37 LOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
38
39 // connect/disconnect only 1 device at a time
40 if (AudioSystem::popCount(device) != 1) return BAD_VALUE;
41
42 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
43 LOGE("setDeviceConnectionState() invalid address: %s", device_address);
44 return BAD_VALUE;
45 }
46
47 // handle output devices
48 if (AudioSystem::isOutputDevice(device)) {
49
50#ifndef WITH_A2DP
51 if (AudioSystem::isA2dpDevice(device)) {
52 LOGE("setDeviceConnectionState() invalid device: %x", device);
53 return BAD_VALUE;
54 }
55#endif
56
57 switch (state)
58 {
59 // handle output device connection
60 case AudioSystem::DEVICE_STATE_AVAILABLE:
61 if (mAvailableOutputDevices & device) {
62 LOGW("setDeviceConnectionState() device already connected: %x", device);
63 return INVALID_OPERATION;
64 }
65 LOGV("setDeviceConnectionState() connecting device %x", device);
66
67 // register new device as available
68 mAvailableOutputDevices |= device;
69
70#ifdef WITH_A2DP
71 // handle A2DP device connection
72 if (AudioSystem::isA2dpDevice(device)) {
73 status_t status = handleA2dpConnection(device, device_address);
74 if (status != NO_ERROR) {
75 mAvailableOutputDevices &= ~device;
76 return status;
77 }
78 } else
79#endif
80 {
81 if (AudioSystem::isBluetoothScoDevice(device)) {
82 LOGV("setDeviceConnectionState() BT SCO device, address %s", device_address);
83 // keep track of SCO device address
84 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
Eric Laurentcef3cd72009-12-10 01:03:50 -080085 }
86 }
87 break;
88 // handle output device disconnection
89 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
90 if (!(mAvailableOutputDevices & device)) {
91 LOGW("setDeviceConnectionState() device not connected: %x", device);
92 return INVALID_OPERATION;
93 }
94
95
96 LOGV("setDeviceConnectionState() disconnecting device %x", device);
97 // remove device from available output devices
98 mAvailableOutputDevices &= ~device;
99
100#ifdef WITH_A2DP
101 // handle A2DP device disconnection
102 if (AudioSystem::isA2dpDevice(device)) {
103 status_t status = handleA2dpDisconnection(device, device_address);
104 if (status != NO_ERROR) {
105 mAvailableOutputDevices |= device;
106 return status;
107 }
108 } else
109#endif
110 {
111 if (AudioSystem::isBluetoothScoDevice(device)) {
112 mScoDeviceAddress = "";
Eric Laurentcef3cd72009-12-10 01:03:50 -0800113 }
114 }
115 } break;
116
117 default:
118 LOGE("setDeviceConnectionState() invalid state: %x", state);
119 return BAD_VALUE;
120 }
121
122 // request routing change if necessary
123 uint32_t newDevice = getNewDevice(mHardwareOutput, false);
124#ifdef WITH_A2DP
Eric Laurentbbc9fd32011-03-01 10:28:01 -0800125 checkA2dpSuspend();
Eric Laurentb8453f42010-08-27 17:10:36 -0700126 checkOutputForAllStrategies();
Eric Laurentcef3cd72009-12-10 01:03:50 -0800127 // A2DP outputs must be closed after checkOutputForAllStrategies() is executed
128 if (state == AudioSystem::DEVICE_STATE_UNAVAILABLE && AudioSystem::isA2dpDevice(device)) {
129 closeA2dpOutputs();
130 }
131#endif
132 updateDeviceForStrategy();
133 setOutputDevice(mHardwareOutput, newDevice);
134
135 if (device == AudioSystem::DEVICE_OUT_WIRED_HEADSET) {
136 device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
137 } else if (device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO ||
138 device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
139 device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
140 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
141 } else {
142 return NO_ERROR;
143 }
144 }
145 // handle input devices
146 if (AudioSystem::isInputDevice(device)) {
147
148 switch (state)
149 {
150 // handle input device connection
151 case AudioSystem::DEVICE_STATE_AVAILABLE: {
152 if (mAvailableInputDevices & device) {
153 LOGW("setDeviceConnectionState() device already connected: %d", device);
154 return INVALID_OPERATION;
155 }
156 mAvailableInputDevices |= device;
157 }
158 break;
159
160 // handle input device disconnection
161 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
162 if (!(mAvailableInputDevices & device)) {
163 LOGW("setDeviceConnectionState() device not connected: %d", device);
164 return INVALID_OPERATION;
165 }
166 mAvailableInputDevices &= ~device;
167 } break;
168
169 default:
170 LOGE("setDeviceConnectionState() invalid state: %x", state);
171 return BAD_VALUE;
172 }
173
174 audio_io_handle_t activeInput = getActiveInput();
175 if (activeInput != 0) {
176 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
177 uint32_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
178 if (newDevice != inputDesc->mDevice) {
179 LOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
180 inputDesc->mDevice, newDevice, activeInput);
181 inputDesc->mDevice = newDevice;
182 AudioParameter param = AudioParameter();
183 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
184 mpClientInterface->setParameters(activeInput, param.toString());
185 }
186 }
187
188 return NO_ERROR;
189 }
190
191 LOGW("setDeviceConnectionState() invalid device: %x", device);
192 return BAD_VALUE;
193}
194
195AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(AudioSystem::audio_devices device,
196 const char *device_address)
197{
198 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
199 String8 address = String8(device_address);
200 if (AudioSystem::isOutputDevice(device)) {
201 if (device & mAvailableOutputDevices) {
202#ifdef WITH_A2DP
203 if (AudioSystem::isA2dpDevice(device) &&
204 address != "" && mA2dpDeviceAddress != address) {
205 return state;
206 }
207#endif
208 if (AudioSystem::isBluetoothScoDevice(device) &&
209 address != "" && mScoDeviceAddress != address) {
210 return state;
211 }
212 state = AudioSystem::DEVICE_STATE_AVAILABLE;
213 }
214 } else if (AudioSystem::isInputDevice(device)) {
215 if (device & mAvailableInputDevices) {
216 state = AudioSystem::DEVICE_STATE_AVAILABLE;
217 }
218 }
219
220 return state;
221}
222
223void AudioPolicyManagerBase::setPhoneState(int state)
224{
225 LOGV("setPhoneState() state %d", state);
226 uint32_t newDevice = 0;
227 if (state < 0 || state >= AudioSystem::NUM_MODES) {
228 LOGW("setPhoneState() invalid state %d", state);
229 return;
230 }
231
232 if (state == mPhoneState ) {
233 LOGW("setPhoneState() setting same state %d", state);
234 return;
235 }
236
237 // if leaving call state, handle special case of active streams
238 // pertaining to sonification strategy see handleIncallSonification()
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -0800239 if (isInCall()) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800240 LOGV("setPhoneState() in call state management: new state is %d", state);
241 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
242 handleIncallSonification(stream, false, true);
243 }
244 }
245
246 // store previous phone state for management of sonification strategy below
247 int oldState = mPhoneState;
248 mPhoneState = state;
249 bool force = false;
250
251 // are we entering or starting a call
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -0800252 if (!isStateInCall(oldState) && isStateInCall(state)) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800253 LOGV(" Entering call in setPhoneState()");
254 // force routing command to audio hardware when starting a call
255 // even if no device change is needed
256 force = true;
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -0800257 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800258 LOGV(" Exiting call in setPhoneState()");
259 // force routing command to audio hardware when exiting a call
260 // even if no device change is needed
261 force = true;
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -0800262 } else if (isStateInCall(state) && (state != oldState)) {
263 LOGV(" Switching between telephony and VoIP in setPhoneState()");
264 // force routing command to audio hardware when switching between telephony and VoIP
265 // even if no device change is needed
266 force = true;
Eric Laurentcef3cd72009-12-10 01:03:50 -0800267 }
268
269 // check for device and output changes triggered by new phone state
270 newDevice = getNewDevice(mHardwareOutput, false);
271#ifdef WITH_A2DP
Eric Laurentb87b53d2010-11-02 12:02:20 -0700272 checkA2dpSuspend();
Eric Laurentbbc9fd32011-03-01 10:28:01 -0800273 checkOutputForAllStrategies();
Eric Laurentcef3cd72009-12-10 01:03:50 -0800274#endif
275 updateDeviceForStrategy();
276
277 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
278
279 // force routing command to audio hardware when ending call
280 // even if no device change is needed
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -0800281 if (isStateInCall(oldState) && newDevice == 0) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800282 newDevice = hwOutputDesc->device();
283 }
Eric Laurent22e1ca32010-02-23 09:48:31 -0800284
285 // when changing from ring tone to in call mode, mute the ringing tone
286 // immediately and delay the route change to avoid sending the ring tone
287 // tail into the earpiece or headset.
288 int delayMs = 0;
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -0800289 if (isStateInCall(state) && oldState == AudioSystem::MODE_RINGTONE) {
Eric Laurent22e1ca32010-02-23 09:48:31 -0800290 // delay the device change command by twice the output latency to have some margin
291 // and be sure that audio buffers not yet affected by the mute are out when
292 // we actually apply the route change
293 delayMs = hwOutputDesc->mLatency*2;
294 setStreamMute(AudioSystem::RING, true, mHardwareOutput);
295 }
296
Eric Laurentcef3cd72009-12-10 01:03:50 -0800297 // change routing is necessary
Eric Laurent22e1ca32010-02-23 09:48:31 -0800298 setOutputDevice(mHardwareOutput, newDevice, force, delayMs);
Eric Laurentcef3cd72009-12-10 01:03:50 -0800299
300 // if entering in call state, handle special case of active streams
301 // pertaining to sonification strategy see handleIncallSonification()
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -0800302 if (isStateInCall(state)) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800303 LOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent22e1ca32010-02-23 09:48:31 -0800304 // unmute the ringing tone after a sufficient delay if it was muted before
305 // setting output device above
306 if (oldState == AudioSystem::MODE_RINGTONE) {
307 setStreamMute(AudioSystem::RING, false, mHardwareOutput, MUTE_TIME_MS);
308 }
Eric Laurentcef3cd72009-12-10 01:03:50 -0800309 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
310 handleIncallSonification(stream, true, true);
311 }
312 }
313
314 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
315 if (state == AudioSystem::MODE_RINGTONE &&
Eric Laurent25101b02011-02-02 09:33:30 -0800316 isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800317 mLimitRingtoneVolume = true;
318 } else {
319 mLimitRingtoneVolume = false;
320 }
321}
322
323void AudioPolicyManagerBase::setRingerMode(uint32_t mode, uint32_t mask)
324{
325 LOGV("setRingerMode() mode %x, mask %x", mode, mask);
326
327 mRingerMode = mode;
328}
329
330void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
331{
332 LOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
333
Jean-Michel Trivi758559e2010-03-09 09:26:08 -0800334 bool forceVolumeReeval = false;
Eric Laurentcef3cd72009-12-10 01:03:50 -0800335 switch(usage) {
336 case AudioSystem::FOR_COMMUNICATION:
337 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
338 config != AudioSystem::FORCE_NONE) {
339 LOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
340 return;
341 }
Eric Laurent257b2d02011-03-15 14:26:03 -0700342 forceVolumeReeval = true;
Eric Laurentcef3cd72009-12-10 01:03:50 -0800343 mForceUse[usage] = config;
344 break;
345 case AudioSystem::FOR_MEDIA:
346 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
Praveen Bharathi21e941b2010-10-06 15:23:14 -0500347 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
348 config != AudioSystem::FORCE_ANALOG_DOCK &&
349 config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800350 LOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
351 return;
352 }
353 mForceUse[usage] = config;
354 break;
355 case AudioSystem::FOR_RECORD:
356 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
357 config != AudioSystem::FORCE_NONE) {
358 LOGW("setForceUse() invalid config %d for FOR_RECORD", config);
359 return;
360 }
361 mForceUse[usage] = config;
362 break;
363 case AudioSystem::FOR_DOCK:
364 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
Praveen Bharathi21e941b2010-10-06 15:23:14 -0500365 config != AudioSystem::FORCE_BT_DESK_DOCK &&
366 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
367 config != AudioSystem::FORCE_ANALOG_DOCK &&
368 config != AudioSystem::FORCE_DIGITAL_DOCK) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800369 LOGW("setForceUse() invalid config %d for FOR_DOCK", config);
370 }
Jean-Michel Trivi758559e2010-03-09 09:26:08 -0800371 forceVolumeReeval = true;
Eric Laurentcef3cd72009-12-10 01:03:50 -0800372 mForceUse[usage] = config;
373 break;
374 default:
375 LOGW("setForceUse() invalid usage %d", usage);
376 break;
377 }
378
379 // check for device and output changes triggered by new phone state
380 uint32_t newDevice = getNewDevice(mHardwareOutput, false);
381#ifdef WITH_A2DP
Eric Laurentb87b53d2010-11-02 12:02:20 -0700382 checkA2dpSuspend();
Eric Laurentbbc9fd32011-03-01 10:28:01 -0800383 checkOutputForAllStrategies();
Eric Laurentcef3cd72009-12-10 01:03:50 -0800384#endif
385 updateDeviceForStrategy();
386 setOutputDevice(mHardwareOutput, newDevice);
Jean-Michel Trivi758559e2010-03-09 09:26:08 -0800387 if (forceVolumeReeval) {
Eric Laurent257b2d02011-03-15 14:26:03 -0700388 applyStreamVolumes(mHardwareOutput, newDevice, 0, true);
Jean-Michel Trivi758559e2010-03-09 09:26:08 -0800389 }
Eric Laurentb8453f42010-08-27 17:10:36 -0700390
391 audio_io_handle_t activeInput = getActiveInput();
392 if (activeInput != 0) {
393 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
394 newDevice = getDeviceForInputSource(inputDesc->mInputSource);
395 if (newDevice != inputDesc->mDevice) {
396 LOGV("setForceUse() changing device from %x to %x for input %d",
397 inputDesc->mDevice, newDevice, activeInput);
398 inputDesc->mDevice = newDevice;
399 AudioParameter param = AudioParameter();
400 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
401 mpClientInterface->setParameters(activeInput, param.toString());
402 }
403 }
404
Eric Laurentcef3cd72009-12-10 01:03:50 -0800405}
406
407AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
408{
409 return mForceUse[usage];
410}
411
412void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
413{
414 LOGV("setSystemProperty() property %s, value %s", property, value);
415 if (strcmp(property, "ro.camera.sound.forced") == 0) {
416 if (atoi(value)) {
417 LOGV("ENFORCED_AUDIBLE cannot be muted");
418 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = false;
419 } else {
420 LOGV("ENFORCED_AUDIBLE can be muted");
421 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = true;
422 }
423 }
424}
425
426audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
427 uint32_t samplingRate,
428 uint32_t format,
429 uint32_t channels,
430 AudioSystem::output_flags flags)
431{
432 audio_io_handle_t output = 0;
433 uint32_t latency = 0;
434 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
435 uint32_t device = getDeviceForStrategy(strategy);
436 LOGV("getOutput() stream %d, samplingRate %d, format %d, channels %x, flags %x", stream, samplingRate, format, channels, flags);
437
438#ifdef AUDIO_POLICY_TEST
439 if (mCurOutput != 0) {
440 LOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channels %x, mDirectOutput %d",
441 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
442
443 if (mTestOutputs[mCurOutput] == 0) {
444 LOGV("getOutput() opening test output");
445 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
446 outputDesc->mDevice = mTestDevice;
447 outputDesc->mSamplingRate = mTestSamplingRate;
448 outputDesc->mFormat = mTestFormat;
449 outputDesc->mChannels = mTestChannels;
450 outputDesc->mLatency = mTestLatencyMs;
451 outputDesc->mFlags = (AudioSystem::output_flags)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
452 outputDesc->mRefCount[stream] = 0;
453 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(&outputDesc->mDevice,
454 &outputDesc->mSamplingRate,
455 &outputDesc->mFormat,
456 &outputDesc->mChannels,
457 &outputDesc->mLatency,
458 outputDesc->mFlags);
459 if (mTestOutputs[mCurOutput]) {
460 AudioParameter outputCmd = AudioParameter();
461 outputCmd.addInt(String8("set_id"),mCurOutput);
462 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
463 addOutput(mTestOutputs[mCurOutput], outputDesc);
464 }
465 }
466 return mTestOutputs[mCurOutput];
467 }
468#endif //AUDIO_POLICY_TEST
469
Eric Laurentef9500f2010-03-11 14:47:00 -0800470 // open a direct output if required by specified parameters
471 if (needsDirectOuput(stream, samplingRate, format, channels, flags, device)) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800472
473 LOGV("getOutput() opening direct output device %x", device);
474 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
475 outputDesc->mDevice = device;
476 outputDesc->mSamplingRate = samplingRate;
477 outputDesc->mFormat = format;
478 outputDesc->mChannels = channels;
479 outputDesc->mLatency = 0;
480 outputDesc->mFlags = (AudioSystem::output_flags)(flags | AudioSystem::OUTPUT_FLAG_DIRECT);
Eric Laurentef9500f2010-03-11 14:47:00 -0800481 outputDesc->mRefCount[stream] = 0;
Eric Laurent25101b02011-02-02 09:33:30 -0800482 outputDesc->mStopTime[stream] = 0;
Eric Laurentcef3cd72009-12-10 01:03:50 -0800483 output = mpClientInterface->openOutput(&outputDesc->mDevice,
484 &outputDesc->mSamplingRate,
485 &outputDesc->mFormat,
486 &outputDesc->mChannels,
487 &outputDesc->mLatency,
488 outputDesc->mFlags);
489
490 // only accept an output with the requeted parameters
491 if (output == 0 ||
492 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
493 (format != 0 && format != outputDesc->mFormat) ||
494 (channels != 0 && channels != outputDesc->mChannels)) {
495 LOGV("getOutput() failed opening direct output: samplingRate %d, format %d, channels %d",
496 samplingRate, format, channels);
497 if (output != 0) {
498 mpClientInterface->closeOutput(output);
499 }
500 delete outputDesc;
501 return 0;
502 }
503 addOutput(output, outputDesc);
504 return output;
505 }
506
507 if (channels != 0 && channels != AudioSystem::CHANNEL_OUT_MONO &&
508 channels != AudioSystem::CHANNEL_OUT_STEREO) {
509 return 0;
510 }
511 // open a non direct output
512
513 // get which output is suitable for the specified stream. The actual routing change will happen
514 // when startOutput() will be called
515 uint32_t a2dpDevice = device & AudioSystem::DEVICE_OUT_ALL_A2DP;
516 if (AudioSystem::popCount((AudioSystem::audio_devices)device) == 2) {
517#ifdef WITH_A2DP
518 if (a2dpUsedForSonification() && a2dpDevice != 0) {
519 // if playing on 2 devices among which one is A2DP, use duplicated output
520 LOGV("getOutput() using duplicated output");
521 LOGW_IF((mA2dpOutput == 0), "getOutput() A2DP device in multiple %x selected but A2DP output not opened", device);
522 output = mDuplicatedOutput;
523 } else
524#endif
525 {
526 // if playing on 2 devices among which none is A2DP, use hardware output
527 output = mHardwareOutput;
528 }
529 LOGV("getOutput() using output %d for 2 devices %x", output, device);
530 } else {
531#ifdef WITH_A2DP
532 if (a2dpDevice != 0) {
533 // if playing on A2DP device, use a2dp output
534 LOGW_IF((mA2dpOutput == 0), "getOutput() A2DP device %x selected but A2DP output not opened", device);
535 output = mA2dpOutput;
536 } else
537#endif
538 {
539 // if playing on not A2DP device, use hardware output
540 output = mHardwareOutput;
541 }
542 }
543
544
545 LOGW_IF((output ==0), "getOutput() could not find output for stream %d, samplingRate %d, format %d, channels %x, flags %x",
546 stream, samplingRate, format, channels, flags);
547
548 return output;
549}
550
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700551status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
552 AudioSystem::stream_type stream,
553 int session)
Eric Laurentcef3cd72009-12-10 01:03:50 -0800554{
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700555 LOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
Eric Laurentcef3cd72009-12-10 01:03:50 -0800556 ssize_t index = mOutputs.indexOfKey(output);
557 if (index < 0) {
558 LOGW("startOutput() unknow output %d", output);
559 return BAD_VALUE;
560 }
561
562 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
563 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
564
565#ifdef WITH_A2DP
566 if (mA2dpOutput != 0 && !a2dpUsedForSonification() && strategy == STRATEGY_SONIFICATION) {
567 setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput);
568 }
569#endif
570
571 // incremenent usage count for this stream on the requested output:
572 // NOTE that the usage count is the same for duplicated output and hardware output which is
573 // necassary for a correct control of hardware output routing by startOutput() and stopOutput()
574 outputDesc->changeRefCount(stream, 1);
575
576 setOutputDevice(output, getNewDevice(output));
577
578 // handle special case for sonification while in call
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -0800579 if (isInCall()) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800580 handleIncallSonification(stream, true, false);
581 }
582
583 // apply volume rules for current stream and device if necessary
584 checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, outputDesc->device());
585
586 return NO_ERROR;
587}
588
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700589status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
590 AudioSystem::stream_type stream,
591 int session)
Eric Laurentcef3cd72009-12-10 01:03:50 -0800592{
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700593 LOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
Eric Laurentcef3cd72009-12-10 01:03:50 -0800594 ssize_t index = mOutputs.indexOfKey(output);
595 if (index < 0) {
596 LOGW("stopOutput() unknow output %d", output);
597 return BAD_VALUE;
598 }
599
600 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
601 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
602
603 // handle special case for sonification while in call
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -0800604 if (isInCall()) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800605 handleIncallSonification(stream, false, false);
606 }
607
608 if (outputDesc->mRefCount[stream] > 0) {
609 // decrement usage count of this stream on the output
610 outputDesc->changeRefCount(stream, -1);
Eric Laurent25101b02011-02-02 09:33:30 -0800611 // store time at which the stream was stopped - see isStreamActive()
612 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentcef3cd72009-12-10 01:03:50 -0800613
Eric Laurentd0545f52011-02-11 14:39:34 -0800614 setOutputDevice(output, getNewDevice(output), false, outputDesc->mLatency*2);
Eric Laurentcef3cd72009-12-10 01:03:50 -0800615
616#ifdef WITH_A2DP
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700617 if (mA2dpOutput != 0 && !a2dpUsedForSonification() &&
618 strategy == STRATEGY_SONIFICATION) {
619 setStrategyMute(STRATEGY_MEDIA,
620 false,
621 mA2dpOutput,
622 mOutputs.valueFor(mHardwareOutput)->mLatency*2);
Eric Laurentcef3cd72009-12-10 01:03:50 -0800623 }
624#endif
Eric Laurentef9500f2010-03-11 14:47:00 -0800625 if (output != mHardwareOutput) {
626 setOutputDevice(mHardwareOutput, getNewDevice(mHardwareOutput), true);
627 }
Eric Laurentcef3cd72009-12-10 01:03:50 -0800628 return NO_ERROR;
629 } else {
630 LOGW("stopOutput() refcount is already 0 for output %d", output);
631 return INVALID_OPERATION;
632 }
633}
634
635void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
636{
637 LOGV("releaseOutput() %d", output);
638 ssize_t index = mOutputs.indexOfKey(output);
639 if (index < 0) {
640 LOGW("releaseOutput() releasing unknown output %d", output);
641 return;
642 }
643
644#ifdef AUDIO_POLICY_TEST
645 int testIndex = testOutputIndex(output);
646 if (testIndex != 0) {
647 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
648 if (outputDesc->refCount() == 0) {
649 mpClientInterface->closeOutput(output);
650 delete mOutputs.valueAt(index);
651 mOutputs.removeItem(output);
652 mTestOutputs[testIndex] = 0;
653 }
654 return;
655 }
656#endif //AUDIO_POLICY_TEST
657
658 if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
659 mpClientInterface->closeOutput(output);
660 delete mOutputs.valueAt(index);
661 mOutputs.removeItem(output);
662 }
663}
664
665audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
666 uint32_t samplingRate,
667 uint32_t format,
668 uint32_t channels,
669 AudioSystem::audio_in_acoustics acoustics)
670{
671 audio_io_handle_t input = 0;
672 uint32_t device = getDeviceForInputSource(inputSource);
673
674 LOGV("getInput() inputSource %d, samplingRate %d, format %d, channels %x, acoustics %x", inputSource, samplingRate, format, channels, acoustics);
675
676 if (device == 0) {
677 return 0;
678 }
679
680 // adapt channel selection to input source
681 switch(inputSource) {
682 case AUDIO_SOURCE_VOICE_UPLINK:
683 channels = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
684 break;
685 case AUDIO_SOURCE_VOICE_DOWNLINK:
686 channels = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
687 break;
688 case AUDIO_SOURCE_VOICE_CALL:
689 channels = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
690 break;
691 default:
692 break;
693 }
694
695 AudioInputDescriptor *inputDesc = new AudioInputDescriptor();
696
697 inputDesc->mInputSource = inputSource;
698 inputDesc->mDevice = device;
699 inputDesc->mSamplingRate = samplingRate;
700 inputDesc->mFormat = format;
701 inputDesc->mChannels = channels;
702 inputDesc->mAcoustics = acoustics;
703 inputDesc->mRefCount = 0;
704 input = mpClientInterface->openInput(&inputDesc->mDevice,
705 &inputDesc->mSamplingRate,
706 &inputDesc->mFormat,
707 &inputDesc->mChannels,
708 inputDesc->mAcoustics);
709
710 // only accept input with the exact requested set of parameters
711 if (input == 0 ||
712 (samplingRate != inputDesc->mSamplingRate) ||
713 (format != inputDesc->mFormat) ||
714 (channels != inputDesc->mChannels)) {
715 LOGV("getInput() failed opening input: samplingRate %d, format %d, channels %d",
716 samplingRate, format, channels);
717 if (input != 0) {
718 mpClientInterface->closeInput(input);
719 }
720 delete inputDesc;
721 return 0;
722 }
723 mInputs.add(input, inputDesc);
724 return input;
725}
726
727status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
728{
729 LOGV("startInput() input %d", input);
730 ssize_t index = mInputs.indexOfKey(input);
731 if (index < 0) {
732 LOGW("startInput() unknow input %d", input);
733 return BAD_VALUE;
734 }
735 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
736
737#ifdef AUDIO_POLICY_TEST
738 if (mTestInput == 0)
739#endif //AUDIO_POLICY_TEST
740 {
741 // refuse 2 active AudioRecord clients at the same time
742 if (getActiveInput() != 0) {
743 LOGW("startInput() input %d failed: other input already started", input);
744 return INVALID_OPERATION;
745 }
746 }
747
748 AudioParameter param = AudioParameter();
749 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
750
Jean-Michel Trivi1a22bdb2010-11-09 14:06:52 -0800751 param.addInt(String8(AudioParameter::keyInputSource), (int)inputDesc->mInputSource);
752 LOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
Eric Laurentcef3cd72009-12-10 01:03:50 -0800753
754 mpClientInterface->setParameters(input, param.toString());
755
756 inputDesc->mRefCount = 1;
757 return NO_ERROR;
758}
759
760status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
761{
762 LOGV("stopInput() input %d", input);
763 ssize_t index = mInputs.indexOfKey(input);
764 if (index < 0) {
765 LOGW("stopInput() unknow input %d", input);
766 return BAD_VALUE;
767 }
768 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
769
770 if (inputDesc->mRefCount == 0) {
771 LOGW("stopInput() input %d already stopped", input);
772 return INVALID_OPERATION;
773 } else {
774 AudioParameter param = AudioParameter();
775 param.addInt(String8(AudioParameter::keyRouting), 0);
776 mpClientInterface->setParameters(input, param.toString());
777 inputDesc->mRefCount = 0;
778 return NO_ERROR;
779 }
780}
781
782void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
783{
784 LOGV("releaseInput() %d", input);
785 ssize_t index = mInputs.indexOfKey(input);
786 if (index < 0) {
787 LOGW("releaseInput() releasing unknown input %d", input);
788 return;
789 }
790 mpClientInterface->closeInput(input);
791 delete mInputs.valueAt(index);
792 mInputs.removeItem(input);
793 LOGV("releaseInput() exit");
794}
795
796void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
797 int indexMin,
798 int indexMax)
799{
800 LOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
801 if (indexMin < 0 || indexMin >= indexMax) {
802 LOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
803 return;
804 }
805 mStreams[stream].mIndexMin = indexMin;
806 mStreams[stream].mIndexMax = indexMax;
807}
808
809status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream, int index)
810{
811
812 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
813 return BAD_VALUE;
814 }
815
816 // Force max volume if stream cannot be muted
817 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
818
819 LOGV("setStreamVolumeIndex() stream %d, index %d", stream, index);
820 mStreams[stream].mIndexCur = index;
821
822 // compute and apply stream volume on all outputs according to connected device
823 status_t status = NO_ERROR;
824 for (size_t i = 0; i < mOutputs.size(); i++) {
825 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), mOutputs.valueAt(i)->device());
826 if (volStatus != NO_ERROR) {
827 status = volStatus;
828 }
829 }
830 return status;
831}
832
833status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream, int *index)
834{
835 if (index == 0) {
836 return BAD_VALUE;
837 }
838 LOGV("getStreamVolumeIndex() stream %d", stream);
839 *index = mStreams[stream].mIndexCur;
840 return NO_ERROR;
841}
842
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700843audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(effect_descriptor_t *desc)
844{
845 LOGV("getOutputForEffect()");
846 // apply simple rule where global effects are attached to the same output as MUSIC streams
847 return getOutput(AudioSystem::MUSIC);
848}
849
850status_t AudioPolicyManagerBase::registerEffect(effect_descriptor_t *desc,
851 audio_io_handle_t output,
852 uint32_t strategy,
853 int session,
854 int id)
855{
856 ssize_t index = mOutputs.indexOfKey(output);
857 if (index < 0) {
858 LOGW("registerEffect() unknown output %d", output);
859 return INVALID_OPERATION;
860 }
861
862 if (mTotalEffectsCpuLoad + desc->cpuLoad > getMaxEffectsCpuLoad()) {
863 LOGW("registerEffect() CPU Load limit exceeded for Fx %s, CPU %f MIPS",
864 desc->name, (float)desc->cpuLoad/10);
865 return INVALID_OPERATION;
866 }
867 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
868 LOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
869 desc->name, desc->memoryUsage);
870 return INVALID_OPERATION;
871 }
872 mTotalEffectsCpuLoad += desc->cpuLoad;
873 mTotalEffectsMemory += desc->memoryUsage;
874 LOGV("registerEffect() effect %s, output %d, strategy %d session %d id %d",
875 desc->name, output, strategy, session, id);
876
877 LOGV("registerEffect() CPU %d, memory %d", desc->cpuLoad, desc->memoryUsage);
878 LOGV(" total CPU %d, total memory %d", mTotalEffectsCpuLoad, mTotalEffectsMemory);
879
880 EffectDescriptor *pDesc = new EffectDescriptor();
881 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
882 pDesc->mOutput = output;
883 pDesc->mStrategy = (routing_strategy)strategy;
884 pDesc->mSession = session;
885 mEffects.add(id, pDesc);
886
887 return NO_ERROR;
888}
889
890status_t AudioPolicyManagerBase::unregisterEffect(int id)
891{
892 ssize_t index = mEffects.indexOfKey(id);
893 if (index < 0) {
894 LOGW("unregisterEffect() unknown effect ID %d", id);
895 return INVALID_OPERATION;
896 }
897
898 EffectDescriptor *pDesc = mEffects.valueAt(index);
899
900 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
901 LOGW("unregisterEffect() CPU load %d too high for total %d",
902 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
903 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
904 }
905 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
906 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
907 LOGW("unregisterEffect() memory %d too big for total %d",
908 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
909 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
910 }
911 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
912 LOGV("unregisterEffect() effect %s, ID %d, CPU %d, memory %d",
913 pDesc->mDesc.name, id, pDesc->mDesc.cpuLoad, pDesc->mDesc.memoryUsage);
914 LOGV(" total CPU %d, total memory %d", mTotalEffectsCpuLoad, mTotalEffectsMemory);
915
916 mEffects.removeItem(id);
917 delete pDesc;
918
919 return NO_ERROR;
920}
921
Eric Laurent25101b02011-02-02 09:33:30 -0800922bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
923{
924 nsecs_t sysTime = systemTime();
925 for (size_t i = 0; i < mOutputs.size(); i++) {
926 if (mOutputs.valueAt(i)->mRefCount[stream] != 0 ||
927 ns2ms(sysTime - mOutputs.valueAt(i)->mStopTime[stream]) < inPastMs) {
928 return true;
929 }
930 }
931 return false;
932}
933
934
Eric Laurentcef3cd72009-12-10 01:03:50 -0800935status_t AudioPolicyManagerBase::dump(int fd)
936{
937 const size_t SIZE = 256;
938 char buffer[SIZE];
939 String8 result;
940
941 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
942 result.append(buffer);
943 snprintf(buffer, SIZE, " Hardware Output: %d\n", mHardwareOutput);
944 result.append(buffer);
945#ifdef WITH_A2DP
946 snprintf(buffer, SIZE, " A2DP Output: %d\n", mA2dpOutput);
947 result.append(buffer);
948 snprintf(buffer, SIZE, " Duplicated Output: %d\n", mDuplicatedOutput);
949 result.append(buffer);
950 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
951 result.append(buffer);
952#endif
953 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
954 result.append(buffer);
955 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
956 result.append(buffer);
957 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
958 result.append(buffer);
959 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
960 result.append(buffer);
961 snprintf(buffer, SIZE, " Ringer mode: %d\n", mRingerMode);
962 result.append(buffer);
963 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
964 result.append(buffer);
965 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
966 result.append(buffer);
967 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
968 result.append(buffer);
969 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
970 result.append(buffer);
971 write(fd, result.string(), result.size());
972
973 snprintf(buffer, SIZE, "\nOutputs dump:\n");
974 write(fd, buffer, strlen(buffer));
975 for (size_t i = 0; i < mOutputs.size(); i++) {
976 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
977 write(fd, buffer, strlen(buffer));
978 mOutputs.valueAt(i)->dump(fd);
979 }
980
981 snprintf(buffer, SIZE, "\nInputs dump:\n");
982 write(fd, buffer, strlen(buffer));
983 for (size_t i = 0; i < mInputs.size(); i++) {
984 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
985 write(fd, buffer, strlen(buffer));
986 mInputs.valueAt(i)->dump(fd);
987 }
988
989 snprintf(buffer, SIZE, "\nStreams dump:\n");
990 write(fd, buffer, strlen(buffer));
991 snprintf(buffer, SIZE, " Stream Index Min Index Max Index Cur Can be muted\n");
992 write(fd, buffer, strlen(buffer));
993 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
994 snprintf(buffer, SIZE, " %02d", i);
995 mStreams[i].dump(buffer + 3, SIZE);
996 write(fd, buffer, strlen(buffer));
997 }
998
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700999 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1000 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1001 write(fd, buffer, strlen(buffer));
1002
1003 snprintf(buffer, SIZE, "Registered effects:\n");
1004 write(fd, buffer, strlen(buffer));
1005 for (size_t i = 0; i < mEffects.size(); i++) {
1006 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1007 write(fd, buffer, strlen(buffer));
1008 mEffects.valueAt(i)->dump(fd);
1009 }
1010
1011
Eric Laurentcef3cd72009-12-10 01:03:50 -08001012 return NO_ERROR;
1013}
1014
1015// ----------------------------------------------------------------------------
1016// AudioPolicyManagerBase
1017// ----------------------------------------------------------------------------
1018
1019AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1020 :
1021#ifdef AUDIO_POLICY_TEST
1022 Thread(false),
1023#endif //AUDIO_POLICY_TEST
Eric Laurentfad77872010-12-01 12:11:10 -08001024 mPhoneState(AudioSystem::MODE_NORMAL), mRingerMode(0),
Eric Laurent25101b02011-02-02 09:33:30 -08001025 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurentfad77872010-12-01 12:11:10 -08001026 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurentb87b53d2010-11-02 12:02:20 -07001027 mA2dpSuspended(false)
Eric Laurentcef3cd72009-12-10 01:03:50 -08001028{
1029 mpClientInterface = clientInterface;
1030
1031 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1032 mForceUse[i] = AudioSystem::FORCE_NONE;
1033 }
1034
Jean-Michel Trivi3aab0582011-01-24 15:28:26 -08001035 initializeVolumeCurves();
1036
Eric Laurentcef3cd72009-12-10 01:03:50 -08001037 // devices available by default are speaker, ear piece and microphone
1038 mAvailableOutputDevices = AudioSystem::DEVICE_OUT_EARPIECE |
1039 AudioSystem::DEVICE_OUT_SPEAKER;
1040 mAvailableInputDevices = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1041
1042#ifdef WITH_A2DP
1043 mA2dpOutput = 0;
1044 mDuplicatedOutput = 0;
1045 mA2dpDeviceAddress = String8("");
1046#endif
1047 mScoDeviceAddress = String8("");
1048
1049 // open hardware output
1050 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1051 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1052 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1053 &outputDesc->mSamplingRate,
1054 &outputDesc->mFormat,
1055 &outputDesc->mChannels,
1056 &outputDesc->mLatency,
1057 outputDesc->mFlags);
1058
1059 if (mHardwareOutput == 0) {
1060 LOGE("Failed to initialize hardware output stream, samplingRate: %d, format %d, channels %d",
1061 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
1062 } else {
1063 addOutput(mHardwareOutput, outputDesc);
1064 setOutputDevice(mHardwareOutput, (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER, true);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001065 //TODO: configure audio effect output stage here
Eric Laurentcef3cd72009-12-10 01:03:50 -08001066 }
1067
1068 updateDeviceForStrategy();
1069#ifdef AUDIO_POLICY_TEST
Eric Laurent01635942011-01-18 18:39:02 -08001070 if (mHardwareOutput != 0) {
1071 AudioParameter outputCmd = AudioParameter();
1072 outputCmd.addInt(String8("set_id"), 0);
1073 mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString());
Eric Laurentcef3cd72009-12-10 01:03:50 -08001074
Eric Laurent01635942011-01-18 18:39:02 -08001075 mTestDevice = AudioSystem::DEVICE_OUT_SPEAKER;
1076 mTestSamplingRate = 44100;
1077 mTestFormat = AudioSystem::PCM_16_BIT;
1078 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1079 mTestLatencyMs = 0;
1080 mCurOutput = 0;
1081 mDirectOutput = false;
1082 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1083 mTestOutputs[i] = 0;
1084 }
1085
1086 const size_t SIZE = 256;
1087 char buffer[SIZE];
1088 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1089 run(buffer, ANDROID_PRIORITY_AUDIO);
Eric Laurentcef3cd72009-12-10 01:03:50 -08001090 }
Eric Laurentcef3cd72009-12-10 01:03:50 -08001091#endif //AUDIO_POLICY_TEST
1092}
1093
1094AudioPolicyManagerBase::~AudioPolicyManagerBase()
1095{
1096#ifdef AUDIO_POLICY_TEST
1097 exit();
1098#endif //AUDIO_POLICY_TEST
1099 for (size_t i = 0; i < mOutputs.size(); i++) {
1100 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1101 delete mOutputs.valueAt(i);
1102 }
1103 mOutputs.clear();
1104 for (size_t i = 0; i < mInputs.size(); i++) {
1105 mpClientInterface->closeInput(mInputs.keyAt(i));
1106 delete mInputs.valueAt(i);
1107 }
1108 mInputs.clear();
1109}
1110
Eric Laurent01635942011-01-18 18:39:02 -08001111status_t AudioPolicyManagerBase::initCheck()
1112{
1113 return (mHardwareOutput == 0) ? NO_INIT : NO_ERROR;
1114}
1115
Eric Laurentcef3cd72009-12-10 01:03:50 -08001116#ifdef AUDIO_POLICY_TEST
1117bool AudioPolicyManagerBase::threadLoop()
1118{
1119 LOGV("entering threadLoop()");
1120 while (!exitPending())
1121 {
1122 String8 command;
1123 int valueInt;
1124 String8 value;
1125
1126 Mutex::Autolock _l(mLock);
1127 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1128
1129 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1130 AudioParameter param = AudioParameter(command);
1131
1132 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1133 valueInt != 0) {
1134 LOGV("Test command %s received", command.string());
1135 String8 target;
1136 if (param.get(String8("target"), target) != NO_ERROR) {
1137 target = "Manager";
1138 }
1139 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1140 param.remove(String8("test_cmd_policy_output"));
1141 mCurOutput = valueInt;
1142 }
1143 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1144 param.remove(String8("test_cmd_policy_direct"));
1145 if (value == "false") {
1146 mDirectOutput = false;
1147 } else if (value == "true") {
1148 mDirectOutput = true;
1149 }
1150 }
1151 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1152 param.remove(String8("test_cmd_policy_input"));
1153 mTestInput = valueInt;
1154 }
1155
1156 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1157 param.remove(String8("test_cmd_policy_format"));
1158 int format = AudioSystem::INVALID_FORMAT;
1159 if (value == "PCM 16 bits") {
1160 format = AudioSystem::PCM_16_BIT;
1161 } else if (value == "PCM 8 bits") {
1162 format = AudioSystem::PCM_8_BIT;
1163 } else if (value == "Compressed MP3") {
1164 format = AudioSystem::MP3;
1165 }
1166 if (format != AudioSystem::INVALID_FORMAT) {
1167 if (target == "Manager") {
1168 mTestFormat = format;
1169 } else if (mTestOutputs[mCurOutput] != 0) {
1170 AudioParameter outputParam = AudioParameter();
1171 outputParam.addInt(String8("format"), format);
1172 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1173 }
1174 }
1175 }
1176 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1177 param.remove(String8("test_cmd_policy_channels"));
1178 int channels = 0;
1179
1180 if (value == "Channels Stereo") {
1181 channels = AudioSystem::CHANNEL_OUT_STEREO;
1182 } else if (value == "Channels Mono") {
1183 channels = AudioSystem::CHANNEL_OUT_MONO;
1184 }
1185 if (channels != 0) {
1186 if (target == "Manager") {
1187 mTestChannels = channels;
1188 } else if (mTestOutputs[mCurOutput] != 0) {
1189 AudioParameter outputParam = AudioParameter();
1190 outputParam.addInt(String8("channels"), channels);
1191 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1192 }
1193 }
1194 }
1195 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1196 param.remove(String8("test_cmd_policy_sampleRate"));
1197 if (valueInt >= 0 && valueInt <= 96000) {
1198 int samplingRate = valueInt;
1199 if (target == "Manager") {
1200 mTestSamplingRate = samplingRate;
1201 } else if (mTestOutputs[mCurOutput] != 0) {
1202 AudioParameter outputParam = AudioParameter();
1203 outputParam.addInt(String8("sampling_rate"), samplingRate);
1204 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1205 }
1206 }
1207 }
1208
1209 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1210 param.remove(String8("test_cmd_policy_reopen"));
1211
1212 mpClientInterface->closeOutput(mHardwareOutput);
1213 delete mOutputs.valueFor(mHardwareOutput);
1214 mOutputs.removeItem(mHardwareOutput);
1215
1216 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1217 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1218 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1219 &outputDesc->mSamplingRate,
1220 &outputDesc->mFormat,
1221 &outputDesc->mChannels,
1222 &outputDesc->mLatency,
1223 outputDesc->mFlags);
1224 if (mHardwareOutput == 0) {
1225 LOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1226 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
1227 } else {
1228 AudioParameter outputCmd = AudioParameter();
1229 outputCmd.addInt(String8("set_id"), 0);
1230 mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString());
1231 addOutput(mHardwareOutput, outputDesc);
1232 }
1233 }
1234
1235
1236 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1237 }
1238 }
1239 return false;
1240}
1241
1242void AudioPolicyManagerBase::exit()
1243{
1244 {
1245 AutoMutex _l(mLock);
1246 requestExit();
1247 mWaitWorkCV.signal();
1248 }
1249 requestExitAndWait();
1250}
1251
1252int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1253{
1254 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1255 if (output == mTestOutputs[i]) return i;
1256 }
1257 return 0;
1258}
1259#endif //AUDIO_POLICY_TEST
1260
1261// ---
1262
1263void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1264{
1265 outputDesc->mId = id;
1266 mOutputs.add(id, outputDesc);
1267}
1268
1269
1270#ifdef WITH_A2DP
1271status_t AudioPolicyManagerBase::handleA2dpConnection(AudioSystem::audio_devices device,
1272 const char *device_address)
1273{
1274 // when an A2DP device is connected, open an A2DP and a duplicated output
1275 LOGV("opening A2DP output for device %s", device_address);
1276 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1277 outputDesc->mDevice = device;
1278 mA2dpOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1279 &outputDesc->mSamplingRate,
1280 &outputDesc->mFormat,
1281 &outputDesc->mChannels,
1282 &outputDesc->mLatency,
1283 outputDesc->mFlags);
1284 if (mA2dpOutput) {
1285 // add A2DP output descriptor
1286 addOutput(mA2dpOutput, outputDesc);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001287
1288 //TODO: configure audio effect output stage here
1289
Eric Laurentcef3cd72009-12-10 01:03:50 -08001290 // set initial stream volume for A2DP device
1291 applyStreamVolumes(mA2dpOutput, device);
1292 if (a2dpUsedForSonification()) {
1293 mDuplicatedOutput = mpClientInterface->openDuplicateOutput(mA2dpOutput, mHardwareOutput);
1294 }
1295 if (mDuplicatedOutput != 0 ||
1296 !a2dpUsedForSonification()) {
1297 // If both A2DP and duplicated outputs are open, send device address to A2DP hardware
1298 // interface
1299 AudioParameter param;
1300 param.add(String8("a2dp_sink_address"), String8(device_address));
1301 mpClientInterface->setParameters(mA2dpOutput, param.toString());
1302 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
1303
1304 if (a2dpUsedForSonification()) {
1305 // add duplicated output descriptor
1306 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor();
1307 dupOutputDesc->mOutput1 = mOutputs.valueFor(mHardwareOutput);
1308 dupOutputDesc->mOutput2 = mOutputs.valueFor(mA2dpOutput);
1309 dupOutputDesc->mSamplingRate = outputDesc->mSamplingRate;
1310 dupOutputDesc->mFormat = outputDesc->mFormat;
1311 dupOutputDesc->mChannels = outputDesc->mChannels;
1312 dupOutputDesc->mLatency = outputDesc->mLatency;
1313 addOutput(mDuplicatedOutput, dupOutputDesc);
1314 applyStreamVolumes(mDuplicatedOutput, device);
1315 }
1316 } else {
1317 LOGW("getOutput() could not open duplicated output for %d and %d",
1318 mHardwareOutput, mA2dpOutput);
1319 mpClientInterface->closeOutput(mA2dpOutput);
1320 mOutputs.removeItem(mA2dpOutput);
1321 mA2dpOutput = 0;
1322 delete outputDesc;
1323 return NO_INIT;
1324 }
1325 } else {
1326 LOGW("setDeviceConnectionState() could not open A2DP output for device %x", device);
1327 delete outputDesc;
1328 return NO_INIT;
1329 }
1330 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
1331
Eric Laurentcef3cd72009-12-10 01:03:50 -08001332 if (!a2dpUsedForSonification()) {
1333 // mute music on A2DP output if a notification or ringtone is playing
1334 uint32_t refCount = hwOutputDesc->strategyRefCount(STRATEGY_SONIFICATION);
1335 for (uint32_t i = 0; i < refCount; i++) {
1336 setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput);
1337 }
1338 }
Eric Laurentb87b53d2010-11-02 12:02:20 -07001339
1340 mA2dpSuspended = false;
1341
Eric Laurentcef3cd72009-12-10 01:03:50 -08001342 return NO_ERROR;
1343}
1344
1345status_t AudioPolicyManagerBase::handleA2dpDisconnection(AudioSystem::audio_devices device,
1346 const char *device_address)
1347{
1348 if (mA2dpOutput == 0) {
1349 LOGW("setDeviceConnectionState() disconnecting A2DP and no A2DP output!");
1350 return INVALID_OPERATION;
1351 }
1352
1353 if (mA2dpDeviceAddress != device_address) {
1354 LOGW("setDeviceConnectionState() disconnecting unknow A2DP sink address %s", device_address);
1355 return INVALID_OPERATION;
1356 }
1357
Eric Laurent22e1ca32010-02-23 09:48:31 -08001358 // mute media strategy to avoid outputting sound on hardware output while music stream
Eric Laurentcef3cd72009-12-10 01:03:50 -08001359 // is switched from A2DP output and before music is paused by music application
1360 setStrategyMute(STRATEGY_MEDIA, true, mHardwareOutput);
Eric Laurent22e1ca32010-02-23 09:48:31 -08001361 setStrategyMute(STRATEGY_MEDIA, false, mHardwareOutput, MUTE_TIME_MS);
Eric Laurentcef3cd72009-12-10 01:03:50 -08001362
1363 if (!a2dpUsedForSonification()) {
1364 // unmute music on A2DP output if a notification or ringtone is playing
1365 uint32_t refCount = mOutputs.valueFor(mHardwareOutput)->strategyRefCount(STRATEGY_SONIFICATION);
1366 for (uint32_t i = 0; i < refCount; i++) {
1367 setStrategyMute(STRATEGY_MEDIA, false, mA2dpOutput);
1368 }
1369 }
1370 mA2dpDeviceAddress = "";
Eric Laurentb87b53d2010-11-02 12:02:20 -07001371 mA2dpSuspended = false;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001372 return NO_ERROR;
1373}
1374
1375void AudioPolicyManagerBase::closeA2dpOutputs()
1376{
Praveen Bharathi21e941b2010-10-06 15:23:14 -05001377
Eric Laurentcef3cd72009-12-10 01:03:50 -08001378 LOGV("setDeviceConnectionState() closing A2DP and duplicated output!");
1379
1380 if (mDuplicatedOutput != 0) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001381 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueFor(mDuplicatedOutput);
1382 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
1383 // As all active tracks on duplicated output will be deleted,
1384 // and as they were also referenced on hardware output, the reference
1385 // count for their stream type must be adjusted accordingly on
1386 // hardware output.
1387 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1388 int refCount = dupOutputDesc->mRefCount[i];
1389 hwOutputDesc->changeRefCount((AudioSystem::stream_type)i,-refCount);
1390 }
1391
Eric Laurentcef3cd72009-12-10 01:03:50 -08001392 mpClientInterface->closeOutput(mDuplicatedOutput);
1393 delete mOutputs.valueFor(mDuplicatedOutput);
1394 mOutputs.removeItem(mDuplicatedOutput);
1395 mDuplicatedOutput = 0;
1396 }
1397 if (mA2dpOutput != 0) {
1398 AudioParameter param;
1399 param.add(String8("closing"), String8("true"));
1400 mpClientInterface->setParameters(mA2dpOutput, param.toString());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001401
Eric Laurentcef3cd72009-12-10 01:03:50 -08001402 mpClientInterface->closeOutput(mA2dpOutput);
1403 delete mOutputs.valueFor(mA2dpOutput);
1404 mOutputs.removeItem(mA2dpOutput);
1405 mA2dpOutput = 0;
1406 }
1407}
1408
Eric Laurentb8453f42010-08-27 17:10:36 -07001409void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
Eric Laurentcef3cd72009-12-10 01:03:50 -08001410{
1411 uint32_t prevDevice = getDeviceForStrategy(strategy);
1412 uint32_t curDevice = getDeviceForStrategy(strategy, false);
1413 bool a2dpWasUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(prevDevice & ~AudioSystem::DEVICE_OUT_SPEAKER));
1414 bool a2dpIsUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(curDevice & ~AudioSystem::DEVICE_OUT_SPEAKER));
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001415 audio_io_handle_t srcOutput = 0;
1416 audio_io_handle_t dstOutput = 0;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001417
1418 if (a2dpWasUsed && !a2dpIsUsed) {
1419 bool dupUsed = a2dpUsedForSonification() && a2dpWasUsed && (AudioSystem::popCount(prevDevice) == 2);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001420 dstOutput = mHardwareOutput;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001421 if (dupUsed) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001422 LOGV("checkOutputForStrategy() moving strategy %d from duplicated", strategy);
1423 srcOutput = mDuplicatedOutput;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001424 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001425 LOGV("checkOutputForStrategy() moving strategy %d from a2dp", strategy);
1426 srcOutput = mA2dpOutput;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001427 }
Eric Laurentcef3cd72009-12-10 01:03:50 -08001428 }
1429 if (a2dpIsUsed && !a2dpWasUsed) {
1430 bool dupUsed = a2dpUsedForSonification() && a2dpIsUsed && (AudioSystem::popCount(curDevice) == 2);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001431 srcOutput = mHardwareOutput;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001432 if (dupUsed) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001433 LOGV("checkOutputForStrategy() moving strategy %d to duplicated", strategy);
1434 dstOutput = mDuplicatedOutput;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001435 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001436 LOGV("checkOutputForStrategy() moving strategy %d to a2dp", strategy);
1437 dstOutput = mA2dpOutput;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001438 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001439 }
Eric Laurentcef3cd72009-12-10 01:03:50 -08001440
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001441 if (srcOutput != 0 && dstOutput != 0) {
1442 // Move effects associated to this strategy from previous output to new output
1443 for (size_t i = 0; i < mEffects.size(); i++) {
1444 EffectDescriptor *desc = mEffects.valueAt(i);
1445 if (desc->mSession != AudioSystem::SESSION_OUTPUT_STAGE &&
1446 desc->mStrategy == strategy &&
1447 desc->mOutput == srcOutput) {
1448 LOGV("checkOutputForStrategy() moving effect %d to output %d", mEffects.keyAt(i), dstOutput);
1449 mpClientInterface->moveEffects(desc->mSession, srcOutput, dstOutput);
1450 desc->mOutput = dstOutput;
1451 }
1452 }
1453 // Move tracks associated to this strategy from previous output to new output
Eric Laurentcef3cd72009-12-10 01:03:50 -08001454 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1455 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001456 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, dstOutput);
Eric Laurentcef3cd72009-12-10 01:03:50 -08001457 }
1458 }
1459 }
1460}
1461
Eric Laurentb8453f42010-08-27 17:10:36 -07001462void AudioPolicyManagerBase::checkOutputForAllStrategies()
Eric Laurentcef3cd72009-12-10 01:03:50 -08001463{
Eric Laurentb8453f42010-08-27 17:10:36 -07001464 checkOutputForStrategy(STRATEGY_PHONE);
1465 checkOutputForStrategy(STRATEGY_SONIFICATION);
1466 checkOutputForStrategy(STRATEGY_MEDIA);
1467 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurentcef3cd72009-12-10 01:03:50 -08001468}
1469
Eric Laurentb87b53d2010-11-02 12:02:20 -07001470void AudioPolicyManagerBase::checkA2dpSuspend()
1471{
1472 // suspend A2DP output if:
1473 // (NOT already suspended) &&
1474 // ((SCO device is connected &&
1475 // (forced usage for communication || for record is SCO))) ||
1476 // (phone state is ringing || in call)
1477 //
1478 // restore A2DP output if:
1479 // (Already suspended) &&
1480 // ((SCO device is NOT connected ||
1481 // (forced usage NOT for communication && NOT for record is SCO))) &&
1482 // (phone state is NOT ringing && NOT in call)
1483 //
1484 if (mA2dpOutput == 0) {
1485 return;
1486 }
1487
1488 if (mA2dpSuspended) {
1489 if (((mScoDeviceAddress == "") ||
1490 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
1491 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
1492 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
1493 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
1494
1495 mpClientInterface->restoreOutput(mA2dpOutput);
1496 mA2dpSuspended = false;
1497 }
1498 } else {
1499 if (((mScoDeviceAddress != "") &&
1500 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1501 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
1502 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
1503 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
1504
1505 mpClientInterface->suspendOutput(mA2dpOutput);
1506 mA2dpSuspended = true;
1507 }
1508 }
1509}
1510
1511
Eric Laurentcef3cd72009-12-10 01:03:50 -08001512#endif
1513
1514uint32_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
1515{
1516 uint32_t device = 0;
1517
1518 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1519 // check the following by order of priority to request a routing change if necessary:
1520 // 1: we are in call or the strategy phone is active on the hardware output:
1521 // use device for strategy phone
1522 // 2: the strategy sonification is active on the hardware output:
1523 // use device for strategy sonification
1524 // 3: the strategy media is active on the hardware output:
1525 // use device for strategy media
1526 // 4: the strategy DTMF is active on the hardware output:
1527 // use device for strategy DTMF
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08001528 if (isInCall() ||
Eric Laurentcef3cd72009-12-10 01:03:50 -08001529 outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
1530 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
1531 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
1532 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
1533 } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
1534 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
1535 } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
1536 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
1537 }
1538
1539 LOGV("getNewDevice() selected device %x", device);
1540 return device;
1541}
1542
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001543uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
1544 return (uint32_t)getStrategy(stream);
1545}
1546
Glenn Kasten8b4b97a2011-02-04 13:54:26 -08001547uint32_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
1548 uint32_t devices;
1549 // By checking the range of stream before calling getStrategy, we avoid
1550 // getStrategy's behavior for invalid streams. getStrategy would do a LOGE
1551 // and then return STRATEGY_MEDIA, but we want to return the empty set.
1552 if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
1553 devices = 0;
1554 } else {
1555 AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
1556 devices = getDeviceForStrategy(strategy, true);
1557 }
1558 return devices;
1559}
1560
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001561AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
1562 AudioSystem::stream_type stream) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001563 // stream to strategy mapping
1564 switch (stream) {
1565 case AudioSystem::VOICE_CALL:
1566 case AudioSystem::BLUETOOTH_SCO:
1567 return STRATEGY_PHONE;
1568 case AudioSystem::RING:
1569 case AudioSystem::NOTIFICATION:
1570 case AudioSystem::ALARM:
1571 case AudioSystem::ENFORCED_AUDIBLE:
1572 return STRATEGY_SONIFICATION;
1573 case AudioSystem::DTMF:
1574 return STRATEGY_DTMF;
1575 default:
1576 LOGE("unknown stream type");
1577 case AudioSystem::SYSTEM:
1578 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
1579 // while key clicks are played produces a poor result
1580 case AudioSystem::TTS:
1581 case AudioSystem::MUSIC:
1582 return STRATEGY_MEDIA;
1583 }
1584}
1585
1586uint32_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy, bool fromCache)
1587{
1588 uint32_t device = 0;
1589
1590 if (fromCache) {
1591 LOGV("getDeviceForStrategy() from cache strategy %d, device %x", strategy, mDeviceForStrategy[strategy]);
1592 return mDeviceForStrategy[strategy];
1593 }
1594
1595 switch (strategy) {
1596 case STRATEGY_DTMF:
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08001597 if (!isInCall()) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001598 // when off call, DTMF strategy follows the same rules as MEDIA strategy
1599 device = getDeviceForStrategy(STRATEGY_MEDIA, false);
1600 break;
1601 }
1602 // when in call, DTMF and PHONE strategies follow the same rules
1603 // FALL THROUGH
1604
1605 case STRATEGY_PHONE:
1606 // for phone strategy, we first consider the forced use and then the available devices by order
1607 // of priority
1608 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
1609 case AudioSystem::FORCE_BT_SCO:
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08001610 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001611 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
1612 if (device) break;
1613 }
1614 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
1615 if (device) break;
1616 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO;
1617 if (device) break;
1618 // if SCO device is requested but no SCO device is available, fall back to default case
1619 // FALL THROUGH
1620
1621 default: // FORCE_NONE
1622 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
1623 if (device) break;
1624 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1625 if (device) break;
Jean-Michel Trivie4b8c422010-03-13 12:33:15 -08001626#ifdef WITH_A2DP
1627 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurentbbc9fd32011-03-01 10:28:01 -08001628 if (!isInCall() && !mA2dpSuspended) {
Jean-Michel Trivie4b8c422010-03-13 12:33:15 -08001629 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1630 if (device) break;
1631 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1632 if (device) break;
1633 }
1634#endif
Eric Laurentee5d4b82011-02-11 10:29:06 -08001635 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1636 if (device) break;
1637 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1638 if (device) break;
1639 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1640 if (device) break;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001641 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_EARPIECE;
1642 if (device == 0) {
1643 LOGE("getDeviceForStrategy() earpiece device not found");
1644 }
1645 break;
1646
1647 case AudioSystem::FORCE_SPEAKER:
Jean-Michel Trivie4b8c422010-03-13 12:33:15 -08001648#ifdef WITH_A2DP
1649 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
1650 // A2DP speaker when forcing to speaker output
Eric Laurentbbc9fd32011-03-01 10:28:01 -08001651 if (!isInCall() && !mA2dpSuspended) {
Jean-Michel Trivie4b8c422010-03-13 12:33:15 -08001652 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1653 if (device) break;
1654 }
1655#endif
Eric Laurentee5d4b82011-02-11 10:29:06 -08001656 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1657 if (device) break;
1658 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1659 if (device) break;
1660 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1661 if (device) break;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001662 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1663 if (device == 0) {
1664 LOGE("getDeviceForStrategy() speaker device not found");
1665 }
1666 break;
1667 }
1668 break;
1669
1670 case STRATEGY_SONIFICATION:
1671
1672 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
1673 // handleIncallSonification().
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08001674 if (isInCall()) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001675 device = getDeviceForStrategy(STRATEGY_PHONE, false);
1676 break;
1677 }
1678 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1679 if (device == 0) {
1680 LOGE("getDeviceForStrategy() speaker device not found");
1681 }
1682 // The second device used for sonification is the same as the device used by media strategy
1683 // FALL THROUGH
1684
1685 case STRATEGY_MEDIA: {
Eric Laurent2c61bee2010-12-14 16:31:33 -08001686 uint32_t device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurentfe2e0752010-03-06 15:46:31 -08001687 if (device2 == 0) {
1688 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1689 }
Eric Laurentcef3cd72009-12-10 01:03:50 -08001690#ifdef WITH_A2DP
Eric Laurentbbc9fd32011-03-01 10:28:01 -08001691 if ((mA2dpOutput != 0) && !mA2dpSuspended &&
Eric Laurentee5d4b82011-02-11 10:29:06 -08001692 (strategy != STRATEGY_SONIFICATION || a2dpUsedForSonification())) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001693 if (device2 == 0) {
1694 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1695 }
1696 if (device2 == 0) {
1697 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1698 }
1699 if (device2 == 0) {
1700 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1701 }
1702 }
1703#endif
1704 if (device2 == 0) {
Eric Laurentee5d4b82011-02-11 10:29:06 -08001705 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1706 }
1707 if (device2 == 0) {
1708 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1709 }
1710 if (device2 == 0) {
1711 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1712 }
1713 if (device2 == 0) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001714 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1715 }
1716
1717 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION, 0 otherwise
1718 device |= device2;
1719 if (device == 0) {
1720 LOGE("getDeviceForStrategy() speaker device not found");
1721 }
1722 } break;
1723
1724 default:
1725 LOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
1726 break;
1727 }
1728
1729 LOGV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
1730 return device;
1731}
1732
1733void AudioPolicyManagerBase::updateDeviceForStrategy()
1734{
1735 for (int i = 0; i < NUM_STRATEGIES; i++) {
1736 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false);
1737 }
1738}
1739
1740void AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output, uint32_t device, bool force, int delayMs)
1741{
1742 LOGV("setOutputDevice() output %d device %x delayMs %d", output, device, delayMs);
1743 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1744
1745
1746 if (outputDesc->isDuplicated()) {
1747 setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
1748 setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
1749 return;
1750 }
1751#ifdef WITH_A2DP
1752 // filter devices according to output selected
Eric Laurentef9500f2010-03-11 14:47:00 -08001753 if (output == mA2dpOutput) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001754 device &= AudioSystem::DEVICE_OUT_ALL_A2DP;
Eric Laurentef9500f2010-03-11 14:47:00 -08001755 } else {
1756 device &= ~AudioSystem::DEVICE_OUT_ALL_A2DP;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001757 }
1758#endif
1759
1760 uint32_t prevDevice = (uint32_t)outputDesc->device();
1761 // Do not change the routing if:
1762 // - the requestede device is 0
1763 // - the requested device is the same as current device and force is not specified.
1764 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentef9500f2010-03-11 14:47:00 -08001765 if ((device == 0 || device == prevDevice) && !force) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001766 LOGV("setOutputDevice() setting same device %x or null device for output %d", device, output);
1767 return;
1768 }
1769
1770 outputDesc->mDevice = device;
1771 // mute media streams if both speaker and headset are selected
1772 if (output == mHardwareOutput && AudioSystem::popCount(device) == 2) {
1773 setStrategyMute(STRATEGY_MEDIA, true, output);
1774 // wait for the PCM output buffers to empty before proceeding with the rest of the command
1775 usleep(outputDesc->mLatency*2*1000);
1776 }
Eric Laurentb87b53d2010-11-02 12:02:20 -07001777
Eric Laurentcef3cd72009-12-10 01:03:50 -08001778 // do the routing
1779 AudioParameter param = AudioParameter();
1780 param.addInt(String8(AudioParameter::keyRouting), (int)device);
1781 mpClientInterface->setParameters(mHardwareOutput, param.toString(), delayMs);
1782 // update stream volumes according to new device
1783 applyStreamVolumes(output, device, delayMs);
1784
Eric Laurentcef3cd72009-12-10 01:03:50 -08001785 // if changing from a combined headset + speaker route, unmute media streams
1786 if (output == mHardwareOutput && AudioSystem::popCount(prevDevice) == 2) {
1787 setStrategyMute(STRATEGY_MEDIA, false, output, delayMs);
1788 }
1789}
1790
1791uint32_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
1792{
1793 uint32_t device;
1794
1795 switch(inputSource) {
1796 case AUDIO_SOURCE_DEFAULT:
1797 case AUDIO_SOURCE_MIC:
1798 case AUDIO_SOURCE_VOICE_RECOGNITION:
Jean-Michel Trivi820b9e02010-11-08 18:38:14 -08001799 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurentcef3cd72009-12-10 01:03:50 -08001800 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
1801 mAvailableInputDevices & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
1802 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
1803 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_WIRED_HEADSET) {
1804 device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
1805 } else {
1806 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1807 }
1808 break;
1809 case AUDIO_SOURCE_CAMCORDER:
1810 if (hasBackMicrophone()) {
1811 device = AudioSystem::DEVICE_IN_BACK_MIC;
1812 } else {
1813 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1814 }
1815 break;
1816 case AUDIO_SOURCE_VOICE_UPLINK:
1817 case AUDIO_SOURCE_VOICE_DOWNLINK:
1818 case AUDIO_SOURCE_VOICE_CALL:
1819 device = AudioSystem::DEVICE_IN_VOICE_CALL;
1820 break;
1821 default:
1822 LOGW("getInput() invalid input source %d", inputSource);
1823 device = 0;
1824 break;
1825 }
1826 LOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
1827 return device;
1828}
1829
1830audio_io_handle_t AudioPolicyManagerBase::getActiveInput()
1831{
1832 for (size_t i = 0; i < mInputs.size(); i++) {
1833 if (mInputs.valueAt(i)->mRefCount > 0) {
1834 return mInputs.keyAt(i);
1835 }
1836 }
1837 return 0;
1838}
1839
Jean-Michel Trivi3aab0582011-01-24 15:28:26 -08001840float AudioPolicyManagerBase::volIndexToAmpl(uint32_t device, const StreamDescriptor& streamDesc,
1841 int indexInUi) {
1842 // the volume index in the UI is relative to the min and max volume indices for this stream type
1843 int nbSteps = 1 + streamDesc.mVolIndex[StreamDescriptor::VOLMAX] -
1844 streamDesc.mVolIndex[StreamDescriptor::VOLMIN];
1845 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
1846 (streamDesc.mIndexMax - streamDesc.mIndexMin);
1847
1848 // find what part of the curve this index volume belongs to, or if it's out of bounds
1849 int segment = 0;
1850 if (volIdx < streamDesc.mVolIndex[StreamDescriptor::VOLMIN]) { // out of bounds
1851 return 0.0f;
1852 } else if (volIdx < streamDesc.mVolIndex[StreamDescriptor::VOLKNEE1]) {
1853 segment = 0;
1854 } else if (volIdx < streamDesc.mVolIndex[StreamDescriptor::VOLKNEE2]) {
1855 segment = 1;
1856 } else if (volIdx <= streamDesc.mVolIndex[StreamDescriptor::VOLMAX]) {
1857 segment = 2;
1858 } else { // out of bounds
1859 return 1.0f;
1860 }
1861
1862 // linear interpolation in the attenuation table in dB
1863 float decibels = streamDesc.mVolDbAtt[segment] +
1864 ((float)(volIdx - streamDesc.mVolIndex[segment])) *
1865 ( (streamDesc.mVolDbAtt[segment+1] - streamDesc.mVolDbAtt[segment]) /
1866 ((float)(streamDesc.mVolIndex[segment+1] - streamDesc.mVolIndex[segment])) );
1867
1868 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
1869
1870 LOGV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
1871 streamDesc.mVolIndex[segment], volIdx, streamDesc.mVolIndex[segment+1],
1872 streamDesc.mVolDbAtt[segment], decibels, streamDesc.mVolDbAtt[segment+1],
1873 amplification);
1874
1875 return amplification;
1876}
1877
1878void AudioPolicyManagerBase::initializeVolumeCurves() {
1879 // initialize the volume curves to a (-49.5 - 0 dB) attenuation in 0.5dB steps
1880 for (int i=0 ; i< AudioSystem::NUM_STREAM_TYPES ; i++) {
1881 mStreams[i].mVolIndex[StreamDescriptor::VOLMIN] = 1;
1882 mStreams[i].mVolDbAtt[StreamDescriptor::VOLMIN] = -49.5f;
1883 mStreams[i].mVolIndex[StreamDescriptor::VOLKNEE1] = 33;
1884 mStreams[i].mVolDbAtt[StreamDescriptor::VOLKNEE1] = -33.5f;
1885 mStreams[i].mVolIndex[StreamDescriptor::VOLKNEE2] = 66;
1886 mStreams[i].mVolDbAtt[StreamDescriptor::VOLKNEE2] = -17.0f;
1887 // here we use 100 steps to avoid rounding errors
1888 // when computing the volume in volIndexToAmpl()
1889 mStreams[i].mVolIndex[StreamDescriptor::VOLMAX] = 100;
1890 mStreams[i].mVolDbAtt[StreamDescriptor::VOLMAX] = 0.0f;
1891 }
1892
Jean-Michel Trivi191ff0922011-02-27 16:41:21 -08001893 // Modification for music: more attenuation for lower volumes, finer steps at high volumes
1894 mStreams[AudioSystem::MUSIC].mVolIndex[StreamDescriptor::VOLMIN] = 1;
1895 mStreams[AudioSystem::MUSIC].mVolDbAtt[StreamDescriptor::VOLMIN] = -58.0f;
1896 mStreams[AudioSystem::MUSIC].mVolIndex[StreamDescriptor::VOLKNEE1] = 20;
1897 mStreams[AudioSystem::MUSIC].mVolDbAtt[StreamDescriptor::VOLKNEE1] = -40.0f;
1898 mStreams[AudioSystem::MUSIC].mVolIndex[StreamDescriptor::VOLKNEE2] = 60;
1899 mStreams[AudioSystem::MUSIC].mVolDbAtt[StreamDescriptor::VOLKNEE2] = -17.0f;
1900 mStreams[AudioSystem::MUSIC].mVolIndex[StreamDescriptor::VOLMAX] = 100;
1901 mStreams[AudioSystem::MUSIC].mVolDbAtt[StreamDescriptor::VOLMAX] = 0.0f;
Jean-Michel Trivi3aab0582011-01-24 15:28:26 -08001902}
1903
Eric Laurentcef3cd72009-12-10 01:03:50 -08001904float AudioPolicyManagerBase::computeVolume(int stream, int index, audio_io_handle_t output, uint32_t device)
1905{
1906 float volume = 1.0;
1907 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1908 StreamDescriptor &streamDesc = mStreams[stream];
1909
1910 if (device == 0) {
1911 device = outputDesc->device();
1912 }
1913
Eric Laurent223995d2011-04-25 13:34:51 -07001914 // if volume is not 0 (not muted), force media volume to max on digital output
1915 if (stream == AudioSystem::MUSIC &&
1916 index != mStreams[stream].mIndexMin &&
1917 device == AudioSystem::DEVICE_OUT_AUX_DIGITAL) {
1918 return 1.0;
1919 }
1920
Jean-Michel Trivi3aab0582011-01-24 15:28:26 -08001921 volume = volIndexToAmpl(device, streamDesc, index);
Eric Laurentcef3cd72009-12-10 01:03:50 -08001922
Eric Laurentef9500f2010-03-11 14:47:00 -08001923 // if a headset is connected, apply the following rules to ring tones and notifications
Eric Laurentcef3cd72009-12-10 01:03:50 -08001924 // to avoid sound level bursts in user's ears:
1925 // - always attenuate ring tones and notifications volume by 6dB
1926 // - if music is playing, always limit the volume to current music volume,
1927 // with a minimum threshold at -36dB so that notification is always perceived.
1928 if ((device &
1929 (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP |
1930 AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
1931 AudioSystem::DEVICE_OUT_WIRED_HEADSET |
Eric Laurentee5d4b82011-02-11 10:29:06 -08001932 AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) &&
Eric Laurent111df672011-01-27 11:32:34 -08001933 ((getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) ||
1934 (stream == AudioSystem::SYSTEM)) &&
Eric Laurentcef3cd72009-12-10 01:03:50 -08001935 streamDesc.mCanBeMuted) {
1936 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
1937 // when the phone is ringing we must consider that music could have been paused just before
1938 // by the music application and behave as if music was active if the last music track was
1939 // just stopped
1940 if (outputDesc->mRefCount[AudioSystem::MUSIC] || mLimitRingtoneVolume) {
1941 float musicVol = computeVolume(AudioSystem::MUSIC, mStreams[AudioSystem::MUSIC].mIndexCur, output, device);
1942 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ? musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
1943 if (volume > minVol) {
1944 volume = minVol;
1945 LOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
1946 }
1947 }
1948 }
1949
1950 return volume;
1951}
1952
1953status_t AudioPolicyManagerBase::checkAndSetVolume(int stream, int index, audio_io_handle_t output, uint32_t device, int delayMs, bool force)
1954{
1955
1956 // do not change actual stream volume if the stream is muted
1957 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
1958 LOGV("checkAndSetVolume() stream %d muted count %d", stream, mOutputs.valueFor(output)->mMuteCount[stream]);
1959 return NO_ERROR;
1960 }
1961
1962 // do not change in call volume if bluetooth is connected and vice versa
1963 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1964 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
1965 LOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
1966 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
1967 return INVALID_OPERATION;
1968 }
1969
1970 float volume = computeVolume(stream, index, output, device);
Eric Laurentcc9c4242010-05-25 09:31:59 -07001971 // We actually change the volume if:
1972 // - the float value returned by computeVolume() changed
1973 // - the force flag is set
1974 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
1975 force) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001976 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
1977 LOGV("setStreamVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
1978 if (stream == AudioSystem::VOICE_CALL ||
1979 stream == AudioSystem::DTMF ||
1980 stream == AudioSystem::BLUETOOTH_SCO) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001981 // offset value to reflect actual hardware volume that never reaches 0
1982 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
1983 volume = 0.01 + 0.99 * volume;
Eric Laurent257b2d02011-03-15 14:26:03 -07001984 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
1985 // enabled
1986 if (stream == AudioSystem::BLUETOOTH_SCO) {
1987 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
1988 }
Eric Laurentcef3cd72009-12-10 01:03:50 -08001989 }
Eric Laurent257b2d02011-03-15 14:26:03 -07001990
Eric Laurentcef3cd72009-12-10 01:03:50 -08001991 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
1992 }
1993
Eric Laurentcc9c4242010-05-25 09:31:59 -07001994 if (stream == AudioSystem::VOICE_CALL ||
1995 stream == AudioSystem::BLUETOOTH_SCO) {
1996 float voiceVolume;
1997 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
1998 if (stream == AudioSystem::VOICE_CALL) {
1999 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
2000 } else {
2001 voiceVolume = 1.0;
2002 }
Eric Laurent257b2d02011-03-15 14:26:03 -07002003
Eric Laurentcc9c4242010-05-25 09:31:59 -07002004 if (voiceVolume != mLastVoiceVolume && output == mHardwareOutput) {
2005 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
2006 mLastVoiceVolume = voiceVolume;
2007 }
2008 }
2009
Eric Laurentcef3cd72009-12-10 01:03:50 -08002010 return NO_ERROR;
2011}
2012
Eric Laurent257b2d02011-03-15 14:26:03 -07002013void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output, uint32_t device, int delayMs, bool force)
Eric Laurentcef3cd72009-12-10 01:03:50 -08002014{
2015 LOGV("applyStreamVolumes() for output %d and device %x", output, device);
2016
2017 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
Eric Laurent257b2d02011-03-15 14:26:03 -07002018 checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, device, delayMs, force);
Eric Laurentcef3cd72009-12-10 01:03:50 -08002019 }
2020}
2021
2022void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy, bool on, audio_io_handle_t output, int delayMs)
2023{
2024 LOGV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
2025 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2026 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
2027 setStreamMute(stream, on, output, delayMs);
2028 }
2029 }
2030}
2031
2032void AudioPolicyManagerBase::setStreamMute(int stream, bool on, audio_io_handle_t output, int delayMs)
2033{
2034 StreamDescriptor &streamDesc = mStreams[stream];
2035 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2036
2037 LOGV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d", stream, on, output, outputDesc->mMuteCount[stream]);
2038
2039 if (on) {
2040 if (outputDesc->mMuteCount[stream] == 0) {
2041 if (streamDesc.mCanBeMuted) {
2042 checkAndSetVolume(stream, 0, output, outputDesc->device(), delayMs);
2043 }
2044 }
2045 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
2046 outputDesc->mMuteCount[stream]++;
2047 } else {
2048 if (outputDesc->mMuteCount[stream] == 0) {
2049 LOGW("setStreamMute() unmuting non muted stream!");
2050 return;
2051 }
2052 if (--outputDesc->mMuteCount[stream] == 0) {
2053 checkAndSetVolume(stream, streamDesc.mIndexCur, output, outputDesc->device(), delayMs);
2054 }
2055 }
2056}
2057
2058void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
2059{
2060 // if the stream pertains to sonification strategy and we are in call we must
2061 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
2062 // in the device used for phone strategy and play the tone if the selected device does not
2063 // interfere with the device used for phone strategy
2064 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
2065 // many times as there are active tracks on the output
2066
2067 if (getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) {
2068 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mHardwareOutput);
2069 LOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
2070 stream, starting, outputDesc->mDevice, stateChange);
2071 if (outputDesc->mRefCount[stream]) {
2072 int muteCount = 1;
2073 if (stateChange) {
2074 muteCount = outputDesc->mRefCount[stream];
2075 }
2076 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
2077 LOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
2078 for (int i = 0; i < muteCount; i++) {
2079 setStreamMute(stream, starting, mHardwareOutput);
2080 }
2081 } else {
2082 LOGV("handleIncallSonification() high visibility");
2083 if (outputDesc->device() & getDeviceForStrategy(STRATEGY_PHONE)) {
2084 LOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
2085 for (int i = 0; i < muteCount; i++) {
2086 setStreamMute(stream, starting, mHardwareOutput);
2087 }
2088 }
2089 if (starting) {
2090 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
2091 } else {
2092 mpClientInterface->stopTone();
2093 }
2094 }
2095 }
2096 }
2097}
2098
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08002099bool AudioPolicyManagerBase::isInCall()
2100{
2101 return isStateInCall(mPhoneState);
2102}
2103
2104bool AudioPolicyManagerBase::isStateInCall(int state) {
2105 return ((state == AudioSystem::MODE_IN_CALL) ||
2106 (state == AudioSystem::MODE_IN_COMMUNICATION));
2107}
2108
Eric Laurentef9500f2010-03-11 14:47:00 -08002109bool AudioPolicyManagerBase::needsDirectOuput(AudioSystem::stream_type stream,
2110 uint32_t samplingRate,
2111 uint32_t format,
2112 uint32_t channels,
2113 AudioSystem::output_flags flags,
2114 uint32_t device)
2115{
2116 return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
2117 (format !=0 && !AudioSystem::isLinearPCM(format)));
2118}
2119
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002120uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
2121{
2122 return MAX_EFFECTS_CPU_LOAD;
2123}
2124
2125uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
2126{
2127 return MAX_EFFECTS_MEMORY;
2128}
2129
Eric Laurentcef3cd72009-12-10 01:03:50 -08002130// --- AudioOutputDescriptor class implementation
2131
2132AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor()
2133 : mId(0), mSamplingRate(0), mFormat(0), mChannels(0), mLatency(0),
2134 mFlags((AudioSystem::output_flags)0), mDevice(0), mOutput1(0), mOutput2(0)
2135{
2136 // clear usage count for all stream types
2137 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2138 mRefCount[i] = 0;
2139 mCurVolume[i] = -1.0;
2140 mMuteCount[i] = 0;
Eric Laurent25101b02011-02-02 09:33:30 -08002141 mStopTime[i] = 0;
Eric Laurentcef3cd72009-12-10 01:03:50 -08002142 }
2143}
2144
2145uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::device()
2146{
2147 uint32_t device = 0;
2148 if (isDuplicated()) {
2149 device = mOutput1->mDevice | mOutput2->mDevice;
2150 } else {
2151 device = mDevice;
2152 }
2153 return device;
2154}
2155
2156void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
2157{
2158 // forward usage count change to attached outputs
2159 if (isDuplicated()) {
2160 mOutput1->changeRefCount(stream, delta);
2161 mOutput2->changeRefCount(stream, delta);
2162 }
2163 if ((delta + (int)mRefCount[stream]) < 0) {
2164 LOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
2165 mRefCount[stream] = 0;
2166 return;
2167 }
2168 mRefCount[stream] += delta;
2169 LOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
2170}
2171
2172uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount()
2173{
2174 uint32_t refcount = 0;
2175 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2176 refcount += mRefCount[i];
2177 }
2178 return refcount;
2179}
2180
2181uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy)
2182{
2183 uint32_t refCount = 0;
2184 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2185 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2186 refCount += mRefCount[i];
2187 }
2188 }
2189 return refCount;
2190}
2191
Eric Laurentcef3cd72009-12-10 01:03:50 -08002192status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
2193{
2194 const size_t SIZE = 256;
2195 char buffer[SIZE];
2196 String8 result;
2197
2198 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2199 result.append(buffer);
2200 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2201 result.append(buffer);
2202 snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
2203 result.append(buffer);
2204 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
2205 result.append(buffer);
2206 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
2207 result.append(buffer);
2208 snprintf(buffer, SIZE, " Devices %08x\n", device());
2209 result.append(buffer);
2210 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
2211 result.append(buffer);
2212 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2213 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
2214 result.append(buffer);
2215 }
2216 write(fd, result.string(), result.size());
2217
2218 return NO_ERROR;
2219}
2220
2221// --- AudioInputDescriptor class implementation
2222
2223AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor()
2224 : mSamplingRate(0), mFormat(0), mChannels(0),
2225 mAcoustics((AudioSystem::audio_in_acoustics)0), mDevice(0), mRefCount(0)
2226{
2227}
2228
2229status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
2230{
2231 const size_t SIZE = 256;
2232 char buffer[SIZE];
2233 String8 result;
2234
2235 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2236 result.append(buffer);
2237 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2238 result.append(buffer);
2239 snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
2240 result.append(buffer);
2241 snprintf(buffer, SIZE, " Acoustics %08x\n", mAcoustics);
2242 result.append(buffer);
2243 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
2244 result.append(buffer);
2245 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
2246 result.append(buffer);
2247 write(fd, result.string(), result.size());
2248
2249 return NO_ERROR;
2250}
2251
2252// --- StreamDescriptor class implementation
2253
2254void AudioPolicyManagerBase::StreamDescriptor::dump(char* buffer, size_t size)
2255{
2256 snprintf(buffer, size, " %02d %02d %02d %d\n",
2257 mIndexMin,
2258 mIndexMax,
2259 mIndexCur,
2260 mCanBeMuted);
2261}
2262
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002263// --- EffectDescriptor class implementation
2264
2265status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
2266{
2267 const size_t SIZE = 256;
2268 char buffer[SIZE];
2269 String8 result;
2270
2271 snprintf(buffer, SIZE, " Output: %d\n", mOutput);
2272 result.append(buffer);
2273 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
2274 result.append(buffer);
2275 snprintf(buffer, SIZE, " Session: %d\n", mSession);
2276 result.append(buffer);
2277 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
2278 result.append(buffer);
2279 write(fd, result.string(), result.size());
2280
2281 return NO_ERROR;
2282}
2283
2284
Eric Laurentcef3cd72009-12-10 01:03:50 -08002285
2286}; // namespace android