OSDN Git Service

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