OSDN Git Service

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