OSDN Git Service

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