OSDN Git Service

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