blob: 70dcb4c113764c43ce069036c1c4cbeb2373c7b4 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
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
Eric Laurente0720872014-03-11 09:30:41 -070017#define LOG_TAG "AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#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
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070036
Eric Laurente552edb2014-03-10 17:42:56 -070037#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <utils/Log.h>
39#include <hardware/audio.h>
40#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070041#include <media/AudioParameter.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070043#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070044
Eric Laurent3b73df72014-03-11 09:06:29 -070045namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070046
47// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070048// Definitions for audio_policy.conf file parsing
49// ----------------------------------------------------------------------------
50
51struct StringToEnum {
52 const char *name;
53 uint32_t value;
54};
55
56#define STRING_TO_ENUM(string) { #string, string }
57#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
58
59const StringToEnum sDeviceNameToEnumTable[] = {
60 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
61 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
62 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
63 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
64 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
68 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070073 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070074 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070080 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurent3a4311c2014-03-17 12:00:47 -070085 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
86 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
87 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
88 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
89 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070090 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070091 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent1b776232014-05-19 17:26:41 -070092 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurent3a4311c2014-03-17 12:00:47 -070093 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
94 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
97 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
100 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
101 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
102 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700103 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700104};
105
106const StringToEnum sFlagNameToEnumTable[] = {
107 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
108 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
109 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
110 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
111 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
112 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
113};
114
115const StringToEnum sFormatNameToEnumTable[] = {
116 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
117 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
118 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
119 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
120 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
121 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
122 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
123 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
124 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
125};
126
127const StringToEnum sOutChannelsNameToEnumTable[] = {
128 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
129 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
130 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
131 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
132};
133
134const StringToEnum sInChannelsNameToEnumTable[] = {
135 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
136 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
137 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
138};
139
Eric Laurent1afeecb2014-05-14 08:52:28 -0700140const StringToEnum sGainModeNameToEnumTable[] = {
141 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
142 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
143 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
144};
145
Eric Laurent3a4311c2014-03-17 12:00:47 -0700146
147uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
148 size_t size,
149 const char *name)
150{
151 for (size_t i = 0; i < size; i++) {
152 if (strcmp(table[i].name, name) == 0) {
153 ALOGV("stringToEnum() found %s", table[i].name);
154 return table[i].value;
155 }
156 }
157 return 0;
158}
159
160const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
161 size_t size,
162 uint32_t value)
163{
164 for (size_t i = 0; i < size; i++) {
165 if (table[i].value == value) {
166 return table[i].name;
167 }
168 }
169 return "";
170}
171
172bool AudioPolicyManager::stringToBool(const char *value)
173{
174 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
175}
176
177
178// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700179// AudioPolicyInterface implementation
180// ----------------------------------------------------------------------------
181
182
Eric Laurente0720872014-03-11 09:30:41 -0700183status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700184 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700185 const char *device_address)
186{
Eric Laurent3a4311c2014-03-17 12:00:47 -0700187 String8 address = String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700188
189 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
190
191 // connect/disconnect only 1 device at a time
192 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
193
Eric Laurente552edb2014-03-10 17:42:56 -0700194 // handle output devices
195 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700196 SortedVector <audio_io_handle_t> outputs;
197
Eric Laurent1afeecb2014-05-14 08:52:28 -0700198 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
199 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700200 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
201
Eric Laurente552edb2014-03-10 17:42:56 -0700202 // save a copy of the opened output descriptors before any output is opened or closed
203 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
204 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700205 switch (state)
206 {
207 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700208 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700209 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700210 ALOGW("setDeviceConnectionState() device already connected: %x", device);
211 return INVALID_OPERATION;
212 }
213 ALOGV("setDeviceConnectionState() connecting device %x", device);
214
Eric Laurent3a4311c2014-03-17 12:00:47 -0700215 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -0700216 return INVALID_OPERATION;
217 }
Eric Laurent6a94d692014-05-20 11:18:06 -0700218 // outputs should never be empty here
219 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
220 "checkOutputsForDevice() returned no outputs but status OK");
Eric Laurentd4692962014-05-05 18:13:44 -0700221 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
Eric Laurente552edb2014-03-10 17:42:56 -0700222 outputs.size());
223 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700224 index = mAvailableOutputDevices.add(devDesc);
225 if (index >= 0) {
226 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent1f2f2232014-06-02 12:01:23 -0700227 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700228 ALOG_ASSERT(module != NULL, "setDeviceConnectionState():"
229 "could not find HW module for device %08x", device);
230 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700231 } else {
232 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700233 }
234
235 break;
236 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700237 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700238 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700239 ALOGW("setDeviceConnectionState() device not connected: %x", device);
240 return INVALID_OPERATION;
241 }
242
243 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
244 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700245 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700246
Eric Laurent3a4311c2014-03-17 12:00:47 -0700247 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700248 // not currently handling multiple simultaneous submixes: ignoring remote submix
249 // case and address
250 } break;
251
252 default:
253 ALOGE("setDeviceConnectionState() invalid state: %x", state);
254 return BAD_VALUE;
255 }
256
Eric Laurent3a4311c2014-03-17 12:00:47 -0700257 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
258 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700259 checkA2dpSuspend();
260 checkOutputForAllStrategies();
261 // outputs must be closed after checkOutputForAllStrategies() is executed
262 if (!outputs.isEmpty()) {
263 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700264 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700265 // close unused outputs after device disconnection or direct outputs that have been
266 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700267 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700268 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
269 (desc->mDirectOpenCount == 0))) {
270 closeOutput(outputs[i]);
271 }
272 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700273 // check again after closing A2DP output to reset mA2dpSuspended if needed
274 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700275 }
276
277 updateDevicesAndOutputs();
278 for (size_t i = 0; i < mOutputs.size(); i++) {
279 // do not force device change on duplicated output because if device is 0, it will
280 // also force a device 0 for the two outputs it is duplicated to which may override
281 // a valid device selection on those outputs.
282 setOutputDevice(mOutputs.keyAt(i),
Eric Laurent1c333e22014-05-20 10:48:17 -0700283 getNewOutputDevice(mOutputs.keyAt(i), true /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700284 !mOutputs.valueAt(i)->isDuplicated(),
285 0);
286 }
287
Eric Laurent72aa32f2014-05-30 18:51:48 -0700288 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700289 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700290 } // end if is output device
291
Eric Laurente552edb2014-03-10 17:42:56 -0700292 // handle input devices
293 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700294 SortedVector <audio_io_handle_t> inputs;
295
Eric Laurent1afeecb2014-05-14 08:52:28 -0700296 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
297 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700298 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700299 switch (state)
300 {
301 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700302 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700303 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700304 ALOGW("setDeviceConnectionState() device already connected: %d", device);
305 return INVALID_OPERATION;
306 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700307 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700308 if (module == NULL) {
309 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
310 device);
311 return INVALID_OPERATION;
312 }
Eric Laurentd4692962014-05-05 18:13:44 -0700313 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
314 return INVALID_OPERATION;
315 }
316
Eric Laurent3a4311c2014-03-17 12:00:47 -0700317 index = mAvailableInputDevices.add(devDesc);
318 if (index >= 0) {
319 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700320 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700321 } else {
322 return NO_MEMORY;
323 }
Eric Laurentd4692962014-05-05 18:13:44 -0700324 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700325
326 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700327 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700328 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700329 ALOGW("setDeviceConnectionState() device not connected: %d", device);
330 return INVALID_OPERATION;
331 }
Eric Laurentd4692962014-05-05 18:13:44 -0700332 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700333 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700334 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700335
336 default:
337 ALOGE("setDeviceConnectionState() invalid state: %x", state);
338 return BAD_VALUE;
339 }
340
Eric Laurentd4692962014-05-05 18:13:44 -0700341 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700342
Eric Laurentb52c1522014-05-20 11:27:36 -0700343 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700344 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700345 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700346
347 ALOGW("setDeviceConnectionState() invalid device: %x", device);
348 return BAD_VALUE;
349}
350
Eric Laurente0720872014-03-11 09:30:41 -0700351audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700352 const char *device_address)
353{
Eric Laurent3b73df72014-03-11 09:06:29 -0700354 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700355 String8 address = String8(device_address);
Eric Laurent1afeecb2014-05-14 08:52:28 -0700356 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
357 devDesc->mAddress = String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700358 ssize_t index;
359 DeviceVector *deviceVector;
360
Eric Laurente552edb2014-03-10 17:42:56 -0700361 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700362 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700363 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700364 deviceVector = &mAvailableInputDevices;
365 } else {
366 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
367 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700368 }
369
Eric Laurent3a4311c2014-03-17 12:00:47 -0700370 index = deviceVector->indexOf(devDesc);
371 if (index >= 0) {
372 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
373 } else {
374 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
375 }
Eric Laurente552edb2014-03-10 17:42:56 -0700376}
377
Eric Laurente0720872014-03-11 09:30:41 -0700378void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700379{
380 ALOGV("setPhoneState() state %d", state);
381 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
Eric Laurent3b73df72014-03-11 09:06:29 -0700382 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700383 ALOGW("setPhoneState() invalid state %d", state);
384 return;
385 }
386
387 if (state == mPhoneState ) {
388 ALOGW("setPhoneState() setting same state %d", state);
389 return;
390 }
391
392 // if leaving call state, handle special case of active streams
393 // pertaining to sonification strategy see handleIncallSonification()
394 if (isInCall()) {
395 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700396 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
397 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700398 }
399 }
400
401 // store previous phone state for management of sonification strategy below
402 int oldState = mPhoneState;
403 mPhoneState = state;
404 bool force = false;
405
406 // are we entering or starting a call
407 if (!isStateInCall(oldState) && isStateInCall(state)) {
408 ALOGV(" Entering call in setPhoneState()");
409 // force routing command to audio hardware when starting a call
410 // even if no device change is needed
411 force = true;
412 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
413 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
414 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
415 }
416 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
417 ALOGV(" Exiting call in setPhoneState()");
418 // force routing command to audio hardware when exiting a call
419 // even if no device change is needed
420 force = true;
421 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
422 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
423 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
424 }
425 } else if (isStateInCall(state) && (state != oldState)) {
426 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
427 // force routing command to audio hardware when switching between telephony and VoIP
428 // even if no device change is needed
429 force = true;
430 }
431
432 // check for device and output changes triggered by new phone state
Eric Laurent1c333e22014-05-20 10:48:17 -0700433 newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700434 checkA2dpSuspend();
435 checkOutputForAllStrategies();
436 updateDevicesAndOutputs();
437
Eric Laurent1f2f2232014-06-02 12:01:23 -0700438 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700439
440 // force routing command to audio hardware when ending call
441 // even if no device change is needed
442 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
443 newDevice = hwOutputDesc->device();
444 }
445
446 int delayMs = 0;
447 if (isStateInCall(state)) {
448 nsecs_t sysTime = systemTime();
449 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700450 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700451 // mute media and sonification strategies and delay device switch by the largest
452 // latency of any output where either strategy is active.
453 // This avoid sending the ring tone or music tail into the earpiece or headset.
454 if ((desc->isStrategyActive(STRATEGY_MEDIA,
455 SONIFICATION_HEADSET_MUSIC_DELAY,
456 sysTime) ||
457 desc->isStrategyActive(STRATEGY_SONIFICATION,
458 SONIFICATION_HEADSET_MUSIC_DELAY,
459 sysTime)) &&
460 (delayMs < (int)desc->mLatency*2)) {
461 delayMs = desc->mLatency*2;
462 }
463 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
464 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
465 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
466 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
467 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
468 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
469 }
470 }
471
472 // change routing is necessary
473 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
474
475 // if entering in call state, handle special case of active streams
476 // pertaining to sonification strategy see handleIncallSonification()
477 if (isStateInCall(state)) {
478 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700479 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
480 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700481 }
482 }
483
484 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700485 if (state == AUDIO_MODE_RINGTONE &&
486 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700487 mLimitRingtoneVolume = true;
488 } else {
489 mLimitRingtoneVolume = false;
490 }
491}
492
Eric Laurente0720872014-03-11 09:30:41 -0700493void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700494 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700495{
496 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
497
498 bool forceVolumeReeval = false;
499 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700500 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
501 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
502 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700503 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
504 return;
505 }
506 forceVolumeReeval = true;
507 mForceUse[usage] = config;
508 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700509 case AUDIO_POLICY_FORCE_FOR_MEDIA:
510 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
511 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
512 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
513 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
514 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700515 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
516 return;
517 }
518 mForceUse[usage] = config;
519 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700520 case AUDIO_POLICY_FORCE_FOR_RECORD:
521 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
522 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700523 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
524 return;
525 }
526 mForceUse[usage] = config;
527 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700528 case AUDIO_POLICY_FORCE_FOR_DOCK:
529 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
530 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
531 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
532 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
533 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700534 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
535 }
536 forceVolumeReeval = true;
537 mForceUse[usage] = config;
538 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700539 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
540 if (config != AUDIO_POLICY_FORCE_NONE &&
541 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700542 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
543 }
544 forceVolumeReeval = true;
545 mForceUse[usage] = config;
546 break;
547 default:
548 ALOGW("setForceUse() invalid usage %d", usage);
549 break;
550 }
551
552 // check for device and output changes triggered by new force usage
553 checkA2dpSuspend();
554 checkOutputForAllStrategies();
555 updateDevicesAndOutputs();
556 for (size_t i = 0; i < mOutputs.size(); i++) {
557 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700558 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700559 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
560 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
561 applyStreamVolumes(output, newDevice, 0, true);
562 }
563 }
564
565 audio_io_handle_t activeInput = getActiveInput();
566 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700567 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700568 }
569
570}
571
Eric Laurente0720872014-03-11 09:30:41 -0700572audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700573{
574 return mForceUse[usage];
575}
576
Eric Laurente0720872014-03-11 09:30:41 -0700577void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700578{
579 ALOGV("setSystemProperty() property %s, value %s", property, value);
580}
581
582// Find a direct output profile compatible with the parameters passed, even if the input flags do
583// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700584sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700585 audio_devices_t device,
586 uint32_t samplingRate,
587 audio_format_t format,
588 audio_channel_mask_t channelMask,
589 audio_output_flags_t flags)
590{
591 for (size_t i = 0; i < mHwModules.size(); i++) {
592 if (mHwModules[i]->mHandle == 0) {
593 continue;
594 }
595 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700596 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent3a4311c2014-03-17 12:00:47 -0700597 bool found = false;
Eric Laurente552edb2014-03-10 17:42:56 -0700598 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
599 if (profile->isCompatibleProfile(device, samplingRate, format,
600 channelMask,
601 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700602 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700603 }
604 } else {
605 if (profile->isCompatibleProfile(device, samplingRate, format,
606 channelMask,
607 AUDIO_OUTPUT_FLAG_DIRECT)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700608 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700609 }
610 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700611 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
612 return profile;
613 }
Eric Laurente552edb2014-03-10 17:42:56 -0700614 }
615 }
616 return 0;
617}
618
Eric Laurente0720872014-03-11 09:30:41 -0700619audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700620 uint32_t samplingRate,
621 audio_format_t format,
622 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700623 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700624 const audio_offload_info_t *offloadInfo)
625{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700626
Eric Laurent3b73df72014-03-11 09:06:29 -0700627 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700628 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
629 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
630 device, stream, samplingRate, format, channelMask, flags);
631
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700632 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
633 offloadInfo);
634}
635
636audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
637 uint32_t samplingRate,
638 audio_format_t format,
639 audio_channel_mask_t channelMask,
640 audio_output_flags_t flags,
641 const audio_offload_info_t *offloadInfo)
642{
643 if (attr == NULL) {
644 ALOGE("getOutputForAttr() called with NULL audio attributes");
645 return 0;
646 }
647 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s",
648 attr->usage, attr->content_type, attr->tags);
649
650 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
651 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
652 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
653 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
654 device, samplingRate, format, channelMask, flags);
655
656 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
657 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
658 offloadInfo);
659}
660
661audio_io_handle_t AudioPolicyManager::getOutputForDevice(
662 audio_devices_t device,
663 audio_stream_type_t stream,
664 uint32_t samplingRate,
665 audio_format_t format,
666 audio_channel_mask_t channelMask,
667 audio_output_flags_t flags,
668 const audio_offload_info_t *offloadInfo)
669{
670 audio_io_handle_t output = 0;
671 uint32_t latency = 0;
672
Eric Laurente552edb2014-03-10 17:42:56 -0700673#ifdef AUDIO_POLICY_TEST
674 if (mCurOutput != 0) {
675 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
676 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
677
678 if (mTestOutputs[mCurOutput] == 0) {
679 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700680 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700681 outputDesc->mDevice = mTestDevice;
682 outputDesc->mSamplingRate = mTestSamplingRate;
683 outputDesc->mFormat = mTestFormat;
684 outputDesc->mChannelMask = mTestChannels;
685 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700686 outputDesc->mFlags =
687 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700688 outputDesc->mRefCount[stream] = 0;
689 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
690 &outputDesc->mSamplingRate,
691 &outputDesc->mFormat,
692 &outputDesc->mChannelMask,
693 &outputDesc->mLatency,
694 outputDesc->mFlags,
695 offloadInfo);
696 if (mTestOutputs[mCurOutput]) {
697 AudioParameter outputCmd = AudioParameter();
698 outputCmd.addInt(String8("set_id"),mCurOutput);
699 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
700 addOutput(mTestOutputs[mCurOutput], outputDesc);
701 }
702 }
703 return mTestOutputs[mCurOutput];
704 }
705#endif //AUDIO_POLICY_TEST
706
707 // open a direct output if required by specified parameters
708 //force direct flag if offload flag is set: offloading implies a direct output stream
709 // and all common behaviors are driven by checking only the direct flag
710 // this should normally be set appropriately in the policy configuration file
711 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700712 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700713 }
714
715 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
716 // creating an offloaded track and tearing it down immediately after start when audioflinger
717 // detects there is an active non offloadable effect.
718 // FIXME: We should check the audio session here but we do not have it in this context.
719 // This may prevent offloading in rare situations where effects are left active by apps
720 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700721 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700722 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
723 !isNonOffloadableEffectEnabled()) {
724 profile = getProfileForDirectOutput(device,
725 samplingRate,
726 format,
727 channelMask,
728 (audio_output_flags_t)flags);
729 }
730
Eric Laurent1c333e22014-05-20 10:48:17 -0700731 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700732 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700733
734 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700735 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700736 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
737 outputDesc = desc;
738 // reuse direct output if currently open and configured with same parameters
739 if ((samplingRate == outputDesc->mSamplingRate) &&
740 (format == outputDesc->mFormat) &&
741 (channelMask == outputDesc->mChannelMask)) {
742 outputDesc->mDirectOpenCount++;
743 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
744 return mOutputs.keyAt(i);
745 }
746 }
747 }
748 // close direct output if currently open and configured with different parameters
749 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700750 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700751 }
752 outputDesc = new AudioOutputDescriptor(profile);
753 outputDesc->mDevice = device;
754 outputDesc->mSamplingRate = samplingRate;
755 outputDesc->mFormat = format;
756 outputDesc->mChannelMask = channelMask;
757 outputDesc->mLatency = 0;
758 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
759 outputDesc->mRefCount[stream] = 0;
760 outputDesc->mStopTime[stream] = 0;
761 outputDesc->mDirectOpenCount = 1;
762 output = mpClientInterface->openOutput(profile->mModule->mHandle,
763 &outputDesc->mDevice,
764 &outputDesc->mSamplingRate,
765 &outputDesc->mFormat,
766 &outputDesc->mChannelMask,
767 &outputDesc->mLatency,
768 outputDesc->mFlags,
769 offloadInfo);
770
771 // only accept an output with the requested parameters
772 if (output == 0 ||
773 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
774 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
775 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
776 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
777 "format %d %d, channelMask %04x %04x", output, samplingRate,
778 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
779 outputDesc->mChannelMask);
780 if (output != 0) {
781 mpClientInterface->closeOutput(output);
782 }
Eric Laurente552edb2014-03-10 17:42:56 -0700783 return 0;
784 }
785 audio_io_handle_t srcOutput = getOutputForEffect();
786 addOutput(output, outputDesc);
787 audio_io_handle_t dstOutput = getOutputForEffect();
788 if (dstOutput == output) {
789 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
790 }
791 mPreviousOutputs = mOutputs;
792 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700793 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700794 return output;
795 }
796
797 // ignoring channel mask due to downmix capability in mixer
798
799 // open a non direct output
800
801 // for non direct outputs, only PCM is supported
802 if (audio_is_linear_pcm(format)) {
803 // get which output is suitable for the specified stream. The actual
804 // routing change will happen when startOutput() will be called
805 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
806
807 output = selectOutput(outputs, flags);
808 }
809 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
810 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
811
812 ALOGV("getOutput() returns output %d", output);
813
814 return output;
815}
816
Eric Laurente0720872014-03-11 09:30:41 -0700817audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700818 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700819{
820 // select one output among several that provide a path to a particular device or set of
821 // devices (the list was previously build by getOutputsForDevice()).
822 // The priority is as follows:
823 // 1: the output with the highest number of requested policy flags
824 // 2: the primary output
825 // 3: the first output in the list
826
827 if (outputs.size() == 0) {
828 return 0;
829 }
830 if (outputs.size() == 1) {
831 return outputs[0];
832 }
833
834 int maxCommonFlags = 0;
835 audio_io_handle_t outputFlags = 0;
836 audio_io_handle_t outputPrimary = 0;
837
838 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700839 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700840 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700841 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700842 if (commonFlags > maxCommonFlags) {
843 outputFlags = outputs[i];
844 maxCommonFlags = commonFlags;
845 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
846 }
847 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
848 outputPrimary = outputs[i];
849 }
850 }
851 }
852
853 if (outputFlags != 0) {
854 return outputFlags;
855 }
856 if (outputPrimary != 0) {
857 return outputPrimary;
858 }
859
860 return outputs[0];
861}
862
Eric Laurente0720872014-03-11 09:30:41 -0700863status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700864 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700865 int session)
866{
867 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
868 ssize_t index = mOutputs.indexOfKey(output);
869 if (index < 0) {
870 ALOGW("startOutput() unknown output %d", output);
871 return BAD_VALUE;
872 }
873
Eric Laurent1f2f2232014-06-02 12:01:23 -0700874 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700875
876 // increment usage count for this stream on the requested output:
877 // NOTE that the usage count is the same for duplicated output and hardware output which is
878 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
879 outputDesc->changeRefCount(stream, 1);
880
881 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700882 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700883 routing_strategy strategy = getStrategy(stream);
884 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
885 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
886 uint32_t waitMs = 0;
887 bool force = false;
888 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700889 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700890 if (desc != outputDesc) {
891 // force a device change if any other output is managed by the same hw
892 // module and has a current device selection that differs from selected device.
893 // In this case, the audio HAL must receive the new device selection so that it can
894 // change the device currently selected by the other active output.
895 if (outputDesc->sharesHwModuleWith(desc) &&
896 desc->device() != newDevice) {
897 force = true;
898 }
899 // wait for audio on other active outputs to be presented when starting
900 // a notification so that audio focus effect can propagate.
901 uint32_t latency = desc->latency();
902 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
903 waitMs = latency;
904 }
905 }
906 }
907 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
908
909 // handle special case for sonification while in call
910 if (isInCall()) {
911 handleIncallSonification(stream, true, false);
912 }
913
914 // apply volume rules for current stream and device if necessary
915 checkAndSetVolume(stream,
916 mStreams[stream].getVolumeIndex(newDevice),
917 output,
918 newDevice);
919
920 // update the outputs if starting an output with a stream that can affect notification
921 // routing
922 handleNotificationRoutingForStream(stream);
923 if (waitMs > muteWaitMs) {
924 usleep((waitMs - muteWaitMs) * 2 * 1000);
925 }
926 }
927 return NO_ERROR;
928}
929
930
Eric Laurente0720872014-03-11 09:30:41 -0700931status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700932 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700933 int session)
934{
935 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
936 ssize_t index = mOutputs.indexOfKey(output);
937 if (index < 0) {
938 ALOGW("stopOutput() unknown output %d", output);
939 return BAD_VALUE;
940 }
941
Eric Laurent1f2f2232014-06-02 12:01:23 -0700942 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700943
944 // handle special case for sonification while in call
945 if (isInCall()) {
946 handleIncallSonification(stream, false, false);
947 }
948
949 if (outputDesc->mRefCount[stream] > 0) {
950 // decrement usage count of this stream on the output
951 outputDesc->changeRefCount(stream, -1);
952 // store time at which the stream was stopped - see isStreamActive()
953 if (outputDesc->mRefCount[stream] == 0) {
954 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -0700955 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700956 // delay the device switch by twice the latency because stopOutput() is executed when
957 // the track stop() command is received and at that time the audio track buffer can
958 // still contain data that needs to be drained. The latency only covers the audio HAL
959 // and kernel buffers. Also the latency does not always include additional delay in the
960 // audio path (audio DSP, CODEC ...)
961 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
962
963 // force restoring the device selection on other active outputs if it differs from the
964 // one being selected for this output
965 for (size_t i = 0; i < mOutputs.size(); i++) {
966 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -0700967 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700968 if (curOutput != output &&
969 desc->isActive() &&
970 outputDesc->sharesHwModuleWith(desc) &&
971 (newDevice != desc->device())) {
972 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -0700973 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -0700974 true,
975 outputDesc->mLatency*2);
976 }
977 }
978 // update the outputs if stopping one with a stream that can affect notification routing
979 handleNotificationRoutingForStream(stream);
980 }
981 return NO_ERROR;
982 } else {
983 ALOGW("stopOutput() refcount is already 0 for output %d", output);
984 return INVALID_OPERATION;
985 }
986}
987
Eric Laurente0720872014-03-11 09:30:41 -0700988void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -0700989{
990 ALOGV("releaseOutput() %d", output);
991 ssize_t index = mOutputs.indexOfKey(output);
992 if (index < 0) {
993 ALOGW("releaseOutput() releasing unknown output %d", output);
994 return;
995 }
996
997#ifdef AUDIO_POLICY_TEST
998 int testIndex = testOutputIndex(output);
999 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001000 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001001 if (outputDesc->isActive()) {
1002 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001003 mOutputs.removeItem(output);
1004 mTestOutputs[testIndex] = 0;
1005 }
1006 return;
1007 }
1008#endif //AUDIO_POLICY_TEST
1009
Eric Laurent1f2f2232014-06-02 12:01:23 -07001010 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001011 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001012 if (desc->mDirectOpenCount <= 0) {
1013 ALOGW("releaseOutput() invalid open count %d for output %d",
1014 desc->mDirectOpenCount, output);
1015 return;
1016 }
1017 if (--desc->mDirectOpenCount == 0) {
1018 closeOutput(output);
1019 // If effects where present on the output, audioflinger moved them to the primary
1020 // output by default: move them back to the appropriate output.
1021 audio_io_handle_t dstOutput = getOutputForEffect();
1022 if (dstOutput != mPrimaryOutput) {
1023 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1024 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001025 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001026 }
1027 }
1028}
1029
1030
Eric Laurente0720872014-03-11 09:30:41 -07001031audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001032 uint32_t samplingRate,
1033 audio_format_t format,
1034 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -07001035 audio_in_acoustics_t acoustics)
Eric Laurente552edb2014-03-10 17:42:56 -07001036{
1037 audio_io_handle_t input = 0;
1038 audio_devices_t device = getDeviceForInputSource(inputSource);
1039
1040 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
1041 inputSource, samplingRate, format, channelMask, acoustics);
1042
1043 if (device == AUDIO_DEVICE_NONE) {
1044 ALOGW("getInput() could not find device for inputSource %d", inputSource);
1045 return 0;
1046 }
1047
1048 // adapt channel selection to input source
1049 switch(inputSource) {
1050 case AUDIO_SOURCE_VOICE_UPLINK:
1051 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1052 break;
1053 case AUDIO_SOURCE_VOICE_DOWNLINK:
1054 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1055 break;
1056 case AUDIO_SOURCE_VOICE_CALL:
1057 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1058 break;
1059 default:
1060 break;
1061 }
1062
Eric Laurent1c333e22014-05-20 10:48:17 -07001063 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001064 samplingRate,
1065 format,
1066 channelMask);
Eric Laurent1c333e22014-05-20 10:48:17 -07001067 if (profile == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07001068 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d, "
1069 "channelMask %04x",
1070 device, samplingRate, format, channelMask);
1071 return 0;
1072 }
1073
1074 if (profile->mModule->mHandle == 0) {
1075 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
1076 return 0;
1077 }
1078
Eric Laurent1f2f2232014-06-02 12:01:23 -07001079 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001080
1081 inputDesc->mInputSource = inputSource;
1082 inputDesc->mDevice = device;
1083 inputDesc->mSamplingRate = samplingRate;
1084 inputDesc->mFormat = format;
1085 inputDesc->mChannelMask = channelMask;
1086 inputDesc->mRefCount = 0;
1087 input = mpClientInterface->openInput(profile->mModule->mHandle,
1088 &inputDesc->mDevice,
1089 &inputDesc->mSamplingRate,
1090 &inputDesc->mFormat,
1091 &inputDesc->mChannelMask);
1092
1093 // only accept input with the exact requested set of parameters
1094 if (input == 0 ||
1095 (samplingRate != inputDesc->mSamplingRate) ||
1096 (format != inputDesc->mFormat) ||
1097 (channelMask != inputDesc->mChannelMask)) {
1098 ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1099 samplingRate, format, channelMask);
1100 if (input != 0) {
1101 mpClientInterface->closeInput(input);
1102 }
Eric Laurente552edb2014-03-10 17:42:56 -07001103 return 0;
1104 }
Eric Laurentd4692962014-05-05 18:13:44 -07001105 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001106 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001107 return input;
1108}
1109
Eric Laurente0720872014-03-11 09:30:41 -07001110status_t AudioPolicyManager::startInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001111{
1112 ALOGV("startInput() input %d", input);
1113 ssize_t index = mInputs.indexOfKey(input);
1114 if (index < 0) {
1115 ALOGW("startInput() unknown input %d", input);
1116 return BAD_VALUE;
1117 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001118 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001119
1120#ifdef AUDIO_POLICY_TEST
1121 if (mTestInput == 0)
1122#endif //AUDIO_POLICY_TEST
1123 {
1124 // refuse 2 active AudioRecord clients at the same time except if the active input
1125 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
1126 audio_io_handle_t activeInput = getActiveInput();
1127 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001128 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001129 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1130 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1131 stopInput(activeInput);
1132 releaseInput(activeInput);
1133 } else {
1134 ALOGW("startInput() input %d failed: other input already started", input);
1135 return INVALID_OPERATION;
1136 }
1137 }
1138 }
1139
Eric Laurent1c333e22014-05-20 10:48:17 -07001140 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001141
1142 // automatically enable the remote submix output when input is started
1143 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1144 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001145 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001146 }
1147
Eric Laurente552edb2014-03-10 17:42:56 -07001148 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1149
Eric Laurente552edb2014-03-10 17:42:56 -07001150 inputDesc->mRefCount = 1;
1151 return NO_ERROR;
1152}
1153
Eric Laurente0720872014-03-11 09:30:41 -07001154status_t AudioPolicyManager::stopInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001155{
1156 ALOGV("stopInput() input %d", input);
1157 ssize_t index = mInputs.indexOfKey(input);
1158 if (index < 0) {
1159 ALOGW("stopInput() unknown input %d", input);
1160 return BAD_VALUE;
1161 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001162 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001163
1164 if (inputDesc->mRefCount == 0) {
1165 ALOGW("stopInput() input %d already stopped", input);
1166 return INVALID_OPERATION;
1167 } else {
1168 // automatically disable the remote submix output when input is stopped
1169 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1170 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001171 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001172 }
1173
Eric Laurent1c333e22014-05-20 10:48:17 -07001174 resetInputDevice(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001175 inputDesc->mRefCount = 0;
1176 return NO_ERROR;
1177 }
1178}
1179
Eric Laurente0720872014-03-11 09:30:41 -07001180void AudioPolicyManager::releaseInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001181{
1182 ALOGV("releaseInput() %d", input);
1183 ssize_t index = mInputs.indexOfKey(input);
1184 if (index < 0) {
1185 ALOGW("releaseInput() releasing unknown input %d", input);
1186 return;
1187 }
1188 mpClientInterface->closeInput(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001189 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001190 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001191 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001192 ALOGV("releaseInput() exit");
1193}
1194
Eric Laurentd4692962014-05-05 18:13:44 -07001195void AudioPolicyManager::closeAllInputs() {
1196 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1197 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1198 }
1199 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001200 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001201}
1202
Eric Laurente0720872014-03-11 09:30:41 -07001203void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001204 int indexMin,
1205 int indexMax)
1206{
1207 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1208 if (indexMin < 0 || indexMin >= indexMax) {
1209 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1210 return;
1211 }
1212 mStreams[stream].mIndexMin = indexMin;
1213 mStreams[stream].mIndexMax = indexMax;
1214}
1215
Eric Laurente0720872014-03-11 09:30:41 -07001216status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001217 int index,
1218 audio_devices_t device)
1219{
1220
1221 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1222 return BAD_VALUE;
1223 }
1224 if (!audio_is_output_device(device)) {
1225 return BAD_VALUE;
1226 }
1227
1228 // Force max volume if stream cannot be muted
1229 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1230
1231 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1232 stream, device, index);
1233
1234 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1235 // clear all device specific values
1236 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1237 mStreams[stream].mIndexCur.clear();
1238 }
1239 mStreams[stream].mIndexCur.add(device, index);
1240
1241 // compute and apply stream volume on all outputs according to connected device
1242 status_t status = NO_ERROR;
1243 for (size_t i = 0; i < mOutputs.size(); i++) {
1244 audio_devices_t curDevice =
1245 getDeviceForVolume(mOutputs.valueAt(i)->device());
1246 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1247 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1248 if (volStatus != NO_ERROR) {
1249 status = volStatus;
1250 }
1251 }
1252 }
1253 return status;
1254}
1255
Eric Laurente0720872014-03-11 09:30:41 -07001256status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001257 int *index,
1258 audio_devices_t device)
1259{
1260 if (index == NULL) {
1261 return BAD_VALUE;
1262 }
1263 if (!audio_is_output_device(device)) {
1264 return BAD_VALUE;
1265 }
1266 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1267 // the strategy the stream belongs to.
1268 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1269 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1270 }
1271 device = getDeviceForVolume(device);
1272
1273 *index = mStreams[stream].getVolumeIndex(device);
1274 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1275 return NO_ERROR;
1276}
1277
Eric Laurente0720872014-03-11 09:30:41 -07001278audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001279 const SortedVector<audio_io_handle_t>& outputs)
1280{
1281 // select one output among several suitable for global effects.
1282 // The priority is as follows:
1283 // 1: An offloaded output. If the effect ends up not being offloadable,
1284 // AudioFlinger will invalidate the track and the offloaded output
1285 // will be closed causing the effect to be moved to a PCM output.
1286 // 2: A deep buffer output
1287 // 3: the first output in the list
1288
1289 if (outputs.size() == 0) {
1290 return 0;
1291 }
1292
1293 audio_io_handle_t outputOffloaded = 0;
1294 audio_io_handle_t outputDeepBuffer = 0;
1295
1296 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001297 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001298 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001299 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1300 outputOffloaded = outputs[i];
1301 }
1302 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1303 outputDeepBuffer = outputs[i];
1304 }
1305 }
1306
1307 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1308 outputOffloaded, outputDeepBuffer);
1309 if (outputOffloaded != 0) {
1310 return outputOffloaded;
1311 }
1312 if (outputDeepBuffer != 0) {
1313 return outputDeepBuffer;
1314 }
1315
1316 return outputs[0];
1317}
1318
Eric Laurente0720872014-03-11 09:30:41 -07001319audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001320{
1321 // apply simple rule where global effects are attached to the same output as MUSIC streams
1322
Eric Laurent3b73df72014-03-11 09:06:29 -07001323 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001324 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1325 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1326
1327 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1328 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1329 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1330
1331 return output;
1332}
1333
Eric Laurente0720872014-03-11 09:30:41 -07001334status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001335 audio_io_handle_t io,
1336 uint32_t strategy,
1337 int session,
1338 int id)
1339{
1340 ssize_t index = mOutputs.indexOfKey(io);
1341 if (index < 0) {
1342 index = mInputs.indexOfKey(io);
1343 if (index < 0) {
1344 ALOGW("registerEffect() unknown io %d", io);
1345 return INVALID_OPERATION;
1346 }
1347 }
1348
1349 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1350 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1351 desc->name, desc->memoryUsage);
1352 return INVALID_OPERATION;
1353 }
1354 mTotalEffectsMemory += desc->memoryUsage;
1355 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1356 desc->name, io, strategy, session, id);
1357 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1358
Eric Laurent1f2f2232014-06-02 12:01:23 -07001359 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1360 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1361 effectDesc->mIo = io;
1362 effectDesc->mStrategy = (routing_strategy)strategy;
1363 effectDesc->mSession = session;
1364 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001365
Eric Laurent1f2f2232014-06-02 12:01:23 -07001366 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001367
1368 return NO_ERROR;
1369}
1370
Eric Laurente0720872014-03-11 09:30:41 -07001371status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001372{
1373 ssize_t index = mEffects.indexOfKey(id);
1374 if (index < 0) {
1375 ALOGW("unregisterEffect() unknown effect ID %d", id);
1376 return INVALID_OPERATION;
1377 }
1378
Eric Laurent1f2f2232014-06-02 12:01:23 -07001379 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001380
Eric Laurent1f2f2232014-06-02 12:01:23 -07001381 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001382
Eric Laurent1f2f2232014-06-02 12:01:23 -07001383 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001384 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001385 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1386 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001387 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001388 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001389 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001390 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001391
1392 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001393
1394 return NO_ERROR;
1395}
1396
Eric Laurente0720872014-03-11 09:30:41 -07001397status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001398{
1399 ssize_t index = mEffects.indexOfKey(id);
1400 if (index < 0) {
1401 ALOGW("unregisterEffect() unknown effect ID %d", id);
1402 return INVALID_OPERATION;
1403 }
1404
1405 return setEffectEnabled(mEffects.valueAt(index), enabled);
1406}
1407
Eric Laurent1f2f2232014-06-02 12:01:23 -07001408status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001409{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001410 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001411 ALOGV("setEffectEnabled(%s) effect already %s",
1412 enabled?"true":"false", enabled?"enabled":"disabled");
1413 return INVALID_OPERATION;
1414 }
1415
1416 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001417 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001418 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001419 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001420 return INVALID_OPERATION;
1421 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001422 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001423 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1424 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001425 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001426 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001427 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1428 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001429 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001430 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001431 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1432 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001433 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001434 return NO_ERROR;
1435}
1436
Eric Laurente0720872014-03-11 09:30:41 -07001437bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001438{
1439 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001440 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1441 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1442 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001443 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001444 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001445 return true;
1446 }
1447 }
1448 return false;
1449}
1450
Eric Laurente0720872014-03-11 09:30:41 -07001451bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001452{
1453 nsecs_t sysTime = systemTime();
1454 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001455 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001456 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001457 return true;
1458 }
1459 }
1460 return false;
1461}
1462
Eric Laurente0720872014-03-11 09:30:41 -07001463bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001464 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001465{
1466 nsecs_t sysTime = systemTime();
1467 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001468 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001469 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001470 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001471 return true;
1472 }
1473 }
1474 return false;
1475}
1476
Eric Laurente0720872014-03-11 09:30:41 -07001477bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001478{
1479 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001480 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001481 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001482 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001483 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1484 && (inputDescriptor->mRefCount > 0)) {
1485 return true;
1486 }
1487 }
1488 return false;
1489}
1490
1491
Eric Laurente0720872014-03-11 09:30:41 -07001492status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001493{
1494 const size_t SIZE = 256;
1495 char buffer[SIZE];
1496 String8 result;
1497
1498 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1499 result.append(buffer);
1500
1501 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1502 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001503 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1504 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001505 snprintf(buffer, SIZE, " Force use for communications %d\n",
1506 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001507 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001508 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001509 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001510 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001511 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001512 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001513 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001514 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001515 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001516
Eric Laurent3a4311c2014-03-17 12:00:47 -07001517 snprintf(buffer, SIZE, " Available output devices:\n");
1518 result.append(buffer);
1519 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001520 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001521 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001522 }
1523 snprintf(buffer, SIZE, "\n Available input devices:\n");
1524 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001525 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001526 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001527 }
Eric Laurente552edb2014-03-10 17:42:56 -07001528
1529 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1530 write(fd, buffer, strlen(buffer));
1531 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001532 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001533 write(fd, buffer, strlen(buffer));
1534 mHwModules[i]->dump(fd);
1535 }
1536
1537 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1538 write(fd, buffer, strlen(buffer));
1539 for (size_t i = 0; i < mOutputs.size(); i++) {
1540 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1541 write(fd, buffer, strlen(buffer));
1542 mOutputs.valueAt(i)->dump(fd);
1543 }
1544
1545 snprintf(buffer, SIZE, "\nInputs dump:\n");
1546 write(fd, buffer, strlen(buffer));
1547 for (size_t i = 0; i < mInputs.size(); i++) {
1548 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1549 write(fd, buffer, strlen(buffer));
1550 mInputs.valueAt(i)->dump(fd);
1551 }
1552
1553 snprintf(buffer, SIZE, "\nStreams dump:\n");
1554 write(fd, buffer, strlen(buffer));
1555 snprintf(buffer, SIZE,
1556 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1557 write(fd, buffer, strlen(buffer));
Eric Laurent3b73df72014-03-11 09:06:29 -07001558 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001559 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001560 write(fd, buffer, strlen(buffer));
1561 mStreams[i].dump(fd);
1562 }
1563
1564 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1565 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1566 write(fd, buffer, strlen(buffer));
1567
1568 snprintf(buffer, SIZE, "Registered effects:\n");
1569 write(fd, buffer, strlen(buffer));
1570 for (size_t i = 0; i < mEffects.size(); i++) {
1571 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1572 write(fd, buffer, strlen(buffer));
1573 mEffects.valueAt(i)->dump(fd);
1574 }
1575
1576
1577 return NO_ERROR;
1578}
1579
1580// This function checks for the parameters which can be offloaded.
1581// This can be enhanced depending on the capability of the DSP and policy
1582// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001583bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001584{
1585 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001586 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001587 offloadInfo.sample_rate, offloadInfo.channel_mask,
1588 offloadInfo.format,
1589 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1590 offloadInfo.has_video);
1591
1592 // Check if offload has been disabled
1593 char propValue[PROPERTY_VALUE_MAX];
1594 if (property_get("audio.offload.disable", propValue, "0")) {
1595 if (atoi(propValue) != 0) {
1596 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1597 return false;
1598 }
1599 }
1600
1601 // Check if stream type is music, then only allow offload as of now.
1602 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1603 {
1604 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1605 return false;
1606 }
1607
1608 //TODO: enable audio offloading with video when ready
1609 if (offloadInfo.has_video)
1610 {
1611 ALOGV("isOffloadSupported: has_video == true, returning false");
1612 return false;
1613 }
1614
1615 //If duration is less than minimum value defined in property, return false
1616 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1617 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1618 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1619 return false;
1620 }
1621 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1622 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1623 return false;
1624 }
1625
1626 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1627 // creating an offloaded track and tearing it down immediately after start when audioflinger
1628 // detects there is an active non offloadable effect.
1629 // FIXME: We should check the audio session here but we do not have it in this context.
1630 // This may prevent offloading in rare situations where effects are left active by apps
1631 // in the background.
1632 if (isNonOffloadableEffectEnabled()) {
1633 return false;
1634 }
1635
1636 // See if there is a profile to support this.
1637 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001638 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001639 offloadInfo.sample_rate,
1640 offloadInfo.format,
1641 offloadInfo.channel_mask,
1642 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001643 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1644 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001645}
1646
Eric Laurent6a94d692014-05-20 11:18:06 -07001647status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1648 audio_port_type_t type,
1649 unsigned int *num_ports,
1650 struct audio_port *ports,
1651 unsigned int *generation)
1652{
1653 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1654 generation == NULL) {
1655 return BAD_VALUE;
1656 }
1657 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1658 if (ports == NULL) {
1659 *num_ports = 0;
1660 }
1661
1662 size_t portsWritten = 0;
1663 size_t portsMax = *num_ports;
1664 *num_ports = 0;
1665 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1666 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1667 for (size_t i = 0;
1668 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1669 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1670 }
1671 *num_ports += mAvailableOutputDevices.size();
1672 }
1673 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1674 for (size_t i = 0;
1675 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1676 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1677 }
1678 *num_ports += mAvailableInputDevices.size();
1679 }
1680 }
1681 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1682 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1683 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1684 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1685 }
1686 *num_ports += mInputs.size();
1687 }
1688 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1689 for (size_t i = 0; i < mOutputs.size() && portsWritten < portsMax; i++) {
1690 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1691 }
1692 *num_ports += mOutputs.size();
1693 }
1694 }
1695 *generation = curAudioPortGeneration();
1696 ALOGV("listAudioPorts() got %d ports needed %d", portsWritten, *num_ports);
1697 return NO_ERROR;
1698}
1699
1700status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1701{
1702 return NO_ERROR;
1703}
1704
Eric Laurent1f2f2232014-06-02 12:01:23 -07001705sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001706 audio_port_handle_t id) const
1707{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001708 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001709 for (size_t i = 0; i < mOutputs.size(); i++) {
1710 outputDesc = mOutputs.valueAt(i);
1711 if (outputDesc->mId == id) {
1712 break;
1713 }
1714 }
1715 return outputDesc;
1716}
1717
Eric Laurent1f2f2232014-06-02 12:01:23 -07001718sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001719 audio_port_handle_t id) const
1720{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001721 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001722 for (size_t i = 0; i < mInputs.size(); i++) {
1723 inputDesc = mInputs.valueAt(i);
1724 if (inputDesc->mId == id) {
1725 break;
1726 }
1727 }
1728 return inputDesc;
1729}
1730
Eric Laurent1f2f2232014-06-02 12:01:23 -07001731sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
1732 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07001733{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001734 sp <HwModule> module;
1735
Eric Laurent6a94d692014-05-20 11:18:06 -07001736 for (size_t i = 0; i < mHwModules.size(); i++) {
1737 if (mHwModules[i]->mHandle == 0) {
1738 continue;
1739 }
1740 if (audio_is_output_device(device)) {
1741 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1742 {
1743 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1744 return mHwModules[i];
1745 }
1746 }
1747 } else {
1748 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1749 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1750 device & ~AUDIO_DEVICE_BIT_IN) {
1751 return mHwModules[i];
1752 }
1753 }
1754 }
1755 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001756 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07001757}
1758
Eric Laurent1f2f2232014-06-02 12:01:23 -07001759sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07001760{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001761 sp <HwModule> module;
1762
Eric Laurent1afeecb2014-05-14 08:52:28 -07001763 for (size_t i = 0; i < mHwModules.size(); i++)
1764 {
1765 if (strcmp(mHwModules[i]->mName, name) == 0) {
1766 return mHwModules[i];
1767 }
1768 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001769 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07001770}
1771
1772
Eric Laurent6a94d692014-05-20 11:18:06 -07001773status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1774 audio_patch_handle_t *handle,
1775 uid_t uid)
1776{
1777 ALOGV("createAudioPatch()");
1778
1779 if (handle == NULL || patch == NULL) {
1780 return BAD_VALUE;
1781 }
1782 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1783
1784 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1785 return INVALID_OPERATION;
1786 }
1787 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1788 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1789 return INVALID_OPERATION;
1790 }
1791
1792 sp<AudioPatch> patchDesc;
1793 ssize_t index = mAudioPatches.indexOfKey(*handle);
1794
1795 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1796 patch->sinks[0].type);
1797 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1798 patch->sources[0].role,
1799 patch->sources[0].type);
1800
1801 if (index >= 0) {
1802 patchDesc = mAudioPatches.valueAt(index);
1803 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1804 mUidCached, patchDesc->mUid, uid);
1805 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1806 return INVALID_OPERATION;
1807 }
1808 } else {
1809 *handle = 0;
1810 }
1811
1812 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1813 // TODO add support for mix to mix connection
1814 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1815 ALOGV("createAudioPatch() source mix sink not device");
1816 return BAD_VALUE;
1817 }
1818 // output mix to output device connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001819 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001820 if (outputDesc == NULL) {
1821 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1822 return BAD_VALUE;
1823 }
1824 if (patchDesc != 0) {
1825 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1826 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1827 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1828 return BAD_VALUE;
1829 }
1830 }
1831 sp<DeviceDescriptor> devDesc =
1832 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1833 if (devDesc == 0) {
1834 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1835 return BAD_VALUE;
1836 }
1837
1838 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mType,
1839 patch->sources[0].sample_rate,
1840 patch->sources[0].format,
1841 patch->sources[0].channel_mask,
1842 AUDIO_OUTPUT_FLAG_NONE)) {
1843 return INVALID_OPERATION;
1844 }
1845 // TODO: reconfigure output format and channels here
1846 ALOGV("createAudioPatch() setting device %08x on output %d",
1847 devDesc->mType, outputDesc->mIoHandle);
1848 setOutputDevice(outputDesc->mIoHandle,
1849 devDesc->mType,
1850 true,
1851 0,
1852 handle);
1853 index = mAudioPatches.indexOfKey(*handle);
1854 if (index >= 0) {
1855 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1856 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1857 }
1858 patchDesc = mAudioPatches.valueAt(index);
1859 patchDesc->mUid = uid;
1860 ALOGV("createAudioPatch() success");
1861 } else {
1862 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1863 return INVALID_OPERATION;
1864 }
1865 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1866 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1867 // input device to input mix connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001868 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001869 if (inputDesc == NULL) {
1870 return BAD_VALUE;
1871 }
1872 if (patchDesc != 0) {
1873 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1874 return BAD_VALUE;
1875 }
1876 }
1877 sp<DeviceDescriptor> devDesc =
1878 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1879 if (devDesc == 0) {
1880 return BAD_VALUE;
1881 }
1882
1883 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mType,
1884 patch->sinks[0].sample_rate,
1885 patch->sinks[0].format,
1886 patch->sinks[0].channel_mask,
1887 AUDIO_OUTPUT_FLAG_NONE)) {
1888 return INVALID_OPERATION;
1889 }
1890 // TODO: reconfigure output format and channels here
1891 ALOGV("createAudioPatch() setting device %08x on output %d",
1892 devDesc->mType, inputDesc->mIoHandle);
1893 setInputDevice(inputDesc->mIoHandle,
1894 devDesc->mType,
1895 true,
1896 handle);
1897 index = mAudioPatches.indexOfKey(*handle);
1898 if (index >= 0) {
1899 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1900 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
1901 }
1902 patchDesc = mAudioPatches.valueAt(index);
1903 patchDesc->mUid = uid;
1904 ALOGV("createAudioPatch() success");
1905 } else {
1906 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
1907 return INVALID_OPERATION;
1908 }
1909 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
1910 // device to device connection
1911 if (patchDesc != 0) {
1912 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
1913 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1914 return BAD_VALUE;
1915 }
1916 }
1917
1918 sp<DeviceDescriptor> srcDeviceDesc =
1919 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1920 sp<DeviceDescriptor> sinkDeviceDesc =
1921 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1922 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
1923 return BAD_VALUE;
1924 }
1925 //update source and sink with our own data as the data passed in the patch may
1926 // be incomplete.
1927 struct audio_patch newPatch = *patch;
1928 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
1929 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
1930
1931 // TODO: add support for devices on different HW modules
1932 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
1933 return INVALID_OPERATION;
1934 }
1935 // TODO: check from routing capabilities in config file and other conflicting patches
1936
1937 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
1938 if (index >= 0) {
1939 afPatchHandle = patchDesc->mAfPatchHandle;
1940 }
1941
1942 status_t status = mpClientInterface->createAudioPatch(&newPatch,
1943 &afPatchHandle,
1944 0);
1945 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
1946 status, afPatchHandle);
1947 if (status == NO_ERROR) {
1948 if (index < 0) {
1949 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
1950 &newPatch, uid);
1951 addAudioPatch(patchDesc->mHandle, patchDesc);
1952 } else {
1953 patchDesc->mPatch = newPatch;
1954 }
1955 patchDesc->mAfPatchHandle = afPatchHandle;
1956 *handle = patchDesc->mHandle;
1957 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001958 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07001959 } else {
1960 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
1961 status);
1962 return INVALID_OPERATION;
1963 }
1964 } else {
1965 return BAD_VALUE;
1966 }
1967 } else {
1968 return BAD_VALUE;
1969 }
1970 return NO_ERROR;
1971}
1972
1973status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
1974 uid_t uid)
1975{
1976 ALOGV("releaseAudioPatch() patch %d", handle);
1977
1978 ssize_t index = mAudioPatches.indexOfKey(handle);
1979
1980 if (index < 0) {
1981 return BAD_VALUE;
1982 }
1983 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
1984 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1985 mUidCached, patchDesc->mUid, uid);
1986 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1987 return INVALID_OPERATION;
1988 }
1989
1990 struct audio_patch *patch = &patchDesc->mPatch;
1991 patchDesc->mUid = mUidCached;
1992 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001993 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001994 if (outputDesc == NULL) {
1995 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
1996 return BAD_VALUE;
1997 }
1998
1999 setOutputDevice(outputDesc->mIoHandle,
2000 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2001 true,
2002 0,
2003 NULL);
2004 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2005 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002006 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002007 if (inputDesc == NULL) {
2008 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2009 return BAD_VALUE;
2010 }
2011 setInputDevice(inputDesc->mIoHandle,
2012 getNewInputDevice(inputDesc->mIoHandle),
2013 true,
2014 NULL);
2015 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2016 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2017 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2018 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2019 status, patchDesc->mAfPatchHandle);
2020 removeAudioPatch(patchDesc->mHandle);
2021 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002022 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002023 } else {
2024 return BAD_VALUE;
2025 }
2026 } else {
2027 return BAD_VALUE;
2028 }
2029 return NO_ERROR;
2030}
2031
2032status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2033 struct audio_patch *patches,
2034 unsigned int *generation)
2035{
2036 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2037 generation == NULL) {
2038 return BAD_VALUE;
2039 }
2040 ALOGV("listAudioPatches() num_patches %d patches %p available patches %d",
2041 *num_patches, patches, mAudioPatches.size());
2042 if (patches == NULL) {
2043 *num_patches = 0;
2044 }
2045
2046 size_t patchesWritten = 0;
2047 size_t patchesMax = *num_patches;
2048 for (size_t i = 0;
2049 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2050 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2051 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
2052 ALOGV("listAudioPatches() patch %d num_sources %d num_sinks %d",
2053 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2054 }
2055 *num_patches = mAudioPatches.size();
2056
2057 *generation = curAudioPortGeneration();
2058 ALOGV("listAudioPatches() got %d patches needed %d", patchesWritten, *num_patches);
2059 return NO_ERROR;
2060}
2061
Eric Laurente1715a42014-05-20 11:30:42 -07002062status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002063{
Eric Laurente1715a42014-05-20 11:30:42 -07002064 ALOGV("setAudioPortConfig()");
2065
2066 if (config == NULL) {
2067 return BAD_VALUE;
2068 }
2069 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2070 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002071 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2072 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002073 }
2074
Eric Laurenta121f902014-06-03 13:32:54 -07002075 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002076 if (config->type == AUDIO_PORT_TYPE_MIX) {
2077 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002078 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002079 if (outputDesc == NULL) {
2080 return BAD_VALUE;
2081 }
Eric Laurenta121f902014-06-03 13:32:54 -07002082 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002083 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002084 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002085 if (inputDesc == NULL) {
2086 return BAD_VALUE;
2087 }
Eric Laurenta121f902014-06-03 13:32:54 -07002088 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002089 } else {
2090 return BAD_VALUE;
2091 }
2092 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2093 sp<DeviceDescriptor> deviceDesc;
2094 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2095 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2096 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2097 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2098 } else {
2099 return BAD_VALUE;
2100 }
2101 if (deviceDesc == NULL) {
2102 return BAD_VALUE;
2103 }
Eric Laurenta121f902014-06-03 13:32:54 -07002104 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002105 } else {
2106 return BAD_VALUE;
2107 }
2108
Eric Laurenta121f902014-06-03 13:32:54 -07002109 struct audio_port_config backupConfig;
2110 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2111 if (status == NO_ERROR) {
2112 struct audio_port_config newConfig;
2113 audioPortConfig->toAudioPortConfig(&newConfig, config);
2114 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002115 }
Eric Laurenta121f902014-06-03 13:32:54 -07002116 if (status != NO_ERROR) {
2117 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002118 }
Eric Laurente1715a42014-05-20 11:30:42 -07002119
2120 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002121}
2122
2123void AudioPolicyManager::clearAudioPatches(uid_t uid)
2124{
2125 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2126 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2127 if (patchDesc->mUid == uid) {
2128 // releaseAudioPatch() removes the patch from mAudioPatches
2129 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2130 i--;
2131 }
2132 }
2133 }
2134}
2135
2136status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2137 const sp<AudioPatch>& patch)
2138{
2139 ssize_t index = mAudioPatches.indexOfKey(handle);
2140
2141 if (index >= 0) {
2142 ALOGW("addAudioPatch() patch %d already in", handle);
2143 return ALREADY_EXISTS;
2144 }
2145 mAudioPatches.add(handle, patch);
2146 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2147 "sink handle %d",
2148 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2149 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2150 return NO_ERROR;
2151}
2152
2153status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2154{
2155 ssize_t index = mAudioPatches.indexOfKey(handle);
2156
2157 if (index < 0) {
2158 ALOGW("removeAudioPatch() patch %d not in", handle);
2159 return ALREADY_EXISTS;
2160 }
2161 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2162 mAudioPatches.valueAt(index)->mAfPatchHandle);
2163 mAudioPatches.removeItemsAt(index);
2164 return NO_ERROR;
2165}
2166
Eric Laurente552edb2014-03-10 17:42:56 -07002167// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002168// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002169// ----------------------------------------------------------------------------
2170
Eric Laurent3a4311c2014-03-17 12:00:47 -07002171uint32_t AudioPolicyManager::nextUniqueId()
2172{
2173 return android_atomic_inc(&mNextUniqueId);
2174}
2175
Eric Laurent6a94d692014-05-20 11:18:06 -07002176uint32_t AudioPolicyManager::nextAudioPortGeneration()
2177{
2178 return android_atomic_inc(&mAudioPortGeneration);
2179}
2180
Eric Laurente0720872014-03-11 09:30:41 -07002181AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002182 :
2183#ifdef AUDIO_POLICY_TEST
2184 Thread(false),
2185#endif //AUDIO_POLICY_TEST
2186 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002187 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002188 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2189 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002190 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002191 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2192 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002193{
Eric Laurent6a94d692014-05-20 11:18:06 -07002194 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002195 mpClientInterface = clientInterface;
2196
Eric Laurent3b73df72014-03-11 09:06:29 -07002197 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2198 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002199 }
2200
Eric Laurent1afeecb2014-05-14 08:52:28 -07002201 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002202 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2203 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2204 ALOGE("could not load audio policy configuration file, setting defaults");
2205 defaultAudioPolicyConfig();
2206 }
2207 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002208 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002209
2210 // must be done after reading the policy
2211 initializeVolumeCurves();
2212
2213 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002214 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2215 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002216 for (size_t i = 0; i < mHwModules.size(); i++) {
2217 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2218 if (mHwModules[i]->mHandle == 0) {
2219 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2220 continue;
2221 }
2222 // open all output streams needed to access attached devices
2223 // except for direct output streams that are only opened when they are actually
2224 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002225 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002226 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2227 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002228 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002229
Eric Laurent3a4311c2014-03-17 12:00:47 -07002230 if (outProfile->mSupportedDevices.isEmpty()) {
2231 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2232 continue;
2233 }
2234
2235 audio_devices_t profileTypes = outProfile->mSupportedDevices.types();
2236 if ((profileTypes & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002237 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002238 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002239
Eric Laurent1c333e22014-05-20 10:48:17 -07002240 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice->mDeviceType & profileTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002241 audio_io_handle_t output = mpClientInterface->openOutput(
2242 outProfile->mModule->mHandle,
2243 &outputDesc->mDevice,
2244 &outputDesc->mSamplingRate,
2245 &outputDesc->mFormat,
2246 &outputDesc->mChannelMask,
2247 &outputDesc->mLatency,
2248 outputDesc->mFlags);
2249 if (output == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002250 ALOGW("Cannot open output stream for device %08x on hw module %s",
2251 outputDesc->mDevice,
2252 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002253 } else {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002254 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002255 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002256 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002257 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002258 // give a valid ID to an attached device once confirmed it is reachable
2259 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2260 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002261 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002262 }
2263 }
Eric Laurente552edb2014-03-10 17:42:56 -07002264 if (mPrimaryOutput == 0 &&
2265 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2266 mPrimaryOutput = output;
2267 }
2268 addOutput(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002269 ALOGI("CSTOR setOutputDevice %08x", outputDesc->mDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07002270 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002271 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002272 true);
2273 }
2274 }
2275 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002276 // open input streams needed to access attached devices to validate
2277 // mAvailableInputDevices list
2278 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2279 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002280 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002281
Eric Laurent3a4311c2014-03-17 12:00:47 -07002282 if (inProfile->mSupportedDevices.isEmpty()) {
2283 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2284 continue;
2285 }
2286
2287 audio_devices_t profileTypes = inProfile->mSupportedDevices.types();
2288 if (profileTypes & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002289 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002290
2291 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent1c333e22014-05-20 10:48:17 -07002292 inputDesc->mDevice = inProfile->mSupportedDevices[0]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002293 audio_io_handle_t input = mpClientInterface->openInput(
2294 inProfile->mModule->mHandle,
2295 &inputDesc->mDevice,
2296 &inputDesc->mSamplingRate,
2297 &inputDesc->mFormat,
2298 &inputDesc->mChannelMask);
2299
2300 if (input != 0) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002301 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002302 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002303 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002304 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002305 // give a valid ID to an attached device once confirmed it is reachable
2306 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2307 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002308 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002309 }
2310 }
2311 mpClientInterface->closeInput(input);
2312 } else {
2313 ALOGW("Cannot open input stream for device %08x on hw module %s",
2314 inputDesc->mDevice,
2315 mHwModules[i]->mName);
2316 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002317 }
2318 }
2319 }
2320 // make sure all attached devices have been allocated a unique ID
2321 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2322 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002323 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002324 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2325 continue;
2326 }
2327 i++;
2328 }
2329 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2330 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002331 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002332 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2333 continue;
2334 }
2335 i++;
2336 }
2337 // make sure default device is reachable
2338 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002339 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002340 }
Eric Laurente552edb2014-03-10 17:42:56 -07002341
2342 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2343
2344 updateDevicesAndOutputs();
2345
2346#ifdef AUDIO_POLICY_TEST
2347 if (mPrimaryOutput != 0) {
2348 AudioParameter outputCmd = AudioParameter();
2349 outputCmd.addInt(String8("set_id"), 0);
2350 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2351
2352 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2353 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002354 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2355 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002356 mTestLatencyMs = 0;
2357 mCurOutput = 0;
2358 mDirectOutput = false;
2359 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2360 mTestOutputs[i] = 0;
2361 }
2362
2363 const size_t SIZE = 256;
2364 char buffer[SIZE];
2365 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2366 run(buffer, ANDROID_PRIORITY_AUDIO);
2367 }
2368#endif //AUDIO_POLICY_TEST
2369}
2370
Eric Laurente0720872014-03-11 09:30:41 -07002371AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002372{
2373#ifdef AUDIO_POLICY_TEST
2374 exit();
2375#endif //AUDIO_POLICY_TEST
2376 for (size_t i = 0; i < mOutputs.size(); i++) {
2377 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002378 }
2379 for (size_t i = 0; i < mInputs.size(); i++) {
2380 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002381 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002382 mAvailableOutputDevices.clear();
2383 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002384 mOutputs.clear();
2385 mInputs.clear();
2386 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002387}
2388
Eric Laurente0720872014-03-11 09:30:41 -07002389status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002390{
2391 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2392}
2393
2394#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002395bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002396{
2397 ALOGV("entering threadLoop()");
2398 while (!exitPending())
2399 {
2400 String8 command;
2401 int valueInt;
2402 String8 value;
2403
2404 Mutex::Autolock _l(mLock);
2405 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2406
2407 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2408 AudioParameter param = AudioParameter(command);
2409
2410 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2411 valueInt != 0) {
2412 ALOGV("Test command %s received", command.string());
2413 String8 target;
2414 if (param.get(String8("target"), target) != NO_ERROR) {
2415 target = "Manager";
2416 }
2417 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2418 param.remove(String8("test_cmd_policy_output"));
2419 mCurOutput = valueInt;
2420 }
2421 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2422 param.remove(String8("test_cmd_policy_direct"));
2423 if (value == "false") {
2424 mDirectOutput = false;
2425 } else if (value == "true") {
2426 mDirectOutput = true;
2427 }
2428 }
2429 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2430 param.remove(String8("test_cmd_policy_input"));
2431 mTestInput = valueInt;
2432 }
2433
2434 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2435 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002436 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002437 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002438 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002439 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002440 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002441 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002442 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002443 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002444 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002445 if (target == "Manager") {
2446 mTestFormat = format;
2447 } else if (mTestOutputs[mCurOutput] != 0) {
2448 AudioParameter outputParam = AudioParameter();
2449 outputParam.addInt(String8("format"), format);
2450 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2451 }
2452 }
2453 }
2454 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2455 param.remove(String8("test_cmd_policy_channels"));
2456 int channels = 0;
2457
2458 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002459 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002460 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002461 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002462 }
2463 if (channels != 0) {
2464 if (target == "Manager") {
2465 mTestChannels = channels;
2466 } else if (mTestOutputs[mCurOutput] != 0) {
2467 AudioParameter outputParam = AudioParameter();
2468 outputParam.addInt(String8("channels"), channels);
2469 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2470 }
2471 }
2472 }
2473 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2474 param.remove(String8("test_cmd_policy_sampleRate"));
2475 if (valueInt >= 0 && valueInt <= 96000) {
2476 int samplingRate = valueInt;
2477 if (target == "Manager") {
2478 mTestSamplingRate = samplingRate;
2479 } else if (mTestOutputs[mCurOutput] != 0) {
2480 AudioParameter outputParam = AudioParameter();
2481 outputParam.addInt(String8("sampling_rate"), samplingRate);
2482 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2483 }
2484 }
2485 }
2486
2487 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2488 param.remove(String8("test_cmd_policy_reopen"));
2489
Eric Laurent1f2f2232014-06-02 12:01:23 -07002490 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002491 mpClientInterface->closeOutput(mPrimaryOutput);
2492
2493 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2494
Eric Laurente552edb2014-03-10 17:42:56 -07002495 mOutputs.removeItem(mPrimaryOutput);
2496
Eric Laurent1f2f2232014-06-02 12:01:23 -07002497 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002498 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
2499 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
2500 &outputDesc->mDevice,
2501 &outputDesc->mSamplingRate,
2502 &outputDesc->mFormat,
2503 &outputDesc->mChannelMask,
2504 &outputDesc->mLatency,
2505 outputDesc->mFlags);
2506 if (mPrimaryOutput == 0) {
2507 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
2508 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
2509 } else {
2510 AudioParameter outputCmd = AudioParameter();
2511 outputCmd.addInt(String8("set_id"), 0);
2512 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2513 addOutput(mPrimaryOutput, outputDesc);
2514 }
2515 }
2516
2517
2518 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2519 }
2520 }
2521 return false;
2522}
2523
Eric Laurente0720872014-03-11 09:30:41 -07002524void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002525{
2526 {
2527 AutoMutex _l(mLock);
2528 requestExit();
2529 mWaitWorkCV.signal();
2530 }
2531 requestExitAndWait();
2532}
2533
Eric Laurente0720872014-03-11 09:30:41 -07002534int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002535{
2536 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2537 if (output == mTestOutputs[i]) return i;
2538 }
2539 return 0;
2540}
2541#endif //AUDIO_POLICY_TEST
2542
2543// ---
2544
Eric Laurent1f2f2232014-06-02 12:01:23 -07002545void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002546{
Eric Laurent1c333e22014-05-20 10:48:17 -07002547 outputDesc->mIoHandle = output;
2548 outputDesc->mId = nextUniqueId();
2549 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002550 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002551}
2552
Eric Laurent1f2f2232014-06-02 12:01:23 -07002553void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002554{
Eric Laurent1c333e22014-05-20 10:48:17 -07002555 inputDesc->mIoHandle = input;
2556 inputDesc->mId = nextUniqueId();
2557 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002558 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002559}
Eric Laurente552edb2014-03-10 17:42:56 -07002560
Eric Laurent3a4311c2014-03-17 12:00:47 -07002561String8 AudioPolicyManager::addressToParameter(audio_devices_t device, const String8 address)
2562{
2563 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
2564 return String8("a2dp_sink_address=")+address;
2565 }
2566 return address;
2567}
2568
Eric Laurente0720872014-03-11 09:30:41 -07002569status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002570 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002571 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002572 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002573{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002574 sp<AudioOutputDescriptor> desc;
Eric Laurente552edb2014-03-10 17:42:56 -07002575
Eric Laurent3b73df72014-03-11 09:06:29 -07002576 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002577 // first list already open outputs that can be routed to this device
2578 for (size_t i = 0; i < mOutputs.size(); i++) {
2579 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002580 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002581 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2582 outputs.add(mOutputs.keyAt(i));
2583 }
2584 }
2585 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002586 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002587 for (size_t i = 0; i < mHwModules.size(); i++)
2588 {
2589 if (mHwModules[i]->mHandle == 0) {
2590 continue;
2591 }
2592 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2593 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002594 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002595 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002596 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2597 }
2598 }
2599 }
2600
2601 if (profiles.isEmpty() && outputs.isEmpty()) {
2602 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2603 return BAD_VALUE;
2604 }
2605
2606 // open outputs for matching profiles if needed. Direct outputs are also opened to
2607 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2608 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002609 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002610
2611 // nothing to do if one output is already opened for this profile
2612 size_t j;
2613 for (j = 0; j < mOutputs.size(); j++) {
2614 desc = mOutputs.valueAt(j);
2615 if (!desc->isDuplicated() && desc->mProfile == profile) {
2616 break;
2617 }
2618 }
2619 if (j != mOutputs.size()) {
2620 continue;
2621 }
2622
Eric Laurent3a4311c2014-03-17 12:00:47 -07002623 ALOGV("opening output for device %08x with params %s", device, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -07002624 desc = new AudioOutputDescriptor(profile);
2625 desc->mDevice = device;
2626 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
2627 offloadInfo.sample_rate = desc->mSamplingRate;
2628 offloadInfo.format = desc->mFormat;
2629 offloadInfo.channel_mask = desc->mChannelMask;
2630
2631 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
2632 &desc->mDevice,
2633 &desc->mSamplingRate,
2634 &desc->mFormat,
2635 &desc->mChannelMask,
2636 &desc->mLatency,
2637 desc->mFlags,
2638 &offloadInfo);
2639 if (output != 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002640 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002641 if (!address.isEmpty()) {
2642 mpClientInterface->setParameters(output, addressToParameter(device, address));
Eric Laurente552edb2014-03-10 17:42:56 -07002643 }
2644
Eric Laurentd4692962014-05-05 18:13:44 -07002645 // Here is where we step through and resolve any "dynamic" fields
2646 String8 reply;
2647 char *value;
2648 if (profile->mSamplingRates[0] == 0) {
2649 reply = mpClientInterface->getParameters(output,
2650 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2651 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
2652 reply.string());
2653 value = strpbrk((char *)reply.string(), "=");
2654 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002655 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002656 }
Eric Laurentd4692962014-05-05 18:13:44 -07002657 }
2658 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2659 reply = mpClientInterface->getParameters(output,
2660 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2661 ALOGV("checkOutputsForDevice() direct output sup formats %s",
2662 reply.string());
2663 value = strpbrk((char *)reply.string(), "=");
2664 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002665 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002666 }
Eric Laurentd4692962014-05-05 18:13:44 -07002667 }
2668 if (profile->mChannelMasks[0] == 0) {
2669 reply = mpClientInterface->getParameters(output,
2670 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2671 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
2672 reply.string());
2673 value = strpbrk((char *)reply.string(), "=");
2674 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002675 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002676 }
Eric Laurentd4692962014-05-05 18:13:44 -07002677 }
2678 if (((profile->mSamplingRates[0] == 0) &&
2679 (profile->mSamplingRates.size() < 2)) ||
2680 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2681 (profile->mFormats.size() < 2)) ||
2682 ((profile->mChannelMasks[0] == 0) &&
2683 (profile->mChannelMasks.size() < 2))) {
2684 ALOGW("checkOutputsForDevice() direct output missing param");
2685 mpClientInterface->closeOutput(output);
2686 output = 0;
2687 } else if (profile->mSamplingRates[0] == 0) {
2688 mpClientInterface->closeOutput(output);
2689 desc->mSamplingRate = profile->mSamplingRates[1];
2690 offloadInfo.sample_rate = desc->mSamplingRate;
2691 output = mpClientInterface->openOutput(
2692 profile->mModule->mHandle,
2693 &desc->mDevice,
2694 &desc->mSamplingRate,
2695 &desc->mFormat,
2696 &desc->mChannelMask,
2697 &desc->mLatency,
2698 desc->mFlags,
2699 &offloadInfo);
2700 }
2701
2702 if (output != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002703 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002704 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
2705 audio_io_handle_t duplicatedOutput = 0;
Eric Laurente552edb2014-03-10 17:42:56 -07002706
Eric Laurentd4692962014-05-05 18:13:44 -07002707 // set initial stream volume for device
2708 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002709
Eric Laurentd4692962014-05-05 18:13:44 -07002710 //TODO: configure audio effect output stage here
2711
2712 // open a duplicating output thread for the new output and the primary output
2713 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2714 mPrimaryOutput);
2715 if (duplicatedOutput != 0) {
2716 // add duplicated output descriptor
Eric Laurent1f2f2232014-06-02 12:01:23 -07002717 sp<AudioOutputDescriptor> dupOutputDesc = new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07002718 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2719 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2720 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2721 dupOutputDesc->mFormat = desc->mFormat;
2722 dupOutputDesc->mChannelMask = desc->mChannelMask;
2723 dupOutputDesc->mLatency = desc->mLatency;
2724 addOutput(duplicatedOutput, dupOutputDesc);
2725 applyStreamVolumes(duplicatedOutput, device, 0, true);
2726 } else {
2727 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2728 mPrimaryOutput, output);
2729 mpClientInterface->closeOutput(output);
2730 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002731 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002732 output = 0;
2733 }
Eric Laurente552edb2014-03-10 17:42:56 -07002734 }
2735 }
2736 }
2737 if (output == 0) {
2738 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07002739 profiles.removeAt(profile_index);
2740 profile_index--;
2741 } else {
2742 outputs.add(output);
2743 ALOGV("checkOutputsForDevice(): adding output %d", output);
2744 }
2745 }
2746
2747 if (profiles.isEmpty()) {
2748 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2749 return BAD_VALUE;
2750 }
Eric Laurentd4692962014-05-05 18:13:44 -07002751 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07002752 // check if one opened output is not needed any more after disconnecting one device
2753 for (size_t i = 0; i < mOutputs.size(); i++) {
2754 desc = mOutputs.valueAt(i);
2755 if (!desc->isDuplicated() &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07002756 !(desc->mProfile->mSupportedDevices.types() &
2757 mAvailableOutputDevices.types())) {
Eric Laurente552edb2014-03-10 17:42:56 -07002758 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
2759 outputs.add(mOutputs.keyAt(i));
2760 }
2761 }
Eric Laurentd4692962014-05-05 18:13:44 -07002762 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002763 for (size_t i = 0; i < mHwModules.size(); i++)
2764 {
2765 if (mHwModules[i]->mHandle == 0) {
2766 continue;
2767 }
2768 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2769 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002770 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07002771 if (profile->mSupportedDevices.types() & device) {
2772 ALOGV("checkOutputsForDevice(): "
2773 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002774 if (profile->mSamplingRates[0] == 0) {
2775 profile->mSamplingRates.clear();
2776 profile->mSamplingRates.add(0);
2777 }
2778 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2779 profile->mFormats.clear();
2780 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2781 }
2782 if (profile->mChannelMasks[0] == 0) {
2783 profile->mChannelMasks.clear();
2784 profile->mChannelMasks.add(0);
2785 }
2786 }
2787 }
2788 }
2789 }
2790 return NO_ERROR;
2791}
2792
Eric Laurentd4692962014-05-05 18:13:44 -07002793status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
2794 audio_policy_dev_state_t state,
2795 SortedVector<audio_io_handle_t>& inputs,
2796 const String8 address)
2797{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002798 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07002799 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2800 // first list already open inputs that can be routed to this device
2801 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2802 desc = mInputs.valueAt(input_index);
2803 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
2804 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
2805 inputs.add(mInputs.keyAt(input_index));
2806 }
2807 }
2808
2809 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002810 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07002811 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
2812 {
2813 if (mHwModules[module_idx]->mHandle == 0) {
2814 continue;
2815 }
2816 for (size_t profile_index = 0;
2817 profile_index < mHwModules[module_idx]->mInputProfiles.size();
2818 profile_index++)
2819 {
2820 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
2821 & (device & ~AUDIO_DEVICE_BIT_IN)) {
2822 ALOGV("checkInputsForDevice(): adding profile %d from module %d",
2823 profile_index, module_idx);
2824 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
2825 }
2826 }
2827 }
2828
2829 if (profiles.isEmpty() && inputs.isEmpty()) {
2830 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2831 return BAD_VALUE;
2832 }
2833
2834 // open inputs for matching profiles if needed. Direct inputs are also opened to
2835 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2836 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2837
Eric Laurent1c333e22014-05-20 10:48:17 -07002838 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002839 // nothing to do if one input is already opened for this profile
2840 size_t input_index;
2841 for (input_index = 0; input_index < mInputs.size(); input_index++) {
2842 desc = mInputs.valueAt(input_index);
2843 if (desc->mProfile == profile) {
2844 break;
2845 }
2846 }
2847 if (input_index != mInputs.size()) {
2848 continue;
2849 }
2850
2851 ALOGV("opening input for device 0x%X with params %s", device, address.string());
2852 desc = new AudioInputDescriptor(profile);
2853 desc->mDevice = device;
2854
2855 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
2856 &desc->mDevice,
2857 &desc->mSamplingRate,
2858 &desc->mFormat,
2859 &desc->mChannelMask);
2860
2861 if (input != 0) {
2862 if (!address.isEmpty()) {
2863 mpClientInterface->setParameters(input, addressToParameter(device, address));
2864 }
2865
2866 // Here is where we step through and resolve any "dynamic" fields
2867 String8 reply;
2868 char *value;
2869 if (profile->mSamplingRates[0] == 0) {
2870 reply = mpClientInterface->getParameters(input,
2871 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2872 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
2873 reply.string());
2874 value = strpbrk((char *)reply.string(), "=");
2875 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002876 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002877 }
2878 }
2879 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2880 reply = mpClientInterface->getParameters(input,
2881 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2882 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
2883 value = strpbrk((char *)reply.string(), "=");
2884 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002885 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002886 }
2887 }
2888 if (profile->mChannelMasks[0] == 0) {
2889 reply = mpClientInterface->getParameters(input,
2890 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2891 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
2892 reply.string());
2893 value = strpbrk((char *)reply.string(), "=");
2894 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002895 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07002896 }
2897 }
2898 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
2899 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
2900 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
2901 ALOGW("checkInputsForDevice() direct input missing param");
2902 mpClientInterface->closeInput(input);
2903 input = 0;
2904 }
2905
2906 if (input != 0) {
2907 addInput(input, desc);
2908 }
2909 } // endif input != 0
2910
2911 if (input == 0) {
2912 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07002913 profiles.removeAt(profile_index);
2914 profile_index--;
2915 } else {
2916 inputs.add(input);
2917 ALOGV("checkInputsForDevice(): adding input %d", input);
2918 }
2919 } // end scan profiles
2920
2921 if (profiles.isEmpty()) {
2922 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2923 return BAD_VALUE;
2924 }
2925 } else {
2926 // Disconnect
2927 // check if one opened input is not needed any more after disconnecting one device
2928 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2929 desc = mInputs.valueAt(input_index);
2930 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
2931 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
2932 mInputs.keyAt(input_index));
2933 inputs.add(mInputs.keyAt(input_index));
2934 }
2935 }
2936 // Clear any profiles associated with the disconnected device.
2937 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
2938 if (mHwModules[module_index]->mHandle == 0) {
2939 continue;
2940 }
2941 for (size_t profile_index = 0;
2942 profile_index < mHwModules[module_index]->mInputProfiles.size();
2943 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002944 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07002945 if (profile->mSupportedDevices.types() & device) {
2946 ALOGV("checkInputsForDevice(): clearing direct input profile %d on module %d",
2947 profile_index, module_index);
2948 if (profile->mSamplingRates[0] == 0) {
2949 profile->mSamplingRates.clear();
2950 profile->mSamplingRates.add(0);
2951 }
2952 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2953 profile->mFormats.clear();
2954 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2955 }
2956 if (profile->mChannelMasks[0] == 0) {
2957 profile->mChannelMasks.clear();
2958 profile->mChannelMasks.add(0);
2959 }
2960 }
2961 }
2962 }
2963 } // end disconnect
2964
2965 return NO_ERROR;
2966}
2967
2968
Eric Laurente0720872014-03-11 09:30:41 -07002969void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002970{
2971 ALOGV("closeOutput(%d)", output);
2972
Eric Laurent1f2f2232014-06-02 12:01:23 -07002973 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07002974 if (outputDesc == NULL) {
2975 ALOGW("closeOutput() unknown output %d", output);
2976 return;
2977 }
2978
2979 // look for duplicated outputs connected to the output being removed.
2980 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002981 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002982 if (dupOutputDesc->isDuplicated() &&
2983 (dupOutputDesc->mOutput1 == outputDesc ||
2984 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002985 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07002986 if (dupOutputDesc->mOutput1 == outputDesc) {
2987 outputDesc2 = dupOutputDesc->mOutput2;
2988 } else {
2989 outputDesc2 = dupOutputDesc->mOutput1;
2990 }
2991 // As all active tracks on duplicated output will be deleted,
2992 // and as they were also referenced on the other output, the reference
2993 // count for their stream type must be adjusted accordingly on
2994 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07002995 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07002996 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07002997 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07002998 }
2999 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3000 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3001
3002 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003003 mOutputs.removeItem(duplicatedOutput);
3004 }
3005 }
3006
3007 AudioParameter param;
3008 param.add(String8("closing"), String8("true"));
3009 mpClientInterface->setParameters(output, param.toString());
3010
3011 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003012 mOutputs.removeItem(output);
3013 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003014 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003015}
3016
Eric Laurente0720872014-03-11 09:30:41 -07003017SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003018 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003019{
3020 SortedVector<audio_io_handle_t> outputs;
3021
3022 ALOGVV("getOutputsForDevice() device %04x", device);
3023 for (size_t i = 0; i < openOutputs.size(); i++) {
3024 ALOGVV("output %d isDuplicated=%d device=%04x",
3025 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3026 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3027 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3028 outputs.add(openOutputs.keyAt(i));
3029 }
3030 }
3031 return outputs;
3032}
3033
Eric Laurente0720872014-03-11 09:30:41 -07003034bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003035 SortedVector<audio_io_handle_t>& outputs2)
3036{
3037 if (outputs1.size() != outputs2.size()) {
3038 return false;
3039 }
3040 for (size_t i = 0; i < outputs1.size(); i++) {
3041 if (outputs1[i] != outputs2[i]) {
3042 return false;
3043 }
3044 }
3045 return true;
3046}
3047
Eric Laurente0720872014-03-11 09:30:41 -07003048void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003049{
3050 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3051 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3052 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3053 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3054
3055 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3056 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3057 strategy, srcOutputs[0], dstOutputs[0]);
3058 // mute strategy while moving tracks from one output to another
3059 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003060 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003061 if (desc->isStrategyActive(strategy)) {
3062 setStrategyMute(strategy, true, srcOutputs[i]);
3063 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3064 }
3065 }
3066
3067 // Move effects associated to this strategy from previous output to new output
3068 if (strategy == STRATEGY_MEDIA) {
3069 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3070 SortedVector<audio_io_handle_t> moved;
3071 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003072 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3073 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3074 effectDesc->mIo != fxOutput) {
3075 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003076 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3077 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003078 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003079 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003080 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003081 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003082 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003083 }
3084 }
3085 }
3086 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003087 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3088 if (getStrategy((audio_stream_type_t)i) == strategy) {
3089 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003090 }
3091 }
3092 }
3093}
3094
Eric Laurente0720872014-03-11 09:30:41 -07003095void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003096{
3097 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3098 checkOutputForStrategy(STRATEGY_PHONE);
3099 checkOutputForStrategy(STRATEGY_SONIFICATION);
3100 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3101 checkOutputForStrategy(STRATEGY_MEDIA);
3102 checkOutputForStrategy(STRATEGY_DTMF);
3103}
3104
Eric Laurente0720872014-03-11 09:30:41 -07003105audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003106{
Eric Laurente552edb2014-03-10 17:42:56 -07003107 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003108 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003109 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3110 return mOutputs.keyAt(i);
3111 }
3112 }
3113
3114 return 0;
3115}
3116
Eric Laurente0720872014-03-11 09:30:41 -07003117void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003118{
Eric Laurente552edb2014-03-10 17:42:56 -07003119 audio_io_handle_t a2dpOutput = getA2dpOutput();
3120 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003121 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003122 return;
3123 }
3124
Eric Laurent3a4311c2014-03-17 12:00:47 -07003125 bool isScoConnected =
3126 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003127 // suspend A2DP output if:
3128 // (NOT already suspended) &&
3129 // ((SCO device is connected &&
3130 // (forced usage for communication || for record is SCO))) ||
3131 // (phone state is ringing || in call)
3132 //
3133 // restore A2DP output if:
3134 // (Already suspended) &&
3135 // ((SCO device is NOT connected ||
3136 // (forced usage NOT for communication && NOT for record is SCO))) &&
3137 // (phone state is NOT ringing && NOT in call)
3138 //
3139 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003140 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003141 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3142 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3143 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3144 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003145
3146 mpClientInterface->restoreOutput(a2dpOutput);
3147 mA2dpSuspended = false;
3148 }
3149 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003150 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003151 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3152 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3153 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3154 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003155
3156 mpClientInterface->suspendOutput(a2dpOutput);
3157 mA2dpSuspended = true;
3158 }
3159 }
3160}
3161
Eric Laurent1c333e22014-05-20 10:48:17 -07003162audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003163{
3164 audio_devices_t device = AUDIO_DEVICE_NONE;
3165
Eric Laurent1f2f2232014-06-02 12:01:23 -07003166 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003167
3168 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3169 if (index >= 0) {
3170 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3171 if (patchDesc->mUid != mUidCached) {
3172 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3173 outputDesc->device(), outputDesc->mPatchHandle);
3174 return outputDesc->device();
3175 }
3176 }
3177
Eric Laurente552edb2014-03-10 17:42:56 -07003178 // check the following by order of priority to request a routing change if necessary:
3179 // 1: the strategy enforced audible is active on the output:
3180 // use device for strategy enforced audible
3181 // 2: we are in call or the strategy phone is active on the output:
3182 // use device for strategy phone
3183 // 3: the strategy sonification is active on the output:
3184 // use device for strategy sonification
3185 // 4: the strategy "respectful" sonification is active on the output:
3186 // use device for strategy "respectful" sonification
3187 // 5: the strategy media is active on the output:
3188 // use device for strategy media
3189 // 6: the strategy DTMF is active on the output:
3190 // use device for strategy DTMF
3191 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3192 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3193 } else if (isInCall() ||
3194 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3195 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3196 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3197 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3198 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3199 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3200 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3201 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3202 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3203 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3204 }
3205
Eric Laurent1c333e22014-05-20 10:48:17 -07003206 ALOGV("getNewOutputDevice() selected device %x", device);
3207 return device;
3208}
3209
3210audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3211{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003212 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003213
3214 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3215 if (index >= 0) {
3216 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3217 if (patchDesc->mUid != mUidCached) {
3218 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3219 inputDesc->mDevice, inputDesc->mPatchHandle);
3220 return inputDesc->mDevice;
3221 }
3222 }
3223
Eric Laurent1c333e22014-05-20 10:48:17 -07003224 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3225
3226 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003227 return device;
3228}
3229
Eric Laurente0720872014-03-11 09:30:41 -07003230uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003231 return (uint32_t)getStrategy(stream);
3232}
3233
Eric Laurente0720872014-03-11 09:30:41 -07003234audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003235 // By checking the range of stream before calling getStrategy, we avoid
3236 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3237 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003238 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003239 return AUDIO_DEVICE_NONE;
3240 }
3241 audio_devices_t devices;
3242 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3243 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3244 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3245 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003246 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003247 if (outputDesc->isStrategyActive(strategy)) {
3248 devices = outputDesc->device();
3249 break;
3250 }
Eric Laurente552edb2014-03-10 17:42:56 -07003251 }
3252 return devices;
3253}
3254
Eric Laurente0720872014-03-11 09:30:41 -07003255AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003256 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003257 // stream to strategy mapping
3258 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003259 case AUDIO_STREAM_VOICE_CALL:
3260 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003261 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003262 case AUDIO_STREAM_RING:
3263 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003264 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003265 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003266 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003267 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003268 return STRATEGY_DTMF;
3269 default:
3270 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003271 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003272 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3273 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003274 case AUDIO_STREAM_TTS:
3275 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003276 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003277 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003278 return STRATEGY_ENFORCED_AUDIBLE;
3279 }
3280}
3281
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003282uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3283 // flags to strategy mapping
3284 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3285 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3286 }
3287
3288 // usage to strategy mapping
3289 switch (attr->usage) {
3290 case AUDIO_USAGE_MEDIA:
3291 case AUDIO_USAGE_GAME:
3292 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3293 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3294 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3295 return (uint32_t) STRATEGY_MEDIA;
3296
3297 case AUDIO_USAGE_VOICE_COMMUNICATION:
3298 return (uint32_t) STRATEGY_PHONE;
3299
3300 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3301 return (uint32_t) STRATEGY_DTMF;
3302
3303 case AUDIO_USAGE_ALARM:
3304 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3305 return (uint32_t) STRATEGY_SONIFICATION;
3306
3307 case AUDIO_USAGE_NOTIFICATION:
3308 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3309 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3310 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3311 case AUDIO_USAGE_NOTIFICATION_EVENT:
3312 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3313
3314 case AUDIO_USAGE_UNKNOWN:
3315 default:
3316 return (uint32_t) STRATEGY_MEDIA;
3317 }
3318}
3319
Eric Laurente0720872014-03-11 09:30:41 -07003320void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003321 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003322 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003323 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3324 updateDevicesAndOutputs();
3325 break;
3326 default:
3327 break;
3328 }
3329}
3330
Eric Laurente0720872014-03-11 09:30:41 -07003331audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003332 bool fromCache)
3333{
3334 uint32_t device = AUDIO_DEVICE_NONE;
3335
3336 if (fromCache) {
3337 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3338 strategy, mDeviceForStrategy[strategy]);
3339 return mDeviceForStrategy[strategy];
3340 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003341 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003342 switch (strategy) {
3343
3344 case STRATEGY_SONIFICATION_RESPECTFUL:
3345 if (isInCall()) {
3346 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003347 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003348 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3349 // while media is playing on a remote device, use the the sonification behavior.
3350 // Note that we test this usecase before testing if media is playing because
3351 // the isStreamActive() method only informs about the activity of a stream, not
3352 // if it's for local playback. Note also that we use the same delay between both tests
3353 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003354 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003355 // while media is playing (or has recently played), use the same device
3356 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3357 } else {
3358 // when media is not playing anymore, fall back on the sonification behavior
3359 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3360 }
3361
3362 break;
3363
3364 case STRATEGY_DTMF:
3365 if (!isInCall()) {
3366 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3367 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3368 break;
3369 }
3370 // when in call, DTMF and PHONE strategies follow the same rules
3371 // FALL THROUGH
3372
3373 case STRATEGY_PHONE:
3374 // for phone strategy, we first consider the forced use and then the available devices by order
3375 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003376 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3377 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003378 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003379 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003380 if (device) break;
3381 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003382 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003383 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003384 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003385 if (device) break;
3386 // if SCO device is requested but no SCO device is available, fall back to default case
3387 // FALL THROUGH
3388
3389 default: // FORCE_NONE
3390 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003391 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003392 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003393 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003394 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003395 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003396 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003397 if (device) break;
3398 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003399 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003400 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003401 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003402 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003403 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003404 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003405 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003406 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003407 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003408 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003409 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003410 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003411 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003412 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003413 if (device) break;
3414 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003415 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003416 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003417 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003418 if (device == AUDIO_DEVICE_NONE) {
3419 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3420 }
3421 break;
3422
Eric Laurent3b73df72014-03-11 09:06:29 -07003423 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003424 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3425 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003426 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003427 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003428 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003429 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003430 if (device) break;
3431 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003432 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003433 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003434 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003435 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003436 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003437 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003438 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003439 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003440 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003441 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003442 if (device) break;
3443 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003444 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003445 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003446 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003447 if (device == AUDIO_DEVICE_NONE) {
3448 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3449 }
3450 break;
3451 }
3452 break;
3453
3454 case STRATEGY_SONIFICATION:
3455
3456 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3457 // handleIncallSonification().
3458 if (isInCall()) {
3459 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3460 break;
3461 }
3462 // FALL THROUGH
3463
3464 case STRATEGY_ENFORCED_AUDIBLE:
3465 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3466 // except:
3467 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3468 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3469
3470 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003471 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003472 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003473 if (device == AUDIO_DEVICE_NONE) {
3474 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3475 }
3476 }
3477 // The second device used for sonification is the same as the device used by media strategy
3478 // FALL THROUGH
3479
3480 case STRATEGY_MEDIA: {
3481 uint32_t device2 = AUDIO_DEVICE_NONE;
3482 if (strategy != STRATEGY_SONIFICATION) {
3483 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003484 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003485 }
3486 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003487 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003488 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003489 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003490 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003491 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003492 }
3493 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003494 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003495 }
3496 }
3497 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003498 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003499 }
3500 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003501 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003502 }
3503 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003504 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003505 }
3506 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003507 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003508 }
3509 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003510 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003511 }
3512 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3513 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003514 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003515 }
3516 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003517 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003518 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003519 }
3520 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003521 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003522 }
3523
3524 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3525 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3526 device |= device2;
3527 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003528 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003529 if (device == AUDIO_DEVICE_NONE) {
3530 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3531 }
3532 } break;
3533
3534 default:
3535 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3536 break;
3537 }
3538
3539 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3540 return device;
3541}
3542
Eric Laurente0720872014-03-11 09:30:41 -07003543void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003544{
3545 for (int i = 0; i < NUM_STRATEGIES; i++) {
3546 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3547 }
3548 mPreviousOutputs = mOutputs;
3549}
3550
Eric Laurent1f2f2232014-06-02 12:01:23 -07003551uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003552 audio_devices_t prevDevice,
3553 uint32_t delayMs)
3554{
3555 // mute/unmute strategies using an incompatible device combination
3556 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3557 // if unmuting, unmute only after the specified delay
3558 if (outputDesc->isDuplicated()) {
3559 return 0;
3560 }
3561
3562 uint32_t muteWaitMs = 0;
3563 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003564 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003565
3566 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3567 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3568 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3569 bool doMute = false;
3570
3571 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3572 doMute = true;
3573 outputDesc->mStrategyMutedByDevice[i] = true;
3574 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3575 doMute = true;
3576 outputDesc->mStrategyMutedByDevice[i] = false;
3577 }
Eric Laurent99401132014-05-07 19:48:15 -07003578 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003579 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003580 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07003581 // skip output if it does not share any device with current output
3582 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3583 == AUDIO_DEVICE_NONE) {
3584 continue;
3585 }
3586 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3587 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3588 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3589 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3590 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003591 if (mute) {
3592 // FIXME: should not need to double latency if volume could be applied
3593 // immediately by the audioflinger mixer. We must account for the delay
3594 // between now and the next time the audioflinger thread for this output
3595 // will process a buffer (which corresponds to one buffer size,
3596 // usually 1/2 or 1/4 of the latency).
3597 if (muteWaitMs < desc->latency() * 2) {
3598 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003599 }
3600 }
3601 }
3602 }
3603 }
3604 }
3605
Eric Laurent99401132014-05-07 19:48:15 -07003606 // temporary mute output if device selection changes to avoid volume bursts due to
3607 // different per device volumes
3608 if (outputDesc->isActive() && (device != prevDevice)) {
3609 if (muteWaitMs < outputDesc->latency() * 2) {
3610 muteWaitMs = outputDesc->latency() * 2;
3611 }
3612 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3613 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003614 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003615 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07003616 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003617 muteWaitMs *2, device);
3618 }
3619 }
3620 }
3621
Eric Laurente552edb2014-03-10 17:42:56 -07003622 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3623 if (muteWaitMs > delayMs) {
3624 muteWaitMs -= delayMs;
3625 usleep(muteWaitMs * 1000);
3626 return muteWaitMs;
3627 }
3628 return 0;
3629}
3630
Eric Laurente0720872014-03-11 09:30:41 -07003631uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003632 audio_devices_t device,
3633 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003634 int delayMs,
3635 audio_patch_handle_t *patchHandle)
Eric Laurente552edb2014-03-10 17:42:56 -07003636{
3637 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003638 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003639 AudioParameter param;
3640 uint32_t muteWaitMs;
3641
3642 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003643 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3644 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003645 return muteWaitMs;
3646 }
3647 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3648 // output profile
3649 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003650 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003651 return 0;
3652 }
3653
3654 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003655 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003656
3657 audio_devices_t prevDevice = outputDesc->mDevice;
3658
3659 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3660
3661 if (device != AUDIO_DEVICE_NONE) {
3662 outputDesc->mDevice = device;
3663 }
3664 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3665
3666 // Do not change the routing if:
3667 // - the requested device is AUDIO_DEVICE_NONE
3668 // - the requested device is the same as current device and force is not specified.
3669 // Doing this check here allows the caller to call setOutputDevice() without conditions
3670 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3671 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3672 return muteWaitMs;
3673 }
3674
3675 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07003676
Eric Laurente552edb2014-03-10 17:42:56 -07003677 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07003678 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003679 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07003680 } else {
3681 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
3682 if (!deviceList.isEmpty()) {
3683 struct audio_patch patch;
3684 outputDesc->toAudioPortConfig(&patch.sources[0]);
3685 patch.num_sources = 1;
3686 patch.num_sinks = 0;
3687 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3688 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003689 patch.num_sinks++;
3690 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003691 ssize_t index;
3692 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3693 index = mAudioPatches.indexOfKey(*patchHandle);
3694 } else {
3695 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3696 }
3697 sp< AudioPatch> patchDesc;
3698 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3699 if (index >= 0) {
3700 patchDesc = mAudioPatches.valueAt(index);
3701 afPatchHandle = patchDesc->mAfPatchHandle;
3702 }
3703
Eric Laurent1c333e22014-05-20 10:48:17 -07003704 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003705 &afPatchHandle,
3706 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003707 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3708 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003709 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07003710 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003711 if (index < 0) {
3712 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3713 &patch, mUidCached);
3714 addAudioPatch(patchDesc->mHandle, patchDesc);
3715 } else {
3716 patchDesc->mPatch = patch;
3717 }
3718 patchDesc->mAfPatchHandle = afPatchHandle;
3719 patchDesc->mUid = mUidCached;
3720 if (patchHandle) {
3721 *patchHandle = patchDesc->mHandle;
3722 }
3723 outputDesc->mPatchHandle = patchDesc->mHandle;
3724 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003725 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003726 }
3727 }
3728 }
Eric Laurente552edb2014-03-10 17:42:56 -07003729
3730 // update stream volumes according to new device
3731 applyStreamVolumes(output, device, delayMs);
3732
3733 return muteWaitMs;
3734}
3735
Eric Laurent1c333e22014-05-20 10:48:17 -07003736status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07003737 int delayMs,
3738 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003739{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003740 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003741 ssize_t index;
3742 if (patchHandle) {
3743 index = mAudioPatches.indexOfKey(*patchHandle);
3744 } else {
3745 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3746 }
3747 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003748 return INVALID_OPERATION;
3749 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003750 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3751 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003752 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
3753 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003754 removeAudioPatch(patchDesc->mHandle);
3755 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003756 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003757 return status;
3758}
3759
3760status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
3761 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07003762 bool force,
3763 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003764{
3765 status_t status = NO_ERROR;
3766
Eric Laurent1f2f2232014-06-02 12:01:23 -07003767 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07003768 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
3769 inputDesc->mDevice = device;
3770
3771 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
3772 if (!deviceList.isEmpty()) {
3773 struct audio_patch patch;
3774 inputDesc->toAudioPortConfig(&patch.sinks[0]);
3775 patch.num_sinks = 1;
3776 //only one input device for now
3777 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003778 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07003779 ssize_t index;
3780 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3781 index = mAudioPatches.indexOfKey(*patchHandle);
3782 } else {
3783 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3784 }
3785 sp< AudioPatch> patchDesc;
3786 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3787 if (index >= 0) {
3788 patchDesc = mAudioPatches.valueAt(index);
3789 afPatchHandle = patchDesc->mAfPatchHandle;
3790 }
3791
Eric Laurent1c333e22014-05-20 10:48:17 -07003792 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003793 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07003794 0);
3795 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003796 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07003797 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003798 if (index < 0) {
3799 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3800 &patch, mUidCached);
3801 addAudioPatch(patchDesc->mHandle, patchDesc);
3802 } else {
3803 patchDesc->mPatch = patch;
3804 }
3805 patchDesc->mAfPatchHandle = afPatchHandle;
3806 patchDesc->mUid = mUidCached;
3807 if (patchHandle) {
3808 *patchHandle = patchDesc->mHandle;
3809 }
3810 inputDesc->mPatchHandle = patchDesc->mHandle;
3811 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003812 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003813 }
3814 }
3815 }
3816 return status;
3817}
3818
Eric Laurent6a94d692014-05-20 11:18:06 -07003819status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
3820 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003821{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003822 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003823 ssize_t index;
3824 if (patchHandle) {
3825 index = mAudioPatches.indexOfKey(*patchHandle);
3826 } else {
3827 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3828 }
3829 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003830 return INVALID_OPERATION;
3831 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003832 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3833 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07003834 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
3835 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003836 removeAudioPatch(patchDesc->mHandle);
3837 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003838 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003839 return status;
3840}
3841
3842sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07003843 uint32_t samplingRate,
3844 audio_format_t format,
3845 audio_channel_mask_t channelMask)
3846{
3847 // Choose an input profile based on the requested capture parameters: select the first available
3848 // profile supporting all requested parameters.
3849
3850 for (size_t i = 0; i < mHwModules.size(); i++)
3851 {
3852 if (mHwModules[i]->mHandle == 0) {
3853 continue;
3854 }
3855 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3856 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003857 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003858 // profile->log();
Eric Laurente552edb2014-03-10 17:42:56 -07003859 if (profile->isCompatibleProfile(device, samplingRate, format,
3860 channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
3861 return profile;
3862 }
3863 }
3864 }
3865 return NULL;
3866}
3867
Eric Laurente0720872014-03-11 09:30:41 -07003868audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07003869{
3870 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003871 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
3872 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003873 switch (inputSource) {
3874 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003875 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003876 device = AUDIO_DEVICE_IN_VOICE_CALL;
3877 break;
3878 }
3879 // FALL THROUGH
3880
3881 case AUDIO_SOURCE_DEFAULT:
3882 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07003883 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
3884 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
3885 break;
3886 }
3887 // FALL THROUGH
3888
Eric Laurente552edb2014-03-10 17:42:56 -07003889 case AUDIO_SOURCE_VOICE_RECOGNITION:
3890 case AUDIO_SOURCE_HOTWORD:
3891 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07003892 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003893 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003894 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003895 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003896 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07003897 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
3898 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003899 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003900 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3901 }
3902 break;
3903 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003904 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003905 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003906 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003907 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3908 }
3909 break;
3910 case AUDIO_SOURCE_VOICE_DOWNLINK:
3911 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003912 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003913 device = AUDIO_DEVICE_IN_VOICE_CALL;
3914 }
3915 break;
3916 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003917 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07003918 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3919 }
3920 break;
3921 default:
3922 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
3923 break;
3924 }
3925 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
3926 return device;
3927}
3928
Eric Laurente0720872014-03-11 09:30:41 -07003929bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003930{
3931 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
3932 device &= ~AUDIO_DEVICE_BIT_IN;
3933 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
3934 return true;
3935 }
3936 return false;
3937}
3938
Eric Laurente0720872014-03-11 09:30:41 -07003939audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003940{
3941 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003942 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003943 if ((input_descriptor->mRefCount > 0)
3944 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
3945 return mInputs.keyAt(i);
3946 }
3947 }
3948 return 0;
3949}
3950
3951
Eric Laurente0720872014-03-11 09:30:41 -07003952audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003953{
3954 if (device == AUDIO_DEVICE_NONE) {
3955 // this happens when forcing a route update and no track is active on an output.
3956 // In this case the returned category is not important.
3957 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07003958 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07003959 // Multiple device selection is either:
3960 // - speaker + one other device: give priority to speaker in this case.
3961 // - one A2DP device + another device: happens with duplicated output. In this case
3962 // retain the device on the A2DP output as the other must not correspond to an active
3963 // selection if not the speaker.
3964 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
3965 device = AUDIO_DEVICE_OUT_SPEAKER;
3966 } else {
3967 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
3968 }
3969 }
3970
Eric Laurent3b73df72014-03-11 09:06:29 -07003971 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07003972 "getDeviceForVolume() invalid device combination: %08x",
3973 device);
3974
3975 return device;
3976}
3977
Eric Laurente0720872014-03-11 09:30:41 -07003978AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003979{
3980 switch(getDeviceForVolume(device)) {
3981 case AUDIO_DEVICE_OUT_EARPIECE:
3982 return DEVICE_CATEGORY_EARPIECE;
3983 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
3984 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
3985 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
3986 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
3987 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
3988 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
3989 return DEVICE_CATEGORY_HEADSET;
3990 case AUDIO_DEVICE_OUT_SPEAKER:
3991 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
3992 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
3993 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
3994 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
3995 case AUDIO_DEVICE_OUT_USB_DEVICE:
3996 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
3997 default:
3998 return DEVICE_CATEGORY_SPEAKER;
3999 }
4000}
4001
Eric Laurente0720872014-03-11 09:30:41 -07004002float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004003 int indexInUi)
4004{
4005 device_category deviceCategory = getDeviceCategory(device);
4006 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4007
4008 // the volume index in the UI is relative to the min and max volume indices for this stream type
4009 int nbSteps = 1 + curve[VOLMAX].mIndex -
4010 curve[VOLMIN].mIndex;
4011 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4012 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4013
4014 // find what part of the curve this index volume belongs to, or if it's out of bounds
4015 int segment = 0;
4016 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4017 return 0.0f;
4018 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4019 segment = 0;
4020 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4021 segment = 1;
4022 } else if (volIdx <= curve[VOLMAX].mIndex) {
4023 segment = 2;
4024 } else { // out of bounds
4025 return 1.0f;
4026 }
4027
4028 // linear interpolation in the attenuation table in dB
4029 float decibels = curve[segment].mDBAttenuation +
4030 ((float)(volIdx - curve[segment].mIndex)) *
4031 ( (curve[segment+1].mDBAttenuation -
4032 curve[segment].mDBAttenuation) /
4033 ((float)(curve[segment+1].mIndex -
4034 curve[segment].mIndex)) );
4035
4036 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4037
4038 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4039 curve[segment].mIndex, volIdx,
4040 curve[segment+1].mIndex,
4041 curve[segment].mDBAttenuation,
4042 decibels,
4043 curve[segment+1].mDBAttenuation,
4044 amplification);
4045
4046 return amplification;
4047}
4048
Eric Laurente0720872014-03-11 09:30:41 -07004049const AudioPolicyManager::VolumeCurvePoint
4050 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004051 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4052};
4053
Eric Laurente0720872014-03-11 09:30:41 -07004054const AudioPolicyManager::VolumeCurvePoint
4055 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004056 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4057};
4058
Eric Laurente0720872014-03-11 09:30:41 -07004059const AudioPolicyManager::VolumeCurvePoint
4060 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004061 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4062};
4063
Eric Laurente0720872014-03-11 09:30:41 -07004064const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004065 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
4066 {1, -56.0f}, {20, -34.0f}, {86, -10.0f}, {100, 0.0f}
4067};
4068
4069const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004070 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004071 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4072};
4073
Eric Laurente0720872014-03-11 09:30:41 -07004074const AudioPolicyManager::VolumeCurvePoint
4075 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004076 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4077};
4078
4079// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4080// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4081// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4082// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4083
Eric Laurente0720872014-03-11 09:30:41 -07004084const AudioPolicyManager::VolumeCurvePoint
4085 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004086 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4087};
4088
Eric Laurente0720872014-03-11 09:30:41 -07004089const AudioPolicyManager::VolumeCurvePoint
4090 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004091 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4092};
4093
Eric Laurente0720872014-03-11 09:30:41 -07004094const AudioPolicyManager::VolumeCurvePoint
4095 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004096 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4097};
4098
Eric Laurente0720872014-03-11 09:30:41 -07004099const AudioPolicyManager::VolumeCurvePoint
4100 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004101 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4102};
4103
Eric Laurente0720872014-03-11 09:30:41 -07004104const AudioPolicyManager::VolumeCurvePoint
4105 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004106 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4107};
4108
Eric Laurente0720872014-03-11 09:30:41 -07004109const AudioPolicyManager::VolumeCurvePoint
4110 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4111 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004112 { // AUDIO_STREAM_VOICE_CALL
4113 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4114 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4115 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4116 },
4117 { // AUDIO_STREAM_SYSTEM
4118 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4119 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4120 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4121 },
4122 { // AUDIO_STREAM_RING
4123 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4124 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4125 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4126 },
4127 { // AUDIO_STREAM_MUSIC
4128 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4129 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4130 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4131 },
4132 { // AUDIO_STREAM_ALARM
4133 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4134 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4135 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4136 },
4137 { // AUDIO_STREAM_NOTIFICATION
4138 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4139 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4140 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4141 },
4142 { // AUDIO_STREAM_BLUETOOTH_SCO
4143 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4144 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4145 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4146 },
4147 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4148 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4149 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4150 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4151 },
4152 { // AUDIO_STREAM_DTMF
4153 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4154 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4155 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4156 },
4157 { // AUDIO_STREAM_TTS
4158 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4159 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4160 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4161 },
4162};
4163
Eric Laurente0720872014-03-11 09:30:41 -07004164void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004165{
4166 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4167 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4168 mStreams[i].mVolumeCurve[j] =
4169 sVolumeProfiles[i][j];
4170 }
4171 }
4172
4173 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4174 if (mSpeakerDrcEnabled) {
4175 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4176 sDefaultSystemVolumeCurveDrc;
4177 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4178 sSpeakerSonificationVolumeCurveDrc;
4179 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4180 sSpeakerSonificationVolumeCurveDrc;
4181 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4182 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004183 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4184 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004185 }
4186}
4187
Eric Laurente0720872014-03-11 09:30:41 -07004188float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004189 int index,
4190 audio_io_handle_t output,
4191 audio_devices_t device)
4192{
4193 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004194 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004195 StreamDescriptor &streamDesc = mStreams[stream];
4196
4197 if (device == AUDIO_DEVICE_NONE) {
4198 device = outputDesc->device();
4199 }
4200
4201 // if volume is not 0 (not muted), force media volume to max on digital output
Eric Laurent3b73df72014-03-11 09:06:29 -07004202 if (stream == AUDIO_STREAM_MUSIC &&
Eric Laurente552edb2014-03-10 17:42:56 -07004203 index != mStreams[stream].mIndexMin &&
4204 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
4205 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
4206 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
4207 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
4208 return 1.0;
4209 }
4210
4211 volume = volIndexToAmpl(device, streamDesc, index);
4212
4213 // if a headset is connected, apply the following rules to ring tones and notifications
4214 // to avoid sound level bursts in user's ears:
4215 // - always attenuate ring tones and notifications volume by 6dB
4216 // - if music is playing, always limit the volume to current music volume,
4217 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004218 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004219 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4220 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4221 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4222 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4223 ((stream_strategy == STRATEGY_SONIFICATION)
4224 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004225 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004226 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004227 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004228 streamDesc.mCanBeMuted) {
4229 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4230 // when the phone is ringing we must consider that music could have been paused just before
4231 // by the music application and behave as if music was active if the last music track was
4232 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004233 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004234 mLimitRingtoneVolume) {
4235 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004236 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4237 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004238 output,
4239 musicDevice);
4240 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4241 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4242 if (volume > minVol) {
4243 volume = minVol;
4244 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4245 }
4246 }
4247 }
4248
4249 return volume;
4250}
4251
Eric Laurente0720872014-03-11 09:30:41 -07004252status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004253 int index,
4254 audio_io_handle_t output,
4255 audio_devices_t device,
4256 int delayMs,
4257 bool force)
4258{
4259
4260 // do not change actual stream volume if the stream is muted
4261 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4262 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4263 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4264 return NO_ERROR;
4265 }
4266
4267 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004268 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4269 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4270 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4271 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004272 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004273 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004274 return INVALID_OPERATION;
4275 }
4276
4277 float volume = computeVolume(stream, index, output, device);
4278 // We actually change the volume if:
4279 // - the float value returned by computeVolume() changed
4280 // - the force flag is set
4281 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4282 force) {
4283 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4284 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4285 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4286 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004287 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4288 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004289 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004290 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004291 }
4292
Eric Laurent3b73df72014-03-11 09:06:29 -07004293 if (stream == AUDIO_STREAM_VOICE_CALL ||
4294 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004295 float voiceVolume;
4296 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004297 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004298 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4299 } else {
4300 voiceVolume = 1.0;
4301 }
4302
4303 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4304 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4305 mLastVoiceVolume = voiceVolume;
4306 }
4307 }
4308
4309 return NO_ERROR;
4310}
4311
Eric Laurente0720872014-03-11 09:30:41 -07004312void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004313 audio_devices_t device,
4314 int delayMs,
4315 bool force)
4316{
4317 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4318
Eric Laurent3b73df72014-03-11 09:06:29 -07004319 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4320 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004321 mStreams[stream].getVolumeIndex(device),
4322 output,
4323 device,
4324 delayMs,
4325 force);
4326 }
4327}
4328
Eric Laurente0720872014-03-11 09:30:41 -07004329void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004330 bool on,
4331 audio_io_handle_t output,
4332 int delayMs,
4333 audio_devices_t device)
4334{
4335 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004336 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4337 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4338 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004339 }
4340 }
4341}
4342
Eric Laurente0720872014-03-11 09:30:41 -07004343void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004344 bool on,
4345 audio_io_handle_t output,
4346 int delayMs,
4347 audio_devices_t device)
4348{
4349 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004350 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004351 if (device == AUDIO_DEVICE_NONE) {
4352 device = outputDesc->device();
4353 }
4354
4355 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4356 stream, on, output, outputDesc->mMuteCount[stream], device);
4357
4358 if (on) {
4359 if (outputDesc->mMuteCount[stream] == 0) {
4360 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004361 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4362 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004363 checkAndSetVolume(stream, 0, output, device, delayMs);
4364 }
4365 }
4366 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4367 outputDesc->mMuteCount[stream]++;
4368 } else {
4369 if (outputDesc->mMuteCount[stream] == 0) {
4370 ALOGV("setStreamMute() unmuting non muted stream!");
4371 return;
4372 }
4373 if (--outputDesc->mMuteCount[stream] == 0) {
4374 checkAndSetVolume(stream,
4375 streamDesc.getVolumeIndex(device),
4376 output,
4377 device,
4378 delayMs);
4379 }
4380 }
4381}
4382
Eric Laurente0720872014-03-11 09:30:41 -07004383void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004384 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004385{
4386 // if the stream pertains to sonification strategy and we are in call we must
4387 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4388 // in the device used for phone strategy and play the tone if the selected device does not
4389 // interfere with the device used for phone strategy
4390 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4391 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004392 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004393 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4394 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004395 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004396 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4397 stream, starting, outputDesc->mDevice, stateChange);
4398 if (outputDesc->mRefCount[stream]) {
4399 int muteCount = 1;
4400 if (stateChange) {
4401 muteCount = outputDesc->mRefCount[stream];
4402 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004403 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004404 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4405 for (int i = 0; i < muteCount; i++) {
4406 setStreamMute(stream, starting, mPrimaryOutput);
4407 }
4408 } else {
4409 ALOGV("handleIncallSonification() high visibility");
4410 if (outputDesc->device() &
4411 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4412 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4413 for (int i = 0; i < muteCount; i++) {
4414 setStreamMute(stream, starting, mPrimaryOutput);
4415 }
4416 }
4417 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004418 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4419 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004420 } else {
4421 mpClientInterface->stopTone();
4422 }
4423 }
4424 }
4425 }
4426}
4427
Eric Laurente0720872014-03-11 09:30:41 -07004428bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004429{
4430 return isStateInCall(mPhoneState);
4431}
4432
Eric Laurente0720872014-03-11 09:30:41 -07004433bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004434 return ((state == AUDIO_MODE_IN_CALL) ||
4435 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004436}
4437
Eric Laurente0720872014-03-11 09:30:41 -07004438uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004439{
4440 return MAX_EFFECTS_CPU_LOAD;
4441}
4442
Eric Laurente0720872014-03-11 09:30:41 -07004443uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004444{
4445 return MAX_EFFECTS_MEMORY;
4446}
4447
Eric Laurent6a94d692014-05-20 11:18:06 -07004448
Eric Laurente552edb2014-03-10 17:42:56 -07004449// --- AudioOutputDescriptor class implementation
4450
Eric Laurente0720872014-03-11 09:30:41 -07004451AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004452 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004453 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004454 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004455 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4456{
4457 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004458 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004459 mRefCount[i] = 0;
4460 mCurVolume[i] = -1.0;
4461 mMuteCount[i] = 0;
4462 mStopTime[i] = 0;
4463 }
4464 for (int i = 0; i < NUM_STRATEGIES; i++) {
4465 mStrategyMutedByDevice[i] = false;
4466 }
4467 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004468 mAudioPort = profile;
Eric Laurente552edb2014-03-10 17:42:56 -07004469 mSamplingRate = profile->mSamplingRates[0];
4470 mFormat = profile->mFormats[0];
4471 mChannelMask = profile->mChannelMasks[0];
Eric Laurenta121f902014-06-03 13:32:54 -07004472 if (profile->mGains.size() > 0) {
4473 profile->mGains[0]->getDefaultConfig(&mGain);
4474 }
Eric Laurente552edb2014-03-10 17:42:56 -07004475 mFlags = profile->mFlags;
4476 }
4477}
4478
Eric Laurente0720872014-03-11 09:30:41 -07004479audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004480{
4481 if (isDuplicated()) {
4482 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4483 } else {
4484 return mDevice;
4485 }
4486}
4487
Eric Laurente0720872014-03-11 09:30:41 -07004488uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004489{
4490 if (isDuplicated()) {
4491 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4492 } else {
4493 return mLatency;
4494 }
4495}
4496
Eric Laurente0720872014-03-11 09:30:41 -07004497bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07004498 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004499{
4500 if (isDuplicated()) {
4501 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4502 } else if (outputDesc->isDuplicated()){
4503 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4504 } else {
4505 return (mProfile->mModule == outputDesc->mProfile->mModule);
4506 }
4507}
4508
Eric Laurente0720872014-03-11 09:30:41 -07004509void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004510 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004511{
4512 // forward usage count change to attached outputs
4513 if (isDuplicated()) {
4514 mOutput1->changeRefCount(stream, delta);
4515 mOutput2->changeRefCount(stream, delta);
4516 }
4517 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004518 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4519 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004520 mRefCount[stream] = 0;
4521 return;
4522 }
4523 mRefCount[stream] += delta;
4524 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4525}
4526
Eric Laurente0720872014-03-11 09:30:41 -07004527audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004528{
4529 if (isDuplicated()) {
4530 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4531 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004532 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004533 }
4534}
4535
Eric Laurente0720872014-03-11 09:30:41 -07004536bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004537{
4538 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4539}
4540
Eric Laurente0720872014-03-11 09:30:41 -07004541bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004542 uint32_t inPastMs,
4543 nsecs_t sysTime) const
4544{
4545 if ((sysTime == 0) && (inPastMs != 0)) {
4546 sysTime = systemTime();
4547 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004548 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4549 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004550 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004551 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004552 return true;
4553 }
4554 }
4555 return false;
4556}
4557
Eric Laurente0720872014-03-11 09:30:41 -07004558bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004559 uint32_t inPastMs,
4560 nsecs_t sysTime) const
4561{
4562 if (mRefCount[stream] != 0) {
4563 return true;
4564 }
4565 if (inPastMs == 0) {
4566 return false;
4567 }
4568 if (sysTime == 0) {
4569 sysTime = systemTime();
4570 }
4571 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4572 return true;
4573 }
4574 return false;
4575}
4576
Eric Laurent1c333e22014-05-20 10:48:17 -07004577void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004578 struct audio_port_config *dstConfig,
4579 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004580{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004581 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4582 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4583 if (srcConfig != NULL) {
4584 dstConfig->config_mask &= srcConfig->config_mask;
4585 }
4586 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4587
Eric Laurent6a94d692014-05-20 11:18:06 -07004588 dstConfig->id = mId;
4589 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4590 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07004591 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4592 dstConfig->ext.mix.handle = mIoHandle;
4593 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07004594}
4595
4596void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4597 struct audio_port *port) const
4598{
4599 mProfile->toAudioPort(port);
4600 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004601 toAudioPortConfig(&port->active_config);
4602 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004603 port->ext.mix.handle = mIoHandle;
4604 port->ext.mix.latency_class =
4605 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4606}
Eric Laurente552edb2014-03-10 17:42:56 -07004607
Eric Laurente0720872014-03-11 09:30:41 -07004608status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004609{
4610 const size_t SIZE = 256;
4611 char buffer[SIZE];
4612 String8 result;
4613
4614 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4615 result.append(buffer);
4616 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4617 result.append(buffer);
4618 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4619 result.append(buffer);
4620 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4621 result.append(buffer);
4622 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4623 result.append(buffer);
4624 snprintf(buffer, SIZE, " Devices %08x\n", device());
4625 result.append(buffer);
4626 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4627 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004628 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4629 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4630 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004631 result.append(buffer);
4632 }
4633 write(fd, result.string(), result.size());
4634
4635 return NO_ERROR;
4636}
4637
4638// --- AudioInputDescriptor class implementation
4639
Eric Laurent1c333e22014-05-20 10:48:17 -07004640AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004641 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004642 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurent3b73df72014-03-11 09:06:29 -07004643 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004644{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004645 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004646 mAudioPort = profile;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004647 mSamplingRate = profile->mSamplingRates[0];
4648 mFormat = profile->mFormats[0];
4649 mChannelMask = profile->mChannelMasks[0];
Eric Laurenta121f902014-06-03 13:32:54 -07004650 if (profile->mGains.size() > 0) {
4651 profile->mGains[0]->getDefaultConfig(&mGain);
4652 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004653 } else {
4654 mSamplingRate = 0;
4655 mFormat = AUDIO_FORMAT_DEFAULT;
4656 mChannelMask = 0;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004657 }
Eric Laurente552edb2014-03-10 17:42:56 -07004658}
4659
Eric Laurent1c333e22014-05-20 10:48:17 -07004660void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004661 struct audio_port_config *dstConfig,
4662 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004663{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004664 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4665 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4666 if (srcConfig != NULL) {
4667 dstConfig->config_mask &= srcConfig->config_mask;
4668 }
4669
4670 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4671
Eric Laurent6a94d692014-05-20 11:18:06 -07004672 dstConfig->id = mId;
4673 dstConfig->role = AUDIO_PORT_ROLE_SINK;
4674 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07004675 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4676 dstConfig->ext.mix.handle = mIoHandle;
4677 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07004678}
4679
4680void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
4681 struct audio_port *port) const
4682{
4683 mProfile->toAudioPort(port);
4684 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004685 toAudioPortConfig(&port->active_config);
4686 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004687 port->ext.mix.handle = mIoHandle;
4688 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
4689}
4690
Eric Laurente0720872014-03-11 09:30:41 -07004691status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004692{
4693 const size_t SIZE = 256;
4694 char buffer[SIZE];
4695 String8 result;
4696
4697 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4698 result.append(buffer);
4699 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
4700 result.append(buffer);
4701 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4702 result.append(buffer);
4703 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
4704 result.append(buffer);
4705 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
4706 result.append(buffer);
4707 write(fd, result.string(), result.size());
4708
4709 return NO_ERROR;
4710}
4711
4712// --- StreamDescriptor class implementation
4713
Eric Laurente0720872014-03-11 09:30:41 -07004714AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07004715 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
4716{
4717 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
4718}
4719
Eric Laurente0720872014-03-11 09:30:41 -07004720int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004721{
Eric Laurente0720872014-03-11 09:30:41 -07004722 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07004723 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
4724 if (mIndexCur.indexOfKey(device) < 0) {
4725 device = AUDIO_DEVICE_OUT_DEFAULT;
4726 }
4727 return mIndexCur.valueFor(device);
4728}
4729
Eric Laurente0720872014-03-11 09:30:41 -07004730void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004731{
4732 const size_t SIZE = 256;
4733 char buffer[SIZE];
4734 String8 result;
4735
4736 snprintf(buffer, SIZE, "%s %02d %02d ",
4737 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
4738 result.append(buffer);
4739 for (size_t i = 0; i < mIndexCur.size(); i++) {
4740 snprintf(buffer, SIZE, "%04x : %02d, ",
4741 mIndexCur.keyAt(i),
4742 mIndexCur.valueAt(i));
4743 result.append(buffer);
4744 }
4745 result.append("\n");
4746
4747 write(fd, result.string(), result.size());
4748}
4749
4750// --- EffectDescriptor class implementation
4751
Eric Laurente0720872014-03-11 09:30:41 -07004752status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004753{
4754 const size_t SIZE = 256;
4755 char buffer[SIZE];
4756 String8 result;
4757
4758 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
4759 result.append(buffer);
4760 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
4761 result.append(buffer);
4762 snprintf(buffer, SIZE, " Session: %d\n", mSession);
4763 result.append(buffer);
4764 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
4765 result.append(buffer);
4766 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
4767 result.append(buffer);
4768 write(fd, result.string(), result.size());
4769
4770 return NO_ERROR;
4771}
4772
Eric Laurent1c333e22014-05-20 10:48:17 -07004773// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07004774
Eric Laurente0720872014-03-11 09:30:41 -07004775AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07004776 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
4777 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07004778{
4779}
4780
Eric Laurente0720872014-03-11 09:30:41 -07004781AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07004782{
4783 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004784 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004785 }
4786 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004787 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07004788 }
4789 free((void *)mName);
4790}
4791
Eric Laurent1afeecb2014-05-14 08:52:28 -07004792status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
4793{
4794 cnode *node = root->first_child;
4795
4796 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
4797
4798 while (node) {
4799 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4800 profile->loadSamplingRates((char *)node->value);
4801 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4802 profile->loadFormats((char *)node->value);
4803 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4804 profile->loadInChannels((char *)node->value);
4805 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4806 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
4807 mDeclaredDevices);
4808 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4809 profile->loadGains(node);
4810 }
4811 node = node->next;
4812 }
4813 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4814 "loadInput() invalid supported devices");
4815 ALOGW_IF(profile->mChannelMasks.size() == 0,
4816 "loadInput() invalid supported channel masks");
4817 ALOGW_IF(profile->mSamplingRates.size() == 0,
4818 "loadInput() invalid supported sampling rates");
4819 ALOGW_IF(profile->mFormats.size() == 0,
4820 "loadInput() invalid supported formats");
4821 if (!profile->mSupportedDevices.isEmpty() &&
4822 (profile->mChannelMasks.size() != 0) &&
4823 (profile->mSamplingRates.size() != 0) &&
4824 (profile->mFormats.size() != 0)) {
4825
4826 ALOGV("loadInput() adding input Supported Devices %04x",
4827 profile->mSupportedDevices.types());
4828
4829 mInputProfiles.add(profile);
4830 return NO_ERROR;
4831 } else {
4832 return BAD_VALUE;
4833 }
4834}
4835
4836status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
4837{
4838 cnode *node = root->first_child;
4839
4840 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
4841
4842 while (node) {
4843 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4844 profile->loadSamplingRates((char *)node->value);
4845 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4846 profile->loadFormats((char *)node->value);
4847 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4848 profile->loadOutChannels((char *)node->value);
4849 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
4850 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
4851 mDeclaredDevices);
4852 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
4853 profile->mFlags = parseFlagNames((char *)node->value);
4854 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4855 profile->loadGains(node);
4856 }
4857 node = node->next;
4858 }
4859 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
4860 "loadOutput() invalid supported devices");
4861 ALOGW_IF(profile->mChannelMasks.size() == 0,
4862 "loadOutput() invalid supported channel masks");
4863 ALOGW_IF(profile->mSamplingRates.size() == 0,
4864 "loadOutput() invalid supported sampling rates");
4865 ALOGW_IF(profile->mFormats.size() == 0,
4866 "loadOutput() invalid supported formats");
4867 if (!profile->mSupportedDevices.isEmpty() &&
4868 (profile->mChannelMasks.size() != 0) &&
4869 (profile->mSamplingRates.size() != 0) &&
4870 (profile->mFormats.size() != 0)) {
4871
4872 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
4873 profile->mSupportedDevices.types(), profile->mFlags);
4874
4875 mOutputProfiles.add(profile);
4876 return NO_ERROR;
4877 } else {
4878 return BAD_VALUE;
4879 }
4880}
4881
4882status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
4883{
4884 cnode *node = root->first_child;
4885
4886 audio_devices_t type = AUDIO_DEVICE_NONE;
4887 while (node) {
4888 if (strcmp(node->name, DEVICE_TYPE) == 0) {
4889 type = parseDeviceNames((char *)node->value);
4890 break;
4891 }
4892 node = node->next;
4893 }
4894 if (type == AUDIO_DEVICE_NONE ||
4895 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
4896 ALOGW("loadDevice() bad type %08x", type);
4897 return BAD_VALUE;
4898 }
4899 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
4900 deviceDesc->mModule = this;
4901
4902 node = root->first_child;
4903 while (node) {
4904 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
4905 deviceDesc->mAddress = String8((char *)node->value);
4906 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4907 if (audio_is_input_device(type)) {
4908 deviceDesc->loadInChannels((char *)node->value);
4909 } else {
4910 deviceDesc->loadOutChannels((char *)node->value);
4911 }
4912 } else if (strcmp(node->name, GAINS_TAG) == 0) {
4913 deviceDesc->loadGains(node);
4914 }
4915 node = node->next;
4916 }
4917
4918 ALOGV("loadDevice() adding device name %s type %08x address %s",
4919 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
4920
4921 mDeclaredDevices.add(deviceDesc);
4922
4923 return NO_ERROR;
4924}
4925
Eric Laurente0720872014-03-11 09:30:41 -07004926void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004927{
4928 const size_t SIZE = 256;
4929 char buffer[SIZE];
4930 String8 result;
4931
4932 snprintf(buffer, SIZE, " - name: %s\n", mName);
4933 result.append(buffer);
4934 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
4935 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07004936 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
4937 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07004938 write(fd, result.string(), result.size());
4939 if (mOutputProfiles.size()) {
4940 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
4941 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004942 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004943 write(fd, buffer, strlen(buffer));
4944 mOutputProfiles[i]->dump(fd);
4945 }
4946 }
4947 if (mInputProfiles.size()) {
4948 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
4949 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07004950 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07004951 write(fd, buffer, strlen(buffer));
4952 mInputProfiles[i]->dump(fd);
4953 }
4954 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07004955 if (mDeclaredDevices.size()) {
4956 write(fd, " - devices:\n", strlen(" - devices:\n"));
4957 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
4958 mDeclaredDevices[i]->dump(fd, 4, i);
4959 }
4960 }
Eric Laurente552edb2014-03-10 17:42:56 -07004961}
4962
Eric Laurent1c333e22014-05-20 10:48:17 -07004963// --- AudioPort class implementation
4964
Eric Laurenta121f902014-06-03 13:32:54 -07004965
4966AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
4967 audio_port_role_t role, const sp<HwModule>& module) :
4968 mName(name), mType(type), mRole(role), mModule(module)
4969{
4970 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
4971 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
4972}
4973
Eric Laurent1c333e22014-05-20 10:48:17 -07004974void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
4975{
4976 port->role = mRole;
4977 port->type = mType;
4978 unsigned int i;
4979 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
4980 port->sample_rates[i] = mSamplingRates[i];
4981 }
4982 port->num_sample_rates = i;
4983 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
4984 port->channel_masks[i] = mChannelMasks[i];
4985 }
4986 port->num_channel_masks = i;
4987 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
4988 port->formats[i] = mFormats[i];
4989 }
4990 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07004991
4992 ALOGV("AudioPort::toAudioPort() num gains %d", mGains.size());
4993
4994 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
4995 port->gains[i] = mGains[i]->mGain;
4996 }
4997 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07004998}
4999
5000
5001void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5002{
5003 char *str = strtok(name, "|");
5004
5005 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5006 // rates should be read from the output stream after it is opened for the first time
5007 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5008 mSamplingRates.add(0);
5009 return;
5010 }
5011
5012 while (str != NULL) {
5013 uint32_t rate = atoi(str);
5014 if (rate != 0) {
5015 ALOGV("loadSamplingRates() adding rate %d", rate);
5016 mSamplingRates.add(rate);
5017 }
5018 str = strtok(NULL, "|");
5019 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005020}
5021
5022void AudioPolicyManager::AudioPort::loadFormats(char *name)
5023{
5024 char *str = strtok(name, "|");
5025
5026 // by convention, "0' in the first entry in mFormats indicates the supported formats
5027 // should be read from the output stream after it is opened for the first time
5028 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5029 mFormats.add(AUDIO_FORMAT_DEFAULT);
5030 return;
5031 }
5032
5033 while (str != NULL) {
5034 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5035 ARRAY_SIZE(sFormatNameToEnumTable),
5036 str);
5037 if (format != AUDIO_FORMAT_DEFAULT) {
5038 mFormats.add(format);
5039 }
5040 str = strtok(NULL, "|");
5041 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005042}
5043
5044void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5045{
5046 const char *str = strtok(name, "|");
5047
5048 ALOGV("loadInChannels() %s", name);
5049
5050 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5051 mChannelMasks.add(0);
5052 return;
5053 }
5054
5055 while (str != NULL) {
5056 audio_channel_mask_t channelMask =
5057 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5058 ARRAY_SIZE(sInChannelsNameToEnumTable),
5059 str);
5060 if (channelMask != 0) {
5061 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5062 mChannelMasks.add(channelMask);
5063 }
5064 str = strtok(NULL, "|");
5065 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005066}
5067
5068void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5069{
5070 const char *str = strtok(name, "|");
5071
5072 ALOGV("loadOutChannels() %s", name);
5073
5074 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5075 // masks should be read from the output stream after it is opened for the first time
5076 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5077 mChannelMasks.add(0);
5078 return;
5079 }
5080
5081 while (str != NULL) {
5082 audio_channel_mask_t channelMask =
5083 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5084 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5085 str);
5086 if (channelMask != 0) {
5087 mChannelMasks.add(channelMask);
5088 }
5089 str = strtok(NULL, "|");
5090 }
5091 return;
5092}
5093
Eric Laurent1afeecb2014-05-14 08:52:28 -07005094audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5095{
5096 const char *str = strtok(name, "|");
5097
5098 ALOGV("loadGainMode() %s", name);
5099 audio_gain_mode_t mode = 0;
5100 while (str != NULL) {
5101 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5102 ARRAY_SIZE(sGainModeNameToEnumTable),
5103 str);
5104 str = strtok(NULL, "|");
5105 }
5106 return mode;
5107}
5108
Eric Laurenta121f902014-06-03 13:32:54 -07005109void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005110{
5111 cnode *node = root->first_child;
5112
Eric Laurenta121f902014-06-03 13:32:54 -07005113 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005114
5115 while (node) {
5116 if (strcmp(node->name, GAIN_MODE) == 0) {
5117 gain->mGain.mode = loadGainMode((char *)node->value);
5118 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005119 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005120 gain->mGain.channel_mask =
5121 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5122 ARRAY_SIZE(sInChannelsNameToEnumTable),
5123 (char *)node->value);
5124 } else {
5125 gain->mGain.channel_mask =
5126 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5127 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5128 (char *)node->value);
5129 }
5130 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5131 gain->mGain.min_value = atoi((char *)node->value);
5132 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5133 gain->mGain.max_value = atoi((char *)node->value);
5134 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5135 gain->mGain.default_value = atoi((char *)node->value);
5136 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5137 gain->mGain.step_value = atoi((char *)node->value);
5138 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5139 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5140 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5141 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5142 }
5143 node = node->next;
5144 }
5145
5146 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5147 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5148
5149 if (gain->mGain.mode == 0) {
5150 return;
5151 }
5152 mGains.add(gain);
5153}
5154
5155void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5156{
5157 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005158 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005159 while (node) {
5160 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005161 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005162 node = node->next;
5163 }
5164}
5165
Eric Laurenta121f902014-06-03 13:32:54 -07005166status_t AudioPolicyManager::AudioPort::checkSamplingRate(uint32_t samplingRate) const
5167{
5168 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5169 if (mSamplingRates[i] == samplingRate) {
5170 return NO_ERROR;
5171 }
5172 }
5173 return BAD_VALUE;
5174}
5175
5176status_t AudioPolicyManager::AudioPort::checkChannelMask(audio_channel_mask_t channelMask) const
5177{
5178 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5179 if (mChannelMasks[i] == channelMask) {
5180 return NO_ERROR;
5181 }
5182 }
5183 return BAD_VALUE;
5184}
5185
5186status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5187{
5188 for (size_t i = 0; i < mFormats.size(); i ++) {
5189 if (mFormats[i] == format) {
5190 return NO_ERROR;
5191 }
5192 }
5193 return BAD_VALUE;
5194}
5195
5196status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
5197 int index) const
5198{
5199 if (index < 0 || (size_t)index >= mGains.size()) {
5200 return BAD_VALUE;
5201 }
5202 return mGains[index]->checkConfig(gainConfig);
5203}
5204
Eric Laurent1afeecb2014-05-14 08:52:28 -07005205void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5206{
5207 const size_t SIZE = 256;
5208 char buffer[SIZE];
5209 String8 result;
5210
5211 if (mName.size() != 0) {
5212 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5213 result.append(buffer);
5214 }
5215
5216 if (mSamplingRates.size() != 0) {
5217 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5218 result.append(buffer);
5219 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5220 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5221 result.append(buffer);
5222 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5223 }
5224 result.append("\n");
5225 }
5226
5227 if (mChannelMasks.size() != 0) {
5228 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5229 result.append(buffer);
5230 for (size_t i = 0; i < mChannelMasks.size(); i++) {
5231 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
5232 result.append(buffer);
5233 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
5234 }
5235 result.append("\n");
5236 }
5237
5238 if (mFormats.size() != 0) {
5239 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
5240 result.append(buffer);
5241 for (size_t i = 0; i < mFormats.size(); i++) {
5242 snprintf(buffer, SIZE, "%-48s", enumToString(sFormatNameToEnumTable,
5243 ARRAY_SIZE(sFormatNameToEnumTable),
5244 mFormats[i]));
5245 result.append(buffer);
5246 result.append(i == (mFormats.size() - 1) ? "" : ", ");
5247 }
5248 result.append("\n");
5249 }
5250 write(fd, result.string(), result.size());
5251 if (mGains.size() != 0) {
5252 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
5253 write(fd, buffer, strlen(buffer) + 1);
5254 result.append(buffer);
5255 for (size_t i = 0; i < mGains.size(); i++) {
5256 mGains[i]->dump(fd, spaces + 2, i);
5257 }
5258 }
5259}
5260
5261// --- AudioGain class implementation
5262
Eric Laurenta121f902014-06-03 13:32:54 -07005263AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005264{
Eric Laurenta121f902014-06-03 13:32:54 -07005265 mIndex = index;
5266 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005267 memset(&mGain, 0, sizeof(struct audio_gain));
5268}
5269
Eric Laurenta121f902014-06-03 13:32:54 -07005270void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
5271{
5272 config->index = mIndex;
5273 config->mode = mGain.mode;
5274 config->channel_mask = mGain.channel_mask;
5275 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5276 config->values[0] = mGain.default_value;
5277 } else {
5278 uint32_t numValues;
5279 if (mUseInChannelMask) {
5280 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
5281 } else {
5282 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
5283 }
5284 for (size_t i = 0; i < numValues; i++) {
5285 config->values[i] = mGain.default_value;
5286 }
5287 }
5288 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5289 config->ramp_duration_ms = mGain.min_ramp_ms;
5290 }
5291}
5292
5293status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
5294{
5295 if ((config->mode & ~mGain.mode) != 0) {
5296 return BAD_VALUE;
5297 }
5298 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5299 if ((config->values[0] < mGain.min_value) ||
5300 (config->values[0] > mGain.max_value)) {
5301 return BAD_VALUE;
5302 }
5303 } else {
5304 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
5305 return BAD_VALUE;
5306 }
5307 uint32_t numValues;
5308 if (mUseInChannelMask) {
5309 numValues = audio_channel_count_from_in_mask(config->channel_mask);
5310 } else {
5311 numValues = audio_channel_count_from_out_mask(config->channel_mask);
5312 }
5313 for (size_t i = 0; i < numValues; i++) {
5314 if ((config->values[i] < mGain.min_value) ||
5315 (config->values[i] > mGain.max_value)) {
5316 return BAD_VALUE;
5317 }
5318 }
5319 }
5320 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5321 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
5322 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
5323 return BAD_VALUE;
5324 }
5325 }
5326 return NO_ERROR;
5327}
5328
Eric Laurent1afeecb2014-05-14 08:52:28 -07005329void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
5330{
5331 const size_t SIZE = 256;
5332 char buffer[SIZE];
5333 String8 result;
5334
5335 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
5336 result.append(buffer);
5337 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
5338 result.append(buffer);
5339 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
5340 result.append(buffer);
5341 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
5342 result.append(buffer);
5343 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
5344 result.append(buffer);
5345 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
5346 result.append(buffer);
5347 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
5348 result.append(buffer);
5349 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
5350 result.append(buffer);
5351 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
5352 result.append(buffer);
5353
5354 write(fd, result.string(), result.size());
5355}
5356
Eric Laurent1f2f2232014-06-02 12:01:23 -07005357// --- AudioPortConfig class implementation
5358
5359AudioPolicyManager::AudioPortConfig::AudioPortConfig()
5360{
5361 mSamplingRate = 0;
5362 mChannelMask = AUDIO_CHANNEL_NONE;
5363 mFormat = AUDIO_FORMAT_INVALID;
5364 mGain.index = -1;
5365}
5366
Eric Laurenta121f902014-06-03 13:32:54 -07005367status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
5368 const struct audio_port_config *config,
5369 struct audio_port_config *backupConfig)
5370{
5371 struct audio_port_config localBackupConfig;
5372 status_t status = NO_ERROR;
5373
5374 localBackupConfig.config_mask = config->config_mask;
5375 toAudioPortConfig(&localBackupConfig);
5376
5377 if (mAudioPort == 0) {
5378 status = NO_INIT;
5379 goto exit;
5380 }
5381 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5382 status = mAudioPort->checkSamplingRate(config->sample_rate);
5383 if (status != NO_ERROR) {
5384 goto exit;
5385 }
5386 mSamplingRate = config->sample_rate;
5387 }
5388 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5389 status = mAudioPort->checkChannelMask(config->channel_mask);
5390 if (status != NO_ERROR) {
5391 goto exit;
5392 }
5393 mChannelMask = config->channel_mask;
5394 }
5395 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5396 status = mAudioPort->checkFormat(config->format);
5397 if (status != NO_ERROR) {
5398 goto exit;
5399 }
5400 mFormat = config->format;
5401 }
5402 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5403 status = mAudioPort->checkGain(&config->gain, config->gain.index);
5404 if (status != NO_ERROR) {
5405 goto exit;
5406 }
5407 mGain = config->gain;
5408 }
5409
5410exit:
5411 if (status != NO_ERROR) {
5412 applyAudioPortConfig(&localBackupConfig);
5413 }
5414 if (backupConfig != NULL) {
5415 *backupConfig = localBackupConfig;
5416 }
5417 return status;
5418}
5419
Eric Laurent1f2f2232014-06-02 12:01:23 -07005420void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
5421 struct audio_port_config *dstConfig,
5422 const struct audio_port_config *srcConfig) const
5423{
5424 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5425 dstConfig->sample_rate = mSamplingRate;
5426 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
5427 dstConfig->sample_rate = srcConfig->sample_rate;
5428 }
5429 } else {
5430 dstConfig->sample_rate = 0;
5431 }
5432 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5433 dstConfig->channel_mask = mChannelMask;
5434 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
5435 dstConfig->channel_mask = srcConfig->channel_mask;
5436 }
5437 } else {
5438 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
5439 }
5440 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5441 dstConfig->format = mFormat;
5442 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
5443 dstConfig->format = srcConfig->format;
5444 }
5445 } else {
5446 dstConfig->format = AUDIO_FORMAT_INVALID;
5447 }
5448 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5449 dstConfig->gain = mGain;
5450 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
5451 dstConfig->gain = srcConfig->gain;
5452 }
5453 } else {
5454 dstConfig->gain.index = -1;
5455 }
5456 if (dstConfig->gain.index != -1) {
5457 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
5458 } else {
5459 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
5460 }
5461}
5462
Eric Laurent1c333e22014-05-20 10:48:17 -07005463// --- IOProfile class implementation
5464
Eric Laurent1afeecb2014-05-14 08:52:28 -07005465AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07005466 const sp<HwModule>& module)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005467 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module), mFlags((audio_output_flags_t)0)
Eric Laurente552edb2014-03-10 17:42:56 -07005468{
5469}
5470
Eric Laurente0720872014-03-11 09:30:41 -07005471AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07005472{
5473}
5474
5475// checks if the IO profile is compatible with specified parameters.
5476// Sampling rate, format and channel mask must be specified in order to
5477// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07005478bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07005479 uint32_t samplingRate,
5480 audio_format_t format,
5481 audio_channel_mask_t channelMask,
5482 audio_output_flags_t flags) const
5483{
5484 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
5485 return false;
5486 }
5487
Eric Laurent3a4311c2014-03-17 12:00:47 -07005488 if ((mSupportedDevices.types() & device) != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07005489 return false;
5490 }
5491 if ((mFlags & flags) != flags) {
5492 return false;
5493 }
Eric Laurenta121f902014-06-03 13:32:54 -07005494 if (checkSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005495 return false;
5496 }
Eric Laurenta121f902014-06-03 13:32:54 -07005497 if (checkChannelMask(channelMask) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005498 return false;
5499 }
Eric Laurenta121f902014-06-03 13:32:54 -07005500 if (checkFormat(format) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005501 return false;
5502 }
5503 return true;
5504}
5505
Eric Laurente0720872014-03-11 09:30:41 -07005506void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005507{
5508 const size_t SIZE = 256;
5509 char buffer[SIZE];
5510 String8 result;
5511
Eric Laurent1afeecb2014-05-14 08:52:28 -07005512 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005513
Eric Laurente552edb2014-03-10 17:42:56 -07005514 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
5515 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005516 snprintf(buffer, SIZE, " - devices:\n");
5517 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005518 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07005519 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
5520 mSupportedDevices[i]->dump(fd, 6, i);
5521 }
Eric Laurente552edb2014-03-10 17:42:56 -07005522}
5523
Eric Laurentd4692962014-05-05 18:13:44 -07005524void AudioPolicyManager::IOProfile::log()
5525{
5526 const size_t SIZE = 256;
5527 char buffer[SIZE];
5528 String8 result;
5529
5530 ALOGV(" - sampling rates: ");
5531 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5532 ALOGV(" %d", mSamplingRates[i]);
5533 }
5534
5535 ALOGV(" - channel masks: ");
5536 for (size_t i = 0; i < mChannelMasks.size(); i++) {
5537 ALOGV(" 0x%04x", mChannelMasks[i]);
5538 }
5539
5540 ALOGV(" - formats: ");
5541 for (size_t i = 0; i < mFormats.size(); i++) {
5542 ALOGV(" 0x%08x", mFormats[i]);
5543 }
5544
5545 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
5546 ALOGV(" - flags: 0x%04x\n", mFlags);
5547}
5548
5549
Eric Laurent3a4311c2014-03-17 12:00:47 -07005550// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005551
Eric Laurent1f2f2232014-06-02 12:01:23 -07005552
5553AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
5554 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
5555 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
5556 AUDIO_PORT_ROLE_SOURCE,
5557 NULL),
5558 mDeviceType(type), mAddress(""),
5559 mChannelMask(AUDIO_CHANNEL_NONE), mId(0)
5560{
5561 mAudioPort = this;
Eric Laurenta121f902014-06-03 13:32:54 -07005562 if (mGains.size() > 0) {
5563 mGains[0]->getDefaultConfig(&mGain);
5564 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07005565}
5566
Eric Laurent3a4311c2014-03-17 12:00:47 -07005567bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07005568{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005569 // Devices are considered equal if they:
5570 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
5571 // - have the same address or one device does not specify the address
5572 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07005573 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005574 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07005575 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07005576 mChannelMask == other->mChannelMask);
5577}
5578
5579void AudioPolicyManager::DeviceVector::refreshTypes()
5580{
Eric Laurent1c333e22014-05-20 10:48:17 -07005581 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005582 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005583 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005584 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005585 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005586}
5587
5588ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
5589{
5590 for(size_t i = 0; i < size(); i++) {
5591 if (item->equals(itemAt(i))) {
5592 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07005593 }
5594 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005595 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07005596}
5597
Eric Laurent3a4311c2014-03-17 12:00:47 -07005598ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07005599{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005600 ssize_t ret = indexOf(item);
5601
5602 if (ret < 0) {
5603 ret = SortedVector::add(item);
5604 if (ret >= 0) {
5605 refreshTypes();
5606 }
5607 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07005608 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005609 ret = -1;
5610 }
5611 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07005612}
5613
Eric Laurent3a4311c2014-03-17 12:00:47 -07005614ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
5615{
5616 size_t i;
5617 ssize_t ret = indexOf(item);
5618
5619 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005620 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005621 } else {
5622 ret = SortedVector::removeAt(ret);
5623 if (ret >= 0) {
5624 refreshTypes();
5625 }
5626 }
5627 return ret;
5628}
5629
5630void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
5631{
5632 DeviceVector deviceList;
5633
5634 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
5635 types &= ~role_bit;
5636
5637 while (types) {
5638 uint32_t i = 31 - __builtin_clz(types);
5639 uint32_t type = 1 << i;
5640 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005641 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07005642 }
5643}
5644
Eric Laurent1afeecb2014-05-14 08:52:28 -07005645void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
5646 const DeviceVector& declaredDevices)
5647{
5648 char *devName = strtok(name, "|");
5649 while (devName != NULL) {
5650 if (strlen(devName) != 0) {
5651 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
5652 ARRAY_SIZE(sDeviceNameToEnumTable),
5653 devName);
5654 if (type != AUDIO_DEVICE_NONE) {
5655 add(new DeviceDescriptor(String8(""), type));
5656 } else {
5657 sp<DeviceDescriptor> deviceDesc =
5658 declaredDevices.getDeviceFromName(String8(devName));
5659 if (deviceDesc != 0) {
5660 add(deviceDesc);
5661 }
5662 }
5663 }
5664 devName = strtok(NULL, "|");
5665 }
5666}
5667
Eric Laurent1c333e22014-05-20 10:48:17 -07005668sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
5669 audio_devices_t type, String8 address) const
5670{
5671 sp<DeviceDescriptor> device;
5672 for (size_t i = 0; i < size(); i++) {
5673 if (itemAt(i)->mDeviceType == type) {
5674 device = itemAt(i);
5675 if (itemAt(i)->mAddress = address) {
5676 break;
5677 }
5678 }
5679 }
5680 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
5681 type, address.string(), device.get());
5682 return device;
5683}
5684
Eric Laurent6a94d692014-05-20 11:18:06 -07005685sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
5686 audio_port_handle_t id) const
5687{
5688 sp<DeviceDescriptor> device;
5689 for (size_t i = 0; i < size(); i++) {
5690 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%d)->mId %d", id, i, itemAt(i)->mId);
5691 if (itemAt(i)->mId == id) {
5692 device = itemAt(i);
5693 break;
5694 }
5695 }
5696 return device;
5697}
5698
Eric Laurent1c333e22014-05-20 10:48:17 -07005699AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
5700 audio_devices_t type) const
5701{
5702 DeviceVector devices;
5703 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
5704 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
5705 devices.add(itemAt(i));
5706 type &= ~itemAt(i)->mDeviceType;
5707 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
5708 itemAt(i)->mDeviceType, itemAt(i).get());
5709 }
5710 }
5711 return devices;
5712}
5713
Eric Laurent1afeecb2014-05-14 08:52:28 -07005714sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
5715 const String8& name) const
5716{
5717 sp<DeviceDescriptor> device;
5718 for (size_t i = 0; i < size(); i++) {
5719 if (itemAt(i)->mName == name) {
5720 device = itemAt(i);
5721 break;
5722 }
5723 }
5724 return device;
5725}
5726
Eric Laurent6a94d692014-05-20 11:18:06 -07005727void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
5728 struct audio_port_config *dstConfig,
5729 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07005730{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005731 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
5732 if (srcConfig != NULL) {
5733 dstConfig->config_mask &= srcConfig->config_mask;
5734 }
5735
5736 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
5737
Eric Laurent6a94d692014-05-20 11:18:06 -07005738 dstConfig->id = mId;
5739 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07005740 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005741 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005742 dstConfig->ext.device.type = mDeviceType;
5743 dstConfig->ext.device.hw_module = mModule->mHandle;
5744 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07005745}
5746
5747void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
5748{
Eric Laurente1715a42014-05-20 11:30:42 -07005749 ALOGV("DeviceVector::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07005750 AudioPort::toAudioPort(port);
5751 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07005752 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07005753 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07005754 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07005755 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
5756}
5757
Eric Laurent1afeecb2014-05-14 08:52:28 -07005758status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07005759{
5760 const size_t SIZE = 256;
5761 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07005762 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005763
Eric Laurent1afeecb2014-05-14 08:52:28 -07005764 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
5765 result.append(buffer);
5766 if (mId != 0) {
5767 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
5768 result.append(buffer);
5769 }
5770 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
5771 enumToString(sDeviceNameToEnumTable,
5772 ARRAY_SIZE(sDeviceNameToEnumTable),
5773 mDeviceType));
5774 result.append(buffer);
5775 if (mAddress.size() != 0) {
5776 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
5777 result.append(buffer);
5778 }
5779 if (mChannelMask != AUDIO_CHANNEL_NONE) {
5780 snprintf(buffer, SIZE, "%*s- channel mask: %08x\n", spaces, "", mChannelMask);
5781 result.append(buffer);
5782 }
5783 write(fd, result.string(), result.size());
5784 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005785
5786 return NO_ERROR;
5787}
5788
5789
5790// --- audio_policy.conf file parsing
5791
Eric Laurente0720872014-03-11 09:30:41 -07005792audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005793{
5794 uint32_t flag = 0;
5795
5796 // it is OK to cast name to non const here as we are not going to use it after
5797 // strtok() modifies it
5798 char *flagName = strtok(name, "|");
5799 while (flagName != NULL) {
5800 if (strlen(flagName) != 0) {
5801 flag |= stringToEnum(sFlagNameToEnumTable,
5802 ARRAY_SIZE(sFlagNameToEnumTable),
5803 flagName);
5804 }
5805 flagName = strtok(NULL, "|");
5806 }
5807 //force direct flag if offload flag is set: offloading implies a direct output stream
5808 // and all common behaviors are driven by checking only the direct flag
5809 // this should normally be set appropriately in the policy configuration file
5810 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
5811 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
5812 }
5813
5814 return (audio_output_flags_t)flag;
5815}
5816
Eric Laurente0720872014-03-11 09:30:41 -07005817audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07005818{
5819 uint32_t device = 0;
5820
5821 char *devName = strtok(name, "|");
5822 while (devName != NULL) {
5823 if (strlen(devName) != 0) {
5824 device |= stringToEnum(sDeviceNameToEnumTable,
5825 ARRAY_SIZE(sDeviceNameToEnumTable),
5826 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005827 }
Eric Laurente552edb2014-03-10 17:42:56 -07005828 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07005829 }
Eric Laurente552edb2014-03-10 17:42:56 -07005830 return device;
5831}
5832
Eric Laurente0720872014-03-11 09:30:41 -07005833void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005834{
Eric Laurente552edb2014-03-10 17:42:56 -07005835 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005836 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005837 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07005838
Eric Laurent1afeecb2014-05-14 08:52:28 -07005839 node = config_find(root, DEVICES_TAG);
5840 if (node != NULL) {
5841 node = node->first_child;
5842 while (node) {
5843 ALOGV("loadHwModule() loading device %s", node->name);
5844 status_t tmpStatus = module->loadDevice(node);
5845 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5846 status = tmpStatus;
5847 }
5848 node = node->next;
5849 }
5850 }
5851 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07005852 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005853 node = node->first_child;
5854 while (node) {
5855 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005856 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07005857 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5858 status = tmpStatus;
5859 }
5860 node = node->next;
5861 }
5862 }
5863 node = config_find(root, INPUTS_TAG);
5864 if (node != NULL) {
5865 node = node->first_child;
5866 while (node) {
5867 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005868 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07005869 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
5870 status = tmpStatus;
5871 }
5872 node = node->next;
5873 }
5874 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005875 loadGlobalConfig(root, module);
5876
Eric Laurente552edb2014-03-10 17:42:56 -07005877 if (status == NO_ERROR) {
5878 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07005879 }
5880}
5881
Eric Laurente0720872014-03-11 09:30:41 -07005882void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07005883{
5884 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
5885 if (node == NULL) {
5886 return;
5887 }
5888
5889 node = node->first_child;
5890 while (node) {
5891 ALOGV("loadHwModules() loading module %s", node->name);
5892 loadHwModule(node);
5893 node = node->next;
5894 }
5895}
5896
Eric Laurent1f2f2232014-06-02 12:01:23 -07005897void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07005898{
5899 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07005900
Eric Laurente552edb2014-03-10 17:42:56 -07005901 if (node == NULL) {
5902 return;
5903 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005904 DeviceVector declaredDevices;
5905 if (module != NULL) {
5906 declaredDevices = module->mDeclaredDevices;
5907 }
5908
Eric Laurente552edb2014-03-10 17:42:56 -07005909 node = node->first_child;
5910 while (node) {
5911 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005912 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
5913 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005914 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
5915 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005916 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005917 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07005918 ARRAY_SIZE(sDeviceNameToEnumTable),
5919 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005920 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005921 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005922 } else {
5923 ALOGW("loadGlobalConfig() default device not specified");
5924 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005925 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005926 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005927 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
5928 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005929 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07005930 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
5931 mSpeakerDrcEnabled = stringToBool((char *)node->value);
5932 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07005933 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
5934 uint32_t major, minor;
5935 sscanf((char *)node->value, "%u.%u", &major, &minor);
5936 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
5937 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
5938 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07005939 }
5940 node = node->next;
5941 }
5942}
5943
Eric Laurente0720872014-03-11 09:30:41 -07005944status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07005945{
5946 cnode *root;
5947 char *data;
5948
5949 data = (char *)load_file(path, NULL);
5950 if (data == NULL) {
5951 return -ENODEV;
5952 }
5953 root = config_node("", "");
5954 config_load(root, data);
5955
Eric Laurente552edb2014-03-10 17:42:56 -07005956 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005957 // legacy audio_policy.conf files have one global_configuration section
5958 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07005959 config_free(root);
5960 free(root);
5961 free(data);
5962
5963 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
5964
5965 return NO_ERROR;
5966}
5967
Eric Laurente0720872014-03-11 09:30:41 -07005968void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07005969{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005970 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07005971 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005972 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
5973 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005974 mAvailableOutputDevices.add(mDefaultOutputDevice);
5975 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005976
5977 module = new HwModule("primary");
5978
Eric Laurent1afeecb2014-05-14 08:52:28 -07005979 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07005980 profile->mSamplingRates.add(44100);
5981 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
5982 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005983 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005984 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
5985 module->mOutputProfiles.add(profile);
5986
Eric Laurent1afeecb2014-05-14 08:52:28 -07005987 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07005988 profile->mSamplingRates.add(8000);
5989 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
5990 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07005991 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07005992 module->mInputProfiles.add(profile);
5993
5994 mHwModules.add(module);
5995}
5996
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07005997audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
5998{
5999 // flags to stream type mapping
6000 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6001 return AUDIO_STREAM_ENFORCED_AUDIBLE;
6002 }
6003 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6004 return AUDIO_STREAM_BLUETOOTH_SCO;
6005 }
6006
6007 // usage to stream type mapping
6008 switch (attr->usage) {
6009 case AUDIO_USAGE_MEDIA:
6010 case AUDIO_USAGE_GAME:
6011 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6012 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6013 return AUDIO_STREAM_MUSIC;
6014 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6015 return AUDIO_STREAM_SYSTEM;
6016 case AUDIO_USAGE_VOICE_COMMUNICATION:
6017 return AUDIO_STREAM_VOICE_CALL;
6018
6019 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6020 return AUDIO_STREAM_DTMF;
6021
6022 case AUDIO_USAGE_ALARM:
6023 return AUDIO_STREAM_ALARM;
6024 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6025 return AUDIO_STREAM_RING;
6026
6027 case AUDIO_USAGE_NOTIFICATION:
6028 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6029 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6030 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6031 case AUDIO_USAGE_NOTIFICATION_EVENT:
6032 return AUDIO_STREAM_NOTIFICATION;
6033
6034 case AUDIO_USAGE_UNKNOWN:
6035 default:
6036 return AUDIO_STREAM_MUSIC;
6037 }
6038}
Eric Laurente552edb2014-03-10 17:42:56 -07006039}; // namespace android