OSDN Git Service

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