OSDN Git Service

Merge "Increase system stream volume on speaker" into jb-dev
[android-x86/hardware-libhardware_legacy.git] / audio / AudioPolicyManagerBase.cpp
1 /*
2  * Copyright (C) 2009 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #define LOG_TAG "AudioPolicyManagerBase"
18 //#define LOG_NDEBUG 0
19
20 //#define VERY_VERBOSE_LOGGING
21 #ifdef VERY_VERBOSE_LOGGING
22 #define ALOGVV ALOGV
23 #else
24 #define ALOGVV(a...) do { } while(0)
25 #endif
26
27 #include <utils/Log.h>
28 #include <hardware_legacy/AudioPolicyManagerBase.h>
29 #include <hardware/audio_effect.h>
30 #include <hardware/audio.h>
31 #include <math.h>
32 #include <hardware_legacy/audio_policy_conf.h>
33
34 namespace android_audio_legacy {
35
36 // ----------------------------------------------------------------------------
37 // AudioPolicyInterface implementation
38 // ----------------------------------------------------------------------------
39
40
41 status_t AudioPolicyManagerBase::setDeviceConnectionState(AudioSystem::audio_devices device,
42                                                   AudioSystem::device_connection_state state,
43                                                   const char *device_address)
44 {
45     SortedVector <audio_io_handle_t> outputs;
46
47     ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
48
49     // connect/disconnect only 1 device at a time
50     if (AudioSystem::popCount(device) != 1) return BAD_VALUE;
51
52     if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
53         ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
54         return BAD_VALUE;
55     }
56
57     // handle output devices
58     if (AudioSystem::isOutputDevice(device)) {
59
60         if (!mHasA2dp && AudioSystem::isA2dpDevice(device)) {
61             ALOGE("setDeviceConnectionState() invalid device: %x", device);
62             return BAD_VALUE;
63         }
64         if (!mHasUsb && audio_is_usb_device((audio_devices_t)device)) {
65             ALOGE("setDeviceConnectionState() invalid device: %x", device);
66             return BAD_VALUE;
67         }
68
69         switch (state)
70         {
71         // handle output device connection
72         case AudioSystem::DEVICE_STATE_AVAILABLE:
73             if (mAvailableOutputDevices & device) {
74                 ALOGW("setDeviceConnectionState() device already connected: %x", device);
75                 return INVALID_OPERATION;
76             }
77             ALOGV("setDeviceConnectionState() connecting device %x", device);
78
79             if (checkOutputsForDevice((audio_devices_t)device, state, outputs) != NO_ERROR) {
80                 return INVALID_OPERATION;
81             }
82             ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %d outputs",
83                   outputs.size());
84             // register new device as available
85             mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
86
87             if (!outputs.isEmpty()) {
88                 String8 paramStr;
89                 if (mHasA2dp && AudioSystem::isA2dpDevice(device)) {
90                     // handle A2DP device connection
91                     AudioParameter param;
92                     param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
93                     paramStr = param.toString();
94                     mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
95                     mA2dpSuspended = false;
96                 } else if (AudioSystem::isBluetoothScoDevice(device)) {
97                     // handle SCO device connection
98                     mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
99                 } else if (mHasUsb && audio_is_usb_device((audio_devices_t)device)) {
100                     // handle USB device connection
101                     mUsbCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
102                     paramStr = mUsbCardAndDevice;
103                 }
104                 if (!paramStr.isEmpty()) {
105                     for (size_t i = 0; i < outputs.size(); i++) {
106                         mpClientInterface->setParameters(outputs[i], paramStr);
107                     }
108                 }
109             }
110             break;
111         // handle output device disconnection
112         case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
113             if (!(mAvailableOutputDevices & device)) {
114                 ALOGW("setDeviceConnectionState() device not connected: %x", device);
115                 return INVALID_OPERATION;
116             }
117
118             ALOGV("setDeviceConnectionState() disconnecting device %x", device);
119             // remove device from available output devices
120             mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
121
122             checkOutputsForDevice((audio_devices_t)device, state, outputs);
123             if (mHasA2dp && AudioSystem::isA2dpDevice(device)) {
124                 // handle A2DP device disconnection
125                 mA2dpDeviceAddress = "";
126                 mA2dpSuspended = false;
127             } else if (AudioSystem::isBluetoothScoDevice(device)) {
128                 // handle SCO device disconnection
129                 mScoDeviceAddress = "";
130             } else if (mHasUsb && audio_is_usb_device((audio_devices_t)device)) {
131                 // handle USB device disconnection
132                 mUsbCardAndDevice = "";
133             }
134             } break;
135
136         default:
137             ALOGE("setDeviceConnectionState() invalid state: %x", state);
138             return BAD_VALUE;
139         }
140
141         checkA2dpSuspend();
142         checkOutputForAllStrategies();
143         // outputs must be closed after checkOutputForAllStrategies() is executed
144         if (!outputs.isEmpty()) {
145             for (size_t i = 0; i < outputs.size(); i++) {
146                 // close unused outputs after device disconnection or direct outputs that have been
147                 // opened by checkOutputsForDevice() to query dynamic parameters
148                 if ((state == AudioSystem::DEVICE_STATE_UNAVAILABLE) ||
149                         (mOutputs.valueFor(outputs[i])->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
150                     closeOutput(outputs[i]);
151                 }
152             }
153         }
154
155         updateDeviceForStrategy();
156         for (size_t i = 0; i < mOutputs.size(); i++) {
157             setOutputDevice(mOutputs.keyAt(i), getNewDevice(mOutputs.keyAt(i), true /*fromCache*/));
158         }
159
160         if (device == AudioSystem::DEVICE_OUT_WIRED_HEADSET) {
161             device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
162         } else if (device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO ||
163                    device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
164                    device == AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
165             device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
166         } else {
167             return NO_ERROR;
168         }
169     }
170     // handle input devices
171     if (AudioSystem::isInputDevice(device)) {
172
173         switch (state)
174         {
175         // handle input device connection
176         case AudioSystem::DEVICE_STATE_AVAILABLE: {
177             if (mAvailableInputDevices & device) {
178                 ALOGW("setDeviceConnectionState() device already connected: %d", device);
179                 return INVALID_OPERATION;
180             }
181             mAvailableInputDevices = (audio_devices_t)(mAvailableInputDevices | device);
182             }
183             break;
184
185         // handle input device disconnection
186         case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
187             if (!(mAvailableInputDevices & device)) {
188                 ALOGW("setDeviceConnectionState() device not connected: %d", device);
189                 return INVALID_OPERATION;
190             }
191             mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
192             } break;
193
194         default:
195             ALOGE("setDeviceConnectionState() invalid state: %x", state);
196             return BAD_VALUE;
197         }
198
199         audio_io_handle_t activeInput = getActiveInput();
200         if (activeInput != 0) {
201             AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
202             audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
203             if ((newDevice != 0) && (newDevice != inputDesc->mDevice)) {
204                 ALOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
205                         inputDesc->mDevice, newDevice, activeInput);
206                 inputDesc->mDevice = newDevice;
207                 AudioParameter param = AudioParameter();
208                 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
209                 mpClientInterface->setParameters(activeInput, param.toString());
210             }
211         }
212
213         return NO_ERROR;
214     }
215
216     ALOGW("setDeviceConnectionState() invalid device: %x", device);
217     return BAD_VALUE;
218 }
219
220 AudioSystem::device_connection_state AudioPolicyManagerBase::getDeviceConnectionState(AudioSystem::audio_devices device,
221                                                   const char *device_address)
222 {
223     AudioSystem::device_connection_state state = AudioSystem::DEVICE_STATE_UNAVAILABLE;
224     String8 address = String8(device_address);
225     if (AudioSystem::isOutputDevice(device)) {
226         if (device & mAvailableOutputDevices) {
227             if (AudioSystem::isA2dpDevice(device) &&
228                 (!mHasA2dp || (address != "" && mA2dpDeviceAddress != address))) {
229                 return state;
230             }
231             if (AudioSystem::isBluetoothScoDevice(device) &&
232                 address != "" && mScoDeviceAddress != address) {
233                 return state;
234             }
235             if (audio_is_usb_device((audio_devices_t)device) &&
236                 (!mHasUsb || (address != "" && mUsbCardAndDevice != address))) {
237                 ALOGE("setDeviceConnectionState() invalid device: %x", device);
238                 return state;
239             }
240             state = AudioSystem::DEVICE_STATE_AVAILABLE;
241         }
242     } else if (AudioSystem::isInputDevice(device)) {
243         if (device & mAvailableInputDevices) {
244             state = AudioSystem::DEVICE_STATE_AVAILABLE;
245         }
246     }
247
248     return state;
249 }
250
251 void AudioPolicyManagerBase::setPhoneState(int state)
252 {
253     ALOGV("setPhoneState() state %d", state);
254     audio_devices_t newDevice = (audio_devices_t)0;
255     if (state < 0 || state >= AudioSystem::NUM_MODES) {
256         ALOGW("setPhoneState() invalid state %d", state);
257         return;
258     }
259
260     if (state == mPhoneState ) {
261         ALOGW("setPhoneState() setting same state %d", state);
262         return;
263     }
264
265     // if leaving call state, handle special case of active streams
266     // pertaining to sonification strategy see handleIncallSonification()
267     if (isInCall()) {
268         ALOGV("setPhoneState() in call state management: new state is %d", state);
269         for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
270             handleIncallSonification(stream, false, true);
271         }
272     }
273
274     // store previous phone state for management of sonification strategy below
275     int oldState = mPhoneState;
276     mPhoneState = state;
277     bool force = false;
278
279     // are we entering or starting a call
280     if (!isStateInCall(oldState) && isStateInCall(state)) {
281         ALOGV("  Entering call in setPhoneState()");
282         // force routing command to audio hardware when starting a call
283         // even if no device change is needed
284         force = true;
285     } else if (isStateInCall(oldState) && !isStateInCall(state)) {
286         ALOGV("  Exiting call in setPhoneState()");
287         // force routing command to audio hardware when exiting a call
288         // even if no device change is needed
289         force = true;
290     } else if (isStateInCall(state) && (state != oldState)) {
291         ALOGV("  Switching between telephony and VoIP in setPhoneState()");
292         // force routing command to audio hardware when switching between telephony and VoIP
293         // even if no device change is needed
294         force = true;
295     }
296
297     // check for device and output changes triggered by new phone state
298     newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
299     checkA2dpSuspend();
300     checkOutputForAllStrategies();
301     updateDeviceForStrategy();
302
303     AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
304
305     // force routing command to audio hardware when ending call
306     // even if no device change is needed
307     if (isStateInCall(oldState) && newDevice == 0) {
308         newDevice = hwOutputDesc->device();
309     }
310
311     // when changing from ring tone to in call mode, mute the ringing tone
312     // immediately and delay the route change to avoid sending the ring tone
313     // tail into the earpiece or headset.
314     int delayMs = 0;
315     if (isStateInCall(state) && oldState == AudioSystem::MODE_RINGTONE) {
316         // delay the device change command by twice the output latency to have some margin
317         // and be sure that audio buffers not yet affected by the mute are out when
318         // we actually apply the route change
319         delayMs = hwOutputDesc->mLatency*2;
320         setStreamMute(AudioSystem::RING, true, mPrimaryOutput);
321     }
322
323     // change routing is necessary
324     setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
325
326     // if entering in call state, handle special case of active streams
327     // pertaining to sonification strategy see handleIncallSonification()
328     if (isStateInCall(state)) {
329         ALOGV("setPhoneState() in call state management: new state is %d", state);
330         // unmute the ringing tone after a sufficient delay if it was muted before
331         // setting output device above
332         if (oldState == AudioSystem::MODE_RINGTONE) {
333             setStreamMute(AudioSystem::RING, false, mPrimaryOutput, MUTE_TIME_MS);
334         }
335         for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
336             handleIncallSonification(stream, true, true);
337         }
338     }
339
340     // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
341     if (state == AudioSystem::MODE_RINGTONE &&
342         isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
343         mLimitRingtoneVolume = true;
344     } else {
345         mLimitRingtoneVolume = false;
346     }
347 }
348
349 void AudioPolicyManagerBase::setForceUse(AudioSystem::force_use usage, AudioSystem::forced_config config)
350 {
351     ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
352
353     bool forceVolumeReeval = false;
354     switch(usage) {
355     case AudioSystem::FOR_COMMUNICATION:
356         if (config != AudioSystem::FORCE_SPEAKER && config != AudioSystem::FORCE_BT_SCO &&
357             config != AudioSystem::FORCE_NONE) {
358             ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
359             return;
360         }
361         forceVolumeReeval = true;
362         mForceUse[usage] = config;
363         break;
364     case AudioSystem::FOR_MEDIA:
365         if (config != AudioSystem::FORCE_HEADPHONES && config != AudioSystem::FORCE_BT_A2DP &&
366             config != AudioSystem::FORCE_WIRED_ACCESSORY &&
367             config != AudioSystem::FORCE_ANALOG_DOCK &&
368             config != AudioSystem::FORCE_DIGITAL_DOCK && config != AudioSystem::FORCE_NONE &&
369             config != AudioSystem::FORCE_NO_BT_A2DP) {
370             ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
371             return;
372         }
373         mForceUse[usage] = config;
374         break;
375     case AudioSystem::FOR_RECORD:
376         if (config != AudioSystem::FORCE_BT_SCO && config != AudioSystem::FORCE_WIRED_ACCESSORY &&
377             config != AudioSystem::FORCE_NONE) {
378             ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
379             return;
380         }
381         mForceUse[usage] = config;
382         break;
383     case AudioSystem::FOR_DOCK:
384         if (config != AudioSystem::FORCE_NONE && config != AudioSystem::FORCE_BT_CAR_DOCK &&
385             config != AudioSystem::FORCE_BT_DESK_DOCK &&
386             config != AudioSystem::FORCE_WIRED_ACCESSORY &&
387             config != AudioSystem::FORCE_ANALOG_DOCK &&
388             config != AudioSystem::FORCE_DIGITAL_DOCK) {
389             ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
390         }
391         forceVolumeReeval = true;
392         mForceUse[usage] = config;
393         break;
394     default:
395         ALOGW("setForceUse() invalid usage %d", usage);
396         break;
397     }
398
399     // check for device and output changes triggered by new force usage
400     checkA2dpSuspend();
401     checkOutputForAllStrategies();
402     updateDeviceForStrategy();
403     for (size_t i = 0; i < mOutputs.size(); i++) {
404         audio_io_handle_t output = mOutputs.keyAt(i);
405         audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
406         setOutputDevice(output, newDevice, true);
407         if (forceVolumeReeval) {
408             applyStreamVolumes(output, newDevice, 0, true);
409         }
410     }
411
412     audio_io_handle_t activeInput = getActiveInput();
413     if (activeInput != 0) {
414         AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
415         audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
416         if ((newDevice != 0) && (newDevice != inputDesc->mDevice)) {
417             ALOGV("setForceUse() changing device from %x to %x for input %d",
418                     inputDesc->mDevice, newDevice, activeInput);
419             inputDesc->mDevice = newDevice;
420             AudioParameter param = AudioParameter();
421             param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
422             mpClientInterface->setParameters(activeInput, param.toString());
423         }
424     }
425
426 }
427
428 AudioSystem::forced_config AudioPolicyManagerBase::getForceUse(AudioSystem::force_use usage)
429 {
430     return mForceUse[usage];
431 }
432
433 void AudioPolicyManagerBase::setSystemProperty(const char* property, const char* value)
434 {
435     ALOGV("setSystemProperty() property %s, value %s", property, value);
436     if (strcmp(property, "ro.camera.sound.forced") == 0) {
437         if (atoi(value)) {
438             ALOGV("ENFORCED_AUDIBLE cannot be muted");
439             mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = false;
440         } else {
441             ALOGV("ENFORCED_AUDIBLE can be muted");
442             mStreams[AudioSystem::ENFORCED_AUDIBLE].mCanBeMuted = true;
443         }
444     }
445 }
446
447 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getProfileForDirectOutput(
448                                                                audio_devices_t device,
449                                                                uint32_t samplingRate,
450                                                                uint32_t format,
451                                                                uint32_t channelMask,
452                                                                audio_output_flags_t flags)
453 {
454     for (size_t i = 0; i < mHwModules.size(); i++) {
455         if (mHwModules[i]->mHandle == 0) {
456             continue;
457         }
458         for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
459            IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
460            if (profile->isCompatibleProfile(device, samplingRate, format,
461                                            channelMask,
462                                            AUDIO_OUTPUT_FLAG_DIRECT)) {
463                if (mAvailableOutputDevices & profile->mSupportedDevices) {
464                    return mHwModules[i]->mOutputProfiles[j];
465                }
466            }
467         }
468     }
469     return 0;
470 }
471
472 audio_io_handle_t AudioPolicyManagerBase::getOutput(AudioSystem::stream_type stream,
473                                     uint32_t samplingRate,
474                                     uint32_t format,
475                                     uint32_t channelMask,
476                                     AudioSystem::output_flags flags)
477 {
478     audio_io_handle_t output = 0;
479     uint32_t latency = 0;
480     routing_strategy strategy = getStrategy((AudioSystem::stream_type)stream);
481     audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
482     ALOGV("getOutput() stream %d, samplingRate %d, format %d, channelMask %x, flags %x",
483           stream, samplingRate, format, channelMask, flags);
484
485 #ifdef AUDIO_POLICY_TEST
486     if (mCurOutput != 0) {
487         ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
488                 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
489
490         if (mTestOutputs[mCurOutput] == 0) {
491             ALOGV("getOutput() opening test output");
492             AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
493             outputDesc->mDevice = mTestDevice;
494             outputDesc->mSamplingRate = mTestSamplingRate;
495             outputDesc->mFormat = mTestFormat;
496             outputDesc->mChannelMask = mTestChannels;
497             outputDesc->mLatency = mTestLatencyMs;
498             outputDesc->mFlags = (audio_output_flags_t)(mDirectOutput ? AudioSystem::OUTPUT_FLAG_DIRECT : 0);
499             outputDesc->mRefCount[stream] = 0;
500             mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
501                                             &outputDesc->mSamplingRate,
502                                             &outputDesc->mFormat,
503                                             &outputDesc->mChannelMask,
504                                             &outputDesc->mLatency,
505                                             outputDesc->mFlags);
506             if (mTestOutputs[mCurOutput]) {
507                 AudioParameter outputCmd = AudioParameter();
508                 outputCmd.addInt(String8("set_id"),mCurOutput);
509                 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
510                 addOutput(mTestOutputs[mCurOutput], outputDesc);
511             }
512         }
513         return mTestOutputs[mCurOutput];
514     }
515 #endif //AUDIO_POLICY_TEST
516
517     // open a direct output if required by specified parameters
518     IOProfile *profile = getProfileForDirectOutput(device,
519                                                    samplingRate,
520                                                    format,
521                                                    channelMask,
522                                                    (audio_output_flags_t)flags);
523     if (profile != NULL) {
524
525         ALOGV("getOutput() opening direct output device %x", device);
526
527         AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(profile);
528         outputDesc->mDevice = device;
529         outputDesc->mSamplingRate = samplingRate;
530         outputDesc->mFormat = (audio_format_t)format;
531         outputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
532         outputDesc->mLatency = 0;
533         outputDesc->mFlags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);;
534         outputDesc->mRefCount[stream] = 0;
535         outputDesc->mStopTime[stream] = 0;
536         output = mpClientInterface->openOutput(profile->mModule->mHandle,
537                                         &outputDesc->mDevice,
538                                         &outputDesc->mSamplingRate,
539                                         &outputDesc->mFormat,
540                                         &outputDesc->mChannelMask,
541                                         &outputDesc->mLatency,
542                                         outputDesc->mFlags);
543
544         // only accept an output with the requested parameters
545         if (output == 0 ||
546             (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
547             (format != 0 && format != outputDesc->mFormat) ||
548             (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
549             ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
550                     "format %d %d, channelMask %04x %04x", output, samplingRate,
551                     outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
552                     outputDesc->mChannelMask);
553             if (output != 0) {
554                 mpClientInterface->closeOutput(output);
555             }
556             delete outputDesc;
557             return 0;
558         }
559         addOutput(output, outputDesc);
560         ALOGV("getOutput() returns direct output %d", output);
561         return output;
562     }
563
564     // ignoring channel mask due to downmix capability in mixer
565
566     // open a non direct output
567
568     // get which output is suitable for the specified stream. The actual routing change will happen
569     // when startOutput() will be called
570     SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device);
571
572     output = selectOutput(outputs, flags);
573
574     ALOGW_IF((output ==0), "getOutput() could not find output for stream %d, samplingRate %d,"
575             "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
576
577     ALOGV("getOutput() returns output %d", output);
578
579     return output;
580 }
581
582 audio_io_handle_t AudioPolicyManagerBase::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
583                                                        AudioSystem::output_flags flags)
584 {
585     // select one output among several that provide a path to a particular device or set of
586     // devices (the list was previously build by getOutputsForDevice()).
587     // The priority is as follows:
588     // 1: the output with the highest number of requested policy flags
589     // 2: the primary output
590     // 3: the first output in the list
591
592     if (outputs.size() == 0) {
593         return 0;
594     }
595     if (outputs.size() == 1) {
596         return outputs[0];
597     }
598
599     int maxCommonFlags = 0;
600     audio_io_handle_t outputFlags = 0;
601     audio_io_handle_t outputPrimary = 0;
602
603     for (size_t i = 0; i < outputs.size(); i++) {
604         AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
605         if (!outputDesc->isDuplicated()) {
606             int commonFlags = (int)AudioSystem::popCount(outputDesc->mProfile->mFlags & flags);
607             if (commonFlags > maxCommonFlags) {
608                 outputFlags = outputs[i];
609                 maxCommonFlags = commonFlags;
610                 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
611             }
612             if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
613                 outputPrimary = outputs[i];
614             }
615         }
616     }
617
618     if (outputFlags != 0) {
619         return outputFlags;
620     }
621     if (outputPrimary != 0) {
622         return outputPrimary;
623     }
624
625     return outputs[0];
626 }
627
628 status_t AudioPolicyManagerBase::startOutput(audio_io_handle_t output,
629                                              AudioSystem::stream_type stream,
630                                              int session)
631 {
632     ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
633     ssize_t index = mOutputs.indexOfKey(output);
634     if (index < 0) {
635         ALOGW("startOutput() unknow output %d", output);
636         return BAD_VALUE;
637     }
638
639     AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
640
641     // increment usage count for this stream on the requested output:
642     // NOTE that the usage count is the same for duplicated output and hardware output which is
643     // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
644     outputDesc->changeRefCount(stream, 1);
645
646     if (outputDesc->mRefCount[stream] == 1) {
647         audio_devices_t prevDevice = outputDesc->device();
648         audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
649         routing_strategy strategy = getStrategy(stream);
650         bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
651                             (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
652         uint32_t waitMs = 0;
653         bool force = false;
654         for (size_t i = 0; i < mOutputs.size(); i++) {
655             AudioOutputDescriptor *desc = mOutputs.valueAt(i);
656             if (desc != outputDesc) {
657                 // force a device change if any other output is managed by the same hw
658                 // module and has a current device selection that differs from selected device.
659                 // In this case, the audio HAL must receive the new device selection so that it can
660                 // change the device currently selected by the other active output.
661                 if (outputDesc->sharesHwModuleWith(desc) &&
662                     desc->device() != newDevice) {
663                     force = true;
664                 }
665                 // wait for audio on other active outputs to be presented when starting
666                 // a notification so that audio focus effect can propagate.
667                 if (shouldWait && (desc->refCount() != 0) && (waitMs < desc->latency())) {
668                     waitMs = desc->latency();
669                 }
670             }
671         }
672         uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
673
674         // handle special case for sonification while in call
675         if (isInCall()) {
676             handleIncallSonification(stream, true, false);
677         }
678
679         // apply volume rules for current stream and device if necessary
680         checkAndSetVolume(stream,
681                           mStreams[stream].getVolumeIndex((audio_devices_t)newDevice),
682                           output,
683                           newDevice);
684
685         // update the outputs if starting an output with a stream that can affect notification
686         // routing
687         handleNotificationRoutingForStream(stream);
688         if (waitMs > muteWaitMs) {
689             usleep((waitMs - muteWaitMs) * 2 * 1000);
690         }
691     }
692     return NO_ERROR;
693 }
694
695
696 status_t AudioPolicyManagerBase::stopOutput(audio_io_handle_t output,
697                                             AudioSystem::stream_type stream,
698                                             int session)
699 {
700     ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
701     ssize_t index = mOutputs.indexOfKey(output);
702     if (index < 0) {
703         ALOGW("stopOutput() unknow output %d", output);
704         return BAD_VALUE;
705     }
706
707     AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
708
709     // handle special case for sonification while in call
710     if (isInCall()) {
711         handleIncallSonification(stream, false, false);
712     }
713
714     if (outputDesc->mRefCount[stream] > 0) {
715         // decrement usage count of this stream on the output
716         outputDesc->changeRefCount(stream, -1);
717         // store time at which the stream was stopped - see isStreamActive()
718         if (outputDesc->mRefCount[stream] == 0) {
719             outputDesc->mStopTime[stream] = systemTime();
720             audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
721             // delay the device switch by twice the latency because stopOutput() is executed when
722             // the track stop() command is received and at that time the audio track buffer can
723             // still contain data that needs to be drained. The latency only covers the audio HAL
724             // and kernel buffers. Also the latency does not always include additional delay in the
725             // audio path (audio DSP, CODEC ...)
726             setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
727
728             // force restoring the device selection on other active outputs if it differs from the
729             // one being selected for this output
730             for (size_t i = 0; i < mOutputs.size(); i++) {
731                 audio_io_handle_t curOutput = mOutputs.keyAt(i);
732                 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
733                 if (curOutput != output &&
734                         desc->refCount() != 0 &&
735                         outputDesc->sharesHwModuleWith(desc) &&
736                         newDevice != desc->device()) {
737                     setOutputDevice(curOutput,
738                                     getNewDevice(curOutput, false /*fromCache*/),
739                                     true,
740                                     outputDesc->mLatency*2);
741                 }
742             }
743             // update the outputs if stopping one with a stream that can affect notification routing
744             handleNotificationRoutingForStream(stream);
745         }
746         return NO_ERROR;
747     } else {
748         ALOGW("stopOutput() refcount is already 0 for output %d", output);
749         return INVALID_OPERATION;
750     }
751 }
752
753 void AudioPolicyManagerBase::releaseOutput(audio_io_handle_t output)
754 {
755     ALOGV("releaseOutput() %d", output);
756     ssize_t index = mOutputs.indexOfKey(output);
757     if (index < 0) {
758         ALOGW("releaseOutput() releasing unknown output %d", output);
759         return;
760     }
761
762 #ifdef AUDIO_POLICY_TEST
763     int testIndex = testOutputIndex(output);
764     if (testIndex != 0) {
765         AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
766         if (outputDesc->refCount() == 0) {
767             mpClientInterface->closeOutput(output);
768             delete mOutputs.valueAt(index);
769             mOutputs.removeItem(output);
770             mTestOutputs[testIndex] = 0;
771         }
772         return;
773     }
774 #endif //AUDIO_POLICY_TEST
775
776     if (mOutputs.valueAt(index)->mFlags & AudioSystem::OUTPUT_FLAG_DIRECT) {
777         mpClientInterface->closeOutput(output);
778         delete mOutputs.valueAt(index);
779         mOutputs.removeItem(output);
780     }
781
782 }
783
784 audio_io_handle_t AudioPolicyManagerBase::getInput(int inputSource,
785                                     uint32_t samplingRate,
786                                     uint32_t format,
787                                     uint32_t channelMask,
788                                     AudioSystem::audio_in_acoustics acoustics)
789 {
790     audio_io_handle_t input = 0;
791     audio_devices_t device = getDeviceForInputSource(inputSource);
792
793     ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
794           inputSource, samplingRate, format, channelMask, acoustics);
795
796     if (device == 0) {
797         ALOGW("getInput() could not find device for inputSource %d", inputSource);
798         return 0;
799     }
800
801     // adapt channel selection to input source
802     switch(inputSource) {
803     case AUDIO_SOURCE_VOICE_UPLINK:
804         channelMask = AudioSystem::CHANNEL_IN_VOICE_UPLINK;
805         break;
806     case AUDIO_SOURCE_VOICE_DOWNLINK:
807         channelMask = AudioSystem::CHANNEL_IN_VOICE_DNLINK;
808         break;
809     case AUDIO_SOURCE_VOICE_CALL:
810         channelMask = (AudioSystem::CHANNEL_IN_VOICE_UPLINK | AudioSystem::CHANNEL_IN_VOICE_DNLINK);
811         break;
812     default:
813         break;
814     }
815
816     IOProfile *profile = getInputProfile(device,
817                                          samplingRate,
818                                          format,
819                                          channelMask);
820     if (profile == NULL) {
821         ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d,"
822                 "channelMask %04x",
823                 device, samplingRate, format, channelMask);
824         return 0;
825     }
826
827     if (profile->mModule->mHandle == 0) {
828         ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
829         return 0;
830     }
831
832     AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
833
834     inputDesc->mInputSource = inputSource;
835     inputDesc->mDevice = device;
836     inputDesc->mSamplingRate = samplingRate;
837     inputDesc->mFormat = (audio_format_t)format;
838     inputDesc->mChannelMask = (audio_channel_mask_t)channelMask;
839     inputDesc->mRefCount = 0;
840     input = mpClientInterface->openInput(profile->mModule->mHandle,
841                                     &inputDesc->mDevice,
842                                     &inputDesc->mSamplingRate,
843                                     &inputDesc->mFormat,
844                                     &inputDesc->mChannelMask);
845
846     // only accept input with the exact requested set of parameters
847     if (input == 0 ||
848         (samplingRate != inputDesc->mSamplingRate) ||
849         (format != inputDesc->mFormat) ||
850         (channelMask != inputDesc->mChannelMask)) {
851         ALOGV("getInput() failed opening input: samplingRate %d, format %d, channelMask %d",
852                 samplingRate, format, channelMask);
853         if (input != 0) {
854             mpClientInterface->closeInput(input);
855         }
856         delete inputDesc;
857         return 0;
858     }
859     mInputs.add(input, inputDesc);
860     return input;
861 }
862
863 status_t AudioPolicyManagerBase::startInput(audio_io_handle_t input)
864 {
865     ALOGV("startInput() input %d", input);
866     ssize_t index = mInputs.indexOfKey(input);
867     if (index < 0) {
868         ALOGW("startInput() unknow input %d", input);
869         return BAD_VALUE;
870     }
871     AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
872
873 #ifdef AUDIO_POLICY_TEST
874     if (mTestInput == 0)
875 #endif //AUDIO_POLICY_TEST
876     {
877         // refuse 2 active AudioRecord clients at the same time
878         if (getActiveInput() != 0) {
879             ALOGW("startInput() input %d failed: other input already started", input);
880             return INVALID_OPERATION;
881         }
882     }
883
884     AudioParameter param = AudioParameter();
885     param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
886
887     param.addInt(String8(AudioParameter::keyInputSource), (int)inputDesc->mInputSource);
888     ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
889
890     mpClientInterface->setParameters(input, param.toString());
891
892     inputDesc->mRefCount = 1;
893     return NO_ERROR;
894 }
895
896 status_t AudioPolicyManagerBase::stopInput(audio_io_handle_t input)
897 {
898     ALOGV("stopInput() input %d", input);
899     ssize_t index = mInputs.indexOfKey(input);
900     if (index < 0) {
901         ALOGW("stopInput() unknow input %d", input);
902         return BAD_VALUE;
903     }
904     AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
905
906     if (inputDesc->mRefCount == 0) {
907         ALOGW("stopInput() input %d already stopped", input);
908         return INVALID_OPERATION;
909     } else {
910         AudioParameter param = AudioParameter();
911         param.addInt(String8(AudioParameter::keyRouting), 0);
912         mpClientInterface->setParameters(input, param.toString());
913         inputDesc->mRefCount = 0;
914         return NO_ERROR;
915     }
916 }
917
918 void AudioPolicyManagerBase::releaseInput(audio_io_handle_t input)
919 {
920     ALOGV("releaseInput() %d", input);
921     ssize_t index = mInputs.indexOfKey(input);
922     if (index < 0) {
923         ALOGW("releaseInput() releasing unknown input %d", input);
924         return;
925     }
926     mpClientInterface->closeInput(input);
927     delete mInputs.valueAt(index);
928     mInputs.removeItem(input);
929     ALOGV("releaseInput() exit");
930 }
931
932 void AudioPolicyManagerBase::initStreamVolume(AudioSystem::stream_type stream,
933                                             int indexMin,
934                                             int indexMax)
935 {
936     ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
937     if (indexMin < 0 || indexMin >= indexMax) {
938         ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
939         return;
940     }
941     mStreams[stream].mIndexMin = indexMin;
942     mStreams[stream].mIndexMax = indexMax;
943 }
944
945 status_t AudioPolicyManagerBase::setStreamVolumeIndex(AudioSystem::stream_type stream,
946                                                       int index,
947                                                       audio_devices_t device)
948 {
949
950     if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
951         return BAD_VALUE;
952     }
953     if (!audio_is_output_device(device)) {
954         return BAD_VALUE;
955     }
956
957     // Force max volume if stream cannot be muted
958     if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
959
960     ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
961           stream, device, index);
962
963     // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
964     // clear all device specific values
965     if (device == AUDIO_DEVICE_OUT_DEFAULT) {
966         mStreams[stream].mIndexCur.clear();
967     }
968     mStreams[stream].mIndexCur.add(device, index);
969
970     // compute and apply stream volume on all outputs according to connected device
971     status_t status = NO_ERROR;
972     for (size_t i = 0; i < mOutputs.size(); i++) {
973         audio_devices_t curDevice =
974                 getDeviceForVolume((audio_devices_t)mOutputs.valueAt(i)->device());
975         if (device == curDevice) {
976             status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
977             if (volStatus != NO_ERROR) {
978                 status = volStatus;
979             }
980         }
981     }
982     return status;
983 }
984
985 status_t AudioPolicyManagerBase::getStreamVolumeIndex(AudioSystem::stream_type stream,
986                                                       int *index,
987                                                       audio_devices_t device)
988 {
989     if (index == NULL) {
990         return BAD_VALUE;
991     }
992     if (!audio_is_output_device(device)) {
993         return BAD_VALUE;
994     }
995     // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
996     // the strategy the stream belongs to.
997     if (device == AUDIO_DEVICE_OUT_DEFAULT) {
998         device = (audio_devices_t)getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
999     }
1000     device = getDeviceForVolume(device);
1001
1002     *index =  mStreams[stream].getVolumeIndex(device);
1003     ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1004     return NO_ERROR;
1005 }
1006
1007 audio_io_handle_t AudioPolicyManagerBase::getOutputForEffect(effect_descriptor_t *desc)
1008 {
1009     ALOGV("getOutputForEffect()");
1010     // apply simple rule where global effects are attached to the same output as MUSIC streams
1011
1012     routing_strategy strategy = getStrategy(AudioSystem::MUSIC);
1013     audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1014     SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device);
1015     int outIdx = 0;
1016     for (size_t i = 0; i < dstOutputs.size(); i++) {
1017         AudioOutputDescriptor *desc = mOutputs.valueFor(dstOutputs[i]);
1018         if (desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
1019             outIdx = i;
1020         }
1021     }
1022     return dstOutputs[outIdx];
1023 }
1024
1025 status_t AudioPolicyManagerBase::registerEffect(effect_descriptor_t *desc,
1026                                 audio_io_handle_t io,
1027                                 uint32_t strategy,
1028                                 int session,
1029                                 int id)
1030 {
1031     ssize_t index = mOutputs.indexOfKey(io);
1032     if (index < 0) {
1033         index = mInputs.indexOfKey(io);
1034         if (index < 0) {
1035             ALOGW("registerEffect() unknown io %d", io);
1036             return INVALID_OPERATION;
1037         }
1038     }
1039
1040     if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1041         ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1042                 desc->name, desc->memoryUsage);
1043         return INVALID_OPERATION;
1044     }
1045     mTotalEffectsMemory += desc->memoryUsage;
1046     ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1047             desc->name, io, strategy, session, id);
1048     ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1049
1050     EffectDescriptor *pDesc = new EffectDescriptor();
1051     memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1052     pDesc->mIo = io;
1053     pDesc->mStrategy = (routing_strategy)strategy;
1054     pDesc->mSession = session;
1055     pDesc->mEnabled = false;
1056
1057     mEffects.add(id, pDesc);
1058
1059     return NO_ERROR;
1060 }
1061
1062 status_t AudioPolicyManagerBase::unregisterEffect(int id)
1063 {
1064     ssize_t index = mEffects.indexOfKey(id);
1065     if (index < 0) {
1066         ALOGW("unregisterEffect() unknown effect ID %d", id);
1067         return INVALID_OPERATION;
1068     }
1069
1070     EffectDescriptor *pDesc = mEffects.valueAt(index);
1071
1072     setEffectEnabled(pDesc, false);
1073
1074     if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1075         ALOGW("unregisterEffect() memory %d too big for total %d",
1076                 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1077         pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1078     }
1079     mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1080     ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1081             pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1082
1083     mEffects.removeItem(id);
1084     delete pDesc;
1085
1086     return NO_ERROR;
1087 }
1088
1089 status_t AudioPolicyManagerBase::setEffectEnabled(int id, bool enabled)
1090 {
1091     ssize_t index = mEffects.indexOfKey(id);
1092     if (index < 0) {
1093         ALOGW("unregisterEffect() unknown effect ID %d", id);
1094         return INVALID_OPERATION;
1095     }
1096
1097     return setEffectEnabled(mEffects.valueAt(index), enabled);
1098 }
1099
1100 status_t AudioPolicyManagerBase::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
1101 {
1102     if (enabled == pDesc->mEnabled) {
1103         ALOGV("setEffectEnabled(%s) effect already %s",
1104              enabled?"true":"false", enabled?"enabled":"disabled");
1105         return INVALID_OPERATION;
1106     }
1107
1108     if (enabled) {
1109         if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1110             ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1111                  pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1112             return INVALID_OPERATION;
1113         }
1114         mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1115         ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1116     } else {
1117         if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1118             ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1119                     pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1120             pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1121         }
1122         mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1123         ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1124     }
1125     pDesc->mEnabled = enabled;
1126     return NO_ERROR;
1127 }
1128
1129 bool AudioPolicyManagerBase::isStreamActive(int stream, uint32_t inPastMs) const
1130 {
1131     nsecs_t sysTime = systemTime();
1132     for (size_t i = 0; i < mOutputs.size(); i++) {
1133         if (mOutputs.valueAt(i)->mRefCount[stream] != 0 ||
1134             ns2ms(sysTime - mOutputs.valueAt(i)->mStopTime[stream]) < inPastMs) {
1135             return true;
1136         }
1137     }
1138     return false;
1139 }
1140
1141
1142 status_t AudioPolicyManagerBase::dump(int fd)
1143 {
1144     const size_t SIZE = 256;
1145     char buffer[SIZE];
1146     String8 result;
1147
1148     snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1149     result.append(buffer);
1150
1151     snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1152     result.append(buffer);
1153     snprintf(buffer, SIZE, " A2DP device address: %s\n", mA2dpDeviceAddress.string());
1154     result.append(buffer);
1155     snprintf(buffer, SIZE, " SCO device address: %s\n", mScoDeviceAddress.string());
1156     result.append(buffer);
1157     snprintf(buffer, SIZE, " USB audio ALSA %s\n", mUsbCardAndDevice.string());
1158     result.append(buffer);
1159     snprintf(buffer, SIZE, " Output devices: %08x\n", mAvailableOutputDevices);
1160     result.append(buffer);
1161     snprintf(buffer, SIZE, " Input devices: %08x\n", mAvailableInputDevices);
1162     result.append(buffer);
1163     snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1164     result.append(buffer);
1165     snprintf(buffer, SIZE, " Force use for communications %d\n", mForceUse[AudioSystem::FOR_COMMUNICATION]);
1166     result.append(buffer);
1167     snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AudioSystem::FOR_MEDIA]);
1168     result.append(buffer);
1169     snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AudioSystem::FOR_RECORD]);
1170     result.append(buffer);
1171     snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AudioSystem::FOR_DOCK]);
1172     result.append(buffer);
1173     write(fd, result.string(), result.size());
1174
1175
1176     snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1177     write(fd, buffer, strlen(buffer));
1178     for (size_t i = 0; i < mHwModules.size(); i++) {
1179         snprintf(buffer, SIZE, "- HW Module %d:\n", i + 1);
1180         write(fd, buffer, strlen(buffer));
1181         mHwModules[i]->dump(fd);
1182     }
1183
1184     snprintf(buffer, SIZE, "\nOutputs dump:\n");
1185     write(fd, buffer, strlen(buffer));
1186     for (size_t i = 0; i < mOutputs.size(); i++) {
1187         snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1188         write(fd, buffer, strlen(buffer));
1189         mOutputs.valueAt(i)->dump(fd);
1190     }
1191
1192     snprintf(buffer, SIZE, "\nInputs dump:\n");
1193     write(fd, buffer, strlen(buffer));
1194     for (size_t i = 0; i < mInputs.size(); i++) {
1195         snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1196         write(fd, buffer, strlen(buffer));
1197         mInputs.valueAt(i)->dump(fd);
1198     }
1199
1200     snprintf(buffer, SIZE, "\nStreams dump:\n");
1201     write(fd, buffer, strlen(buffer));
1202     snprintf(buffer, SIZE,
1203              " Stream  Can be muted  Index Min  Index Max  Index Cur [device : index]...\n");
1204     write(fd, buffer, strlen(buffer));
1205     for (size_t i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
1206         snprintf(buffer, SIZE, " %02d      ", i);
1207         write(fd, buffer, strlen(buffer));
1208         mStreams[i].dump(fd);
1209     }
1210
1211     snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1212             (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1213     write(fd, buffer, strlen(buffer));
1214
1215     snprintf(buffer, SIZE, "Registered effects:\n");
1216     write(fd, buffer, strlen(buffer));
1217     for (size_t i = 0; i < mEffects.size(); i++) {
1218         snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1219         write(fd, buffer, strlen(buffer));
1220         mEffects.valueAt(i)->dump(fd);
1221     }
1222
1223
1224     return NO_ERROR;
1225 }
1226
1227 // ----------------------------------------------------------------------------
1228 // AudioPolicyManagerBase
1229 // ----------------------------------------------------------------------------
1230
1231 AudioPolicyManagerBase::AudioPolicyManagerBase(AudioPolicyClientInterface *clientInterface)
1232     :
1233 #ifdef AUDIO_POLICY_TEST
1234     Thread(false),
1235 #endif //AUDIO_POLICY_TEST
1236     mPrimaryOutput((audio_io_handle_t)0),
1237     mAvailableOutputDevices((audio_devices_t)0),
1238     mPhoneState(AudioSystem::MODE_NORMAL),
1239     mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1240     mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
1241     mA2dpSuspended(false), mHasA2dp(false), mHasUsb(false)
1242 {
1243     mpClientInterface = clientInterface;
1244
1245     for (int i = 0; i < AudioSystem::NUM_FORCE_USE; i++) {
1246         mForceUse[i] = AudioSystem::FORCE_NONE;
1247     }
1248
1249     initializeVolumeCurves();
1250
1251     mA2dpDeviceAddress = String8("");
1252     mScoDeviceAddress = String8("");
1253     mUsbCardAndDevice = String8("");
1254
1255     if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
1256         if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1257             ALOGE("could not load audio policy configuration file, setting defaults");
1258             defaultAudioPolicyConfig();
1259         }
1260     }
1261
1262     // open all output streams needed to access attached devices
1263     for (size_t i = 0; i < mHwModules.size(); i++) {
1264         mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
1265         if (mHwModules[i]->mHandle == 0) {
1266             ALOGW("could not open HW module %s", mHwModules[i]->mName);
1267             continue;
1268         }
1269         // open all output streams needed to access attached devices
1270         for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1271         {
1272             const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
1273
1274             if (outProfile->mSupportedDevices & mAttachedOutputDevices) {
1275                 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
1276                 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice &
1277                                                             outProfile->mSupportedDevices);
1278                 audio_io_handle_t output = mpClientInterface->openOutput(
1279                                                 outProfile->mModule->mHandle,
1280                                                 &outputDesc->mDevice,
1281                                                 &outputDesc->mSamplingRate,
1282                                                 &outputDesc->mFormat,
1283                                                 &outputDesc->mChannelMask,
1284                                                 &outputDesc->mLatency,
1285                                                 outputDesc->mFlags);
1286                 if (output == 0) {
1287                     delete outputDesc;
1288                 } else {
1289                     mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices |
1290                                             (outProfile->mSupportedDevices & mAttachedOutputDevices));
1291                     if (mPrimaryOutput == 0 &&
1292                             outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1293                         mPrimaryOutput = output;
1294                     }
1295                     addOutput(output, outputDesc);
1296                     setOutputDevice(output,
1297                                     (audio_devices_t)(mDefaultOutputDevice &
1298                                                         outProfile->mSupportedDevices),
1299                                     true);
1300                 }
1301             }
1302         }
1303     }
1304
1305     ALOGE_IF((mAttachedOutputDevices & ~mAvailableOutputDevices),
1306              "Not output found for attached devices %08x",
1307              (mAttachedOutputDevices & ~mAvailableOutputDevices));
1308
1309     ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1310
1311     updateDeviceForStrategy();
1312
1313 #ifdef AUDIO_POLICY_TEST
1314     if (mPrimaryOutput != 0) {
1315         AudioParameter outputCmd = AudioParameter();
1316         outputCmd.addInt(String8("set_id"), 0);
1317         mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1318
1319         mTestDevice = AudioSystem::DEVICE_OUT_SPEAKER;
1320         mTestSamplingRate = 44100;
1321         mTestFormat = AudioSystem::PCM_16_BIT;
1322         mTestChannels =  AudioSystem::CHANNEL_OUT_STEREO;
1323         mTestLatencyMs = 0;
1324         mCurOutput = 0;
1325         mDirectOutput = false;
1326         for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1327             mTestOutputs[i] = 0;
1328         }
1329
1330         const size_t SIZE = 256;
1331         char buffer[SIZE];
1332         snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1333         run(buffer, ANDROID_PRIORITY_AUDIO);
1334     }
1335 #endif //AUDIO_POLICY_TEST
1336 }
1337
1338 AudioPolicyManagerBase::~AudioPolicyManagerBase()
1339 {
1340 #ifdef AUDIO_POLICY_TEST
1341     exit();
1342 #endif //AUDIO_POLICY_TEST
1343    for (size_t i = 0; i < mOutputs.size(); i++) {
1344         mpClientInterface->closeOutput(mOutputs.keyAt(i));
1345         delete mOutputs.valueAt(i);
1346    }
1347    for (size_t i = 0; i < mInputs.size(); i++) {
1348         mpClientInterface->closeInput(mInputs.keyAt(i));
1349         delete mInputs.valueAt(i);
1350    }
1351    for (size_t i = 0; i < mHwModules.size(); i++) {
1352         delete mHwModules[i];
1353    }
1354 }
1355
1356 status_t AudioPolicyManagerBase::initCheck()
1357 {
1358     return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1359 }
1360
1361 #ifdef AUDIO_POLICY_TEST
1362 bool AudioPolicyManagerBase::threadLoop()
1363 {
1364     ALOGV("entering threadLoop()");
1365     while (!exitPending())
1366     {
1367         String8 command;
1368         int valueInt;
1369         String8 value;
1370
1371         Mutex::Autolock _l(mLock);
1372         mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1373
1374         command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1375         AudioParameter param = AudioParameter(command);
1376
1377         if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1378             valueInt != 0) {
1379             ALOGV("Test command %s received", command.string());
1380             String8 target;
1381             if (param.get(String8("target"), target) != NO_ERROR) {
1382                 target = "Manager";
1383             }
1384             if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1385                 param.remove(String8("test_cmd_policy_output"));
1386                 mCurOutput = valueInt;
1387             }
1388             if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1389                 param.remove(String8("test_cmd_policy_direct"));
1390                 if (value == "false") {
1391                     mDirectOutput = false;
1392                 } else if (value == "true") {
1393                     mDirectOutput = true;
1394                 }
1395             }
1396             if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1397                 param.remove(String8("test_cmd_policy_input"));
1398                 mTestInput = valueInt;
1399             }
1400
1401             if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1402                 param.remove(String8("test_cmd_policy_format"));
1403                 int format = AudioSystem::INVALID_FORMAT;
1404                 if (value == "PCM 16 bits") {
1405                     format = AudioSystem::PCM_16_BIT;
1406                 } else if (value == "PCM 8 bits") {
1407                     format = AudioSystem::PCM_8_BIT;
1408                 } else if (value == "Compressed MP3") {
1409                     format = AudioSystem::MP3;
1410                 }
1411                 if (format != AudioSystem::INVALID_FORMAT) {
1412                     if (target == "Manager") {
1413                         mTestFormat = format;
1414                     } else if (mTestOutputs[mCurOutput] != 0) {
1415                         AudioParameter outputParam = AudioParameter();
1416                         outputParam.addInt(String8("format"), format);
1417                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1418                     }
1419                 }
1420             }
1421             if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1422                 param.remove(String8("test_cmd_policy_channels"));
1423                 int channels = 0;
1424
1425                 if (value == "Channels Stereo") {
1426                     channels =  AudioSystem::CHANNEL_OUT_STEREO;
1427                 } else if (value == "Channels Mono") {
1428                     channels =  AudioSystem::CHANNEL_OUT_MONO;
1429                 }
1430                 if (channels != 0) {
1431                     if (target == "Manager") {
1432                         mTestChannels = channels;
1433                     } else if (mTestOutputs[mCurOutput] != 0) {
1434                         AudioParameter outputParam = AudioParameter();
1435                         outputParam.addInt(String8("channels"), channels);
1436                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1437                     }
1438                 }
1439             }
1440             if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1441                 param.remove(String8("test_cmd_policy_sampleRate"));
1442                 if (valueInt >= 0 && valueInt <= 96000) {
1443                     int samplingRate = valueInt;
1444                     if (target == "Manager") {
1445                         mTestSamplingRate = samplingRate;
1446                     } else if (mTestOutputs[mCurOutput] != 0) {
1447                         AudioParameter outputParam = AudioParameter();
1448                         outputParam.addInt(String8("sampling_rate"), samplingRate);
1449                         mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1450                     }
1451                 }
1452             }
1453
1454             if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1455                 param.remove(String8("test_cmd_policy_reopen"));
1456
1457                 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
1458                 mpClientInterface->closeOutput(mPrimaryOutput);
1459
1460                 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
1461
1462                 delete mOutputs.valueFor(mPrimaryOutput);
1463                 mOutputs.removeItem(mPrimaryOutput);
1464
1465                 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1466                 outputDesc->mDevice = (uint32_t)AudioSystem::DEVICE_OUT_SPEAKER;
1467                 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
1468                                                 &outputDesc->mDevice,
1469                                                 &outputDesc->mSamplingRate,
1470                                                 &outputDesc->mFormat,
1471                                                 &outputDesc->mChannelMask,
1472                                                 &outputDesc->mLatency,
1473                                                 outputDesc->mFlags);
1474                 if (mPrimaryOutput == 0) {
1475                     ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1476                             outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
1477                 } else {
1478                     AudioParameter outputCmd = AudioParameter();
1479                     outputCmd.addInt(String8("set_id"), 0);
1480                     mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1481                     addOutput(mPrimaryOutput, outputDesc);
1482                 }
1483             }
1484
1485
1486             mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1487         }
1488     }
1489     return false;
1490 }
1491
1492 void AudioPolicyManagerBase::exit()
1493 {
1494     {
1495         AutoMutex _l(mLock);
1496         requestExit();
1497         mWaitWorkCV.signal();
1498     }
1499     requestExitAndWait();
1500 }
1501
1502 int AudioPolicyManagerBase::testOutputIndex(audio_io_handle_t output)
1503 {
1504     for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1505         if (output == mTestOutputs[i]) return i;
1506     }
1507     return 0;
1508 }
1509 #endif //AUDIO_POLICY_TEST
1510
1511 // ---
1512
1513 void AudioPolicyManagerBase::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
1514 {
1515     outputDesc->mId = id;
1516     mOutputs.add(id, outputDesc);
1517 }
1518
1519
1520 status_t AudioPolicyManagerBase::checkOutputsForDevice(audio_devices_t device,
1521                                                        AudioSystem::device_connection_state state,
1522                                                        SortedVector<audio_io_handle_t>& outputs)
1523 {
1524     AudioOutputDescriptor *desc;
1525
1526     if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
1527         // first list already open outputs that can be routed to this device
1528         for (size_t i = 0; i < mOutputs.size(); i++) {
1529             desc = mOutputs.valueAt(i);
1530             if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices & device)) {
1531                 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
1532                 outputs.add(mOutputs.keyAt(i));
1533             }
1534         }
1535         // then look for output profiles that can be routed to this device
1536         SortedVector<IOProfile *> profiles;
1537         for (size_t i = 0; i < mHwModules.size(); i++)
1538         {
1539             if (mHwModules[i]->mHandle == 0) {
1540                 continue;
1541             }
1542             for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1543             {
1544                 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices & device) {
1545                     ALOGV("checkOutputsForDevice(): adding profile %d from module %d", j, i);
1546                     profiles.add(mHwModules[i]->mOutputProfiles[j]);
1547                 }
1548             }
1549         }
1550
1551         if (profiles.isEmpty() && outputs.isEmpty()) {
1552             ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1553             return BAD_VALUE;
1554         }
1555
1556         // open outputs for matching profiles if needed. Direct outputs are also opened to
1557         // query for dynamic parameters and will be closed later by setDeviceConnectionState()
1558         for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
1559             IOProfile *profile = profiles[profile_index];
1560
1561             // nothing to do if one output is already opened for this profile
1562             size_t j;
1563             for (j = 0; j < outputs.size(); j++) {
1564                 desc = mOutputs.valueAt(j);
1565                 if (!desc->isDuplicated() && desc->mProfile == profile) {
1566                     break;
1567                 }
1568             }
1569             if (j != outputs.size()) {
1570                 continue;
1571             }
1572
1573             ALOGV("opening output for device %08x", device);
1574             desc = new AudioOutputDescriptor(profile);
1575             desc->mDevice = device;
1576             audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
1577                                                                        &desc->mDevice,
1578                                                                        &desc->mSamplingRate,
1579                                                                        &desc->mFormat,
1580                                                                        &desc->mChannelMask,
1581                                                                        &desc->mLatency,
1582                                                                        desc->mFlags);
1583             if (output != 0) {
1584                 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1585                     String8 reply;
1586                     char *value;
1587                     if (profile->mSamplingRates[0] == 0) {
1588                         reply = mpClientInterface->getParameters(output,
1589                                                 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
1590                         ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
1591                                   reply.string());
1592                         value = strpbrk((char *)reply.string(), "=");
1593                         if (value != NULL) {
1594                             loadSamplingRates(value, profile);
1595                         }
1596                     }
1597                     if (profile->mFormats[0] == 0) {
1598                         reply = mpClientInterface->getParameters(output,
1599                                                        String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
1600                         ALOGV("checkOutputsForDevice() direct output sup formats %s",
1601                                   reply.string());
1602                         value = strpbrk((char *)reply.string(), "=");
1603                         if (value != NULL) {
1604                             loadFormats(value, profile);
1605                         }
1606                     }
1607                     if (profile->mChannelMasks[0] == 0) {
1608                         reply = mpClientInterface->getParameters(output,
1609                                                       String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
1610                         ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
1611                                   reply.string());
1612                         value = strpbrk((char *)reply.string(), "=");
1613                         if (value != NULL) {
1614                             loadOutChannels(value + 1, profile);
1615                         }
1616                     }
1617                     if (((profile->mSamplingRates[0] == 0) &&
1618                              (profile->mSamplingRates.size() < 2)) ||
1619                          ((profile->mFormats[0] == 0) &&
1620                              (profile->mFormats.size() < 2)) ||
1621                          ((profile->mFormats[0] == 0) &&
1622                              (profile->mChannelMasks.size() < 2))) {
1623                         ALOGW("checkOutputsForDevice() direct output missing param");
1624                         output = 0;
1625                     } else {
1626                         addOutput(output, desc);
1627                     }
1628                 } else {
1629                     audio_io_handle_t duplicatedOutput = 0;
1630                     // add output descriptor
1631                     addOutput(output, desc);
1632                     // set initial stream volume for device
1633                     applyStreamVolumes(output, device);
1634
1635                     //TODO: configure audio effect output stage here
1636
1637                     // open a duplicating output thread for the new output and the primary output
1638                     duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
1639                                                                               mPrimaryOutput);
1640                     if (duplicatedOutput != 0) {
1641                         // add duplicated output descriptor
1642                         AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
1643                         dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
1644                         dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
1645                         dupOutputDesc->mSamplingRate = desc->mSamplingRate;
1646                         dupOutputDesc->mFormat = desc->mFormat;
1647                         dupOutputDesc->mChannelMask = desc->mChannelMask;
1648                         dupOutputDesc->mLatency = desc->mLatency;
1649                         addOutput(duplicatedOutput, dupOutputDesc);
1650                         applyStreamVolumes(duplicatedOutput, device);
1651                     } else {
1652                         ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
1653                                 mPrimaryOutput, output);
1654                         mpClientInterface->closeOutput(output);
1655                         mOutputs.removeItem(output);
1656                         output = 0;
1657                     }
1658                 }
1659             }
1660             if (output == 0) {
1661                 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
1662                 delete desc;
1663                 profiles.removeAt(profile_index);
1664                 profile_index--;
1665             } else {
1666                 outputs.add(output);
1667                 ALOGV("checkOutputsForDevice(): adding output %d", output);
1668             }
1669         }
1670
1671         if (profiles.isEmpty()) {
1672             ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
1673             return BAD_VALUE;
1674         }
1675     } else {
1676         // check if one opened output is not needed any more after disconnecting one device
1677         for (size_t i = 0; i < mOutputs.size(); i++) {
1678             desc = mOutputs.valueAt(i);
1679             if (!desc->isDuplicated() &&
1680                     !(desc->mProfile->mSupportedDevices & mAvailableOutputDevices)) {
1681                 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
1682                 outputs.add(mOutputs.keyAt(i));
1683             }
1684         }
1685         for (size_t i = 0; i < mHwModules.size(); i++)
1686         {
1687             if (mHwModules[i]->mHandle == 0) {
1688                 continue;
1689             }
1690             for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1691             {
1692                 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
1693                 if ((profile->mSupportedDevices & device) &&
1694                         (profile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
1695                     ALOGV("checkOutputsForDevice(): clearing direct output profile %d on module %d",
1696                           j, i);
1697                     if (profile->mSamplingRates[0] == 0) {
1698                         profile->mSamplingRates.clear();
1699                         profile->mSamplingRates.add(0);
1700                     }
1701                     if (profile->mFormats[0] == 0) {
1702                         profile->mFormats.clear();
1703                         profile->mFormats.add((audio_format_t)0);
1704                     }
1705                     if (profile->mChannelMasks[0] == 0) {
1706                         profile->mChannelMasks.clear();
1707                         profile->mChannelMasks.add((audio_channel_mask_t)0);
1708                     }
1709                 }
1710             }
1711         }
1712     }
1713     return NO_ERROR;
1714 }
1715
1716 void AudioPolicyManagerBase::closeOutput(audio_io_handle_t output)
1717 {
1718     ALOGV("closeOutput(%d)", output);
1719
1720     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1721     if (outputDesc == NULL) {
1722         ALOGW("closeOutput() unknown output %d", output);
1723         return;
1724     }
1725
1726     // look for duplicated outputs connected to the output being removed.
1727     for (size_t i = 0; i < mOutputs.size(); i++) {
1728         AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
1729         if (dupOutputDesc->isDuplicated() &&
1730                 (dupOutputDesc->mOutput1 == outputDesc ||
1731                 dupOutputDesc->mOutput2 == outputDesc)) {
1732             AudioOutputDescriptor *outputDesc2;
1733             if (dupOutputDesc->mOutput1 == outputDesc) {
1734                 outputDesc2 = dupOutputDesc->mOutput2;
1735             } else {
1736                 outputDesc2 = dupOutputDesc->mOutput1;
1737             }
1738             // As all active tracks on duplicated output will be deleted,
1739             // and as they were also referenced on the other output, the reference
1740             // count for their stream type must be adjusted accordingly on
1741             // the other output.
1742             for (int j = 0; j < (int)AudioSystem::NUM_STREAM_TYPES; j++) {
1743                 int refCount = dupOutputDesc->mRefCount[j];
1744                 outputDesc2->changeRefCount((AudioSystem::stream_type)j,-refCount);
1745             }
1746             audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
1747             ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
1748
1749             mpClientInterface->closeOutput(duplicatedOutput);
1750             delete mOutputs.valueFor(duplicatedOutput);
1751             mOutputs.removeItem(duplicatedOutput);
1752         }
1753     }
1754
1755     AudioParameter param;
1756     param.add(String8("closing"), String8("true"));
1757     mpClientInterface->setParameters(output, param.toString());
1758
1759     mpClientInterface->closeOutput(output);
1760     delete mOutputs.valueFor(output);
1761     mOutputs.removeItem(output);
1762 }
1763
1764 SortedVector<audio_io_handle_t> AudioPolicyManagerBase::getOutputsForDevice(audio_devices_t device)
1765 {
1766     SortedVector<audio_io_handle_t> outputs;
1767
1768     ALOGVV("getOutputsForDevice() device %04x", device);
1769     for (size_t i = 0; i < mOutputs.size(); i++) {
1770         ALOGVV("output %d isDuplicated=%d device=%04x",
1771                 i, mOutputs.valueAt(i)->isDuplicated(), mOutputs.valueAt(i)->supportedDevices());
1772         if ((device & mOutputs.valueAt(i)->supportedDevices()) == device) {
1773             ALOGVV("getOutputsForDevice() found output %d", mOutputs.keyAt(i));
1774             outputs.add(mOutputs.keyAt(i));
1775         }
1776     }
1777     return outputs;
1778 }
1779
1780 bool AudioPolicyManagerBase::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
1781                                    SortedVector<audio_io_handle_t>& outputs2)
1782 {
1783     if (outputs1.size() != outputs2.size()) {
1784         return false;
1785     }
1786     for (size_t i = 0; i < outputs1.size(); i++) {
1787         if (outputs1[i] != outputs2[i]) {
1788             return false;
1789         }
1790     }
1791     return true;
1792 }
1793
1794 void AudioPolicyManagerBase::checkOutputForStrategy(routing_strategy strategy)
1795 {
1796     audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
1797     audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
1798     SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice);
1799     SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice);
1800
1801     if (!vectorsEqual(srcOutputs,dstOutputs)) {
1802         ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
1803               strategy, srcOutputs[0], dstOutputs[0]);
1804         // mute strategy while moving tracks from one output to another
1805         for (size_t i = 0; i < srcOutputs.size(); i++) {
1806             AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
1807             if (desc->strategyRefCount(strategy) != 0) {
1808                 setStrategyMute(strategy, true, srcOutputs[i]);
1809                 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
1810             }
1811         }
1812
1813         // Move effects associated to this strategy from previous output to new output
1814         if (strategy == STRATEGY_MEDIA) {
1815             int outIdx = 0;
1816             for (size_t i = 0; i < dstOutputs.size(); i++) {
1817                 AudioOutputDescriptor *desc = mOutputs.valueFor(dstOutputs[i]);
1818                 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) {
1819                     outIdx = i;
1820                 }
1821             }
1822             SortedVector<audio_io_handle_t> moved;
1823             for (size_t i = 0; i < mEffects.size(); i++) {
1824                 EffectDescriptor *desc = mEffects.valueAt(i);
1825                 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
1826                         desc->mIo != dstOutputs[outIdx]) {
1827                     if (moved.indexOf(desc->mIo) < 0) {
1828                         ALOGV("checkOutputForStrategy() moving effect %d to output %d",
1829                               mEffects.keyAt(i), dstOutputs[outIdx]);
1830                         mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
1831                                                        dstOutputs[outIdx]);
1832                         moved.add(desc->mIo);
1833                     }
1834                     desc->mIo = dstOutputs[outIdx];
1835                 }
1836             }
1837         }
1838         // Move tracks associated to this strategy from previous output to new output
1839         for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
1840             if (getStrategy((AudioSystem::stream_type)i) == strategy) {
1841                 //FIXME see fixme on name change
1842                 mpClientInterface->setStreamOutput((AudioSystem::stream_type)i,
1843                                                    dstOutputs[0] /* ignored */);
1844             }
1845         }
1846     }
1847 }
1848
1849 void AudioPolicyManagerBase::checkOutputForAllStrategies()
1850 {
1851     checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
1852     checkOutputForStrategy(STRATEGY_PHONE);
1853     checkOutputForStrategy(STRATEGY_SONIFICATION);
1854     checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
1855     checkOutputForStrategy(STRATEGY_MEDIA);
1856     checkOutputForStrategy(STRATEGY_DTMF);
1857 }
1858
1859 audio_io_handle_t AudioPolicyManagerBase::getA2dpOutput()
1860 {
1861     if (!mHasA2dp) {
1862         return 0;
1863     }
1864
1865     for (size_t i = 0; i < mOutputs.size(); i++) {
1866         AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1867         if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
1868             return mOutputs.keyAt(i);
1869         }
1870     }
1871
1872     return 0;
1873 }
1874
1875 void AudioPolicyManagerBase::checkA2dpSuspend()
1876 {
1877     if (!mHasA2dp) {
1878         return;
1879     }
1880     audio_io_handle_t a2dpOutput = getA2dpOutput();
1881     if (a2dpOutput == 0) {
1882         return;
1883     }
1884
1885     // suspend A2DP output if:
1886     //      (NOT already suspended) &&
1887     //      ((SCO device is connected &&
1888     //       (forced usage for communication || for record is SCO))) ||
1889     //      (phone state is ringing || in call)
1890     //
1891     // restore A2DP output if:
1892     //      (Already suspended) &&
1893     //      ((SCO device is NOT connected ||
1894     //       (forced usage NOT for communication && NOT for record is SCO))) &&
1895     //      (phone state is NOT ringing && NOT in call)
1896     //
1897     if (mA2dpSuspended) {
1898         if (((mScoDeviceAddress == "") ||
1899              ((mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO) &&
1900               (mForceUse[AudioSystem::FOR_RECORD] != AudioSystem::FORCE_BT_SCO))) &&
1901              ((mPhoneState != AudioSystem::MODE_IN_CALL) &&
1902               (mPhoneState != AudioSystem::MODE_RINGTONE))) {
1903
1904             mpClientInterface->restoreOutput(a2dpOutput);
1905             mA2dpSuspended = false;
1906         }
1907     } else {
1908         if (((mScoDeviceAddress != "") &&
1909              ((mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
1910               (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO))) ||
1911              ((mPhoneState == AudioSystem::MODE_IN_CALL) ||
1912               (mPhoneState == AudioSystem::MODE_RINGTONE))) {
1913
1914             mpClientInterface->suspendOutput(a2dpOutput);
1915             mA2dpSuspended = true;
1916         }
1917     }
1918 }
1919
1920 audio_devices_t AudioPolicyManagerBase::getNewDevice(audio_io_handle_t output, bool fromCache)
1921 {
1922     audio_devices_t device = (audio_devices_t)0;
1923
1924     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
1925     // check the following by order of priority to request a routing change if necessary:
1926     // 1: the strategy enforced audible is active on the output:
1927     //      use device for strategy enforced audible
1928     // 2: we are in call or the strategy phone is active on the output:
1929     //      use device for strategy phone
1930     // 3: the strategy sonification is active on the output:
1931     //      use device for strategy sonification
1932     // 4: the strategy "respectful" sonification is active on the output:
1933     //      use device for strategy "respectful" sonification
1934     // 5: the strategy media is active on the output:
1935     //      use device for strategy media
1936     // 6: the strategy DTMF is active on the output:
1937     //      use device for strategy DTMF
1938     if (outputDesc->isUsedByStrategy(STRATEGY_ENFORCED_AUDIBLE)) {
1939         device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
1940     } else if (isInCall() ||
1941                     outputDesc->isUsedByStrategy(STRATEGY_PHONE)) {
1942         device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
1943     } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION)) {
1944         device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
1945     } else if (outputDesc->isUsedByStrategy(STRATEGY_SONIFICATION_RESPECTFUL)) {
1946         device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
1947     } else if (outputDesc->isUsedByStrategy(STRATEGY_MEDIA)) {
1948         device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
1949     } else if (outputDesc->isUsedByStrategy(STRATEGY_DTMF)) {
1950         device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
1951     }
1952
1953     ALOGV("getNewDevice() selected device %x", device);
1954     return device;
1955 }
1956
1957 uint32_t AudioPolicyManagerBase::getStrategyForStream(AudioSystem::stream_type stream) {
1958     return (uint32_t)getStrategy(stream);
1959 }
1960
1961 audio_devices_t AudioPolicyManagerBase::getDevicesForStream(AudioSystem::stream_type stream) {
1962     audio_devices_t devices;
1963     // By checking the range of stream before calling getStrategy, we avoid
1964     // getStrategy's behavior for invalid streams.  getStrategy would do a ALOGE
1965     // and then return STRATEGY_MEDIA, but we want to return the empty set.
1966     if (stream < (AudioSystem::stream_type) 0 || stream >= AudioSystem::NUM_STREAM_TYPES) {
1967         devices = (audio_devices_t)0;
1968     } else {
1969         AudioPolicyManagerBase::routing_strategy strategy = getStrategy(stream);
1970         devices = getDeviceForStrategy(strategy, true /*fromCache*/);
1971     }
1972     return devices;
1973 }
1974
1975 AudioPolicyManagerBase::routing_strategy AudioPolicyManagerBase::getStrategy(
1976         AudioSystem::stream_type stream) {
1977     // stream to strategy mapping
1978     switch (stream) {
1979     case AudioSystem::VOICE_CALL:
1980     case AudioSystem::BLUETOOTH_SCO:
1981         return STRATEGY_PHONE;
1982     case AudioSystem::RING:
1983     case AudioSystem::ALARM:
1984         return STRATEGY_SONIFICATION;
1985     case AudioSystem::NOTIFICATION:
1986         return STRATEGY_SONIFICATION_RESPECTFUL;
1987     case AudioSystem::DTMF:
1988         return STRATEGY_DTMF;
1989     default:
1990         ALOGE("unknown stream type");
1991     case AudioSystem::SYSTEM:
1992         // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
1993         // while key clicks are played produces a poor result
1994     case AudioSystem::TTS:
1995     case AudioSystem::MUSIC:
1996         return STRATEGY_MEDIA;
1997     case AudioSystem::ENFORCED_AUDIBLE:
1998         return STRATEGY_ENFORCED_AUDIBLE;
1999     }
2000 }
2001
2002 void AudioPolicyManagerBase::handleNotificationRoutingForStream(AudioSystem::stream_type stream) {
2003     switch(stream) {
2004     case AudioSystem::MUSIC:
2005         checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2006         updateDeviceForStrategy();
2007         break;
2008     default:
2009         break;
2010     }
2011 }
2012
2013 audio_devices_t AudioPolicyManagerBase::getDeviceForStrategy(routing_strategy strategy,
2014                                                              bool fromCache)
2015 {
2016     uint32_t device = 0;
2017
2018     if (fromCache) {
2019         ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
2020               strategy, mDeviceForStrategy[strategy]);
2021         return mDeviceForStrategy[strategy];
2022     }
2023
2024     switch (strategy) {
2025
2026     case STRATEGY_SONIFICATION_RESPECTFUL:
2027         if (isInCall()) {
2028             device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2029         } else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2030             // while media is playing (or has recently played), use the same device
2031             device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2032         } else {
2033             // when media is not playing anymore, fall back on the sonification behavior
2034             device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2035         }
2036
2037         break;
2038
2039     case STRATEGY_DTMF:
2040         if (!isInCall()) {
2041             // when off call, DTMF strategy follows the same rules as MEDIA strategy
2042             device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2043             break;
2044         }
2045         // when in call, DTMF and PHONE strategies follow the same rules
2046         // FALL THROUGH
2047
2048     case STRATEGY_PHONE:
2049         // for phone strategy, we first consider the forced use and then the available devices by order
2050         // of priority
2051         switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
2052         case AudioSystem::FORCE_BT_SCO:
2053             if (!isInCall() || strategy != STRATEGY_DTMF) {
2054                 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
2055                 if (device) break;
2056             }
2057             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
2058             if (device) break;
2059             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_SCO;
2060             if (device) break;
2061             // if SCO device is requested but no SCO device is available, fall back to default case
2062             // FALL THROUGH
2063
2064         default:    // FORCE_NONE
2065             // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
2066             if (mHasA2dp && !isInCall() &&
2067                     (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2068                     (getA2dpOutput() != 0) && !mA2dpSuspended) {
2069                 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
2070                 if (device) break;
2071                 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2072                 if (device) break;
2073             }
2074             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
2075             if (device) break;
2076             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
2077             if (device) break;
2078             device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2079             if (device) break;
2080             device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2081             if (device) break;
2082             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
2083             if (device) break;
2084             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
2085             if (device) break;
2086             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
2087             if (device) break;
2088             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_EARPIECE;
2089             if (device) break;
2090             device = mDefaultOutputDevice;
2091             if (device == 0) {
2092                 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
2093             }
2094             break;
2095
2096         case AudioSystem::FORCE_SPEAKER:
2097             // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
2098             // A2DP speaker when forcing to speaker output
2099             if (mHasA2dp && !isInCall() &&
2100                     (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2101                     (getA2dpOutput() != 0) && !mA2dpSuspended) {
2102                 device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2103                 if (device) break;
2104             }
2105             device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2106             if (device) break;
2107             device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2108             if (device) break;
2109             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
2110             if (device) break;
2111             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
2112             if (device) break;
2113             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
2114             if (device) break;
2115             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
2116             if (device) break;
2117             device = mDefaultOutputDevice;
2118             if (device == 0) {
2119                 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
2120             }
2121             break;
2122         }
2123     break;
2124
2125     case STRATEGY_SONIFICATION:
2126
2127         // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
2128         // handleIncallSonification().
2129         if (isInCall()) {
2130             device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
2131             break;
2132         }
2133         // FALL THROUGH
2134
2135     case STRATEGY_ENFORCED_AUDIBLE:
2136         // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2137         // except:
2138         //   - when in call where it doesn't default to STRATEGY_PHONE behavior
2139         //   - in countries where not enforced in which case it follows STRATEGY_MEDIA
2140
2141         if (strategy == STRATEGY_SONIFICATION ||
2142                 !mStreams[AUDIO_STREAM_ENFORCED_AUDIBLE].mCanBeMuted) {
2143             device = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
2144             if (device == 0) {
2145                 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2146             }
2147         }
2148         // The second device used for sonification is the same as the device used by media strategy
2149         // FALL THROUGH
2150
2151     case STRATEGY_MEDIA: {
2152         uint32_t device2 = 0;
2153         if (mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
2154                 (getA2dpOutput() != 0) && !mA2dpSuspended) {
2155             device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP;
2156             if (device2 == 0) {
2157                 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
2158             }
2159             if (device2 == 0) {
2160                 device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
2161             }
2162         }
2163         if (device2 == 0) {
2164             device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADPHONE;
2165         }
2166         if (device2 == 0) {
2167             device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_WIRED_HEADSET;
2168         }
2169         if (device2 == 0) {
2170             device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
2171         }
2172         if (device2 == 0) {
2173             device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
2174         }
2175         if (device2 == 0) {
2176             device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_DGTL_DOCK_HEADSET;
2177         }
2178         if (device2 == 0) {
2179             device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_AUX_DIGITAL;
2180         }
2181         if (device2 == 0) {
2182             device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_ANLG_DOCK_HEADSET;
2183         }
2184         if (device2 == 0) {
2185             device2 = mAvailableOutputDevices & AudioSystem::DEVICE_OUT_SPEAKER;
2186         }
2187
2188         // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2189         // STRATEGY_ENFORCED_AUDIBLE, 0 otherwise
2190         device |= device2;
2191         if (device) break;
2192         device = mDefaultOutputDevice;
2193         if (device == 0) {
2194             ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2195         }
2196         } break;
2197
2198     default:
2199         ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2200         break;
2201     }
2202
2203     ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2204     return (audio_devices_t)device;
2205 }
2206
2207 void AudioPolicyManagerBase::updateDeviceForStrategy()
2208 {
2209     for (int i = 0; i < NUM_STRATEGIES; i++) {
2210         mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2211     }
2212 }
2213
2214 uint32_t AudioPolicyManagerBase::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
2215                                                        audio_devices_t prevDevice,
2216                                                        uint32_t delayMs)
2217 {
2218     // mute/unmute strategies using an incompatible device combination
2219     // if muting, wait for the audio in pcm buffer to be drained before proceeding
2220     // if unmuting, unmute only after the specified delay
2221     if (outputDesc->isDuplicated()) {
2222         return 0;
2223     }
2224
2225     uint32_t muteWaitMs = 0;
2226     audio_devices_t device = outputDesc->device();
2227     bool shouldMute = (outputDesc->refCount() != 0) &&
2228                     (AudioSystem::popCount(device) >= 2);
2229     // temporary mute output if device selection changes to avoid volume bursts due to
2230     // different per device volumes
2231     bool tempMute = (outputDesc->refCount() != 0) && (device != prevDevice);
2232
2233     for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2234         audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2235         bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2236         bool doMute = false;
2237
2238         if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2239             doMute = true;
2240             outputDesc->mStrategyMutedByDevice[i] = true;
2241         } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2242             doMute = true;
2243             outputDesc->mStrategyMutedByDevice[i] = false;
2244         }
2245         if (doMute || tempMute) {
2246             for (size_t j = 0; j < mOutputs.size(); j++) {
2247                 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2248                 if ((desc->supportedDevices() & outputDesc->supportedDevices()) == 0) {
2249                     continue;
2250                 }
2251                 audio_io_handle_t curOutput = mOutputs.keyAt(j);
2252                 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2253                       mute ? "muting" : "unmuting", i, curDevice, curOutput);
2254                 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2255                 if (desc->strategyRefCount((routing_strategy)i) != 0) {
2256                     if (tempMute) {
2257                         setStrategyMute((routing_strategy)i, true, curOutput);
2258                         setStrategyMute((routing_strategy)i, false, curOutput,
2259                                             desc->latency() * 2, device);
2260                     }
2261                     if (tempMute || mute) {
2262                         if (muteWaitMs < desc->latency()) {
2263                             muteWaitMs = desc->latency();
2264                         }
2265                     }
2266                 }
2267             }
2268         }
2269     }
2270
2271     // FIXME: should not need to double latency if volume could be applied immediately by the
2272     // audioflinger mixer. We must account for the delay between now and the next time
2273     // the audioflinger thread for this output will process a buffer (which corresponds to
2274     // one buffer size, usually 1/2 or 1/4 of the latency).
2275     muteWaitMs *= 2;
2276     // wait for the PCM output buffers to empty before proceeding with the rest of the command
2277     if (muteWaitMs > delayMs) {
2278         muteWaitMs -= delayMs;
2279         usleep(muteWaitMs * 1000);
2280         return muteWaitMs;
2281     }
2282     return 0;
2283 }
2284
2285 uint32_t AudioPolicyManagerBase::setOutputDevice(audio_io_handle_t output,
2286                                              audio_devices_t device,
2287                                              bool force,
2288                                              int delayMs)
2289 {
2290     ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2291     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2292     AudioParameter param;
2293     uint32_t muteWaitMs = 0;
2294
2295     if (outputDesc->isDuplicated()) {
2296         muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2297         muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2298         return muteWaitMs;
2299     }
2300     // filter devices according to output selected
2301     device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices);
2302
2303     audio_devices_t prevDevice = outputDesc->mDevice;
2304
2305     ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
2306
2307     if (device != 0) {
2308         outputDesc->mDevice = device;
2309     }
2310     muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
2311
2312     // Do not change the routing if:
2313     //  - the requested device is 0
2314     //  - the requested device is the same as current device and force is not specified.
2315     // Doing this check here allows the caller to call setOutputDevice() without conditions
2316     if ((device == 0 || device == prevDevice) && !force) {
2317         ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
2318         return muteWaitMs;
2319     }
2320
2321     ALOGV("setOutputDevice() changing device");
2322     // do the routing
2323     param.addInt(String8(AudioParameter::keyRouting), (int)device);
2324     mpClientInterface->setParameters(output, param.toString(), delayMs);
2325
2326     // update stream volumes according to new device
2327     applyStreamVolumes(output, device, delayMs);
2328
2329     return muteWaitMs;
2330 }
2331
2332 AudioPolicyManagerBase::IOProfile *AudioPolicyManagerBase::getInputProfile(audio_devices_t device,
2333                                                    uint32_t samplingRate,
2334                                                    uint32_t format,
2335                                                    uint32_t channelMask)
2336 {
2337     // Choose an input profile based on the requested capture parameters: select the first available
2338     // profile supporting all requested parameters.
2339
2340     for (size_t i = 0; i < mHwModules.size(); i++)
2341     {
2342         if (mHwModules[i]->mHandle == 0) {
2343             continue;
2344         }
2345         for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2346         {
2347             IOProfile *profile = mHwModules[i]->mInputProfiles[j];
2348             if (profile->isCompatibleProfile(device, samplingRate, format,
2349                                              channelMask,(audio_output_flags_t)0)) {
2350                 return profile;
2351             }
2352         }
2353     }
2354     return NULL;
2355 }
2356
2357 audio_devices_t AudioPolicyManagerBase::getDeviceForInputSource(int inputSource)
2358 {
2359     uint32_t device = 0;
2360
2361     switch(inputSource) {
2362     case AUDIO_SOURCE_DEFAULT:
2363     case AUDIO_SOURCE_MIC:
2364     case AUDIO_SOURCE_VOICE_RECOGNITION:
2365     case AUDIO_SOURCE_VOICE_COMMUNICATION:
2366         if (mForceUse[AudioSystem::FOR_RECORD] == AudioSystem::FORCE_BT_SCO &&
2367             mAvailableInputDevices & AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
2368             device = AudioSystem::DEVICE_IN_BLUETOOTH_SCO_HEADSET;
2369         } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_WIRED_HEADSET) {
2370             device = AudioSystem::DEVICE_IN_WIRED_HEADSET;
2371         } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_BUILTIN_MIC) {
2372             device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
2373         }
2374         break;
2375     case AUDIO_SOURCE_CAMCORDER:
2376         if (mAvailableInputDevices & AudioSystem::DEVICE_IN_BACK_MIC) {
2377             device = AudioSystem::DEVICE_IN_BACK_MIC;
2378         } else if (mAvailableInputDevices & AudioSystem::DEVICE_IN_BUILTIN_MIC) {
2379             device = AudioSystem::DEVICE_IN_BUILTIN_MIC;
2380         }
2381         break;
2382     case AUDIO_SOURCE_VOICE_UPLINK:
2383     case AUDIO_SOURCE_VOICE_DOWNLINK:
2384     case AUDIO_SOURCE_VOICE_CALL:
2385         if (mAvailableInputDevices & AudioSystem::DEVICE_IN_VOICE_CALL) {
2386             device = AudioSystem::DEVICE_IN_VOICE_CALL;
2387         }
2388         break;
2389     default:
2390         ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
2391         break;
2392     }
2393     ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
2394     return (audio_devices_t)device;
2395 }
2396
2397 audio_io_handle_t AudioPolicyManagerBase::getActiveInput()
2398 {
2399     for (size_t i = 0; i < mInputs.size(); i++) {
2400         if (mInputs.valueAt(i)->mRefCount > 0) {
2401             return mInputs.keyAt(i);
2402         }
2403     }
2404     return 0;
2405 }
2406
2407
2408 audio_devices_t AudioPolicyManagerBase::getDeviceForVolume(audio_devices_t device)
2409 {
2410     if (device == 0) {
2411         // this happens when forcing a route update and no track is active on an output.
2412         // In this case the returned category is not important.
2413         device =  AUDIO_DEVICE_OUT_SPEAKER;
2414     } else if (AudioSystem::popCount(device) > 1) {
2415         // Multiple device selection is either:
2416         //  - speaker + one other device: give priority to speaker in this case.
2417         //  - one A2DP device + another device: happens with duplicated output. In this case
2418         // retain the device on the A2DP output as the other must not correspond to an active
2419         // selection if not the speaker.
2420         if (device & AUDIO_DEVICE_OUT_SPEAKER) {
2421             device = AUDIO_DEVICE_OUT_SPEAKER;
2422         } else {
2423             device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
2424         }
2425     }
2426
2427     ALOGW_IF(AudioSystem::popCount(device) != 1,
2428             "getDeviceForVolume() invalid device combination: %08x",
2429             device);
2430
2431     return device;
2432 }
2433
2434 AudioPolicyManagerBase::device_category AudioPolicyManagerBase::getDeviceCategory(audio_devices_t device)
2435 {
2436     switch(getDeviceForVolume(device)) {
2437         case AUDIO_DEVICE_OUT_EARPIECE:
2438             return DEVICE_CATEGORY_EARPIECE;
2439         case AUDIO_DEVICE_OUT_WIRED_HEADSET:
2440         case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
2441         case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
2442         case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
2443         case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
2444         case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
2445             return DEVICE_CATEGORY_HEADSET;
2446         case AUDIO_DEVICE_OUT_SPEAKER:
2447         case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
2448         case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
2449         case AUDIO_DEVICE_OUT_AUX_DIGITAL:
2450         case AUDIO_DEVICE_OUT_USB_ACCESSORY:
2451         case AUDIO_DEVICE_OUT_USB_DEVICE:
2452         default:
2453             return DEVICE_CATEGORY_SPEAKER;
2454     }
2455 }
2456
2457 float AudioPolicyManagerBase::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
2458         int indexInUi)
2459 {
2460     device_category deviceCategory = getDeviceCategory(device);
2461     const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
2462
2463     // the volume index in the UI is relative to the min and max volume indices for this stream type
2464     int nbSteps = 1 + curve[VOLMAX].mIndex -
2465             curve[VOLMIN].mIndex;
2466     int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
2467             (streamDesc.mIndexMax - streamDesc.mIndexMin);
2468
2469     // find what part of the curve this index volume belongs to, or if it's out of bounds
2470     int segment = 0;
2471     if (volIdx < curve[VOLMIN].mIndex) {         // out of bounds
2472         return 0.0f;
2473     } else if (volIdx < curve[VOLKNEE1].mIndex) {
2474         segment = 0;
2475     } else if (volIdx < curve[VOLKNEE2].mIndex) {
2476         segment = 1;
2477     } else if (volIdx <= curve[VOLMAX].mIndex) {
2478         segment = 2;
2479     } else {                                                               // out of bounds
2480         return 1.0f;
2481     }
2482
2483     // linear interpolation in the attenuation table in dB
2484     float decibels = curve[segment].mDBAttenuation +
2485             ((float)(volIdx - curve[segment].mIndex)) *
2486                 ( (curve[segment+1].mDBAttenuation -
2487                         curve[segment].mDBAttenuation) /
2488                     ((float)(curve[segment+1].mIndex -
2489                             curve[segment].mIndex)) );
2490
2491     float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
2492
2493     ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
2494             curve[segment].mIndex, volIdx,
2495             curve[segment+1].mIndex,
2496             curve[segment].mDBAttenuation,
2497             decibels,
2498             curve[segment+1].mDBAttenuation,
2499             amplification);
2500
2501     return amplification;
2502 }
2503
2504 const AudioPolicyManagerBase::VolumeCurvePoint
2505     AudioPolicyManagerBase::sDefaultVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2506     {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
2507 };
2508
2509 const AudioPolicyManagerBase::VolumeCurvePoint
2510     AudioPolicyManagerBase::sDefaultMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2511     {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
2512 };
2513
2514 const AudioPolicyManagerBase::VolumeCurvePoint
2515     AudioPolicyManagerBase::sSpeakerMediaVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2516     {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
2517 };
2518
2519 const AudioPolicyManagerBase::VolumeCurvePoint
2520     AudioPolicyManagerBase::sSpeakerSonificationVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2521     {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
2522 };
2523
2524 // AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
2525 // AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets (See AudioService.java).
2526 // The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
2527 const AudioPolicyManagerBase::VolumeCurvePoint
2528     AudioPolicyManagerBase::sDefaultSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2529     {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
2530 };
2531
2532 const AudioPolicyManagerBase::VolumeCurvePoint
2533     AudioPolicyManagerBase::sHeadsetSystemVolumeCurve[AudioPolicyManagerBase::VOLCNT] = {
2534     {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
2535 };
2536
2537 const AudioPolicyManagerBase::VolumeCurvePoint
2538             *AudioPolicyManagerBase::sVolumeProfiles[AUDIO_STREAM_CNT]
2539                                                    [AudioPolicyManagerBase::DEVICE_CATEGORY_CNT] = {
2540     { // AUDIO_STREAM_VOICE_CALL
2541         sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2542         sDefaultVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2543         sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2544     },
2545     { // AUDIO_STREAM_SYSTEM
2546         sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2547         sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2548         sDefaultSystemVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2549     },
2550     { // AUDIO_STREAM_RING
2551         sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2552         sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2553         sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2554     },
2555     { // AUDIO_STREAM_MUSIC
2556         sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2557         sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2558         sDefaultMediaVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2559     },
2560     { // AUDIO_STREAM_ALARM
2561         sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2562         sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2563         sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2564     },
2565     { // AUDIO_STREAM_NOTIFICATION
2566         sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2567         sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2568         sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2569     },
2570     { // AUDIO_STREAM_BLUETOOTH_SCO
2571         sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
2572         sDefaultVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2573         sDefaultVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2574     },
2575     { // AUDIO_STREAM_ENFORCED_AUDIBLE
2576         sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2577         sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2578         sDefaultSystemVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2579     },
2580     {  // AUDIO_STREAM_DTMF
2581         sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
2582         sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2583         sDefaultSystemVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2584     },
2585     { // AUDIO_STREAM_TTS
2586         sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
2587         sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
2588         sDefaultMediaVolumeCurve  // DEVICE_CATEGORY_EARPIECE
2589     },
2590 };
2591
2592 void AudioPolicyManagerBase::initializeVolumeCurves()
2593 {
2594     for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
2595         for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
2596             mStreams[i].mVolumeCurve[j] =
2597                     sVolumeProfiles[i][j];
2598         }
2599     }
2600 }
2601
2602 float AudioPolicyManagerBase::computeVolume(int stream,
2603                                             int index,
2604                                             audio_io_handle_t output,
2605                                             audio_devices_t device)
2606 {
2607     float volume = 1.0;
2608     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2609     StreamDescriptor &streamDesc = mStreams[stream];
2610
2611     if (device == 0) {
2612         device = outputDesc->device();
2613     }
2614
2615     // if volume is not 0 (not muted), force media volume to max on digital output
2616     if (stream == AudioSystem::MUSIC &&
2617         index != mStreams[stream].mIndexMin &&
2618         (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
2619          device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
2620          device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
2621          device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
2622         return 1.0;
2623     }
2624
2625     volume = volIndexToAmpl(device, streamDesc, index);
2626
2627     // if a headset is connected, apply the following rules to ring tones and notifications
2628     // to avoid sound level bursts in user's ears:
2629     // - always attenuate ring tones and notifications volume by 6dB
2630     // - if music is playing, always limit the volume to current music volume,
2631     // with a minimum threshold at -36dB so that notification is always perceived.
2632     const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2633     if ((device & (AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP |
2634             AudioSystem::DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
2635             AudioSystem::DEVICE_OUT_WIRED_HEADSET |
2636             AudioSystem::DEVICE_OUT_WIRED_HEADPHONE)) &&
2637         ((stream_strategy == STRATEGY_SONIFICATION)
2638                 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
2639                 || (stream == AudioSystem::SYSTEM)) &&
2640         streamDesc.mCanBeMuted) {
2641         volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
2642         // when the phone is ringing we must consider that music could have been paused just before
2643         // by the music application and behave as if music was active if the last music track was
2644         // just stopped
2645         if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
2646                 mLimitRingtoneVolume) {
2647             float musicVol = computeVolume(AudioSystem::MUSIC,
2648                                mStreams[AudioSystem::MUSIC].getVolumeIndex(device),
2649                                output,
2650                                device);
2651             float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
2652                                 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
2653             if (volume > minVol) {
2654                 volume = minVol;
2655                 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
2656             }
2657         }
2658     }
2659
2660     return volume;
2661 }
2662
2663 status_t AudioPolicyManagerBase::checkAndSetVolume(int stream,
2664                                                    int index,
2665                                                    audio_io_handle_t output,
2666                                                    audio_devices_t device,
2667                                                    int delayMs,
2668                                                    bool force)
2669 {
2670
2671     // do not change actual stream volume if the stream is muted
2672     if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
2673         ALOGVV("checkAndSetVolume() stream %d muted count %d",
2674               stream, mOutputs.valueFor(output)->mMuteCount[stream]);
2675         return NO_ERROR;
2676     }
2677
2678     // do not change in call volume if bluetooth is connected and vice versa
2679     if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
2680         (stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
2681         ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
2682              stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
2683         return INVALID_OPERATION;
2684     }
2685
2686     float volume = computeVolume(stream, index, output, device);
2687     // We actually change the volume if:
2688     // - the float value returned by computeVolume() changed
2689     // - the force flag is set
2690     if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
2691             force) {
2692         mOutputs.valueFor(output)->mCurVolume[stream] = volume;
2693         ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
2694         if (stream == AudioSystem::VOICE_CALL ||
2695             stream == AudioSystem::DTMF ||
2696             stream == AudioSystem::BLUETOOTH_SCO) {
2697             // offset value to reflect actual hardware volume that never reaches 0
2698             // 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
2699             volume = 0.01 + 0.99 * volume;
2700             // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
2701             // enabled
2702             if (stream == AudioSystem::BLUETOOTH_SCO) {
2703                 mpClientInterface->setStreamVolume(AudioSystem::VOICE_CALL, volume, output, delayMs);
2704             }
2705         }
2706
2707         mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
2708     }
2709
2710     if (stream == AudioSystem::VOICE_CALL ||
2711         stream == AudioSystem::BLUETOOTH_SCO) {
2712         float voiceVolume;
2713         // Force voice volume to max for bluetooth SCO as volume is managed by the headset
2714         if (stream == AudioSystem::VOICE_CALL) {
2715             voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
2716         } else {
2717             voiceVolume = 1.0;
2718         }
2719
2720         if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
2721             mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
2722             mLastVoiceVolume = voiceVolume;
2723         }
2724     }
2725
2726     return NO_ERROR;
2727 }
2728
2729 void AudioPolicyManagerBase::applyStreamVolumes(audio_io_handle_t output,
2730                                                 audio_devices_t device,
2731                                                 int delayMs,
2732                                                 bool force)
2733 {
2734     ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
2735
2736     for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2737         checkAndSetVolume(stream,
2738                           mStreams[stream].getVolumeIndex(device),
2739                           output,
2740                           device,
2741                           delayMs,
2742                           force);
2743     }
2744 }
2745
2746 void AudioPolicyManagerBase::setStrategyMute(routing_strategy strategy,
2747                                              bool on,
2748                                              audio_io_handle_t output,
2749                                              int delayMs,
2750                                              audio_devices_t device)
2751 {
2752     ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
2753     for (int stream = 0; stream < AudioSystem::NUM_STREAM_TYPES; stream++) {
2754         if (getStrategy((AudioSystem::stream_type)stream) == strategy) {
2755             setStreamMute(stream, on, output, delayMs, device);
2756         }
2757     }
2758 }
2759
2760 void AudioPolicyManagerBase::setStreamMute(int stream,
2761                                            bool on,
2762                                            audio_io_handle_t output,
2763                                            int delayMs,
2764                                            audio_devices_t device)
2765 {
2766     StreamDescriptor &streamDesc = mStreams[stream];
2767     AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2768     if (device == 0) {
2769         device = outputDesc->device();
2770     }
2771
2772     ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
2773           stream, on, output, outputDesc->mMuteCount[stream], device);
2774
2775     if (on) {
2776         if (outputDesc->mMuteCount[stream] == 0) {
2777             if (streamDesc.mCanBeMuted) {
2778                 checkAndSetVolume(stream, 0, output, device, delayMs);
2779             }
2780         }
2781         // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
2782         outputDesc->mMuteCount[stream]++;
2783     } else {
2784         if (outputDesc->mMuteCount[stream] == 0) {
2785             ALOGV("setStreamMute() unmuting non muted stream!");
2786             return;
2787         }
2788         if (--outputDesc->mMuteCount[stream] == 0) {
2789             checkAndSetVolume(stream,
2790                               streamDesc.getVolumeIndex((audio_devices_t)device),
2791                               output,
2792                               device,
2793                               delayMs);
2794         }
2795     }
2796 }
2797
2798 void AudioPolicyManagerBase::handleIncallSonification(int stream, bool starting, bool stateChange)
2799 {
2800     // if the stream pertains to sonification strategy and we are in call we must
2801     // mute the stream if it is low visibility. If it is high visibility, we must play a tone
2802     // in the device used for phone strategy and play the tone if the selected device does not
2803     // interfere with the device used for phone strategy
2804     // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
2805     // many times as there are active tracks on the output
2806     const routing_strategy stream_strategy = getStrategy((AudioSystem::stream_type)stream);
2807     if ((stream_strategy == STRATEGY_SONIFICATION) ||
2808             ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
2809         AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
2810         ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
2811                 stream, starting, outputDesc->mDevice, stateChange);
2812         if (outputDesc->mRefCount[stream]) {
2813             int muteCount = 1;
2814             if (stateChange) {
2815                 muteCount = outputDesc->mRefCount[stream];
2816             }
2817             if (AudioSystem::isLowVisibility((AudioSystem::stream_type)stream)) {
2818                 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
2819                 for (int i = 0; i < muteCount; i++) {
2820                     setStreamMute(stream, starting, mPrimaryOutput);
2821                 }
2822             } else {
2823                 ALOGV("handleIncallSonification() high visibility");
2824                 if (outputDesc->device() &
2825                         getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
2826                     ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
2827                     for (int i = 0; i < muteCount; i++) {
2828                         setStreamMute(stream, starting, mPrimaryOutput);
2829                     }
2830                 }
2831                 if (starting) {
2832                     mpClientInterface->startTone(ToneGenerator::TONE_SUP_CALL_WAITING, AudioSystem::VOICE_CALL);
2833                 } else {
2834                     mpClientInterface->stopTone();
2835                 }
2836             }
2837         }
2838     }
2839 }
2840
2841 bool AudioPolicyManagerBase::isInCall()
2842 {
2843     return isStateInCall(mPhoneState);
2844 }
2845
2846 bool AudioPolicyManagerBase::isStateInCall(int state) {
2847     return ((state == AudioSystem::MODE_IN_CALL) ||
2848             (state == AudioSystem::MODE_IN_COMMUNICATION));
2849 }
2850
2851 bool AudioPolicyManagerBase::needsDirectOuput(audio_stream_type_t stream,
2852                                               uint32_t samplingRate,
2853                                               audio_format_t format,
2854                                               audio_channel_mask_t channelMask,
2855                                               audio_output_flags_t flags,
2856                                               audio_devices_t device)
2857 {
2858    return ((flags & AudioSystem::OUTPUT_FLAG_DIRECT) ||
2859           (format != 0 && !AudioSystem::isLinearPCM(format)));
2860 }
2861
2862 uint32_t AudioPolicyManagerBase::getMaxEffectsCpuLoad()
2863 {
2864     return MAX_EFFECTS_CPU_LOAD;
2865 }
2866
2867 uint32_t AudioPolicyManagerBase::getMaxEffectsMemory()
2868 {
2869     return MAX_EFFECTS_MEMORY;
2870 }
2871
2872 // --- AudioOutputDescriptor class implementation
2873
2874 AudioPolicyManagerBase::AudioOutputDescriptor::AudioOutputDescriptor(
2875         const IOProfile *profile)
2876     : mId(0), mSamplingRate(0), mFormat((audio_format_t)0),
2877       mChannelMask((audio_channel_mask_t)0), mLatency(0),
2878     mFlags((audio_output_flags_t)0), mDevice((audio_devices_t)0),
2879     mOutput1(0), mOutput2(0), mProfile(profile)
2880 {
2881     // clear usage count for all stream types
2882     for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2883         mRefCount[i] = 0;
2884         mCurVolume[i] = -1.0;
2885         mMuteCount[i] = 0;
2886         mStopTime[i] = 0;
2887     }
2888     if (profile != NULL) {
2889         mSamplingRate = profile->mSamplingRates[0];
2890         mFormat = profile->mFormats[0];
2891         mChannelMask = profile->mChannelMasks[0];
2892         mFlags = profile->mFlags;
2893     }
2894 }
2895
2896 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::device()
2897 {
2898     if (isDuplicated()) {
2899         return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
2900     } else {
2901         return mDevice;
2902     }
2903 }
2904
2905 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::latency()
2906 {
2907     if (isDuplicated()) {
2908         return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
2909     } else {
2910         return mLatency;
2911     }
2912 }
2913
2914 bool AudioPolicyManagerBase::AudioOutputDescriptor::sharesHwModuleWith(
2915         const AudioOutputDescriptor *outputDesc)
2916 {
2917     if (isDuplicated()) {
2918         return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
2919     } else if (outputDesc->isDuplicated()){
2920         return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
2921     } else {
2922         return (mProfile->mModule == outputDesc->mProfile->mModule);
2923     }
2924 }
2925
2926 void AudioPolicyManagerBase::AudioOutputDescriptor::changeRefCount(AudioSystem::stream_type stream, int delta)
2927 {
2928     // forward usage count change to attached outputs
2929     if (isDuplicated()) {
2930         mOutput1->changeRefCount(stream, delta);
2931         mOutput2->changeRefCount(stream, delta);
2932     }
2933     if ((delta + (int)mRefCount[stream]) < 0) {
2934         ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d", delta, stream, mRefCount[stream]);
2935         mRefCount[stream] = 0;
2936         return;
2937     }
2938     mRefCount[stream] += delta;
2939     ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
2940 }
2941
2942 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::refCount()
2943 {
2944     uint32_t refcount = 0;
2945     for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2946         refcount += mRefCount[i];
2947     }
2948     return refcount;
2949 }
2950
2951 uint32_t AudioPolicyManagerBase::AudioOutputDescriptor::strategyRefCount(routing_strategy strategy)
2952 {
2953     uint32_t refCount = 0;
2954     for (int i = 0; i < (int)AudioSystem::NUM_STREAM_TYPES; i++) {
2955         if (getStrategy((AudioSystem::stream_type)i) == strategy) {
2956             refCount += mRefCount[i];
2957         }
2958     }
2959     return refCount;
2960 }
2961
2962 audio_devices_t AudioPolicyManagerBase::AudioOutputDescriptor::supportedDevices()
2963 {
2964     if (isDuplicated()) {
2965         return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
2966     } else {
2967         return mProfile->mSupportedDevices ;
2968     }
2969 }
2970
2971 status_t AudioPolicyManagerBase::AudioOutputDescriptor::dump(int fd)
2972 {
2973     const size_t SIZE = 256;
2974     char buffer[SIZE];
2975     String8 result;
2976
2977     snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
2978     result.append(buffer);
2979     snprintf(buffer, SIZE, " Format: %d\n", mFormat);
2980     result.append(buffer);
2981     snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
2982     result.append(buffer);
2983     snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
2984     result.append(buffer);
2985     snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
2986     result.append(buffer);
2987     snprintf(buffer, SIZE, " Devices %08x\n", device());
2988     result.append(buffer);
2989     snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
2990     result.append(buffer);
2991     for (int i = 0; i < AudioSystem::NUM_STREAM_TYPES; i++) {
2992         snprintf(buffer, SIZE, " %02d     %.03f     %02d       %02d\n", i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
2993         result.append(buffer);
2994     }
2995     write(fd, result.string(), result.size());
2996
2997     return NO_ERROR;
2998 }
2999
3000 // --- AudioInputDescriptor class implementation
3001
3002 AudioPolicyManagerBase::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
3003     : mSamplingRate(0), mFormat((audio_format_t)0), mChannelMask((audio_channel_mask_t)0),
3004       mDevice((audio_devices_t)0), mRefCount(0),
3005       mInputSource(0), mProfile(profile)
3006 {
3007 }
3008
3009 status_t AudioPolicyManagerBase::AudioInputDescriptor::dump(int fd)
3010 {
3011     const size_t SIZE = 256;
3012     char buffer[SIZE];
3013     String8 result;
3014
3015     snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3016     result.append(buffer);
3017     snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3018     result.append(buffer);
3019     snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3020     result.append(buffer);
3021     snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
3022     result.append(buffer);
3023     snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
3024     result.append(buffer);
3025     write(fd, result.string(), result.size());
3026
3027     return NO_ERROR;
3028 }
3029
3030 // --- StreamDescriptor class implementation
3031
3032 AudioPolicyManagerBase::StreamDescriptor::StreamDescriptor()
3033     :   mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
3034 {
3035     mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
3036 }
3037
3038 int AudioPolicyManagerBase::StreamDescriptor::getVolumeIndex(audio_devices_t device)
3039 {
3040     device = AudioPolicyManagerBase::getDeviceForVolume(device);
3041     // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
3042     if (mIndexCur.indexOfKey(device) < 0) {
3043         device = AUDIO_DEVICE_OUT_DEFAULT;
3044     }
3045     return mIndexCur.valueFor(device);
3046 }
3047
3048 void AudioPolicyManagerBase::StreamDescriptor::dump(int fd)
3049 {
3050     const size_t SIZE = 256;
3051     char buffer[SIZE];
3052     String8 result;
3053
3054     snprintf(buffer, SIZE, "%s         %02d         %02d         ",
3055              mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
3056     result.append(buffer);
3057     for (size_t i = 0; i < mIndexCur.size(); i++) {
3058         snprintf(buffer, SIZE, "%04x : %02d, ",
3059                  mIndexCur.keyAt(i),
3060                  mIndexCur.valueAt(i));
3061         result.append(buffer);
3062     }
3063     result.append("\n");
3064
3065     write(fd, result.string(), result.size());
3066 }
3067
3068 // --- EffectDescriptor class implementation
3069
3070 status_t AudioPolicyManagerBase::EffectDescriptor::dump(int fd)
3071 {
3072     const size_t SIZE = 256;
3073     char buffer[SIZE];
3074     String8 result;
3075
3076     snprintf(buffer, SIZE, " I/O: %d\n", mIo);
3077     result.append(buffer);
3078     snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
3079     result.append(buffer);
3080     snprintf(buffer, SIZE, " Session: %d\n", mSession);
3081     result.append(buffer);
3082     snprintf(buffer, SIZE, " Name: %s\n",  mDesc.name);
3083     result.append(buffer);
3084     snprintf(buffer, SIZE, " %s\n",  mEnabled ? "Enabled" : "Disabled");
3085     result.append(buffer);
3086     write(fd, result.string(), result.size());
3087
3088     return NO_ERROR;
3089 }
3090
3091 // --- IOProfile class implementation
3092
3093 AudioPolicyManagerBase::HwModule::HwModule(const char *name)
3094     : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
3095 {
3096 }
3097
3098 AudioPolicyManagerBase::HwModule::~HwModule()
3099 {
3100     for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3101          delete mOutputProfiles[i];
3102     }
3103     for (size_t i = 0; i < mInputProfiles.size(); i++) {
3104          delete mInputProfiles[i];
3105     }
3106     free((void *)mName);
3107 }
3108
3109 void AudioPolicyManagerBase::HwModule::dump(int fd)
3110 {
3111     const size_t SIZE = 256;
3112     char buffer[SIZE];
3113     String8 result;
3114
3115     snprintf(buffer, SIZE, "  - name: %s\n", mName);
3116     result.append(buffer);
3117     snprintf(buffer, SIZE, "  - handle: %d\n", mHandle);
3118     result.append(buffer);
3119     write(fd, result.string(), result.size());
3120     if (mOutputProfiles.size()) {
3121         write(fd, "  - outputs:\n", sizeof("  - outputs:\n"));
3122         for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3123             snprintf(buffer, SIZE, "    output %d:\n", i);
3124             write(fd, buffer, strlen(buffer));
3125             mOutputProfiles[i]->dump(fd);
3126         }
3127     }
3128     if (mInputProfiles.size()) {
3129         write(fd, "  - inputs:\n", sizeof("  - inputs:\n"));
3130         for (size_t i = 0; i < mInputProfiles.size(); i++) {
3131             snprintf(buffer, SIZE, "    input %d:\n", i);
3132             write(fd, buffer, strlen(buffer));
3133             mInputProfiles[i]->dump(fd);
3134         }
3135     }
3136 }
3137
3138 AudioPolicyManagerBase::IOProfile::IOProfile(HwModule *module)
3139     : mFlags((audio_output_flags_t)0), mModule(module)
3140 {
3141 }
3142
3143 AudioPolicyManagerBase::IOProfile::~IOProfile()
3144 {
3145 }
3146
3147 // checks if the IO profile is compatible with specified parameters. By convention a value of 0
3148 // means a parameter is don't care
3149 bool AudioPolicyManagerBase::IOProfile::isCompatibleProfile(audio_devices_t device,
3150                                                             uint32_t samplingRate,
3151                                                             uint32_t format,
3152                                                             uint32_t channelMask,
3153                                                             audio_output_flags_t flags) const
3154 {
3155     if ((mSupportedDevices & device) != device) {
3156         return false;
3157     }
3158     if ((mFlags & flags) != flags) {
3159         return false;
3160     }
3161     if (samplingRate != 0) {
3162         size_t i;
3163         for (i = 0; i < mSamplingRates.size(); i++)
3164         {
3165             if (mSamplingRates[i] == samplingRate) {
3166                 break;
3167             }
3168         }
3169         if (i == mSamplingRates.size()) {
3170             return false;
3171         }
3172     }
3173     if (format != 0) {
3174         size_t i;
3175         for (i = 0; i < mFormats.size(); i++)
3176         {
3177             if (mFormats[i] == format) {
3178                 break;
3179             }
3180         }
3181         if (i == mFormats.size()) {
3182             return false;
3183         }
3184     }
3185     if (channelMask != 0) {
3186         size_t i;
3187         for (i = 0; i < mChannelMasks.size(); i++)
3188         {
3189             if (mChannelMasks[i] == channelMask) {
3190                 break;
3191             }
3192         }
3193         if (i == mChannelMasks.size()) {
3194             return false;
3195         }
3196     }
3197     return true;
3198 }
3199
3200 void AudioPolicyManagerBase::IOProfile::dump(int fd)
3201 {
3202     const size_t SIZE = 256;
3203     char buffer[SIZE];
3204     String8 result;
3205
3206     snprintf(buffer, SIZE, "    - sampling rates: ");
3207     result.append(buffer);
3208     for (size_t i = 0; i < mSamplingRates.size(); i++) {
3209         snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
3210         result.append(buffer);
3211         result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
3212     }
3213
3214     snprintf(buffer, SIZE, "    - channel masks: ");
3215     result.append(buffer);
3216     for (size_t i = 0; i < mChannelMasks.size(); i++) {
3217         snprintf(buffer, SIZE, "%04x", mChannelMasks[i]);
3218         result.append(buffer);
3219         result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
3220     }
3221
3222     snprintf(buffer, SIZE, "    - formats: ");
3223     result.append(buffer);
3224     for (size_t i = 0; i < mFormats.size(); i++) {
3225         snprintf(buffer, SIZE, "%d", mFormats[i]);
3226         result.append(buffer);
3227         result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
3228     }
3229
3230     snprintf(buffer, SIZE, "    - devices: %04x\n", mSupportedDevices);
3231     result.append(buffer);
3232     snprintf(buffer, SIZE, "    - flags: %04x\n", mFlags);
3233     result.append(buffer);
3234
3235     write(fd, result.string(), result.size());
3236 }
3237
3238 // --- audio_policy.conf file parsing
3239
3240 struct StringToEnum {
3241     const char *name;
3242     uint32_t value;
3243 };
3244
3245 #define STRING_TO_ENUM(string) { #string, string }
3246 #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
3247
3248 const struct StringToEnum sDeviceNameToEnumTable[] = {
3249     STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
3250     STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
3251     STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
3252     STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
3253     STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
3254     STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
3255     STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
3256     STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
3257     STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
3258     STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
3259     STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
3260     STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
3261     STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
3262     STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
3263     STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
3264     STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
3265     STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
3266     STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
3267 };
3268
3269 const struct StringToEnum sFlagNameToEnumTable[] = {
3270     STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
3271     STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
3272     STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
3273     STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
3274 };
3275
3276 const struct StringToEnum sFormatNameToEnumTable[] = {
3277     STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
3278     STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
3279     STRING_TO_ENUM(AUDIO_FORMAT_MP3),
3280     STRING_TO_ENUM(AUDIO_FORMAT_AAC),
3281     STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
3282 };
3283
3284 const struct StringToEnum sOutChannelsNameToEnumTable[] = {
3285     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
3286     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
3287     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
3288     STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
3289 };
3290
3291 const struct StringToEnum sInChannelsNameToEnumTable[] = {
3292     STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
3293     STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
3294 };
3295
3296
3297 uint32_t AudioPolicyManagerBase::stringToEnum(const struct StringToEnum *table,
3298                                               size_t size,
3299                                               const char *name)
3300 {
3301     for (size_t i = 0; i < size; i++) {
3302         if (strcmp(table[i].name, name) == 0) {
3303             ALOGV("stringToEnum() found %s", table[i].name);
3304             return table[i].value;
3305         }
3306     }
3307     return 0;
3308 }
3309
3310 audio_output_flags_t AudioPolicyManagerBase::parseFlagNames(char *name)
3311 {
3312     uint32_t flag = 0;
3313
3314     // it is OK to cast name to non const here as we are not going to use it after
3315     // strtok() modifies it
3316     char *flagName = strtok(name, "|");
3317     while (flagName != NULL) {
3318         if (strlen(flagName) != 0) {
3319             flag |= stringToEnum(sFlagNameToEnumTable,
3320                                ARRAY_SIZE(sFlagNameToEnumTable),
3321                                flagName);
3322         }
3323         flagName = strtok(NULL, "|");
3324     }
3325     return (audio_output_flags_t)flag;
3326 }
3327
3328 audio_devices_t AudioPolicyManagerBase::parseDeviceNames(char *name)
3329 {
3330     uint32_t device = 0;
3331
3332     char *devName = strtok(name, "|");
3333     while (devName != NULL) {
3334         if (strlen(devName) != 0) {
3335             device |= stringToEnum(sDeviceNameToEnumTable,
3336                                  ARRAY_SIZE(sDeviceNameToEnumTable),
3337                                  devName);
3338         }
3339         devName = strtok(NULL, "|");
3340     }
3341     return (audio_devices_t)device;
3342 }
3343
3344 void AudioPolicyManagerBase::loadSamplingRates(char *name, IOProfile *profile)
3345 {
3346     char *str = strtok(name, "|");
3347
3348     // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
3349     // rates should be read from the output stream after it is opened for the first time
3350     if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3351         profile->mSamplingRates.add(0);
3352         return;
3353     }
3354
3355     while (str != NULL) {
3356         uint32_t rate = atoi(str);
3357         if (rate != 0) {
3358             ALOGV("loadSamplingRates() adding rate %d", rate);
3359             profile->mSamplingRates.add(rate);
3360         }
3361         str = strtok(NULL, "|");
3362     }
3363     return;
3364 }
3365
3366 void AudioPolicyManagerBase::loadFormats(char *name, IOProfile *profile)
3367 {
3368     char *str = strtok(name, "|");
3369
3370     // by convention, "0' in the first entry in mFormats indicates the supported formats
3371     // should be read from the output stream after it is opened for the first time
3372     if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3373         profile->mFormats.add((audio_format_t)0);
3374         return;
3375     }
3376
3377     while (str != NULL) {
3378         audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
3379                                                              ARRAY_SIZE(sFormatNameToEnumTable),
3380                                                              str);
3381         if (format != 0) {
3382             profile->mFormats.add(format);
3383         }
3384         str = strtok(NULL, "|");
3385     }
3386     return;
3387 }
3388
3389 void AudioPolicyManagerBase::loadInChannels(char *name, IOProfile *profile)
3390 {
3391     const char *str = strtok(name, "|");
3392
3393     ALOGV("loadInChannels() %s", name);
3394
3395     if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3396         profile->mChannelMasks.add((audio_channel_mask_t)0);
3397         return;
3398     }
3399
3400     while (str != NULL) {
3401         audio_channel_mask_t channelMask =
3402                 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
3403                                                    ARRAY_SIZE(sInChannelsNameToEnumTable),
3404                                                    str);
3405         if (channelMask != 0) {
3406             ALOGV("loadInChannels() adding channelMask %04x", channelMask);
3407             profile->mChannelMasks.add(channelMask);
3408         }
3409         str = strtok(NULL, "|");
3410     }
3411     return;
3412 }
3413
3414 void AudioPolicyManagerBase::loadOutChannels(char *name, IOProfile *profile)
3415 {
3416     const char *str = strtok(name, "|");
3417
3418     ALOGV("loadOutChannels() %s", name);
3419
3420     // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
3421     // masks should be read from the output stream after it is opened for the first time
3422     if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
3423         profile->mChannelMasks.add((audio_channel_mask_t)0);
3424         return;
3425     }
3426
3427     while (str != NULL) {
3428         audio_channel_mask_t channelMask =
3429                 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
3430                                                    ARRAY_SIZE(sOutChannelsNameToEnumTable),
3431                                                    str);
3432         if (channelMask != 0) {
3433             profile->mChannelMasks.add(channelMask);
3434         }
3435         str = strtok(NULL, "|");
3436     }
3437     return;
3438 }
3439
3440 status_t AudioPolicyManagerBase::loadInput(cnode *root, HwModule *module)
3441 {
3442     cnode *node = root->first_child;
3443
3444     IOProfile *profile = new IOProfile(module);
3445
3446     while (node) {
3447         if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3448             loadSamplingRates((char *)node->value, profile);
3449         } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3450             loadFormats((char *)node->value, profile);
3451         } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3452             loadInChannels((char *)node->value, profile);
3453         } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3454             profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3455         }
3456         node = node->next;
3457     }
3458     ALOGW_IF(profile->mSupportedDevices == (audio_devices_t)0,
3459             "loadInput() invalid supported devices");
3460     ALOGW_IF(profile->mChannelMasks.size() == 0,
3461             "loadInput() invalid supported channel masks");
3462     ALOGW_IF(profile->mSamplingRates.size() == 0,
3463             "loadInput() invalid supported sampling rates");
3464     ALOGW_IF(profile->mFormats.size() == 0,
3465             "loadInput() invalid supported formats");
3466     if ((profile->mSupportedDevices != (audio_devices_t)0) &&
3467             (profile->mChannelMasks.size() != 0) &&
3468             (profile->mSamplingRates.size() != 0) &&
3469             (profile->mFormats.size() != 0)) {
3470
3471         ALOGV("loadInput() adding input mSupportedDevices %04x", profile->mSupportedDevices);
3472
3473         module->mInputProfiles.add(profile);
3474         return NO_ERROR;
3475     } else {
3476         delete profile;
3477         return BAD_VALUE;
3478     }
3479 }
3480
3481 status_t AudioPolicyManagerBase::loadOutput(cnode *root, HwModule *module)
3482 {
3483     cnode *node = root->first_child;
3484
3485     IOProfile *profile = new IOProfile(module);
3486
3487     while (node) {
3488         if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
3489             loadSamplingRates((char *)node->value, profile);
3490         } else if (strcmp(node->name, FORMATS_TAG) == 0) {
3491             loadFormats((char *)node->value, profile);
3492         } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
3493             loadOutChannels((char *)node->value, profile);
3494         } else if (strcmp(node->name, DEVICES_TAG) == 0) {
3495             profile->mSupportedDevices = parseDeviceNames((char *)node->value);
3496         } else if (strcmp(node->name, FLAGS_TAG) == 0) {
3497             profile->mFlags = parseFlagNames((char *)node->value);
3498         }
3499         node = node->next;
3500     }
3501     ALOGW_IF(profile->mSupportedDevices == (audio_devices_t)0,
3502             "loadOutput() invalid supported devices");
3503     ALOGW_IF(profile->mChannelMasks.size() == 0,
3504             "loadOutput() invalid supported channel masks");
3505     ALOGW_IF(profile->mSamplingRates.size() == 0,
3506             "loadOutput() invalid supported sampling rates");
3507     ALOGW_IF(profile->mFormats.size() == 0,
3508             "loadOutput() invalid supported formats");
3509     if ((profile->mSupportedDevices != (audio_devices_t)0) &&
3510             (profile->mChannelMasks.size() != 0) &&
3511             (profile->mSamplingRates.size() != 0) &&
3512             (profile->mFormats.size() != 0)) {
3513
3514         ALOGV("loadOutput() adding output mSupportedDevices %04x, mFlags %04x",
3515               profile->mSupportedDevices, profile->mFlags);
3516
3517         module->mOutputProfiles.add(profile);
3518         return NO_ERROR;
3519     } else {
3520         delete profile;
3521         return BAD_VALUE;
3522     }
3523 }
3524
3525 void AudioPolicyManagerBase::loadHwModule(cnode *root)
3526 {
3527     cnode *node = config_find(root, OUTPUTS_TAG);
3528     status_t status = NAME_NOT_FOUND;
3529
3530     HwModule *module = new HwModule(root->name);
3531
3532     if (node != NULL) {
3533         if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
3534             mHasA2dp = true;
3535         } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
3536             mHasUsb = true;
3537         }
3538
3539         node = node->first_child;
3540         while (node) {
3541             ALOGV("loadHwModule() loading output %s", node->name);
3542             status_t tmpStatus = loadOutput(node, module);
3543             if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3544                 status = tmpStatus;
3545             }
3546             node = node->next;
3547         }
3548     }
3549     node = config_find(root, INPUTS_TAG);
3550     if (node != NULL) {
3551         node = node->first_child;
3552         while (node) {
3553             ALOGV("loadHwModule() loading input %s", node->name);
3554             status_t tmpStatus = loadInput(node, module);
3555             if (status == NAME_NOT_FOUND || status == NO_ERROR) {
3556                 status = tmpStatus;
3557             }
3558             node = node->next;
3559         }
3560     }
3561     if (status == NO_ERROR) {
3562         mHwModules.add(module);
3563     } else {
3564         delete module;
3565     }
3566 }
3567
3568 void AudioPolicyManagerBase::loadHwModules(cnode *root)
3569 {
3570     cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
3571     if (node == NULL) {
3572         return;
3573     }
3574
3575     node = node->first_child;
3576     while (node) {
3577         ALOGV("loadHwModules() loading module %s", node->name);
3578         loadHwModule(node);
3579         node = node->next;
3580     }
3581 }
3582
3583 void AudioPolicyManagerBase::loadGlobalConfig(cnode *root)
3584 {
3585     cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
3586     if (node == NULL) {
3587         return;
3588     }
3589     node = node->first_child;
3590     while (node) {
3591         if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
3592             mAttachedOutputDevices = parseDeviceNames((char *)node->value);
3593             ALOGW_IF(mAttachedOutputDevices == 0, "loadGlobalConfig() no attached output devices");
3594             ALOGV("loadGlobalConfig() mAttachedOutputDevices %04x", mAttachedOutputDevices);
3595         } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
3596             mDefaultOutputDevice = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
3597                                               ARRAY_SIZE(sDeviceNameToEnumTable),
3598                                               (char *)node->value);
3599             ALOGW_IF(mDefaultOutputDevice == 0, "loadGlobalConfig() default device not specified");
3600             ALOGV("loadGlobalConfig() mDefaultOutputDevice %04x", mDefaultOutputDevice);
3601         } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
3602             mAvailableInputDevices = parseDeviceNames((char *)node->value);
3603             ALOGV("loadGlobalConfig() mAvailableInputDevices %04x", mAvailableInputDevices);
3604         }
3605         node = node->next;
3606     }
3607 }
3608
3609 status_t AudioPolicyManagerBase::loadAudioPolicyConfig(const char *path)
3610 {
3611     cnode *root;
3612     char *data;
3613
3614     data = (char *)load_file(path, NULL);
3615     if (data == NULL) {
3616         return -ENODEV;
3617     }
3618     root = config_node("", "");
3619     config_load(root, data);
3620
3621     loadGlobalConfig(root);
3622     loadHwModules(root);
3623
3624     config_free(root);
3625     free(root);
3626     free(data);
3627
3628     ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
3629
3630     return NO_ERROR;
3631 }
3632
3633 void AudioPolicyManagerBase::defaultAudioPolicyConfig(void)
3634 {
3635     HwModule *module;
3636     IOProfile *profile;
3637
3638     mDefaultOutputDevice = AUDIO_DEVICE_OUT_SPEAKER;
3639     mAttachedOutputDevices = AUDIO_DEVICE_OUT_SPEAKER;
3640     mAvailableInputDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
3641
3642     module = new HwModule("primary");
3643
3644     profile = new IOProfile(module);
3645     profile->mSamplingRates.add(44100);
3646     profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
3647     profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
3648     profile->mSupportedDevices = AUDIO_DEVICE_OUT_SPEAKER;
3649     profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
3650     module->mOutputProfiles.add(profile);
3651
3652     profile = new IOProfile(module);
3653     profile->mSamplingRates.add(8000);
3654     profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
3655     profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
3656     profile->mSupportedDevices = AUDIO_DEVICE_IN_BUILTIN_MIC;
3657     module->mInputProfiles.add(profile);
3658
3659     mHwModules.add(module);
3660 }
3661
3662 }; // namespace android