OSDN Git Service

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