AudioPolicyManager.cpp revision a57ab8da6fe56fdb91dfc95ebd0282eb879dde53
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 "AudioPolicyManager"
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// A device mask for all audio input and output devices where matching inputs/outputs on device
34// type alone is not enough: the address must match too
35#define APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX | \
36                                            AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
37
38#include <inttypes.h>
39#include <math.h>
40
41#include <cutils/properties.h>
42#include <utils/Log.h>
43#include <hardware/audio.h>
44#include <hardware/audio_effect.h>
45#include <media/AudioParameter.h>
46#include <soundtrigger/SoundTrigger.h>
47#include "AudioPolicyManager.h"
48#include "audio_policy_conf.h"
49
50namespace android {
51
52// ----------------------------------------------------------------------------
53// Definitions for audio_policy.conf file parsing
54// ----------------------------------------------------------------------------
55
56struct StringToEnum {
57    const char *name;
58    uint32_t value;
59};
60
61#define STRING_TO_ENUM(string) { #string, string }
62#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
63
64const StringToEnum sDeviceNameToEnumTable[] = {
65    STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
66    STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
67    STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
68    STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
69    STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
70    STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
71    STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
72    STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
73    STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
74    STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
75    STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
76    STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
77    STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
78    STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
79    STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
80    STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
81    STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
82    STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
83    STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
84    STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
85    STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
86    STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
87    STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
88    STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
89    STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
90    STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
91    STRING_TO_ENUM(AUDIO_DEVICE_IN_AMBIENT),
92    STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
93    STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
94    STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
95    STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
96    STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
97    STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
98    STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
99    STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
100    STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
101    STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
102    STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
103    STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
104    STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
105    STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
106    STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
107    STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
108    STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
109    STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
110    STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
111    STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
112};
113
114const StringToEnum sFlagNameToEnumTable[] = {
115    STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
116    STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
117    STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
118    STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
119    STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
120    STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
121};
122
123const StringToEnum sFormatNameToEnumTable[] = {
124    STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
125    STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
126    STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
127    STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
128    STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
129    STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
130    STRING_TO_ENUM(AUDIO_FORMAT_MP3),
131    STRING_TO_ENUM(AUDIO_FORMAT_AAC),
132    STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
133    STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
134    STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
135    STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
136    STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
137    STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
138    STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
139    STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
140    STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
141    STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
142    STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
143    STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
144    STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
145    STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
146    STRING_TO_ENUM(AUDIO_FORMAT_AC3),
147    STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
148};
149
150const StringToEnum sOutChannelsNameToEnumTable[] = {
151    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
152    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
153    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
154    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
155    STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
156};
157
158const StringToEnum sInChannelsNameToEnumTable[] = {
159    STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
160    STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
161    STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
162};
163
164const StringToEnum sGainModeNameToEnumTable[] = {
165    STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
166    STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
167    STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
168};
169
170
171uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
172                                              size_t size,
173                                              const char *name)
174{
175    for (size_t i = 0; i < size; i++) {
176        if (strcmp(table[i].name, name) == 0) {
177            ALOGV("stringToEnum() found %s", table[i].name);
178            return table[i].value;
179        }
180    }
181    return 0;
182}
183
184const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
185                                              size_t size,
186                                              uint32_t value)
187{
188    for (size_t i = 0; i < size; i++) {
189        if (table[i].value == value) {
190            return table[i].name;
191        }
192    }
193    return "";
194}
195
196bool AudioPolicyManager::stringToBool(const char *value)
197{
198    return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
199}
200
201
202// ----------------------------------------------------------------------------
203// AudioPolicyInterface implementation
204// ----------------------------------------------------------------------------
205
206
207status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
208                                                          audio_policy_dev_state_t state,
209                                                  const char *device_address)
210{
211    String8 address = (device_address == NULL) ? String8("") : String8(device_address);
212
213    ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
214            device, state, address.string());
215
216    // connect/disconnect only 1 device at a time
217    if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
218
219    // handle output devices
220    if (audio_is_output_device(device)) {
221        SortedVector <audio_io_handle_t> outputs;
222
223        sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
224        devDesc->mAddress = address;
225        ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
226
227        // save a copy of the opened output descriptors before any output is opened or closed
228        // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
229        mPreviousOutputs = mOutputs;
230        switch (state)
231        {
232        // handle output device connection
233        case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
234            if (index >= 0) {
235                ALOGW("setDeviceConnectionState() device already connected: %x", device);
236                return INVALID_OPERATION;
237            }
238            ALOGV("setDeviceConnectionState() connecting device %x", device);
239
240            // register new device as available
241            index = mAvailableOutputDevices.add(devDesc);
242            if (index >= 0) {
243                mAvailableOutputDevices[index]->mId = nextUniqueId();
244                sp<HwModule> module = getModuleForDevice(device);
245                ALOG_ASSERT(module != NULL, "setDeviceConnectionState():"
246                        "could not find HW module for device %08x", device);
247                mAvailableOutputDevices[index]->mModule = module;
248            } else {
249                return NO_MEMORY;
250            }
251
252            if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
253                mAvailableOutputDevices.remove(devDesc);
254                return INVALID_OPERATION;
255            }
256            // outputs should never be empty here
257            ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
258                    "checkOutputsForDevice() returned no outputs but status OK");
259            ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
260                  outputs.size());
261            break;
262        // handle output device disconnection
263        case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
264            if (index < 0) {
265                ALOGW("setDeviceConnectionState() device not connected: %x", device);
266                return INVALID_OPERATION;
267            }
268
269            ALOGV("setDeviceConnectionState() disconnecting device %x", device);
270            // remove device from available output devices
271            mAvailableOutputDevices.remove(devDesc);
272
273            checkOutputsForDevice(device, state, outputs, address);
274            } break;
275
276        default:
277            ALOGE("setDeviceConnectionState() invalid state: %x", state);
278            return BAD_VALUE;
279        }
280
281        // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
282        // output is suspended before any tracks are moved to it
283        checkA2dpSuspend();
284        checkOutputForAllStrategies();
285        // outputs must be closed after checkOutputForAllStrategies() is executed
286        if (!outputs.isEmpty()) {
287            for (size_t i = 0; i < outputs.size(); i++) {
288                sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
289                // close unused outputs after device disconnection or direct outputs that have been
290                // opened by checkOutputsForDevice() to query dynamic parameters
291                if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
292                        (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
293                         (desc->mDirectOpenCount == 0))) {
294                    closeOutput(outputs[i]);
295                }
296            }
297            // check again after closing A2DP output to reset mA2dpSuspended if needed
298            checkA2dpSuspend();
299        }
300
301        updateDevicesAndOutputs();
302        for (size_t i = 0; i < mOutputs.size(); i++) {
303            // do not force device change on duplicated output because if device is 0, it will
304            // also force a device 0 for the two outputs it is duplicated to which may override
305            // a valid device selection on those outputs.
306            bool force = !mOutputs.valueAt(i)->isDuplicated()
307                    && (!deviceDistinguishesOnAddress(device)
308                            // always force when disconnecting (a non-duplicated device)
309                            || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
310            setOutputDevice(mOutputs.keyAt(i),
311                            getNewOutputDevice(mOutputs.keyAt(i), true /*fromCache*/),
312                            force, 0);
313        }
314
315        mpClientInterface->onAudioPortListUpdate();
316        return NO_ERROR;
317    }  // end if is output device
318
319    // handle input devices
320    if (audio_is_input_device(device)) {
321        SortedVector <audio_io_handle_t> inputs;
322
323        sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
324        devDesc->mAddress = address;
325        ssize_t index = mAvailableInputDevices.indexOf(devDesc);
326        switch (state)
327        {
328        // handle input device connection
329        case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
330            if (index >= 0) {
331                ALOGW("setDeviceConnectionState() device already connected: %d", device);
332                return INVALID_OPERATION;
333            }
334            sp<HwModule> module = getModuleForDevice(device);
335            if (module == NULL) {
336                ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
337                      device);
338                return INVALID_OPERATION;
339            }
340            if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
341                return INVALID_OPERATION;
342            }
343
344            index = mAvailableInputDevices.add(devDesc);
345            if (index >= 0) {
346                mAvailableInputDevices[index]->mId = nextUniqueId();
347                mAvailableInputDevices[index]->mModule = module;
348            } else {
349                return NO_MEMORY;
350            }
351        } break;
352
353        // handle input device disconnection
354        case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
355            if (index < 0) {
356                ALOGW("setDeviceConnectionState() device not connected: %d", device);
357                return INVALID_OPERATION;
358            }
359            checkInputsForDevice(device, state, inputs, address);
360            mAvailableInputDevices.remove(devDesc);
361        } break;
362
363        default:
364            ALOGE("setDeviceConnectionState() invalid state: %x", state);
365            return BAD_VALUE;
366        }
367
368        closeAllInputs();
369
370        mpClientInterface->onAudioPortListUpdate();
371        return NO_ERROR;
372    } // end if is input device
373
374    ALOGW("setDeviceConnectionState() invalid device: %x", device);
375    return BAD_VALUE;
376}
377
378audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
379                                                  const char *device_address)
380{
381    audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
382    sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
383    devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
384    ssize_t index;
385    DeviceVector *deviceVector;
386
387    if (audio_is_output_device(device)) {
388        deviceVector = &mAvailableOutputDevices;
389    } else if (audio_is_input_device(device)) {
390        deviceVector = &mAvailableInputDevices;
391    } else {
392        ALOGW("getDeviceConnectionState() invalid device type %08x", device);
393        return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
394    }
395
396    index = deviceVector->indexOf(devDesc);
397    if (index >= 0) {
398        return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
399    } else {
400        return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
401    }
402}
403
404void AudioPolicyManager::setPhoneState(audio_mode_t state)
405{
406    ALOGV("setPhoneState() state %d", state);
407    audio_devices_t newDevice = AUDIO_DEVICE_NONE;
408    if (state < 0 || state >= AUDIO_MODE_CNT) {
409        ALOGW("setPhoneState() invalid state %d", state);
410        return;
411    }
412
413    if (state == mPhoneState ) {
414        ALOGW("setPhoneState() setting same state %d", state);
415        return;
416    }
417
418    // if leaving call state, handle special case of active streams
419    // pertaining to sonification strategy see handleIncallSonification()
420    if (isInCall()) {
421        ALOGV("setPhoneState() in call state management: new state is %d", state);
422        for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
423            handleIncallSonification((audio_stream_type_t)stream, false, true);
424        }
425    }
426
427    // store previous phone state for management of sonification strategy below
428    int oldState = mPhoneState;
429    mPhoneState = state;
430    bool force = false;
431
432    // are we entering or starting a call
433    if (!isStateInCall(oldState) && isStateInCall(state)) {
434        ALOGV("  Entering call in setPhoneState()");
435        // force routing command to audio hardware when starting a call
436        // even if no device change is needed
437        force = true;
438        for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
439            mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
440                    sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
441        }
442    } else if (isStateInCall(oldState) && !isStateInCall(state)) {
443        ALOGV("  Exiting call in setPhoneState()");
444        // force routing command to audio hardware when exiting a call
445        // even if no device change is needed
446        force = true;
447        for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
448            mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
449                    sVolumeProfiles[AUDIO_STREAM_DTMF][j];
450        }
451    } else if (isStateInCall(state) && (state != oldState)) {
452        ALOGV("  Switching between telephony and VoIP in setPhoneState()");
453        // force routing command to audio hardware when switching between telephony and VoIP
454        // even if no device change is needed
455        force = true;
456    }
457
458    // check for device and output changes triggered by new phone state
459    newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
460    checkA2dpSuspend();
461    checkOutputForAllStrategies();
462    updateDevicesAndOutputs();
463
464    sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
465
466    // force routing command to audio hardware when ending call
467    // even if no device change is needed
468    if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
469        newDevice = hwOutputDesc->device();
470    }
471
472    int delayMs = 0;
473    if (isStateInCall(state)) {
474        nsecs_t sysTime = systemTime();
475        for (size_t i = 0; i < mOutputs.size(); i++) {
476            sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
477            // mute media and sonification strategies and delay device switch by the largest
478            // latency of any output where either strategy is active.
479            // This avoid sending the ring tone or music tail into the earpiece or headset.
480            if ((desc->isStrategyActive(STRATEGY_MEDIA,
481                                     SONIFICATION_HEADSET_MUSIC_DELAY,
482                                     sysTime) ||
483                    desc->isStrategyActive(STRATEGY_SONIFICATION,
484                                         SONIFICATION_HEADSET_MUSIC_DELAY,
485                                         sysTime)) &&
486                    (delayMs < (int)desc->mLatency*2)) {
487                delayMs = desc->mLatency*2;
488            }
489            setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
490            setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
491                getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
492            setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
493            setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
494                getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
495        }
496    }
497
498    // change routing is necessary
499    setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
500
501    // if entering in call state, handle special case of active streams
502    // pertaining to sonification strategy see handleIncallSonification()
503    if (isStateInCall(state)) {
504        ALOGV("setPhoneState() in call state management: new state is %d", state);
505        for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
506            handleIncallSonification((audio_stream_type_t)stream, true, true);
507        }
508    }
509
510    // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
511    if (state == AUDIO_MODE_RINGTONE &&
512        isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
513        mLimitRingtoneVolume = true;
514    } else {
515        mLimitRingtoneVolume = false;
516    }
517}
518
519void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
520                                         audio_policy_forced_cfg_t config)
521{
522    ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
523
524    bool forceVolumeReeval = false;
525    switch(usage) {
526    case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
527        if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
528            config != AUDIO_POLICY_FORCE_NONE) {
529            ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
530            return;
531        }
532        forceVolumeReeval = true;
533        mForceUse[usage] = config;
534        break;
535    case AUDIO_POLICY_FORCE_FOR_MEDIA:
536        if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
537            config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
538            config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
539            config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
540            config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
541            ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
542            return;
543        }
544        mForceUse[usage] = config;
545        break;
546    case AUDIO_POLICY_FORCE_FOR_RECORD:
547        if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
548            config != AUDIO_POLICY_FORCE_NONE) {
549            ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
550            return;
551        }
552        mForceUse[usage] = config;
553        break;
554    case AUDIO_POLICY_FORCE_FOR_DOCK:
555        if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
556            config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
557            config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
558            config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
559            config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
560            ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
561        }
562        forceVolumeReeval = true;
563        mForceUse[usage] = config;
564        break;
565    case AUDIO_POLICY_FORCE_FOR_SYSTEM:
566        if (config != AUDIO_POLICY_FORCE_NONE &&
567            config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
568            ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
569        }
570        forceVolumeReeval = true;
571        mForceUse[usage] = config;
572        break;
573    case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
574        if (config != AUDIO_POLICY_FORCE_NONE &&
575            config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
576            ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
577        }
578        mForceUse[usage] = config;
579        break;
580    default:
581        ALOGW("setForceUse() invalid usage %d", usage);
582        break;
583    }
584
585    // check for device and output changes triggered by new force usage
586    checkA2dpSuspend();
587    checkOutputForAllStrategies();
588    updateDevicesAndOutputs();
589    for (size_t i = 0; i < mOutputs.size(); i++) {
590        audio_io_handle_t output = mOutputs.keyAt(i);
591        audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
592        setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
593        if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
594            applyStreamVolumes(output, newDevice, 0, true);
595        }
596    }
597
598    audio_io_handle_t activeInput = getActiveInput();
599    if (activeInput != 0) {
600        setInputDevice(activeInput, getNewInputDevice(activeInput));
601    }
602
603}
604
605audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
606{
607    return mForceUse[usage];
608}
609
610void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
611{
612    ALOGV("setSystemProperty() property %s, value %s", property, value);
613}
614
615// Find a direct output profile compatible with the parameters passed, even if the input flags do
616// not explicitly request a direct output
617sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
618                                                               audio_devices_t device,
619                                                               uint32_t samplingRate,
620                                                               audio_format_t format,
621                                                               audio_channel_mask_t channelMask,
622                                                               audio_output_flags_t flags)
623{
624    for (size_t i = 0; i < mHwModules.size(); i++) {
625        if (mHwModules[i]->mHandle == 0) {
626            continue;
627        }
628        for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
629            sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
630            bool found = profile->isCompatibleProfile(device, samplingRate,
631                    NULL /*updatedSamplingRate*/, format, channelMask,
632                    flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
633                        AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
634            if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
635                return profile;
636            }
637        }
638    }
639    return 0;
640}
641
642audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
643                                    uint32_t samplingRate,
644                                    audio_format_t format,
645                                    audio_channel_mask_t channelMask,
646                                    audio_output_flags_t flags,
647                                    const audio_offload_info_t *offloadInfo)
648{
649
650    routing_strategy strategy = getStrategy(stream);
651    audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
652    ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
653          device, stream, samplingRate, format, channelMask, flags);
654
655    return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
656            offloadInfo);
657}
658
659audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
660                                    uint32_t samplingRate,
661                                    audio_format_t format,
662                                    audio_channel_mask_t channelMask,
663                                    audio_output_flags_t flags,
664                                    const audio_offload_info_t *offloadInfo)
665{
666    if (attr == NULL) {
667        ALOGE("getOutputForAttr() called with NULL audio attributes");
668        return 0;
669    }
670    ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s",
671            attr->usage, attr->content_type, attr->tags);
672
673    // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
674    routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
675    audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
676    ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
677          device, samplingRate, format, channelMask, flags);
678
679    audio_stream_type_t stream = streamTypefromAttributesInt(attr);
680    return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
681                offloadInfo);
682}
683
684audio_io_handle_t AudioPolicyManager::getOutputForDevice(
685        audio_devices_t device,
686        audio_stream_type_t stream,
687        uint32_t samplingRate,
688        audio_format_t format,
689        audio_channel_mask_t channelMask,
690        audio_output_flags_t flags,
691        const audio_offload_info_t *offloadInfo)
692{
693    audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
694    uint32_t latency = 0;
695    status_t status;
696
697#ifdef AUDIO_POLICY_TEST
698    if (mCurOutput != 0) {
699        ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
700                mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
701
702        if (mTestOutputs[mCurOutput] == 0) {
703            ALOGV("getOutput() opening test output");
704            sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
705            outputDesc->mDevice = mTestDevice;
706            outputDesc->mLatency = mTestLatencyMs;
707            outputDesc->mFlags =
708                    (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
709            outputDesc->mRefCount[stream] = 0;
710            audio_config_t config = AUDIO_CONFIG_INITIALIZER;
711            config.sample_rate = mTestSamplingRate;
712            config.channel_mask = mTestChannels;
713            config.format = mTestFormat;
714            if (offloadInfo != NULL) {
715                config.offload_info = *offloadInfo;
716            }
717            status = mpClientInterface->openOutput(0,
718                                                  &mTestOutputs[mCurOutput],
719                                                  &config,
720                                                  &outputDesc->mDevice,
721                                                  String8(""),
722                                                  &outputDesc->mLatency,
723                                                  outputDesc->mFlags);
724            if (status == NO_ERROR) {
725                outputDesc->mSamplingRate = config.sample_rate;
726                outputDesc->mFormat = config.format;
727                outputDesc->mChannelMask = config.channel_mask;
728                AudioParameter outputCmd = AudioParameter();
729                outputCmd.addInt(String8("set_id"),mCurOutput);
730                mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
731                addOutput(mTestOutputs[mCurOutput], outputDesc);
732            }
733        }
734        return mTestOutputs[mCurOutput];
735    }
736#endif //AUDIO_POLICY_TEST
737
738    // open a direct output if required by specified parameters
739    //force direct flag if offload flag is set: offloading implies a direct output stream
740    // and all common behaviors are driven by checking only the direct flag
741    // this should normally be set appropriately in the policy configuration file
742    if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
743        flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
744    }
745
746    // Do not allow offloading if one non offloadable effect is enabled. This prevents from
747    // creating an offloaded track and tearing it down immediately after start when audioflinger
748    // detects there is an active non offloadable effect.
749    // FIXME: We should check the audio session here but we do not have it in this context.
750    // This may prevent offloading in rare situations where effects are left active by apps
751    // in the background.
752    sp<IOProfile> profile;
753    if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
754            !isNonOffloadableEffectEnabled()) {
755        profile = getProfileForDirectOutput(device,
756                                           samplingRate,
757                                           format,
758                                           channelMask,
759                                           (audio_output_flags_t)flags);
760    }
761
762    if (profile != 0) {
763        sp<AudioOutputDescriptor> outputDesc = NULL;
764
765        for (size_t i = 0; i < mOutputs.size(); i++) {
766            sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
767            if (!desc->isDuplicated() && (profile == desc->mProfile)) {
768                outputDesc = desc;
769                // reuse direct output if currently open and configured with same parameters
770                if ((samplingRate == outputDesc->mSamplingRate) &&
771                        (format == outputDesc->mFormat) &&
772                        (channelMask == outputDesc->mChannelMask)) {
773                    outputDesc->mDirectOpenCount++;
774                    ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
775                    return mOutputs.keyAt(i);
776                }
777            }
778        }
779        // close direct output if currently open and configured with different parameters
780        if (outputDesc != NULL) {
781            closeOutput(outputDesc->mIoHandle);
782        }
783        outputDesc = new AudioOutputDescriptor(profile);
784        outputDesc->mDevice = device;
785        outputDesc->mLatency = 0;
786        outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
787        audio_config_t config = AUDIO_CONFIG_INITIALIZER;
788        config.sample_rate = samplingRate;
789        config.channel_mask = channelMask;
790        config.format = format;
791        if (offloadInfo != NULL) {
792            config.offload_info = *offloadInfo;
793        }
794        status = mpClientInterface->openOutput(profile->mModule->mHandle,
795                                               &output,
796                                               &config,
797                                               &outputDesc->mDevice,
798                                               String8(""),
799                                               &outputDesc->mLatency,
800                                               outputDesc->mFlags);
801
802        // only accept an output with the requested parameters
803        if (status != NO_ERROR ||
804            (samplingRate != 0 && samplingRate != config.sample_rate) ||
805            (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
806            (channelMask != 0 && channelMask != config.channel_mask)) {
807            ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
808                    "format %d %d, channelMask %04x %04x", output, samplingRate,
809                    outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
810                    outputDesc->mChannelMask);
811            if (output != AUDIO_IO_HANDLE_NONE) {
812                mpClientInterface->closeOutput(output);
813            }
814            return AUDIO_IO_HANDLE_NONE;
815        }
816        outputDesc->mSamplingRate = config.sample_rate;
817        outputDesc->mChannelMask = config.channel_mask;
818        outputDesc->mFormat = config.format;
819        outputDesc->mRefCount[stream] = 0;
820        outputDesc->mStopTime[stream] = 0;
821        outputDesc->mDirectOpenCount = 1;
822
823        audio_io_handle_t srcOutput = getOutputForEffect();
824        addOutput(output, outputDesc);
825        audio_io_handle_t dstOutput = getOutputForEffect();
826        if (dstOutput == output) {
827            mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
828        }
829        mPreviousOutputs = mOutputs;
830        ALOGV("getOutput() returns new direct output %d", output);
831        mpClientInterface->onAudioPortListUpdate();
832        return output;
833    }
834
835    // ignoring channel mask due to downmix capability in mixer
836
837    // open a non direct output
838
839    // for non direct outputs, only PCM is supported
840    if (audio_is_linear_pcm(format)) {
841        // get which output is suitable for the specified stream. The actual
842        // routing change will happen when startOutput() will be called
843        SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
844
845        output = selectOutput(outputs, flags);
846    }
847    ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
848            "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
849
850    ALOGV("getOutput() returns output %d", output);
851
852    return output;
853}
854
855audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
856                                                       audio_output_flags_t flags)
857{
858    // select one output among several that provide a path to a particular device or set of
859    // devices (the list was previously build by getOutputsForDevice()).
860    // The priority is as follows:
861    // 1: the output with the highest number of requested policy flags
862    // 2: the primary output
863    // 3: the first output in the list
864
865    if (outputs.size() == 0) {
866        return 0;
867    }
868    if (outputs.size() == 1) {
869        return outputs[0];
870    }
871
872    int maxCommonFlags = 0;
873    audio_io_handle_t outputFlags = 0;
874    audio_io_handle_t outputPrimary = 0;
875
876    for (size_t i = 0; i < outputs.size(); i++) {
877        sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
878        if (!outputDesc->isDuplicated()) {
879            int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
880            if (commonFlags > maxCommonFlags) {
881                outputFlags = outputs[i];
882                maxCommonFlags = commonFlags;
883                ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
884            }
885            if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
886                outputPrimary = outputs[i];
887            }
888        }
889    }
890
891    if (outputFlags != 0) {
892        return outputFlags;
893    }
894    if (outputPrimary != 0) {
895        return outputPrimary;
896    }
897
898    return outputs[0];
899}
900
901status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
902                                             audio_stream_type_t stream,
903                                             int session)
904{
905    ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
906    ssize_t index = mOutputs.indexOfKey(output);
907    if (index < 0) {
908        ALOGW("startOutput() unknown output %d", output);
909        return BAD_VALUE;
910    }
911
912    sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
913
914    // increment usage count for this stream on the requested output:
915    // NOTE that the usage count is the same for duplicated output and hardware output which is
916    // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
917    outputDesc->changeRefCount(stream, 1);
918
919    if (outputDesc->mRefCount[stream] == 1) {
920        audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
921        routing_strategy strategy = getStrategy(stream);
922        bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
923                            (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
924        uint32_t waitMs = 0;
925        bool force = false;
926        for (size_t i = 0; i < mOutputs.size(); i++) {
927            sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
928            if (desc != outputDesc) {
929                // force a device change if any other output is managed by the same hw
930                // module and has a current device selection that differs from selected device.
931                // In this case, the audio HAL must receive the new device selection so that it can
932                // change the device currently selected by the other active output.
933                if (outputDesc->sharesHwModuleWith(desc) &&
934                    desc->device() != newDevice) {
935                    force = true;
936                }
937                // wait for audio on other active outputs to be presented when starting
938                // a notification so that audio focus effect can propagate.
939                uint32_t latency = desc->latency();
940                if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
941                    waitMs = latency;
942                }
943            }
944        }
945        uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
946
947        // handle special case for sonification while in call
948        if (isInCall()) {
949            handleIncallSonification(stream, true, false);
950        }
951
952        // apply volume rules for current stream and device if necessary
953        checkAndSetVolume(stream,
954                          mStreams[stream].getVolumeIndex(newDevice),
955                          output,
956                          newDevice);
957
958        // update the outputs if starting an output with a stream that can affect notification
959        // routing
960        handleNotificationRoutingForStream(stream);
961        if (waitMs > muteWaitMs) {
962            usleep((waitMs - muteWaitMs) * 2 * 1000);
963        }
964    }
965    return NO_ERROR;
966}
967
968
969status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
970                                            audio_stream_type_t stream,
971                                            int session)
972{
973    ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
974    ssize_t index = mOutputs.indexOfKey(output);
975    if (index < 0) {
976        ALOGW("stopOutput() unknown output %d", output);
977        return BAD_VALUE;
978    }
979
980    sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
981
982    // handle special case for sonification while in call
983    if (isInCall()) {
984        handleIncallSonification(stream, false, false);
985    }
986
987    if (outputDesc->mRefCount[stream] > 0) {
988        // decrement usage count of this stream on the output
989        outputDesc->changeRefCount(stream, -1);
990        // store time at which the stream was stopped - see isStreamActive()
991        if (outputDesc->mRefCount[stream] == 0) {
992            outputDesc->mStopTime[stream] = systemTime();
993            audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
994            // delay the device switch by twice the latency because stopOutput() is executed when
995            // the track stop() command is received and at that time the audio track buffer can
996            // still contain data that needs to be drained. The latency only covers the audio HAL
997            // and kernel buffers. Also the latency does not always include additional delay in the
998            // audio path (audio DSP, CODEC ...)
999            setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1000
1001            // force restoring the device selection on other active outputs if it differs from the
1002            // one being selected for this output
1003            for (size_t i = 0; i < mOutputs.size(); i++) {
1004                audio_io_handle_t curOutput = mOutputs.keyAt(i);
1005                sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
1006                if (curOutput != output &&
1007                        desc->isActive() &&
1008                        outputDesc->sharesHwModuleWith(desc) &&
1009                        (newDevice != desc->device())) {
1010                    setOutputDevice(curOutput,
1011                                    getNewOutputDevice(curOutput, false /*fromCache*/),
1012                                    true,
1013                                    outputDesc->mLatency*2);
1014                }
1015            }
1016            // update the outputs if stopping one with a stream that can affect notification routing
1017            handleNotificationRoutingForStream(stream);
1018        }
1019        return NO_ERROR;
1020    } else {
1021        ALOGW("stopOutput() refcount is already 0 for output %d", output);
1022        return INVALID_OPERATION;
1023    }
1024}
1025
1026void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
1027{
1028    ALOGV("releaseOutput() %d", output);
1029    ssize_t index = mOutputs.indexOfKey(output);
1030    if (index < 0) {
1031        ALOGW("releaseOutput() releasing unknown output %d", output);
1032        return;
1033    }
1034
1035#ifdef AUDIO_POLICY_TEST
1036    int testIndex = testOutputIndex(output);
1037    if (testIndex != 0) {
1038        sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
1039        if (outputDesc->isActive()) {
1040            mpClientInterface->closeOutput(output);
1041            mOutputs.removeItem(output);
1042            mTestOutputs[testIndex] = 0;
1043        }
1044        return;
1045    }
1046#endif //AUDIO_POLICY_TEST
1047
1048    sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
1049    if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1050        if (desc->mDirectOpenCount <= 0) {
1051            ALOGW("releaseOutput() invalid open count %d for output %d",
1052                                                              desc->mDirectOpenCount, output);
1053            return;
1054        }
1055        if (--desc->mDirectOpenCount == 0) {
1056            closeOutput(output);
1057            // If effects where present on the output, audioflinger moved them to the primary
1058            // output by default: move them back to the appropriate output.
1059            audio_io_handle_t dstOutput = getOutputForEffect();
1060            if (dstOutput != mPrimaryOutput) {
1061                mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1062            }
1063            mpClientInterface->onAudioPortListUpdate();
1064        }
1065    }
1066}
1067
1068
1069audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
1070                                    uint32_t samplingRate,
1071                                    audio_format_t format,
1072                                    audio_channel_mask_t channelMask,
1073                                    audio_session_t session,
1074                                    audio_input_flags_t flags)
1075{
1076    ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
1077          "flags %#x",
1078          inputSource, samplingRate, format, channelMask, session, flags);
1079
1080    audio_devices_t device = getDeviceForInputSource(inputSource);
1081
1082    if (device == AUDIO_DEVICE_NONE) {
1083        ALOGW("getInput() could not find device for inputSource %d", inputSource);
1084        return AUDIO_IO_HANDLE_NONE;
1085    }
1086
1087    // adapt channel selection to input source
1088    switch (inputSource) {
1089    case AUDIO_SOURCE_VOICE_UPLINK:
1090        channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1091        break;
1092    case AUDIO_SOURCE_VOICE_DOWNLINK:
1093        channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1094        break;
1095    case AUDIO_SOURCE_VOICE_CALL:
1096        channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1097        break;
1098    default:
1099        break;
1100    }
1101
1102    sp<IOProfile> profile = getInputProfile(device,
1103                                         samplingRate,
1104                                         format,
1105                                         channelMask,
1106                                         flags);
1107    if (profile == 0) {
1108        ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1109                "channelMask 0x%X, flags %#x",
1110                device, samplingRate, format, channelMask, flags);
1111        return AUDIO_IO_HANDLE_NONE;
1112    }
1113
1114    if (profile->mModule->mHandle == 0) {
1115        ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
1116        return AUDIO_IO_HANDLE_NONE;
1117    }
1118
1119    audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1120    config.sample_rate = samplingRate;
1121    config.channel_mask = channelMask;
1122    config.format = format;
1123    audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1124
1125    bool isSoundTrigger = false;
1126    if (inputSource == AUDIO_SOURCE_HOTWORD) {
1127        ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1128        if (index >= 0) {
1129            input = mSoundTriggerSessions.valueFor(session);
1130            isSoundTrigger = true;
1131            ALOGV("SoundTrigger capture on session %d input %d", session, input);
1132        }
1133    }
1134
1135    status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1136                                                   &input,
1137                                                   &config,
1138                                                   &device,
1139                                                   String8(""),
1140                                                   inputSource,
1141                                                   flags);
1142
1143    // only accept input with the exact requested set of parameters
1144    if (status != NO_ERROR ||
1145        (samplingRate != config.sample_rate) ||
1146        (format != config.format) ||
1147        (channelMask != config.channel_mask)) {
1148        ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1149                samplingRate, format, channelMask);
1150        if (input != AUDIO_IO_HANDLE_NONE) {
1151            mpClientInterface->closeInput(input);
1152        }
1153        return AUDIO_IO_HANDLE_NONE;
1154    }
1155
1156    sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
1157    inputDesc->mInputSource = inputSource;
1158    inputDesc->mRefCount = 0;
1159    inputDesc->mOpenRefCount = 1;
1160    inputDesc->mSamplingRate = samplingRate;
1161    inputDesc->mFormat = format;
1162    inputDesc->mChannelMask = channelMask;
1163    inputDesc->mDevice = device;
1164    inputDesc->mSessions.add(session);
1165    inputDesc->mIsSoundTrigger = isSoundTrigger;
1166
1167    addInput(input, inputDesc);
1168    mpClientInterface->onAudioPortListUpdate();
1169    return input;
1170}
1171
1172status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1173                                        audio_session_t session)
1174{
1175    ALOGV("startInput() input %d", input);
1176    ssize_t index = mInputs.indexOfKey(input);
1177    if (index < 0) {
1178        ALOGW("startInput() unknown input %d", input);
1179        return BAD_VALUE;
1180    }
1181    sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1182
1183    index = inputDesc->mSessions.indexOf(session);
1184    if (index < 0) {
1185        ALOGW("startInput() unknown session %d on input %d", session, input);
1186        return BAD_VALUE;
1187    }
1188
1189    // virtual input devices are compatible with other input devices
1190    if (!isVirtualInputDevice(inputDesc->mDevice)) {
1191
1192        // for a non-virtual input device, check if there is another (non-virtual) active input
1193        audio_io_handle_t activeInput = getActiveInput();
1194        if (activeInput != 0 && activeInput != input) {
1195
1196            // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1197            // otherwise the active input continues and the new input cannot be started.
1198            sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
1199            if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1200                ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
1201                stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1202                releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
1203            } else {
1204                ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
1205                return INVALID_OPERATION;
1206            }
1207        }
1208    }
1209
1210    if (inputDesc->mRefCount == 0) {
1211        if (activeInputsCount() == 0) {
1212            SoundTrigger::setCaptureState(true);
1213        }
1214        setInputDevice(input, getNewInputDevice(input), true /* force */);
1215
1216        // Automatically enable the remote submix output when input is started.
1217        // For remote submix (a virtual device), we open only one input per capture request.
1218        if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1219            setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1220                    AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1221        }
1222    }
1223
1224    ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1225
1226    inputDesc->mRefCount++;
1227    return NO_ERROR;
1228}
1229
1230status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1231                                       audio_session_t session)
1232{
1233    ALOGV("stopInput() input %d", input);
1234    ssize_t index = mInputs.indexOfKey(input);
1235    if (index < 0) {
1236        ALOGW("stopInput() unknown input %d", input);
1237        return BAD_VALUE;
1238    }
1239    sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1240
1241    index = inputDesc->mSessions.indexOf(session);
1242    if (index < 0) {
1243        ALOGW("stopInput() unknown session %d on input %d", session, input);
1244        return BAD_VALUE;
1245    }
1246
1247    if (inputDesc->mRefCount == 0) {
1248        ALOGW("stopInput() input %d already stopped", input);
1249        return INVALID_OPERATION;
1250    }
1251
1252    inputDesc->mRefCount--;
1253    if (inputDesc->mRefCount == 0) {
1254
1255        // automatically disable the remote submix output when input is stopped
1256        if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1257            setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1258                    AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1259        }
1260
1261        resetInputDevice(input);
1262
1263        if (activeInputsCount() == 0) {
1264            SoundTrigger::setCaptureState(false);
1265        }
1266    }
1267    return NO_ERROR;
1268}
1269
1270void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1271                                      audio_session_t session)
1272{
1273    ALOGV("releaseInput() %d", input);
1274    ssize_t index = mInputs.indexOfKey(input);
1275    if (index < 0) {
1276        ALOGW("releaseInput() releasing unknown input %d", input);
1277        return;
1278    }
1279    sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1280    ALOG_ASSERT(inputDesc != 0);
1281
1282    index = inputDesc->mSessions.indexOf(session);
1283    if (index < 0) {
1284        ALOGW("releaseInput() unknown session %d on input %d", session, input);
1285        return;
1286    }
1287    inputDesc->mSessions.remove(session);
1288    if (inputDesc->mOpenRefCount == 0) {
1289        ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1290        return;
1291    }
1292    inputDesc->mOpenRefCount--;
1293    if (inputDesc->mOpenRefCount > 0) {
1294        ALOGV("releaseInput() exit > 0");
1295        return;
1296    }
1297
1298    mpClientInterface->closeInput(input);
1299    mInputs.removeItem(input);
1300    nextAudioPortGeneration();
1301    mpClientInterface->onAudioPortListUpdate();
1302    ALOGV("releaseInput() exit");
1303}
1304
1305void AudioPolicyManager::closeAllInputs() {
1306    for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1307        mpClientInterface->closeInput(mInputs.keyAt(input_index));
1308    }
1309    mInputs.clear();
1310    nextAudioPortGeneration();
1311}
1312
1313void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
1314                                            int indexMin,
1315                                            int indexMax)
1316{
1317    ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1318    if (indexMin < 0 || indexMin >= indexMax) {
1319        ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1320        return;
1321    }
1322    mStreams[stream].mIndexMin = indexMin;
1323    mStreams[stream].mIndexMax = indexMax;
1324}
1325
1326status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
1327                                                      int index,
1328                                                      audio_devices_t device)
1329{
1330
1331    if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1332        return BAD_VALUE;
1333    }
1334    if (!audio_is_output_device(device)) {
1335        return BAD_VALUE;
1336    }
1337
1338    // Force max volume if stream cannot be muted
1339    if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1340
1341    ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1342          stream, device, index);
1343
1344    // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1345    // clear all device specific values
1346    if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1347        mStreams[stream].mIndexCur.clear();
1348    }
1349    mStreams[stream].mIndexCur.add(device, index);
1350
1351    // compute and apply stream volume on all outputs according to connected device
1352    status_t status = NO_ERROR;
1353    for (size_t i = 0; i < mOutputs.size(); i++) {
1354        audio_devices_t curDevice =
1355                getDeviceForVolume(mOutputs.valueAt(i)->device());
1356        if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1357            status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1358            if (volStatus != NO_ERROR) {
1359                status = volStatus;
1360            }
1361        }
1362    }
1363    return status;
1364}
1365
1366status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
1367                                                      int *index,
1368                                                      audio_devices_t device)
1369{
1370    if (index == NULL) {
1371        return BAD_VALUE;
1372    }
1373    if (!audio_is_output_device(device)) {
1374        return BAD_VALUE;
1375    }
1376    // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1377    // the strategy the stream belongs to.
1378    if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1379        device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1380    }
1381    device = getDeviceForVolume(device);
1382
1383    *index =  mStreams[stream].getVolumeIndex(device);
1384    ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1385    return NO_ERROR;
1386}
1387
1388audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
1389                                            const SortedVector<audio_io_handle_t>& outputs)
1390{
1391    // select one output among several suitable for global effects.
1392    // The priority is as follows:
1393    // 1: An offloaded output. If the effect ends up not being offloadable,
1394    //    AudioFlinger will invalidate the track and the offloaded output
1395    //    will be closed causing the effect to be moved to a PCM output.
1396    // 2: A deep buffer output
1397    // 3: the first output in the list
1398
1399    if (outputs.size() == 0) {
1400        return 0;
1401    }
1402
1403    audio_io_handle_t outputOffloaded = 0;
1404    audio_io_handle_t outputDeepBuffer = 0;
1405
1406    for (size_t i = 0; i < outputs.size(); i++) {
1407        sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
1408        ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
1409        if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1410            outputOffloaded = outputs[i];
1411        }
1412        if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1413            outputDeepBuffer = outputs[i];
1414        }
1415    }
1416
1417    ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1418          outputOffloaded, outputDeepBuffer);
1419    if (outputOffloaded != 0) {
1420        return outputOffloaded;
1421    }
1422    if (outputDeepBuffer != 0) {
1423        return outputDeepBuffer;
1424    }
1425
1426    return outputs[0];
1427}
1428
1429audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
1430{
1431    // apply simple rule where global effects are attached to the same output as MUSIC streams
1432
1433    routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
1434    audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1435    SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1436
1437    audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1438    ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1439          output, (desc == NULL) ? "unspecified" : desc->name,  (desc == NULL) ? 0 : desc->flags);
1440
1441    return output;
1442}
1443
1444status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
1445                                audio_io_handle_t io,
1446                                uint32_t strategy,
1447                                int session,
1448                                int id)
1449{
1450    ssize_t index = mOutputs.indexOfKey(io);
1451    if (index < 0) {
1452        index = mInputs.indexOfKey(io);
1453        if (index < 0) {
1454            ALOGW("registerEffect() unknown io %d", io);
1455            return INVALID_OPERATION;
1456        }
1457    }
1458
1459    if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1460        ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1461                desc->name, desc->memoryUsage);
1462        return INVALID_OPERATION;
1463    }
1464    mTotalEffectsMemory += desc->memoryUsage;
1465    ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1466            desc->name, io, strategy, session, id);
1467    ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1468
1469    sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1470    memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1471    effectDesc->mIo = io;
1472    effectDesc->mStrategy = (routing_strategy)strategy;
1473    effectDesc->mSession = session;
1474    effectDesc->mEnabled = false;
1475
1476    mEffects.add(id, effectDesc);
1477
1478    return NO_ERROR;
1479}
1480
1481status_t AudioPolicyManager::unregisterEffect(int id)
1482{
1483    ssize_t index = mEffects.indexOfKey(id);
1484    if (index < 0) {
1485        ALOGW("unregisterEffect() unknown effect ID %d", id);
1486        return INVALID_OPERATION;
1487    }
1488
1489    sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
1490
1491    setEffectEnabled(effectDesc, false);
1492
1493    if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
1494        ALOGW("unregisterEffect() memory %d too big for total %d",
1495                effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1496        effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1497    }
1498    mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
1499    ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1500            effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1501
1502    mEffects.removeItem(id);
1503
1504    return NO_ERROR;
1505}
1506
1507status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
1508{
1509    ssize_t index = mEffects.indexOfKey(id);
1510    if (index < 0) {
1511        ALOGW("unregisterEffect() unknown effect ID %d", id);
1512        return INVALID_OPERATION;
1513    }
1514
1515    return setEffectEnabled(mEffects.valueAt(index), enabled);
1516}
1517
1518status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
1519{
1520    if (enabled == effectDesc->mEnabled) {
1521        ALOGV("setEffectEnabled(%s) effect already %s",
1522             enabled?"true":"false", enabled?"enabled":"disabled");
1523        return INVALID_OPERATION;
1524    }
1525
1526    if (enabled) {
1527        if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1528            ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1529                 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
1530            return INVALID_OPERATION;
1531        }
1532        mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
1533        ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1534    } else {
1535        if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
1536            ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1537                    effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1538            effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1539        }
1540        mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
1541        ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1542    }
1543    effectDesc->mEnabled = enabled;
1544    return NO_ERROR;
1545}
1546
1547bool AudioPolicyManager::isNonOffloadableEffectEnabled()
1548{
1549    for (size_t i = 0; i < mEffects.size(); i++) {
1550        sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1551        if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1552                ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
1553            ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
1554                  effectDesc->mDesc.name, effectDesc->mSession);
1555            return true;
1556        }
1557    }
1558    return false;
1559}
1560
1561bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
1562{
1563    nsecs_t sysTime = systemTime();
1564    for (size_t i = 0; i < mOutputs.size(); i++) {
1565        const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
1566        if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
1567            return true;
1568        }
1569    }
1570    return false;
1571}
1572
1573bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
1574                                                    uint32_t inPastMs) const
1575{
1576    nsecs_t sysTime = systemTime();
1577    for (size_t i = 0; i < mOutputs.size(); i++) {
1578        const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
1579        if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
1580                outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
1581            return true;
1582        }
1583    }
1584    return false;
1585}
1586
1587bool AudioPolicyManager::isSourceActive(audio_source_t source) const
1588{
1589    for (size_t i = 0; i < mInputs.size(); i++) {
1590        const sp<AudioInputDescriptor>  inputDescriptor = mInputs.valueAt(i);
1591        if ((inputDescriptor->mInputSource == (int)source ||
1592                (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
1593                 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1594             && (inputDescriptor->mRefCount > 0)) {
1595            return true;
1596        }
1597    }
1598    return false;
1599}
1600
1601
1602status_t AudioPolicyManager::dump(int fd)
1603{
1604    const size_t SIZE = 256;
1605    char buffer[SIZE];
1606    String8 result;
1607
1608    snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1609    result.append(buffer);
1610
1611    snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1612    result.append(buffer);
1613    snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1614    result.append(buffer);
1615    snprintf(buffer, SIZE, " Force use for communications %d\n",
1616             mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
1617    result.append(buffer);
1618    snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
1619    result.append(buffer);
1620    snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
1621    result.append(buffer);
1622    snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
1623    result.append(buffer);
1624    snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
1625    result.append(buffer);
1626    snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1627            mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1628    result.append(buffer);
1629
1630    snprintf(buffer, SIZE, " Available output devices:\n");
1631    result.append(buffer);
1632    write(fd, result.string(), result.size());
1633    for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
1634        mAvailableOutputDevices[i]->dump(fd, 2, i);
1635    }
1636    snprintf(buffer, SIZE, "\n Available input devices:\n");
1637    write(fd, buffer, strlen(buffer));
1638    for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1639        mAvailableInputDevices[i]->dump(fd, 2, i);
1640    }
1641
1642    snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1643    write(fd, buffer, strlen(buffer));
1644    for (size_t i = 0; i < mHwModules.size(); i++) {
1645        snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
1646        write(fd, buffer, strlen(buffer));
1647        mHwModules[i]->dump(fd);
1648    }
1649
1650    snprintf(buffer, SIZE, "\nOutputs dump:\n");
1651    write(fd, buffer, strlen(buffer));
1652    for (size_t i = 0; i < mOutputs.size(); i++) {
1653        snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1654        write(fd, buffer, strlen(buffer));
1655        mOutputs.valueAt(i)->dump(fd);
1656    }
1657
1658    snprintf(buffer, SIZE, "\nInputs dump:\n");
1659    write(fd, buffer, strlen(buffer));
1660    for (size_t i = 0; i < mInputs.size(); i++) {
1661        snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1662        write(fd, buffer, strlen(buffer));
1663        mInputs.valueAt(i)->dump(fd);
1664    }
1665
1666    snprintf(buffer, SIZE, "\nStreams dump:\n");
1667    write(fd, buffer, strlen(buffer));
1668    snprintf(buffer, SIZE,
1669             " Stream  Can be muted  Index Min  Index Max  Index Cur [device : index]...\n");
1670    write(fd, buffer, strlen(buffer));
1671    for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
1672        snprintf(buffer, SIZE, " %02zu      ", i);
1673        write(fd, buffer, strlen(buffer));
1674        mStreams[i].dump(fd);
1675    }
1676
1677    snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1678            (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1679    write(fd, buffer, strlen(buffer));
1680
1681    snprintf(buffer, SIZE, "Registered effects:\n");
1682    write(fd, buffer, strlen(buffer));
1683    for (size_t i = 0; i < mEffects.size(); i++) {
1684        snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1685        write(fd, buffer, strlen(buffer));
1686        mEffects.valueAt(i)->dump(fd);
1687    }
1688
1689
1690    return NO_ERROR;
1691}
1692
1693// This function checks for the parameters which can be offloaded.
1694// This can be enhanced depending on the capability of the DSP and policy
1695// of the system.
1696bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
1697{
1698    ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
1699     " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
1700     offloadInfo.sample_rate, offloadInfo.channel_mask,
1701     offloadInfo.format,
1702     offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1703     offloadInfo.has_video);
1704
1705    // Check if offload has been disabled
1706    char propValue[PROPERTY_VALUE_MAX];
1707    if (property_get("audio.offload.disable", propValue, "0")) {
1708        if (atoi(propValue) != 0) {
1709            ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1710            return false;
1711        }
1712    }
1713
1714    // Check if stream type is music, then only allow offload as of now.
1715    if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1716    {
1717        ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1718        return false;
1719    }
1720
1721    //TODO: enable audio offloading with video when ready
1722    if (offloadInfo.has_video)
1723    {
1724        ALOGV("isOffloadSupported: has_video == true, returning false");
1725        return false;
1726    }
1727
1728    //If duration is less than minimum value defined in property, return false
1729    if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1730        if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1731            ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1732            return false;
1733        }
1734    } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1735        ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1736        return false;
1737    }
1738
1739    // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1740    // creating an offloaded track and tearing it down immediately after start when audioflinger
1741    // detects there is an active non offloadable effect.
1742    // FIXME: We should check the audio session here but we do not have it in this context.
1743    // This may prevent offloading in rare situations where effects are left active by apps
1744    // in the background.
1745    if (isNonOffloadableEffectEnabled()) {
1746        return false;
1747    }
1748
1749    // See if there is a profile to support this.
1750    // AUDIO_DEVICE_NONE
1751    sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
1752                                            offloadInfo.sample_rate,
1753                                            offloadInfo.format,
1754                                            offloadInfo.channel_mask,
1755                                            AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1756    ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1757    return (profile != 0);
1758}
1759
1760status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1761                                            audio_port_type_t type,
1762                                            unsigned int *num_ports,
1763                                            struct audio_port *ports,
1764                                            unsigned int *generation)
1765{
1766    if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1767            generation == NULL) {
1768        return BAD_VALUE;
1769    }
1770    ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1771    if (ports == NULL) {
1772        *num_ports = 0;
1773    }
1774
1775    size_t portsWritten = 0;
1776    size_t portsMax = *num_ports;
1777    *num_ports = 0;
1778    if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1779        if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1780            for (size_t i = 0;
1781                    i  < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1782                mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1783            }
1784            *num_ports += mAvailableOutputDevices.size();
1785        }
1786        if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1787            for (size_t i = 0;
1788                    i  < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1789                mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1790            }
1791            *num_ports += mAvailableInputDevices.size();
1792        }
1793    }
1794    if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1795        if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1796            for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1797                mInputs[i]->toAudioPort(&ports[portsWritten++]);
1798            }
1799            *num_ports += mInputs.size();
1800        }
1801        if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1802            size_t numOutputs = 0;
1803            for (size_t i = 0; i < mOutputs.size(); i++) {
1804                if (!mOutputs[i]->isDuplicated()) {
1805                    numOutputs++;
1806                    if (portsWritten < portsMax) {
1807                        mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1808                    }
1809                }
1810            }
1811            *num_ports += numOutputs;
1812        }
1813    }
1814    *generation = curAudioPortGeneration();
1815    ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
1816    return NO_ERROR;
1817}
1818
1819status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1820{
1821    return NO_ERROR;
1822}
1823
1824sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
1825                                                                    audio_port_handle_t id) const
1826{
1827    sp<AudioOutputDescriptor> outputDesc = NULL;
1828    for (size_t i = 0; i < mOutputs.size(); i++) {
1829        outputDesc = mOutputs.valueAt(i);
1830        if (outputDesc->mId == id) {
1831            break;
1832        }
1833    }
1834    return outputDesc;
1835}
1836
1837sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
1838                                                                    audio_port_handle_t id) const
1839{
1840    sp<AudioInputDescriptor> inputDesc = NULL;
1841    for (size_t i = 0; i < mInputs.size(); i++) {
1842        inputDesc = mInputs.valueAt(i);
1843        if (inputDesc->mId == id) {
1844            break;
1845        }
1846    }
1847    return inputDesc;
1848}
1849
1850sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
1851                                                                    audio_devices_t device) const
1852{
1853    sp <HwModule> module;
1854
1855    for (size_t i = 0; i < mHwModules.size(); i++) {
1856        if (mHwModules[i]->mHandle == 0) {
1857            continue;
1858        }
1859        if (audio_is_output_device(device)) {
1860            for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1861            {
1862                if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1863                    return mHwModules[i];
1864                }
1865            }
1866        } else {
1867            for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1868                if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1869                        device & ~AUDIO_DEVICE_BIT_IN) {
1870                    return mHwModules[i];
1871                }
1872            }
1873        }
1874    }
1875    return module;
1876}
1877
1878sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
1879{
1880    sp <HwModule> module;
1881
1882    for (size_t i = 0; i < mHwModules.size(); i++)
1883    {
1884        if (strcmp(mHwModules[i]->mName, name) == 0) {
1885            return mHwModules[i];
1886        }
1887    }
1888    return module;
1889}
1890
1891
1892status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1893                                               audio_patch_handle_t *handle,
1894                                               uid_t uid)
1895{
1896    ALOGV("createAudioPatch()");
1897
1898    if (handle == NULL || patch == NULL) {
1899        return BAD_VALUE;
1900    }
1901    ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1902
1903    if (patch->num_sources > 1 || patch->num_sinks > 1) {
1904        return INVALID_OPERATION;
1905    }
1906    if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1907            patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1908        return INVALID_OPERATION;
1909    }
1910
1911    sp<AudioPatch> patchDesc;
1912    ssize_t index = mAudioPatches.indexOfKey(*handle);
1913
1914    ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1915                                                         patch->sinks[0].type);
1916    ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1917                                                           patch->sources[0].role,
1918                                                           patch->sources[0].type);
1919
1920    if (index >= 0) {
1921        patchDesc = mAudioPatches.valueAt(index);
1922        ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1923                                                                  mUidCached, patchDesc->mUid, uid);
1924        if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1925            return INVALID_OPERATION;
1926        }
1927    } else {
1928        *handle = 0;
1929    }
1930
1931    if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1932        // TODO add support for mix to mix connection
1933        if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1934            ALOGV("createAudioPatch() source mix sink not device");
1935            return BAD_VALUE;
1936        }
1937        // output mix to output device connection
1938        sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
1939        if (outputDesc == NULL) {
1940            ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1941            return BAD_VALUE;
1942        }
1943        ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
1944                                                outputDesc->mIoHandle);
1945        if (patchDesc != 0) {
1946            if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1947                ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1948                                          patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1949                return BAD_VALUE;
1950            }
1951        }
1952        sp<DeviceDescriptor> devDesc =
1953                mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1954        if (devDesc == 0) {
1955            ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1956            return BAD_VALUE;
1957        }
1958
1959        if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
1960                                                       patch->sources[0].sample_rate,
1961                                                     NULL,  // updatedSamplingRate
1962                                                     patch->sources[0].format,
1963                                                     patch->sources[0].channel_mask,
1964                                                     AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
1965            ALOGV("createAudioPatch() profile not supported");
1966            return INVALID_OPERATION;
1967        }
1968        // TODO: reconfigure output format and channels here
1969        ALOGV("createAudioPatch() setting device %08x on output %d",
1970                                              devDesc->mDeviceType, outputDesc->mIoHandle);
1971        setOutputDevice(outputDesc->mIoHandle,
1972                        devDesc->mDeviceType,
1973                       true,
1974                       0,
1975                       handle);
1976        index = mAudioPatches.indexOfKey(*handle);
1977        if (index >= 0) {
1978            if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1979                ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1980            }
1981            patchDesc = mAudioPatches.valueAt(index);
1982            patchDesc->mUid = uid;
1983            ALOGV("createAudioPatch() success");
1984        } else {
1985            ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1986            return INVALID_OPERATION;
1987        }
1988    } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1989        if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1990            // input device to input mix connection
1991            sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
1992            if (inputDesc == NULL) {
1993                return BAD_VALUE;
1994            }
1995            if (patchDesc != 0) {
1996                if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1997                    return BAD_VALUE;
1998                }
1999            }
2000            sp<DeviceDescriptor> devDesc =
2001                    mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2002            if (devDesc == 0) {
2003                return BAD_VALUE;
2004            }
2005
2006            if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
2007                                                         patch->sinks[0].sample_rate,
2008                                                         NULL, /*updatedSampleRate*/
2009                                                         patch->sinks[0].format,
2010                                                         patch->sinks[0].channel_mask,
2011                                                         // FIXME for the parameter type,
2012                                                         // and the NONE
2013                                                         (audio_output_flags_t)
2014                                                            AUDIO_INPUT_FLAG_NONE)) {
2015                return INVALID_OPERATION;
2016            }
2017            // TODO: reconfigure output format and channels here
2018            ALOGV("createAudioPatch() setting device %08x on output %d",
2019                                                  devDesc->mDeviceType, inputDesc->mIoHandle);
2020            setInputDevice(inputDesc->mIoHandle,
2021                           devDesc->mDeviceType,
2022                           true,
2023                           handle);
2024            index = mAudioPatches.indexOfKey(*handle);
2025            if (index >= 0) {
2026                if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2027                    ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2028                }
2029                patchDesc = mAudioPatches.valueAt(index);
2030                patchDesc->mUid = uid;
2031                ALOGV("createAudioPatch() success");
2032            } else {
2033                ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2034                return INVALID_OPERATION;
2035            }
2036        } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2037            // device to device connection
2038            if (patchDesc != 0) {
2039                if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
2040                    patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2041                    return BAD_VALUE;
2042                }
2043            }
2044
2045            sp<DeviceDescriptor> srcDeviceDesc =
2046                    mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2047            sp<DeviceDescriptor> sinkDeviceDesc =
2048                    mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
2049            if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
2050                return BAD_VALUE;
2051            }
2052            //update source and sink with our own data as the data passed in the patch may
2053            // be incomplete.
2054            struct audio_patch newPatch = *patch;
2055            srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
2056            sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
2057
2058            if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2059                SortedVector<audio_io_handle_t> outputs =
2060                                        getOutputsForDevice(sinkDeviceDesc->mDeviceType, mOutputs);
2061                // if the sink device is reachable via an opened output stream, request to go via
2062                // this output stream by adding a second source to the patch description
2063                audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
2064                if (output != AUDIO_IO_HANDLE_NONE) {
2065                    sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2066                    if (outputDesc->isDuplicated()) {
2067                        return INVALID_OPERATION;
2068                    }
2069                    outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2070                    newPatch.num_sources = 2;
2071                }
2072            }
2073            // TODO: check from routing capabilities in config file and other conflicting patches
2074
2075            audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2076            if (index >= 0) {
2077                afPatchHandle = patchDesc->mAfPatchHandle;
2078            }
2079
2080            status_t status = mpClientInterface->createAudioPatch(&newPatch,
2081                                                                  &afPatchHandle,
2082                                                                  0);
2083            ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2084                                                                  status, afPatchHandle);
2085            if (status == NO_ERROR) {
2086                if (index < 0) {
2087                    patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2088                                               &newPatch, uid);
2089                    addAudioPatch(patchDesc->mHandle, patchDesc);
2090                } else {
2091                    patchDesc->mPatch = newPatch;
2092                }
2093                patchDesc->mAfPatchHandle = afPatchHandle;
2094                *handle = patchDesc->mHandle;
2095                nextAudioPortGeneration();
2096                mpClientInterface->onAudioPatchListUpdate();
2097            } else {
2098                ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2099                status);
2100                return INVALID_OPERATION;
2101            }
2102        } else {
2103            return BAD_VALUE;
2104        }
2105    } else {
2106        return BAD_VALUE;
2107    }
2108    return NO_ERROR;
2109}
2110
2111status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2112                                                  uid_t uid)
2113{
2114    ALOGV("releaseAudioPatch() patch %d", handle);
2115
2116    ssize_t index = mAudioPatches.indexOfKey(handle);
2117
2118    if (index < 0) {
2119        return BAD_VALUE;
2120    }
2121    sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2122    ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2123          mUidCached, patchDesc->mUid, uid);
2124    if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2125        return INVALID_OPERATION;
2126    }
2127
2128    struct audio_patch *patch = &patchDesc->mPatch;
2129    patchDesc->mUid = mUidCached;
2130    if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
2131        sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
2132        if (outputDesc == NULL) {
2133            ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2134            return BAD_VALUE;
2135        }
2136
2137        setOutputDevice(outputDesc->mIoHandle,
2138                        getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2139                       true,
2140                       0,
2141                       NULL);
2142    } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2143        if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2144            sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
2145            if (inputDesc == NULL) {
2146                ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2147                return BAD_VALUE;
2148            }
2149            setInputDevice(inputDesc->mIoHandle,
2150                           getNewInputDevice(inputDesc->mIoHandle),
2151                           true,
2152                           NULL);
2153        } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2154            audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2155            status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2156            ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2157                                                              status, patchDesc->mAfPatchHandle);
2158            removeAudioPatch(patchDesc->mHandle);
2159            nextAudioPortGeneration();
2160            mpClientInterface->onAudioPatchListUpdate();
2161        } else {
2162            return BAD_VALUE;
2163        }
2164    } else {
2165        return BAD_VALUE;
2166    }
2167    return NO_ERROR;
2168}
2169
2170status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2171                                              struct audio_patch *patches,
2172                                              unsigned int *generation)
2173{
2174    if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2175            generation == NULL) {
2176        return BAD_VALUE;
2177    }
2178    ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
2179          *num_patches, patches, mAudioPatches.size());
2180    if (patches == NULL) {
2181        *num_patches = 0;
2182    }
2183
2184    size_t patchesWritten = 0;
2185    size_t patchesMax = *num_patches;
2186    for (size_t i = 0;
2187            i  < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2188        patches[patchesWritten] = mAudioPatches[i]->mPatch;
2189        patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
2190        ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
2191              i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2192    }
2193    *num_patches = mAudioPatches.size();
2194
2195    *generation = curAudioPortGeneration();
2196    ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
2197    return NO_ERROR;
2198}
2199
2200status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
2201{
2202    ALOGV("setAudioPortConfig()");
2203
2204    if (config == NULL) {
2205        return BAD_VALUE;
2206    }
2207    ALOGV("setAudioPortConfig() on port handle %d", config->id);
2208    // Only support gain configuration for now
2209    if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2210        return INVALID_OPERATION;
2211    }
2212
2213    sp<AudioPortConfig> audioPortConfig;
2214    if (config->type == AUDIO_PORT_TYPE_MIX) {
2215        if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2216            sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
2217            if (outputDesc == NULL) {
2218                return BAD_VALUE;
2219            }
2220            ALOG_ASSERT(!outputDesc->isDuplicated(),
2221                        "setAudioPortConfig() called on duplicated output %d",
2222                        outputDesc->mIoHandle);
2223            audioPortConfig = outputDesc;
2224        } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2225            sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
2226            if (inputDesc == NULL) {
2227                return BAD_VALUE;
2228            }
2229            audioPortConfig = inputDesc;
2230        } else {
2231            return BAD_VALUE;
2232        }
2233    } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2234        sp<DeviceDescriptor> deviceDesc;
2235        if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2236            deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2237        } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2238            deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2239        } else {
2240            return BAD_VALUE;
2241        }
2242        if (deviceDesc == NULL) {
2243            return BAD_VALUE;
2244        }
2245        audioPortConfig = deviceDesc;
2246    } else {
2247        return BAD_VALUE;
2248    }
2249
2250    struct audio_port_config backupConfig;
2251    status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2252    if (status == NO_ERROR) {
2253        struct audio_port_config newConfig;
2254        audioPortConfig->toAudioPortConfig(&newConfig, config);
2255        status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
2256    }
2257    if (status != NO_ERROR) {
2258        audioPortConfig->applyAudioPortConfig(&backupConfig);
2259    }
2260
2261    return status;
2262}
2263
2264void AudioPolicyManager::clearAudioPatches(uid_t uid)
2265{
2266    for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++)  {
2267        sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2268        if (patchDesc->mUid == uid) {
2269            // releaseAudioPatch() removes the patch from mAudioPatches
2270            if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2271                i--;
2272            }
2273        }
2274    }
2275}
2276
2277status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2278                                       audio_io_handle_t *ioHandle,
2279                                       audio_devices_t *device)
2280{
2281    *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2282    *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
2283    *device = getDeviceForInputSource(AUDIO_SOURCE_HOTWORD);
2284
2285    mSoundTriggerSessions.add(*session, *ioHandle);
2286
2287    return NO_ERROR;
2288}
2289
2290status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2291{
2292    ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2293    if (index < 0) {
2294        ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2295        return BAD_VALUE;
2296    }
2297
2298    mSoundTriggerSessions.removeItem(session);
2299    return NO_ERROR;
2300}
2301
2302status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2303                                           const sp<AudioPatch>& patch)
2304{
2305    ssize_t index = mAudioPatches.indexOfKey(handle);
2306
2307    if (index >= 0) {
2308        ALOGW("addAudioPatch() patch %d already in", handle);
2309        return ALREADY_EXISTS;
2310    }
2311    mAudioPatches.add(handle, patch);
2312    ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2313            "sink handle %d",
2314          handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2315          patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2316    return NO_ERROR;
2317}
2318
2319status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2320{
2321    ssize_t index = mAudioPatches.indexOfKey(handle);
2322
2323    if (index < 0) {
2324        ALOGW("removeAudioPatch() patch %d not in", handle);
2325        return ALREADY_EXISTS;
2326    }
2327    ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2328                      mAudioPatches.valueAt(index)->mAfPatchHandle);
2329    mAudioPatches.removeItemsAt(index);
2330    return NO_ERROR;
2331}
2332
2333// ----------------------------------------------------------------------------
2334// AudioPolicyManager
2335// ----------------------------------------------------------------------------
2336
2337uint32_t AudioPolicyManager::nextUniqueId()
2338{
2339    return android_atomic_inc(&mNextUniqueId);
2340}
2341
2342uint32_t AudioPolicyManager::nextAudioPortGeneration()
2343{
2344    return android_atomic_inc(&mAudioPortGeneration);
2345}
2346
2347AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
2348    :
2349#ifdef AUDIO_POLICY_TEST
2350    Thread(false),
2351#endif //AUDIO_POLICY_TEST
2352    mPrimaryOutput((audio_io_handle_t)0),
2353    mPhoneState(AUDIO_MODE_NORMAL),
2354    mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2355    mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
2356    mA2dpSuspended(false),
2357    mSpeakerDrcEnabled(false), mNextUniqueId(1),
2358    mAudioPortGeneration(1)
2359{
2360    mUidCached = getuid();
2361    mpClientInterface = clientInterface;
2362
2363    for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2364        mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
2365    }
2366
2367    mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
2368    if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2369        if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2370            ALOGE("could not load audio policy configuration file, setting defaults");
2371            defaultAudioPolicyConfig();
2372        }
2373    }
2374    // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
2375
2376    // must be done after reading the policy
2377    initializeVolumeCurves();
2378
2379    // open all output streams needed to access attached devices
2380    audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2381    audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
2382    for (size_t i = 0; i < mHwModules.size(); i++) {
2383        mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2384        if (mHwModules[i]->mHandle == 0) {
2385            ALOGW("could not open HW module %s", mHwModules[i]->mName);
2386            continue;
2387        }
2388        // open all output streams needed to access attached devices
2389        // except for direct output streams that are only opened when they are actually
2390        // required by an app.
2391        // This also validates mAvailableOutputDevices list
2392        for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2393        {
2394            const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
2395
2396            if (outProfile->mSupportedDevices.isEmpty()) {
2397                ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2398                continue;
2399            }
2400
2401            audio_devices_t profileType = outProfile->mSupportedDevices.types();
2402            if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2403                profileType = mDefaultOutputDevice->mDeviceType;
2404            } else {
2405                profileType = outProfile->mSupportedDevices[0]->mDeviceType;
2406            }
2407            if ((profileType & outputDeviceTypes) &&
2408                    ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
2409                sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
2410
2411                outputDesc->mDevice = profileType;
2412                audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2413                config.sample_rate = outputDesc->mSamplingRate;
2414                config.channel_mask = outputDesc->mChannelMask;
2415                config.format = outputDesc->mFormat;
2416                audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2417                status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2418                                                                &output,
2419                                                                &config,
2420                                                                &outputDesc->mDevice,
2421                                                                String8(""),
2422                                                                &outputDesc->mLatency,
2423                                                                outputDesc->mFlags);
2424
2425                if (status != NO_ERROR) {
2426                    ALOGW("Cannot open output stream for device %08x on hw module %s",
2427                          outputDesc->mDevice,
2428                          mHwModules[i]->mName);
2429                } else {
2430                    outputDesc->mSamplingRate = config.sample_rate;
2431                    outputDesc->mChannelMask = config.channel_mask;
2432                    outputDesc->mFormat = config.format;
2433
2434                    for (size_t k = 0; k  < outProfile->mSupportedDevices.size(); k++) {
2435                        audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
2436                        ssize_t index =
2437                                mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
2438                        // give a valid ID to an attached device once confirmed it is reachable
2439                        if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2440                            mAvailableOutputDevices[index]->mId = nextUniqueId();
2441                            mAvailableOutputDevices[index]->mModule = mHwModules[i];
2442                        }
2443                    }
2444                    if (mPrimaryOutput == 0 &&
2445                            outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2446                        mPrimaryOutput = output;
2447                    }
2448                    addOutput(output, outputDesc);
2449                    setOutputDevice(output,
2450                                    outputDesc->mDevice,
2451                                    true);
2452                }
2453            }
2454        }
2455        // open input streams needed to access attached devices to validate
2456        // mAvailableInputDevices list
2457        for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2458        {
2459            const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
2460
2461            if (inProfile->mSupportedDevices.isEmpty()) {
2462                ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2463                continue;
2464            }
2465
2466            audio_devices_t profileType = inProfile->mSupportedDevices[0]->mDeviceType;
2467            if (profileType & inputDeviceTypes) {
2468                sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
2469
2470                inputDesc->mInputSource = AUDIO_SOURCE_MIC;
2471                inputDesc->mDevice = profileType;
2472
2473                audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2474                config.sample_rate = inputDesc->mSamplingRate;
2475                config.channel_mask = inputDesc->mChannelMask;
2476                config.format = inputDesc->mFormat;
2477                audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2478                status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2479                                                               &input,
2480                                                               &config,
2481                                                               &inputDesc->mDevice,
2482                                                               String8(""),
2483                                                               AUDIO_SOURCE_MIC,
2484                                                               AUDIO_INPUT_FLAG_NONE);
2485
2486                if (status == NO_ERROR) {
2487                    for (size_t k = 0; k  < inProfile->mSupportedDevices.size(); k++) {
2488                        audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
2489                        ssize_t index =
2490                                mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
2491                        // give a valid ID to an attached device once confirmed it is reachable
2492                        if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2493                            mAvailableInputDevices[index]->mId = nextUniqueId();
2494                            mAvailableInputDevices[index]->mModule = mHwModules[i];
2495                        }
2496                    }
2497                    mpClientInterface->closeInput(input);
2498                } else {
2499                    ALOGW("Cannot open input stream for device %08x on hw module %s",
2500                          inputDesc->mDevice,
2501                          mHwModules[i]->mName);
2502                }
2503            }
2504        }
2505    }
2506    // make sure all attached devices have been allocated a unique ID
2507    for (size_t i = 0; i  < mAvailableOutputDevices.size();) {
2508        if (mAvailableOutputDevices[i]->mId == 0) {
2509            ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
2510            mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2511            continue;
2512        }
2513        i++;
2514    }
2515    for (size_t i = 0; i  < mAvailableInputDevices.size();) {
2516        if (mAvailableInputDevices[i]->mId == 0) {
2517            ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
2518            mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2519            continue;
2520        }
2521        i++;
2522    }
2523    // make sure default device is reachable
2524    if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
2525        ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
2526    }
2527
2528    ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2529
2530    updateDevicesAndOutputs();
2531
2532#ifdef AUDIO_POLICY_TEST
2533    if (mPrimaryOutput != 0) {
2534        AudioParameter outputCmd = AudioParameter();
2535        outputCmd.addInt(String8("set_id"), 0);
2536        mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2537
2538        mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2539        mTestSamplingRate = 44100;
2540        mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2541        mTestChannels =  AUDIO_CHANNEL_OUT_STEREO;
2542        mTestLatencyMs = 0;
2543        mCurOutput = 0;
2544        mDirectOutput = false;
2545        for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2546            mTestOutputs[i] = 0;
2547        }
2548
2549        const size_t SIZE = 256;
2550        char buffer[SIZE];
2551        snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2552        run(buffer, ANDROID_PRIORITY_AUDIO);
2553    }
2554#endif //AUDIO_POLICY_TEST
2555}
2556
2557AudioPolicyManager::~AudioPolicyManager()
2558{
2559#ifdef AUDIO_POLICY_TEST
2560    exit();
2561#endif //AUDIO_POLICY_TEST
2562   for (size_t i = 0; i < mOutputs.size(); i++) {
2563        mpClientInterface->closeOutput(mOutputs.keyAt(i));
2564   }
2565   for (size_t i = 0; i < mInputs.size(); i++) {
2566        mpClientInterface->closeInput(mInputs.keyAt(i));
2567   }
2568   mAvailableOutputDevices.clear();
2569   mAvailableInputDevices.clear();
2570   mOutputs.clear();
2571   mInputs.clear();
2572   mHwModules.clear();
2573}
2574
2575status_t AudioPolicyManager::initCheck()
2576{
2577    return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2578}
2579
2580#ifdef AUDIO_POLICY_TEST
2581bool AudioPolicyManager::threadLoop()
2582{
2583    ALOGV("entering threadLoop()");
2584    while (!exitPending())
2585    {
2586        String8 command;
2587        int valueInt;
2588        String8 value;
2589
2590        Mutex::Autolock _l(mLock);
2591        mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2592
2593        command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2594        AudioParameter param = AudioParameter(command);
2595
2596        if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2597            valueInt != 0) {
2598            ALOGV("Test command %s received", command.string());
2599            String8 target;
2600            if (param.get(String8("target"), target) != NO_ERROR) {
2601                target = "Manager";
2602            }
2603            if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2604                param.remove(String8("test_cmd_policy_output"));
2605                mCurOutput = valueInt;
2606            }
2607            if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2608                param.remove(String8("test_cmd_policy_direct"));
2609                if (value == "false") {
2610                    mDirectOutput = false;
2611                } else if (value == "true") {
2612                    mDirectOutput = true;
2613                }
2614            }
2615            if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2616                param.remove(String8("test_cmd_policy_input"));
2617                mTestInput = valueInt;
2618            }
2619
2620            if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2621                param.remove(String8("test_cmd_policy_format"));
2622                int format = AUDIO_FORMAT_INVALID;
2623                if (value == "PCM 16 bits") {
2624                    format = AUDIO_FORMAT_PCM_16_BIT;
2625                } else if (value == "PCM 8 bits") {
2626                    format = AUDIO_FORMAT_PCM_8_BIT;
2627                } else if (value == "Compressed MP3") {
2628                    format = AUDIO_FORMAT_MP3;
2629                }
2630                if (format != AUDIO_FORMAT_INVALID) {
2631                    if (target == "Manager") {
2632                        mTestFormat = format;
2633                    } else if (mTestOutputs[mCurOutput] != 0) {
2634                        AudioParameter outputParam = AudioParameter();
2635                        outputParam.addInt(String8("format"), format);
2636                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2637                    }
2638                }
2639            }
2640            if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2641                param.remove(String8("test_cmd_policy_channels"));
2642                int channels = 0;
2643
2644                if (value == "Channels Stereo") {
2645                    channels =  AUDIO_CHANNEL_OUT_STEREO;
2646                } else if (value == "Channels Mono") {
2647                    channels =  AUDIO_CHANNEL_OUT_MONO;
2648                }
2649                if (channels != 0) {
2650                    if (target == "Manager") {
2651                        mTestChannels = channels;
2652                    } else if (mTestOutputs[mCurOutput] != 0) {
2653                        AudioParameter outputParam = AudioParameter();
2654                        outputParam.addInt(String8("channels"), channels);
2655                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2656                    }
2657                }
2658            }
2659            if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2660                param.remove(String8("test_cmd_policy_sampleRate"));
2661                if (valueInt >= 0 && valueInt <= 96000) {
2662                    int samplingRate = valueInt;
2663                    if (target == "Manager") {
2664                        mTestSamplingRate = samplingRate;
2665                    } else if (mTestOutputs[mCurOutput] != 0) {
2666                        AudioParameter outputParam = AudioParameter();
2667                        outputParam.addInt(String8("sampling_rate"), samplingRate);
2668                        mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2669                    }
2670                }
2671            }
2672
2673            if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2674                param.remove(String8("test_cmd_policy_reopen"));
2675
2676                sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2677                mpClientInterface->closeOutput(mPrimaryOutput);
2678
2679                audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2680
2681                mOutputs.removeItem(mPrimaryOutput);
2682
2683                sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
2684                outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
2685                audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2686                config.sample_rate = outputDesc->mSamplingRate;
2687                config.channel_mask = outputDesc->mChannelMask;
2688                config.format = outputDesc->mFormat;
2689                status_t status = mpClientInterface->openOutput(moduleHandle,
2690                                                                &mPrimaryOutput,
2691                                                                &config,
2692                                                                &outputDesc->mDevice,
2693                                                                String8(""),
2694                                                                &outputDesc->mLatency,
2695                                                                outputDesc->mFlags);
2696                if (status != NO_ERROR) {
2697                    ALOGE("Failed to reopen hardware output stream, "
2698                        "samplingRate: %d, format %d, channels %d",
2699                        outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
2700                } else {
2701                    outputDesc->mSamplingRate = config.sample_rate;
2702                    outputDesc->mChannelMask = config.channel_mask;
2703                    outputDesc->mFormat = config.format;
2704                    AudioParameter outputCmd = AudioParameter();
2705                    outputCmd.addInt(String8("set_id"), 0);
2706                    mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2707                    addOutput(mPrimaryOutput, outputDesc);
2708                }
2709            }
2710
2711
2712            mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2713        }
2714    }
2715    return false;
2716}
2717
2718void AudioPolicyManager::exit()
2719{
2720    {
2721        AutoMutex _l(mLock);
2722        requestExit();
2723        mWaitWorkCV.signal();
2724    }
2725    requestExitAndWait();
2726}
2727
2728int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
2729{
2730    for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2731        if (output == mTestOutputs[i]) return i;
2732    }
2733    return 0;
2734}
2735#endif //AUDIO_POLICY_TEST
2736
2737// ---
2738
2739void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
2740{
2741    outputDesc->mIoHandle = output;
2742    outputDesc->mId = nextUniqueId();
2743    mOutputs.add(output, outputDesc);
2744    nextAudioPortGeneration();
2745}
2746
2747void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
2748{
2749    inputDesc->mIoHandle = input;
2750    inputDesc->mId = nextUniqueId();
2751    mInputs.add(input, inputDesc);
2752    nextAudioPortGeneration();
2753}
2754
2755void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
2756        const String8 address /*in*/,
2757        SortedVector<audio_io_handle_t>& outputs /*out*/) {
2758    // look for a match on the given address on the addresses of the outputs:
2759    // find the address by finding the patch that maps to this output
2760    ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
2761    //ALOGV("    inspecting output %d (patch %d) for supported device=0x%x",
2762    //        outputIdx, patchIdx,  desc->mProfile->mSupportedDevices.types());
2763    if (patchIdx >= 0) {
2764        const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
2765        const int numSinks = patchDesc->mPatch.num_sinks;
2766        for (ssize_t j=0; j < numSinks; j++) {
2767            if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
2768                const char* patchAddr =
2769                        patchDesc->mPatch.sinks[j].ext.device.address;
2770                if (strncmp(patchAddr,
2771                        address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
2772                    ALOGV("checkOutputsForDevice(): adding opened output %d on same address %s",
2773                            desc->mIoHandle,  patchDesc->mPatch.sinks[j].ext.device.address);
2774                    outputs.add(desc->mIoHandle);
2775                    break;
2776                }
2777            }
2778        }
2779    }
2780}
2781
2782status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
2783                                                       audio_policy_dev_state_t state,
2784                                                       SortedVector<audio_io_handle_t>& outputs,
2785                                                       const String8 address)
2786{
2787    sp<AudioOutputDescriptor> desc;
2788
2789    if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2790        // first list already open outputs that can be routed to this device
2791        for (size_t i = 0; i < mOutputs.size(); i++) {
2792            desc = mOutputs.valueAt(i);
2793            if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
2794                if (!deviceDistinguishesOnAddress(device)) {
2795                    ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2796                    outputs.add(mOutputs.keyAt(i));
2797                } else {
2798                    ALOGV("  checking address match due to device 0x%x", device);
2799                    findIoHandlesByAddress(desc, address, outputs);
2800                }
2801            }
2802        }
2803        // then look for output profiles that can be routed to this device
2804        SortedVector< sp<IOProfile> > profiles;
2805        for (size_t i = 0; i < mHwModules.size(); i++)
2806        {
2807            if (mHwModules[i]->mHandle == 0) {
2808                continue;
2809            }
2810            for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2811            {
2812                if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2813                    ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
2814                    profiles.add(mHwModules[i]->mOutputProfiles[j]);
2815                }
2816            }
2817        }
2818
2819        ALOGV("  found %d profiles, %d outputs", profiles.size(), outputs.size());
2820
2821        if (profiles.isEmpty() && outputs.isEmpty()) {
2822            ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2823            return BAD_VALUE;
2824        }
2825
2826        // open outputs for matching profiles if needed. Direct outputs are also opened to
2827        // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2828        for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2829            sp<IOProfile> profile = profiles[profile_index];
2830
2831            // nothing to do if one output is already opened for this profile
2832            size_t j;
2833            for (j = 0; j < outputs.size(); j++) {
2834                desc = mOutputs.valueFor(outputs.itemAt(j));
2835                if (!desc->isDuplicated() && desc->mProfile == profile) {
2836                    break;
2837                }
2838            }
2839            if (j != outputs.size()) {
2840                continue;
2841            }
2842
2843            ALOGV("opening output for device %08x with params %s profile %p",
2844                                                      device, address.string(), profile.get());
2845            desc = new AudioOutputDescriptor(profile);
2846            desc->mDevice = device;
2847            audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2848            config.sample_rate = desc->mSamplingRate;
2849            config.channel_mask = desc->mChannelMask;
2850            config.format = desc->mFormat;
2851            config.offload_info.sample_rate = desc->mSamplingRate;
2852            config.offload_info.channel_mask = desc->mChannelMask;
2853            config.offload_info.format = desc->mFormat;
2854            audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2855            status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
2856                                                            &output,
2857                                                            &config,
2858                                                            &desc->mDevice,
2859                                                            address,
2860                                                            &desc->mLatency,
2861                                                            desc->mFlags);
2862            if (status == NO_ERROR) {
2863                desc->mSamplingRate = config.sample_rate;
2864                desc->mChannelMask = config.channel_mask;
2865                desc->mFormat = config.format;
2866
2867                // Here is where the out_set_parameters() for card & device gets called
2868                if (!address.isEmpty()) {
2869                    char *param = audio_device_address_to_parameter(device, address);
2870                    mpClientInterface->setParameters(output, String8(param));
2871                    free(param);
2872                }
2873
2874                // Here is where we step through and resolve any "dynamic" fields
2875                String8 reply;
2876                char *value;
2877                if (profile->mSamplingRates[0] == 0) {
2878                    reply = mpClientInterface->getParameters(output,
2879                                            String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2880                    ALOGV("checkOutputsForDevice() supported sampling rates %s",
2881                              reply.string());
2882                    value = strpbrk((char *)reply.string(), "=");
2883                    if (value != NULL) {
2884                        profile->loadSamplingRates(value + 1);
2885                    }
2886                }
2887                if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2888                    reply = mpClientInterface->getParameters(output,
2889                                                   String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2890                    ALOGV("checkOutputsForDevice() supported formats %s",
2891                              reply.string());
2892                    value = strpbrk((char *)reply.string(), "=");
2893                    if (value != NULL) {
2894                        profile->loadFormats(value + 1);
2895                    }
2896                }
2897                if (profile->mChannelMasks[0] == 0) {
2898                    reply = mpClientInterface->getParameters(output,
2899                                                  String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2900                    ALOGV("checkOutputsForDevice() supported channel masks %s",
2901                              reply.string());
2902                    value = strpbrk((char *)reply.string(), "=");
2903                    if (value != NULL) {
2904                        profile->loadOutChannels(value + 1);
2905                    }
2906                }
2907                if (((profile->mSamplingRates[0] == 0) &&
2908                         (profile->mSamplingRates.size() < 2)) ||
2909                     ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2910                         (profile->mFormats.size() < 2)) ||
2911                     ((profile->mChannelMasks[0] == 0) &&
2912                         (profile->mChannelMasks.size() < 2))) {
2913                    ALOGW("checkOutputsForDevice() missing param");
2914                    mpClientInterface->closeOutput(output);
2915                    output = AUDIO_IO_HANDLE_NONE;
2916                } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
2917                            profile->mChannelMasks[0] == 0) {
2918                    mpClientInterface->closeOutput(output);
2919                    config.sample_rate = profile->pickSamplingRate();
2920                    config.channel_mask = profile->pickChannelMask();
2921                    config.format = profile->pickFormat();
2922                    config.offload_info.sample_rate = config.sample_rate;
2923                    config.offload_info.channel_mask = config.channel_mask;
2924                    config.offload_info.format = config.format;
2925                    status = mpClientInterface->openOutput(profile->mModule->mHandle,
2926                                                           &output,
2927                                                           &config,
2928                                                           &desc->mDevice,
2929                                                           address,
2930                                                           &desc->mLatency,
2931                                                           desc->mFlags);
2932                    if (status == NO_ERROR) {
2933                        desc->mSamplingRate = config.sample_rate;
2934                        desc->mChannelMask = config.channel_mask;
2935                        desc->mFormat = config.format;
2936                    } else {
2937                        output = AUDIO_IO_HANDLE_NONE;
2938                    }
2939                }
2940
2941                if (output != AUDIO_IO_HANDLE_NONE) {
2942                    addOutput(output, desc);
2943                    if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
2944                        audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
2945
2946                        // set initial stream volume for device
2947                        applyStreamVolumes(output, device, 0, true);
2948
2949                        //TODO: configure audio effect output stage here
2950
2951                        // open a duplicating output thread for the new output and the primary output
2952                        duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2953                                                                                  mPrimaryOutput);
2954                        if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
2955                            // add duplicated output descriptor
2956                            sp<AudioOutputDescriptor> dupOutputDesc =
2957                                    new AudioOutputDescriptor(NULL);
2958                            dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2959                            dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2960                            dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2961                            dupOutputDesc->mFormat = desc->mFormat;
2962                            dupOutputDesc->mChannelMask = desc->mChannelMask;
2963                            dupOutputDesc->mLatency = desc->mLatency;
2964                            addOutput(duplicatedOutput, dupOutputDesc);
2965                            applyStreamVolumes(duplicatedOutput, device, 0, true);
2966                        } else {
2967                            ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2968                                    mPrimaryOutput, output);
2969                            mpClientInterface->closeOutput(output);
2970                            mOutputs.removeItem(output);
2971                            nextAudioPortGeneration();
2972                            output = AUDIO_IO_HANDLE_NONE;
2973                        }
2974                    }
2975                }
2976            } else {
2977                output = AUDIO_IO_HANDLE_NONE;
2978            }
2979            if (output == AUDIO_IO_HANDLE_NONE) {
2980                ALOGW("checkOutputsForDevice() could not open output for device %x", device);
2981                profiles.removeAt(profile_index);
2982                profile_index--;
2983            } else {
2984                outputs.add(output);
2985                if (deviceDistinguishesOnAddress(device)) {
2986                    ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
2987                            device, address.string());
2988                    setOutputDevice(output, device, true/*force*/, 0/*delay*/,
2989                            NULL/*patch handle*/, address.string());
2990                }
2991                ALOGV("checkOutputsForDevice(): adding output %d", output);
2992            }
2993        }
2994
2995        if (profiles.isEmpty()) {
2996            ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2997            return BAD_VALUE;
2998        }
2999    } else { // Disconnect
3000        // check if one opened output is not needed any more after disconnecting one device
3001        for (size_t i = 0; i < mOutputs.size(); i++) {
3002            desc = mOutputs.valueAt(i);
3003            if (!desc->isDuplicated()) {
3004                if  (!(desc->mProfile->mSupportedDevices.types()
3005                        & mAvailableOutputDevices.types())) {
3006                    ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3007                            mOutputs.keyAt(i));
3008                    outputs.add(mOutputs.keyAt(i));
3009                } else if (deviceDistinguishesOnAddress(device) &&
3010                        // exact match on device
3011                        (desc->mProfile->mSupportedDevices.types() == device)) {
3012                    findIoHandlesByAddress(desc, address, outputs);
3013                }
3014            }
3015        }
3016        // Clear any profiles associated with the disconnected device.
3017        for (size_t i = 0; i < mHwModules.size(); i++)
3018        {
3019            if (mHwModules[i]->mHandle == 0) {
3020                continue;
3021            }
3022            for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3023            {
3024                sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
3025                if (profile->mSupportedDevices.types() & device) {
3026                    ALOGV("checkOutputsForDevice(): "
3027                            "clearing direct output profile %zu on module %zu", j, i);
3028                    if (profile->mSamplingRates[0] == 0) {
3029                        profile->mSamplingRates.clear();
3030                        profile->mSamplingRates.add(0);
3031                    }
3032                    if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3033                        profile->mFormats.clear();
3034                        profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3035                    }
3036                    if (profile->mChannelMasks[0] == 0) {
3037                        profile->mChannelMasks.clear();
3038                        profile->mChannelMasks.add(0);
3039                    }
3040                }
3041            }
3042        }
3043    }
3044    return NO_ERROR;
3045}
3046
3047status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3048                                                      audio_policy_dev_state_t state,
3049                                                      SortedVector<audio_io_handle_t>& inputs,
3050                                                      const String8 address)
3051{
3052    sp<AudioInputDescriptor> desc;
3053    if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3054        // first list already open inputs that can be routed to this device
3055        for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3056            desc = mInputs.valueAt(input_index);
3057            if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3058                ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3059               inputs.add(mInputs.keyAt(input_index));
3060            }
3061        }
3062
3063        // then look for input profiles that can be routed to this device
3064        SortedVector< sp<IOProfile> > profiles;
3065        for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3066        {
3067            if (mHwModules[module_idx]->mHandle == 0) {
3068                continue;
3069            }
3070            for (size_t profile_index = 0;
3071                 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3072                 profile_index++)
3073            {
3074                if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3075                        & (device & ~AUDIO_DEVICE_BIT_IN)) {
3076                    ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3077                          profile_index, module_idx);
3078                    profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3079                }
3080            }
3081        }
3082
3083        if (profiles.isEmpty() && inputs.isEmpty()) {
3084            ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3085            return BAD_VALUE;
3086        }
3087
3088        // open inputs for matching profiles if needed. Direct inputs are also opened to
3089        // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3090        for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3091
3092            sp<IOProfile> profile = profiles[profile_index];
3093            // nothing to do if one input is already opened for this profile
3094            size_t input_index;
3095            for (input_index = 0; input_index < mInputs.size(); input_index++) {
3096                desc = mInputs.valueAt(input_index);
3097                if (desc->mProfile == profile) {
3098                    break;
3099                }
3100            }
3101            if (input_index != mInputs.size()) {
3102                continue;
3103            }
3104
3105            ALOGV("opening input for device 0x%X with params %s", device, address.string());
3106            desc = new AudioInputDescriptor(profile);
3107            desc->mDevice = device;
3108            audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3109            config.sample_rate = desc->mSamplingRate;
3110            config.channel_mask = desc->mChannelMask;
3111            config.format = desc->mFormat;
3112            audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3113            status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3114                                                           &input,
3115                                                           &config,
3116                                                           &desc->mDevice,
3117                                                           address,
3118                                                           AUDIO_SOURCE_MIC,
3119                                                           AUDIO_INPUT_FLAG_NONE /*FIXME*/);
3120
3121            if (status == NO_ERROR) {
3122                desc->mSamplingRate = config.sample_rate;
3123                desc->mChannelMask = config.channel_mask;
3124                desc->mFormat = config.format;
3125
3126                if (!address.isEmpty()) {
3127                    char *param = audio_device_address_to_parameter(device, address);
3128                    mpClientInterface->setParameters(input, String8(param));
3129                    free(param);
3130                }
3131
3132                // Here is where we step through and resolve any "dynamic" fields
3133                String8 reply;
3134                char *value;
3135                if (profile->mSamplingRates[0] == 0) {
3136                    reply = mpClientInterface->getParameters(input,
3137                                            String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3138                    ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3139                              reply.string());
3140                    value = strpbrk((char *)reply.string(), "=");
3141                    if (value != NULL) {
3142                        profile->loadSamplingRates(value + 1);
3143                    }
3144                }
3145                if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3146                    reply = mpClientInterface->getParameters(input,
3147                                                   String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3148                    ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3149                    value = strpbrk((char *)reply.string(), "=");
3150                    if (value != NULL) {
3151                        profile->loadFormats(value + 1);
3152                    }
3153                }
3154                if (profile->mChannelMasks[0] == 0) {
3155                    reply = mpClientInterface->getParameters(input,
3156                                                  String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3157                    ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3158                              reply.string());
3159                    value = strpbrk((char *)reply.string(), "=");
3160                    if (value != NULL) {
3161                        profile->loadInChannels(value + 1);
3162                    }
3163                }
3164                if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3165                     ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3166                     ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3167                    ALOGW("checkInputsForDevice() direct input missing param");
3168                    mpClientInterface->closeInput(input);
3169                    input = AUDIO_IO_HANDLE_NONE;
3170                }
3171
3172                if (input != 0) {
3173                    addInput(input, desc);
3174                }
3175            } // endif input != 0
3176
3177            if (input == AUDIO_IO_HANDLE_NONE) {
3178                ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
3179                profiles.removeAt(profile_index);
3180                profile_index--;
3181            } else {
3182                inputs.add(input);
3183                ALOGV("checkInputsForDevice(): adding input %d", input);
3184            }
3185        } // end scan profiles
3186
3187        if (profiles.isEmpty()) {
3188            ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3189            return BAD_VALUE;
3190        }
3191    } else {
3192        // Disconnect
3193        // check if one opened input is not needed any more after disconnecting one device
3194        for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3195            desc = mInputs.valueAt(input_index);
3196            if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3197                ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3198                      mInputs.keyAt(input_index));
3199                inputs.add(mInputs.keyAt(input_index));
3200            }
3201        }
3202        // Clear any profiles associated with the disconnected device.
3203        for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3204            if (mHwModules[module_index]->mHandle == 0) {
3205                continue;
3206            }
3207            for (size_t profile_index = 0;
3208                 profile_index < mHwModules[module_index]->mInputProfiles.size();
3209                 profile_index++) {
3210                sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
3211                if (profile->mSupportedDevices.types() & device) {
3212                    ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
3213                          profile_index, module_index);
3214                    if (profile->mSamplingRates[0] == 0) {
3215                        profile->mSamplingRates.clear();
3216                        profile->mSamplingRates.add(0);
3217                    }
3218                    if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3219                        profile->mFormats.clear();
3220                        profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3221                    }
3222                    if (profile->mChannelMasks[0] == 0) {
3223                        profile->mChannelMasks.clear();
3224                        profile->mChannelMasks.add(0);
3225                    }
3226                }
3227            }
3228        }
3229    } // end disconnect
3230
3231    return NO_ERROR;
3232}
3233
3234
3235void AudioPolicyManager::closeOutput(audio_io_handle_t output)
3236{
3237    ALOGV("closeOutput(%d)", output);
3238
3239    sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3240    if (outputDesc == NULL) {
3241        ALOGW("closeOutput() unknown output %d", output);
3242        return;
3243    }
3244
3245    // look for duplicated outputs connected to the output being removed.
3246    for (size_t i = 0; i < mOutputs.size(); i++) {
3247        sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
3248        if (dupOutputDesc->isDuplicated() &&
3249                (dupOutputDesc->mOutput1 == outputDesc ||
3250                dupOutputDesc->mOutput2 == outputDesc)) {
3251            sp<AudioOutputDescriptor> outputDesc2;
3252            if (dupOutputDesc->mOutput1 == outputDesc) {
3253                outputDesc2 = dupOutputDesc->mOutput2;
3254            } else {
3255                outputDesc2 = dupOutputDesc->mOutput1;
3256            }
3257            // As all active tracks on duplicated output will be deleted,
3258            // and as they were also referenced on the other output, the reference
3259            // count for their stream type must be adjusted accordingly on
3260            // the other output.
3261            for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
3262                int refCount = dupOutputDesc->mRefCount[j];
3263                outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
3264            }
3265            audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3266            ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3267
3268            mpClientInterface->closeOutput(duplicatedOutput);
3269            mOutputs.removeItem(duplicatedOutput);
3270        }
3271    }
3272
3273    AudioParameter param;
3274    param.add(String8("closing"), String8("true"));
3275    mpClientInterface->setParameters(output, param.toString());
3276
3277    mpClientInterface->closeOutput(output);
3278    mOutputs.removeItem(output);
3279    mPreviousOutputs = mOutputs;
3280    nextAudioPortGeneration();
3281}
3282
3283SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
3284                        DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
3285{
3286    SortedVector<audio_io_handle_t> outputs;
3287
3288    ALOGVV("getOutputsForDevice() device %04x", device);
3289    for (size_t i = 0; i < openOutputs.size(); i++) {
3290        ALOGVV("output %d isDuplicated=%d device=%04x",
3291                i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3292        if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3293            ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3294            outputs.add(openOutputs.keyAt(i));
3295        }
3296    }
3297    return outputs;
3298}
3299
3300bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
3301                                   SortedVector<audio_io_handle_t>& outputs2)
3302{
3303    if (outputs1.size() != outputs2.size()) {
3304        return false;
3305    }
3306    for (size_t i = 0; i < outputs1.size(); i++) {
3307        if (outputs1[i] != outputs2[i]) {
3308            return false;
3309        }
3310    }
3311    return true;
3312}
3313
3314void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
3315{
3316    audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3317    audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3318    SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3319    SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3320
3321    if (!vectorsEqual(srcOutputs,dstOutputs)) {
3322        ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3323              strategy, srcOutputs[0], dstOutputs[0]);
3324        // mute strategy while moving tracks from one output to another
3325        for (size_t i = 0; i < srcOutputs.size(); i++) {
3326            sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
3327            if (desc->isStrategyActive(strategy)) {
3328                setStrategyMute(strategy, true, srcOutputs[i]);
3329                setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3330            }
3331        }
3332
3333        // Move effects associated to this strategy from previous output to new output
3334        if (strategy == STRATEGY_MEDIA) {
3335            audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3336            SortedVector<audio_io_handle_t> moved;
3337            for (size_t i = 0; i < mEffects.size(); i++) {
3338                sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3339                if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3340                        effectDesc->mIo != fxOutput) {
3341                    if (moved.indexOf(effectDesc->mIo) < 0) {
3342                        ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3343                              mEffects.keyAt(i), fxOutput);
3344                        mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
3345                                                       fxOutput);
3346                        moved.add(effectDesc->mIo);
3347                    }
3348                    effectDesc->mIo = fxOutput;
3349                }
3350            }
3351        }
3352        // Move tracks associated to this strategy from previous output to new output
3353        for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3354            if (getStrategy((audio_stream_type_t)i) == strategy) {
3355                mpClientInterface->invalidateStream((audio_stream_type_t)i);
3356            }
3357        }
3358    }
3359}
3360
3361void AudioPolicyManager::checkOutputForAllStrategies()
3362{
3363    checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3364    checkOutputForStrategy(STRATEGY_PHONE);
3365    checkOutputForStrategy(STRATEGY_SONIFICATION);
3366    checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3367    checkOutputForStrategy(STRATEGY_MEDIA);
3368    checkOutputForStrategy(STRATEGY_DTMF);
3369}
3370
3371audio_io_handle_t AudioPolicyManager::getA2dpOutput()
3372{
3373    for (size_t i = 0; i < mOutputs.size(); i++) {
3374        sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3375        if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3376            return mOutputs.keyAt(i);
3377        }
3378    }
3379
3380    return 0;
3381}
3382
3383void AudioPolicyManager::checkA2dpSuspend()
3384{
3385    audio_io_handle_t a2dpOutput = getA2dpOutput();
3386    if (a2dpOutput == 0) {
3387        mA2dpSuspended = false;
3388        return;
3389    }
3390
3391    bool isScoConnected =
3392            (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
3393    // suspend A2DP output if:
3394    //      (NOT already suspended) &&
3395    //      ((SCO device is connected &&
3396    //       (forced usage for communication || for record is SCO))) ||
3397    //      (phone state is ringing || in call)
3398    //
3399    // restore A2DP output if:
3400    //      (Already suspended) &&
3401    //      ((SCO device is NOT connected ||
3402    //       (forced usage NOT for communication && NOT for record is SCO))) &&
3403    //      (phone state is NOT ringing && NOT in call)
3404    //
3405    if (mA2dpSuspended) {
3406        if ((!isScoConnected ||
3407             ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3408              (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3409             ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3410              (mPhoneState != AUDIO_MODE_RINGTONE))) {
3411
3412            mpClientInterface->restoreOutput(a2dpOutput);
3413            mA2dpSuspended = false;
3414        }
3415    } else {
3416        if ((isScoConnected &&
3417             ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3418              (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3419             ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3420              (mPhoneState == AUDIO_MODE_RINGTONE))) {
3421
3422            mpClientInterface->suspendOutput(a2dpOutput);
3423            mA2dpSuspended = true;
3424        }
3425    }
3426}
3427
3428audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
3429{
3430    audio_devices_t device = AUDIO_DEVICE_NONE;
3431
3432    sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3433
3434    ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3435    if (index >= 0) {
3436        sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3437        if (patchDesc->mUid != mUidCached) {
3438            ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3439                  outputDesc->device(), outputDesc->mPatchHandle);
3440            return outputDesc->device();
3441        }
3442    }
3443
3444    // check the following by order of priority to request a routing change if necessary:
3445    // 1: the strategy enforced audible is active on the output:
3446    //      use device for strategy enforced audible
3447    // 2: we are in call or the strategy phone is active on the output:
3448    //      use device for strategy phone
3449    // 3: the strategy sonification is active on the output:
3450    //      use device for strategy sonification
3451    // 4: the strategy "respectful" sonification is active on the output:
3452    //      use device for strategy "respectful" sonification
3453    // 5: the strategy media is active on the output:
3454    //      use device for strategy media
3455    // 6: the strategy DTMF is active on the output:
3456    //      use device for strategy DTMF
3457    if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3458        device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3459    } else if (isInCall() ||
3460                    outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3461        device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3462    } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3463        device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3464    } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3465        device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3466    } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3467        device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3468    } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3469        device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3470    }
3471
3472    ALOGV("getNewOutputDevice() selected device %x", device);
3473    return device;
3474}
3475
3476audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3477{
3478    sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
3479
3480    ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3481    if (index >= 0) {
3482        sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3483        if (patchDesc->mUid != mUidCached) {
3484            ALOGV("getNewInputDevice() device %08x forced by patch %d",
3485                  inputDesc->mDevice, inputDesc->mPatchHandle);
3486            return inputDesc->mDevice;
3487        }
3488    }
3489
3490    audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3491
3492    ALOGV("getNewInputDevice() selected device %x", device);
3493    return device;
3494}
3495
3496uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
3497    return (uint32_t)getStrategy(stream);
3498}
3499
3500audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
3501    // By checking the range of stream before calling getStrategy, we avoid
3502    // getStrategy's behavior for invalid streams.  getStrategy would do a ALOGE
3503    // and then return STRATEGY_MEDIA, but we want to return the empty set.
3504    if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
3505        return AUDIO_DEVICE_NONE;
3506    }
3507    audio_devices_t devices;
3508    AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3509    devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3510    SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3511    for (size_t i = 0; i < outputs.size(); i++) {
3512        sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
3513        if (outputDesc->isStrategyActive(strategy)) {
3514            devices = outputDesc->device();
3515            break;
3516        }
3517    }
3518    return devices;
3519}
3520
3521AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
3522        audio_stream_type_t stream) {
3523    // stream to strategy mapping
3524    switch (stream) {
3525    case AUDIO_STREAM_VOICE_CALL:
3526    case AUDIO_STREAM_BLUETOOTH_SCO:
3527        return STRATEGY_PHONE;
3528    case AUDIO_STREAM_RING:
3529    case AUDIO_STREAM_ALARM:
3530        return STRATEGY_SONIFICATION;
3531    case AUDIO_STREAM_NOTIFICATION:
3532        return STRATEGY_SONIFICATION_RESPECTFUL;
3533    case AUDIO_STREAM_DTMF:
3534        return STRATEGY_DTMF;
3535    default:
3536        ALOGE("unknown stream type");
3537    case AUDIO_STREAM_SYSTEM:
3538        // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3539        // while key clicks are played produces a poor result
3540    case AUDIO_STREAM_TTS:
3541    case AUDIO_STREAM_MUSIC:
3542        return STRATEGY_MEDIA;
3543    case AUDIO_STREAM_ENFORCED_AUDIBLE:
3544        return STRATEGY_ENFORCED_AUDIBLE;
3545    }
3546}
3547
3548uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3549    // flags to strategy mapping
3550    if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3551        return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3552    }
3553
3554    // usage to strategy mapping
3555    switch (attr->usage) {
3556    case AUDIO_USAGE_MEDIA:
3557    case AUDIO_USAGE_GAME:
3558    case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3559    case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3560    case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3561        return (uint32_t) STRATEGY_MEDIA;
3562
3563    case AUDIO_USAGE_VOICE_COMMUNICATION:
3564        return (uint32_t) STRATEGY_PHONE;
3565
3566    case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3567        return (uint32_t) STRATEGY_DTMF;
3568
3569    case AUDIO_USAGE_ALARM:
3570    case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3571        return (uint32_t) STRATEGY_SONIFICATION;
3572
3573    case AUDIO_USAGE_NOTIFICATION:
3574    case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3575    case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3576    case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3577    case AUDIO_USAGE_NOTIFICATION_EVENT:
3578        return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3579
3580    case AUDIO_USAGE_UNKNOWN:
3581    default:
3582        return (uint32_t) STRATEGY_MEDIA;
3583    }
3584}
3585
3586void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
3587    switch(stream) {
3588    case AUDIO_STREAM_MUSIC:
3589        checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3590        updateDevicesAndOutputs();
3591        break;
3592    default:
3593        break;
3594    }
3595}
3596
3597audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
3598                                                             bool fromCache)
3599{
3600    uint32_t device = AUDIO_DEVICE_NONE;
3601
3602    if (fromCache) {
3603        ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3604              strategy, mDeviceForStrategy[strategy]);
3605        return mDeviceForStrategy[strategy];
3606    }
3607    audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
3608    switch (strategy) {
3609
3610    case STRATEGY_SONIFICATION_RESPECTFUL:
3611        if (isInCall()) {
3612            device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3613        } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
3614                SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3615            // while media is playing on a remote device, use the the sonification behavior.
3616            // Note that we test this usecase before testing if media is playing because
3617            //   the isStreamActive() method only informs about the activity of a stream, not
3618            //   if it's for local playback. Note also that we use the same delay between both tests
3619            device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3620        } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3621            // while media is playing (or has recently played), use the same device
3622            device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3623        } else {
3624            // when media is not playing anymore, fall back on the sonification behavior
3625            device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3626        }
3627
3628        break;
3629
3630    case STRATEGY_DTMF:
3631        if (!isInCall()) {
3632            // when off call, DTMF strategy follows the same rules as MEDIA strategy
3633            device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3634            break;
3635        }
3636        // when in call, DTMF and PHONE strategies follow the same rules
3637        // FALL THROUGH
3638
3639    case STRATEGY_PHONE:
3640        // for phone strategy, we first consider the forced use and then the available devices by order
3641        // of priority
3642        switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3643        case AUDIO_POLICY_FORCE_BT_SCO:
3644            if (!isInCall() || strategy != STRATEGY_DTMF) {
3645                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
3646                if (device) break;
3647            }
3648            device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
3649            if (device) break;
3650            device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
3651            if (device) break;
3652            // if SCO device is requested but no SCO device is available, fall back to default case
3653            // FALL THROUGH
3654
3655        default:    // FORCE_NONE
3656            // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
3657            if (!isInCall() &&
3658                    (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
3659                    (getA2dpOutput() != 0) && !mA2dpSuspended) {
3660                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
3661                if (device) break;
3662                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
3663                if (device) break;
3664            }
3665            device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
3666            if (device) break;
3667            device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
3668            if (device) break;
3669            if (mPhoneState != AUDIO_MODE_IN_CALL) {
3670                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
3671                if (device) break;
3672                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
3673                if (device) break;
3674                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
3675                if (device) break;
3676                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
3677                if (device) break;
3678                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
3679                if (device) break;
3680            }
3681            device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
3682            if (device) break;
3683            device = mDefaultOutputDevice->mDeviceType;
3684            if (device == AUDIO_DEVICE_NONE) {
3685                ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3686            }
3687            break;
3688
3689        case AUDIO_POLICY_FORCE_SPEAKER:
3690            // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3691            // A2DP speaker when forcing to speaker output
3692            if (!isInCall() &&
3693                    (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
3694                    (getA2dpOutput() != 0) && !mA2dpSuspended) {
3695                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
3696                if (device) break;
3697            }
3698            if (mPhoneState != AUDIO_MODE_IN_CALL) {
3699                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
3700                if (device) break;
3701                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
3702                if (device) break;
3703                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
3704                if (device) break;
3705                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
3706                if (device) break;
3707                device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
3708                if (device) break;
3709            }
3710            device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
3711            if (device) break;
3712            device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
3713            if (device) break;
3714            device = mDefaultOutputDevice->mDeviceType;
3715            if (device == AUDIO_DEVICE_NONE) {
3716                ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3717            }
3718            break;
3719        }
3720    break;
3721
3722    case STRATEGY_SONIFICATION:
3723
3724        // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3725        // handleIncallSonification().
3726        if (isInCall()) {
3727            device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3728            break;
3729        }
3730        // FALL THROUGH
3731
3732    case STRATEGY_ENFORCED_AUDIBLE:
3733        // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3734        // except:
3735        //   - when in call where it doesn't default to STRATEGY_PHONE behavior
3736        //   - in countries where not enforced in which case it follows STRATEGY_MEDIA
3737
3738        if ((strategy == STRATEGY_SONIFICATION) ||
3739                (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
3740            device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
3741            if (device == AUDIO_DEVICE_NONE) {
3742                ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3743            }
3744        }
3745        // The second device used for sonification is the same as the device used by media strategy
3746        // FALL THROUGH
3747
3748    case STRATEGY_MEDIA: {
3749        uint32_t device2 = AUDIO_DEVICE_NONE;
3750        if (strategy != STRATEGY_SONIFICATION) {
3751            // no sonification on remote submix (e.g. WFD)
3752            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
3753        }
3754        if ((device2 == AUDIO_DEVICE_NONE) &&
3755                (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
3756                (getA2dpOutput() != 0) && !mA2dpSuspended) {
3757            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
3758            if (device2 == AUDIO_DEVICE_NONE) {
3759                device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
3760            }
3761            if (device2 == AUDIO_DEVICE_NONE) {
3762                device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
3763            }
3764        }
3765        if (device2 == AUDIO_DEVICE_NONE) {
3766            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
3767        }
3768        if ((device2 == AUDIO_DEVICE_NONE)) {
3769            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
3770        }
3771        if (device2 == AUDIO_DEVICE_NONE) {
3772            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
3773        }
3774        if (device2 == AUDIO_DEVICE_NONE) {
3775            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
3776        }
3777        if (device2 == AUDIO_DEVICE_NONE) {
3778            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
3779        }
3780        if (device2 == AUDIO_DEVICE_NONE) {
3781            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
3782        }
3783        if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3784            // no sonification on aux digital (e.g. HDMI)
3785            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
3786        }
3787        if ((device2 == AUDIO_DEVICE_NONE) &&
3788                (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
3789            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
3790        }
3791        if (device2 == AUDIO_DEVICE_NONE) {
3792            device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
3793        }
3794        int device3 = AUDIO_DEVICE_NONE;
3795        if (strategy == STRATEGY_MEDIA) {
3796            // ARC, SPDIF and AUX_LINE can co-exist with others.
3797            device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
3798            device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
3799            device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
3800        }
3801
3802        device2 |= device3;
3803        // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3804        // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3805        device |= device2;
3806
3807        // If hdmi system audio mode is on, remove speaker out of output list.
3808        if ((strategy == STRATEGY_MEDIA) &&
3809            (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
3810                AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
3811            device &= ~AUDIO_DEVICE_OUT_SPEAKER;
3812        }
3813
3814        if (device) break;
3815        device = mDefaultOutputDevice->mDeviceType;
3816        if (device == AUDIO_DEVICE_NONE) {
3817            ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3818        }
3819        } break;
3820
3821    default:
3822        ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3823        break;
3824    }
3825
3826    ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3827    return device;
3828}
3829
3830void AudioPolicyManager::updateDevicesAndOutputs()
3831{
3832    for (int i = 0; i < NUM_STRATEGIES; i++) {
3833        mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3834    }
3835    mPreviousOutputs = mOutputs;
3836}
3837
3838uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
3839                                                       audio_devices_t prevDevice,
3840                                                       uint32_t delayMs)
3841{
3842    // mute/unmute strategies using an incompatible device combination
3843    // if muting, wait for the audio in pcm buffer to be drained before proceeding
3844    // if unmuting, unmute only after the specified delay
3845    if (outputDesc->isDuplicated()) {
3846        return 0;
3847    }
3848
3849    uint32_t muteWaitMs = 0;
3850    audio_devices_t device = outputDesc->device();
3851    bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
3852
3853    for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3854        audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3855        bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3856        bool doMute = false;
3857
3858        if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3859            doMute = true;
3860            outputDesc->mStrategyMutedByDevice[i] = true;
3861        } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3862            doMute = true;
3863            outputDesc->mStrategyMutedByDevice[i] = false;
3864        }
3865        if (doMute) {
3866            for (size_t j = 0; j < mOutputs.size(); j++) {
3867                sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
3868                // skip output if it does not share any device with current output
3869                if ((desc->supportedDevices() & outputDesc->supportedDevices())
3870                        == AUDIO_DEVICE_NONE) {
3871                    continue;
3872                }
3873                audio_io_handle_t curOutput = mOutputs.keyAt(j);
3874                ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3875                      mute ? "muting" : "unmuting", i, curDevice, curOutput);
3876                setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3877                if (desc->isStrategyActive((routing_strategy)i)) {
3878                    if (mute) {
3879                        // FIXME: should not need to double latency if volume could be applied
3880                        // immediately by the audioflinger mixer. We must account for the delay
3881                        // between now and the next time the audioflinger thread for this output
3882                        // will process a buffer (which corresponds to one buffer size,
3883                        // usually 1/2 or 1/4 of the latency).
3884                        if (muteWaitMs < desc->latency() * 2) {
3885                            muteWaitMs = desc->latency() * 2;
3886                        }
3887                    }
3888                }
3889            }
3890        }
3891    }
3892
3893    // temporary mute output if device selection changes to avoid volume bursts due to
3894    // different per device volumes
3895    if (outputDesc->isActive() && (device != prevDevice)) {
3896        if (muteWaitMs < outputDesc->latency() * 2) {
3897            muteWaitMs = outputDesc->latency() * 2;
3898        }
3899        for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3900            if (outputDesc->isStrategyActive((routing_strategy)i)) {
3901                setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
3902                // do tempMute unmute after twice the mute wait time
3903                setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
3904                                muteWaitMs *2, device);
3905            }
3906        }
3907    }
3908
3909    // wait for the PCM output buffers to empty before proceeding with the rest of the command
3910    if (muteWaitMs > delayMs) {
3911        muteWaitMs -= delayMs;
3912        usleep(muteWaitMs * 1000);
3913        return muteWaitMs;
3914    }
3915    return 0;
3916}
3917
3918uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
3919                                             audio_devices_t device,
3920                                             bool force,
3921                                             int delayMs,
3922                                             audio_patch_handle_t *patchHandle,
3923                                             const char* address)
3924{
3925    ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
3926    sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
3927    AudioParameter param;
3928    uint32_t muteWaitMs;
3929
3930    if (outputDesc->isDuplicated()) {
3931        muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3932        muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
3933        return muteWaitMs;
3934    }
3935    // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3936    // output profile
3937    if ((device != AUDIO_DEVICE_NONE) &&
3938            ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
3939        return 0;
3940    }
3941
3942    // filter devices according to output selected
3943    device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
3944
3945    audio_devices_t prevDevice = outputDesc->mDevice;
3946
3947    ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3948
3949    if (device != AUDIO_DEVICE_NONE) {
3950        outputDesc->mDevice = device;
3951    }
3952    muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3953
3954    // Do not change the routing if:
3955    //  - the requested device is AUDIO_DEVICE_NONE
3956    //  - the requested device is the same as current device and force is not specified.
3957    // Doing this check here allows the caller to call setOutputDevice() without conditions
3958    if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3959        ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3960        return muteWaitMs;
3961    }
3962
3963    ALOGV("setOutputDevice() changing device");
3964
3965    // do the routing
3966    if (device == AUDIO_DEVICE_NONE) {
3967        resetOutputDevice(output, delayMs, NULL);
3968    } else {
3969        DeviceVector deviceList = (address == NULL) ?
3970                mAvailableOutputDevices.getDevicesFromType(device)
3971                : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
3972        if (!deviceList.isEmpty()) {
3973            struct audio_patch patch;
3974            outputDesc->toAudioPortConfig(&patch.sources[0]);
3975            patch.num_sources = 1;
3976            patch.num_sinks = 0;
3977            for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3978                deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
3979                patch.num_sinks++;
3980            }
3981            ssize_t index;
3982            if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3983                index = mAudioPatches.indexOfKey(*patchHandle);
3984            } else {
3985                index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3986            }
3987            sp< AudioPatch> patchDesc;
3988            audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3989            if (index >= 0) {
3990                patchDesc = mAudioPatches.valueAt(index);
3991                afPatchHandle = patchDesc->mAfPatchHandle;
3992            }
3993
3994            status_t status = mpClientInterface->createAudioPatch(&patch,
3995                                                                   &afPatchHandle,
3996                                                                   delayMs);
3997            ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3998                    "num_sources %d num_sinks %d",
3999                                       status, afPatchHandle, patch.num_sources, patch.num_sinks);
4000            if (status == NO_ERROR) {
4001                if (index < 0) {
4002                    patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4003                                               &patch, mUidCached);
4004                    addAudioPatch(patchDesc->mHandle, patchDesc);
4005                } else {
4006                    patchDesc->mPatch = patch;
4007                }
4008                patchDesc->mAfPatchHandle = afPatchHandle;
4009                patchDesc->mUid = mUidCached;
4010                if (patchHandle) {
4011                    *patchHandle = patchDesc->mHandle;
4012                }
4013                outputDesc->mPatchHandle = patchDesc->mHandle;
4014                nextAudioPortGeneration();
4015                mpClientInterface->onAudioPatchListUpdate();
4016            }
4017        }
4018    }
4019
4020    // update stream volumes according to new device
4021    applyStreamVolumes(output, device, delayMs);
4022
4023    return muteWaitMs;
4024}
4025
4026status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
4027                                               int delayMs,
4028                                               audio_patch_handle_t *patchHandle)
4029{
4030    sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
4031    ssize_t index;
4032    if (patchHandle) {
4033        index = mAudioPatches.indexOfKey(*patchHandle);
4034    } else {
4035        index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4036    }
4037    if (index < 0) {
4038        return INVALID_OPERATION;
4039    }
4040    sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4041    status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
4042    ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
4043    outputDesc->mPatchHandle = 0;
4044    removeAudioPatch(patchDesc->mHandle);
4045    nextAudioPortGeneration();
4046    mpClientInterface->onAudioPatchListUpdate();
4047    return status;
4048}
4049
4050status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
4051                                            audio_devices_t device,
4052                                            bool force,
4053                                            audio_patch_handle_t *patchHandle)
4054{
4055    status_t status = NO_ERROR;
4056
4057    sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4058    if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4059        inputDesc->mDevice = device;
4060
4061        DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4062        if (!deviceList.isEmpty()) {
4063            struct audio_patch patch;
4064            inputDesc->toAudioPortConfig(&patch.sinks[0]);
4065            // AUDIO_SOURCE_HOTWORD is for internal use only:
4066            // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
4067            if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
4068                    !inputDesc->mIsSoundTrigger) {
4069                patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4070            }
4071            patch.num_sinks = 1;
4072            //only one input device for now
4073            deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
4074            patch.num_sources = 1;
4075            ssize_t index;
4076            if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4077                index = mAudioPatches.indexOfKey(*patchHandle);
4078            } else {
4079                index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4080            }
4081            sp< AudioPatch> patchDesc;
4082            audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4083            if (index >= 0) {
4084                patchDesc = mAudioPatches.valueAt(index);
4085                afPatchHandle = patchDesc->mAfPatchHandle;
4086            }
4087
4088            status_t status = mpClientInterface->createAudioPatch(&patch,
4089                                                                  &afPatchHandle,
4090                                                                  0);
4091            ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
4092                                                                          status, afPatchHandle);
4093            if (status == NO_ERROR) {
4094                if (index < 0) {
4095                    patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4096                                               &patch, mUidCached);
4097                    addAudioPatch(patchDesc->mHandle, patchDesc);
4098                } else {
4099                    patchDesc->mPatch = patch;
4100                }
4101                patchDesc->mAfPatchHandle = afPatchHandle;
4102                patchDesc->mUid = mUidCached;
4103                if (patchHandle) {
4104                    *patchHandle = patchDesc->mHandle;
4105                }
4106                inputDesc->mPatchHandle = patchDesc->mHandle;
4107                nextAudioPortGeneration();
4108                mpClientInterface->onAudioPatchListUpdate();
4109            }
4110        }
4111    }
4112    return status;
4113}
4114
4115status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4116                                              audio_patch_handle_t *patchHandle)
4117{
4118    sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4119    ssize_t index;
4120    if (patchHandle) {
4121        index = mAudioPatches.indexOfKey(*patchHandle);
4122    } else {
4123        index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4124    }
4125    if (index < 0) {
4126        return INVALID_OPERATION;
4127    }
4128    sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4129    status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4130    ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4131    inputDesc->mPatchHandle = 0;
4132    removeAudioPatch(patchDesc->mHandle);
4133    nextAudioPortGeneration();
4134    mpClientInterface->onAudioPatchListUpdate();
4135    return status;
4136}
4137
4138sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
4139                                                   uint32_t& samplingRate,
4140                                                   audio_format_t format,
4141                                                   audio_channel_mask_t channelMask,
4142                                                   audio_input_flags_t flags)
4143{
4144    // Choose an input profile based on the requested capture parameters: select the first available
4145    // profile supporting all requested parameters.
4146
4147    for (size_t i = 0; i < mHwModules.size(); i++)
4148    {
4149        if (mHwModules[i]->mHandle == 0) {
4150            continue;
4151        }
4152        for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4153        {
4154            sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
4155            // profile->log();
4156            if (profile->isCompatibleProfile(device, samplingRate,
4157                                             &samplingRate /*updatedSamplingRate*/,
4158                                             format, channelMask, (audio_output_flags_t) flags)) {
4159                return profile;
4160            }
4161        }
4162    }
4163    return NULL;
4164}
4165
4166audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
4167{
4168    uint32_t device = AUDIO_DEVICE_NONE;
4169    audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4170                                            ~AUDIO_DEVICE_BIT_IN;
4171    switch (inputSource) {
4172    case AUDIO_SOURCE_VOICE_UPLINK:
4173      if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
4174          device = AUDIO_DEVICE_IN_VOICE_CALL;
4175          break;
4176      }
4177      // FALL THROUGH
4178
4179    case AUDIO_SOURCE_DEFAULT:
4180    case AUDIO_SOURCE_MIC:
4181    if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4182        device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
4183        break;
4184    }
4185    // FALL THROUGH
4186
4187    case AUDIO_SOURCE_VOICE_RECOGNITION:
4188    case AUDIO_SOURCE_HOTWORD:
4189    case AUDIO_SOURCE_VOICE_COMMUNICATION:
4190        if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
4191                availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
4192            device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
4193        } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
4194            device = AUDIO_DEVICE_IN_WIRED_HEADSET;
4195        } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4196            device = AUDIO_DEVICE_IN_USB_DEVICE;
4197        } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4198            device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4199        }
4200        break;
4201    case AUDIO_SOURCE_CAMCORDER:
4202        if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
4203            device = AUDIO_DEVICE_IN_BACK_MIC;
4204        } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
4205            device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4206        }
4207        break;
4208    case AUDIO_SOURCE_VOICE_DOWNLINK:
4209    case AUDIO_SOURCE_VOICE_CALL:
4210        if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
4211            device = AUDIO_DEVICE_IN_VOICE_CALL;
4212        }
4213        break;
4214    case AUDIO_SOURCE_REMOTE_SUBMIX:
4215        if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
4216            device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4217        }
4218        break;
4219    default:
4220        ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4221        break;
4222    }
4223    ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4224    return device;
4225}
4226
4227bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
4228{
4229    if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4230        device &= ~AUDIO_DEVICE_BIT_IN;
4231        if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4232            return true;
4233    }
4234    return false;
4235}
4236
4237bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4238    return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4239}
4240
4241audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
4242{
4243    for (size_t i = 0; i < mInputs.size(); i++) {
4244        const sp<AudioInputDescriptor>  input_descriptor = mInputs.valueAt(i);
4245        if ((input_descriptor->mRefCount > 0)
4246                && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4247            return mInputs.keyAt(i);
4248        }
4249    }
4250    return 0;
4251}
4252
4253uint32_t AudioPolicyManager::activeInputsCount() const
4254{
4255    uint32_t count = 0;
4256    for (size_t i = 0; i < mInputs.size(); i++) {
4257        const sp<AudioInputDescriptor>  desc = mInputs.valueAt(i);
4258        if (desc->mRefCount > 0) {
4259            return count++;
4260        }
4261    }
4262    return count;
4263}
4264
4265
4266audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
4267{
4268    if (device == AUDIO_DEVICE_NONE) {
4269        // this happens when forcing a route update and no track is active on an output.
4270        // In this case the returned category is not important.
4271        device =  AUDIO_DEVICE_OUT_SPEAKER;
4272    } else if (popcount(device) > 1) {
4273        // Multiple device selection is either:
4274        //  - speaker + one other device: give priority to speaker in this case.
4275        //  - one A2DP device + another device: happens with duplicated output. In this case
4276        // retain the device on the A2DP output as the other must not correspond to an active
4277        // selection if not the speaker.
4278        if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4279            device = AUDIO_DEVICE_OUT_SPEAKER;
4280        } else {
4281            device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4282        }
4283    }
4284
4285    ALOGW_IF(popcount(device) != 1,
4286            "getDeviceForVolume() invalid device combination: %08x",
4287            device);
4288
4289    return device;
4290}
4291
4292AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
4293{
4294    switch(getDeviceForVolume(device)) {
4295        case AUDIO_DEVICE_OUT_EARPIECE:
4296            return DEVICE_CATEGORY_EARPIECE;
4297        case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4298        case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4299        case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4300        case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4301        case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4302        case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4303            return DEVICE_CATEGORY_HEADSET;
4304        case AUDIO_DEVICE_OUT_LINE:
4305        case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4306        /*USB?  Remote submix?*/
4307            return DEVICE_CATEGORY_EXT_MEDIA;
4308        case AUDIO_DEVICE_OUT_SPEAKER:
4309        case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4310        case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
4311        case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4312        case AUDIO_DEVICE_OUT_USB_DEVICE:
4313        case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4314        default:
4315            return DEVICE_CATEGORY_SPEAKER;
4316    }
4317}
4318
4319float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
4320        int indexInUi)
4321{
4322    device_category deviceCategory = getDeviceCategory(device);
4323    const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4324
4325    // the volume index in the UI is relative to the min and max volume indices for this stream type
4326    int nbSteps = 1 + curve[VOLMAX].mIndex -
4327            curve[VOLMIN].mIndex;
4328    int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4329            (streamDesc.mIndexMax - streamDesc.mIndexMin);
4330
4331    // find what part of the curve this index volume belongs to, or if it's out of bounds
4332    int segment = 0;
4333    if (volIdx < curve[VOLMIN].mIndex) {         // out of bounds
4334        return 0.0f;
4335    } else if (volIdx < curve[VOLKNEE1].mIndex) {
4336        segment = 0;
4337    } else if (volIdx < curve[VOLKNEE2].mIndex) {
4338        segment = 1;
4339    } else if (volIdx <= curve[VOLMAX].mIndex) {
4340        segment = 2;
4341    } else {                                                               // out of bounds
4342        return 1.0f;
4343    }
4344
4345    // linear interpolation in the attenuation table in dB
4346    float decibels = curve[segment].mDBAttenuation +
4347            ((float)(volIdx - curve[segment].mIndex)) *
4348                ( (curve[segment+1].mDBAttenuation -
4349                        curve[segment].mDBAttenuation) /
4350                    ((float)(curve[segment+1].mIndex -
4351                            curve[segment].mIndex)) );
4352
4353    float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4354
4355    ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4356            curve[segment].mIndex, volIdx,
4357            curve[segment+1].mIndex,
4358            curve[segment].mDBAttenuation,
4359            decibels,
4360            curve[segment+1].mDBAttenuation,
4361            amplification);
4362
4363    return amplification;
4364}
4365
4366const AudioPolicyManager::VolumeCurvePoint
4367    AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
4368    {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4369};
4370
4371const AudioPolicyManager::VolumeCurvePoint
4372    AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
4373    {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4374};
4375
4376const AudioPolicyManager::VolumeCurvePoint
4377    AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4378    {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
4379};
4380
4381const AudioPolicyManager::VolumeCurvePoint
4382    AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
4383    {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4384};
4385
4386const AudioPolicyManager::VolumeCurvePoint
4387    AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
4388    {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
4389};
4390
4391const AudioPolicyManager::VolumeCurvePoint
4392    AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
4393    {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4394};
4395
4396const AudioPolicyManager::VolumeCurvePoint
4397    AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
4398    {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4399};
4400
4401// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4402// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4403// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4404// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4405
4406const AudioPolicyManager::VolumeCurvePoint
4407    AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4408    {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4409};
4410
4411const AudioPolicyManager::VolumeCurvePoint
4412    AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
4413    {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4414};
4415
4416const AudioPolicyManager::VolumeCurvePoint
4417    AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
4418    {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4419};
4420
4421const AudioPolicyManager::VolumeCurvePoint
4422    AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
4423    {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4424};
4425
4426const AudioPolicyManager::VolumeCurvePoint
4427    AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
4428    {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4429};
4430
4431const AudioPolicyManager::VolumeCurvePoint
4432            *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4433                                                   [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
4434    { // AUDIO_STREAM_VOICE_CALL
4435        sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4436        sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4437        sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4438        sDefaultMediaVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
4439    },
4440    { // AUDIO_STREAM_SYSTEM
4441        sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4442        sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4443        sDefaultSystemVolumeCurve,  // DEVICE_CATEGORY_EARPIECE
4444        sExtMediaSystemVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
4445    },
4446    { // AUDIO_STREAM_RING
4447        sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4448        sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4449        sDefaultVolumeCurve,  // DEVICE_CATEGORY_EARPIECE
4450        sExtMediaSystemVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
4451    },
4452    { // AUDIO_STREAM_MUSIC
4453        sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4454        sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4455        sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4456        sDefaultMediaVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
4457    },
4458    { // AUDIO_STREAM_ALARM
4459        sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4460        sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4461        sDefaultVolumeCurve,  // DEVICE_CATEGORY_EARPIECE
4462        sExtMediaSystemVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
4463    },
4464    { // AUDIO_STREAM_NOTIFICATION
4465        sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4466        sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4467        sDefaultVolumeCurve,  // DEVICE_CATEGORY_EARPIECE
4468        sExtMediaSystemVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
4469    },
4470    { // AUDIO_STREAM_BLUETOOTH_SCO
4471        sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4472        sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4473        sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4474        sDefaultMediaVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
4475    },
4476    { // AUDIO_STREAM_ENFORCED_AUDIBLE
4477        sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4478        sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4479        sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4480        sExtMediaSystemVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
4481    },
4482    {  // AUDIO_STREAM_DTMF
4483        sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4484        sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4485        sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4486        sExtMediaSystemVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
4487    },
4488    { // AUDIO_STREAM_TTS
4489        sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4490        sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4491        sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
4492        sDefaultMediaVolumeCurve  // DEVICE_CATEGORY_EXT_MEDIA
4493    },
4494};
4495
4496void AudioPolicyManager::initializeVolumeCurves()
4497{
4498    for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4499        for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4500            mStreams[i].mVolumeCurve[j] =
4501                    sVolumeProfiles[i][j];
4502        }
4503    }
4504
4505    // Check availability of DRC on speaker path: if available, override some of the speaker curves
4506    if (mSpeakerDrcEnabled) {
4507        mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4508                sDefaultSystemVolumeCurveDrc;
4509        mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4510                sSpeakerSonificationVolumeCurveDrc;
4511        mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4512                sSpeakerSonificationVolumeCurveDrc;
4513        mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4514                sSpeakerSonificationVolumeCurveDrc;
4515        mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4516                sSpeakerMediaVolumeCurveDrc;
4517    }
4518}
4519
4520float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
4521                                            int index,
4522                                            audio_io_handle_t output,
4523                                            audio_devices_t device)
4524{
4525    float volume = 1.0;
4526    sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
4527    StreamDescriptor &streamDesc = mStreams[stream];
4528
4529    if (device == AUDIO_DEVICE_NONE) {
4530        device = outputDesc->device();
4531    }
4532
4533    volume = volIndexToAmpl(device, streamDesc, index);
4534
4535    // if a headset is connected, apply the following rules to ring tones and notifications
4536    // to avoid sound level bursts in user's ears:
4537    // - always attenuate ring tones and notifications volume by 6dB
4538    // - if music is playing, always limit the volume to current music volume,
4539    // with a minimum threshold at -36dB so that notification is always perceived.
4540    const routing_strategy stream_strategy = getStrategy(stream);
4541    if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4542            AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4543            AUDIO_DEVICE_OUT_WIRED_HEADSET |
4544            AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4545        ((stream_strategy == STRATEGY_SONIFICATION)
4546                || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
4547                || (stream == AUDIO_STREAM_SYSTEM)
4548                || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
4549                    (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
4550        streamDesc.mCanBeMuted) {
4551        volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4552        // when the phone is ringing we must consider that music could have been paused just before
4553        // by the music application and behave as if music was active if the last music track was
4554        // just stopped
4555        if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
4556                mLimitRingtoneVolume) {
4557            audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
4558            float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4559                               mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
4560                               output,
4561                               musicDevice);
4562            float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4563                                musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4564            if (volume > minVol) {
4565                volume = minVol;
4566                ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4567            }
4568        }
4569    }
4570
4571    return volume;
4572}
4573
4574status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
4575                                                   int index,
4576                                                   audio_io_handle_t output,
4577                                                   audio_devices_t device,
4578                                                   int delayMs,
4579                                                   bool force)
4580{
4581
4582    // do not change actual stream volume if the stream is muted
4583    if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4584        ALOGVV("checkAndSetVolume() stream %d muted count %d",
4585              stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4586        return NO_ERROR;
4587    }
4588
4589    // do not change in call volume if bluetooth is connected and vice versa
4590    if ((stream == AUDIO_STREAM_VOICE_CALL &&
4591            mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4592        (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4593                mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
4594        ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
4595             stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
4596        return INVALID_OPERATION;
4597    }
4598
4599    float volume = computeVolume(stream, index, output, device);
4600    // We actually change the volume if:
4601    // - the float value returned by computeVolume() changed
4602    // - the force flag is set
4603    if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4604            force) {
4605        mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4606        ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4607        // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4608        // enabled
4609        if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4610            mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
4611        }
4612        mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
4613    }
4614
4615    if (stream == AUDIO_STREAM_VOICE_CALL ||
4616        stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4617        float voiceVolume;
4618        // Force voice volume to max for bluetooth SCO as volume is managed by the headset
4619        if (stream == AUDIO_STREAM_VOICE_CALL) {
4620            voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4621        } else {
4622            voiceVolume = 1.0;
4623        }
4624
4625        if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4626            mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4627            mLastVoiceVolume = voiceVolume;
4628        }
4629    }
4630
4631    return NO_ERROR;
4632}
4633
4634void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
4635                                                audio_devices_t device,
4636                                                int delayMs,
4637                                                bool force)
4638{
4639    ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4640
4641    for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4642        checkAndSetVolume((audio_stream_type_t)stream,
4643                          mStreams[stream].getVolumeIndex(device),
4644                          output,
4645                          device,
4646                          delayMs,
4647                          force);
4648    }
4649}
4650
4651void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
4652                                             bool on,
4653                                             audio_io_handle_t output,
4654                                             int delayMs,
4655                                             audio_devices_t device)
4656{
4657    ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
4658    for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4659        if (getStrategy((audio_stream_type_t)stream) == strategy) {
4660            setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
4661        }
4662    }
4663}
4664
4665void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
4666                                           bool on,
4667                                           audio_io_handle_t output,
4668                                           int delayMs,
4669                                           audio_devices_t device)
4670{
4671    StreamDescriptor &streamDesc = mStreams[stream];
4672    sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
4673    if (device == AUDIO_DEVICE_NONE) {
4674        device = outputDesc->device();
4675    }
4676
4677    ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4678          stream, on, output, outputDesc->mMuteCount[stream], device);
4679
4680    if (on) {
4681        if (outputDesc->mMuteCount[stream] == 0) {
4682            if (streamDesc.mCanBeMuted &&
4683                    ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4684                     (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
4685                checkAndSetVolume(stream, 0, output, device, delayMs);
4686            }
4687        }
4688        // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4689        outputDesc->mMuteCount[stream]++;
4690    } else {
4691        if (outputDesc->mMuteCount[stream] == 0) {
4692            ALOGV("setStreamMute() unmuting non muted stream!");
4693            return;
4694        }
4695        if (--outputDesc->mMuteCount[stream] == 0) {
4696            checkAndSetVolume(stream,
4697                              streamDesc.getVolumeIndex(device),
4698                              output,
4699                              device,
4700                              delayMs);
4701        }
4702    }
4703}
4704
4705void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
4706                                                      bool starting, bool stateChange)
4707{
4708    // if the stream pertains to sonification strategy and we are in call we must
4709    // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4710    // in the device used for phone strategy and play the tone if the selected device does not
4711    // interfere with the device used for phone strategy
4712    // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4713    // many times as there are active tracks on the output
4714    const routing_strategy stream_strategy = getStrategy(stream);
4715    if ((stream_strategy == STRATEGY_SONIFICATION) ||
4716            ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
4717        sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
4718        ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4719                stream, starting, outputDesc->mDevice, stateChange);
4720        if (outputDesc->mRefCount[stream]) {
4721            int muteCount = 1;
4722            if (stateChange) {
4723                muteCount = outputDesc->mRefCount[stream];
4724            }
4725            if (audio_is_low_visibility(stream)) {
4726                ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4727                for (int i = 0; i < muteCount; i++) {
4728                    setStreamMute(stream, starting, mPrimaryOutput);
4729                }
4730            } else {
4731                ALOGV("handleIncallSonification() high visibility");
4732                if (outputDesc->device() &
4733                        getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4734                    ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4735                    for (int i = 0; i < muteCount; i++) {
4736                        setStreamMute(stream, starting, mPrimaryOutput);
4737                    }
4738                }
4739                if (starting) {
4740                    mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4741                                                 AUDIO_STREAM_VOICE_CALL);
4742                } else {
4743                    mpClientInterface->stopTone();
4744                }
4745            }
4746        }
4747    }
4748}
4749
4750bool AudioPolicyManager::isInCall()
4751{
4752    return isStateInCall(mPhoneState);
4753}
4754
4755bool AudioPolicyManager::isStateInCall(int state) {
4756    return ((state == AUDIO_MODE_IN_CALL) ||
4757            (state == AUDIO_MODE_IN_COMMUNICATION));
4758}
4759
4760uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
4761{
4762    return MAX_EFFECTS_CPU_LOAD;
4763}
4764
4765uint32_t AudioPolicyManager::getMaxEffectsMemory()
4766{
4767    return MAX_EFFECTS_MEMORY;
4768}
4769
4770
4771// --- AudioOutputDescriptor class implementation
4772
4773AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
4774        const sp<IOProfile>& profile)
4775    : mId(0), mIoHandle(0), mLatency(0),
4776    mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
4777    mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4778{
4779    // clear usage count for all stream types
4780    for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4781        mRefCount[i] = 0;
4782        mCurVolume[i] = -1.0;
4783        mMuteCount[i] = 0;
4784        mStopTime[i] = 0;
4785    }
4786    for (int i = 0; i < NUM_STRATEGIES; i++) {
4787        mStrategyMutedByDevice[i] = false;
4788    }
4789    if (profile != NULL) {
4790        mAudioPort = profile;
4791        mFlags = profile->mFlags;
4792        mSamplingRate = profile->pickSamplingRate();
4793        mFormat = profile->pickFormat();
4794        mChannelMask = profile->pickChannelMask();
4795        if (profile->mGains.size() > 0) {
4796            profile->mGains[0]->getDefaultConfig(&mGain);
4797        }
4798    }
4799}
4800
4801audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
4802{
4803    if (isDuplicated()) {
4804        return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4805    } else {
4806        return mDevice;
4807    }
4808}
4809
4810uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
4811{
4812    if (isDuplicated()) {
4813        return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4814    } else {
4815        return mLatency;
4816    }
4817}
4818
4819bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
4820        const sp<AudioOutputDescriptor> outputDesc)
4821{
4822    if (isDuplicated()) {
4823        return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4824    } else if (outputDesc->isDuplicated()){
4825        return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4826    } else {
4827        return (mProfile->mModule == outputDesc->mProfile->mModule);
4828    }
4829}
4830
4831void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
4832                                                                   int delta)
4833{
4834    // forward usage count change to attached outputs
4835    if (isDuplicated()) {
4836        mOutput1->changeRefCount(stream, delta);
4837        mOutput2->changeRefCount(stream, delta);
4838    }
4839    if ((delta + (int)mRefCount[stream]) < 0) {
4840        ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4841              delta, stream, mRefCount[stream]);
4842        mRefCount[stream] = 0;
4843        return;
4844    }
4845    mRefCount[stream] += delta;
4846    ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4847}
4848
4849audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
4850{
4851    if (isDuplicated()) {
4852        return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4853    } else {
4854        return mProfile->mSupportedDevices.types() ;
4855    }
4856}
4857
4858bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
4859{
4860    return isStrategyActive(NUM_STRATEGIES, inPastMs);
4861}
4862
4863bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
4864                                                                       uint32_t inPastMs,
4865                                                                       nsecs_t sysTime) const
4866{
4867    if ((sysTime == 0) && (inPastMs != 0)) {
4868        sysTime = systemTime();
4869    }
4870    for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4871        if (((getStrategy((audio_stream_type_t)i) == strategy) ||
4872                (NUM_STRATEGIES == strategy)) &&
4873                isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
4874            return true;
4875        }
4876    }
4877    return false;
4878}
4879
4880bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
4881                                                                       uint32_t inPastMs,
4882                                                                       nsecs_t sysTime) const
4883{
4884    if (mRefCount[stream] != 0) {
4885        return true;
4886    }
4887    if (inPastMs == 0) {
4888        return false;
4889    }
4890    if (sysTime == 0) {
4891        sysTime = systemTime();
4892    }
4893    if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4894        return true;
4895    }
4896    return false;
4897}
4898
4899void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
4900                                                 struct audio_port_config *dstConfig,
4901                                                 const struct audio_port_config *srcConfig) const
4902{
4903    ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
4904
4905    dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4906                            AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4907    if (srcConfig != NULL) {
4908        dstConfig->config_mask |= srcConfig->config_mask;
4909    }
4910    AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4911
4912    dstConfig->id = mId;
4913    dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4914    dstConfig->type = AUDIO_PORT_TYPE_MIX;
4915    dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4916    dstConfig->ext.mix.handle = mIoHandle;
4917    dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
4918}
4919
4920void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4921                                                    struct audio_port *port) const
4922{
4923    ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
4924    mProfile->toAudioPort(port);
4925    port->id = mId;
4926    toAudioPortConfig(&port->active_config);
4927    port->ext.mix.hw_module = mProfile->mModule->mHandle;
4928    port->ext.mix.handle = mIoHandle;
4929    port->ext.mix.latency_class =
4930            mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4931}
4932
4933status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
4934{
4935    const size_t SIZE = 256;
4936    char buffer[SIZE];
4937    String8 result;
4938
4939    snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4940    result.append(buffer);
4941    snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4942    result.append(buffer);
4943    snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4944    result.append(buffer);
4945    snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4946    result.append(buffer);
4947    snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4948    result.append(buffer);
4949    snprintf(buffer, SIZE, " Devices %08x\n", device());
4950    result.append(buffer);
4951    snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4952    result.append(buffer);
4953    for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4954        snprintf(buffer, SIZE, " %02d     %.03f     %02d       %02d\n",
4955                 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
4956        result.append(buffer);
4957    }
4958    write(fd, result.string(), result.size());
4959
4960    return NO_ERROR;
4961}
4962
4963// --- AudioInputDescriptor class implementation
4964
4965AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
4966    : mId(0), mIoHandle(0),
4967      mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
4968      mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
4969{
4970    if (profile != NULL) {
4971        mAudioPort = profile;
4972        mSamplingRate = profile->pickSamplingRate();
4973        mFormat = profile->pickFormat();
4974        mChannelMask = profile->pickChannelMask();
4975        if (profile->mGains.size() > 0) {
4976            profile->mGains[0]->getDefaultConfig(&mGain);
4977        }
4978    }
4979}
4980
4981void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
4982                                                   struct audio_port_config *dstConfig,
4983                                                   const struct audio_port_config *srcConfig) const
4984{
4985    ALOG_ASSERT(mProfile != 0,
4986                "toAudioPortConfig() called on input with null profile %d", mIoHandle);
4987    dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4988                            AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4989    if (srcConfig != NULL) {
4990        dstConfig->config_mask |= srcConfig->config_mask;
4991    }
4992
4993    AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4994
4995    dstConfig->id = mId;
4996    dstConfig->role = AUDIO_PORT_ROLE_SINK;
4997    dstConfig->type = AUDIO_PORT_TYPE_MIX;
4998    dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4999    dstConfig->ext.mix.handle = mIoHandle;
5000    dstConfig->ext.mix.usecase.source = mInputSource;
5001}
5002
5003void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
5004                                                    struct audio_port *port) const
5005{
5006    ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
5007
5008    mProfile->toAudioPort(port);
5009    port->id = mId;
5010    toAudioPortConfig(&port->active_config);
5011    port->ext.mix.hw_module = mProfile->mModule->mHandle;
5012    port->ext.mix.handle = mIoHandle;
5013    port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
5014}
5015
5016status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
5017{
5018    const size_t SIZE = 256;
5019    char buffer[SIZE];
5020    String8 result;
5021
5022    snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
5023    result.append(buffer);
5024    snprintf(buffer, SIZE, " Format: %d\n", mFormat);
5025    result.append(buffer);
5026    snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
5027    result.append(buffer);
5028    snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
5029    result.append(buffer);
5030    snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
5031    result.append(buffer);
5032    snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
5033    result.append(buffer);
5034
5035    write(fd, result.string(), result.size());
5036
5037    return NO_ERROR;
5038}
5039
5040// --- StreamDescriptor class implementation
5041
5042AudioPolicyManager::StreamDescriptor::StreamDescriptor()
5043    :   mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
5044{
5045    mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
5046}
5047
5048int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
5049{
5050    device = AudioPolicyManager::getDeviceForVolume(device);
5051    // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
5052    if (mIndexCur.indexOfKey(device) < 0) {
5053        device = AUDIO_DEVICE_OUT_DEFAULT;
5054    }
5055    return mIndexCur.valueFor(device);
5056}
5057
5058void AudioPolicyManager::StreamDescriptor::dump(int fd)
5059{
5060    const size_t SIZE = 256;
5061    char buffer[SIZE];
5062    String8 result;
5063
5064    snprintf(buffer, SIZE, "%s         %02d         %02d         ",
5065             mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
5066    result.append(buffer);
5067    for (size_t i = 0; i < mIndexCur.size(); i++) {
5068        snprintf(buffer, SIZE, "%04x : %02d, ",
5069                 mIndexCur.keyAt(i),
5070                 mIndexCur.valueAt(i));
5071        result.append(buffer);
5072    }
5073    result.append("\n");
5074
5075    write(fd, result.string(), result.size());
5076}
5077
5078// --- EffectDescriptor class implementation
5079
5080status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
5081{
5082    const size_t SIZE = 256;
5083    char buffer[SIZE];
5084    String8 result;
5085
5086    snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5087    result.append(buffer);
5088    snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5089    result.append(buffer);
5090    snprintf(buffer, SIZE, " Session: %d\n", mSession);
5091    result.append(buffer);
5092    snprintf(buffer, SIZE, " Name: %s\n",  mDesc.name);
5093    result.append(buffer);
5094    snprintf(buffer, SIZE, " %s\n",  mEnabled ? "Enabled" : "Disabled");
5095    result.append(buffer);
5096    write(fd, result.string(), result.size());
5097
5098    return NO_ERROR;
5099}
5100
5101// --- HwModule class implementation
5102
5103AudioPolicyManager::HwModule::HwModule(const char *name)
5104    : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5105      mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
5106{
5107}
5108
5109AudioPolicyManager::HwModule::~HwModule()
5110{
5111    for (size_t i = 0; i < mOutputProfiles.size(); i++) {
5112        mOutputProfiles[i]->mSupportedDevices.clear();
5113    }
5114    for (size_t i = 0; i < mInputProfiles.size(); i++) {
5115        mInputProfiles[i]->mSupportedDevices.clear();
5116    }
5117    free((void *)mName);
5118}
5119
5120status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5121{
5122    cnode *node = root->first_child;
5123
5124    sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5125
5126    while (node) {
5127        if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5128            profile->loadSamplingRates((char *)node->value);
5129        } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5130            profile->loadFormats((char *)node->value);
5131        } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5132            profile->loadInChannels((char *)node->value);
5133        } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5134            profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5135                                                           mDeclaredDevices);
5136        } else if (strcmp(node->name, GAINS_TAG) == 0) {
5137            profile->loadGains(node);
5138        }
5139        node = node->next;
5140    }
5141    ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5142            "loadInput() invalid supported devices");
5143    ALOGW_IF(profile->mChannelMasks.size() == 0,
5144            "loadInput() invalid supported channel masks");
5145    ALOGW_IF(profile->mSamplingRates.size() == 0,
5146            "loadInput() invalid supported sampling rates");
5147    ALOGW_IF(profile->mFormats.size() == 0,
5148            "loadInput() invalid supported formats");
5149    if (!profile->mSupportedDevices.isEmpty() &&
5150            (profile->mChannelMasks.size() != 0) &&
5151            (profile->mSamplingRates.size() != 0) &&
5152            (profile->mFormats.size() != 0)) {
5153
5154        ALOGV("loadInput() adding input Supported Devices %04x",
5155              profile->mSupportedDevices.types());
5156
5157        mInputProfiles.add(profile);
5158        return NO_ERROR;
5159    } else {
5160        return BAD_VALUE;
5161    }
5162}
5163
5164status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5165{
5166    cnode *node = root->first_child;
5167
5168    sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5169
5170    while (node) {
5171        if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5172            profile->loadSamplingRates((char *)node->value);
5173        } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5174            profile->loadFormats((char *)node->value);
5175        } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5176            profile->loadOutChannels((char *)node->value);
5177        } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5178            profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5179                                                           mDeclaredDevices);
5180        } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5181            profile->mFlags = parseFlagNames((char *)node->value);
5182        } else if (strcmp(node->name, GAINS_TAG) == 0) {
5183            profile->loadGains(node);
5184        }
5185        node = node->next;
5186    }
5187    ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5188            "loadOutput() invalid supported devices");
5189    ALOGW_IF(profile->mChannelMasks.size() == 0,
5190            "loadOutput() invalid supported channel masks");
5191    ALOGW_IF(profile->mSamplingRates.size() == 0,
5192            "loadOutput() invalid supported sampling rates");
5193    ALOGW_IF(profile->mFormats.size() == 0,
5194            "loadOutput() invalid supported formats");
5195    if (!profile->mSupportedDevices.isEmpty() &&
5196            (profile->mChannelMasks.size() != 0) &&
5197            (profile->mSamplingRates.size() != 0) &&
5198            (profile->mFormats.size() != 0)) {
5199
5200        ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5201              profile->mSupportedDevices.types(), profile->mFlags);
5202
5203        mOutputProfiles.add(profile);
5204        return NO_ERROR;
5205    } else {
5206        return BAD_VALUE;
5207    }
5208}
5209
5210status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5211{
5212    cnode *node = root->first_child;
5213
5214    audio_devices_t type = AUDIO_DEVICE_NONE;
5215    while (node) {
5216        if (strcmp(node->name, DEVICE_TYPE) == 0) {
5217            type = parseDeviceNames((char *)node->value);
5218            break;
5219        }
5220        node = node->next;
5221    }
5222    if (type == AUDIO_DEVICE_NONE ||
5223            (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5224        ALOGW("loadDevice() bad type %08x", type);
5225        return BAD_VALUE;
5226    }
5227    sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5228    deviceDesc->mModule = this;
5229
5230    node = root->first_child;
5231    while (node) {
5232        if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5233            deviceDesc->mAddress = String8((char *)node->value);
5234        } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5235            if (audio_is_input_device(type)) {
5236                deviceDesc->loadInChannels((char *)node->value);
5237            } else {
5238                deviceDesc->loadOutChannels((char *)node->value);
5239            }
5240        } else if (strcmp(node->name, GAINS_TAG) == 0) {
5241            deviceDesc->loadGains(node);
5242        }
5243        node = node->next;
5244    }
5245
5246    ALOGV("loadDevice() adding device name %s type %08x address %s",
5247          deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5248
5249    mDeclaredDevices.add(deviceDesc);
5250
5251    return NO_ERROR;
5252}
5253
5254void AudioPolicyManager::HwModule::dump(int fd)
5255{
5256    const size_t SIZE = 256;
5257    char buffer[SIZE];
5258    String8 result;
5259
5260    snprintf(buffer, SIZE, "  - name: %s\n", mName);
5261    result.append(buffer);
5262    snprintf(buffer, SIZE, "  - handle: %d\n", mHandle);
5263    result.append(buffer);
5264    snprintf(buffer, SIZE, "  - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5265    result.append(buffer);
5266    write(fd, result.string(), result.size());
5267    if (mOutputProfiles.size()) {
5268        write(fd, "  - outputs:\n", strlen("  - outputs:\n"));
5269        for (size_t i = 0; i < mOutputProfiles.size(); i++) {
5270            snprintf(buffer, SIZE, "    output %zu:\n", i);
5271            write(fd, buffer, strlen(buffer));
5272            mOutputProfiles[i]->dump(fd);
5273        }
5274    }
5275    if (mInputProfiles.size()) {
5276        write(fd, "  - inputs:\n", strlen("  - inputs:\n"));
5277        for (size_t i = 0; i < mInputProfiles.size(); i++) {
5278            snprintf(buffer, SIZE, "    input %zu:\n", i);
5279            write(fd, buffer, strlen(buffer));
5280            mInputProfiles[i]->dump(fd);
5281        }
5282    }
5283    if (mDeclaredDevices.size()) {
5284        write(fd, "  - devices:\n", strlen("  - devices:\n"));
5285        for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5286            mDeclaredDevices[i]->dump(fd, 4, i);
5287        }
5288    }
5289}
5290
5291// --- AudioPort class implementation
5292
5293
5294AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5295          audio_port_role_t role, const sp<HwModule>& module) :
5296    mName(name), mType(type), mRole(role), mModule(module), mFlags((audio_output_flags_t)0)
5297{
5298    mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5299                    ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5300}
5301
5302void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5303{
5304    port->role = mRole;
5305    port->type = mType;
5306    unsigned int i;
5307    for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
5308        port->sample_rates[i] = mSamplingRates[i];
5309    }
5310    port->num_sample_rates = i;
5311    for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
5312        port->channel_masks[i] = mChannelMasks[i];
5313    }
5314    port->num_channel_masks = i;
5315    for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
5316        port->formats[i] = mFormats[i];
5317    }
5318    port->num_formats = i;
5319
5320    ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
5321
5322    for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5323        port->gains[i] = mGains[i]->mGain;
5324    }
5325    port->num_gains = i;
5326}
5327
5328
5329void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5330{
5331    char *str = strtok(name, "|");
5332
5333    // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5334    // rates should be read from the output stream after it is opened for the first time
5335    if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5336        mSamplingRates.add(0);
5337        return;
5338    }
5339
5340    while (str != NULL) {
5341        uint32_t rate = atoi(str);
5342        if (rate != 0) {
5343            ALOGV("loadSamplingRates() adding rate %d", rate);
5344            mSamplingRates.add(rate);
5345        }
5346        str = strtok(NULL, "|");
5347    }
5348}
5349
5350void AudioPolicyManager::AudioPort::loadFormats(char *name)
5351{
5352    char *str = strtok(name, "|");
5353
5354    // by convention, "0' in the first entry in mFormats indicates the supported formats
5355    // should be read from the output stream after it is opened for the first time
5356    if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5357        mFormats.add(AUDIO_FORMAT_DEFAULT);
5358        return;
5359    }
5360
5361    while (str != NULL) {
5362        audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5363                                                             ARRAY_SIZE(sFormatNameToEnumTable),
5364                                                             str);
5365        if (format != AUDIO_FORMAT_DEFAULT) {
5366            mFormats.add(format);
5367        }
5368        str = strtok(NULL, "|");
5369    }
5370}
5371
5372void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5373{
5374    const char *str = strtok(name, "|");
5375
5376    ALOGV("loadInChannels() %s", name);
5377
5378    if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5379        mChannelMasks.add(0);
5380        return;
5381    }
5382
5383    while (str != NULL) {
5384        audio_channel_mask_t channelMask =
5385                (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5386                                                   ARRAY_SIZE(sInChannelsNameToEnumTable),
5387                                                   str);
5388        if (channelMask != 0) {
5389            ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5390            mChannelMasks.add(channelMask);
5391        }
5392        str = strtok(NULL, "|");
5393    }
5394}
5395
5396void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5397{
5398    const char *str = strtok(name, "|");
5399
5400    ALOGV("loadOutChannels() %s", name);
5401
5402    // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5403    // masks should be read from the output stream after it is opened for the first time
5404    if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5405        mChannelMasks.add(0);
5406        return;
5407    }
5408
5409    while (str != NULL) {
5410        audio_channel_mask_t channelMask =
5411                (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5412                                                   ARRAY_SIZE(sOutChannelsNameToEnumTable),
5413                                                   str);
5414        if (channelMask != 0) {
5415            mChannelMasks.add(channelMask);
5416        }
5417        str = strtok(NULL, "|");
5418    }
5419    return;
5420}
5421
5422audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5423{
5424    const char *str = strtok(name, "|");
5425
5426    ALOGV("loadGainMode() %s", name);
5427    audio_gain_mode_t mode = 0;
5428    while (str != NULL) {
5429        mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5430                                                ARRAY_SIZE(sGainModeNameToEnumTable),
5431                                                str);
5432        str = strtok(NULL, "|");
5433    }
5434    return mode;
5435}
5436
5437void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
5438{
5439    cnode *node = root->first_child;
5440
5441    sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
5442
5443    while (node) {
5444        if (strcmp(node->name, GAIN_MODE) == 0) {
5445            gain->mGain.mode = loadGainMode((char *)node->value);
5446        } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
5447            if (mUseInChannelMask) {
5448                gain->mGain.channel_mask =
5449                        (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5450                                                           ARRAY_SIZE(sInChannelsNameToEnumTable),
5451                                                           (char *)node->value);
5452            } else {
5453                gain->mGain.channel_mask =
5454                        (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5455                                                           ARRAY_SIZE(sOutChannelsNameToEnumTable),
5456                                                           (char *)node->value);
5457            }
5458        } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5459            gain->mGain.min_value = atoi((char *)node->value);
5460        } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5461            gain->mGain.max_value = atoi((char *)node->value);
5462        } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5463            gain->mGain.default_value = atoi((char *)node->value);
5464        } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5465            gain->mGain.step_value = atoi((char *)node->value);
5466        } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5467            gain->mGain.min_ramp_ms = atoi((char *)node->value);
5468        } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5469            gain->mGain.max_ramp_ms = atoi((char *)node->value);
5470        }
5471        node = node->next;
5472    }
5473
5474    ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5475          gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5476
5477    if (gain->mGain.mode == 0) {
5478        return;
5479    }
5480    mGains.add(gain);
5481}
5482
5483void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5484{
5485    cnode *node = root->first_child;
5486    int index = 0;
5487    while (node) {
5488        ALOGV("loadGains() loading gain %s", node->name);
5489        loadGain(node, index++);
5490        node = node->next;
5491    }
5492}
5493
5494status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
5495{
5496    for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5497        if (mSamplingRates[i] == samplingRate) {
5498            return NO_ERROR;
5499        }
5500    }
5501    return BAD_VALUE;
5502}
5503
5504status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
5505        uint32_t *updatedSamplingRate) const
5506{
5507    // Search for the closest supported sampling rate that is above (preferred)
5508    // or below (acceptable) the desired sampling rate, within a permitted ratio.
5509    // The sampling rates do not need to be sorted in ascending order.
5510    ssize_t maxBelow = -1;
5511    ssize_t minAbove = -1;
5512    uint32_t candidate;
5513    for (size_t i = 0; i < mSamplingRates.size(); i++) {
5514        candidate = mSamplingRates[i];
5515        if (candidate == samplingRate) {
5516            if (updatedSamplingRate != NULL) {
5517                *updatedSamplingRate = candidate;
5518            }
5519            return NO_ERROR;
5520        }
5521        // candidate < desired
5522        if (candidate < samplingRate) {
5523            if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
5524                maxBelow = i;
5525            }
5526        // candidate > desired
5527        } else {
5528            if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
5529                minAbove = i;
5530            }
5531        }
5532    }
5533    // This uses hard-coded knowledge about AudioFlinger resampling ratios.
5534    // TODO Move these assumptions out.
5535    static const uint32_t kMaxDownSampleRatio = 6;  // beyond this aliasing occurs
5536    static const uint32_t kMaxUpSampleRatio = 256;  // beyond this sample rate inaccuracies occur
5537                                                    // due to approximation by an int32_t of the
5538                                                    // phase increments
5539    // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
5540    if (minAbove >= 0) {
5541        candidate = mSamplingRates[minAbove];
5542        if (candidate / kMaxDownSampleRatio <= samplingRate) {
5543            if (updatedSamplingRate != NULL) {
5544                *updatedSamplingRate = candidate;
5545            }
5546            return NO_ERROR;
5547        }
5548    }
5549    // But if we have to up-sample from a lower sampling rate, that's OK.
5550    if (maxBelow >= 0) {
5551        candidate = mSamplingRates[maxBelow];
5552        if (candidate * kMaxUpSampleRatio >= samplingRate) {
5553            if (updatedSamplingRate != NULL) {
5554                *updatedSamplingRate = candidate;
5555            }
5556            return NO_ERROR;
5557        }
5558    }
5559    // leave updatedSamplingRate unmodified
5560    return BAD_VALUE;
5561}
5562
5563status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
5564{
5565    for (size_t i = 0; i < mChannelMasks.size(); i++) {
5566        if (mChannelMasks[i] == channelMask) {
5567            return NO_ERROR;
5568        }
5569    }
5570    return BAD_VALUE;
5571}
5572
5573status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
5574        const
5575{
5576    const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
5577    for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5578        // FIXME Does not handle multi-channel automatic conversions yet
5579        audio_channel_mask_t supported = mChannelMasks[i];
5580        if (supported == channelMask) {
5581            return NO_ERROR;
5582        }
5583        if (isRecordThread) {
5584            // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
5585            // FIXME Abstract this out to a table.
5586            if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
5587                    && channelMask == AUDIO_CHANNEL_IN_MONO) ||
5588                (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
5589                    || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
5590                return NO_ERROR;
5591            }
5592        }
5593    }
5594    return BAD_VALUE;
5595}
5596
5597status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5598{
5599    for (size_t i = 0; i < mFormats.size(); i ++) {
5600        if (mFormats[i] == format) {
5601            return NO_ERROR;
5602        }
5603    }
5604    return BAD_VALUE;
5605}
5606
5607
5608uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
5609{
5610    // special case for uninitialized dynamic profile
5611    if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
5612        return 0;
5613    }
5614
5615    uint32_t samplingRate = 0;
5616    uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
5617
5618    // For mixed output and inputs, use max mixer sampling rates. Do not
5619    // limit sampling rate otherwise
5620    if ((mType != AUDIO_PORT_TYPE_MIX) ||
5621            ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5622            (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5623        maxRate = UINT_MAX;
5624    }
5625    for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5626        if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
5627            samplingRate = mSamplingRates[i];
5628        }
5629    }
5630    return samplingRate;
5631}
5632
5633audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
5634{
5635    // special case for uninitialized dynamic profile
5636    if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
5637        return AUDIO_CHANNEL_NONE;
5638    }
5639
5640    audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
5641    uint32_t channelCount = 0;
5642    uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
5643
5644    // For mixed output and inputs, use max mixer channel count. Do not
5645    // limit channel count otherwise
5646    if ((mType != AUDIO_PORT_TYPE_MIX) ||
5647            ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5648            (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5649        maxCount = UINT_MAX;
5650    }
5651    for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5652        uint32_t cnlCount;
5653        if (mUseInChannelMask) {
5654            cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
5655        } else {
5656            cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
5657        }
5658        if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
5659            channelMask = mChannelMasks[i];
5660        }
5661    }
5662    return channelMask;
5663}
5664
5665/* format in order of increasing preference */
5666const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
5667        AUDIO_FORMAT_DEFAULT,
5668        AUDIO_FORMAT_PCM_16_BIT,
5669        AUDIO_FORMAT_PCM_8_24_BIT,
5670        AUDIO_FORMAT_PCM_24_BIT_PACKED,
5671        AUDIO_FORMAT_PCM_32_BIT,
5672        AUDIO_FORMAT_PCM_FLOAT,
5673};
5674
5675int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
5676                                                  audio_format_t format2)
5677{
5678    // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
5679    // compressed format and better than any PCM format. This is by design of pickFormat()
5680    if (!audio_is_linear_pcm(format1)) {
5681        if (!audio_is_linear_pcm(format2)) {
5682            return 0;
5683        }
5684        return 1;
5685    }
5686    if (!audio_is_linear_pcm(format2)) {
5687        return -1;
5688    }
5689
5690    int index1 = -1, index2 = -1;
5691    for (size_t i = 0;
5692            (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
5693            i ++) {
5694        if (sPcmFormatCompareTable[i] == format1) {
5695            index1 = i;
5696        }
5697        if (sPcmFormatCompareTable[i] == format2) {
5698            index2 = i;
5699        }
5700    }
5701    // format1 not found => index1 < 0 => format2 > format1
5702    // format2 not found => index2 < 0 => format2 < format1
5703    return index1 - index2;
5704}
5705
5706audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
5707{
5708    // special case for uninitialized dynamic profile
5709    if (mFormats.size() == 1 && mFormats[0] == 0) {
5710        return AUDIO_FORMAT_DEFAULT;
5711    }
5712
5713    audio_format_t format = AUDIO_FORMAT_DEFAULT;
5714    audio_format_t bestFormat =
5715            AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
5716                ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
5717    // For mixed output and inputs, use best mixer output format. Do not
5718    // limit format otherwise
5719    if ((mType != AUDIO_PORT_TYPE_MIX) ||
5720            ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5721             (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
5722        bestFormat = AUDIO_FORMAT_INVALID;
5723    }
5724
5725    for (size_t i = 0; i < mFormats.size(); i ++) {
5726        if ((compareFormats(mFormats[i], format) > 0) &&
5727                (compareFormats(mFormats[i], bestFormat) <= 0)) {
5728            format = mFormats[i];
5729        }
5730    }
5731    return format;
5732}
5733
5734status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
5735                                                  int index) const
5736{
5737    if (index < 0 || (size_t)index >= mGains.size()) {
5738        return BAD_VALUE;
5739    }
5740    return mGains[index]->checkConfig(gainConfig);
5741}
5742
5743void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5744{
5745    const size_t SIZE = 256;
5746    char buffer[SIZE];
5747    String8 result;
5748
5749    if (mName.size() != 0) {
5750        snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5751        result.append(buffer);
5752    }
5753
5754    if (mSamplingRates.size() != 0) {
5755        snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5756        result.append(buffer);
5757        for (size_t i = 0; i < mSamplingRates.size(); i++) {
5758            if (i == 0 && mSamplingRates[i] == 0) {
5759                snprintf(buffer, SIZE, "Dynamic");
5760            } else {
5761                snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5762            }
5763            result.append(buffer);
5764            result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5765        }
5766        result.append("\n");
5767    }
5768
5769    if (mChannelMasks.size() != 0) {
5770        snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5771        result.append(buffer);
5772        for (size_t i = 0; i < mChannelMasks.size(); i++) {
5773            ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
5774
5775            if (i == 0 && mChannelMasks[i] == 0) {
5776                snprintf(buffer, SIZE, "Dynamic");
5777            } else {
5778                snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
5779            }
5780            result.append(buffer);
5781            result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
5782        }
5783        result.append("\n");
5784    }
5785
5786    if (mFormats.size() != 0) {
5787        snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
5788        result.append(buffer);
5789        for (size_t i = 0; i < mFormats.size(); i++) {
5790            const char *formatStr = enumToString(sFormatNameToEnumTable,
5791                                                 ARRAY_SIZE(sFormatNameToEnumTable),
5792                                                 mFormats[i]);
5793            if (i == 0 && strcmp(formatStr, "") == 0) {
5794                snprintf(buffer, SIZE, "Dynamic");
5795            } else {
5796                snprintf(buffer, SIZE, "%s", formatStr);
5797            }
5798            result.append(buffer);
5799            result.append(i == (mFormats.size() - 1) ? "" : ", ");
5800        }
5801        result.append("\n");
5802    }
5803    write(fd, result.string(), result.size());
5804    if (mGains.size() != 0) {
5805        snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
5806        write(fd, buffer, strlen(buffer) + 1);
5807        result.append(buffer);
5808        for (size_t i = 0; i < mGains.size(); i++) {
5809            mGains[i]->dump(fd, spaces + 2, i);
5810        }
5811    }
5812}
5813
5814// --- AudioGain class implementation
5815
5816AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
5817{
5818    mIndex = index;
5819    mUseInChannelMask = useInChannelMask;
5820    memset(&mGain, 0, sizeof(struct audio_gain));
5821}
5822
5823void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
5824{
5825    config->index = mIndex;
5826    config->mode = mGain.mode;
5827    config->channel_mask = mGain.channel_mask;
5828    if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5829        config->values[0] = mGain.default_value;
5830    } else {
5831        uint32_t numValues;
5832        if (mUseInChannelMask) {
5833            numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
5834        } else {
5835            numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
5836        }
5837        for (size_t i = 0; i < numValues; i++) {
5838            config->values[i] = mGain.default_value;
5839        }
5840    }
5841    if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5842        config->ramp_duration_ms = mGain.min_ramp_ms;
5843    }
5844}
5845
5846status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
5847{
5848    if ((config->mode & ~mGain.mode) != 0) {
5849        return BAD_VALUE;
5850    }
5851    if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5852        if ((config->values[0] < mGain.min_value) ||
5853                    (config->values[0] > mGain.max_value)) {
5854            return BAD_VALUE;
5855        }
5856    } else {
5857        if ((config->channel_mask & ~mGain.channel_mask) != 0) {
5858            return BAD_VALUE;
5859        }
5860        uint32_t numValues;
5861        if (mUseInChannelMask) {
5862            numValues = audio_channel_count_from_in_mask(config->channel_mask);
5863        } else {
5864            numValues = audio_channel_count_from_out_mask(config->channel_mask);
5865        }
5866        for (size_t i = 0; i < numValues; i++) {
5867            if ((config->values[i] < mGain.min_value) ||
5868                    (config->values[i] > mGain.max_value)) {
5869                return BAD_VALUE;
5870            }
5871        }
5872    }
5873    if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5874        if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
5875                    (config->ramp_duration_ms > mGain.max_ramp_ms)) {
5876            return BAD_VALUE;
5877        }
5878    }
5879    return NO_ERROR;
5880}
5881
5882void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
5883{
5884    const size_t SIZE = 256;
5885    char buffer[SIZE];
5886    String8 result;
5887
5888    snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
5889    result.append(buffer);
5890    snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
5891    result.append(buffer);
5892    snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
5893    result.append(buffer);
5894    snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
5895    result.append(buffer);
5896    snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
5897    result.append(buffer);
5898    snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
5899    result.append(buffer);
5900    snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
5901    result.append(buffer);
5902    snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
5903    result.append(buffer);
5904    snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
5905    result.append(buffer);
5906
5907    write(fd, result.string(), result.size());
5908}
5909
5910// --- AudioPortConfig class implementation
5911
5912AudioPolicyManager::AudioPortConfig::AudioPortConfig()
5913{
5914    mSamplingRate = 0;
5915    mChannelMask = AUDIO_CHANNEL_NONE;
5916    mFormat = AUDIO_FORMAT_INVALID;
5917    mGain.index = -1;
5918}
5919
5920status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
5921                                                        const struct audio_port_config *config,
5922                                                        struct audio_port_config *backupConfig)
5923{
5924    struct audio_port_config localBackupConfig;
5925    status_t status = NO_ERROR;
5926
5927    localBackupConfig.config_mask = config->config_mask;
5928    toAudioPortConfig(&localBackupConfig);
5929
5930    if (mAudioPort == 0) {
5931        status = NO_INIT;
5932        goto exit;
5933    }
5934    if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5935        status = mAudioPort->checkExactSamplingRate(config->sample_rate);
5936        if (status != NO_ERROR) {
5937            goto exit;
5938        }
5939        mSamplingRate = config->sample_rate;
5940    }
5941    if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5942        status = mAudioPort->checkExactChannelMask(config->channel_mask);
5943        if (status != NO_ERROR) {
5944            goto exit;
5945        }
5946        mChannelMask = config->channel_mask;
5947    }
5948    if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5949        status = mAudioPort->checkFormat(config->format);
5950        if (status != NO_ERROR) {
5951            goto exit;
5952        }
5953        mFormat = config->format;
5954    }
5955    if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5956        status = mAudioPort->checkGain(&config->gain, config->gain.index);
5957        if (status != NO_ERROR) {
5958            goto exit;
5959        }
5960        mGain = config->gain;
5961    }
5962
5963exit:
5964    if (status != NO_ERROR) {
5965        applyAudioPortConfig(&localBackupConfig);
5966    }
5967    if (backupConfig != NULL) {
5968        *backupConfig = localBackupConfig;
5969    }
5970    return status;
5971}
5972
5973void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
5974                                                    struct audio_port_config *dstConfig,
5975                                                    const struct audio_port_config *srcConfig) const
5976{
5977    if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5978        dstConfig->sample_rate = mSamplingRate;
5979        if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
5980            dstConfig->sample_rate = srcConfig->sample_rate;
5981        }
5982    } else {
5983        dstConfig->sample_rate = 0;
5984    }
5985    if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5986        dstConfig->channel_mask = mChannelMask;
5987        if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
5988            dstConfig->channel_mask = srcConfig->channel_mask;
5989        }
5990    } else {
5991        dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
5992    }
5993    if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5994        dstConfig->format = mFormat;
5995        if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
5996            dstConfig->format = srcConfig->format;
5997        }
5998    } else {
5999        dstConfig->format = AUDIO_FORMAT_INVALID;
6000    }
6001    if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
6002        dstConfig->gain = mGain;
6003        if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
6004            dstConfig->gain = srcConfig->gain;
6005        }
6006    } else {
6007        dstConfig->gain.index = -1;
6008    }
6009    if (dstConfig->gain.index != -1) {
6010        dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
6011    } else {
6012        dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
6013    }
6014}
6015
6016// --- IOProfile class implementation
6017
6018AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
6019                                         const sp<HwModule>& module)
6020    : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
6021{
6022}
6023
6024AudioPolicyManager::IOProfile::~IOProfile()
6025{
6026}
6027
6028// checks if the IO profile is compatible with specified parameters.
6029// Sampling rate, format and channel mask must be specified in order to
6030// get a valid a match
6031bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
6032                                                            uint32_t samplingRate,
6033                                                            uint32_t *updatedSamplingRate,
6034                                                            audio_format_t format,
6035                                                            audio_channel_mask_t channelMask,
6036                                                            audio_output_flags_t flags) const
6037{
6038    const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
6039    const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6040    ALOG_ASSERT(isPlaybackThread != isRecordThread);
6041
6042    if ((mSupportedDevices.types() & device) != device) {
6043        return false;
6044    }
6045
6046    if (samplingRate == 0) {
6047         return false;
6048    }
6049    uint32_t myUpdatedSamplingRate = samplingRate;
6050    if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
6051         return false;
6052    }
6053    if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
6054            NO_ERROR) {
6055         return false;
6056    }
6057
6058    if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
6059        return false;
6060    }
6061
6062    if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
6063            checkExactChannelMask(channelMask) != NO_ERROR)) {
6064        return false;
6065    }
6066    if (isRecordThread && (!audio_is_input_channel(channelMask) ||
6067            checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
6068        return false;
6069    }
6070
6071    if (isPlaybackThread && (mFlags & flags) != flags) {
6072        return false;
6073    }
6074    // The only input flag that is allowed to be different is the fast flag.
6075    // An existing fast stream is compatible with a normal track request.
6076    // An existing normal stream is compatible with a fast track request,
6077    // but the fast request will be denied by AudioFlinger and converted to normal track.
6078    if (isRecordThread && (((audio_input_flags_t) mFlags ^ (audio_input_flags_t) flags) &
6079            ~AUDIO_INPUT_FLAG_FAST)) {
6080        return false;
6081    }
6082
6083    if (updatedSamplingRate != NULL) {
6084        *updatedSamplingRate = myUpdatedSamplingRate;
6085    }
6086    return true;
6087}
6088
6089void AudioPolicyManager::IOProfile::dump(int fd)
6090{
6091    const size_t SIZE = 256;
6092    char buffer[SIZE];
6093    String8 result;
6094
6095    AudioPort::dump(fd, 4);
6096
6097    snprintf(buffer, SIZE, "    - flags: 0x%04x\n", mFlags);
6098    result.append(buffer);
6099    snprintf(buffer, SIZE, "    - devices:\n");
6100    result.append(buffer);
6101    write(fd, result.string(), result.size());
6102    for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6103        mSupportedDevices[i]->dump(fd, 6, i);
6104    }
6105}
6106
6107void AudioPolicyManager::IOProfile::log()
6108{
6109    const size_t SIZE = 256;
6110    char buffer[SIZE];
6111    String8 result;
6112
6113    ALOGV("    - sampling rates: ");
6114    for (size_t i = 0; i < mSamplingRates.size(); i++) {
6115        ALOGV("  %d", mSamplingRates[i]);
6116    }
6117
6118    ALOGV("    - channel masks: ");
6119    for (size_t i = 0; i < mChannelMasks.size(); i++) {
6120        ALOGV("  0x%04x", mChannelMasks[i]);
6121    }
6122
6123    ALOGV("    - formats: ");
6124    for (size_t i = 0; i < mFormats.size(); i++) {
6125        ALOGV("  0x%08x", mFormats[i]);
6126    }
6127
6128    ALOGV("    - devices: 0x%04x\n", mSupportedDevices.types());
6129    ALOGV("    - flags: 0x%04x\n", mFlags);
6130}
6131
6132
6133// --- DeviceDescriptor implementation
6134
6135
6136AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6137                     AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6138                               audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6139                                                              AUDIO_PORT_ROLE_SOURCE,
6140                             NULL),
6141                     mDeviceType(type), mAddress(""), mId(0)
6142{
6143    mAudioPort = this;
6144    if (mGains.size() > 0) {
6145        mGains[0]->getDefaultConfig(&mGain);
6146    }
6147}
6148
6149bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
6150{
6151    // Devices are considered equal if they:
6152    // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6153    // - have the same address or one device does not specify the address
6154    // - have the same channel mask or one device does not specify the channel mask
6155    return (mDeviceType == other->mDeviceType) &&
6156           (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
6157           (mChannelMask == 0 || other->mChannelMask == 0 ||
6158                mChannelMask == other->mChannelMask);
6159}
6160
6161void AudioPolicyManager::DeviceVector::refreshTypes()
6162{
6163    mDeviceTypes = AUDIO_DEVICE_NONE;
6164    for(size_t i = 0; i < size(); i++) {
6165        mDeviceTypes |= itemAt(i)->mDeviceType;
6166    }
6167    ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
6168}
6169
6170ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6171{
6172    for(size_t i = 0; i < size(); i++) {
6173        if (item->equals(itemAt(i))) {
6174            return i;
6175        }
6176    }
6177    return -1;
6178}
6179
6180ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
6181{
6182    ssize_t ret = indexOf(item);
6183
6184    if (ret < 0) {
6185        ret = SortedVector::add(item);
6186        if (ret >= 0) {
6187            refreshTypes();
6188        }
6189    } else {
6190        ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
6191        ret = -1;
6192    }
6193    return ret;
6194}
6195
6196ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6197{
6198    size_t i;
6199    ssize_t ret = indexOf(item);
6200
6201    if (ret < 0) {
6202        ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
6203    } else {
6204        ret = SortedVector::removeAt(ret);
6205        if (ret >= 0) {
6206            refreshTypes();
6207        }
6208    }
6209    return ret;
6210}
6211
6212void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6213{
6214    DeviceVector deviceList;
6215
6216    uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6217    types &= ~role_bit;
6218
6219    while (types) {
6220        uint32_t i = 31 - __builtin_clz(types);
6221        uint32_t type = 1 << i;
6222        types &= ~type;
6223        add(new DeviceDescriptor(String8(""), type | role_bit));
6224    }
6225}
6226
6227void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6228                                                           const DeviceVector& declaredDevices)
6229{
6230    char *devName = strtok(name, "|");
6231    while (devName != NULL) {
6232        if (strlen(devName) != 0) {
6233            audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6234                                 ARRAY_SIZE(sDeviceNameToEnumTable),
6235                                 devName);
6236            if (type != AUDIO_DEVICE_NONE) {
6237                add(new DeviceDescriptor(String8(""), type));
6238            } else {
6239                sp<DeviceDescriptor> deviceDesc =
6240                        declaredDevices.getDeviceFromName(String8(devName));
6241                if (deviceDesc != 0) {
6242                    add(deviceDesc);
6243                }
6244            }
6245         }
6246        devName = strtok(NULL, "|");
6247     }
6248}
6249
6250sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6251                                                        audio_devices_t type, String8 address) const
6252{
6253    sp<DeviceDescriptor> device;
6254    for (size_t i = 0; i < size(); i++) {
6255        if (itemAt(i)->mDeviceType == type) {
6256            device = itemAt(i);
6257            if (itemAt(i)->mAddress = address) {
6258                break;
6259            }
6260        }
6261    }
6262    ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6263          type, address.string(), device.get());
6264    return device;
6265}
6266
6267sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6268                                                                    audio_port_handle_t id) const
6269{
6270    sp<DeviceDescriptor> device;
6271    for (size_t i = 0; i < size(); i++) {
6272        ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
6273        if (itemAt(i)->mId == id) {
6274            device = itemAt(i);
6275            break;
6276        }
6277    }
6278    return device;
6279}
6280
6281AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6282                                                                        audio_devices_t type) const
6283{
6284    DeviceVector devices;
6285    for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6286        if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6287            devices.add(itemAt(i));
6288            type &= ~itemAt(i)->mDeviceType;
6289            ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6290                  itemAt(i)->mDeviceType, itemAt(i).get());
6291        }
6292    }
6293    return devices;
6294}
6295
6296AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6297        audio_devices_t type, String8 address) const
6298{
6299    DeviceVector devices;
6300    //ALOGV("   looking for device=%x, addr=%s", type, address.string());
6301    for (size_t i = 0; i < size(); i++) {
6302        //ALOGV("     at i=%d: device=%x, addr=%s",
6303        //        i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6304        if (itemAt(i)->mDeviceType == type) {
6305            if (itemAt(i)->mAddress == address) {
6306                //ALOGV("      found matching address %s", address.string());
6307                devices.add(itemAt(i));
6308            }
6309        }
6310    }
6311    return devices;
6312}
6313
6314sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6315        const String8& name) const
6316{
6317    sp<DeviceDescriptor> device;
6318    for (size_t i = 0; i < size(); i++) {
6319        if (itemAt(i)->mName == name) {
6320            device = itemAt(i);
6321            break;
6322        }
6323    }
6324    return device;
6325}
6326
6327void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6328                                                    struct audio_port_config *dstConfig,
6329                                                    const struct audio_port_config *srcConfig) const
6330{
6331    dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6332    if (srcConfig != NULL) {
6333        dstConfig->config_mask |= srcConfig->config_mask;
6334    }
6335
6336    AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6337
6338    dstConfig->id = mId;
6339    dstConfig->role = audio_is_output_device(mDeviceType) ?
6340                        AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
6341    dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
6342    dstConfig->ext.device.type = mDeviceType;
6343    dstConfig->ext.device.hw_module = mModule->mHandle;
6344    strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6345}
6346
6347void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6348{
6349    ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
6350    AudioPort::toAudioPort(port);
6351    port->id = mId;
6352    toAudioPortConfig(&port->active_config);
6353    port->ext.device.type = mDeviceType;
6354    port->ext.device.hw_module = mModule->mHandle;
6355    strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6356}
6357
6358status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
6359{
6360    const size_t SIZE = 256;
6361    char buffer[SIZE];
6362    String8 result;
6363
6364    snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6365    result.append(buffer);
6366    if (mId != 0) {
6367        snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6368        result.append(buffer);
6369    }
6370    snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6371                                              enumToString(sDeviceNameToEnumTable,
6372                                                           ARRAY_SIZE(sDeviceNameToEnumTable),
6373                                                           mDeviceType));
6374    result.append(buffer);
6375    if (mAddress.size() != 0) {
6376        snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6377        result.append(buffer);
6378    }
6379    write(fd, result.string(), result.size());
6380    AudioPort::dump(fd, spaces);
6381
6382    return NO_ERROR;
6383}
6384
6385
6386// --- audio_policy.conf file parsing
6387
6388audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
6389{
6390    uint32_t flag = 0;
6391
6392    // it is OK to cast name to non const here as we are not going to use it after
6393    // strtok() modifies it
6394    char *flagName = strtok(name, "|");
6395    while (flagName != NULL) {
6396        if (strlen(flagName) != 0) {
6397            flag |= stringToEnum(sFlagNameToEnumTable,
6398                               ARRAY_SIZE(sFlagNameToEnumTable),
6399                               flagName);
6400        }
6401        flagName = strtok(NULL, "|");
6402    }
6403    //force direct flag if offload flag is set: offloading implies a direct output stream
6404    // and all common behaviors are driven by checking only the direct flag
6405    // this should normally be set appropriately in the policy configuration file
6406    if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
6407        flag |= AUDIO_OUTPUT_FLAG_DIRECT;
6408    }
6409
6410    return (audio_output_flags_t)flag;
6411}
6412
6413audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
6414{
6415    uint32_t device = 0;
6416
6417    char *devName = strtok(name, "|");
6418    while (devName != NULL) {
6419        if (strlen(devName) != 0) {
6420            device |= stringToEnum(sDeviceNameToEnumTable,
6421                                 ARRAY_SIZE(sDeviceNameToEnumTable),
6422                                 devName);
6423         }
6424        devName = strtok(NULL, "|");
6425     }
6426    return device;
6427}
6428
6429void AudioPolicyManager::loadHwModule(cnode *root)
6430{
6431    status_t status = NAME_NOT_FOUND;
6432    cnode *node;
6433    sp<HwModule> module = new HwModule(root->name);
6434
6435    node = config_find(root, DEVICES_TAG);
6436    if (node != NULL) {
6437        node = node->first_child;
6438        while (node) {
6439            ALOGV("loadHwModule() loading device %s", node->name);
6440            status_t tmpStatus = module->loadDevice(node);
6441            if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6442                status = tmpStatus;
6443            }
6444            node = node->next;
6445        }
6446    }
6447    node = config_find(root, OUTPUTS_TAG);
6448    if (node != NULL) {
6449        node = node->first_child;
6450        while (node) {
6451            ALOGV("loadHwModule() loading output %s", node->name);
6452            status_t tmpStatus = module->loadOutput(node);
6453            if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6454                status = tmpStatus;
6455            }
6456            node = node->next;
6457        }
6458    }
6459    node = config_find(root, INPUTS_TAG);
6460    if (node != NULL) {
6461        node = node->first_child;
6462        while (node) {
6463            ALOGV("loadHwModule() loading input %s", node->name);
6464            status_t tmpStatus = module->loadInput(node);
6465            if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6466                status = tmpStatus;
6467            }
6468            node = node->next;
6469        }
6470    }
6471    loadGlobalConfig(root, module);
6472
6473    if (status == NO_ERROR) {
6474        mHwModules.add(module);
6475    }
6476}
6477
6478void AudioPolicyManager::loadHwModules(cnode *root)
6479{
6480    cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
6481    if (node == NULL) {
6482        return;
6483    }
6484
6485    node = node->first_child;
6486    while (node) {
6487        ALOGV("loadHwModules() loading module %s", node->name);
6488        loadHwModule(node);
6489        node = node->next;
6490    }
6491}
6492
6493void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
6494{
6495    cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
6496
6497    if (node == NULL) {
6498        return;
6499    }
6500    DeviceVector declaredDevices;
6501    if (module != NULL) {
6502        declaredDevices = module->mDeclaredDevices;
6503    }
6504
6505    node = node->first_child;
6506    while (node) {
6507        if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
6508            mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
6509                                                        declaredDevices);
6510            ALOGV("loadGlobalConfig() Attached Output Devices %08x",
6511                  mAvailableOutputDevices.types());
6512        } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
6513            audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
6514                                              ARRAY_SIZE(sDeviceNameToEnumTable),
6515                                              (char *)node->value);
6516            if (device != AUDIO_DEVICE_NONE) {
6517                mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
6518            } else {
6519                ALOGW("loadGlobalConfig() default device not specified");
6520            }
6521            ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
6522        } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
6523            mAvailableInputDevices.loadDevicesFromName((char *)node->value,
6524                                                       declaredDevices);
6525            ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
6526        } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
6527            mSpeakerDrcEnabled = stringToBool((char *)node->value);
6528            ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
6529        } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
6530            uint32_t major, minor;
6531            sscanf((char *)node->value, "%u.%u", &major, &minor);
6532            module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
6533            ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
6534                  module->mHalVersion, major, minor);
6535        }
6536        node = node->next;
6537    }
6538}
6539
6540status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
6541{
6542    cnode *root;
6543    char *data;
6544
6545    data = (char *)load_file(path, NULL);
6546    if (data == NULL) {
6547        return -ENODEV;
6548    }
6549    root = config_node("", "");
6550    config_load(root, data);
6551
6552    loadHwModules(root);
6553    // legacy audio_policy.conf files have one global_configuration section
6554    loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
6555    config_free(root);
6556    free(root);
6557    free(data);
6558
6559    ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
6560
6561    return NO_ERROR;
6562}
6563
6564void AudioPolicyManager::defaultAudioPolicyConfig(void)
6565{
6566    sp<HwModule> module;
6567    sp<IOProfile> profile;
6568    sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
6569                                                                   AUDIO_DEVICE_IN_BUILTIN_MIC);
6570    mAvailableOutputDevices.add(mDefaultOutputDevice);
6571    mAvailableInputDevices.add(defaultInputDevice);
6572
6573    module = new HwModule("primary");
6574
6575    profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
6576    profile->mSamplingRates.add(44100);
6577    profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6578    profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
6579    profile->mSupportedDevices.add(mDefaultOutputDevice);
6580    profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
6581    module->mOutputProfiles.add(profile);
6582
6583    profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
6584    profile->mSamplingRates.add(8000);
6585    profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6586    profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
6587    profile->mSupportedDevices.add(defaultInputDevice);
6588    module->mInputProfiles.add(profile);
6589
6590    mHwModules.add(module);
6591}
6592
6593audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
6594{
6595    // flags to stream type mapping
6596    if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6597        return AUDIO_STREAM_ENFORCED_AUDIBLE;
6598    }
6599    if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6600        return AUDIO_STREAM_BLUETOOTH_SCO;
6601    }
6602
6603    // usage to stream type mapping
6604    switch (attr->usage) {
6605    case AUDIO_USAGE_MEDIA:
6606    case AUDIO_USAGE_GAME:
6607    case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6608    case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6609        return AUDIO_STREAM_MUSIC;
6610    case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6611        return AUDIO_STREAM_SYSTEM;
6612    case AUDIO_USAGE_VOICE_COMMUNICATION:
6613        return AUDIO_STREAM_VOICE_CALL;
6614
6615    case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6616        return AUDIO_STREAM_DTMF;
6617
6618    case AUDIO_USAGE_ALARM:
6619        return AUDIO_STREAM_ALARM;
6620    case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6621        return AUDIO_STREAM_RING;
6622
6623    case AUDIO_USAGE_NOTIFICATION:
6624    case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6625    case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6626    case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6627    case AUDIO_USAGE_NOTIFICATION_EVENT:
6628        return AUDIO_STREAM_NOTIFICATION;
6629
6630    case AUDIO_USAGE_UNKNOWN:
6631    default:
6632        return AUDIO_STREAM_MUSIC;
6633    }
6634}
6635}; // namespace android
6636