OSDN Git Service

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