blob: 18abc0b15844ae0233aebaf76787840e03d425ec [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 Laurentb8453f42010-08-27 17:10:36 -0700125 checkOutputForAllStrategies();
Eric Laurentcef3cd72009-12-10 01:03:50 -0800126 // A2DP outputs must be closed after checkOutputForAllStrategies() is executed
127 if (state == AudioSystem::DEVICE_STATE_UNAVAILABLE && AudioSystem::isA2dpDevice(device)) {
128 closeA2dpOutputs();
129 }
Eric Laurentb87b53d2010-11-02 12:02:20 -0700130 checkA2dpSuspend();
Eric Laurentcef3cd72009-12-10 01:03:50 -0800131#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 Laurentb8453f42010-08-27 17:10:36 -0700272 checkOutputForAllStrategies();
Eric Laurentb87b53d2010-11-02 12:02:20 -0700273 checkA2dpSuspend();
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 &&
316 (hwOutputDesc->mRefCount[AudioSystem::MUSIC] ||
317 (systemTime() - mMusicStopTime) < seconds(SONIFICATION_HEADSET_MUSIC_DELAY))) {
318 mLimitRingtoneVolume = true;
319 } else {
320 mLimitRingtoneVolume = false;
321 }
322}
323
324void AudioPolicyManagerBase::setRingerMode(uint32_t mode, uint32_t mask)
325{
326 LOGV("setRingerMode() mode %x, mask %x", mode, mask);
327
328 mRingerMode = mode;
329}
330
331void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
332{
333 LOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
334
Jean-Michel Trivi758559e2010-03-09 09:26:08 -0800335 bool forceVolumeReeval = false;
Eric Laurentcef3cd72009-12-10 01:03:50 -0800336 switch(usage) {
337 case AudioSystem::FOR_COMMUNICATION:
338 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
339 config != AudioSystem::FORCE_NONE) {
340 LOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
341 return;
342 }
343 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 Laurentb8453f42010-08-27 17:10:36 -0700382 checkOutputForAllStrategies();
Eric Laurentb87b53d2010-11-02 12:02:20 -0700383 checkA2dpSuspend();
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) {
388 applyStreamVolumes(mHardwareOutput, newDevice);
389 }
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 Laurentcef3cd72009-12-10 01:03:50 -0800482 output = mpClientInterface->openOutput(&outputDesc->mDevice,
483 &outputDesc->mSamplingRate,
484 &outputDesc->mFormat,
485 &outputDesc->mChannels,
486 &outputDesc->mLatency,
487 outputDesc->mFlags);
488
489 // only accept an output with the requeted parameters
490 if (output == 0 ||
491 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
492 (format != 0 && format != outputDesc->mFormat) ||
493 (channels != 0 && channels != outputDesc->mChannels)) {
494 LOGV("getOutput() failed opening direct output: samplingRate %d, format %d, channels %d",
495 samplingRate, format, channels);
496 if (output != 0) {
497 mpClientInterface->closeOutput(output);
498 }
499 delete outputDesc;
500 return 0;
501 }
502 addOutput(output, outputDesc);
503 return output;
504 }
505
506 if (channels != 0 && channels != AudioSystem::CHANNEL_OUT_MONO &&
507 channels != AudioSystem::CHANNEL_OUT_STEREO) {
508 return 0;
509 }
510 // open a non direct output
511
512 // get which output is suitable for the specified stream. The actual routing change will happen
513 // when startOutput() will be called
514 uint32_t a2dpDevice = device & AudioSystem::DEVICE_OUT_ALL_A2DP;
515 if (AudioSystem::popCount((AudioSystem::audio_devices)device) == 2) {
516#ifdef WITH_A2DP
517 if (a2dpUsedForSonification() && a2dpDevice != 0) {
518 // if playing on 2 devices among which one is A2DP, use duplicated output
519 LOGV("getOutput() using duplicated output");
520 LOGW_IF((mA2dpOutput == 0), "getOutput() A2DP device in multiple %x selected but A2DP output not opened", device);
521 output = mDuplicatedOutput;
522 } else
523#endif
524 {
525 // if playing on 2 devices among which none is A2DP, use hardware output
526 output = mHardwareOutput;
527 }
528 LOGV("getOutput() using output %d for 2 devices %x", output, device);
529 } else {
530#ifdef WITH_A2DP
531 if (a2dpDevice != 0) {
532 // if playing on A2DP device, use a2dp output
533 LOGW_IF((mA2dpOutput == 0), "getOutput() A2DP device %x selected but A2DP output not opened", device);
534 output = mA2dpOutput;
535 } else
536#endif
537 {
538 // if playing on not A2DP device, use hardware output
539 output = mHardwareOutput;
540 }
541 }
542
543
544 LOGW_IF((output ==0), "getOutput() could not find output for stream %d, samplingRate %d, format %d, channels %x, flags %x",
545 stream, samplingRate, format, channels, flags);
546
547 return output;
548}
549
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700550status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
551 AudioSystem::stream_type stream,
552 int session)
Eric Laurentcef3cd72009-12-10 01:03:50 -0800553{
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700554 LOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
Eric Laurentcef3cd72009-12-10 01:03:50 -0800555 ssize_t index = mOutputs.indexOfKey(output);
556 if (index < 0) {
557 LOGW("startOutput() unknow output %d", output);
558 return BAD_VALUE;
559 }
560
561 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
562 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
563
564#ifdef WITH_A2DP
565 if (mA2dpOutput != 0 && !a2dpUsedForSonification() && strategy == STRATEGY_SONIFICATION) {
566 setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput);
567 }
568#endif
569
570 // incremenent usage count for this stream on the requested output:
571 // NOTE that the usage count is the same for duplicated output and hardware output which is
572 // necassary for a correct control of hardware output routing by startOutput() and stopOutput()
573 outputDesc->changeRefCount(stream, 1);
574
575 setOutputDevice(output, getNewDevice(output));
576
577 // handle special case for sonification while in call
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -0800578 if (isInCall()) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800579 handleIncallSonification(stream, true, false);
580 }
581
582 // apply volume rules for current stream and device if necessary
583 checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, outputDesc->device());
584
585 return NO_ERROR;
586}
587
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700588status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
589 AudioSystem::stream_type stream,
590 int session)
Eric Laurentcef3cd72009-12-10 01:03:50 -0800591{
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700592 LOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
Eric Laurentcef3cd72009-12-10 01:03:50 -0800593 ssize_t index = mOutputs.indexOfKey(output);
594 if (index < 0) {
595 LOGW("stopOutput() unknow output %d", output);
596 return BAD_VALUE;
597 }
598
599 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
600 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
601
602 // handle special case for sonification while in call
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -0800603 if (isInCall()) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800604 handleIncallSonification(stream, false, false);
605 }
606
607 if (outputDesc->mRefCount[stream] > 0) {
608 // decrement usage count of this stream on the output
609 outputDesc->changeRefCount(stream, -1);
610 // store time at which the last music track was stopped - see computeVolume()
611 if (stream == AudioSystem::MUSIC) {
612 mMusicStopTime = systemTime();
613 }
614
615 setOutputDevice(output, getNewDevice(output));
616
617#ifdef WITH_A2DP
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700618 if (mA2dpOutput != 0 && !a2dpUsedForSonification() &&
619 strategy == STRATEGY_SONIFICATION) {
620 setStrategyMute(STRATEGY_MEDIA,
621 false,
622 mA2dpOutput,
623 mOutputs.valueFor(mHardwareOutput)->mLatency*2);
Eric Laurentcef3cd72009-12-10 01:03:50 -0800624 }
625#endif
Eric Laurentef9500f2010-03-11 14:47:00 -0800626 if (output != mHardwareOutput) {
627 setOutputDevice(mHardwareOutput, getNewDevice(mHardwareOutput), true);
628 }
Eric Laurentcef3cd72009-12-10 01:03:50 -0800629 return NO_ERROR;
630 } else {
631 LOGW("stopOutput() refcount is already 0 for output %d", output);
632 return INVALID_OPERATION;
633 }
634}
635
636void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
637{
638 LOGV("releaseOutput() %d", output);
639 ssize_t index = mOutputs.indexOfKey(output);
640 if (index < 0) {
641 LOGW("releaseOutput() releasing unknown output %d", output);
642 return;
643 }
644
645#ifdef AUDIO_POLICY_TEST
646 int testIndex = testOutputIndex(output);
647 if (testIndex != 0) {
648 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
649 if (outputDesc->refCount() == 0) {
650 mpClientInterface->closeOutput(output);
651 delete mOutputs.valueAt(index);
652 mOutputs.removeItem(output);
653 mTestOutputs[testIndex] = 0;
654 }
655 return;
656 }
657#endif //AUDIO_POLICY_TEST
658
659 if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
660 mpClientInterface->closeOutput(output);
661 delete mOutputs.valueAt(index);
662 mOutputs.removeItem(output);
663 }
664}
665
666audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
667 uint32_t samplingRate,
668 uint32_t format,
669 uint32_t channels,
670 AudioSystem::audio_in_acoustics acoustics)
671{
672 audio_io_handle_t input = 0;
673 uint32_t device = getDeviceForInputSource(inputSource);
674
675 LOGV("getInput() inputSource %d, samplingRate %d, format %d, channels %x, acoustics %x", inputSource, samplingRate, format, channels, acoustics);
676
677 if (device == 0) {
678 return 0;
679 }
680
681 // adapt channel selection to input source
682 switch(inputSource) {
683 case AUDIO_SOURCE_VOICE_UPLINK:
684 channels = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
685 break;
686 case AUDIO_SOURCE_VOICE_DOWNLINK:
687 channels = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
688 break;
689 case AUDIO_SOURCE_VOICE_CALL:
690 channels = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
691 break;
692 default:
693 break;
694 }
695
696 AudioInputDescriptor *inputDesc = new AudioInputDescriptor();
697
698 inputDesc->mInputSource = inputSource;
699 inputDesc->mDevice = device;
700 inputDesc->mSamplingRate = samplingRate;
701 inputDesc->mFormat = format;
702 inputDesc->mChannels = channels;
703 inputDesc->mAcoustics = acoustics;
704 inputDesc->mRefCount = 0;
705 input = mpClientInterface->openInput(&inputDesc->mDevice,
706 &inputDesc->mSamplingRate,
707 &inputDesc->mFormat,
708 &inputDesc->mChannels,
709 inputDesc->mAcoustics);
710
711 // only accept input with the exact requested set of parameters
712 if (input == 0 ||
713 (samplingRate != inputDesc->mSamplingRate) ||
714 (format != inputDesc->mFormat) ||
715 (channels != inputDesc->mChannels)) {
716 LOGV("getInput() failed opening input: samplingRate %d, format %d, channels %d",
717 samplingRate, format, channels);
718 if (input != 0) {
719 mpClientInterface->closeInput(input);
720 }
721 delete inputDesc;
722 return 0;
723 }
724 mInputs.add(input, inputDesc);
725 return input;
726}
727
728status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
729{
730 LOGV("startInput() input %d", input);
731 ssize_t index = mInputs.indexOfKey(input);
732 if (index < 0) {
733 LOGW("startInput() unknow input %d", input);
734 return BAD_VALUE;
735 }
736 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
737
738#ifdef AUDIO_POLICY_TEST
739 if (mTestInput == 0)
740#endif //AUDIO_POLICY_TEST
741 {
742 // refuse 2 active AudioRecord clients at the same time
743 if (getActiveInput() != 0) {
744 LOGW("startInput() input %d failed: other input already started", input);
745 return INVALID_OPERATION;
746 }
747 }
748
749 AudioParameter param = AudioParameter();
750 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
751
Jean-Michel Trivi1a22bdb2010-11-09 14:06:52 -0800752 param.addInt(String8(AudioParameter::keyInputSource), (int)inputDesc->mInputSource);
753 LOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
Eric Laurentcef3cd72009-12-10 01:03:50 -0800754
755 mpClientInterface->setParameters(input, param.toString());
756
757 inputDesc->mRefCount = 1;
758 return NO_ERROR;
759}
760
761status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
762{
763 LOGV("stopInput() input %d", input);
764 ssize_t index = mInputs.indexOfKey(input);
765 if (index < 0) {
766 LOGW("stopInput() unknow input %d", input);
767 return BAD_VALUE;
768 }
769 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
770
771 if (inputDesc->mRefCount == 0) {
772 LOGW("stopInput() input %d already stopped", input);
773 return INVALID_OPERATION;
774 } else {
775 AudioParameter param = AudioParameter();
776 param.addInt(String8(AudioParameter::keyRouting), 0);
777 mpClientInterface->setParameters(input, param.toString());
778 inputDesc->mRefCount = 0;
779 return NO_ERROR;
780 }
781}
782
783void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
784{
785 LOGV("releaseInput() %d", input);
786 ssize_t index = mInputs.indexOfKey(input);
787 if (index < 0) {
788 LOGW("releaseInput() releasing unknown input %d", input);
789 return;
790 }
791 mpClientInterface->closeInput(input);
792 delete mInputs.valueAt(index);
793 mInputs.removeItem(input);
794 LOGV("releaseInput() exit");
795}
796
797void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
798 int indexMin,
799 int indexMax)
800{
801 LOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
802 if (indexMin < 0 || indexMin >= indexMax) {
803 LOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
804 return;
805 }
806 mStreams[stream].mIndexMin = indexMin;
807 mStreams[stream].mIndexMax = indexMax;
808}
809
810status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream, int index)
811{
812
813 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
814 return BAD_VALUE;
815 }
816
817 // Force max volume if stream cannot be muted
818 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
819
820 LOGV("setStreamVolumeIndex() stream %d, index %d", stream, index);
821 mStreams[stream].mIndexCur = index;
822
823 // compute and apply stream volume on all outputs according to connected device
824 status_t status = NO_ERROR;
825 for (size_t i = 0; i < mOutputs.size(); i++) {
826 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), mOutputs.valueAt(i)->device());
827 if (volStatus != NO_ERROR) {
828 status = volStatus;
829 }
830 }
831 return status;
832}
833
834status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream, int *index)
835{
836 if (index == 0) {
837 return BAD_VALUE;
838 }
839 LOGV("getStreamVolumeIndex() stream %d", stream);
840 *index = mStreams[stream].mIndexCur;
841 return NO_ERROR;
842}
843
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700844audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(effect_descriptor_t *desc)
845{
846 LOGV("getOutputForEffect()");
847 // apply simple rule where global effects are attached to the same output as MUSIC streams
848 return getOutput(AudioSystem::MUSIC);
849}
850
851status_t AudioPolicyManagerBase::registerEffect(effect_descriptor_t *desc,
852 audio_io_handle_t output,
853 uint32_t strategy,
854 int session,
855 int id)
856{
857 ssize_t index = mOutputs.indexOfKey(output);
858 if (index < 0) {
859 LOGW("registerEffect() unknown output %d", output);
860 return INVALID_OPERATION;
861 }
862
863 if (mTotalEffectsCpuLoad + desc->cpuLoad > getMaxEffectsCpuLoad()) {
864 LOGW("registerEffect() CPU Load limit exceeded for Fx %s, CPU %f MIPS",
865 desc->name, (float)desc->cpuLoad/10);
866 return INVALID_OPERATION;
867 }
868 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
869 LOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
870 desc->name, desc->memoryUsage);
871 return INVALID_OPERATION;
872 }
873 mTotalEffectsCpuLoad += desc->cpuLoad;
874 mTotalEffectsMemory += desc->memoryUsage;
875 LOGV("registerEffect() effect %s, output %d, strategy %d session %d id %d",
876 desc->name, output, strategy, session, id);
877
878 LOGV("registerEffect() CPU %d, memory %d", desc->cpuLoad, desc->memoryUsage);
879 LOGV(" total CPU %d, total memory %d", mTotalEffectsCpuLoad, mTotalEffectsMemory);
880
881 EffectDescriptor *pDesc = new EffectDescriptor();
882 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
883 pDesc->mOutput = output;
884 pDesc->mStrategy = (routing_strategy)strategy;
885 pDesc->mSession = session;
886 mEffects.add(id, pDesc);
887
888 return NO_ERROR;
889}
890
891status_t AudioPolicyManagerBase::unregisterEffect(int id)
892{
893 ssize_t index = mEffects.indexOfKey(id);
894 if (index < 0) {
895 LOGW("unregisterEffect() unknown effect ID %d", id);
896 return INVALID_OPERATION;
897 }
898
899 EffectDescriptor *pDesc = mEffects.valueAt(index);
900
901 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
902 LOGW("unregisterEffect() CPU load %d too high for total %d",
903 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
904 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
905 }
906 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
907 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
908 LOGW("unregisterEffect() memory %d too big for total %d",
909 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
910 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
911 }
912 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
913 LOGV("unregisterEffect() effect %s, ID %d, CPU %d, memory %d",
914 pDesc->mDesc.name, id, pDesc->mDesc.cpuLoad, pDesc->mDesc.memoryUsage);
915 LOGV(" total CPU %d, total memory %d", mTotalEffectsCpuLoad, mTotalEffectsMemory);
916
917 mEffects.removeItem(id);
918 delete pDesc;
919
920 return NO_ERROR;
921}
922
Eric Laurentcef3cd72009-12-10 01:03:50 -0800923status_t AudioPolicyManagerBase::dump(int fd)
924{
925 const size_t SIZE = 256;
926 char buffer[SIZE];
927 String8 result;
928
929 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
930 result.append(buffer);
931 snprintf(buffer, SIZE, " Hardware Output: %d\n", mHardwareOutput);
932 result.append(buffer);
933#ifdef WITH_A2DP
934 snprintf(buffer, SIZE, " A2DP Output: %d\n", mA2dpOutput);
935 result.append(buffer);
936 snprintf(buffer, SIZE, " Duplicated Output: %d\n", mDuplicatedOutput);
937 result.append(buffer);
938 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
939 result.append(buffer);
940#endif
941 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
942 result.append(buffer);
943 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
944 result.append(buffer);
945 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
946 result.append(buffer);
947 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
948 result.append(buffer);
949 snprintf(buffer, SIZE, " Ringer mode: %d\n", mRingerMode);
950 result.append(buffer);
951 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
952 result.append(buffer);
953 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
954 result.append(buffer);
955 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
956 result.append(buffer);
957 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
958 result.append(buffer);
959 write(fd, result.string(), result.size());
960
961 snprintf(buffer, SIZE, "\nOutputs dump:\n");
962 write(fd, buffer, strlen(buffer));
963 for (size_t i = 0; i < mOutputs.size(); i++) {
964 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
965 write(fd, buffer, strlen(buffer));
966 mOutputs.valueAt(i)->dump(fd);
967 }
968
969 snprintf(buffer, SIZE, "\nInputs dump:\n");
970 write(fd, buffer, strlen(buffer));
971 for (size_t i = 0; i < mInputs.size(); i++) {
972 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
973 write(fd, buffer, strlen(buffer));
974 mInputs.valueAt(i)->dump(fd);
975 }
976
977 snprintf(buffer, SIZE, "\nStreams dump:\n");
978 write(fd, buffer, strlen(buffer));
979 snprintf(buffer, SIZE, " Stream Index Min Index Max Index Cur Can be muted\n");
980 write(fd, buffer, strlen(buffer));
981 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
982 snprintf(buffer, SIZE, " %02d", i);
983 mStreams[i].dump(buffer + 3, SIZE);
984 write(fd, buffer, strlen(buffer));
985 }
986
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700987 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
988 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
989 write(fd, buffer, strlen(buffer));
990
991 snprintf(buffer, SIZE, "Registered effects:\n");
992 write(fd, buffer, strlen(buffer));
993 for (size_t i = 0; i < mEffects.size(); i++) {
994 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
995 write(fd, buffer, strlen(buffer));
996 mEffects.valueAt(i)->dump(fd);
997 }
998
999
Eric Laurentcef3cd72009-12-10 01:03:50 -08001000 return NO_ERROR;
1001}
1002
1003// ----------------------------------------------------------------------------
1004// AudioPolicyManagerBase
1005// ----------------------------------------------------------------------------
1006
1007AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1008 :
1009#ifdef AUDIO_POLICY_TEST
1010 Thread(false),
1011#endif //AUDIO_POLICY_TEST
Eric Laurentfad77872010-12-01 12:11:10 -08001012 mPhoneState(AudioSystem::MODE_NORMAL), mRingerMode(0),
1013 mMusicStopTime(0), mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1014 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurentb87b53d2010-11-02 12:02:20 -07001015 mA2dpSuspended(false)
Eric Laurentcef3cd72009-12-10 01:03:50 -08001016{
1017 mpClientInterface = clientInterface;
1018
1019 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1020 mForceUse[i] = AudioSystem::FORCE_NONE;
1021 }
1022
Jean-Michel Trivi3aab0582011-01-24 15:28:26 -08001023 initializeVolumeCurves();
1024
Eric Laurentcef3cd72009-12-10 01:03:50 -08001025 // devices available by default are speaker, ear piece and microphone
1026 mAvailableOutputDevices = AudioSystem::DEVICE_OUT_EARPIECE |
1027 AudioSystem::DEVICE_OUT_SPEAKER;
1028 mAvailableInputDevices = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1029
1030#ifdef WITH_A2DP
1031 mA2dpOutput = 0;
1032 mDuplicatedOutput = 0;
1033 mA2dpDeviceAddress = String8("");
1034#endif
1035 mScoDeviceAddress = String8("");
1036
1037 // open hardware output
1038 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1039 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1040 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1041 &outputDesc->mSamplingRate,
1042 &outputDesc->mFormat,
1043 &outputDesc->mChannels,
1044 &outputDesc->mLatency,
1045 outputDesc->mFlags);
1046
1047 if (mHardwareOutput == 0) {
1048 LOGE("Failed to initialize hardware output stream, samplingRate: %d, format %d, channels %d",
1049 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
1050 } else {
1051 addOutput(mHardwareOutput, outputDesc);
1052 setOutputDevice(mHardwareOutput, (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER, true);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001053 //TODO: configure audio effect output stage here
Eric Laurentcef3cd72009-12-10 01:03:50 -08001054 }
1055
1056 updateDeviceForStrategy();
1057#ifdef AUDIO_POLICY_TEST
Eric Laurent01635942011-01-18 18:39:02 -08001058 if (mHardwareOutput != 0) {
1059 AudioParameter outputCmd = AudioParameter();
1060 outputCmd.addInt(String8("set_id"), 0);
1061 mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString());
Eric Laurentcef3cd72009-12-10 01:03:50 -08001062
Eric Laurent01635942011-01-18 18:39:02 -08001063 mTestDevice = AudioSystem::DEVICE_OUT_SPEAKER;
1064 mTestSamplingRate = 44100;
1065 mTestFormat = AudioSystem::PCM_16_BIT;
1066 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1067 mTestLatencyMs = 0;
1068 mCurOutput = 0;
1069 mDirectOutput = false;
1070 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1071 mTestOutputs[i] = 0;
1072 }
1073
1074 const size_t SIZE = 256;
1075 char buffer[SIZE];
1076 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1077 run(buffer, ANDROID_PRIORITY_AUDIO);
Eric Laurentcef3cd72009-12-10 01:03:50 -08001078 }
Eric Laurentcef3cd72009-12-10 01:03:50 -08001079#endif //AUDIO_POLICY_TEST
1080}
1081
1082AudioPolicyManagerBase::~AudioPolicyManagerBase()
1083{
1084#ifdef AUDIO_POLICY_TEST
1085 exit();
1086#endif //AUDIO_POLICY_TEST
1087 for (size_t i = 0; i < mOutputs.size(); i++) {
1088 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1089 delete mOutputs.valueAt(i);
1090 }
1091 mOutputs.clear();
1092 for (size_t i = 0; i < mInputs.size(); i++) {
1093 mpClientInterface->closeInput(mInputs.keyAt(i));
1094 delete mInputs.valueAt(i);
1095 }
1096 mInputs.clear();
1097}
1098
Eric Laurent01635942011-01-18 18:39:02 -08001099status_t AudioPolicyManagerBase::initCheck()
1100{
1101 return (mHardwareOutput == 0) ? NO_INIT : NO_ERROR;
1102}
1103
Eric Laurentcef3cd72009-12-10 01:03:50 -08001104#ifdef AUDIO_POLICY_TEST
1105bool AudioPolicyManagerBase::threadLoop()
1106{
1107 LOGV("entering threadLoop()");
1108 while (!exitPending())
1109 {
1110 String8 command;
1111 int valueInt;
1112 String8 value;
1113
1114 Mutex::Autolock _l(mLock);
1115 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1116
1117 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1118 AudioParameter param = AudioParameter(command);
1119
1120 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1121 valueInt != 0) {
1122 LOGV("Test command %s received", command.string());
1123 String8 target;
1124 if (param.get(String8("target"), target) != NO_ERROR) {
1125 target = "Manager";
1126 }
1127 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1128 param.remove(String8("test_cmd_policy_output"));
1129 mCurOutput = valueInt;
1130 }
1131 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1132 param.remove(String8("test_cmd_policy_direct"));
1133 if (value == "false") {
1134 mDirectOutput = false;
1135 } else if (value == "true") {
1136 mDirectOutput = true;
1137 }
1138 }
1139 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1140 param.remove(String8("test_cmd_policy_input"));
1141 mTestInput = valueInt;
1142 }
1143
1144 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1145 param.remove(String8("test_cmd_policy_format"));
1146 int format = AudioSystem::INVALID_FORMAT;
1147 if (value == "PCM 16 bits") {
1148 format = AudioSystem::PCM_16_BIT;
1149 } else if (value == "PCM 8 bits") {
1150 format = AudioSystem::PCM_8_BIT;
1151 } else if (value == "Compressed MP3") {
1152 format = AudioSystem::MP3;
1153 }
1154 if (format != AudioSystem::INVALID_FORMAT) {
1155 if (target == "Manager") {
1156 mTestFormat = format;
1157 } else if (mTestOutputs[mCurOutput] != 0) {
1158 AudioParameter outputParam = AudioParameter();
1159 outputParam.addInt(String8("format"), format);
1160 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1161 }
1162 }
1163 }
1164 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1165 param.remove(String8("test_cmd_policy_channels"));
1166 int channels = 0;
1167
1168 if (value == "Channels Stereo") {
1169 channels = AudioSystem::CHANNEL_OUT_STEREO;
1170 } else if (value == "Channels Mono") {
1171 channels = AudioSystem::CHANNEL_OUT_MONO;
1172 }
1173 if (channels != 0) {
1174 if (target == "Manager") {
1175 mTestChannels = channels;
1176 } else if (mTestOutputs[mCurOutput] != 0) {
1177 AudioParameter outputParam = AudioParameter();
1178 outputParam.addInt(String8("channels"), channels);
1179 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1180 }
1181 }
1182 }
1183 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1184 param.remove(String8("test_cmd_policy_sampleRate"));
1185 if (valueInt >= 0 && valueInt <= 96000) {
1186 int samplingRate = valueInt;
1187 if (target == "Manager") {
1188 mTestSamplingRate = samplingRate;
1189 } else if (mTestOutputs[mCurOutput] != 0) {
1190 AudioParameter outputParam = AudioParameter();
1191 outputParam.addInt(String8("sampling_rate"), samplingRate);
1192 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1193 }
1194 }
1195 }
1196
1197 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1198 param.remove(String8("test_cmd_policy_reopen"));
1199
1200 mpClientInterface->closeOutput(mHardwareOutput);
1201 delete mOutputs.valueFor(mHardwareOutput);
1202 mOutputs.removeItem(mHardwareOutput);
1203
1204 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1205 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1206 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1207 &outputDesc->mSamplingRate,
1208 &outputDesc->mFormat,
1209 &outputDesc->mChannels,
1210 &outputDesc->mLatency,
1211 outputDesc->mFlags);
1212 if (mHardwareOutput == 0) {
1213 LOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1214 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
1215 } else {
1216 AudioParameter outputCmd = AudioParameter();
1217 outputCmd.addInt(String8("set_id"), 0);
1218 mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString());
1219 addOutput(mHardwareOutput, outputDesc);
1220 }
1221 }
1222
1223
1224 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1225 }
1226 }
1227 return false;
1228}
1229
1230void AudioPolicyManagerBase::exit()
1231{
1232 {
1233 AutoMutex _l(mLock);
1234 requestExit();
1235 mWaitWorkCV.signal();
1236 }
1237 requestExitAndWait();
1238}
1239
1240int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1241{
1242 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1243 if (output == mTestOutputs[i]) return i;
1244 }
1245 return 0;
1246}
1247#endif //AUDIO_POLICY_TEST
1248
1249// ---
1250
1251void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1252{
1253 outputDesc->mId = id;
1254 mOutputs.add(id, outputDesc);
1255}
1256
1257
1258#ifdef WITH_A2DP
1259status_t AudioPolicyManagerBase::handleA2dpConnection(AudioSystem::audio_devices device,
1260 const char *device_address)
1261{
1262 // when an A2DP device is connected, open an A2DP and a duplicated output
1263 LOGV("opening A2DP output for device %s", device_address);
1264 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1265 outputDesc->mDevice = device;
1266 mA2dpOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1267 &outputDesc->mSamplingRate,
1268 &outputDesc->mFormat,
1269 &outputDesc->mChannels,
1270 &outputDesc->mLatency,
1271 outputDesc->mFlags);
1272 if (mA2dpOutput) {
1273 // add A2DP output descriptor
1274 addOutput(mA2dpOutput, outputDesc);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001275
1276 //TODO: configure audio effect output stage here
1277
Eric Laurentcef3cd72009-12-10 01:03:50 -08001278 // set initial stream volume for A2DP device
1279 applyStreamVolumes(mA2dpOutput, device);
1280 if (a2dpUsedForSonification()) {
1281 mDuplicatedOutput = mpClientInterface->openDuplicateOutput(mA2dpOutput, mHardwareOutput);
1282 }
1283 if (mDuplicatedOutput != 0 ||
1284 !a2dpUsedForSonification()) {
1285 // If both A2DP and duplicated outputs are open, send device address to A2DP hardware
1286 // interface
1287 AudioParameter param;
1288 param.add(String8("a2dp_sink_address"), String8(device_address));
1289 mpClientInterface->setParameters(mA2dpOutput, param.toString());
1290 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
1291
1292 if (a2dpUsedForSonification()) {
1293 // add duplicated output descriptor
1294 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor();
1295 dupOutputDesc->mOutput1 = mOutputs.valueFor(mHardwareOutput);
1296 dupOutputDesc->mOutput2 = mOutputs.valueFor(mA2dpOutput);
1297 dupOutputDesc->mSamplingRate = outputDesc->mSamplingRate;
1298 dupOutputDesc->mFormat = outputDesc->mFormat;
1299 dupOutputDesc->mChannels = outputDesc->mChannels;
1300 dupOutputDesc->mLatency = outputDesc->mLatency;
1301 addOutput(mDuplicatedOutput, dupOutputDesc);
1302 applyStreamVolumes(mDuplicatedOutput, device);
1303 }
1304 } else {
1305 LOGW("getOutput() could not open duplicated output for %d and %d",
1306 mHardwareOutput, mA2dpOutput);
1307 mpClientInterface->closeOutput(mA2dpOutput);
1308 mOutputs.removeItem(mA2dpOutput);
1309 mA2dpOutput = 0;
1310 delete outputDesc;
1311 return NO_INIT;
1312 }
1313 } else {
1314 LOGW("setDeviceConnectionState() could not open A2DP output for device %x", device);
1315 delete outputDesc;
1316 return NO_INIT;
1317 }
1318 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
1319
Eric Laurentcef3cd72009-12-10 01:03:50 -08001320 if (!a2dpUsedForSonification()) {
1321 // mute music on A2DP output if a notification or ringtone is playing
1322 uint32_t refCount = hwOutputDesc->strategyRefCount(STRATEGY_SONIFICATION);
1323 for (uint32_t i = 0; i < refCount; i++) {
1324 setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput);
1325 }
1326 }
Eric Laurentb87b53d2010-11-02 12:02:20 -07001327
1328 mA2dpSuspended = false;
1329
Eric Laurentcef3cd72009-12-10 01:03:50 -08001330 return NO_ERROR;
1331}
1332
1333status_t AudioPolicyManagerBase::handleA2dpDisconnection(AudioSystem::audio_devices device,
1334 const char *device_address)
1335{
1336 if (mA2dpOutput == 0) {
1337 LOGW("setDeviceConnectionState() disconnecting A2DP and no A2DP output!");
1338 return INVALID_OPERATION;
1339 }
1340
1341 if (mA2dpDeviceAddress != device_address) {
1342 LOGW("setDeviceConnectionState() disconnecting unknow A2DP sink address %s", device_address);
1343 return INVALID_OPERATION;
1344 }
1345
Eric Laurent22e1ca32010-02-23 09:48:31 -08001346 // mute media strategy to avoid outputting sound on hardware output while music stream
Eric Laurentcef3cd72009-12-10 01:03:50 -08001347 // is switched from A2DP output and before music is paused by music application
1348 setStrategyMute(STRATEGY_MEDIA, true, mHardwareOutput);
Eric Laurent22e1ca32010-02-23 09:48:31 -08001349 setStrategyMute(STRATEGY_MEDIA, false, mHardwareOutput, MUTE_TIME_MS);
Eric Laurentcef3cd72009-12-10 01:03:50 -08001350
1351 if (!a2dpUsedForSonification()) {
1352 // unmute music on A2DP output if a notification or ringtone is playing
1353 uint32_t refCount = mOutputs.valueFor(mHardwareOutput)->strategyRefCount(STRATEGY_SONIFICATION);
1354 for (uint32_t i = 0; i < refCount; i++) {
1355 setStrategyMute(STRATEGY_MEDIA, false, mA2dpOutput);
1356 }
1357 }
1358 mA2dpDeviceAddress = "";
Eric Laurentb87b53d2010-11-02 12:02:20 -07001359 mA2dpSuspended = false;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001360 return NO_ERROR;
1361}
1362
1363void AudioPolicyManagerBase::closeA2dpOutputs()
1364{
Praveen Bharathi21e941b2010-10-06 15:23:14 -05001365
Eric Laurentcef3cd72009-12-10 01:03:50 -08001366 LOGV("setDeviceConnectionState() closing A2DP and duplicated output!");
1367
1368 if (mDuplicatedOutput != 0) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001369 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueFor(mDuplicatedOutput);
1370 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
1371 // As all active tracks on duplicated output will be deleted,
1372 // and as they were also referenced on hardware output, the reference
1373 // count for their stream type must be adjusted accordingly on
1374 // hardware output.
1375 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1376 int refCount = dupOutputDesc->mRefCount[i];
1377 hwOutputDesc->changeRefCount((AudioSystem::stream_type)i,-refCount);
1378 }
1379
Eric Laurentcef3cd72009-12-10 01:03:50 -08001380 mpClientInterface->closeOutput(mDuplicatedOutput);
1381 delete mOutputs.valueFor(mDuplicatedOutput);
1382 mOutputs.removeItem(mDuplicatedOutput);
1383 mDuplicatedOutput = 0;
1384 }
1385 if (mA2dpOutput != 0) {
1386 AudioParameter param;
1387 param.add(String8("closing"), String8("true"));
1388 mpClientInterface->setParameters(mA2dpOutput, param.toString());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001389
Eric Laurentcef3cd72009-12-10 01:03:50 -08001390 mpClientInterface->closeOutput(mA2dpOutput);
1391 delete mOutputs.valueFor(mA2dpOutput);
1392 mOutputs.removeItem(mA2dpOutput);
1393 mA2dpOutput = 0;
1394 }
1395}
1396
Eric Laurentb8453f42010-08-27 17:10:36 -07001397void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
Eric Laurentcef3cd72009-12-10 01:03:50 -08001398{
1399 uint32_t prevDevice = getDeviceForStrategy(strategy);
1400 uint32_t curDevice = getDeviceForStrategy(strategy, false);
1401 bool a2dpWasUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(prevDevice & ~AudioSystem::DEVICE_OUT_SPEAKER));
1402 bool a2dpIsUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(curDevice & ~AudioSystem::DEVICE_OUT_SPEAKER));
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001403 audio_io_handle_t srcOutput = 0;
1404 audio_io_handle_t dstOutput = 0;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001405
1406 if (a2dpWasUsed && !a2dpIsUsed) {
1407 bool dupUsed = a2dpUsedForSonification() && a2dpWasUsed && (AudioSystem::popCount(prevDevice) == 2);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001408 dstOutput = mHardwareOutput;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001409 if (dupUsed) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001410 LOGV("checkOutputForStrategy() moving strategy %d from duplicated", strategy);
1411 srcOutput = mDuplicatedOutput;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001412 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001413 LOGV("checkOutputForStrategy() moving strategy %d from a2dp", strategy);
1414 srcOutput = mA2dpOutput;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001415 }
Eric Laurentcef3cd72009-12-10 01:03:50 -08001416 }
1417 if (a2dpIsUsed && !a2dpWasUsed) {
1418 bool dupUsed = a2dpUsedForSonification() && a2dpIsUsed && (AudioSystem::popCount(curDevice) == 2);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001419 srcOutput = mHardwareOutput;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001420 if (dupUsed) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001421 LOGV("checkOutputForStrategy() moving strategy %d to duplicated", strategy);
1422 dstOutput = mDuplicatedOutput;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001423 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001424 LOGV("checkOutputForStrategy() moving strategy %d to a2dp", strategy);
1425 dstOutput = mA2dpOutput;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001426 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001427 }
Eric Laurentcef3cd72009-12-10 01:03:50 -08001428
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001429 if (srcOutput != 0 && dstOutput != 0) {
1430 // Move effects associated to this strategy from previous output to new output
1431 for (size_t i = 0; i < mEffects.size(); i++) {
1432 EffectDescriptor *desc = mEffects.valueAt(i);
1433 if (desc->mSession != AudioSystem::SESSION_OUTPUT_STAGE &&
1434 desc->mStrategy == strategy &&
1435 desc->mOutput == srcOutput) {
1436 LOGV("checkOutputForStrategy() moving effect %d to output %d", mEffects.keyAt(i), dstOutput);
1437 mpClientInterface->moveEffects(desc->mSession, srcOutput, dstOutput);
1438 desc->mOutput = dstOutput;
1439 }
1440 }
1441 // Move tracks associated to this strategy from previous output to new output
Eric Laurentcef3cd72009-12-10 01:03:50 -08001442 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1443 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001444 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, dstOutput);
Eric Laurentcef3cd72009-12-10 01:03:50 -08001445 }
1446 }
1447 }
1448}
1449
Eric Laurentb8453f42010-08-27 17:10:36 -07001450void AudioPolicyManagerBase::checkOutputForAllStrategies()
Eric Laurentcef3cd72009-12-10 01:03:50 -08001451{
Eric Laurentb8453f42010-08-27 17:10:36 -07001452 checkOutputForStrategy(STRATEGY_PHONE);
1453 checkOutputForStrategy(STRATEGY_SONIFICATION);
1454 checkOutputForStrategy(STRATEGY_MEDIA);
1455 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurentcef3cd72009-12-10 01:03:50 -08001456}
1457
Eric Laurentb87b53d2010-11-02 12:02:20 -07001458void AudioPolicyManagerBase::checkA2dpSuspend()
1459{
1460 // suspend A2DP output if:
1461 // (NOT already suspended) &&
1462 // ((SCO device is connected &&
1463 // (forced usage for communication || for record is SCO))) ||
1464 // (phone state is ringing || in call)
1465 //
1466 // restore A2DP output if:
1467 // (Already suspended) &&
1468 // ((SCO device is NOT connected ||
1469 // (forced usage NOT for communication && NOT for record is SCO))) &&
1470 // (phone state is NOT ringing && NOT in call)
1471 //
1472 if (mA2dpOutput == 0) {
1473 return;
1474 }
1475
1476 if (mA2dpSuspended) {
1477 if (((mScoDeviceAddress == "") ||
1478 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
1479 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
1480 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
1481 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
1482
1483 mpClientInterface->restoreOutput(mA2dpOutput);
1484 mA2dpSuspended = false;
1485 }
1486 } else {
1487 if (((mScoDeviceAddress != "") &&
1488 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1489 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
1490 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
1491 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
1492
1493 mpClientInterface->suspendOutput(mA2dpOutput);
1494 mA2dpSuspended = true;
1495 }
1496 }
1497}
1498
1499
Eric Laurentcef3cd72009-12-10 01:03:50 -08001500#endif
1501
1502uint32_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
1503{
1504 uint32_t device = 0;
1505
1506 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1507 // check the following by order of priority to request a routing change if necessary:
1508 // 1: we are in call or the strategy phone is active on the hardware output:
1509 // use device for strategy phone
1510 // 2: the strategy sonification is active on the hardware output:
1511 // use device for strategy sonification
1512 // 3: the strategy media is active on the hardware output:
1513 // use device for strategy media
1514 // 4: the strategy DTMF is active on the hardware output:
1515 // use device for strategy DTMF
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08001516 if (isInCall() ||
Eric Laurentcef3cd72009-12-10 01:03:50 -08001517 outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
1518 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
1519 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
1520 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
1521 } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
1522 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
1523 } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
1524 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
1525 }
1526
1527 LOGV("getNewDevice() selected device %x", device);
1528 return device;
1529}
1530
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001531uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
1532 return (uint32_t)getStrategy(stream);
1533}
1534
1535AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
1536 AudioSystem::stream_type stream) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001537 // stream to strategy mapping
1538 switch (stream) {
1539 case AudioSystem::VOICE_CALL:
1540 case AudioSystem::BLUETOOTH_SCO:
1541 return STRATEGY_PHONE;
1542 case AudioSystem::RING:
1543 case AudioSystem::NOTIFICATION:
1544 case AudioSystem::ALARM:
1545 case AudioSystem::ENFORCED_AUDIBLE:
1546 return STRATEGY_SONIFICATION;
1547 case AudioSystem::DTMF:
1548 return STRATEGY_DTMF;
1549 default:
1550 LOGE("unknown stream type");
1551 case AudioSystem::SYSTEM:
1552 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
1553 // while key clicks are played produces a poor result
1554 case AudioSystem::TTS:
1555 case AudioSystem::MUSIC:
1556 return STRATEGY_MEDIA;
1557 }
1558}
1559
1560uint32_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy, bool fromCache)
1561{
1562 uint32_t device = 0;
1563
1564 if (fromCache) {
1565 LOGV("getDeviceForStrategy() from cache strategy %d, device %x", strategy, mDeviceForStrategy[strategy]);
1566 return mDeviceForStrategy[strategy];
1567 }
1568
1569 switch (strategy) {
1570 case STRATEGY_DTMF:
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08001571 if (!isInCall()) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001572 // when off call, DTMF strategy follows the same rules as MEDIA strategy
1573 device = getDeviceForStrategy(STRATEGY_MEDIA, false);
1574 break;
1575 }
1576 // when in call, DTMF and PHONE strategies follow the same rules
1577 // FALL THROUGH
1578
1579 case STRATEGY_PHONE:
1580 // for phone strategy, we first consider the forced use and then the available devices by order
1581 // of priority
1582 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
1583 case AudioSystem::FORCE_BT_SCO:
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08001584 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001585 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
1586 if (device) break;
1587 }
1588 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
1589 if (device) break;
1590 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO;
1591 if (device) break;
1592 // if SCO device is requested but no SCO device is available, fall back to default case
1593 // FALL THROUGH
1594
1595 default: // FORCE_NONE
1596 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
1597 if (device) break;
1598 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1599 if (device) break;
Eric Laurent58bf1d92011-01-09 15:33:01 -08001600 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1601 if (device) break;
1602 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1603 if (device) break;
Praveen Bharathi21e941b2010-10-06 15:23:14 -05001604 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1605 if (device) break;
Jean-Michel Trivie4b8c422010-03-13 12:33:15 -08001606#ifdef WITH_A2DP
1607 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08001608 if (!isInCall()) {
Jean-Michel Trivie4b8c422010-03-13 12:33:15 -08001609 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1610 if (device) break;
1611 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1612 if (device) break;
1613 }
1614#endif
Eric Laurentcef3cd72009-12-10 01:03:50 -08001615 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_EARPIECE;
1616 if (device == 0) {
1617 LOGE("getDeviceForStrategy() earpiece device not found");
1618 }
1619 break;
1620
1621 case AudioSystem::FORCE_SPEAKER:
Eric Laurent58bf1d92011-01-09 15:33:01 -08001622 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1623 if (device) break;
1624 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1625 if (device) break;
Eric Laurentaef0cbb2010-12-16 09:44:42 -08001626 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1627 if (device) break;
Jean-Michel Trivie4b8c422010-03-13 12:33:15 -08001628#ifdef WITH_A2DP
1629 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
1630 // A2DP speaker when forcing to speaker output
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08001631 if (!isInCall()) {
Jean-Michel Trivie4b8c422010-03-13 12:33:15 -08001632 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1633 if (device) break;
1634 }
1635#endif
Eric Laurentcef3cd72009-12-10 01:03:50 -08001636 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1637 if (device == 0) {
1638 LOGE("getDeviceForStrategy() speaker device not found");
1639 }
1640 break;
1641 }
1642 break;
1643
1644 case STRATEGY_SONIFICATION:
1645
1646 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
1647 // handleIncallSonification().
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08001648 if (isInCall()) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001649 device = getDeviceForStrategy(STRATEGY_PHONE, false);
1650 break;
1651 }
1652 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1653 if (device == 0) {
1654 LOGE("getDeviceForStrategy() speaker device not found");
1655 }
1656 // The second device used for sonification is the same as the device used by media strategy
1657 // FALL THROUGH
1658
1659 case STRATEGY_MEDIA: {
Eric Laurent2c61bee2010-12-14 16:31:33 -08001660 uint32_t device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurentfe2e0752010-03-06 15:46:31 -08001661 if (device2 == 0) {
1662 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1663 }
Praveen Bharathi21e941b2010-10-06 15:23:14 -05001664 if (device2 == 0) {
Eric Laurent2c61bee2010-12-14 16:31:33 -08001665 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
Praveen Bharathi21e941b2010-10-06 15:23:14 -05001666 }
1667 if (device2 == 0) {
1668 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1669 }
Eric Laurent2c61bee2010-12-14 16:31:33 -08001670 if (device2 == 0) {
1671 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1672 }
Eric Laurentcef3cd72009-12-10 01:03:50 -08001673#ifdef WITH_A2DP
1674 if (mA2dpOutput != 0) {
1675 if (strategy == STRATEGY_SONIFICATION && !a2dpUsedForSonification()) {
1676 break;
1677 }
1678 if (device2 == 0) {
1679 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1680 }
1681 if (device2 == 0) {
1682 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1683 }
1684 if (device2 == 0) {
1685 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1686 }
1687 }
1688#endif
1689 if (device2 == 0) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001690 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1691 }
1692
1693 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION, 0 otherwise
1694 device |= device2;
1695 if (device == 0) {
1696 LOGE("getDeviceForStrategy() speaker device not found");
1697 }
1698 } break;
1699
1700 default:
1701 LOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
1702 break;
1703 }
1704
1705 LOGV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
1706 return device;
1707}
1708
1709void AudioPolicyManagerBase::updateDeviceForStrategy()
1710{
1711 for (int i = 0; i < NUM_STRATEGIES; i++) {
1712 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false);
1713 }
1714}
1715
1716void AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output, uint32_t device, bool force, int delayMs)
1717{
1718 LOGV("setOutputDevice() output %d device %x delayMs %d", output, device, delayMs);
1719 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1720
1721
1722 if (outputDesc->isDuplicated()) {
1723 setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
1724 setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
1725 return;
1726 }
1727#ifdef WITH_A2DP
1728 // filter devices according to output selected
Eric Laurentef9500f2010-03-11 14:47:00 -08001729 if (output == mA2dpOutput) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001730 device &= AudioSystem::DEVICE_OUT_ALL_A2DP;
Eric Laurentef9500f2010-03-11 14:47:00 -08001731 } else {
1732 device &= ~AudioSystem::DEVICE_OUT_ALL_A2DP;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001733 }
1734#endif
1735
1736 uint32_t prevDevice = (uint32_t)outputDesc->device();
1737 // Do not change the routing if:
1738 // - the requestede device is 0
1739 // - the requested device is the same as current device and force is not specified.
1740 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentef9500f2010-03-11 14:47:00 -08001741 if ((device == 0 || device == prevDevice) && !force) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001742 LOGV("setOutputDevice() setting same device %x or null device for output %d", device, output);
1743 return;
1744 }
1745
1746 outputDesc->mDevice = device;
1747 // mute media streams if both speaker and headset are selected
1748 if (output == mHardwareOutput && AudioSystem::popCount(device) == 2) {
1749 setStrategyMute(STRATEGY_MEDIA, true, output);
1750 // wait for the PCM output buffers to empty before proceeding with the rest of the command
1751 usleep(outputDesc->mLatency*2*1000);
1752 }
Eric Laurentb87b53d2010-11-02 12:02:20 -07001753
Eric Laurentcef3cd72009-12-10 01:03:50 -08001754 // do the routing
1755 AudioParameter param = AudioParameter();
1756 param.addInt(String8(AudioParameter::keyRouting), (int)device);
1757 mpClientInterface->setParameters(mHardwareOutput, param.toString(), delayMs);
1758 // update stream volumes according to new device
1759 applyStreamVolumes(output, device, delayMs);
1760
Eric Laurentcef3cd72009-12-10 01:03:50 -08001761 // if changing from a combined headset + speaker route, unmute media streams
1762 if (output == mHardwareOutput && AudioSystem::popCount(prevDevice) == 2) {
1763 setStrategyMute(STRATEGY_MEDIA, false, output, delayMs);
1764 }
1765}
1766
1767uint32_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
1768{
1769 uint32_t device;
1770
1771 switch(inputSource) {
1772 case AUDIO_SOURCE_DEFAULT:
1773 case AUDIO_SOURCE_MIC:
1774 case AUDIO_SOURCE_VOICE_RECOGNITION:
Jean-Michel Trivi820b9e02010-11-08 18:38:14 -08001775 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurentcef3cd72009-12-10 01:03:50 -08001776 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
1777 mAvailableInputDevices & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
1778 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
1779 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_WIRED_HEADSET) {
1780 device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
1781 } else {
1782 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1783 }
1784 break;
1785 case AUDIO_SOURCE_CAMCORDER:
1786 if (hasBackMicrophone()) {
1787 device = AudioSystem::DEVICE_IN_BACK_MIC;
1788 } else {
1789 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1790 }
1791 break;
1792 case AUDIO_SOURCE_VOICE_UPLINK:
1793 case AUDIO_SOURCE_VOICE_DOWNLINK:
1794 case AUDIO_SOURCE_VOICE_CALL:
1795 device = AudioSystem::DEVICE_IN_VOICE_CALL;
1796 break;
1797 default:
1798 LOGW("getInput() invalid input source %d", inputSource);
1799 device = 0;
1800 break;
1801 }
1802 LOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
1803 return device;
1804}
1805
1806audio_io_handle_t AudioPolicyManagerBase::getActiveInput()
1807{
1808 for (size_t i = 0; i < mInputs.size(); i++) {
1809 if (mInputs.valueAt(i)->mRefCount > 0) {
1810 return mInputs.keyAt(i);
1811 }
1812 }
1813 return 0;
1814}
1815
Jean-Michel Trivi3aab0582011-01-24 15:28:26 -08001816float AudioPolicyManagerBase::volIndexToAmpl(uint32_t device, const StreamDescriptor& streamDesc,
1817 int indexInUi) {
1818 // the volume index in the UI is relative to the min and max volume indices for this stream type
1819 int nbSteps = 1 + streamDesc.mVolIndex[StreamDescriptor::VOLMAX] -
1820 streamDesc.mVolIndex[StreamDescriptor::VOLMIN];
1821 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
1822 (streamDesc.mIndexMax - streamDesc.mIndexMin);
1823
1824 // find what part of the curve this index volume belongs to, or if it's out of bounds
1825 int segment = 0;
1826 if (volIdx < streamDesc.mVolIndex[StreamDescriptor::VOLMIN]) { // out of bounds
1827 return 0.0f;
1828 } else if (volIdx < streamDesc.mVolIndex[StreamDescriptor::VOLKNEE1]) {
1829 segment = 0;
1830 } else if (volIdx < streamDesc.mVolIndex[StreamDescriptor::VOLKNEE2]) {
1831 segment = 1;
1832 } else if (volIdx <= streamDesc.mVolIndex[StreamDescriptor::VOLMAX]) {
1833 segment = 2;
1834 } else { // out of bounds
1835 return 1.0f;
1836 }
1837
1838 // linear interpolation in the attenuation table in dB
1839 float decibels = streamDesc.mVolDbAtt[segment] +
1840 ((float)(volIdx - streamDesc.mVolIndex[segment])) *
1841 ( (streamDesc.mVolDbAtt[segment+1] - streamDesc.mVolDbAtt[segment]) /
1842 ((float)(streamDesc.mVolIndex[segment+1] - streamDesc.mVolIndex[segment])) );
1843
1844 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
1845
1846 LOGV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
1847 streamDesc.mVolIndex[segment], volIdx, streamDesc.mVolIndex[segment+1],
1848 streamDesc.mVolDbAtt[segment], decibels, streamDesc.mVolDbAtt[segment+1],
1849 amplification);
1850
1851 return amplification;
1852}
1853
1854void AudioPolicyManagerBase::initializeVolumeCurves() {
1855 // initialize the volume curves to a (-49.5 - 0 dB) attenuation in 0.5dB steps
1856 for (int i=0 ; i< AudioSystem::NUM_STREAM_TYPES ; i++) {
1857 mStreams[i].mVolIndex[StreamDescriptor::VOLMIN] = 1;
1858 mStreams[i].mVolDbAtt[StreamDescriptor::VOLMIN] = -49.5f;
1859 mStreams[i].mVolIndex[StreamDescriptor::VOLKNEE1] = 33;
1860 mStreams[i].mVolDbAtt[StreamDescriptor::VOLKNEE1] = -33.5f;
1861 mStreams[i].mVolIndex[StreamDescriptor::VOLKNEE2] = 66;
1862 mStreams[i].mVolDbAtt[StreamDescriptor::VOLKNEE2] = -17.0f;
1863 // here we use 100 steps to avoid rounding errors
1864 // when computing the volume in volIndexToAmpl()
1865 mStreams[i].mVolIndex[StreamDescriptor::VOLMAX] = 100;
1866 mStreams[i].mVolDbAtt[StreamDescriptor::VOLMAX] = 0.0f;
1867 }
1868
1869 // TODO add modifications for music to have finer steps below knee1 and above knee2
1870}
1871
Eric Laurentcef3cd72009-12-10 01:03:50 -08001872float AudioPolicyManagerBase::computeVolume(int stream, int index, audio_io_handle_t output, uint32_t device)
1873{
1874 float volume = 1.0;
1875 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1876 StreamDescriptor &streamDesc = mStreams[stream];
1877
1878 if (device == 0) {
1879 device = outputDesc->device();
1880 }
1881
Jean-Michel Trivi3aab0582011-01-24 15:28:26 -08001882 volume = volIndexToAmpl(device, streamDesc, index);
Eric Laurentcef3cd72009-12-10 01:03:50 -08001883
Eric Laurentef9500f2010-03-11 14:47:00 -08001884 // if a headset is connected, apply the following rules to ring tones and notifications
Eric Laurentcef3cd72009-12-10 01:03:50 -08001885 // to avoid sound level bursts in user's ears:
1886 // - always attenuate ring tones and notifications volume by 6dB
1887 // - if music is playing, always limit the volume to current music volume,
1888 // with a minimum threshold at -36dB so that notification is always perceived.
1889 if ((device &
1890 (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP |
1891 AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
1892 AudioSystem::DEVICE_OUT_WIRED_HEADSET |
Praveen Bharathi21e941b2010-10-06 15:23:14 -05001893 AudioSystem::DEVICE_OUT_WIRED_HEADPHONE |
1894 AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET |
1895 AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET)) &&
Eric Laurentcef3cd72009-12-10 01:03:50 -08001896 (getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) &&
1897 streamDesc.mCanBeMuted) {
1898 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
1899 // when the phone is ringing we must consider that music could have been paused just before
1900 // by the music application and behave as if music was active if the last music track was
1901 // just stopped
1902 if (outputDesc->mRefCount[AudioSystem::MUSIC] || mLimitRingtoneVolume) {
1903 float musicVol = computeVolume(AudioSystem::MUSIC, mStreams[AudioSystem::MUSIC].mIndexCur, output, device);
1904 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ? musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
1905 if (volume > minVol) {
1906 volume = minVol;
1907 LOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
1908 }
1909 }
1910 }
1911
1912 return volume;
1913}
1914
1915status_t AudioPolicyManagerBase::checkAndSetVolume(int stream, int index, audio_io_handle_t output, uint32_t device, int delayMs, bool force)
1916{
1917
1918 // do not change actual stream volume if the stream is muted
1919 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
1920 LOGV("checkAndSetVolume() stream %d muted count %d", stream, mOutputs.valueFor(output)->mMuteCount[stream]);
1921 return NO_ERROR;
1922 }
1923
1924 // do not change in call volume if bluetooth is connected and vice versa
1925 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1926 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
1927 LOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
1928 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
1929 return INVALID_OPERATION;
1930 }
1931
1932 float volume = computeVolume(stream, index, output, device);
Eric Laurentcc9c4242010-05-25 09:31:59 -07001933 // We actually change the volume if:
1934 // - the float value returned by computeVolume() changed
1935 // - the force flag is set
1936 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
1937 force) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001938 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
1939 LOGV("setStreamVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
1940 if (stream == AudioSystem::VOICE_CALL ||
1941 stream == AudioSystem::DTMF ||
1942 stream == AudioSystem::BLUETOOTH_SCO) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001943 // offset value to reflect actual hardware volume that never reaches 0
1944 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
1945 volume = 0.01 + 0.99 * volume;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001946 }
1947 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
1948 }
1949
Eric Laurentcc9c4242010-05-25 09:31:59 -07001950 if (stream == AudioSystem::VOICE_CALL ||
1951 stream == AudioSystem::BLUETOOTH_SCO) {
1952 float voiceVolume;
1953 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
1954 if (stream == AudioSystem::VOICE_CALL) {
1955 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
1956 } else {
1957 voiceVolume = 1.0;
1958 }
1959 if (voiceVolume != mLastVoiceVolume && output == mHardwareOutput) {
1960 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
1961 mLastVoiceVolume = voiceVolume;
1962 }
1963 }
1964
Eric Laurentcef3cd72009-12-10 01:03:50 -08001965 return NO_ERROR;
1966}
1967
1968void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output, uint32_t device, int delayMs)
1969{
1970 LOGV("applyStreamVolumes() for output %d and device %x", output, device);
1971
1972 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
1973 checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, device, delayMs);
1974 }
1975}
1976
1977void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy, bool on, audio_io_handle_t output, int delayMs)
1978{
1979 LOGV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
1980 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
1981 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
1982 setStreamMute(stream, on, output, delayMs);
1983 }
1984 }
1985}
1986
1987void AudioPolicyManagerBase::setStreamMute(int stream, bool on, audio_io_handle_t output, int delayMs)
1988{
1989 StreamDescriptor &streamDesc = mStreams[stream];
1990 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1991
1992 LOGV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d", stream, on, output, outputDesc->mMuteCount[stream]);
1993
1994 if (on) {
1995 if (outputDesc->mMuteCount[stream] == 0) {
1996 if (streamDesc.mCanBeMuted) {
1997 checkAndSetVolume(stream, 0, output, outputDesc->device(), delayMs);
1998 }
1999 }
2000 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
2001 outputDesc->mMuteCount[stream]++;
2002 } else {
2003 if (outputDesc->mMuteCount[stream] == 0) {
2004 LOGW("setStreamMute() unmuting non muted stream!");
2005 return;
2006 }
2007 if (--outputDesc->mMuteCount[stream] == 0) {
2008 checkAndSetVolume(stream, streamDesc.mIndexCur, output, outputDesc->device(), delayMs);
2009 }
2010 }
2011}
2012
2013void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
2014{
2015 // if the stream pertains to sonification strategy and we are in call we must
2016 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
2017 // in the device used for phone strategy and play the tone if the selected device does not
2018 // interfere with the device used for phone strategy
2019 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
2020 // many times as there are active tracks on the output
2021
2022 if (getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) {
2023 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mHardwareOutput);
2024 LOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
2025 stream, starting, outputDesc->mDevice, stateChange);
2026 if (outputDesc->mRefCount[stream]) {
2027 int muteCount = 1;
2028 if (stateChange) {
2029 muteCount = outputDesc->mRefCount[stream];
2030 }
2031 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
2032 LOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
2033 for (int i = 0; i < muteCount; i++) {
2034 setStreamMute(stream, starting, mHardwareOutput);
2035 }
2036 } else {
2037 LOGV("handleIncallSonification() high visibility");
2038 if (outputDesc->device() & getDeviceForStrategy(STRATEGY_PHONE)) {
2039 LOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
2040 for (int i = 0; i < muteCount; i++) {
2041 setStreamMute(stream, starting, mHardwareOutput);
2042 }
2043 }
2044 if (starting) {
2045 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
2046 } else {
2047 mpClientInterface->stopTone();
2048 }
2049 }
2050 }
2051 }
2052}
2053
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08002054bool AudioPolicyManagerBase::isInCall()
2055{
2056 return isStateInCall(mPhoneState);
2057}
2058
2059bool AudioPolicyManagerBase::isStateInCall(int state) {
2060 return ((state == AudioSystem::MODE_IN_CALL) ||
2061 (state == AudioSystem::MODE_IN_COMMUNICATION));
2062}
2063
Eric Laurentef9500f2010-03-11 14:47:00 -08002064bool AudioPolicyManagerBase::needsDirectOuput(AudioSystem::stream_type stream,
2065 uint32_t samplingRate,
2066 uint32_t format,
2067 uint32_t channels,
2068 AudioSystem::output_flags flags,
2069 uint32_t device)
2070{
2071 return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
2072 (format !=0 && !AudioSystem::isLinearPCM(format)));
2073}
2074
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002075uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
2076{
2077 return MAX_EFFECTS_CPU_LOAD;
2078}
2079
2080uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
2081{
2082 return MAX_EFFECTS_MEMORY;
2083}
2084
Eric Laurentcef3cd72009-12-10 01:03:50 -08002085// --- AudioOutputDescriptor class implementation
2086
2087AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor()
2088 : mId(0), mSamplingRate(0), mFormat(0), mChannels(0), mLatency(0),
2089 mFlags((AudioSystem::output_flags)0), mDevice(0), mOutput1(0), mOutput2(0)
2090{
2091 // clear usage count for all stream types
2092 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2093 mRefCount[i] = 0;
2094 mCurVolume[i] = -1.0;
2095 mMuteCount[i] = 0;
2096 }
2097}
2098
2099uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::device()
2100{
2101 uint32_t device = 0;
2102 if (isDuplicated()) {
2103 device = mOutput1->mDevice | mOutput2->mDevice;
2104 } else {
2105 device = mDevice;
2106 }
2107 return device;
2108}
2109
2110void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
2111{
2112 // forward usage count change to attached outputs
2113 if (isDuplicated()) {
2114 mOutput1->changeRefCount(stream, delta);
2115 mOutput2->changeRefCount(stream, delta);
2116 }
2117 if ((delta + (int)mRefCount[stream]) < 0) {
2118 LOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
2119 mRefCount[stream] = 0;
2120 return;
2121 }
2122 mRefCount[stream] += delta;
2123 LOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
2124}
2125
2126uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount()
2127{
2128 uint32_t refcount = 0;
2129 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2130 refcount += mRefCount[i];
2131 }
2132 return refcount;
2133}
2134
2135uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy)
2136{
2137 uint32_t refCount = 0;
2138 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2139 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2140 refCount += mRefCount[i];
2141 }
2142 }
2143 return refCount;
2144}
2145
2146
2147status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
2148{
2149 const size_t SIZE = 256;
2150 char buffer[SIZE];
2151 String8 result;
2152
2153 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2154 result.append(buffer);
2155 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2156 result.append(buffer);
2157 snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
2158 result.append(buffer);
2159 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
2160 result.append(buffer);
2161 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
2162 result.append(buffer);
2163 snprintf(buffer, SIZE, " Devices %08x\n", device());
2164 result.append(buffer);
2165 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
2166 result.append(buffer);
2167 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2168 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
2169 result.append(buffer);
2170 }
2171 write(fd, result.string(), result.size());
2172
2173 return NO_ERROR;
2174}
2175
2176// --- AudioInputDescriptor class implementation
2177
2178AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor()
2179 : mSamplingRate(0), mFormat(0), mChannels(0),
2180 mAcoustics((AudioSystem::audio_in_acoustics)0), mDevice(0), mRefCount(0)
2181{
2182}
2183
2184status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
2185{
2186 const size_t SIZE = 256;
2187 char buffer[SIZE];
2188 String8 result;
2189
2190 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2191 result.append(buffer);
2192 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2193 result.append(buffer);
2194 snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
2195 result.append(buffer);
2196 snprintf(buffer, SIZE, " Acoustics %08x\n", mAcoustics);
2197 result.append(buffer);
2198 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
2199 result.append(buffer);
2200 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
2201 result.append(buffer);
2202 write(fd, result.string(), result.size());
2203
2204 return NO_ERROR;
2205}
2206
2207// --- StreamDescriptor class implementation
2208
2209void AudioPolicyManagerBase::StreamDescriptor::dump(char* buffer, size_t size)
2210{
2211 snprintf(buffer, size, " %02d %02d %02d %d\n",
2212 mIndexMin,
2213 mIndexMax,
2214 mIndexCur,
2215 mCanBeMuted);
2216}
2217
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002218// --- EffectDescriptor class implementation
2219
2220status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
2221{
2222 const size_t SIZE = 256;
2223 char buffer[SIZE];
2224 String8 result;
2225
2226 snprintf(buffer, SIZE, " Output: %d\n", mOutput);
2227 result.append(buffer);
2228 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
2229 result.append(buffer);
2230 snprintf(buffer, SIZE, " Session: %d\n", mSession);
2231 result.append(buffer);
2232 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
2233 result.append(buffer);
2234 write(fd, result.string(), result.size());
2235
2236 return NO_ERROR;
2237}
2238
2239
Eric Laurentcef3cd72009-12-10 01:03:50 -08002240
2241}; // namespace android