OSDN Git Service

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