OSDN Git Service

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