blob: afa9acc9ee3dc010ac038a72dd722dff26c13c36 [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>
22
23namespace android {
24
25
26// ----------------------------------------------------------------------------
27// AudioPolicyInterface implementation
28// ----------------------------------------------------------------------------
29
30
31status_t AudioPolicyManagerBase::setDeviceConnectionState(AudioSystem::audio_devices device,
32 AudioSystem::device_connection_state state,
33 const char *device_address)
34{
35
36 LOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
37
38 // connect/disconnect only 1 device at a time
39 if (AudioSystem::popCount(device) != 1) return BAD_VALUE;
40
41 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
42 LOGE("setDeviceConnectionState() invalid address: %s", device_address);
43 return BAD_VALUE;
44 }
45
46 // handle output devices
47 if (AudioSystem::isOutputDevice(device)) {
48
49#ifndef WITH_A2DP
50 if (AudioSystem::isA2dpDevice(device)) {
51 LOGE("setDeviceConnectionState() invalid device: %x", device);
52 return BAD_VALUE;
53 }
54#endif
55
56 switch (state)
57 {
58 // handle output device connection
59 case AudioSystem::DEVICE_STATE_AVAILABLE:
60 if (mAvailableOutputDevices & device) {
61 LOGW("setDeviceConnectionState() device already connected: %x", device);
62 return INVALID_OPERATION;
63 }
64 LOGV("setDeviceConnectionState() connecting device %x", device);
65
66 // register new device as available
67 mAvailableOutputDevices |= device;
68
69#ifdef WITH_A2DP
70 // handle A2DP device connection
71 if (AudioSystem::isA2dpDevice(device)) {
72 status_t status = handleA2dpConnection(device, device_address);
73 if (status != NO_ERROR) {
74 mAvailableOutputDevices &= ~device;
75 return status;
76 }
77 } else
78#endif
79 {
80 if (AudioSystem::isBluetoothScoDevice(device)) {
81 LOGV("setDeviceConnectionState() BT SCO device, address %s", device_address);
82 // keep track of SCO device address
83 mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
Eric Laurentcef3cd72009-12-10 01:03:50 -080084 }
85 }
86 break;
87 // handle output device disconnection
88 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
89 if (!(mAvailableOutputDevices & device)) {
90 LOGW("setDeviceConnectionState() device not connected: %x", device);
91 return INVALID_OPERATION;
92 }
93
94
95 LOGV("setDeviceConnectionState() disconnecting device %x", device);
96 // remove device from available output devices
97 mAvailableOutputDevices &= ~device;
98
99#ifdef WITH_A2DP
100 // handle A2DP device disconnection
101 if (AudioSystem::isA2dpDevice(device)) {
102 status_t status = handleA2dpDisconnection(device, device_address);
103 if (status != NO_ERROR) {
104 mAvailableOutputDevices |= device;
105 return status;
106 }
107 } else
108#endif
109 {
110 if (AudioSystem::isBluetoothScoDevice(device)) {
111 mScoDeviceAddress = "";
Eric Laurentcef3cd72009-12-10 01:03:50 -0800112 }
113 }
114 } break;
115
116 default:
117 LOGE("setDeviceConnectionState() invalid state: %x", state);
118 return BAD_VALUE;
119 }
120
121 // request routing change if necessary
122 uint32_t newDevice = getNewDevice(mHardwareOutput, false);
123#ifdef WITH_A2DP
Eric Laurentb8453f42010-08-27 17:10:36 -0700124 checkOutputForAllStrategies();
Eric Laurentcef3cd72009-12-10 01:03:50 -0800125 // A2DP outputs must be closed after checkOutputForAllStrategies() is executed
126 if (state == AudioSystem::DEVICE_STATE_UNAVAILABLE && AudioSystem::isA2dpDevice(device)) {
127 closeA2dpOutputs();
128 }
Eric Laurentb87b53d2010-11-02 12:02:20 -0700129 checkA2dpSuspend();
Eric Laurentcef3cd72009-12-10 01:03:50 -0800130#endif
131 updateDeviceForStrategy();
132 setOutputDevice(mHardwareOutput, newDevice);
133
134 if (device == AudioSystem::DEVICE_OUT_WIRED_HEADSET) {
135 device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
136 } else if (device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO ||
137 device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
138 device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
139 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
140 } else {
141 return NO_ERROR;
142 }
143 }
144 // handle input devices
145 if (AudioSystem::isInputDevice(device)) {
146
147 switch (state)
148 {
149 // handle input device connection
150 case AudioSystem::DEVICE_STATE_AVAILABLE: {
151 if (mAvailableInputDevices & device) {
152 LOGW("setDeviceConnectionState() device already connected: %d", device);
153 return INVALID_OPERATION;
154 }
155 mAvailableInputDevices |= device;
156 }
157 break;
158
159 // handle input device disconnection
160 case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
161 if (!(mAvailableInputDevices & device)) {
162 LOGW("setDeviceConnectionState() device not connected: %d", device);
163 return INVALID_OPERATION;
164 }
165 mAvailableInputDevices &= ~device;
166 } break;
167
168 default:
169 LOGE("setDeviceConnectionState() invalid state: %x", state);
170 return BAD_VALUE;
171 }
172
173 audio_io_handle_t activeInput = getActiveInput();
174 if (activeInput != 0) {
175 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
176 uint32_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
177 if (newDevice != inputDesc->mDevice) {
178 LOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
179 inputDesc->mDevice, newDevice, activeInput);
180 inputDesc->mDevice = newDevice;
181 AudioParameter param = AudioParameter();
182 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
183 mpClientInterface->setParameters(activeInput, param.toString());
184 }
185 }
186
187 return NO_ERROR;
188 }
189
190 LOGW("setDeviceConnectionState() invalid device: %x", device);
191 return BAD_VALUE;
192}
193
194AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(AudioSystem::audio_devices device,
195 const char *device_address)
196{
197 AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
198 String8 address = String8(device_address);
199 if (AudioSystem::isOutputDevice(device)) {
200 if (device & mAvailableOutputDevices) {
201#ifdef WITH_A2DP
202 if (AudioSystem::isA2dpDevice(device) &&
203 address != "" && mA2dpDeviceAddress != address) {
204 return state;
205 }
206#endif
207 if (AudioSystem::isBluetoothScoDevice(device) &&
208 address != "" && mScoDeviceAddress != address) {
209 return state;
210 }
211 state = AudioSystem::DEVICE_STATE_AVAILABLE;
212 }
213 } else if (AudioSystem::isInputDevice(device)) {
214 if (device & mAvailableInputDevices) {
215 state = AudioSystem::DEVICE_STATE_AVAILABLE;
216 }
217 }
218
219 return state;
220}
221
222void AudioPolicyManagerBase::setPhoneState(int state)
223{
224 LOGV("setPhoneState() state %d", state);
225 uint32_t newDevice = 0;
226 if (state < 0 || state >= AudioSystem::NUM_MODES) {
227 LOGW("setPhoneState() invalid state %d", state);
228 return;
229 }
230
231 if (state == mPhoneState ) {
232 LOGW("setPhoneState() setting same state %d", state);
233 return;
234 }
235
236 // if leaving call state, handle special case of active streams
237 // pertaining to sonification strategy see handleIncallSonification()
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -0800238 if (isInCall()) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800239 LOGV("setPhoneState() in call state management: new state is %d", state);
240 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
241 handleIncallSonification(stream, false, true);
242 }
243 }
244
245 // store previous phone state for management of sonification strategy below
246 int oldState = mPhoneState;
247 mPhoneState = state;
248 bool force = false;
249
250 // are we entering or starting a call
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -0800251 if (!isStateInCall(oldState) && isStateInCall(state)) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800252 LOGV(" Entering call in setPhoneState()");
253 // force routing command to audio hardware when starting a call
254 // even if no device change is needed
255 force = true;
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -0800256 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800257 LOGV(" Exiting call in setPhoneState()");
258 // force routing command to audio hardware when exiting a call
259 // even if no device change is needed
260 force = true;
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -0800261 } else if (isStateInCall(state) && (state != oldState)) {
262 LOGV(" Switching between telephony and VoIP in setPhoneState()");
263 // force routing command to audio hardware when switching between telephony and VoIP
264 // even if no device change is needed
265 force = true;
Eric Laurentcef3cd72009-12-10 01:03:50 -0800266 }
267
268 // check for device and output changes triggered by new phone state
269 newDevice = getNewDevice(mHardwareOutput, false);
270#ifdef WITH_A2DP
Eric Laurentb8453f42010-08-27 17:10:36 -0700271 checkOutputForAllStrategies();
Eric Laurentb87b53d2010-11-02 12:02:20 -0700272 checkA2dpSuspend();
Eric Laurentcef3cd72009-12-10 01:03:50 -0800273#endif
274 updateDeviceForStrategy();
275
276 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
277
278 // force routing command to audio hardware when ending call
279 // even if no device change is needed
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -0800280 if (isStateInCall(oldState) && newDevice == 0) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800281 newDevice = hwOutputDesc->device();
282 }
Eric Laurent22e1ca32010-02-23 09:48:31 -0800283
284 // when changing from ring tone to in call mode, mute the ringing tone
285 // immediately and delay the route change to avoid sending the ring tone
286 // tail into the earpiece or headset.
287 int delayMs = 0;
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -0800288 if (isStateInCall(state) && oldState == AudioSystem::MODE_RINGTONE) {
Eric Laurent22e1ca32010-02-23 09:48:31 -0800289 // delay the device change command by twice the output latency to have some margin
290 // and be sure that audio buffers not yet affected by the mute are out when
291 // we actually apply the route change
292 delayMs = hwOutputDesc->mLatency*2;
293 setStreamMute(AudioSystem::RING, true, mHardwareOutput);
294 }
295
Eric Laurentcef3cd72009-12-10 01:03:50 -0800296 // change routing is necessary
Eric Laurent22e1ca32010-02-23 09:48:31 -0800297 setOutputDevice(mHardwareOutput, newDevice, force, delayMs);
Eric Laurentcef3cd72009-12-10 01:03:50 -0800298
299 // if entering in call state, handle special case of active streams
300 // pertaining to sonification strategy see handleIncallSonification()
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -0800301 if (isStateInCall(state)) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800302 LOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent22e1ca32010-02-23 09:48:31 -0800303 // unmute the ringing tone after a sufficient delay if it was muted before
304 // setting output device above
305 if (oldState == AudioSystem::MODE_RINGTONE) {
306 setStreamMute(AudioSystem::RING, false, mHardwareOutput, MUTE_TIME_MS);
307 }
Eric Laurentcef3cd72009-12-10 01:03:50 -0800308 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
309 handleIncallSonification(stream, true, true);
310 }
311 }
312
313 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
314 if (state == AudioSystem::MODE_RINGTONE &&
Eric Laurent25101b02011-02-02 09:33:30 -0800315 isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800316 mLimitRingtoneVolume = true;
317 } else {
318 mLimitRingtoneVolume = false;
319 }
320}
321
322void AudioPolicyManagerBase::setRingerMode(uint32_t mode, uint32_t mask)
323{
324 LOGV("setRingerMode() mode %x, mask %x", mode, mask);
325
326 mRingerMode = mode;
327}
328
329void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
330{
331 LOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
332
Jean-Michel Trivi758559e2010-03-09 09:26:08 -0800333 bool forceVolumeReeval = false;
Eric Laurentcef3cd72009-12-10 01:03:50 -0800334 switch(usage) {
335 case AudioSystem::FOR_COMMUNICATION:
336 if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
337 config != AudioSystem::FORCE_NONE) {
338 LOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
339 return;
340 }
341 mForceUse[usage] = config;
342 break;
343 case AudioSystem::FOR_MEDIA:
344 if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
Praveen Bharathi21e941b2010-10-06 15:23:14 -0500345 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
346 config != AudioSystem::FORCE_ANALOG_DOCK &&
347 config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800348 LOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
349 return;
350 }
351 mForceUse[usage] = config;
352 break;
353 case AudioSystem::FOR_RECORD:
354 if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
355 config != AudioSystem::FORCE_NONE) {
356 LOGW("setForceUse() invalid config %d for FOR_RECORD", config);
357 return;
358 }
359 mForceUse[usage] = config;
360 break;
361 case AudioSystem::FOR_DOCK:
362 if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
Praveen Bharathi21e941b2010-10-06 15:23:14 -0500363 config != AudioSystem::FORCE_BT_DESK_DOCK &&
364 config != AudioSystem::FORCE_WIRED_ACCESSORY &&
365 config != AudioSystem::FORCE_ANALOG_DOCK &&
366 config != AudioSystem::FORCE_DIGITAL_DOCK) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800367 LOGW("setForceUse() invalid config %d for FOR_DOCK", config);
368 }
Jean-Michel Trivi758559e2010-03-09 09:26:08 -0800369 forceVolumeReeval = true;
Eric Laurentcef3cd72009-12-10 01:03:50 -0800370 mForceUse[usage] = config;
371 break;
372 default:
373 LOGW("setForceUse() invalid usage %d", usage);
374 break;
375 }
376
377 // check for device and output changes triggered by new phone state
378 uint32_t newDevice = getNewDevice(mHardwareOutput, false);
379#ifdef WITH_A2DP
Eric Laurentb8453f42010-08-27 17:10:36 -0700380 checkOutputForAllStrategies();
Eric Laurentb87b53d2010-11-02 12:02:20 -0700381 checkA2dpSuspend();
Eric Laurentcef3cd72009-12-10 01:03:50 -0800382#endif
383 updateDeviceForStrategy();
384 setOutputDevice(mHardwareOutput, newDevice);
Jean-Michel Trivi758559e2010-03-09 09:26:08 -0800385 if (forceVolumeReeval) {
386 applyStreamVolumes(mHardwareOutput, newDevice);
387 }
Eric Laurentb8453f42010-08-27 17:10:36 -0700388
389 audio_io_handle_t activeInput = getActiveInput();
390 if (activeInput != 0) {
391 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
392 newDevice = getDeviceForInputSource(inputDesc->mInputSource);
393 if (newDevice != inputDesc->mDevice) {
394 LOGV("setForceUse() changing device from %x to %x for input %d",
395 inputDesc->mDevice, newDevice, activeInput);
396 inputDesc->mDevice = newDevice;
397 AudioParameter param = AudioParameter();
398 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
399 mpClientInterface->setParameters(activeInput, param.toString());
400 }
401 }
402
Eric Laurentcef3cd72009-12-10 01:03:50 -0800403}
404
405AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
406{
407 return mForceUse[usage];
408}
409
410void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
411{
412 LOGV("setSystemProperty() property %s, value %s", property, value);
413 if (strcmp(property, "ro.camera.sound.forced") == 0) {
414 if (atoi(value)) {
415 LOGV("ENFORCED_AUDIBLE cannot be muted");
416 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = false;
417 } else {
418 LOGV("ENFORCED_AUDIBLE can be muted");
419 mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = true;
420 }
421 }
422}
423
424audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
425 uint32_t samplingRate,
426 uint32_t format,
427 uint32_t channels,
428 AudioSystem::output_flags flags)
429{
430 audio_io_handle_t output = 0;
431 uint32_t latency = 0;
432 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
433 uint32_t device = getDeviceForStrategy(strategy);
434 LOGV("getOutput() stream %d, samplingRate %d, format %d, channels %x, flags %x", stream, samplingRate, format, channels, flags);
435
436#ifdef AUDIO_POLICY_TEST
437 if (mCurOutput != 0) {
438 LOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channels %x, mDirectOutput %d",
439 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
440
441 if (mTestOutputs[mCurOutput] == 0) {
442 LOGV("getOutput() opening test output");
443 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
444 outputDesc->mDevice = mTestDevice;
445 outputDesc->mSamplingRate = mTestSamplingRate;
446 outputDesc->mFormat = mTestFormat;
447 outputDesc->mChannels = mTestChannels;
448 outputDesc->mLatency = mTestLatencyMs;
449 outputDesc->mFlags = (AudioSystem::output_flags)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
450 outputDesc->mRefCount[stream] = 0;
451 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(&outputDesc->mDevice,
452 &outputDesc->mSamplingRate,
453 &outputDesc->mFormat,
454 &outputDesc->mChannels,
455 &outputDesc->mLatency,
456 outputDesc->mFlags);
457 if (mTestOutputs[mCurOutput]) {
458 AudioParameter outputCmd = AudioParameter();
459 outputCmd.addInt(String8("set_id"),mCurOutput);
460 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
461 addOutput(mTestOutputs[mCurOutput], outputDesc);
462 }
463 }
464 return mTestOutputs[mCurOutput];
465 }
466#endif //AUDIO_POLICY_TEST
467
Eric Laurentef9500f2010-03-11 14:47:00 -0800468 // open a direct output if required by specified parameters
469 if (needsDirectOuput(stream, samplingRate, format, channels, flags, device)) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800470
471 LOGV("getOutput() opening direct output device %x", device);
472 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
473 outputDesc->mDevice = device;
474 outputDesc->mSamplingRate = samplingRate;
475 outputDesc->mFormat = format;
476 outputDesc->mChannels = channels;
477 outputDesc->mLatency = 0;
478 outputDesc->mFlags = (AudioSystem::output_flags)(flags | AudioSystem::OUTPUT_FLAG_DIRECT);
Eric Laurentef9500f2010-03-11 14:47:00 -0800479 outputDesc->mRefCount[stream] = 0;
Eric Laurent25101b02011-02-02 09:33:30 -0800480 outputDesc->mStopTime[stream] = 0;
Eric Laurentcef3cd72009-12-10 01:03:50 -0800481 output = mpClientInterface->openOutput(&outputDesc->mDevice,
482 &outputDesc->mSamplingRate,
483 &outputDesc->mFormat,
484 &outputDesc->mChannels,
485 &outputDesc->mLatency,
486 outputDesc->mFlags);
487
488 // only accept an output with the requeted parameters
489 if (output == 0 ||
490 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
491 (format != 0 && format != outputDesc->mFormat) ||
492 (channels != 0 && channels != outputDesc->mChannels)) {
493 LOGV("getOutput() failed opening direct output: samplingRate %d, format %d, channels %d",
494 samplingRate, format, channels);
495 if (output != 0) {
496 mpClientInterface->closeOutput(output);
497 }
498 delete outputDesc;
499 return 0;
500 }
501 addOutput(output, outputDesc);
502 return output;
503 }
504
505 if (channels != 0 && channels != AudioSystem::CHANNEL_OUT_MONO &&
506 channels != AudioSystem::CHANNEL_OUT_STEREO) {
507 return 0;
508 }
509 // open a non direct output
510
511 // get which output is suitable for the specified stream. The actual routing change will happen
512 // when startOutput() will be called
513 uint32_t a2dpDevice = device & AudioSystem::DEVICE_OUT_ALL_A2DP;
514 if (AudioSystem::popCount((AudioSystem::audio_devices)device) == 2) {
515#ifdef WITH_A2DP
516 if (a2dpUsedForSonification() && a2dpDevice != 0) {
517 // if playing on 2 devices among which one is A2DP, use duplicated output
518 LOGV("getOutput() using duplicated output");
519 LOGW_IF((mA2dpOutput == 0), "getOutput() A2DP device in multiple %x selected but A2DP output not opened", device);
520 output = mDuplicatedOutput;
521 } else
522#endif
523 {
524 // if playing on 2 devices among which none is A2DP, use hardware output
525 output = mHardwareOutput;
526 }
527 LOGV("getOutput() using output %d for 2 devices %x", output, device);
528 } else {
529#ifdef WITH_A2DP
530 if (a2dpDevice != 0) {
531 // if playing on A2DP device, use a2dp output
532 LOGW_IF((mA2dpOutput == 0), "getOutput() A2DP device %x selected but A2DP output not opened", device);
533 output = mA2dpOutput;
534 } else
535#endif
536 {
537 // if playing on not A2DP device, use hardware output
538 output = mHardwareOutput;
539 }
540 }
541
542
543 LOGW_IF((output ==0), "getOutput() could not find output for stream %d, samplingRate %d, format %d, channels %x, flags %x",
544 stream, samplingRate, format, channels, flags);
545
546 return output;
547}
548
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700549status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
550 AudioSystem::stream_type stream,
551 int session)
Eric Laurentcef3cd72009-12-10 01:03:50 -0800552{
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700553 LOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
Eric Laurentcef3cd72009-12-10 01:03:50 -0800554 ssize_t index = mOutputs.indexOfKey(output);
555 if (index < 0) {
556 LOGW("startOutput() unknow output %d", output);
557 return BAD_VALUE;
558 }
559
560 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
561 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
562
563#ifdef WITH_A2DP
564 if (mA2dpOutput != 0 && !a2dpUsedForSonification() && strategy == STRATEGY_SONIFICATION) {
565 setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput);
566 }
567#endif
568
569 // incremenent usage count for this stream on the requested output:
570 // NOTE that the usage count is the same for duplicated output and hardware output which is
571 // necassary for a correct control of hardware output routing by startOutput() and stopOutput()
572 outputDesc->changeRefCount(stream, 1);
573
574 setOutputDevice(output, getNewDevice(output));
575
576 // handle special case for sonification while in call
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -0800577 if (isInCall()) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800578 handleIncallSonification(stream, true, false);
579 }
580
581 // apply volume rules for current stream and device if necessary
582 checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, outputDesc->device());
583
584 return NO_ERROR;
585}
586
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700587status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
588 AudioSystem::stream_type stream,
589 int session)
Eric Laurentcef3cd72009-12-10 01:03:50 -0800590{
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700591 LOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
Eric Laurentcef3cd72009-12-10 01:03:50 -0800592 ssize_t index = mOutputs.indexOfKey(output);
593 if (index < 0) {
594 LOGW("stopOutput() unknow output %d", output);
595 return BAD_VALUE;
596 }
597
598 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
599 routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
600
601 // handle special case for sonification while in call
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -0800602 if (isInCall()) {
Eric Laurentcef3cd72009-12-10 01:03:50 -0800603 handleIncallSonification(stream, false, false);
604 }
605
606 if (outputDesc->mRefCount[stream] > 0) {
607 // decrement usage count of this stream on the output
608 outputDesc->changeRefCount(stream, -1);
Eric Laurent25101b02011-02-02 09:33:30 -0800609 // store time at which the stream was stopped - see isStreamActive()
610 outputDesc->mStopTime[stream] = systemTime();
Eric Laurentcef3cd72009-12-10 01:03:50 -0800611
612 setOutputDevice(output, getNewDevice(output));
613
614#ifdef WITH_A2DP
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700615 if (mA2dpOutput != 0 && !a2dpUsedForSonification() &&
616 strategy == STRATEGY_SONIFICATION) {
617 setStrategyMute(STRATEGY_MEDIA,
618 false,
619 mA2dpOutput,
620 mOutputs.valueFor(mHardwareOutput)->mLatency*2);
Eric Laurentcef3cd72009-12-10 01:03:50 -0800621 }
622#endif
Eric Laurentef9500f2010-03-11 14:47:00 -0800623 if (output != mHardwareOutput) {
624 setOutputDevice(mHardwareOutput, getNewDevice(mHardwareOutput), true);
625 }
Eric Laurentcef3cd72009-12-10 01:03:50 -0800626 return NO_ERROR;
627 } else {
628 LOGW("stopOutput() refcount is already 0 for output %d", output);
629 return INVALID_OPERATION;
630 }
631}
632
633void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
634{
635 LOGV("releaseOutput() %d", output);
636 ssize_t index = mOutputs.indexOfKey(output);
637 if (index < 0) {
638 LOGW("releaseOutput() releasing unknown output %d", output);
639 return;
640 }
641
642#ifdef AUDIO_POLICY_TEST
643 int testIndex = testOutputIndex(output);
644 if (testIndex != 0) {
645 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
646 if (outputDesc->refCount() == 0) {
647 mpClientInterface->closeOutput(output);
648 delete mOutputs.valueAt(index);
649 mOutputs.removeItem(output);
650 mTestOutputs[testIndex] = 0;
651 }
652 return;
653 }
654#endif //AUDIO_POLICY_TEST
655
656 if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
657 mpClientInterface->closeOutput(output);
658 delete mOutputs.valueAt(index);
659 mOutputs.removeItem(output);
660 }
661}
662
663audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
664 uint32_t samplingRate,
665 uint32_t format,
666 uint32_t channels,
667 AudioSystem::audio_in_acoustics acoustics)
668{
669 audio_io_handle_t input = 0;
670 uint32_t device = getDeviceForInputSource(inputSource);
671
672 LOGV("getInput() inputSource %d, samplingRate %d, format %d, channels %x, acoustics %x", inputSource, samplingRate, format, channels, acoustics);
673
674 if (device == 0) {
675 return 0;
676 }
677
678 // adapt channel selection to input source
679 switch(inputSource) {
680 case AUDIO_SOURCE_VOICE_UPLINK:
681 channels = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
682 break;
683 case AUDIO_SOURCE_VOICE_DOWNLINK:
684 channels = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
685 break;
686 case AUDIO_SOURCE_VOICE_CALL:
687 channels = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
688 break;
689 default:
690 break;
691 }
692
693 AudioInputDescriptor *inputDesc = new AudioInputDescriptor();
694
695 inputDesc->mInputSource = inputSource;
696 inputDesc->mDevice = device;
697 inputDesc->mSamplingRate = samplingRate;
698 inputDesc->mFormat = format;
699 inputDesc->mChannels = channels;
700 inputDesc->mAcoustics = acoustics;
701 inputDesc->mRefCount = 0;
702 input = mpClientInterface->openInput(&inputDesc->mDevice,
703 &inputDesc->mSamplingRate,
704 &inputDesc->mFormat,
705 &inputDesc->mChannels,
706 inputDesc->mAcoustics);
707
708 // only accept input with the exact requested set of parameters
709 if (input == 0 ||
710 (samplingRate != inputDesc->mSamplingRate) ||
711 (format != inputDesc->mFormat) ||
712 (channels != inputDesc->mChannels)) {
713 LOGV("getInput() failed opening input: samplingRate %d, format %d, channels %d",
714 samplingRate, format, channels);
715 if (input != 0) {
716 mpClientInterface->closeInput(input);
717 }
718 delete inputDesc;
719 return 0;
720 }
721 mInputs.add(input, inputDesc);
722 return input;
723}
724
725status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
726{
727 LOGV("startInput() input %d", input);
728 ssize_t index = mInputs.indexOfKey(input);
729 if (index < 0) {
730 LOGW("startInput() unknow input %d", input);
731 return BAD_VALUE;
732 }
733 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
734
735#ifdef AUDIO_POLICY_TEST
736 if (mTestInput == 0)
737#endif //AUDIO_POLICY_TEST
738 {
739 // refuse 2 active AudioRecord clients at the same time
740 if (getActiveInput() != 0) {
741 LOGW("startInput() input %d failed: other input already started", input);
742 return INVALID_OPERATION;
743 }
744 }
745
746 AudioParameter param = AudioParameter();
747 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
748
Jean-Michel Trivi1a22bdb2010-11-09 14:06:52 -0800749 param.addInt(String8(AudioParameter::keyInputSource), (int)inputDesc->mInputSource);
750 LOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
Eric Laurentcef3cd72009-12-10 01:03:50 -0800751
752 mpClientInterface->setParameters(input, param.toString());
753
754 inputDesc->mRefCount = 1;
755 return NO_ERROR;
756}
757
758status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
759{
760 LOGV("stopInput() input %d", input);
761 ssize_t index = mInputs.indexOfKey(input);
762 if (index < 0) {
763 LOGW("stopInput() unknow input %d", input);
764 return BAD_VALUE;
765 }
766 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
767
768 if (inputDesc->mRefCount == 0) {
769 LOGW("stopInput() input %d already stopped", input);
770 return INVALID_OPERATION;
771 } else {
772 AudioParameter param = AudioParameter();
773 param.addInt(String8(AudioParameter::keyRouting), 0);
774 mpClientInterface->setParameters(input, param.toString());
775 inputDesc->mRefCount = 0;
776 return NO_ERROR;
777 }
778}
779
780void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
781{
782 LOGV("releaseInput() %d", input);
783 ssize_t index = mInputs.indexOfKey(input);
784 if (index < 0) {
785 LOGW("releaseInput() releasing unknown input %d", input);
786 return;
787 }
788 mpClientInterface->closeInput(input);
789 delete mInputs.valueAt(index);
790 mInputs.removeItem(input);
791 LOGV("releaseInput() exit");
792}
793
794void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
795 int indexMin,
796 int indexMax)
797{
798 LOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
799 if (indexMin < 0 || indexMin >= indexMax) {
800 LOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
801 return;
802 }
803 mStreams[stream].mIndexMin = indexMin;
804 mStreams[stream].mIndexMax = indexMax;
805}
806
807status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream, int index)
808{
809
810 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
811 return BAD_VALUE;
812 }
813
814 // Force max volume if stream cannot be muted
815 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
816
817 LOGV("setStreamVolumeIndex() stream %d, index %d", stream, index);
818 mStreams[stream].mIndexCur = index;
819
820 // compute and apply stream volume on all outputs according to connected device
821 status_t status = NO_ERROR;
822 for (size_t i = 0; i < mOutputs.size(); i++) {
823 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), mOutputs.valueAt(i)->device());
824 if (volStatus != NO_ERROR) {
825 status = volStatus;
826 }
827 }
828 return status;
829}
830
831status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream, int *index)
832{
833 if (index == 0) {
834 return BAD_VALUE;
835 }
836 LOGV("getStreamVolumeIndex() stream %d", stream);
837 *index = mStreams[stream].mIndexCur;
838 return NO_ERROR;
839}
840
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700841audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(effect_descriptor_t *desc)
842{
843 LOGV("getOutputForEffect()");
844 // apply simple rule where global effects are attached to the same output as MUSIC streams
845 return getOutput(AudioSystem::MUSIC);
846}
847
848status_t AudioPolicyManagerBase::registerEffect(effect_descriptor_t *desc,
849 audio_io_handle_t output,
850 uint32_t strategy,
851 int session,
852 int id)
853{
854 ssize_t index = mOutputs.indexOfKey(output);
855 if (index < 0) {
856 LOGW("registerEffect() unknown output %d", output);
857 return INVALID_OPERATION;
858 }
859
860 if (mTotalEffectsCpuLoad + desc->cpuLoad > getMaxEffectsCpuLoad()) {
861 LOGW("registerEffect() CPU Load limit exceeded for Fx %s, CPU %f MIPS",
862 desc->name, (float)desc->cpuLoad/10);
863 return INVALID_OPERATION;
864 }
865 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
866 LOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
867 desc->name, desc->memoryUsage);
868 return INVALID_OPERATION;
869 }
870 mTotalEffectsCpuLoad += desc->cpuLoad;
871 mTotalEffectsMemory += desc->memoryUsage;
872 LOGV("registerEffect() effect %s, output %d, strategy %d session %d id %d",
873 desc->name, output, strategy, session, id);
874
875 LOGV("registerEffect() CPU %d, memory %d", desc->cpuLoad, desc->memoryUsage);
876 LOGV(" total CPU %d, total memory %d", mTotalEffectsCpuLoad, mTotalEffectsMemory);
877
878 EffectDescriptor *pDesc = new EffectDescriptor();
879 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
880 pDesc->mOutput = output;
881 pDesc->mStrategy = (routing_strategy)strategy;
882 pDesc->mSession = session;
883 mEffects.add(id, pDesc);
884
885 return NO_ERROR;
886}
887
888status_t AudioPolicyManagerBase::unregisterEffect(int id)
889{
890 ssize_t index = mEffects.indexOfKey(id);
891 if (index < 0) {
892 LOGW("unregisterEffect() unknown effect ID %d", id);
893 return INVALID_OPERATION;
894 }
895
896 EffectDescriptor *pDesc = mEffects.valueAt(index);
897
898 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
899 LOGW("unregisterEffect() CPU load %d too high for total %d",
900 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
901 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
902 }
903 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
904 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
905 LOGW("unregisterEffect() memory %d too big for total %d",
906 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
907 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
908 }
909 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
910 LOGV("unregisterEffect() effect %s, ID %d, CPU %d, memory %d",
911 pDesc->mDesc.name, id, pDesc->mDesc.cpuLoad, pDesc->mDesc.memoryUsage);
912 LOGV(" total CPU %d, total memory %d", mTotalEffectsCpuLoad, mTotalEffectsMemory);
913
914 mEffects.removeItem(id);
915 delete pDesc;
916
917 return NO_ERROR;
918}
919
Eric Laurent25101b02011-02-02 09:33:30 -0800920bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
921{
922 nsecs_t sysTime = systemTime();
923 for (size_t i = 0; i < mOutputs.size(); i++) {
924 if (mOutputs.valueAt(i)->mRefCount[stream] != 0 ||
925 ns2ms(sysTime - mOutputs.valueAt(i)->mStopTime[stream]) < inPastMs) {
926 return true;
927 }
928 }
929 return false;
930}
931
932
Eric Laurentcef3cd72009-12-10 01:03:50 -0800933status_t AudioPolicyManagerBase::dump(int fd)
934{
935 const size_t SIZE = 256;
936 char buffer[SIZE];
937 String8 result;
938
939 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
940 result.append(buffer);
941 snprintf(buffer, SIZE, " Hardware Output: %d\n", mHardwareOutput);
942 result.append(buffer);
943#ifdef WITH_A2DP
944 snprintf(buffer, SIZE, " A2DP Output: %d\n", mA2dpOutput);
945 result.append(buffer);
946 snprintf(buffer, SIZE, " Duplicated Output: %d\n", mDuplicatedOutput);
947 result.append(buffer);
948 snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
949 result.append(buffer);
950#endif
951 snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
952 result.append(buffer);
953 snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
954 result.append(buffer);
955 snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
956 result.append(buffer);
957 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
958 result.append(buffer);
959 snprintf(buffer, SIZE, " Ringer mode: %d\n", mRingerMode);
960 result.append(buffer);
961 snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
962 result.append(buffer);
963 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
964 result.append(buffer);
965 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
966 result.append(buffer);
967 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
968 result.append(buffer);
969 write(fd, result.string(), result.size());
970
971 snprintf(buffer, SIZE, "\nOutputs dump:\n");
972 write(fd, buffer, strlen(buffer));
973 for (size_t i = 0; i < mOutputs.size(); i++) {
974 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
975 write(fd, buffer, strlen(buffer));
976 mOutputs.valueAt(i)->dump(fd);
977 }
978
979 snprintf(buffer, SIZE, "\nInputs dump:\n");
980 write(fd, buffer, strlen(buffer));
981 for (size_t i = 0; i < mInputs.size(); i++) {
982 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
983 write(fd, buffer, strlen(buffer));
984 mInputs.valueAt(i)->dump(fd);
985 }
986
987 snprintf(buffer, SIZE, "\nStreams dump:\n");
988 write(fd, buffer, strlen(buffer));
989 snprintf(buffer, SIZE, " Stream Index Min Index Max Index Cur Can be muted\n");
990 write(fd, buffer, strlen(buffer));
991 for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
992 snprintf(buffer, SIZE, " %02d", i);
993 mStreams[i].dump(buffer + 3, SIZE);
994 write(fd, buffer, strlen(buffer));
995 }
996
Eric Laurent8ed6ed02010-07-13 04:45:46 -0700997 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
998 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
999 write(fd, buffer, strlen(buffer));
1000
1001 snprintf(buffer, SIZE, "Registered effects:\n");
1002 write(fd, buffer, strlen(buffer));
1003 for (size_t i = 0; i < mEffects.size(); i++) {
1004 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1005 write(fd, buffer, strlen(buffer));
1006 mEffects.valueAt(i)->dump(fd);
1007 }
1008
1009
Eric Laurentcef3cd72009-12-10 01:03:50 -08001010 return NO_ERROR;
1011}
1012
1013// ----------------------------------------------------------------------------
1014// AudioPolicyManagerBase
1015// ----------------------------------------------------------------------------
1016
1017AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1018 :
1019#ifdef AUDIO_POLICY_TEST
1020 Thread(false),
1021#endif //AUDIO_POLICY_TEST
Eric Laurentfad77872010-12-01 12:11:10 -08001022 mPhoneState(AudioSystem::MODE_NORMAL), mRingerMode(0),
Eric Laurent25101b02011-02-02 09:33:30 -08001023 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurentfad77872010-12-01 12:11:10 -08001024 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurentb87b53d2010-11-02 12:02:20 -07001025 mA2dpSuspended(false)
Eric Laurentcef3cd72009-12-10 01:03:50 -08001026{
1027 mpClientInterface = clientInterface;
1028
1029 for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1030 mForceUse[i] = AudioSystem::FORCE_NONE;
1031 }
1032
1033 // devices available by default are speaker, ear piece and microphone
1034 mAvailableOutputDevices = AudioSystem::DEVICE_OUT_EARPIECE |
1035 AudioSystem::DEVICE_OUT_SPEAKER;
1036 mAvailableInputDevices = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1037
1038#ifdef WITH_A2DP
1039 mA2dpOutput = 0;
1040 mDuplicatedOutput = 0;
1041 mA2dpDeviceAddress = String8("");
1042#endif
1043 mScoDeviceAddress = String8("");
1044
1045 // open hardware output
1046 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1047 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1048 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1049 &outputDesc->mSamplingRate,
1050 &outputDesc->mFormat,
1051 &outputDesc->mChannels,
1052 &outputDesc->mLatency,
1053 outputDesc->mFlags);
1054
1055 if (mHardwareOutput == 0) {
1056 LOGE("Failed to initialize hardware output stream, samplingRate: %d, format %d, channels %d",
1057 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
1058 } else {
1059 addOutput(mHardwareOutput, outputDesc);
1060 setOutputDevice(mHardwareOutput, (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER, true);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001061 //TODO: configure audio effect output stage here
Eric Laurentcef3cd72009-12-10 01:03:50 -08001062 }
1063
1064 updateDeviceForStrategy();
1065#ifdef AUDIO_POLICY_TEST
Eric Laurent01635942011-01-18 18:39:02 -08001066 if (mHardwareOutput != 0) {
1067 AudioParameter outputCmd = AudioParameter();
1068 outputCmd.addInt(String8("set_id"), 0);
1069 mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString());
Eric Laurentcef3cd72009-12-10 01:03:50 -08001070
Eric Laurent01635942011-01-18 18:39:02 -08001071 mTestDevice = AudioSystem::DEVICE_OUT_SPEAKER;
1072 mTestSamplingRate = 44100;
1073 mTestFormat = AudioSystem::PCM_16_BIT;
1074 mTestChannels = AudioSystem::CHANNEL_OUT_STEREO;
1075 mTestLatencyMs = 0;
1076 mCurOutput = 0;
1077 mDirectOutput = false;
1078 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1079 mTestOutputs[i] = 0;
1080 }
1081
1082 const size_t SIZE = 256;
1083 char buffer[SIZE];
1084 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1085 run(buffer, ANDROID_PRIORITY_AUDIO);
Eric Laurentcef3cd72009-12-10 01:03:50 -08001086 }
Eric Laurentcef3cd72009-12-10 01:03:50 -08001087#endif //AUDIO_POLICY_TEST
1088}
1089
1090AudioPolicyManagerBase::~AudioPolicyManagerBase()
1091{
1092#ifdef AUDIO_POLICY_TEST
1093 exit();
1094#endif //AUDIO_POLICY_TEST
1095 for (size_t i = 0; i < mOutputs.size(); i++) {
1096 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1097 delete mOutputs.valueAt(i);
1098 }
1099 mOutputs.clear();
1100 for (size_t i = 0; i < mInputs.size(); i++) {
1101 mpClientInterface->closeInput(mInputs.keyAt(i));
1102 delete mInputs.valueAt(i);
1103 }
1104 mInputs.clear();
1105}
1106
Eric Laurent01635942011-01-18 18:39:02 -08001107status_t AudioPolicyManagerBase::initCheck()
1108{
1109 return (mHardwareOutput == 0) ? NO_INIT : NO_ERROR;
1110}
1111
Eric Laurentcef3cd72009-12-10 01:03:50 -08001112#ifdef AUDIO_POLICY_TEST
1113bool AudioPolicyManagerBase::threadLoop()
1114{
1115 LOGV("entering threadLoop()");
1116 while (!exitPending())
1117 {
1118 String8 command;
1119 int valueInt;
1120 String8 value;
1121
1122 Mutex::Autolock _l(mLock);
1123 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1124
1125 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1126 AudioParameter param = AudioParameter(command);
1127
1128 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1129 valueInt != 0) {
1130 LOGV("Test command %s received", command.string());
1131 String8 target;
1132 if (param.get(String8("target"), target) != NO_ERROR) {
1133 target = "Manager";
1134 }
1135 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1136 param.remove(String8("test_cmd_policy_output"));
1137 mCurOutput = valueInt;
1138 }
1139 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1140 param.remove(String8("test_cmd_policy_direct"));
1141 if (value == "false") {
1142 mDirectOutput = false;
1143 } else if (value == "true") {
1144 mDirectOutput = true;
1145 }
1146 }
1147 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1148 param.remove(String8("test_cmd_policy_input"));
1149 mTestInput = valueInt;
1150 }
1151
1152 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1153 param.remove(String8("test_cmd_policy_format"));
1154 int format = AudioSystem::INVALID_FORMAT;
1155 if (value == "PCM 16 bits") {
1156 format = AudioSystem::PCM_16_BIT;
1157 } else if (value == "PCM 8 bits") {
1158 format = AudioSystem::PCM_8_BIT;
1159 } else if (value == "Compressed MP3") {
1160 format = AudioSystem::MP3;
1161 }
1162 if (format != AudioSystem::INVALID_FORMAT) {
1163 if (target == "Manager") {
1164 mTestFormat = format;
1165 } else if (mTestOutputs[mCurOutput] != 0) {
1166 AudioParameter outputParam = AudioParameter();
1167 outputParam.addInt(String8("format"), format);
1168 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1169 }
1170 }
1171 }
1172 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1173 param.remove(String8("test_cmd_policy_channels"));
1174 int channels = 0;
1175
1176 if (value == "Channels Stereo") {
1177 channels = AudioSystem::CHANNEL_OUT_STEREO;
1178 } else if (value == "Channels Mono") {
1179 channels = AudioSystem::CHANNEL_OUT_MONO;
1180 }
1181 if (channels != 0) {
1182 if (target == "Manager") {
1183 mTestChannels = channels;
1184 } else if (mTestOutputs[mCurOutput] != 0) {
1185 AudioParameter outputParam = AudioParameter();
1186 outputParam.addInt(String8("channels"), channels);
1187 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1188 }
1189 }
1190 }
1191 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1192 param.remove(String8("test_cmd_policy_sampleRate"));
1193 if (valueInt >= 0 && valueInt <= 96000) {
1194 int samplingRate = valueInt;
1195 if (target == "Manager") {
1196 mTestSamplingRate = samplingRate;
1197 } else if (mTestOutputs[mCurOutput] != 0) {
1198 AudioParameter outputParam = AudioParameter();
1199 outputParam.addInt(String8("sampling_rate"), samplingRate);
1200 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1201 }
1202 }
1203 }
1204
1205 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1206 param.remove(String8("test_cmd_policy_reopen"));
1207
1208 mpClientInterface->closeOutput(mHardwareOutput);
1209 delete mOutputs.valueFor(mHardwareOutput);
1210 mOutputs.removeItem(mHardwareOutput);
1211
1212 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1213 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1214 mHardwareOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1215 &outputDesc->mSamplingRate,
1216 &outputDesc->mFormat,
1217 &outputDesc->mChannels,
1218 &outputDesc->mLatency,
1219 outputDesc->mFlags);
1220 if (mHardwareOutput == 0) {
1221 LOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1222 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannels);
1223 } else {
1224 AudioParameter outputCmd = AudioParameter();
1225 outputCmd.addInt(String8("set_id"), 0);
1226 mpClientInterface->setParameters(mHardwareOutput, outputCmd.toString());
1227 addOutput(mHardwareOutput, outputDesc);
1228 }
1229 }
1230
1231
1232 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1233 }
1234 }
1235 return false;
1236}
1237
1238void AudioPolicyManagerBase::exit()
1239{
1240 {
1241 AutoMutex _l(mLock);
1242 requestExit();
1243 mWaitWorkCV.signal();
1244 }
1245 requestExitAndWait();
1246}
1247
1248int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1249{
1250 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1251 if (output == mTestOutputs[i]) return i;
1252 }
1253 return 0;
1254}
1255#endif //AUDIO_POLICY_TEST
1256
1257// ---
1258
1259void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1260{
1261 outputDesc->mId = id;
1262 mOutputs.add(id, outputDesc);
1263}
1264
1265
1266#ifdef WITH_A2DP
1267status_t AudioPolicyManagerBase::handleA2dpConnection(AudioSystem::audio_devices device,
1268 const char *device_address)
1269{
1270 // when an A2DP device is connected, open an A2DP and a duplicated output
1271 LOGV("opening A2DP output for device %s", device_address);
1272 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor();
1273 outputDesc->mDevice = device;
1274 mA2dpOutput = mpClientInterface->openOutput(&outputDesc->mDevice,
1275 &outputDesc->mSamplingRate,
1276 &outputDesc->mFormat,
1277 &outputDesc->mChannels,
1278 &outputDesc->mLatency,
1279 outputDesc->mFlags);
1280 if (mA2dpOutput) {
1281 // add A2DP output descriptor
1282 addOutput(mA2dpOutput, outputDesc);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001283
1284 //TODO: configure audio effect output stage here
1285
Eric Laurentcef3cd72009-12-10 01:03:50 -08001286 // set initial stream volume for A2DP device
1287 applyStreamVolumes(mA2dpOutput, device);
1288 if (a2dpUsedForSonification()) {
1289 mDuplicatedOutput = mpClientInterface->openDuplicateOutput(mA2dpOutput, mHardwareOutput);
1290 }
1291 if (mDuplicatedOutput != 0 ||
1292 !a2dpUsedForSonification()) {
1293 // If both A2DP and duplicated outputs are open, send device address to A2DP hardware
1294 // interface
1295 AudioParameter param;
1296 param.add(String8("a2dp_sink_address"), String8(device_address));
1297 mpClientInterface->setParameters(mA2dpOutput, param.toString());
1298 mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
1299
1300 if (a2dpUsedForSonification()) {
1301 // add duplicated output descriptor
1302 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor();
1303 dupOutputDesc->mOutput1 = mOutputs.valueFor(mHardwareOutput);
1304 dupOutputDesc->mOutput2 = mOutputs.valueFor(mA2dpOutput);
1305 dupOutputDesc->mSamplingRate = outputDesc->mSamplingRate;
1306 dupOutputDesc->mFormat = outputDesc->mFormat;
1307 dupOutputDesc->mChannels = outputDesc->mChannels;
1308 dupOutputDesc->mLatency = outputDesc->mLatency;
1309 addOutput(mDuplicatedOutput, dupOutputDesc);
1310 applyStreamVolumes(mDuplicatedOutput, device);
1311 }
1312 } else {
1313 LOGW("getOutput() could not open duplicated output for %d and %d",
1314 mHardwareOutput, mA2dpOutput);
1315 mpClientInterface->closeOutput(mA2dpOutput);
1316 mOutputs.removeItem(mA2dpOutput);
1317 mA2dpOutput = 0;
1318 delete outputDesc;
1319 return NO_INIT;
1320 }
1321 } else {
1322 LOGW("setDeviceConnectionState() could not open A2DP output for device %x", device);
1323 delete outputDesc;
1324 return NO_INIT;
1325 }
1326 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
1327
Eric Laurentcef3cd72009-12-10 01:03:50 -08001328 if (!a2dpUsedForSonification()) {
1329 // mute music on A2DP output if a notification or ringtone is playing
1330 uint32_t refCount = hwOutputDesc->strategyRefCount(STRATEGY_SONIFICATION);
1331 for (uint32_t i = 0; i < refCount; i++) {
1332 setStrategyMute(STRATEGY_MEDIA, true, mA2dpOutput);
1333 }
1334 }
Eric Laurentb87b53d2010-11-02 12:02:20 -07001335
1336 mA2dpSuspended = false;
1337
Eric Laurentcef3cd72009-12-10 01:03:50 -08001338 return NO_ERROR;
1339}
1340
1341status_t AudioPolicyManagerBase::handleA2dpDisconnection(AudioSystem::audio_devices device,
1342 const char *device_address)
1343{
1344 if (mA2dpOutput == 0) {
1345 LOGW("setDeviceConnectionState() disconnecting A2DP and no A2DP output!");
1346 return INVALID_OPERATION;
1347 }
1348
1349 if (mA2dpDeviceAddress != device_address) {
1350 LOGW("setDeviceConnectionState() disconnecting unknow A2DP sink address %s", device_address);
1351 return INVALID_OPERATION;
1352 }
1353
Eric Laurent22e1ca32010-02-23 09:48:31 -08001354 // mute media strategy to avoid outputting sound on hardware output while music stream
Eric Laurentcef3cd72009-12-10 01:03:50 -08001355 // is switched from A2DP output and before music is paused by music application
1356 setStrategyMute(STRATEGY_MEDIA, true, mHardwareOutput);
Eric Laurent22e1ca32010-02-23 09:48:31 -08001357 setStrategyMute(STRATEGY_MEDIA, false, mHardwareOutput, MUTE_TIME_MS);
Eric Laurentcef3cd72009-12-10 01:03:50 -08001358
1359 if (!a2dpUsedForSonification()) {
1360 // unmute music on A2DP output if a notification or ringtone is playing
1361 uint32_t refCount = mOutputs.valueFor(mHardwareOutput)->strategyRefCount(STRATEGY_SONIFICATION);
1362 for (uint32_t i = 0; i < refCount; i++) {
1363 setStrategyMute(STRATEGY_MEDIA, false, mA2dpOutput);
1364 }
1365 }
1366 mA2dpDeviceAddress = "";
Eric Laurentb87b53d2010-11-02 12:02:20 -07001367 mA2dpSuspended = false;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001368 return NO_ERROR;
1369}
1370
1371void AudioPolicyManagerBase::closeA2dpOutputs()
1372{
Praveen Bharathi21e941b2010-10-06 15:23:14 -05001373
Eric Laurentcef3cd72009-12-10 01:03:50 -08001374 LOGV("setDeviceConnectionState() closing A2DP and duplicated output!");
1375
1376 if (mDuplicatedOutput != 0) {
Eric Laurenteb8f850d2010-05-14 03:26:45 -07001377 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueFor(mDuplicatedOutput);
1378 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mHardwareOutput);
1379 // As all active tracks on duplicated output will be deleted,
1380 // and as they were also referenced on hardware output, the reference
1381 // count for their stream type must be adjusted accordingly on
1382 // hardware output.
1383 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1384 int refCount = dupOutputDesc->mRefCount[i];
1385 hwOutputDesc->changeRefCount((AudioSystem::stream_type)i,-refCount);
1386 }
1387
Eric Laurentcef3cd72009-12-10 01:03:50 -08001388 mpClientInterface->closeOutput(mDuplicatedOutput);
1389 delete mOutputs.valueFor(mDuplicatedOutput);
1390 mOutputs.removeItem(mDuplicatedOutput);
1391 mDuplicatedOutput = 0;
1392 }
1393 if (mA2dpOutput != 0) {
1394 AudioParameter param;
1395 param.add(String8("closing"), String8("true"));
1396 mpClientInterface->setParameters(mA2dpOutput, param.toString());
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001397
Eric Laurentcef3cd72009-12-10 01:03:50 -08001398 mpClientInterface->closeOutput(mA2dpOutput);
1399 delete mOutputs.valueFor(mA2dpOutput);
1400 mOutputs.removeItem(mA2dpOutput);
1401 mA2dpOutput = 0;
1402 }
1403}
1404
Eric Laurentb8453f42010-08-27 17:10:36 -07001405void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
Eric Laurentcef3cd72009-12-10 01:03:50 -08001406{
1407 uint32_t prevDevice = getDeviceForStrategy(strategy);
1408 uint32_t curDevice = getDeviceForStrategy(strategy, false);
1409 bool a2dpWasUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(prevDevice & ~AudioSystem::DEVICE_OUT_SPEAKER));
1410 bool a2dpIsUsed = AudioSystem::isA2dpDevice((AudioSystem::audio_devices)(curDevice & ~AudioSystem::DEVICE_OUT_SPEAKER));
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001411 audio_io_handle_t srcOutput = 0;
1412 audio_io_handle_t dstOutput = 0;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001413
1414 if (a2dpWasUsed && !a2dpIsUsed) {
1415 bool dupUsed = a2dpUsedForSonification() && a2dpWasUsed && (AudioSystem::popCount(prevDevice) == 2);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001416 dstOutput = mHardwareOutput;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001417 if (dupUsed) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001418 LOGV("checkOutputForStrategy() moving strategy %d from duplicated", strategy);
1419 srcOutput = mDuplicatedOutput;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001420 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001421 LOGV("checkOutputForStrategy() moving strategy %d from a2dp", strategy);
1422 srcOutput = mA2dpOutput;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001423 }
Eric Laurentcef3cd72009-12-10 01:03:50 -08001424 }
1425 if (a2dpIsUsed && !a2dpWasUsed) {
1426 bool dupUsed = a2dpUsedForSonification() && a2dpIsUsed && (AudioSystem::popCount(curDevice) == 2);
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001427 srcOutput = mHardwareOutput;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001428 if (dupUsed) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001429 LOGV("checkOutputForStrategy() moving strategy %d to duplicated", strategy);
1430 dstOutput = mDuplicatedOutput;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001431 } else {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001432 LOGV("checkOutputForStrategy() moving strategy %d to a2dp", strategy);
1433 dstOutput = mA2dpOutput;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001434 }
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001435 }
Eric Laurentcef3cd72009-12-10 01:03:50 -08001436
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001437 if (srcOutput != 0 && dstOutput != 0) {
1438 // Move effects associated to this strategy from previous output to new output
1439 for (size_t i = 0; i < mEffects.size(); i++) {
1440 EffectDescriptor *desc = mEffects.valueAt(i);
1441 if (desc->mSession != AudioSystem::SESSION_OUTPUT_STAGE &&
1442 desc->mStrategy == strategy &&
1443 desc->mOutput == srcOutput) {
1444 LOGV("checkOutputForStrategy() moving effect %d to output %d", mEffects.keyAt(i), dstOutput);
1445 mpClientInterface->moveEffects(desc->mSession, srcOutput, dstOutput);
1446 desc->mOutput = dstOutput;
1447 }
1448 }
1449 // Move tracks associated to this strategy from previous output to new output
Eric Laurentcef3cd72009-12-10 01:03:50 -08001450 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1451 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001452 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i, dstOutput);
Eric Laurentcef3cd72009-12-10 01:03:50 -08001453 }
1454 }
1455 }
1456}
1457
Eric Laurentb8453f42010-08-27 17:10:36 -07001458void AudioPolicyManagerBase::checkOutputForAllStrategies()
Eric Laurentcef3cd72009-12-10 01:03:50 -08001459{
Eric Laurentb8453f42010-08-27 17:10:36 -07001460 checkOutputForStrategy(STRATEGY_PHONE);
1461 checkOutputForStrategy(STRATEGY_SONIFICATION);
1462 checkOutputForStrategy(STRATEGY_MEDIA);
1463 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurentcef3cd72009-12-10 01:03:50 -08001464}
1465
Eric Laurentb87b53d2010-11-02 12:02:20 -07001466void AudioPolicyManagerBase::checkA2dpSuspend()
1467{
1468 // suspend A2DP output if:
1469 // (NOT already suspended) &&
1470 // ((SCO device is connected &&
1471 // (forced usage for communication || for record is SCO))) ||
1472 // (phone state is ringing || in call)
1473 //
1474 // restore A2DP output if:
1475 // (Already suspended) &&
1476 // ((SCO device is NOT connected ||
1477 // (forced usage NOT for communication && NOT for record is SCO))) &&
1478 // (phone state is NOT ringing && NOT in call)
1479 //
1480 if (mA2dpOutput == 0) {
1481 return;
1482 }
1483
1484 if (mA2dpSuspended) {
1485 if (((mScoDeviceAddress == "") ||
1486 ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
1487 (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
1488 ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
1489 (mPhoneState != AudioSystem::MODE_RINGTONE))) {
1490
1491 mpClientInterface->restoreOutput(mA2dpOutput);
1492 mA2dpSuspended = false;
1493 }
1494 } else {
1495 if (((mScoDeviceAddress != "") &&
1496 ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1497 (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
1498 ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
1499 (mPhoneState == AudioSystem::MODE_RINGTONE))) {
1500
1501 mpClientInterface->suspendOutput(mA2dpOutput);
1502 mA2dpSuspended = true;
1503 }
1504 }
1505}
1506
1507
Eric Laurentcef3cd72009-12-10 01:03:50 -08001508#endif
1509
1510uint32_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
1511{
1512 uint32_t device = 0;
1513
1514 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1515 // check the following by order of priority to request a routing change if necessary:
1516 // 1: we are in call or the strategy phone is active on the hardware output:
1517 // use device for strategy phone
1518 // 2: the strategy sonification is active on the hardware output:
1519 // use device for strategy sonification
1520 // 3: the strategy media is active on the hardware output:
1521 // use device for strategy media
1522 // 4: the strategy DTMF is active on the hardware output:
1523 // use device for strategy DTMF
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08001524 if (isInCall() ||
Eric Laurentcef3cd72009-12-10 01:03:50 -08001525 outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
1526 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
1527 } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
1528 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
1529 } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
1530 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
1531 } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
1532 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
1533 }
1534
1535 LOGV("getNewDevice() selected device %x", device);
1536 return device;
1537}
1538
Eric Laurent8ed6ed02010-07-13 04:45:46 -07001539uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
1540 return (uint32_t)getStrategy(stream);
1541}
1542
1543AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
1544 AudioSystem::stream_type stream) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001545 // stream to strategy mapping
1546 switch (stream) {
1547 case AudioSystem::VOICE_CALL:
1548 case AudioSystem::BLUETOOTH_SCO:
1549 return STRATEGY_PHONE;
1550 case AudioSystem::RING:
1551 case AudioSystem::NOTIFICATION:
1552 case AudioSystem::ALARM:
1553 case AudioSystem::ENFORCED_AUDIBLE:
1554 return STRATEGY_SONIFICATION;
1555 case AudioSystem::DTMF:
1556 return STRATEGY_DTMF;
1557 default:
1558 LOGE("unknown stream type");
1559 case AudioSystem::SYSTEM:
1560 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
1561 // while key clicks are played produces a poor result
1562 case AudioSystem::TTS:
1563 case AudioSystem::MUSIC:
1564 return STRATEGY_MEDIA;
1565 }
1566}
1567
1568uint32_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy, bool fromCache)
1569{
1570 uint32_t device = 0;
1571
1572 if (fromCache) {
1573 LOGV("getDeviceForStrategy() from cache strategy %d, device %x", strategy, mDeviceForStrategy[strategy]);
1574 return mDeviceForStrategy[strategy];
1575 }
1576
1577 switch (strategy) {
1578 case STRATEGY_DTMF:
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08001579 if (!isInCall()) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001580 // when off call, DTMF strategy follows the same rules as MEDIA strategy
1581 device = getDeviceForStrategy(STRATEGY_MEDIA, false);
1582 break;
1583 }
1584 // when in call, DTMF and PHONE strategies follow the same rules
1585 // FALL THROUGH
1586
1587 case STRATEGY_PHONE:
1588 // for phone strategy, we first consider the forced use and then the available devices by order
1589 // of priority
1590 switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
1591 case AudioSystem::FORCE_BT_SCO:
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08001592 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001593 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
1594 if (device) break;
1595 }
1596 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
1597 if (device) break;
1598 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO;
1599 if (device) break;
1600 // if SCO device is requested but no SCO device is available, fall back to default case
1601 // FALL THROUGH
1602
1603 default: // FORCE_NONE
1604 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
1605 if (device) break;
1606 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1607 if (device) break;
Eric Laurent58bf1d92011-01-09 15:33:01 -08001608 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1609 if (device) break;
1610 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1611 if (device) break;
Praveen Bharathi21e941b2010-10-06 15:23:14 -05001612 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1613 if (device) break;
Jean-Michel Trivie4b8c422010-03-13 12:33:15 -08001614#ifdef WITH_A2DP
1615 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08001616 if (!isInCall()) {
Jean-Michel Trivie4b8c422010-03-13 12:33:15 -08001617 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1618 if (device) break;
1619 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1620 if (device) break;
1621 }
1622#endif
Eric Laurentcef3cd72009-12-10 01:03:50 -08001623 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_EARPIECE;
1624 if (device == 0) {
1625 LOGE("getDeviceForStrategy() earpiece device not found");
1626 }
1627 break;
1628
1629 case AudioSystem::FORCE_SPEAKER:
Eric Laurent58bf1d92011-01-09 15:33:01 -08001630 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
1631 if (device) break;
1632 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1633 if (device) break;
Eric Laurentaef0cbb2010-12-16 09:44:42 -08001634 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1635 if (device) break;
Jean-Michel Trivie4b8c422010-03-13 12:33:15 -08001636#ifdef WITH_A2DP
1637 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
1638 // A2DP speaker when forcing to speaker output
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08001639 if (!isInCall()) {
Jean-Michel Trivie4b8c422010-03-13 12:33:15 -08001640 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1641 if (device) break;
1642 }
1643#endif
Eric Laurentcef3cd72009-12-10 01:03:50 -08001644 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1645 if (device == 0) {
1646 LOGE("getDeviceForStrategy() speaker device not found");
1647 }
1648 break;
1649 }
1650 break;
1651
1652 case STRATEGY_SONIFICATION:
1653
1654 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
1655 // handleIncallSonification().
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08001656 if (isInCall()) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001657 device = getDeviceForStrategy(STRATEGY_PHONE, false);
1658 break;
1659 }
1660 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1661 if (device == 0) {
1662 LOGE("getDeviceForStrategy() speaker device not found");
1663 }
1664 // The second device used for sonification is the same as the device used by media strategy
1665 // FALL THROUGH
1666
1667 case STRATEGY_MEDIA: {
Eric Laurent2c61bee2010-12-14 16:31:33 -08001668 uint32_t device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurentfe2e0752010-03-06 15:46:31 -08001669 if (device2 == 0) {
1670 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
1671 }
Praveen Bharathi21e941b2010-10-06 15:23:14 -05001672 if (device2 == 0) {
Eric Laurent2c61bee2010-12-14 16:31:33 -08001673 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
Praveen Bharathi21e941b2010-10-06 15:23:14 -05001674 }
1675 if (device2 == 0) {
1676 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
1677 }
Eric Laurent2c61bee2010-12-14 16:31:33 -08001678 if (device2 == 0) {
1679 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
1680 }
Eric Laurentcef3cd72009-12-10 01:03:50 -08001681#ifdef WITH_A2DP
1682 if (mA2dpOutput != 0) {
1683 if (strategy == STRATEGY_SONIFICATION && !a2dpUsedForSonification()) {
1684 break;
1685 }
1686 if (device2 == 0) {
1687 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
1688 }
1689 if (device2 == 0) {
1690 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
1691 }
1692 if (device2 == 0) {
1693 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
1694 }
1695 }
1696#endif
1697 if (device2 == 0) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001698 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
1699 }
1700
1701 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION, 0 otherwise
1702 device |= device2;
1703 if (device == 0) {
1704 LOGE("getDeviceForStrategy() speaker device not found");
1705 }
1706 } break;
1707
1708 default:
1709 LOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
1710 break;
1711 }
1712
1713 LOGV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
1714 return device;
1715}
1716
1717void AudioPolicyManagerBase::updateDeviceForStrategy()
1718{
1719 for (int i = 0; i < NUM_STRATEGIES; i++) {
1720 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false);
1721 }
1722}
1723
1724void AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output, uint32_t device, bool force, int delayMs)
1725{
1726 LOGV("setOutputDevice() output %d device %x delayMs %d", output, device, delayMs);
1727 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1728
1729
1730 if (outputDesc->isDuplicated()) {
1731 setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
1732 setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
1733 return;
1734 }
1735#ifdef WITH_A2DP
1736 // filter devices according to output selected
Eric Laurentef9500f2010-03-11 14:47:00 -08001737 if (output == mA2dpOutput) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001738 device &= AudioSystem::DEVICE_OUT_ALL_A2DP;
Eric Laurentef9500f2010-03-11 14:47:00 -08001739 } else {
1740 device &= ~AudioSystem::DEVICE_OUT_ALL_A2DP;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001741 }
1742#endif
1743
1744 uint32_t prevDevice = (uint32_t)outputDesc->device();
1745 // Do not change the routing if:
1746 // - the requestede device is 0
1747 // - the requested device is the same as current device and force is not specified.
1748 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentef9500f2010-03-11 14:47:00 -08001749 if ((device == 0 || device == prevDevice) && !force) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001750 LOGV("setOutputDevice() setting same device %x or null device for output %d", device, output);
1751 return;
1752 }
1753
1754 outputDesc->mDevice = device;
1755 // mute media streams if both speaker and headset are selected
1756 if (output == mHardwareOutput && AudioSystem::popCount(device) == 2) {
1757 setStrategyMute(STRATEGY_MEDIA, true, output);
1758 // wait for the PCM output buffers to empty before proceeding with the rest of the command
1759 usleep(outputDesc->mLatency*2*1000);
1760 }
Eric Laurentb87b53d2010-11-02 12:02:20 -07001761
Eric Laurentcef3cd72009-12-10 01:03:50 -08001762 // do the routing
1763 AudioParameter param = AudioParameter();
1764 param.addInt(String8(AudioParameter::keyRouting), (int)device);
1765 mpClientInterface->setParameters(mHardwareOutput, param.toString(), delayMs);
1766 // update stream volumes according to new device
1767 applyStreamVolumes(output, device, delayMs);
1768
Eric Laurentcef3cd72009-12-10 01:03:50 -08001769 // if changing from a combined headset + speaker route, unmute media streams
1770 if (output == mHardwareOutput && AudioSystem::popCount(prevDevice) == 2) {
1771 setStrategyMute(STRATEGY_MEDIA, false, output, delayMs);
1772 }
1773}
1774
1775uint32_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
1776{
1777 uint32_t device;
1778
1779 switch(inputSource) {
1780 case AUDIO_SOURCE_DEFAULT:
1781 case AUDIO_SOURCE_MIC:
1782 case AUDIO_SOURCE_VOICE_RECOGNITION:
Jean-Michel Trivi820b9e02010-11-08 18:38:14 -08001783 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurentcef3cd72009-12-10 01:03:50 -08001784 if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
1785 mAvailableInputDevices & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
1786 device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
1787 } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_WIRED_HEADSET) {
1788 device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
1789 } else {
1790 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1791 }
1792 break;
1793 case AUDIO_SOURCE_CAMCORDER:
1794 if (hasBackMicrophone()) {
1795 device = AudioSystem::DEVICE_IN_BACK_MIC;
1796 } else {
1797 device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
1798 }
1799 break;
1800 case AUDIO_SOURCE_VOICE_UPLINK:
1801 case AUDIO_SOURCE_VOICE_DOWNLINK:
1802 case AUDIO_SOURCE_VOICE_CALL:
1803 device = AudioSystem::DEVICE_IN_VOICE_CALL;
1804 break;
1805 default:
1806 LOGW("getInput() invalid input source %d", inputSource);
1807 device = 0;
1808 break;
1809 }
1810 LOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
1811 return device;
1812}
1813
1814audio_io_handle_t AudioPolicyManagerBase::getActiveInput()
1815{
1816 for (size_t i = 0; i < mInputs.size(); i++) {
1817 if (mInputs.valueAt(i)->mRefCount > 0) {
1818 return mInputs.keyAt(i);
1819 }
1820 }
1821 return 0;
1822}
1823
1824float AudioPolicyManagerBase::computeVolume(int stream, int index, audio_io_handle_t output, uint32_t device)
1825{
1826 float volume = 1.0;
1827 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1828 StreamDescriptor &streamDesc = mStreams[stream];
1829
1830 if (device == 0) {
1831 device = outputDesc->device();
1832 }
1833
1834 int volInt = (100 * (index - streamDesc.mIndexMin)) / (streamDesc.mIndexMax - streamDesc.mIndexMin);
1835 volume = AudioSystem::linearToLog(volInt);
1836
Eric Laurentef9500f2010-03-11 14:47:00 -08001837 // if a headset is connected, apply the following rules to ring tones and notifications
Eric Laurentcef3cd72009-12-10 01:03:50 -08001838 // to avoid sound level bursts in user's ears:
1839 // - always attenuate ring tones and notifications volume by 6dB
1840 // - if music is playing, always limit the volume to current music volume,
1841 // with a minimum threshold at -36dB so that notification is always perceived.
1842 if ((device &
1843 (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP |
1844 AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
1845 AudioSystem::DEVICE_OUT_WIRED_HEADSET |
Praveen Bharathi21e941b2010-10-06 15:23:14 -05001846 AudioSystem::DEVICE_OUT_WIRED_HEADPHONE |
1847 AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET |
1848 AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET)) &&
Eric Laurent111df672011-01-27 11:32:34 -08001849 ((getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) ||
1850 (stream == AudioSystem::SYSTEM)) &&
Eric Laurentcef3cd72009-12-10 01:03:50 -08001851 streamDesc.mCanBeMuted) {
1852 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
1853 // when the phone is ringing we must consider that music could have been paused just before
1854 // by the music application and behave as if music was active if the last music track was
1855 // just stopped
1856 if (outputDesc->mRefCount[AudioSystem::MUSIC] || mLimitRingtoneVolume) {
1857 float musicVol = computeVolume(AudioSystem::MUSIC, mStreams[AudioSystem::MUSIC].mIndexCur, output, device);
1858 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ? musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
1859 if (volume > minVol) {
1860 volume = minVol;
1861 LOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
1862 }
1863 }
1864 }
1865
1866 return volume;
1867}
1868
1869status_t AudioPolicyManagerBase::checkAndSetVolume(int stream, int index, audio_io_handle_t output, uint32_t device, int delayMs, bool force)
1870{
1871
1872 // do not change actual stream volume if the stream is muted
1873 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
1874 LOGV("checkAndSetVolume() stream %d muted count %d", stream, mOutputs.valueFor(output)->mMuteCount[stream]);
1875 return NO_ERROR;
1876 }
1877
1878 // do not change in call volume if bluetooth is connected and vice versa
1879 if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1880 (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
1881 LOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
1882 stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
1883 return INVALID_OPERATION;
1884 }
1885
1886 float volume = computeVolume(stream, index, output, device);
Eric Laurentcc9c4242010-05-25 09:31:59 -07001887 // We actually change the volume if:
1888 // - the float value returned by computeVolume() changed
1889 // - the force flag is set
1890 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
1891 force) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001892 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
1893 LOGV("setStreamVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
1894 if (stream == AudioSystem::VOICE_CALL ||
1895 stream == AudioSystem::DTMF ||
1896 stream == AudioSystem::BLUETOOTH_SCO) {
Eric Laurentcef3cd72009-12-10 01:03:50 -08001897 // offset value to reflect actual hardware volume that never reaches 0
1898 // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
1899 volume = 0.01 + 0.99 * volume;
Eric Laurentcef3cd72009-12-10 01:03:50 -08001900 }
1901 mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
1902 }
1903
Eric Laurentcc9c4242010-05-25 09:31:59 -07001904 if (stream == AudioSystem::VOICE_CALL ||
1905 stream == AudioSystem::BLUETOOTH_SCO) {
1906 float voiceVolume;
1907 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
1908 if (stream == AudioSystem::VOICE_CALL) {
1909 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
1910 } else {
1911 voiceVolume = 1.0;
1912 }
1913 if (voiceVolume != mLastVoiceVolume && output == mHardwareOutput) {
1914 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
1915 mLastVoiceVolume = voiceVolume;
1916 }
1917 }
1918
Eric Laurentcef3cd72009-12-10 01:03:50 -08001919 return NO_ERROR;
1920}
1921
1922void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output, uint32_t device, int delayMs)
1923{
1924 LOGV("applyStreamVolumes() for output %d and device %x", output, device);
1925
1926 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
1927 checkAndSetVolume(stream, mStreams[stream].mIndexCur, output, device, delayMs);
1928 }
1929}
1930
1931void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy, bool on, audio_io_handle_t output, int delayMs)
1932{
1933 LOGV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
1934 for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
1935 if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
1936 setStreamMute(stream, on, output, delayMs);
1937 }
1938 }
1939}
1940
1941void AudioPolicyManagerBase::setStreamMute(int stream, bool on, audio_io_handle_t output, int delayMs)
1942{
1943 StreamDescriptor &streamDesc = mStreams[stream];
1944 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1945
1946 LOGV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d", stream, on, output, outputDesc->mMuteCount[stream]);
1947
1948 if (on) {
1949 if (outputDesc->mMuteCount[stream] == 0) {
1950 if (streamDesc.mCanBeMuted) {
1951 checkAndSetVolume(stream, 0, output, outputDesc->device(), delayMs);
1952 }
1953 }
1954 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
1955 outputDesc->mMuteCount[stream]++;
1956 } else {
1957 if (outputDesc->mMuteCount[stream] == 0) {
1958 LOGW("setStreamMute() unmuting non muted stream!");
1959 return;
1960 }
1961 if (--outputDesc->mMuteCount[stream] == 0) {
1962 checkAndSetVolume(stream, streamDesc.mIndexCur, output, outputDesc->device(), delayMs);
1963 }
1964 }
1965}
1966
1967void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
1968{
1969 // if the stream pertains to sonification strategy and we are in call we must
1970 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
1971 // in the device used for phone strategy and play the tone if the selected device does not
1972 // interfere with the device used for phone strategy
1973 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
1974 // many times as there are active tracks on the output
1975
1976 if (getStrategy((AudioSystem::stream_type)stream) == STRATEGY_SONIFICATION) {
1977 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mHardwareOutput);
1978 LOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
1979 stream, starting, outputDesc->mDevice, stateChange);
1980 if (outputDesc->mRefCount[stream]) {
1981 int muteCount = 1;
1982 if (stateChange) {
1983 muteCount = outputDesc->mRefCount[stream];
1984 }
1985 if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
1986 LOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
1987 for (int i = 0; i < muteCount; i++) {
1988 setStreamMute(stream, starting, mHardwareOutput);
1989 }
1990 } else {
1991 LOGV("handleIncallSonification() high visibility");
1992 if (outputDesc->device() & getDeviceForStrategy(STRATEGY_PHONE)) {
1993 LOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
1994 for (int i = 0; i < muteCount; i++) {
1995 setStreamMute(stream, starting, mHardwareOutput);
1996 }
1997 }
1998 if (starting) {
1999 mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
2000 } else {
2001 mpClientInterface->stopTone();
2002 }
2003 }
2004 }
2005 }
2006}
2007
Jean-Michel Trivi8f677d62010-11-15 12:11:32 -08002008bool AudioPolicyManagerBase::isInCall()
2009{
2010 return isStateInCall(mPhoneState);
2011}
2012
2013bool AudioPolicyManagerBase::isStateInCall(int state) {
2014 return ((state == AudioSystem::MODE_IN_CALL) ||
2015 (state == AudioSystem::MODE_IN_COMMUNICATION));
2016}
2017
Eric Laurentef9500f2010-03-11 14:47:00 -08002018bool AudioPolicyManagerBase::needsDirectOuput(AudioSystem::stream_type stream,
2019 uint32_t samplingRate,
2020 uint32_t format,
2021 uint32_t channels,
2022 AudioSystem::output_flags flags,
2023 uint32_t device)
2024{
2025 return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
2026 (format !=0 && !AudioSystem::isLinearPCM(format)));
2027}
2028
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002029uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
2030{
2031 return MAX_EFFECTS_CPU_LOAD;
2032}
2033
2034uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
2035{
2036 return MAX_EFFECTS_MEMORY;
2037}
2038
Eric Laurentcef3cd72009-12-10 01:03:50 -08002039// --- AudioOutputDescriptor class implementation
2040
2041AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor()
2042 : mId(0), mSamplingRate(0), mFormat(0), mChannels(0), mLatency(0),
2043 mFlags((AudioSystem::output_flags)0), mDevice(0), mOutput1(0), mOutput2(0)
2044{
2045 // clear usage count for all stream types
2046 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2047 mRefCount[i] = 0;
2048 mCurVolume[i] = -1.0;
2049 mMuteCount[i] = 0;
Eric Laurent25101b02011-02-02 09:33:30 -08002050 mStopTime[i] = 0;
Eric Laurentcef3cd72009-12-10 01:03:50 -08002051 }
2052}
2053
2054uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::device()
2055{
2056 uint32_t device = 0;
2057 if (isDuplicated()) {
2058 device = mOutput1->mDevice | mOutput2->mDevice;
2059 } else {
2060 device = mDevice;
2061 }
2062 return device;
2063}
2064
2065void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
2066{
2067 // forward usage count change to attached outputs
2068 if (isDuplicated()) {
2069 mOutput1->changeRefCount(stream, delta);
2070 mOutput2->changeRefCount(stream, delta);
2071 }
2072 if ((delta + (int)mRefCount[stream]) < 0) {
2073 LOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
2074 mRefCount[stream] = 0;
2075 return;
2076 }
2077 mRefCount[stream] += delta;
2078 LOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
2079}
2080
2081uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount()
2082{
2083 uint32_t refcount = 0;
2084 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2085 refcount += mRefCount[i];
2086 }
2087 return refcount;
2088}
2089
2090uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy)
2091{
2092 uint32_t refCount = 0;
2093 for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2094 if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2095 refCount += mRefCount[i];
2096 }
2097 }
2098 return refCount;
2099}
2100
Eric Laurentcef3cd72009-12-10 01:03:50 -08002101status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
2102{
2103 const size_t SIZE = 256;
2104 char buffer[SIZE];
2105 String8 result;
2106
2107 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2108 result.append(buffer);
2109 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2110 result.append(buffer);
2111 snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
2112 result.append(buffer);
2113 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
2114 result.append(buffer);
2115 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
2116 result.append(buffer);
2117 snprintf(buffer, SIZE, " Devices %08x\n", device());
2118 result.append(buffer);
2119 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
2120 result.append(buffer);
2121 for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2122 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
2123 result.append(buffer);
2124 }
2125 write(fd, result.string(), result.size());
2126
2127 return NO_ERROR;
2128}
2129
2130// --- AudioInputDescriptor class implementation
2131
2132AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor()
2133 : mSamplingRate(0), mFormat(0), mChannels(0),
2134 mAcoustics((AudioSystem::audio_in_acoustics)0), mDevice(0), mRefCount(0)
2135{
2136}
2137
2138status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
2139{
2140 const size_t SIZE = 256;
2141 char buffer[SIZE];
2142 String8 result;
2143
2144 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2145 result.append(buffer);
2146 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2147 result.append(buffer);
2148 snprintf(buffer, SIZE, " Channels: %08x\n", mChannels);
2149 result.append(buffer);
2150 snprintf(buffer, SIZE, " Acoustics %08x\n", mAcoustics);
2151 result.append(buffer);
2152 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
2153 result.append(buffer);
2154 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
2155 result.append(buffer);
2156 write(fd, result.string(), result.size());
2157
2158 return NO_ERROR;
2159}
2160
2161// --- StreamDescriptor class implementation
2162
2163void AudioPolicyManagerBase::StreamDescriptor::dump(char* buffer, size_t size)
2164{
2165 snprintf(buffer, size, " %02d %02d %02d %d\n",
2166 mIndexMin,
2167 mIndexMax,
2168 mIndexCur,
2169 mCanBeMuted);
2170}
2171
Eric Laurent8ed6ed02010-07-13 04:45:46 -07002172// --- EffectDescriptor class implementation
2173
2174status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
2175{
2176 const size_t SIZE = 256;
2177 char buffer[SIZE];
2178 String8 result;
2179
2180 snprintf(buffer, SIZE, " Output: %d\n", mOutput);
2181 result.append(buffer);
2182 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
2183 result.append(buffer);
2184 snprintf(buffer, SIZE, " Session: %d\n", mSession);
2185 result.append(buffer);
2186 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
2187 result.append(buffer);
2188 write(fd, result.string(), result.size());
2189
2190 return NO_ERROR;
2191}
2192
2193
Eric Laurentcef3cd72009-12-10 01:03:50 -08002194
2195}; // namespace android