blob: 11490c36031ac0dfc3129540f4776e6e4bc26f05 [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>
41#include <hardware_legacy/audio_policy_conf.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070042#include <media/AudioParameter.h>
Eric Laurentd4692962014-05-05 18:13:44 -070043#include "AudioPolicyManager.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),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
79 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
80 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
81 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
82 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
83 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
84 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
85 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
86 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
87 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
88 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
89 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -070090 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent3a4311c2014-03-17 12:00:47 -070091};
92
93const StringToEnum sFlagNameToEnumTable[] = {
94 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
95 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
96 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
97 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
98 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
99 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
100};
101
102const StringToEnum sFormatNameToEnumTable[] = {
103 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
104 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
105 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
106 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
107 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
108 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
109 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
110 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
111 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
112};
113
114const StringToEnum sOutChannelsNameToEnumTable[] = {
115 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
116 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
117 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
118 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
119};
120
121const StringToEnum sInChannelsNameToEnumTable[] = {
122 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
123 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
124 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
125};
126
127
128uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
129 size_t size,
130 const char *name)
131{
132 for (size_t i = 0; i < size; i++) {
133 if (strcmp(table[i].name, name) == 0) {
134 ALOGV("stringToEnum() found %s", table[i].name);
135 return table[i].value;
136 }
137 }
138 return 0;
139}
140
141const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
142 size_t size,
143 uint32_t value)
144{
145 for (size_t i = 0; i < size; i++) {
146 if (table[i].value == value) {
147 return table[i].name;
148 }
149 }
150 return "";
151}
152
153bool AudioPolicyManager::stringToBool(const char *value)
154{
155 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
156}
157
158
159// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700160// AudioPolicyInterface implementation
161// ----------------------------------------------------------------------------
162
163
Eric Laurente0720872014-03-11 09:30:41 -0700164status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700165 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700166 const char *device_address)
167{
Eric Laurent3a4311c2014-03-17 12:00:47 -0700168 String8 address = String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700169
170 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
171
172 // connect/disconnect only 1 device at a time
173 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
174
Eric Laurente552edb2014-03-10 17:42:56 -0700175 // handle output devices
176 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700177 SortedVector <audio_io_handle_t> outputs;
178
Eric Laurent3a4311c2014-03-17 12:00:47 -0700179 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(device,
180 address,
Eric Laurent2f8a36f2014-03-26 19:05:55 -0700181 0);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700182 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
183
Eric Laurente552edb2014-03-10 17:42:56 -0700184 // save a copy of the opened output descriptors before any output is opened or closed
185 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
186 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700187 switch (state)
188 {
189 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700190 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700192 ALOGW("setDeviceConnectionState() device already connected: %x", device);
193 return INVALID_OPERATION;
194 }
195 ALOGV("setDeviceConnectionState() connecting device %x", device);
196
Eric Laurent3a4311c2014-03-17 12:00:47 -0700197 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -0700198 return INVALID_OPERATION;
199 }
Eric Laurentd4692962014-05-05 18:13:44 -0700200 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
Eric Laurente552edb2014-03-10 17:42:56 -0700201 outputs.size());
202 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700203 index = mAvailableOutputDevices.add(devDesc);
204 if (index >= 0) {
205 mAvailableOutputDevices[index]->mId = nextUniqueId();
206 } else {
207 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700208 }
209
210 break;
211 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700212 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700213 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700214 ALOGW("setDeviceConnectionState() device not connected: %x", device);
215 return INVALID_OPERATION;
216 }
217
218 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
219 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700220 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700221
Eric Laurent3a4311c2014-03-17 12:00:47 -0700222 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700223 // not currently handling multiple simultaneous submixes: ignoring remote submix
224 // case and address
225 } break;
226
227 default:
228 ALOGE("setDeviceConnectionState() invalid state: %x", state);
229 return BAD_VALUE;
230 }
231
Eric Laurent3a4311c2014-03-17 12:00:47 -0700232 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
233 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700234 checkA2dpSuspend();
235 checkOutputForAllStrategies();
236 // outputs must be closed after checkOutputForAllStrategies() is executed
237 if (!outputs.isEmpty()) {
238 for (size_t i = 0; i < outputs.size(); i++) {
239 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
240 // close unused outputs after device disconnection or direct outputs that have been
241 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700242 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700243 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
244 (desc->mDirectOpenCount == 0))) {
245 closeOutput(outputs[i]);
246 }
247 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700248 // check again after closing A2DP output to reset mA2dpSuspended if needed
249 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700250 }
251
252 updateDevicesAndOutputs();
253 for (size_t i = 0; i < mOutputs.size(); i++) {
254 // do not force device change on duplicated output because if device is 0, it will
255 // also force a device 0 for the two outputs it is duplicated to which may override
256 // a valid device selection on those outputs.
257 setOutputDevice(mOutputs.keyAt(i),
258 getNewDevice(mOutputs.keyAt(i), true /*fromCache*/),
259 !mOutputs.valueAt(i)->isDuplicated(),
260 0);
261 }
262
263 if (device == AUDIO_DEVICE_OUT_WIRED_HEADSET) {
264 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
265 } else if (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO ||
266 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
267 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
268 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
269 } else {
270 return NO_ERROR;
271 }
Eric Laurentd4692962014-05-05 18:13:44 -0700272 } // end if is output device
273
Eric Laurente552edb2014-03-10 17:42:56 -0700274 // handle input devices
275 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700276 SortedVector <audio_io_handle_t> inputs;
277
Eric Laurent3a4311c2014-03-17 12:00:47 -0700278 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(device,
279 address,
Eric Laurent2f8a36f2014-03-26 19:05:55 -0700280 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700281
Eric Laurent3a4311c2014-03-17 12:00:47 -0700282 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700283 switch (state)
284 {
285 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700286 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700287 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700288 ALOGW("setDeviceConnectionState() device already connected: %d", device);
289 return INVALID_OPERATION;
290 }
Eric Laurentd4692962014-05-05 18:13:44 -0700291 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
292 return INVALID_OPERATION;
293 }
294
Eric Laurent3a4311c2014-03-17 12:00:47 -0700295 index = mAvailableInputDevices.add(devDesc);
296 if (index >= 0) {
297 mAvailableInputDevices[index]->mId = nextUniqueId();
298 } else {
299 return NO_MEMORY;
300 }
Eric Laurentd4692962014-05-05 18:13:44 -0700301 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700302
303 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700304 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700305 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700306 ALOGW("setDeviceConnectionState() device not connected: %d", device);
307 return INVALID_OPERATION;
308 }
Eric Laurentd4692962014-05-05 18:13:44 -0700309 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700310 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700311 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700312
313 default:
314 ALOGE("setDeviceConnectionState() invalid state: %x", state);
315 return BAD_VALUE;
316 }
317
Eric Laurentd4692962014-05-05 18:13:44 -0700318 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700319
320 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700321 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700322
323 ALOGW("setDeviceConnectionState() invalid device: %x", device);
324 return BAD_VALUE;
325}
326
Eric Laurente0720872014-03-11 09:30:41 -0700327audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700328 const char *device_address)
329{
Eric Laurent3b73df72014-03-11 09:06:29 -0700330 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700331 String8 address = String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700332 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(device,
333 String8(device_address),
Eric Laurent2f8a36f2014-03-26 19:05:55 -0700334 0);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700335 ssize_t index;
336 DeviceVector *deviceVector;
337
Eric Laurente552edb2014-03-10 17:42:56 -0700338 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700339 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700340 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700341 deviceVector = &mAvailableInputDevices;
342 } else {
343 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
344 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700345 }
346
Eric Laurent3a4311c2014-03-17 12:00:47 -0700347 index = deviceVector->indexOf(devDesc);
348 if (index >= 0) {
349 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
350 } else {
351 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
352 }
Eric Laurente552edb2014-03-10 17:42:56 -0700353}
354
Eric Laurente0720872014-03-11 09:30:41 -0700355void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700356{
357 ALOGV("setPhoneState() state %d", state);
358 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
Eric Laurent3b73df72014-03-11 09:06:29 -0700359 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700360 ALOGW("setPhoneState() invalid state %d", state);
361 return;
362 }
363
364 if (state == mPhoneState ) {
365 ALOGW("setPhoneState() setting same state %d", state);
366 return;
367 }
368
369 // if leaving call state, handle special case of active streams
370 // pertaining to sonification strategy see handleIncallSonification()
371 if (isInCall()) {
372 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700373 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
374 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700375 }
376 }
377
378 // store previous phone state for management of sonification strategy below
379 int oldState = mPhoneState;
380 mPhoneState = state;
381 bool force = false;
382
383 // are we entering or starting a call
384 if (!isStateInCall(oldState) && isStateInCall(state)) {
385 ALOGV(" Entering call in setPhoneState()");
386 // force routing command to audio hardware when starting a call
387 // even if no device change is needed
388 force = true;
389 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
390 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
391 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
392 }
393 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
394 ALOGV(" Exiting call in setPhoneState()");
395 // force routing command to audio hardware when exiting a call
396 // even if no device change is needed
397 force = true;
398 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
399 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
400 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
401 }
402 } else if (isStateInCall(state) && (state != oldState)) {
403 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
404 // force routing command to audio hardware when switching between telephony and VoIP
405 // even if no device change is needed
406 force = true;
407 }
408
409 // check for device and output changes triggered by new phone state
410 newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
411 checkA2dpSuspend();
412 checkOutputForAllStrategies();
413 updateDevicesAndOutputs();
414
415 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
416
417 // force routing command to audio hardware when ending call
418 // even if no device change is needed
419 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
420 newDevice = hwOutputDesc->device();
421 }
422
423 int delayMs = 0;
424 if (isStateInCall(state)) {
425 nsecs_t sysTime = systemTime();
426 for (size_t i = 0; i < mOutputs.size(); i++) {
427 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
428 // mute media and sonification strategies and delay device switch by the largest
429 // latency of any output where either strategy is active.
430 // This avoid sending the ring tone or music tail into the earpiece or headset.
431 if ((desc->isStrategyActive(STRATEGY_MEDIA,
432 SONIFICATION_HEADSET_MUSIC_DELAY,
433 sysTime) ||
434 desc->isStrategyActive(STRATEGY_SONIFICATION,
435 SONIFICATION_HEADSET_MUSIC_DELAY,
436 sysTime)) &&
437 (delayMs < (int)desc->mLatency*2)) {
438 delayMs = desc->mLatency*2;
439 }
440 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
441 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
442 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
443 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
444 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
445 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
446 }
447 }
448
449 // change routing is necessary
450 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
451
452 // if entering in call state, handle special case of active streams
453 // pertaining to sonification strategy see handleIncallSonification()
454 if (isStateInCall(state)) {
455 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700456 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
457 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700458 }
459 }
460
461 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700462 if (state == AUDIO_MODE_RINGTONE &&
463 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700464 mLimitRingtoneVolume = true;
465 } else {
466 mLimitRingtoneVolume = false;
467 }
468}
469
Eric Laurente0720872014-03-11 09:30:41 -0700470void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700471 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700472{
473 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
474
475 bool forceVolumeReeval = false;
476 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700477 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
478 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
479 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700480 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
481 return;
482 }
483 forceVolumeReeval = true;
484 mForceUse[usage] = config;
485 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700486 case AUDIO_POLICY_FORCE_FOR_MEDIA:
487 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
488 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
489 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
490 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
491 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700492 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
493 return;
494 }
495 mForceUse[usage] = config;
496 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700497 case AUDIO_POLICY_FORCE_FOR_RECORD:
498 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
499 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700500 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
501 return;
502 }
503 mForceUse[usage] = config;
504 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700505 case AUDIO_POLICY_FORCE_FOR_DOCK:
506 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
507 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
508 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
509 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
510 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700511 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
512 }
513 forceVolumeReeval = true;
514 mForceUse[usage] = config;
515 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700516 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
517 if (config != AUDIO_POLICY_FORCE_NONE &&
518 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700519 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
520 }
521 forceVolumeReeval = true;
522 mForceUse[usage] = config;
523 break;
524 default:
525 ALOGW("setForceUse() invalid usage %d", usage);
526 break;
527 }
528
529 // check for device and output changes triggered by new force usage
530 checkA2dpSuspend();
531 checkOutputForAllStrategies();
532 updateDevicesAndOutputs();
533 for (size_t i = 0; i < mOutputs.size(); i++) {
534 audio_io_handle_t output = mOutputs.keyAt(i);
535 audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
536 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
537 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
538 applyStreamVolumes(output, newDevice, 0, true);
539 }
540 }
541
542 audio_io_handle_t activeInput = getActiveInput();
543 if (activeInput != 0) {
544 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
545 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
546 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
547 ALOGV("setForceUse() changing device from %x to %x for input %d",
548 inputDesc->mDevice, newDevice, activeInput);
549 inputDesc->mDevice = newDevice;
550 AudioParameter param = AudioParameter();
551 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
552 mpClientInterface->setParameters(activeInput, param.toString());
553 }
554 }
555
556}
557
Eric Laurente0720872014-03-11 09:30:41 -0700558audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700559{
560 return mForceUse[usage];
561}
562
Eric Laurente0720872014-03-11 09:30:41 -0700563void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700564{
565 ALOGV("setSystemProperty() property %s, value %s", property, value);
566}
567
568// Find a direct output profile compatible with the parameters passed, even if the input flags do
569// not explicitly request a direct output
Eric Laurente0720872014-03-11 09:30:41 -0700570AudioPolicyManager::IOProfile *AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700571 audio_devices_t device,
572 uint32_t samplingRate,
573 audio_format_t format,
574 audio_channel_mask_t channelMask,
575 audio_output_flags_t flags)
576{
577 for (size_t i = 0; i < mHwModules.size(); i++) {
578 if (mHwModules[i]->mHandle == 0) {
579 continue;
580 }
581 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
582 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent3a4311c2014-03-17 12:00:47 -0700583 bool found = false;
Eric Laurente552edb2014-03-10 17:42:56 -0700584 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
585 if (profile->isCompatibleProfile(device, samplingRate, format,
586 channelMask,
587 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700588 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700589 }
590 } else {
591 if (profile->isCompatibleProfile(device, samplingRate, format,
592 channelMask,
593 AUDIO_OUTPUT_FLAG_DIRECT)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700594 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700595 }
596 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700597 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
598 return profile;
599 }
Eric Laurente552edb2014-03-10 17:42:56 -0700600 }
601 }
602 return 0;
603}
604
Eric Laurente0720872014-03-11 09:30:41 -0700605audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700606 uint32_t samplingRate,
607 audio_format_t format,
608 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700609 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700610 const audio_offload_info_t *offloadInfo)
611{
612 audio_io_handle_t output = 0;
613 uint32_t latency = 0;
Eric Laurent3b73df72014-03-11 09:06:29 -0700614 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700615 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
616 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
617 device, stream, samplingRate, format, channelMask, flags);
618
619#ifdef AUDIO_POLICY_TEST
620 if (mCurOutput != 0) {
621 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
622 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
623
624 if (mTestOutputs[mCurOutput] == 0) {
625 ALOGV("getOutput() opening test output");
626 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
627 outputDesc->mDevice = mTestDevice;
628 outputDesc->mSamplingRate = mTestSamplingRate;
629 outputDesc->mFormat = mTestFormat;
630 outputDesc->mChannelMask = mTestChannels;
631 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700632 outputDesc->mFlags =
633 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700634 outputDesc->mRefCount[stream] = 0;
635 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
636 &outputDesc->mSamplingRate,
637 &outputDesc->mFormat,
638 &outputDesc->mChannelMask,
639 &outputDesc->mLatency,
640 outputDesc->mFlags,
641 offloadInfo);
642 if (mTestOutputs[mCurOutput]) {
643 AudioParameter outputCmd = AudioParameter();
644 outputCmd.addInt(String8("set_id"),mCurOutput);
645 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
646 addOutput(mTestOutputs[mCurOutput], outputDesc);
647 }
648 }
649 return mTestOutputs[mCurOutput];
650 }
651#endif //AUDIO_POLICY_TEST
652
653 // open a direct output if required by specified parameters
654 //force direct flag if offload flag is set: offloading implies a direct output stream
655 // and all common behaviors are driven by checking only the direct flag
656 // this should normally be set appropriately in the policy configuration file
657 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700658 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700659 }
660
661 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
662 // creating an offloaded track and tearing it down immediately after start when audioflinger
663 // detects there is an active non offloadable effect.
664 // FIXME: We should check the audio session here but we do not have it in this context.
665 // This may prevent offloading in rare situations where effects are left active by apps
666 // in the background.
667 IOProfile *profile = NULL;
668 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
669 !isNonOffloadableEffectEnabled()) {
670 profile = getProfileForDirectOutput(device,
671 samplingRate,
672 format,
673 channelMask,
674 (audio_output_flags_t)flags);
675 }
676
677 if (profile != NULL) {
678 AudioOutputDescriptor *outputDesc = NULL;
679
680 for (size_t i = 0; i < mOutputs.size(); i++) {
681 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
682 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
683 outputDesc = desc;
684 // reuse direct output if currently open and configured with same parameters
685 if ((samplingRate == outputDesc->mSamplingRate) &&
686 (format == outputDesc->mFormat) &&
687 (channelMask == outputDesc->mChannelMask)) {
688 outputDesc->mDirectOpenCount++;
689 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
690 return mOutputs.keyAt(i);
691 }
692 }
693 }
694 // close direct output if currently open and configured with different parameters
695 if (outputDesc != NULL) {
696 closeOutput(outputDesc->mId);
697 }
698 outputDesc = new AudioOutputDescriptor(profile);
699 outputDesc->mDevice = device;
700 outputDesc->mSamplingRate = samplingRate;
701 outputDesc->mFormat = format;
702 outputDesc->mChannelMask = channelMask;
703 outputDesc->mLatency = 0;
704 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
705 outputDesc->mRefCount[stream] = 0;
706 outputDesc->mStopTime[stream] = 0;
707 outputDesc->mDirectOpenCount = 1;
708 output = mpClientInterface->openOutput(profile->mModule->mHandle,
709 &outputDesc->mDevice,
710 &outputDesc->mSamplingRate,
711 &outputDesc->mFormat,
712 &outputDesc->mChannelMask,
713 &outputDesc->mLatency,
714 outputDesc->mFlags,
715 offloadInfo);
716
717 // only accept an output with the requested parameters
718 if (output == 0 ||
719 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
720 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
721 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
722 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
723 "format %d %d, channelMask %04x %04x", output, samplingRate,
724 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
725 outputDesc->mChannelMask);
726 if (output != 0) {
727 mpClientInterface->closeOutput(output);
728 }
729 delete outputDesc;
730 return 0;
731 }
732 audio_io_handle_t srcOutput = getOutputForEffect();
733 addOutput(output, outputDesc);
734 audio_io_handle_t dstOutput = getOutputForEffect();
735 if (dstOutput == output) {
736 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
737 }
738 mPreviousOutputs = mOutputs;
739 ALOGV("getOutput() returns new direct output %d", output);
740 return output;
741 }
742
743 // ignoring channel mask due to downmix capability in mixer
744
745 // open a non direct output
746
747 // for non direct outputs, only PCM is supported
748 if (audio_is_linear_pcm(format)) {
749 // get which output is suitable for the specified stream. The actual
750 // routing change will happen when startOutput() will be called
751 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
752
753 output = selectOutput(outputs, flags);
754 }
755 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
756 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
757
758 ALOGV("getOutput() returns output %d", output);
759
760 return output;
761}
762
Eric Laurente0720872014-03-11 09:30:41 -0700763audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700764 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700765{
766 // select one output among several that provide a path to a particular device or set of
767 // devices (the list was previously build by getOutputsForDevice()).
768 // The priority is as follows:
769 // 1: the output with the highest number of requested policy flags
770 // 2: the primary output
771 // 3: the first output in the list
772
773 if (outputs.size() == 0) {
774 return 0;
775 }
776 if (outputs.size() == 1) {
777 return outputs[0];
778 }
779
780 int maxCommonFlags = 0;
781 audio_io_handle_t outputFlags = 0;
782 audio_io_handle_t outputPrimary = 0;
783
784 for (size_t i = 0; i < outputs.size(); i++) {
785 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
786 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700787 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700788 if (commonFlags > maxCommonFlags) {
789 outputFlags = outputs[i];
790 maxCommonFlags = commonFlags;
791 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
792 }
793 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
794 outputPrimary = outputs[i];
795 }
796 }
797 }
798
799 if (outputFlags != 0) {
800 return outputFlags;
801 }
802 if (outputPrimary != 0) {
803 return outputPrimary;
804 }
805
806 return outputs[0];
807}
808
Eric Laurente0720872014-03-11 09:30:41 -0700809status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700810 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700811 int session)
812{
813 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
814 ssize_t index = mOutputs.indexOfKey(output);
815 if (index < 0) {
816 ALOGW("startOutput() unknown output %d", output);
817 return BAD_VALUE;
818 }
819
820 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
821
822 // increment usage count for this stream on the requested output:
823 // NOTE that the usage count is the same for duplicated output and hardware output which is
824 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
825 outputDesc->changeRefCount(stream, 1);
826
827 if (outputDesc->mRefCount[stream] == 1) {
828 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
829 routing_strategy strategy = getStrategy(stream);
830 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
831 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
832 uint32_t waitMs = 0;
833 bool force = false;
834 for (size_t i = 0; i < mOutputs.size(); i++) {
835 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
836 if (desc != outputDesc) {
837 // force a device change if any other output is managed by the same hw
838 // module and has a current device selection that differs from selected device.
839 // In this case, the audio HAL must receive the new device selection so that it can
840 // change the device currently selected by the other active output.
841 if (outputDesc->sharesHwModuleWith(desc) &&
842 desc->device() != newDevice) {
843 force = true;
844 }
845 // wait for audio on other active outputs to be presented when starting
846 // a notification so that audio focus effect can propagate.
847 uint32_t latency = desc->latency();
848 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
849 waitMs = latency;
850 }
851 }
852 }
853 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
854
855 // handle special case for sonification while in call
856 if (isInCall()) {
857 handleIncallSonification(stream, true, false);
858 }
859
860 // apply volume rules for current stream and device if necessary
861 checkAndSetVolume(stream,
862 mStreams[stream].getVolumeIndex(newDevice),
863 output,
864 newDevice);
865
866 // update the outputs if starting an output with a stream that can affect notification
867 // routing
868 handleNotificationRoutingForStream(stream);
869 if (waitMs > muteWaitMs) {
870 usleep((waitMs - muteWaitMs) * 2 * 1000);
871 }
872 }
873 return NO_ERROR;
874}
875
876
Eric Laurente0720872014-03-11 09:30:41 -0700877status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700878 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700879 int session)
880{
881 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
882 ssize_t index = mOutputs.indexOfKey(output);
883 if (index < 0) {
884 ALOGW("stopOutput() unknown output %d", output);
885 return BAD_VALUE;
886 }
887
888 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
889
890 // handle special case for sonification while in call
891 if (isInCall()) {
892 handleIncallSonification(stream, false, false);
893 }
894
895 if (outputDesc->mRefCount[stream] > 0) {
896 // decrement usage count of this stream on the output
897 outputDesc->changeRefCount(stream, -1);
898 // store time at which the stream was stopped - see isStreamActive()
899 if (outputDesc->mRefCount[stream] == 0) {
900 outputDesc->mStopTime[stream] = systemTime();
901 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
902 // delay the device switch by twice the latency because stopOutput() is executed when
903 // the track stop() command is received and at that time the audio track buffer can
904 // still contain data that needs to be drained. The latency only covers the audio HAL
905 // and kernel buffers. Also the latency does not always include additional delay in the
906 // audio path (audio DSP, CODEC ...)
907 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
908
909 // force restoring the device selection on other active outputs if it differs from the
910 // one being selected for this output
911 for (size_t i = 0; i < mOutputs.size(); i++) {
912 audio_io_handle_t curOutput = mOutputs.keyAt(i);
913 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
914 if (curOutput != output &&
915 desc->isActive() &&
916 outputDesc->sharesHwModuleWith(desc) &&
917 (newDevice != desc->device())) {
918 setOutputDevice(curOutput,
919 getNewDevice(curOutput, false /*fromCache*/),
920 true,
921 outputDesc->mLatency*2);
922 }
923 }
924 // update the outputs if stopping one with a stream that can affect notification routing
925 handleNotificationRoutingForStream(stream);
926 }
927 return NO_ERROR;
928 } else {
929 ALOGW("stopOutput() refcount is already 0 for output %d", output);
930 return INVALID_OPERATION;
931 }
932}
933
Eric Laurente0720872014-03-11 09:30:41 -0700934void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -0700935{
936 ALOGV("releaseOutput() %d", output);
937 ssize_t index = mOutputs.indexOfKey(output);
938 if (index < 0) {
939 ALOGW("releaseOutput() releasing unknown output %d", output);
940 return;
941 }
942
943#ifdef AUDIO_POLICY_TEST
944 int testIndex = testOutputIndex(output);
945 if (testIndex != 0) {
946 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
947 if (outputDesc->isActive()) {
948 mpClientInterface->closeOutput(output);
949 delete mOutputs.valueAt(index);
950 mOutputs.removeItem(output);
951 mTestOutputs[testIndex] = 0;
952 }
953 return;
954 }
955#endif //AUDIO_POLICY_TEST
956
957 AudioOutputDescriptor *desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -0700958 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700959 if (desc->mDirectOpenCount <= 0) {
960 ALOGW("releaseOutput() invalid open count %d for output %d",
961 desc->mDirectOpenCount, output);
962 return;
963 }
964 if (--desc->mDirectOpenCount == 0) {
965 closeOutput(output);
966 // If effects where present on the output, audioflinger moved them to the primary
967 // output by default: move them back to the appropriate output.
968 audio_io_handle_t dstOutput = getOutputForEffect();
969 if (dstOutput != mPrimaryOutput) {
970 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
971 }
972 }
973 }
974}
975
976
Eric Laurente0720872014-03-11 09:30:41 -0700977audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -0700978 uint32_t samplingRate,
979 audio_format_t format,
980 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700981 audio_in_acoustics_t acoustics)
Eric Laurente552edb2014-03-10 17:42:56 -0700982{
983 audio_io_handle_t input = 0;
984 audio_devices_t device = getDeviceForInputSource(inputSource);
985
986 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
987 inputSource, samplingRate, format, channelMask, acoustics);
988
989 if (device == AUDIO_DEVICE_NONE) {
990 ALOGW("getInput() could not find device for inputSource %d", inputSource);
991 return 0;
992 }
993
994 // adapt channel selection to input source
995 switch(inputSource) {
996 case AUDIO_SOURCE_VOICE_UPLINK:
997 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
998 break;
999 case AUDIO_SOURCE_VOICE_DOWNLINK:
1000 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1001 break;
1002 case AUDIO_SOURCE_VOICE_CALL:
1003 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1004 break;
1005 default:
1006 break;
1007 }
1008
1009 IOProfile *profile = getInputProfile(device,
1010 samplingRate,
1011 format,
1012 channelMask);
1013 if (profile == NULL) {
1014 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d, "
1015 "channelMask %04x",
1016 device, samplingRate, format, channelMask);
1017 return 0;
1018 }
1019
1020 if (profile->mModule->mHandle == 0) {
1021 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
1022 return 0;
1023 }
1024
1025 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
1026
1027 inputDesc->mInputSource = inputSource;
1028 inputDesc->mDevice = device;
1029 inputDesc->mSamplingRate = samplingRate;
1030 inputDesc->mFormat = format;
1031 inputDesc->mChannelMask = channelMask;
1032 inputDesc->mRefCount = 0;
1033 input = mpClientInterface->openInput(profile->mModule->mHandle,
1034 &inputDesc->mDevice,
1035 &inputDesc->mSamplingRate,
1036 &inputDesc->mFormat,
1037 &inputDesc->mChannelMask);
1038
1039 // only accept input with the exact requested set of parameters
1040 if (input == 0 ||
1041 (samplingRate != inputDesc->mSamplingRate) ||
1042 (format != inputDesc->mFormat) ||
1043 (channelMask != inputDesc->mChannelMask)) {
1044 ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1045 samplingRate, format, channelMask);
1046 if (input != 0) {
1047 mpClientInterface->closeInput(input);
1048 }
1049 delete inputDesc;
1050 return 0;
1051 }
Eric Laurentd4692962014-05-05 18:13:44 -07001052 addInput(input, inputDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001053 return input;
1054}
1055
Eric Laurente0720872014-03-11 09:30:41 -07001056status_t AudioPolicyManager::startInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001057{
1058 ALOGV("startInput() input %d", input);
1059 ssize_t index = mInputs.indexOfKey(input);
1060 if (index < 0) {
1061 ALOGW("startInput() unknown input %d", input);
1062 return BAD_VALUE;
1063 }
1064 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1065
1066#ifdef AUDIO_POLICY_TEST
1067 if (mTestInput == 0)
1068#endif //AUDIO_POLICY_TEST
1069 {
1070 // refuse 2 active AudioRecord clients at the same time except if the active input
1071 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
1072 audio_io_handle_t activeInput = getActiveInput();
1073 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
1074 AudioInputDescriptor *activeDesc = mInputs.valueFor(activeInput);
1075 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1076 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1077 stopInput(activeInput);
1078 releaseInput(activeInput);
1079 } else {
1080 ALOGW("startInput() input %d failed: other input already started", input);
1081 return INVALID_OPERATION;
1082 }
1083 }
1084 }
1085
1086 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
1087 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
1088 inputDesc->mDevice = newDevice;
1089 }
1090
1091 // automatically enable the remote submix output when input is started
1092 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1093 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001094 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001095 }
1096
1097 AudioParameter param = AudioParameter();
1098 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
1099
1100 int aliasSource = (inputDesc->mInputSource == AUDIO_SOURCE_HOTWORD) ?
1101 AUDIO_SOURCE_VOICE_RECOGNITION : inputDesc->mInputSource;
1102
1103 param.addInt(String8(AudioParameter::keyInputSource), aliasSource);
1104 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1105
1106 mpClientInterface->setParameters(input, param.toString());
1107
1108 inputDesc->mRefCount = 1;
1109 return NO_ERROR;
1110}
1111
Eric Laurente0720872014-03-11 09:30:41 -07001112status_t AudioPolicyManager::stopInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001113{
1114 ALOGV("stopInput() input %d", input);
1115 ssize_t index = mInputs.indexOfKey(input);
1116 if (index < 0) {
1117 ALOGW("stopInput() unknown input %d", input);
1118 return BAD_VALUE;
1119 }
1120 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1121
1122 if (inputDesc->mRefCount == 0) {
1123 ALOGW("stopInput() input %d already stopped", input);
1124 return INVALID_OPERATION;
1125 } else {
1126 // automatically disable the remote submix output when input is stopped
1127 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1128 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001129 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001130 }
1131
1132 AudioParameter param = AudioParameter();
1133 param.addInt(String8(AudioParameter::keyRouting), 0);
1134 mpClientInterface->setParameters(input, param.toString());
1135 inputDesc->mRefCount = 0;
1136 return NO_ERROR;
1137 }
1138}
1139
Eric Laurente0720872014-03-11 09:30:41 -07001140void AudioPolicyManager::releaseInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001141{
1142 ALOGV("releaseInput() %d", input);
1143 ssize_t index = mInputs.indexOfKey(input);
1144 if (index < 0) {
1145 ALOGW("releaseInput() releasing unknown input %d", input);
1146 return;
1147 }
1148 mpClientInterface->closeInput(input);
1149 delete mInputs.valueAt(index);
1150 mInputs.removeItem(input);
1151 ALOGV("releaseInput() exit");
1152}
1153
Eric Laurentd4692962014-05-05 18:13:44 -07001154void AudioPolicyManager::closeAllInputs() {
1155 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1156 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1157 }
1158 mInputs.clear();
1159}
1160
Eric Laurente0720872014-03-11 09:30:41 -07001161void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001162 int indexMin,
1163 int indexMax)
1164{
1165 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1166 if (indexMin < 0 || indexMin >= indexMax) {
1167 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1168 return;
1169 }
1170 mStreams[stream].mIndexMin = indexMin;
1171 mStreams[stream].mIndexMax = indexMax;
1172}
1173
Eric Laurente0720872014-03-11 09:30:41 -07001174status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001175 int index,
1176 audio_devices_t device)
1177{
1178
1179 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1180 return BAD_VALUE;
1181 }
1182 if (!audio_is_output_device(device)) {
1183 return BAD_VALUE;
1184 }
1185
1186 // Force max volume if stream cannot be muted
1187 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1188
1189 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1190 stream, device, index);
1191
1192 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1193 // clear all device specific values
1194 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1195 mStreams[stream].mIndexCur.clear();
1196 }
1197 mStreams[stream].mIndexCur.add(device, index);
1198
1199 // compute and apply stream volume on all outputs according to connected device
1200 status_t status = NO_ERROR;
1201 for (size_t i = 0; i < mOutputs.size(); i++) {
1202 audio_devices_t curDevice =
1203 getDeviceForVolume(mOutputs.valueAt(i)->device());
1204 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1205 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1206 if (volStatus != NO_ERROR) {
1207 status = volStatus;
1208 }
1209 }
1210 }
1211 return status;
1212}
1213
Eric Laurente0720872014-03-11 09:30:41 -07001214status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001215 int *index,
1216 audio_devices_t device)
1217{
1218 if (index == NULL) {
1219 return BAD_VALUE;
1220 }
1221 if (!audio_is_output_device(device)) {
1222 return BAD_VALUE;
1223 }
1224 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1225 // the strategy the stream belongs to.
1226 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1227 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1228 }
1229 device = getDeviceForVolume(device);
1230
1231 *index = mStreams[stream].getVolumeIndex(device);
1232 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1233 return NO_ERROR;
1234}
1235
Eric Laurente0720872014-03-11 09:30:41 -07001236audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001237 const SortedVector<audio_io_handle_t>& outputs)
1238{
1239 // select one output among several suitable for global effects.
1240 // The priority is as follows:
1241 // 1: An offloaded output. If the effect ends up not being offloadable,
1242 // AudioFlinger will invalidate the track and the offloaded output
1243 // will be closed causing the effect to be moved to a PCM output.
1244 // 2: A deep buffer output
1245 // 3: the first output in the list
1246
1247 if (outputs.size() == 0) {
1248 return 0;
1249 }
1250
1251 audio_io_handle_t outputOffloaded = 0;
1252 audio_io_handle_t outputDeepBuffer = 0;
1253
1254 for (size_t i = 0; i < outputs.size(); i++) {
1255 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001256 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001257 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1258 outputOffloaded = outputs[i];
1259 }
1260 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1261 outputDeepBuffer = outputs[i];
1262 }
1263 }
1264
1265 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1266 outputOffloaded, outputDeepBuffer);
1267 if (outputOffloaded != 0) {
1268 return outputOffloaded;
1269 }
1270 if (outputDeepBuffer != 0) {
1271 return outputDeepBuffer;
1272 }
1273
1274 return outputs[0];
1275}
1276
Eric Laurente0720872014-03-11 09:30:41 -07001277audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001278{
1279 // apply simple rule where global effects are attached to the same output as MUSIC streams
1280
Eric Laurent3b73df72014-03-11 09:06:29 -07001281 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001282 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1283 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1284
1285 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1286 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1287 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1288
1289 return output;
1290}
1291
Eric Laurente0720872014-03-11 09:30:41 -07001292status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001293 audio_io_handle_t io,
1294 uint32_t strategy,
1295 int session,
1296 int id)
1297{
1298 ssize_t index = mOutputs.indexOfKey(io);
1299 if (index < 0) {
1300 index = mInputs.indexOfKey(io);
1301 if (index < 0) {
1302 ALOGW("registerEffect() unknown io %d", io);
1303 return INVALID_OPERATION;
1304 }
1305 }
1306
1307 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1308 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1309 desc->name, desc->memoryUsage);
1310 return INVALID_OPERATION;
1311 }
1312 mTotalEffectsMemory += desc->memoryUsage;
1313 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1314 desc->name, io, strategy, session, id);
1315 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1316
1317 EffectDescriptor *pDesc = new EffectDescriptor();
1318 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1319 pDesc->mIo = io;
1320 pDesc->mStrategy = (routing_strategy)strategy;
1321 pDesc->mSession = session;
1322 pDesc->mEnabled = false;
1323
1324 mEffects.add(id, pDesc);
1325
1326 return NO_ERROR;
1327}
1328
Eric Laurente0720872014-03-11 09:30:41 -07001329status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001330{
1331 ssize_t index = mEffects.indexOfKey(id);
1332 if (index < 0) {
1333 ALOGW("unregisterEffect() unknown effect ID %d", id);
1334 return INVALID_OPERATION;
1335 }
1336
1337 EffectDescriptor *pDesc = mEffects.valueAt(index);
1338
1339 setEffectEnabled(pDesc, false);
1340
1341 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1342 ALOGW("unregisterEffect() memory %d too big for total %d",
1343 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1344 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1345 }
1346 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1347 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1348 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1349
1350 mEffects.removeItem(id);
1351 delete pDesc;
1352
1353 return NO_ERROR;
1354}
1355
Eric Laurente0720872014-03-11 09:30:41 -07001356status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001357{
1358 ssize_t index = mEffects.indexOfKey(id);
1359 if (index < 0) {
1360 ALOGW("unregisterEffect() unknown effect ID %d", id);
1361 return INVALID_OPERATION;
1362 }
1363
1364 return setEffectEnabled(mEffects.valueAt(index), enabled);
1365}
1366
Eric Laurente0720872014-03-11 09:30:41 -07001367status_t AudioPolicyManager::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001368{
1369 if (enabled == pDesc->mEnabled) {
1370 ALOGV("setEffectEnabled(%s) effect already %s",
1371 enabled?"true":"false", enabled?"enabled":"disabled");
1372 return INVALID_OPERATION;
1373 }
1374
1375 if (enabled) {
1376 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1377 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1378 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1379 return INVALID_OPERATION;
1380 }
1381 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1382 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1383 } else {
1384 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1385 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1386 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1387 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1388 }
1389 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1390 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1391 }
1392 pDesc->mEnabled = enabled;
1393 return NO_ERROR;
1394}
1395
Eric Laurente0720872014-03-11 09:30:41 -07001396bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001397{
1398 for (size_t i = 0; i < mEffects.size(); i++) {
1399 const EffectDescriptor * const pDesc = mEffects.valueAt(i);
1400 if (pDesc->mEnabled && (pDesc->mStrategy == STRATEGY_MEDIA) &&
1401 ((pDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
1402 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
1403 pDesc->mDesc.name, pDesc->mSession);
1404 return true;
1405 }
1406 }
1407 return false;
1408}
1409
Eric Laurente0720872014-03-11 09:30:41 -07001410bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001411{
1412 nsecs_t sysTime = systemTime();
1413 for (size_t i = 0; i < mOutputs.size(); i++) {
1414 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001415 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001416 return true;
1417 }
1418 }
1419 return false;
1420}
1421
Eric Laurente0720872014-03-11 09:30:41 -07001422bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001423 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001424{
1425 nsecs_t sysTime = systemTime();
1426 for (size_t i = 0; i < mOutputs.size(); i++) {
1427 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1428 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001429 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001430 return true;
1431 }
1432 }
1433 return false;
1434}
1435
Eric Laurente0720872014-03-11 09:30:41 -07001436bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001437{
1438 for (size_t i = 0; i < mInputs.size(); i++) {
1439 const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
1440 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001441 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001442 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1443 && (inputDescriptor->mRefCount > 0)) {
1444 return true;
1445 }
1446 }
1447 return false;
1448}
1449
1450
Eric Laurente0720872014-03-11 09:30:41 -07001451status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001452{
1453 const size_t SIZE = 256;
1454 char buffer[SIZE];
1455 String8 result;
1456
1457 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1458 result.append(buffer);
1459
1460 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1461 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001462 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1463 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001464 snprintf(buffer, SIZE, " Force use for communications %d\n",
1465 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001466 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001467 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001468 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001469 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001470 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001471 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001472 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001473 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001474 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001475
Eric Laurent3a4311c2014-03-17 12:00:47 -07001476 snprintf(buffer, SIZE, " Available output devices:\n");
1477 result.append(buffer);
1478 write(fd, result.string(), result.size());
1479 DeviceDescriptor::dumpHeader(fd, 2);
1480 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
1481 mAvailableOutputDevices[i]->dump(fd, 2);
1482 }
1483 snprintf(buffer, SIZE, "\n Available input devices:\n");
1484 write(fd, buffer, strlen(buffer));
1485 DeviceDescriptor::dumpHeader(fd, 2);
1486 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1487 mAvailableInputDevices[i]->dump(fd, 2);
1488 }
Eric Laurente552edb2014-03-10 17:42:56 -07001489
1490 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1491 write(fd, buffer, strlen(buffer));
1492 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001493 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001494 write(fd, buffer, strlen(buffer));
1495 mHwModules[i]->dump(fd);
1496 }
1497
1498 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1499 write(fd, buffer, strlen(buffer));
1500 for (size_t i = 0; i < mOutputs.size(); i++) {
1501 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1502 write(fd, buffer, strlen(buffer));
1503 mOutputs.valueAt(i)->dump(fd);
1504 }
1505
1506 snprintf(buffer, SIZE, "\nInputs dump:\n");
1507 write(fd, buffer, strlen(buffer));
1508 for (size_t i = 0; i < mInputs.size(); i++) {
1509 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1510 write(fd, buffer, strlen(buffer));
1511 mInputs.valueAt(i)->dump(fd);
1512 }
1513
1514 snprintf(buffer, SIZE, "\nStreams dump:\n");
1515 write(fd, buffer, strlen(buffer));
1516 snprintf(buffer, SIZE,
1517 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1518 write(fd, buffer, strlen(buffer));
Eric Laurent3b73df72014-03-11 09:06:29 -07001519 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001520 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001521 write(fd, buffer, strlen(buffer));
1522 mStreams[i].dump(fd);
1523 }
1524
1525 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1526 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1527 write(fd, buffer, strlen(buffer));
1528
1529 snprintf(buffer, SIZE, "Registered effects:\n");
1530 write(fd, buffer, strlen(buffer));
1531 for (size_t i = 0; i < mEffects.size(); i++) {
1532 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1533 write(fd, buffer, strlen(buffer));
1534 mEffects.valueAt(i)->dump(fd);
1535 }
1536
1537
1538 return NO_ERROR;
1539}
1540
1541// This function checks for the parameters which can be offloaded.
1542// This can be enhanced depending on the capability of the DSP and policy
1543// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001544bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001545{
1546 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001547 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001548 offloadInfo.sample_rate, offloadInfo.channel_mask,
1549 offloadInfo.format,
1550 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1551 offloadInfo.has_video);
1552
1553 // Check if offload has been disabled
1554 char propValue[PROPERTY_VALUE_MAX];
1555 if (property_get("audio.offload.disable", propValue, "0")) {
1556 if (atoi(propValue) != 0) {
1557 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1558 return false;
1559 }
1560 }
1561
1562 // Check if stream type is music, then only allow offload as of now.
1563 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1564 {
1565 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1566 return false;
1567 }
1568
1569 //TODO: enable audio offloading with video when ready
1570 if (offloadInfo.has_video)
1571 {
1572 ALOGV("isOffloadSupported: has_video == true, returning false");
1573 return false;
1574 }
1575
1576 //If duration is less than minimum value defined in property, return false
1577 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1578 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1579 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1580 return false;
1581 }
1582 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1583 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1584 return false;
1585 }
1586
1587 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1588 // creating an offloaded track and tearing it down immediately after start when audioflinger
1589 // detects there is an active non offloadable effect.
1590 // FIXME: We should check the audio session here but we do not have it in this context.
1591 // This may prevent offloading in rare situations where effects are left active by apps
1592 // in the background.
1593 if (isNonOffloadableEffectEnabled()) {
1594 return false;
1595 }
1596
1597 // See if there is a profile to support this.
1598 // AUDIO_DEVICE_NONE
1599 IOProfile *profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
1600 offloadInfo.sample_rate,
1601 offloadInfo.format,
1602 offloadInfo.channel_mask,
1603 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1604 ALOGV("isOffloadSupported() profile %sfound", profile != NULL ? "" : "NOT ");
1605 return (profile != NULL);
1606}
1607
1608// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07001609// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07001610// ----------------------------------------------------------------------------
1611
Eric Laurent3a4311c2014-03-17 12:00:47 -07001612uint32_t AudioPolicyManager::nextUniqueId()
1613{
1614 return android_atomic_inc(&mNextUniqueId);
1615}
1616
Eric Laurente0720872014-03-11 09:30:41 -07001617AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07001618 :
1619#ifdef AUDIO_POLICY_TEST
1620 Thread(false),
1621#endif //AUDIO_POLICY_TEST
1622 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07001623 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07001624 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1625 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07001626 mA2dpSuspended(false),
1627 mSpeakerDrcEnabled(false), mNextUniqueId(0)
Eric Laurente552edb2014-03-10 17:42:56 -07001628{
1629 mpClientInterface = clientInterface;
1630
Eric Laurent3b73df72014-03-11 09:06:29 -07001631 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
1632 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001633 }
1634
Eric Laurent3a4311c2014-03-17 12:00:47 -07001635 mDefaultOutputDevice = new DeviceDescriptor(AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07001636 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
1637 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1638 ALOGE("could not load audio policy configuration file, setting defaults");
1639 defaultAudioPolicyConfig();
1640 }
1641 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07001642 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07001643
1644 // must be done after reading the policy
1645 initializeVolumeCurves();
1646
1647 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07001648 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
1649 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07001650 for (size_t i = 0; i < mHwModules.size(); i++) {
1651 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
1652 if (mHwModules[i]->mHandle == 0) {
1653 ALOGW("could not open HW module %s", mHwModules[i]->mName);
1654 continue;
1655 }
1656 // open all output streams needed to access attached devices
1657 // except for direct output streams that are only opened when they are actually
1658 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07001659 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07001660 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1661 {
1662 const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
1663
Eric Laurent3a4311c2014-03-17 12:00:47 -07001664 if (outProfile->mSupportedDevices.isEmpty()) {
1665 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
1666 continue;
1667 }
1668
1669 audio_devices_t profileTypes = outProfile->mSupportedDevices.types();
1670 if ((profileTypes & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07001671 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
1672 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001673
1674 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice->mType & profileTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07001675 audio_io_handle_t output = mpClientInterface->openOutput(
1676 outProfile->mModule->mHandle,
1677 &outputDesc->mDevice,
1678 &outputDesc->mSamplingRate,
1679 &outputDesc->mFormat,
1680 &outputDesc->mChannelMask,
1681 &outputDesc->mLatency,
1682 outputDesc->mFlags);
1683 if (output == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07001684 ALOGW("Cannot open output stream for device %08x on hw module %s",
1685 outputDesc->mDevice,
1686 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07001687 delete outputDesc;
1688 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07001689 for (size_t i = 0; i < outProfile->mSupportedDevices.size(); i++) {
1690 audio_devices_t type = outProfile->mSupportedDevices[i]->mType;
1691 ssize_t index =
1692 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[i]);
1693 // give a valid ID to an attached device once confirmed it is reachable
1694 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
1695 mAvailableOutputDevices[index]->mId = nextUniqueId();
1696 }
1697 }
Eric Laurente552edb2014-03-10 17:42:56 -07001698 if (mPrimaryOutput == 0 &&
1699 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1700 mPrimaryOutput = output;
1701 }
1702 addOutput(output, outputDesc);
1703 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07001704 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07001705 true);
1706 }
1707 }
1708 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07001709 // open input streams needed to access attached devices to validate
1710 // mAvailableInputDevices list
1711 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
1712 {
1713 const IOProfile *inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07001714
Eric Laurent3a4311c2014-03-17 12:00:47 -07001715 if (inProfile->mSupportedDevices.isEmpty()) {
1716 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
1717 continue;
1718 }
1719
1720 audio_devices_t profileTypes = inProfile->mSupportedDevices.types();
1721 if (profileTypes & inputDeviceTypes) {
1722 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(inProfile);
1723
1724 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
1725 inputDesc->mDevice = inProfile->mSupportedDevices[0]->mType;
1726 audio_io_handle_t input = mpClientInterface->openInput(
1727 inProfile->mModule->mHandle,
1728 &inputDesc->mDevice,
1729 &inputDesc->mSamplingRate,
1730 &inputDesc->mFormat,
1731 &inputDesc->mChannelMask);
1732
1733 if (input != 0) {
1734 for (size_t i = 0; i < inProfile->mSupportedDevices.size(); i++) {
1735 audio_devices_t type = inProfile->mSupportedDevices[i]->mType;
1736 ssize_t index =
1737 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[i]);
1738 // give a valid ID to an attached device once confirmed it is reachable
1739 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
1740 mAvailableInputDevices[index]->mId = nextUniqueId();
1741 }
1742 }
1743 mpClientInterface->closeInput(input);
1744 } else {
1745 ALOGW("Cannot open input stream for device %08x on hw module %s",
1746 inputDesc->mDevice,
1747 mHwModules[i]->mName);
1748 }
1749 delete inputDesc;
1750 }
1751 }
1752 }
1753 // make sure all attached devices have been allocated a unique ID
1754 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
1755 if (mAvailableOutputDevices[i]->mId == 0) {
1756 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mType);
1757 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
1758 continue;
1759 }
1760 i++;
1761 }
1762 for (size_t i = 0; i < mAvailableInputDevices.size();) {
1763 if (mAvailableInputDevices[i]->mId == 0) {
1764 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mType);
1765 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
1766 continue;
1767 }
1768 i++;
1769 }
1770 // make sure default device is reachable
1771 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
1772 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mType);
1773 }
Eric Laurente552edb2014-03-10 17:42:56 -07001774
1775 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1776
1777 updateDevicesAndOutputs();
1778
1779#ifdef AUDIO_POLICY_TEST
1780 if (mPrimaryOutput != 0) {
1781 AudioParameter outputCmd = AudioParameter();
1782 outputCmd.addInt(String8("set_id"), 0);
1783 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1784
1785 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
1786 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07001787 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
1788 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07001789 mTestLatencyMs = 0;
1790 mCurOutput = 0;
1791 mDirectOutput = false;
1792 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1793 mTestOutputs[i] = 0;
1794 }
1795
1796 const size_t SIZE = 256;
1797 char buffer[SIZE];
1798 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1799 run(buffer, ANDROID_PRIORITY_AUDIO);
1800 }
1801#endif //AUDIO_POLICY_TEST
1802}
1803
Eric Laurente0720872014-03-11 09:30:41 -07001804AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07001805{
1806#ifdef AUDIO_POLICY_TEST
1807 exit();
1808#endif //AUDIO_POLICY_TEST
1809 for (size_t i = 0; i < mOutputs.size(); i++) {
1810 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1811 delete mOutputs.valueAt(i);
1812 }
1813 for (size_t i = 0; i < mInputs.size(); i++) {
1814 mpClientInterface->closeInput(mInputs.keyAt(i));
1815 delete mInputs.valueAt(i);
1816 }
1817 for (size_t i = 0; i < mHwModules.size(); i++) {
1818 delete mHwModules[i];
1819 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07001820 mAvailableOutputDevices.clear();
1821 mAvailableInputDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07001822}
1823
Eric Laurente0720872014-03-11 09:30:41 -07001824status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07001825{
1826 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1827}
1828
1829#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07001830bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07001831{
1832 ALOGV("entering threadLoop()");
1833 while (!exitPending())
1834 {
1835 String8 command;
1836 int valueInt;
1837 String8 value;
1838
1839 Mutex::Autolock _l(mLock);
1840 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1841
1842 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1843 AudioParameter param = AudioParameter(command);
1844
1845 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1846 valueInt != 0) {
1847 ALOGV("Test command %s received", command.string());
1848 String8 target;
1849 if (param.get(String8("target"), target) != NO_ERROR) {
1850 target = "Manager";
1851 }
1852 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1853 param.remove(String8("test_cmd_policy_output"));
1854 mCurOutput = valueInt;
1855 }
1856 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1857 param.remove(String8("test_cmd_policy_direct"));
1858 if (value == "false") {
1859 mDirectOutput = false;
1860 } else if (value == "true") {
1861 mDirectOutput = true;
1862 }
1863 }
1864 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1865 param.remove(String8("test_cmd_policy_input"));
1866 mTestInput = valueInt;
1867 }
1868
1869 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1870 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07001871 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001872 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07001873 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07001874 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07001875 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07001876 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07001877 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07001878 }
Eric Laurent3b73df72014-03-11 09:06:29 -07001879 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07001880 if (target == "Manager") {
1881 mTestFormat = format;
1882 } else if (mTestOutputs[mCurOutput] != 0) {
1883 AudioParameter outputParam = AudioParameter();
1884 outputParam.addInt(String8("format"), format);
1885 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1886 }
1887 }
1888 }
1889 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1890 param.remove(String8("test_cmd_policy_channels"));
1891 int channels = 0;
1892
1893 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07001894 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07001895 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07001896 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07001897 }
1898 if (channels != 0) {
1899 if (target == "Manager") {
1900 mTestChannels = channels;
1901 } else if (mTestOutputs[mCurOutput] != 0) {
1902 AudioParameter outputParam = AudioParameter();
1903 outputParam.addInt(String8("channels"), channels);
1904 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1905 }
1906 }
1907 }
1908 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1909 param.remove(String8("test_cmd_policy_sampleRate"));
1910 if (valueInt >= 0 && valueInt <= 96000) {
1911 int samplingRate = valueInt;
1912 if (target == "Manager") {
1913 mTestSamplingRate = samplingRate;
1914 } else if (mTestOutputs[mCurOutput] != 0) {
1915 AudioParameter outputParam = AudioParameter();
1916 outputParam.addInt(String8("sampling_rate"), samplingRate);
1917 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1918 }
1919 }
1920 }
1921
1922 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1923 param.remove(String8("test_cmd_policy_reopen"));
1924
1925 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
1926 mpClientInterface->closeOutput(mPrimaryOutput);
1927
1928 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
1929
1930 delete mOutputs.valueFor(mPrimaryOutput);
1931 mOutputs.removeItem(mPrimaryOutput);
1932
1933 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1934 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
1935 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
1936 &outputDesc->mDevice,
1937 &outputDesc->mSamplingRate,
1938 &outputDesc->mFormat,
1939 &outputDesc->mChannelMask,
1940 &outputDesc->mLatency,
1941 outputDesc->mFlags);
1942 if (mPrimaryOutput == 0) {
1943 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1944 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
1945 } else {
1946 AudioParameter outputCmd = AudioParameter();
1947 outputCmd.addInt(String8("set_id"), 0);
1948 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1949 addOutput(mPrimaryOutput, outputDesc);
1950 }
1951 }
1952
1953
1954 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1955 }
1956 }
1957 return false;
1958}
1959
Eric Laurente0720872014-03-11 09:30:41 -07001960void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07001961{
1962 {
1963 AutoMutex _l(mLock);
1964 requestExit();
1965 mWaitWorkCV.signal();
1966 }
1967 requestExitAndWait();
1968}
1969
Eric Laurente0720872014-03-11 09:30:41 -07001970int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001971{
1972 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1973 if (output == mTestOutputs[i]) return i;
1974 }
1975 return 0;
1976}
1977#endif //AUDIO_POLICY_TEST
1978
1979// ---
1980
Eric Laurente0720872014-03-11 09:30:41 -07001981void AudioPolicyManager::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07001982{
1983 outputDesc->mId = id;
1984 mOutputs.add(id, outputDesc);
1985}
1986
Eric Laurentd4692962014-05-05 18:13:44 -07001987void AudioPolicyManager::addInput(audio_io_handle_t id, AudioInputDescriptor *inputDesc)
1988{
1989 inputDesc->mId = id;
1990 mInputs.add(id, inputDesc);
1991}
Eric Laurente552edb2014-03-10 17:42:56 -07001992
Eric Laurent3a4311c2014-03-17 12:00:47 -07001993String8 AudioPolicyManager::addressToParameter(audio_devices_t device, const String8 address)
1994{
1995 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
1996 return String8("a2dp_sink_address=")+address;
1997 }
1998 return address;
1999}
2000
Eric Laurente0720872014-03-11 09:30:41 -07002001status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002002 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002003 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002004 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002005{
2006 AudioOutputDescriptor *desc;
2007
Eric Laurent3b73df72014-03-11 09:06:29 -07002008 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002009 // first list already open outputs that can be routed to this device
2010 for (size_t i = 0; i < mOutputs.size(); i++) {
2011 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002012 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002013 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2014 outputs.add(mOutputs.keyAt(i));
2015 }
2016 }
2017 // then look for output profiles that can be routed to this device
2018 SortedVector<IOProfile *> profiles;
2019 for (size_t i = 0; i < mHwModules.size(); i++)
2020 {
2021 if (mHwModules[i]->mHandle == 0) {
2022 continue;
2023 }
2024 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2025 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002026 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002027 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002028 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2029 }
2030 }
2031 }
2032
2033 if (profiles.isEmpty() && outputs.isEmpty()) {
2034 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2035 return BAD_VALUE;
2036 }
2037
2038 // open outputs for matching profiles if needed. Direct outputs are also opened to
2039 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2040 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2041 IOProfile *profile = profiles[profile_index];
2042
2043 // nothing to do if one output is already opened for this profile
2044 size_t j;
2045 for (j = 0; j < mOutputs.size(); j++) {
2046 desc = mOutputs.valueAt(j);
2047 if (!desc->isDuplicated() && desc->mProfile == profile) {
2048 break;
2049 }
2050 }
2051 if (j != mOutputs.size()) {
2052 continue;
2053 }
2054
Eric Laurent3a4311c2014-03-17 12:00:47 -07002055 ALOGV("opening output for device %08x with params %s", device, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -07002056 desc = new AudioOutputDescriptor(profile);
2057 desc->mDevice = device;
2058 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
2059 offloadInfo.sample_rate = desc->mSamplingRate;
2060 offloadInfo.format = desc->mFormat;
2061 offloadInfo.channel_mask = desc->mChannelMask;
2062
2063 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
2064 &desc->mDevice,
2065 &desc->mSamplingRate,
2066 &desc->mFormat,
2067 &desc->mChannelMask,
2068 &desc->mLatency,
2069 desc->mFlags,
2070 &offloadInfo);
2071 if (output != 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002072 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002073 if (!address.isEmpty()) {
2074 mpClientInterface->setParameters(output, addressToParameter(device, address));
Eric Laurente552edb2014-03-10 17:42:56 -07002075 }
2076
Eric Laurentd4692962014-05-05 18:13:44 -07002077 // Here is where we step through and resolve any "dynamic" fields
2078 String8 reply;
2079 char *value;
2080 if (profile->mSamplingRates[0] == 0) {
2081 reply = mpClientInterface->getParameters(output,
2082 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2083 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
2084 reply.string());
2085 value = strpbrk((char *)reply.string(), "=");
2086 if (value != NULL) {
2087 loadSamplingRates(value + 1, profile);
Eric Laurente552edb2014-03-10 17:42:56 -07002088 }
Eric Laurentd4692962014-05-05 18:13:44 -07002089 }
2090 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2091 reply = mpClientInterface->getParameters(output,
2092 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2093 ALOGV("checkOutputsForDevice() direct output sup formats %s",
2094 reply.string());
2095 value = strpbrk((char *)reply.string(), "=");
2096 if (value != NULL) {
2097 loadFormats(value + 1, profile);
Eric Laurente552edb2014-03-10 17:42:56 -07002098 }
Eric Laurentd4692962014-05-05 18:13:44 -07002099 }
2100 if (profile->mChannelMasks[0] == 0) {
2101 reply = mpClientInterface->getParameters(output,
2102 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2103 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
2104 reply.string());
2105 value = strpbrk((char *)reply.string(), "=");
2106 if (value != NULL) {
2107 loadOutChannels(value + 1, profile);
Eric Laurente552edb2014-03-10 17:42:56 -07002108 }
Eric Laurentd4692962014-05-05 18:13:44 -07002109 }
2110 if (((profile->mSamplingRates[0] == 0) &&
2111 (profile->mSamplingRates.size() < 2)) ||
2112 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2113 (profile->mFormats.size() < 2)) ||
2114 ((profile->mChannelMasks[0] == 0) &&
2115 (profile->mChannelMasks.size() < 2))) {
2116 ALOGW("checkOutputsForDevice() direct output missing param");
2117 mpClientInterface->closeOutput(output);
2118 output = 0;
2119 } else if (profile->mSamplingRates[0] == 0) {
2120 mpClientInterface->closeOutput(output);
2121 desc->mSamplingRate = profile->mSamplingRates[1];
2122 offloadInfo.sample_rate = desc->mSamplingRate;
2123 output = mpClientInterface->openOutput(
2124 profile->mModule->mHandle,
2125 &desc->mDevice,
2126 &desc->mSamplingRate,
2127 &desc->mFormat,
2128 &desc->mChannelMask,
2129 &desc->mLatency,
2130 desc->mFlags,
2131 &offloadInfo);
2132 }
2133
2134 if (output != 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002135 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002136 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
2137 audio_io_handle_t duplicatedOutput = 0;
Eric Laurente552edb2014-03-10 17:42:56 -07002138
Eric Laurentd4692962014-05-05 18:13:44 -07002139 // set initial stream volume for device
2140 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002141
Eric Laurentd4692962014-05-05 18:13:44 -07002142 //TODO: configure audio effect output stage here
2143
2144 // open a duplicating output thread for the new output and the primary output
2145 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2146 mPrimaryOutput);
2147 if (duplicatedOutput != 0) {
2148 // add duplicated output descriptor
2149 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
2150 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2151 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2152 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2153 dupOutputDesc->mFormat = desc->mFormat;
2154 dupOutputDesc->mChannelMask = desc->mChannelMask;
2155 dupOutputDesc->mLatency = desc->mLatency;
2156 addOutput(duplicatedOutput, dupOutputDesc);
2157 applyStreamVolumes(duplicatedOutput, device, 0, true);
2158 } else {
2159 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2160 mPrimaryOutput, output);
2161 mpClientInterface->closeOutput(output);
2162 mOutputs.removeItem(output);
2163 output = 0;
2164 }
Eric Laurente552edb2014-03-10 17:42:56 -07002165 }
2166 }
2167 }
2168 if (output == 0) {
2169 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
2170 delete desc;
2171 profiles.removeAt(profile_index);
2172 profile_index--;
2173 } else {
2174 outputs.add(output);
2175 ALOGV("checkOutputsForDevice(): adding output %d", output);
2176 }
2177 }
2178
2179 if (profiles.isEmpty()) {
2180 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2181 return BAD_VALUE;
2182 }
Eric Laurentd4692962014-05-05 18:13:44 -07002183 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07002184 // check if one opened output is not needed any more after disconnecting one device
2185 for (size_t i = 0; i < mOutputs.size(); i++) {
2186 desc = mOutputs.valueAt(i);
2187 if (!desc->isDuplicated() &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07002188 !(desc->mProfile->mSupportedDevices.types() &
2189 mAvailableOutputDevices.types())) {
Eric Laurente552edb2014-03-10 17:42:56 -07002190 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
2191 outputs.add(mOutputs.keyAt(i));
2192 }
2193 }
Eric Laurentd4692962014-05-05 18:13:44 -07002194 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002195 for (size_t i = 0; i < mHwModules.size(); i++)
2196 {
2197 if (mHwModules[i]->mHandle == 0) {
2198 continue;
2199 }
2200 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2201 {
2202 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07002203 if (profile->mSupportedDevices.types() & device) {
2204 ALOGV("checkOutputsForDevice(): "
2205 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002206 if (profile->mSamplingRates[0] == 0) {
2207 profile->mSamplingRates.clear();
2208 profile->mSamplingRates.add(0);
2209 }
2210 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2211 profile->mFormats.clear();
2212 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2213 }
2214 if (profile->mChannelMasks[0] == 0) {
2215 profile->mChannelMasks.clear();
2216 profile->mChannelMasks.add(0);
2217 }
2218 }
2219 }
2220 }
2221 }
2222 return NO_ERROR;
2223}
2224
Eric Laurentd4692962014-05-05 18:13:44 -07002225status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
2226 audio_policy_dev_state_t state,
2227 SortedVector<audio_io_handle_t>& inputs,
2228 const String8 address)
2229{
2230 AudioInputDescriptor *desc;
2231 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
2232 // first list already open inputs that can be routed to this device
2233 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2234 desc = mInputs.valueAt(input_index);
2235 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
2236 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
2237 inputs.add(mInputs.keyAt(input_index));
2238 }
2239 }
2240
2241 // then look for input profiles that can be routed to this device
2242 SortedVector<IOProfile *> profiles;
2243 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
2244 {
2245 if (mHwModules[module_idx]->mHandle == 0) {
2246 continue;
2247 }
2248 for (size_t profile_index = 0;
2249 profile_index < mHwModules[module_idx]->mInputProfiles.size();
2250 profile_index++)
2251 {
2252 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
2253 & (device & ~AUDIO_DEVICE_BIT_IN)) {
2254 ALOGV("checkInputsForDevice(): adding profile %d from module %d",
2255 profile_index, module_idx);
2256 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
2257 }
2258 }
2259 }
2260
2261 if (profiles.isEmpty() && inputs.isEmpty()) {
2262 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2263 return BAD_VALUE;
2264 }
2265
2266 // open inputs for matching profiles if needed. Direct inputs are also opened to
2267 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2268 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2269
2270 IOProfile *profile = profiles[profile_index];
2271 // nothing to do if one input is already opened for this profile
2272 size_t input_index;
2273 for (input_index = 0; input_index < mInputs.size(); input_index++) {
2274 desc = mInputs.valueAt(input_index);
2275 if (desc->mProfile == profile) {
2276 break;
2277 }
2278 }
2279 if (input_index != mInputs.size()) {
2280 continue;
2281 }
2282
2283 ALOGV("opening input for device 0x%X with params %s", device, address.string());
2284 desc = new AudioInputDescriptor(profile);
2285 desc->mDevice = device;
2286
2287 audio_io_handle_t input = mpClientInterface->openInput(profile->mModule->mHandle,
2288 &desc->mDevice,
2289 &desc->mSamplingRate,
2290 &desc->mFormat,
2291 &desc->mChannelMask);
2292
2293 if (input != 0) {
2294 if (!address.isEmpty()) {
2295 mpClientInterface->setParameters(input, addressToParameter(device, address));
2296 }
2297
2298 // Here is where we step through and resolve any "dynamic" fields
2299 String8 reply;
2300 char *value;
2301 if (profile->mSamplingRates[0] == 0) {
2302 reply = mpClientInterface->getParameters(input,
2303 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2304 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
2305 reply.string());
2306 value = strpbrk((char *)reply.string(), "=");
2307 if (value != NULL) {
2308 loadSamplingRates(value + 1, profile);
2309 }
2310 }
2311 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2312 reply = mpClientInterface->getParameters(input,
2313 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2314 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
2315 value = strpbrk((char *)reply.string(), "=");
2316 if (value != NULL) {
2317 loadFormats(value + 1, profile);
2318 }
2319 }
2320 if (profile->mChannelMasks[0] == 0) {
2321 reply = mpClientInterface->getParameters(input,
2322 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2323 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
2324 reply.string());
2325 value = strpbrk((char *)reply.string(), "=");
2326 if (value != NULL) {
2327 loadInChannels(value + 1, profile);
2328 }
2329 }
2330 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
2331 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
2332 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
2333 ALOGW("checkInputsForDevice() direct input missing param");
2334 mpClientInterface->closeInput(input);
2335 input = 0;
2336 }
2337
2338 if (input != 0) {
2339 addInput(input, desc);
2340 }
2341 } // endif input != 0
2342
2343 if (input == 0) {
2344 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
2345 delete desc;
2346 profiles.removeAt(profile_index);
2347 profile_index--;
2348 } else {
2349 inputs.add(input);
2350 ALOGV("checkInputsForDevice(): adding input %d", input);
2351 }
2352 } // end scan profiles
2353
2354 if (profiles.isEmpty()) {
2355 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
2356 return BAD_VALUE;
2357 }
2358 } else {
2359 // Disconnect
2360 // check if one opened input is not needed any more after disconnecting one device
2361 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
2362 desc = mInputs.valueAt(input_index);
2363 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
2364 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
2365 mInputs.keyAt(input_index));
2366 inputs.add(mInputs.keyAt(input_index));
2367 }
2368 }
2369 // Clear any profiles associated with the disconnected device.
2370 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
2371 if (mHwModules[module_index]->mHandle == 0) {
2372 continue;
2373 }
2374 for (size_t profile_index = 0;
2375 profile_index < mHwModules[module_index]->mInputProfiles.size();
2376 profile_index++) {
2377 IOProfile *profile = mHwModules[module_index]->mInputProfiles[profile_index];
2378 if (profile->mSupportedDevices.types() & device) {
2379 ALOGV("checkInputsForDevice(): clearing direct input profile %d on module %d",
2380 profile_index, module_index);
2381 if (profile->mSamplingRates[0] == 0) {
2382 profile->mSamplingRates.clear();
2383 profile->mSamplingRates.add(0);
2384 }
2385 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2386 profile->mFormats.clear();
2387 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2388 }
2389 if (profile->mChannelMasks[0] == 0) {
2390 profile->mChannelMasks.clear();
2391 profile->mChannelMasks.add(0);
2392 }
2393 }
2394 }
2395 }
2396 } // end disconnect
2397
2398 return NO_ERROR;
2399}
2400
2401
Eric Laurente0720872014-03-11 09:30:41 -07002402void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002403{
2404 ALOGV("closeOutput(%d)", output);
2405
2406 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2407 if (outputDesc == NULL) {
2408 ALOGW("closeOutput() unknown output %d", output);
2409 return;
2410 }
2411
2412 // look for duplicated outputs connected to the output being removed.
2413 for (size_t i = 0; i < mOutputs.size(); i++) {
2414 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
2415 if (dupOutputDesc->isDuplicated() &&
2416 (dupOutputDesc->mOutput1 == outputDesc ||
2417 dupOutputDesc->mOutput2 == outputDesc)) {
2418 AudioOutputDescriptor *outputDesc2;
2419 if (dupOutputDesc->mOutput1 == outputDesc) {
2420 outputDesc2 = dupOutputDesc->mOutput2;
2421 } else {
2422 outputDesc2 = dupOutputDesc->mOutput1;
2423 }
2424 // As all active tracks on duplicated output will be deleted,
2425 // and as they were also referenced on the other output, the reference
2426 // count for their stream type must be adjusted accordingly on
2427 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07002428 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07002429 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07002430 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07002431 }
2432 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
2433 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
2434
2435 mpClientInterface->closeOutput(duplicatedOutput);
2436 delete mOutputs.valueFor(duplicatedOutput);
2437 mOutputs.removeItem(duplicatedOutput);
2438 }
2439 }
2440
2441 AudioParameter param;
2442 param.add(String8("closing"), String8("true"));
2443 mpClientInterface->setParameters(output, param.toString());
2444
2445 mpClientInterface->closeOutput(output);
2446 delete outputDesc;
2447 mOutputs.removeItem(output);
2448 mPreviousOutputs = mOutputs;
2449}
2450
Eric Laurente0720872014-03-11 09:30:41 -07002451SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07002452 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
2453{
2454 SortedVector<audio_io_handle_t> outputs;
2455
2456 ALOGVV("getOutputsForDevice() device %04x", device);
2457 for (size_t i = 0; i < openOutputs.size(); i++) {
2458 ALOGVV("output %d isDuplicated=%d device=%04x",
2459 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
2460 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
2461 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
2462 outputs.add(openOutputs.keyAt(i));
2463 }
2464 }
2465 return outputs;
2466}
2467
Eric Laurente0720872014-03-11 09:30:41 -07002468bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07002469 SortedVector<audio_io_handle_t>& outputs2)
2470{
2471 if (outputs1.size() != outputs2.size()) {
2472 return false;
2473 }
2474 for (size_t i = 0; i < outputs1.size(); i++) {
2475 if (outputs1[i] != outputs2[i]) {
2476 return false;
2477 }
2478 }
2479 return true;
2480}
2481
Eric Laurente0720872014-03-11 09:30:41 -07002482void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07002483{
2484 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
2485 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
2486 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
2487 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
2488
2489 if (!vectorsEqual(srcOutputs,dstOutputs)) {
2490 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
2491 strategy, srcOutputs[0], dstOutputs[0]);
2492 // mute strategy while moving tracks from one output to another
2493 for (size_t i = 0; i < srcOutputs.size(); i++) {
2494 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
2495 if (desc->isStrategyActive(strategy)) {
2496 setStrategyMute(strategy, true, srcOutputs[i]);
2497 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
2498 }
2499 }
2500
2501 // Move effects associated to this strategy from previous output to new output
2502 if (strategy == STRATEGY_MEDIA) {
2503 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
2504 SortedVector<audio_io_handle_t> moved;
2505 for (size_t i = 0; i < mEffects.size(); i++) {
2506 EffectDescriptor *desc = mEffects.valueAt(i);
2507 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
2508 desc->mIo != fxOutput) {
2509 if (moved.indexOf(desc->mIo) < 0) {
2510 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
2511 mEffects.keyAt(i), fxOutput);
2512 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
2513 fxOutput);
2514 moved.add(desc->mIo);
2515 }
2516 desc->mIo = fxOutput;
2517 }
2518 }
2519 }
2520 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07002521 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
2522 if (getStrategy((audio_stream_type_t)i) == strategy) {
2523 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07002524 }
2525 }
2526 }
2527}
2528
Eric Laurente0720872014-03-11 09:30:41 -07002529void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07002530{
2531 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
2532 checkOutputForStrategy(STRATEGY_PHONE);
2533 checkOutputForStrategy(STRATEGY_SONIFICATION);
2534 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2535 checkOutputForStrategy(STRATEGY_MEDIA);
2536 checkOutputForStrategy(STRATEGY_DTMF);
2537}
2538
Eric Laurente0720872014-03-11 09:30:41 -07002539audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07002540{
Eric Laurente552edb2014-03-10 17:42:56 -07002541 for (size_t i = 0; i < mOutputs.size(); i++) {
2542 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
2543 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
2544 return mOutputs.keyAt(i);
2545 }
2546 }
2547
2548 return 0;
2549}
2550
Eric Laurente0720872014-03-11 09:30:41 -07002551void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07002552{
Eric Laurente552edb2014-03-10 17:42:56 -07002553 audio_io_handle_t a2dpOutput = getA2dpOutput();
2554 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002555 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07002556 return;
2557 }
2558
Eric Laurent3a4311c2014-03-17 12:00:47 -07002559 bool isScoConnected =
2560 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07002561 // suspend A2DP output if:
2562 // (NOT already suspended) &&
2563 // ((SCO device is connected &&
2564 // (forced usage for communication || for record is SCO))) ||
2565 // (phone state is ringing || in call)
2566 //
2567 // restore A2DP output if:
2568 // (Already suspended) &&
2569 // ((SCO device is NOT connected ||
2570 // (forced usage NOT for communication && NOT for record is SCO))) &&
2571 // (phone state is NOT ringing && NOT in call)
2572 //
2573 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002574 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07002575 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
2576 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
2577 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
2578 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002579
2580 mpClientInterface->restoreOutput(a2dpOutput);
2581 mA2dpSuspended = false;
2582 }
2583 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002584 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07002585 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
2586 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
2587 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
2588 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002589
2590 mpClientInterface->suspendOutput(a2dpOutput);
2591 mA2dpSuspended = true;
2592 }
2593 }
2594}
2595
Eric Laurente0720872014-03-11 09:30:41 -07002596audio_devices_t AudioPolicyManager::getNewDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07002597{
2598 audio_devices_t device = AUDIO_DEVICE_NONE;
2599
2600 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2601 // check the following by order of priority to request a routing change if necessary:
2602 // 1: the strategy enforced audible is active on the output:
2603 // use device for strategy enforced audible
2604 // 2: we are in call or the strategy phone is active on the output:
2605 // use device for strategy phone
2606 // 3: the strategy sonification is active on the output:
2607 // use device for strategy sonification
2608 // 4: the strategy "respectful" sonification is active on the output:
2609 // use device for strategy "respectful" sonification
2610 // 5: the strategy media is active on the output:
2611 // use device for strategy media
2612 // 6: the strategy DTMF is active on the output:
2613 // use device for strategy DTMF
2614 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
2615 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
2616 } else if (isInCall() ||
2617 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
2618 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
2619 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
2620 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
2621 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
2622 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
2623 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
2624 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
2625 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
2626 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
2627 }
2628
2629 ALOGV("getNewDevice() selected device %x", device);
2630 return device;
2631}
2632
Eric Laurente0720872014-03-11 09:30:41 -07002633uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07002634 return (uint32_t)getStrategy(stream);
2635}
2636
Eric Laurente0720872014-03-11 09:30:41 -07002637audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07002638 audio_devices_t devices;
2639 // By checking the range of stream before calling getStrategy, we avoid
2640 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
2641 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07002642 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -07002643 devices = AUDIO_DEVICE_NONE;
2644 } else {
Eric Laurente0720872014-03-11 09:30:41 -07002645 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002646 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
2647 }
2648 return devices;
2649}
2650
Eric Laurente0720872014-03-11 09:30:41 -07002651AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07002652 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07002653 // stream to strategy mapping
2654 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07002655 case AUDIO_STREAM_VOICE_CALL:
2656 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07002657 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07002658 case AUDIO_STREAM_RING:
2659 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07002660 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07002661 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07002662 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07002663 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07002664 return STRATEGY_DTMF;
2665 default:
2666 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07002667 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07002668 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
2669 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07002670 case AUDIO_STREAM_TTS:
2671 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07002672 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07002673 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07002674 return STRATEGY_ENFORCED_AUDIBLE;
2675 }
2676}
2677
Eric Laurente0720872014-03-11 09:30:41 -07002678void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07002679 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07002680 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07002681 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2682 updateDevicesAndOutputs();
2683 break;
2684 default:
2685 break;
2686 }
2687}
2688
Eric Laurente0720872014-03-11 09:30:41 -07002689audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07002690 bool fromCache)
2691{
2692 uint32_t device = AUDIO_DEVICE_NONE;
2693
2694 if (fromCache) {
2695 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
2696 strategy, mDeviceForStrategy[strategy]);
2697 return mDeviceForStrategy[strategy];
2698 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002699 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07002700 switch (strategy) {
2701
2702 case STRATEGY_SONIFICATION_RESPECTFUL:
2703 if (isInCall()) {
2704 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07002705 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07002706 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2707 // while media is playing on a remote device, use the the sonification behavior.
2708 // Note that we test this usecase before testing if media is playing because
2709 // the isStreamActive() method only informs about the activity of a stream, not
2710 // if it's for local playback. Note also that we use the same delay between both tests
2711 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07002712 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002713 // while media is playing (or has recently played), use the same device
2714 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2715 } else {
2716 // when media is not playing anymore, fall back on the sonification behavior
2717 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2718 }
2719
2720 break;
2721
2722 case STRATEGY_DTMF:
2723 if (!isInCall()) {
2724 // when off call, DTMF strategy follows the same rules as MEDIA strategy
2725 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2726 break;
2727 }
2728 // when in call, DTMF and PHONE strategies follow the same rules
2729 // FALL THROUGH
2730
2731 case STRATEGY_PHONE:
2732 // for phone strategy, we first consider the forced use and then the available devices by order
2733 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07002734 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
2735 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07002736 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002737 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002738 if (device) break;
2739 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002740 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07002741 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002742 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07002743 if (device) break;
2744 // if SCO device is requested but no SCO device is available, fall back to default case
2745 // FALL THROUGH
2746
2747 default: // FORCE_NONE
2748 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07002749 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07002750 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002751 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002752 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07002753 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002754 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07002755 if (device) break;
2756 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002757 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002758 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002759 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07002760 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07002761 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002762 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07002763 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002764 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07002765 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002766 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07002767 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002768 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07002769 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002770 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07002771 if (device) break;
2772 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002773 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07002774 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002775 device = mDefaultOutputDevice->mType;
Eric Laurente552edb2014-03-10 17:42:56 -07002776 if (device == AUDIO_DEVICE_NONE) {
2777 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
2778 }
2779 break;
2780
Eric Laurent3b73df72014-03-11 09:06:29 -07002781 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07002782 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
2783 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07002784 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07002785 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002786 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002787 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07002788 if (device) break;
2789 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002790 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002791 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07002792 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002793 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07002794 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002795 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07002796 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002797 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07002798 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002799 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07002800 if (device) break;
2801 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002802 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07002803 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002804 device = mDefaultOutputDevice->mType;
Eric Laurente552edb2014-03-10 17:42:56 -07002805 if (device == AUDIO_DEVICE_NONE) {
2806 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
2807 }
2808 break;
2809 }
2810 break;
2811
2812 case STRATEGY_SONIFICATION:
2813
2814 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
2815 // handleIncallSonification().
2816 if (isInCall()) {
2817 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
2818 break;
2819 }
2820 // FALL THROUGH
2821
2822 case STRATEGY_ENFORCED_AUDIBLE:
2823 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2824 // except:
2825 // - when in call where it doesn't default to STRATEGY_PHONE behavior
2826 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
2827
2828 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07002829 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002830 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07002831 if (device == AUDIO_DEVICE_NONE) {
2832 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2833 }
2834 }
2835 // The second device used for sonification is the same as the device used by media strategy
2836 // FALL THROUGH
2837
2838 case STRATEGY_MEDIA: {
2839 uint32_t device2 = AUDIO_DEVICE_NONE;
2840 if (strategy != STRATEGY_SONIFICATION) {
2841 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07002842 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07002843 }
2844 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07002845 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002846 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002847 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07002848 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002849 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07002850 }
2851 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002852 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07002853 }
2854 }
2855 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002856 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002857 }
2858 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002859 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07002860 }
2861 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002862 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07002863 }
2864 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002865 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07002866 }
2867 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002868 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07002869 }
2870 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
2871 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07002872 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07002873 }
2874 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07002875 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002876 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07002877 }
2878 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002879 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07002880 }
2881
2882 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2883 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
2884 device |= device2;
2885 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002886 device = mDefaultOutputDevice->mType;
Eric Laurente552edb2014-03-10 17:42:56 -07002887 if (device == AUDIO_DEVICE_NONE) {
2888 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2889 }
2890 } break;
2891
2892 default:
2893 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2894 break;
2895 }
2896
2897 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2898 return device;
2899}
2900
Eric Laurente0720872014-03-11 09:30:41 -07002901void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07002902{
2903 for (int i = 0; i < NUM_STRATEGIES; i++) {
2904 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2905 }
2906 mPreviousOutputs = mOutputs;
2907}
2908
Eric Laurente0720872014-03-11 09:30:41 -07002909uint32_t AudioPolicyManager::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07002910 audio_devices_t prevDevice,
2911 uint32_t delayMs)
2912{
2913 // mute/unmute strategies using an incompatible device combination
2914 // if muting, wait for the audio in pcm buffer to be drained before proceeding
2915 // if unmuting, unmute only after the specified delay
2916 if (outputDesc->isDuplicated()) {
2917 return 0;
2918 }
2919
2920 uint32_t muteWaitMs = 0;
2921 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07002922 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07002923 // temporary mute output if device selection changes to avoid volume bursts due to
2924 // different per device volumes
2925 bool tempMute = outputDesc->isActive() && (device != prevDevice);
2926
2927 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2928 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2929 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2930 bool doMute = false;
2931
2932 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2933 doMute = true;
2934 outputDesc->mStrategyMutedByDevice[i] = true;
2935 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2936 doMute = true;
2937 outputDesc->mStrategyMutedByDevice[i] = false;
2938 }
2939 if (doMute || tempMute) {
2940 for (size_t j = 0; j < mOutputs.size(); j++) {
2941 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2942 // skip output if it does not share any device with current output
2943 if ((desc->supportedDevices() & outputDesc->supportedDevices())
2944 == AUDIO_DEVICE_NONE) {
2945 continue;
2946 }
2947 audio_io_handle_t curOutput = mOutputs.keyAt(j);
2948 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2949 mute ? "muting" : "unmuting", i, curDevice, curOutput);
2950 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2951 if (desc->isStrategyActive((routing_strategy)i)) {
2952 // do tempMute only for current output
2953 if (tempMute && (desc == outputDesc)) {
2954 setStrategyMute((routing_strategy)i, true, curOutput);
2955 setStrategyMute((routing_strategy)i, false, curOutput,
2956 desc->latency() * 2, device);
2957 }
2958 if ((tempMute && (desc == outputDesc)) || mute) {
2959 if (muteWaitMs < desc->latency()) {
2960 muteWaitMs = desc->latency();
2961 }
2962 }
2963 }
2964 }
2965 }
2966 }
2967
2968 // FIXME: should not need to double latency if volume could be applied immediately by the
2969 // audioflinger mixer. We must account for the delay between now and the next time
2970 // the audioflinger thread for this output will process a buffer (which corresponds to
2971 // one buffer size, usually 1/2 or 1/4 of the latency).
2972 muteWaitMs *= 2;
2973 // wait for the PCM output buffers to empty before proceeding with the rest of the command
2974 if (muteWaitMs > delayMs) {
2975 muteWaitMs -= delayMs;
2976 usleep(muteWaitMs * 1000);
2977 return muteWaitMs;
2978 }
2979 return 0;
2980}
2981
Eric Laurente0720872014-03-11 09:30:41 -07002982uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07002983 audio_devices_t device,
2984 bool force,
2985 int delayMs)
2986{
2987 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2988 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2989 AudioParameter param;
2990 uint32_t muteWaitMs;
2991
2992 if (outputDesc->isDuplicated()) {
2993 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2994 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2995 return muteWaitMs;
2996 }
2997 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
2998 // output profile
2999 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003000 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003001 return 0;
3002 }
3003
3004 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003005 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003006
3007 audio_devices_t prevDevice = outputDesc->mDevice;
3008
3009 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3010
3011 if (device != AUDIO_DEVICE_NONE) {
3012 outputDesc->mDevice = device;
3013 }
3014 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3015
3016 // Do not change the routing if:
3017 // - the requested device is AUDIO_DEVICE_NONE
3018 // - the requested device is the same as current device and force is not specified.
3019 // Doing this check here allows the caller to call setOutputDevice() without conditions
3020 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3021 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3022 return muteWaitMs;
3023 }
3024
3025 ALOGV("setOutputDevice() changing device");
3026 // do the routing
3027 param.addInt(String8(AudioParameter::keyRouting), (int)device);
3028 mpClientInterface->setParameters(output, param.toString(), delayMs);
3029
3030 // update stream volumes according to new device
3031 applyStreamVolumes(output, device, delayMs);
3032
3033 return muteWaitMs;
3034}
3035
Eric Laurente0720872014-03-11 09:30:41 -07003036AudioPolicyManager::IOProfile *AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07003037 uint32_t samplingRate,
3038 audio_format_t format,
3039 audio_channel_mask_t channelMask)
3040{
3041 // Choose an input profile based on the requested capture parameters: select the first available
3042 // profile supporting all requested parameters.
3043
3044 for (size_t i = 0; i < mHwModules.size(); i++)
3045 {
3046 if (mHwModules[i]->mHandle == 0) {
3047 continue;
3048 }
3049 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3050 {
3051 IOProfile *profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003052 // profile->log();
Eric Laurente552edb2014-03-10 17:42:56 -07003053 if (profile->isCompatibleProfile(device, samplingRate, format,
3054 channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
3055 return profile;
3056 }
3057 }
3058 }
3059 return NULL;
3060}
3061
Eric Laurente0720872014-03-11 09:30:41 -07003062audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07003063{
3064 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003065 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
3066 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003067 switch (inputSource) {
3068 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003069 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003070 device = AUDIO_DEVICE_IN_VOICE_CALL;
3071 break;
3072 }
3073 // FALL THROUGH
3074
3075 case AUDIO_SOURCE_DEFAULT:
3076 case AUDIO_SOURCE_MIC:
3077 case AUDIO_SOURCE_VOICE_RECOGNITION:
3078 case AUDIO_SOURCE_HOTWORD:
3079 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07003080 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003081 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003082 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003083 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07003084 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07003085 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
3086 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003087 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003088 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3089 }
3090 break;
3091 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003092 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003093 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003094 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07003095 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
3096 }
3097 break;
3098 case AUDIO_SOURCE_VOICE_DOWNLINK:
3099 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003100 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003101 device = AUDIO_DEVICE_IN_VOICE_CALL;
3102 }
3103 break;
3104 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07003105 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07003106 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3107 }
3108 break;
3109 default:
3110 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
3111 break;
3112 }
3113 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
3114 return device;
3115}
3116
Eric Laurente0720872014-03-11 09:30:41 -07003117bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003118{
3119 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
3120 device &= ~AUDIO_DEVICE_BIT_IN;
3121 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
3122 return true;
3123 }
3124 return false;
3125}
3126
Eric Laurente0720872014-03-11 09:30:41 -07003127audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003128{
3129 for (size_t i = 0; i < mInputs.size(); i++) {
3130 const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
3131 if ((input_descriptor->mRefCount > 0)
3132 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
3133 return mInputs.keyAt(i);
3134 }
3135 }
3136 return 0;
3137}
3138
3139
Eric Laurente0720872014-03-11 09:30:41 -07003140audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003141{
3142 if (device == AUDIO_DEVICE_NONE) {
3143 // this happens when forcing a route update and no track is active on an output.
3144 // In this case the returned category is not important.
3145 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07003146 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07003147 // Multiple device selection is either:
3148 // - speaker + one other device: give priority to speaker in this case.
3149 // - one A2DP device + another device: happens with duplicated output. In this case
3150 // retain the device on the A2DP output as the other must not correspond to an active
3151 // selection if not the speaker.
3152 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
3153 device = AUDIO_DEVICE_OUT_SPEAKER;
3154 } else {
3155 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
3156 }
3157 }
3158
Eric Laurent3b73df72014-03-11 09:06:29 -07003159 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07003160 "getDeviceForVolume() invalid device combination: %08x",
3161 device);
3162
3163 return device;
3164}
3165
Eric Laurente0720872014-03-11 09:30:41 -07003166AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003167{
3168 switch(getDeviceForVolume(device)) {
3169 case AUDIO_DEVICE_OUT_EARPIECE:
3170 return DEVICE_CATEGORY_EARPIECE;
3171 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
3172 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
3173 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
3174 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
3175 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
3176 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
3177 return DEVICE_CATEGORY_HEADSET;
3178 case AUDIO_DEVICE_OUT_SPEAKER:
3179 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
3180 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
3181 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
3182 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
3183 case AUDIO_DEVICE_OUT_USB_DEVICE:
3184 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
3185 default:
3186 return DEVICE_CATEGORY_SPEAKER;
3187 }
3188}
3189
Eric Laurente0720872014-03-11 09:30:41 -07003190float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003191 int indexInUi)
3192{
3193 device_category deviceCategory = getDeviceCategory(device);
3194 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
3195
3196 // the volume index in the UI is relative to the min and max volume indices for this stream type
3197 int nbSteps = 1 + curve[VOLMAX].mIndex -
3198 curve[VOLMIN].mIndex;
3199 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
3200 (streamDesc.mIndexMax - streamDesc.mIndexMin);
3201
3202 // find what part of the curve this index volume belongs to, or if it's out of bounds
3203 int segment = 0;
3204 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
3205 return 0.0f;
3206 } else if (volIdx < curve[VOLKNEE1].mIndex) {
3207 segment = 0;
3208 } else if (volIdx < curve[VOLKNEE2].mIndex) {
3209 segment = 1;
3210 } else if (volIdx <= curve[VOLMAX].mIndex) {
3211 segment = 2;
3212 } else { // out of bounds
3213 return 1.0f;
3214 }
3215
3216 // linear interpolation in the attenuation table in dB
3217 float decibels = curve[segment].mDBAttenuation +
3218 ((float)(volIdx - curve[segment].mIndex)) *
3219 ( (curve[segment+1].mDBAttenuation -
3220 curve[segment].mDBAttenuation) /
3221 ((float)(curve[segment+1].mIndex -
3222 curve[segment].mIndex)) );
3223
3224 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
3225
3226 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
3227 curve[segment].mIndex, volIdx,
3228 curve[segment+1].mIndex,
3229 curve[segment].mDBAttenuation,
3230 decibels,
3231 curve[segment+1].mDBAttenuation,
3232 amplification);
3233
3234 return amplification;
3235}
3236
Eric Laurente0720872014-03-11 09:30:41 -07003237const AudioPolicyManager::VolumeCurvePoint
3238 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003239 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
3240};
3241
Eric Laurente0720872014-03-11 09:30:41 -07003242const AudioPolicyManager::VolumeCurvePoint
3243 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003244 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
3245};
3246
Eric Laurente0720872014-03-11 09:30:41 -07003247const AudioPolicyManager::VolumeCurvePoint
3248 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003249 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
3250};
3251
Eric Laurente0720872014-03-11 09:30:41 -07003252const AudioPolicyManager::VolumeCurvePoint
3253 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003254 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
3255};
3256
Eric Laurente0720872014-03-11 09:30:41 -07003257const AudioPolicyManager::VolumeCurvePoint
3258 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003259 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
3260};
3261
3262// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
3263// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
3264// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
3265// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
3266
Eric Laurente0720872014-03-11 09:30:41 -07003267const AudioPolicyManager::VolumeCurvePoint
3268 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003269 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
3270};
3271
Eric Laurente0720872014-03-11 09:30:41 -07003272const AudioPolicyManager::VolumeCurvePoint
3273 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003274 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
3275};
3276
Eric Laurente0720872014-03-11 09:30:41 -07003277const AudioPolicyManager::VolumeCurvePoint
3278 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003279 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
3280};
3281
Eric Laurente0720872014-03-11 09:30:41 -07003282const AudioPolicyManager::VolumeCurvePoint
3283 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003284 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
3285};
3286
Eric Laurente0720872014-03-11 09:30:41 -07003287const AudioPolicyManager::VolumeCurvePoint
3288 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003289 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
3290};
3291
Eric Laurente0720872014-03-11 09:30:41 -07003292const AudioPolicyManager::VolumeCurvePoint
3293 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
3294 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003295 { // AUDIO_STREAM_VOICE_CALL
3296 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
3297 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3298 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
3299 },
3300 { // AUDIO_STREAM_SYSTEM
3301 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3302 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3303 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
3304 },
3305 { // AUDIO_STREAM_RING
3306 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3307 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3308 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3309 },
3310 { // AUDIO_STREAM_MUSIC
3311 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
3312 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3313 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
3314 },
3315 { // AUDIO_STREAM_ALARM
3316 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3317 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3318 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3319 },
3320 { // AUDIO_STREAM_NOTIFICATION
3321 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3322 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3323 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3324 },
3325 { // AUDIO_STREAM_BLUETOOTH_SCO
3326 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
3327 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3328 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
3329 },
3330 { // AUDIO_STREAM_ENFORCED_AUDIBLE
3331 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3332 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3333 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
3334 },
3335 { // AUDIO_STREAM_DTMF
3336 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3337 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3338 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
3339 },
3340 { // AUDIO_STREAM_TTS
3341 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
3342 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3343 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
3344 },
3345};
3346
Eric Laurente0720872014-03-11 09:30:41 -07003347void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07003348{
3349 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3350 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
3351 mStreams[i].mVolumeCurve[j] =
3352 sVolumeProfiles[i][j];
3353 }
3354 }
3355
3356 // Check availability of DRC on speaker path: if available, override some of the speaker curves
3357 if (mSpeakerDrcEnabled) {
3358 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3359 sDefaultSystemVolumeCurveDrc;
3360 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3361 sSpeakerSonificationVolumeCurveDrc;
3362 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3363 sSpeakerSonificationVolumeCurveDrc;
3364 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3365 sSpeakerSonificationVolumeCurveDrc;
3366 }
3367}
3368
Eric Laurente0720872014-03-11 09:30:41 -07003369float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07003370 int index,
3371 audio_io_handle_t output,
3372 audio_devices_t device)
3373{
3374 float volume = 1.0;
3375 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3376 StreamDescriptor &streamDesc = mStreams[stream];
3377
3378 if (device == AUDIO_DEVICE_NONE) {
3379 device = outputDesc->device();
3380 }
3381
3382 // if volume is not 0 (not muted), force media volume to max on digital output
Eric Laurent3b73df72014-03-11 09:06:29 -07003383 if (stream == AUDIO_STREAM_MUSIC &&
Eric Laurente552edb2014-03-10 17:42:56 -07003384 index != mStreams[stream].mIndexMin &&
3385 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
3386 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
3387 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
3388 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
3389 return 1.0;
3390 }
3391
3392 volume = volIndexToAmpl(device, streamDesc, index);
3393
3394 // if a headset is connected, apply the following rules to ring tones and notifications
3395 // to avoid sound level bursts in user's ears:
3396 // - always attenuate ring tones and notifications volume by 6dB
3397 // - if music is playing, always limit the volume to current music volume,
3398 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07003399 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07003400 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
3401 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
3402 AUDIO_DEVICE_OUT_WIRED_HEADSET |
3403 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
3404 ((stream_strategy == STRATEGY_SONIFICATION)
3405 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07003406 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07003407 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003408 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003409 streamDesc.mCanBeMuted) {
3410 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
3411 // when the phone is ringing we must consider that music could have been paused just before
3412 // by the music application and behave as if music was active if the last music track was
3413 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07003414 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07003415 mLimitRingtoneVolume) {
3416 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003417 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
3418 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07003419 output,
3420 musicDevice);
3421 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
3422 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
3423 if (volume > minVol) {
3424 volume = minVol;
3425 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
3426 }
3427 }
3428 }
3429
3430 return volume;
3431}
3432
Eric Laurente0720872014-03-11 09:30:41 -07003433status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07003434 int index,
3435 audio_io_handle_t output,
3436 audio_devices_t device,
3437 int delayMs,
3438 bool force)
3439{
3440
3441 // do not change actual stream volume if the stream is muted
3442 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
3443 ALOGVV("checkAndSetVolume() stream %d muted count %d",
3444 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
3445 return NO_ERROR;
3446 }
3447
3448 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07003449 if ((stream == AUDIO_STREAM_VOICE_CALL &&
3450 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3451 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
3452 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003453 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07003454 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07003455 return INVALID_OPERATION;
3456 }
3457
3458 float volume = computeVolume(stream, index, output, device);
3459 // We actually change the volume if:
3460 // - the float value returned by computeVolume() changed
3461 // - the force flag is set
3462 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
3463 force) {
3464 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
3465 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
3466 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
3467 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07003468 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
3469 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003470 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003471 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003472 }
3473
Eric Laurent3b73df72014-03-11 09:06:29 -07003474 if (stream == AUDIO_STREAM_VOICE_CALL ||
3475 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07003476 float voiceVolume;
3477 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07003478 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003479 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
3480 } else {
3481 voiceVolume = 1.0;
3482 }
3483
3484 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
3485 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
3486 mLastVoiceVolume = voiceVolume;
3487 }
3488 }
3489
3490 return NO_ERROR;
3491}
3492
Eric Laurente0720872014-03-11 09:30:41 -07003493void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003494 audio_devices_t device,
3495 int delayMs,
3496 bool force)
3497{
3498 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
3499
Eric Laurent3b73df72014-03-11 09:06:29 -07003500 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
3501 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07003502 mStreams[stream].getVolumeIndex(device),
3503 output,
3504 device,
3505 delayMs,
3506 force);
3507 }
3508}
3509
Eric Laurente0720872014-03-11 09:30:41 -07003510void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003511 bool on,
3512 audio_io_handle_t output,
3513 int delayMs,
3514 audio_devices_t device)
3515{
3516 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07003517 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
3518 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3519 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003520 }
3521 }
3522}
3523
Eric Laurente0720872014-03-11 09:30:41 -07003524void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07003525 bool on,
3526 audio_io_handle_t output,
3527 int delayMs,
3528 audio_devices_t device)
3529{
3530 StreamDescriptor &streamDesc = mStreams[stream];
3531 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3532 if (device == AUDIO_DEVICE_NONE) {
3533 device = outputDesc->device();
3534 }
3535
3536 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
3537 stream, on, output, outputDesc->mMuteCount[stream], device);
3538
3539 if (on) {
3540 if (outputDesc->mMuteCount[stream] == 0) {
3541 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003542 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
3543 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003544 checkAndSetVolume(stream, 0, output, device, delayMs);
3545 }
3546 }
3547 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
3548 outputDesc->mMuteCount[stream]++;
3549 } else {
3550 if (outputDesc->mMuteCount[stream] == 0) {
3551 ALOGV("setStreamMute() unmuting non muted stream!");
3552 return;
3553 }
3554 if (--outputDesc->mMuteCount[stream] == 0) {
3555 checkAndSetVolume(stream,
3556 streamDesc.getVolumeIndex(device),
3557 output,
3558 device,
3559 delayMs);
3560 }
3561 }
3562}
3563
Eric Laurente0720872014-03-11 09:30:41 -07003564void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07003565 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07003566{
3567 // if the stream pertains to sonification strategy and we are in call we must
3568 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
3569 // in the device used for phone strategy and play the tone if the selected device does not
3570 // interfere with the device used for phone strategy
3571 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
3572 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07003573 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07003574 if ((stream_strategy == STRATEGY_SONIFICATION) ||
3575 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
3576 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
3577 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
3578 stream, starting, outputDesc->mDevice, stateChange);
3579 if (outputDesc->mRefCount[stream]) {
3580 int muteCount = 1;
3581 if (stateChange) {
3582 muteCount = outputDesc->mRefCount[stream];
3583 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003584 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003585 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
3586 for (int i = 0; i < muteCount; i++) {
3587 setStreamMute(stream, starting, mPrimaryOutput);
3588 }
3589 } else {
3590 ALOGV("handleIncallSonification() high visibility");
3591 if (outputDesc->device() &
3592 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
3593 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
3594 for (int i = 0; i < muteCount; i++) {
3595 setStreamMute(stream, starting, mPrimaryOutput);
3596 }
3597 }
3598 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003599 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
3600 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07003601 } else {
3602 mpClientInterface->stopTone();
3603 }
3604 }
3605 }
3606 }
3607}
3608
Eric Laurente0720872014-03-11 09:30:41 -07003609bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07003610{
3611 return isStateInCall(mPhoneState);
3612}
3613
Eric Laurente0720872014-03-11 09:30:41 -07003614bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003615 return ((state == AUDIO_MODE_IN_CALL) ||
3616 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07003617}
3618
Eric Laurente0720872014-03-11 09:30:41 -07003619uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07003620{
3621 return MAX_EFFECTS_CPU_LOAD;
3622}
3623
Eric Laurente0720872014-03-11 09:30:41 -07003624uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07003625{
3626 return MAX_EFFECTS_MEMORY;
3627}
3628
3629// --- AudioOutputDescriptor class implementation
3630
Eric Laurente0720872014-03-11 09:30:41 -07003631AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurente552edb2014-03-10 17:42:56 -07003632 const IOProfile *profile)
3633 : mId(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT),
3634 mChannelMask(0), mLatency(0),
3635 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE),
3636 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
3637{
3638 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07003639 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003640 mRefCount[i] = 0;
3641 mCurVolume[i] = -1.0;
3642 mMuteCount[i] = 0;
3643 mStopTime[i] = 0;
3644 }
3645 for (int i = 0; i < NUM_STRATEGIES; i++) {
3646 mStrategyMutedByDevice[i] = false;
3647 }
3648 if (profile != NULL) {
3649 mSamplingRate = profile->mSamplingRates[0];
3650 mFormat = profile->mFormats[0];
3651 mChannelMask = profile->mChannelMasks[0];
3652 mFlags = profile->mFlags;
3653 }
3654}
3655
Eric Laurente0720872014-03-11 09:30:41 -07003656audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07003657{
3658 if (isDuplicated()) {
3659 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
3660 } else {
3661 return mDevice;
3662 }
3663}
3664
Eric Laurente0720872014-03-11 09:30:41 -07003665uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07003666{
3667 if (isDuplicated()) {
3668 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
3669 } else {
3670 return mLatency;
3671 }
3672}
3673
Eric Laurente0720872014-03-11 09:30:41 -07003674bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurente552edb2014-03-10 17:42:56 -07003675 const AudioOutputDescriptor *outputDesc)
3676{
3677 if (isDuplicated()) {
3678 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
3679 } else if (outputDesc->isDuplicated()){
3680 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
3681 } else {
3682 return (mProfile->mModule == outputDesc->mProfile->mModule);
3683 }
3684}
3685
Eric Laurente0720872014-03-11 09:30:41 -07003686void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07003687 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07003688{
3689 // forward usage count change to attached outputs
3690 if (isDuplicated()) {
3691 mOutput1->changeRefCount(stream, delta);
3692 mOutput2->changeRefCount(stream, delta);
3693 }
3694 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003695 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
3696 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07003697 mRefCount[stream] = 0;
3698 return;
3699 }
3700 mRefCount[stream] += delta;
3701 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
3702}
3703
Eric Laurente0720872014-03-11 09:30:41 -07003704audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07003705{
3706 if (isDuplicated()) {
3707 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
3708 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003709 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07003710 }
3711}
3712
Eric Laurente0720872014-03-11 09:30:41 -07003713bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07003714{
3715 return isStrategyActive(NUM_STRATEGIES, inPastMs);
3716}
3717
Eric Laurente0720872014-03-11 09:30:41 -07003718bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003719 uint32_t inPastMs,
3720 nsecs_t sysTime) const
3721{
3722 if ((sysTime == 0) && (inPastMs != 0)) {
3723 sysTime = systemTime();
3724 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003725 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
3726 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07003727 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003728 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003729 return true;
3730 }
3731 }
3732 return false;
3733}
3734
Eric Laurente0720872014-03-11 09:30:41 -07003735bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07003736 uint32_t inPastMs,
3737 nsecs_t sysTime) const
3738{
3739 if (mRefCount[stream] != 0) {
3740 return true;
3741 }
3742 if (inPastMs == 0) {
3743 return false;
3744 }
3745 if (sysTime == 0) {
3746 sysTime = systemTime();
3747 }
3748 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
3749 return true;
3750 }
3751 return false;
3752}
3753
3754
Eric Laurente0720872014-03-11 09:30:41 -07003755status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07003756{
3757 const size_t SIZE = 256;
3758 char buffer[SIZE];
3759 String8 result;
3760
3761 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3762 result.append(buffer);
3763 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
3764 result.append(buffer);
3765 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3766 result.append(buffer);
3767 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
3768 result.append(buffer);
3769 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
3770 result.append(buffer);
3771 snprintf(buffer, SIZE, " Devices %08x\n", device());
3772 result.append(buffer);
3773 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
3774 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07003775 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
3776 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
3777 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003778 result.append(buffer);
3779 }
3780 write(fd, result.string(), result.size());
3781
3782 return NO_ERROR;
3783}
3784
3785// --- AudioInputDescriptor class implementation
3786
Eric Laurente0720872014-03-11 09:30:41 -07003787AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
Eric Laurentd4692962014-05-05 18:13:44 -07003788 : mId(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT), mChannelMask(0),
Eric Laurente552edb2014-03-10 17:42:56 -07003789 mDevice(AUDIO_DEVICE_NONE), mRefCount(0),
Eric Laurent3b73df72014-03-11 09:06:29 -07003790 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile)
Eric Laurente552edb2014-03-10 17:42:56 -07003791{
Eric Laurent3a4311c2014-03-17 12:00:47 -07003792 if (profile != NULL) {
3793 mSamplingRate = profile->mSamplingRates[0];
3794 mFormat = profile->mFormats[0];
3795 mChannelMask = profile->mChannelMasks[0];
3796 }
Eric Laurente552edb2014-03-10 17:42:56 -07003797}
3798
Eric Laurente0720872014-03-11 09:30:41 -07003799status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07003800{
3801 const size_t SIZE = 256;
3802 char buffer[SIZE];
3803 String8 result;
3804
3805 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3806 result.append(buffer);
3807 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3808 result.append(buffer);
3809 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3810 result.append(buffer);
3811 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
3812 result.append(buffer);
3813 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
3814 result.append(buffer);
3815 write(fd, result.string(), result.size());
3816
3817 return NO_ERROR;
3818}
3819
3820// --- StreamDescriptor class implementation
3821
Eric Laurente0720872014-03-11 09:30:41 -07003822AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07003823 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
3824{
3825 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
3826}
3827
Eric Laurente0720872014-03-11 09:30:41 -07003828int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003829{
Eric Laurente0720872014-03-11 09:30:41 -07003830 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07003831 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
3832 if (mIndexCur.indexOfKey(device) < 0) {
3833 device = AUDIO_DEVICE_OUT_DEFAULT;
3834 }
3835 return mIndexCur.valueFor(device);
3836}
3837
Eric Laurente0720872014-03-11 09:30:41 -07003838void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07003839{
3840 const size_t SIZE = 256;
3841 char buffer[SIZE];
3842 String8 result;
3843
3844 snprintf(buffer, SIZE, "%s %02d %02d ",
3845 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
3846 result.append(buffer);
3847 for (size_t i = 0; i < mIndexCur.size(); i++) {
3848 snprintf(buffer, SIZE, "%04x : %02d, ",
3849 mIndexCur.keyAt(i),
3850 mIndexCur.valueAt(i));
3851 result.append(buffer);
3852 }
3853 result.append("\n");
3854
3855 write(fd, result.string(), result.size());
3856}
3857
3858// --- EffectDescriptor class implementation
3859
Eric Laurente0720872014-03-11 09:30:41 -07003860status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07003861{
3862 const size_t SIZE = 256;
3863 char buffer[SIZE];
3864 String8 result;
3865
3866 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
3867 result.append(buffer);
3868 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
3869 result.append(buffer);
3870 snprintf(buffer, SIZE, " Session: %d\n", mSession);
3871 result.append(buffer);
3872 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
3873 result.append(buffer);
3874 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
3875 result.append(buffer);
3876 write(fd, result.string(), result.size());
3877
3878 return NO_ERROR;
3879}
3880
3881// --- IOProfile class implementation
3882
Eric Laurente0720872014-03-11 09:30:41 -07003883AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07003884 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
3885{
3886}
3887
Eric Laurente0720872014-03-11 09:30:41 -07003888AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07003889{
3890 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003891 mOutputProfiles[i]->mSupportedDevices.clear();
3892 delete mOutputProfiles[i];
Eric Laurente552edb2014-03-10 17:42:56 -07003893 }
3894 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003895 mInputProfiles[i]->mSupportedDevices.clear();
3896 delete mInputProfiles[i];
Eric Laurente552edb2014-03-10 17:42:56 -07003897 }
3898 free((void *)mName);
3899}
3900
Eric Laurente0720872014-03-11 09:30:41 -07003901void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07003902{
3903 const size_t SIZE = 256;
3904 char buffer[SIZE];
3905 String8 result;
3906
3907 snprintf(buffer, SIZE, " - name: %s\n", mName);
3908 result.append(buffer);
3909 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
3910 result.append(buffer);
3911 write(fd, result.string(), result.size());
3912 if (mOutputProfiles.size()) {
3913 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
3914 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07003915 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07003916 write(fd, buffer, strlen(buffer));
3917 mOutputProfiles[i]->dump(fd);
3918 }
3919 }
3920 if (mInputProfiles.size()) {
3921 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
3922 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07003923 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07003924 write(fd, buffer, strlen(buffer));
3925 mInputProfiles[i]->dump(fd);
3926 }
3927 }
3928}
3929
Eric Laurente0720872014-03-11 09:30:41 -07003930AudioPolicyManager::IOProfile::IOProfile(HwModule *module)
Eric Laurente552edb2014-03-10 17:42:56 -07003931 : mFlags((audio_output_flags_t)0), mModule(module)
3932{
3933}
3934
Eric Laurente0720872014-03-11 09:30:41 -07003935AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07003936{
3937}
3938
3939// checks if the IO profile is compatible with specified parameters.
3940// Sampling rate, format and channel mask must be specified in order to
3941// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07003942bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07003943 uint32_t samplingRate,
3944 audio_format_t format,
3945 audio_channel_mask_t channelMask,
3946 audio_output_flags_t flags) const
3947{
3948 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
3949 return false;
3950 }
3951
Eric Laurent3a4311c2014-03-17 12:00:47 -07003952 if ((mSupportedDevices.types() & device) != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07003953 return false;
3954 }
3955 if ((mFlags & flags) != flags) {
3956 return false;
3957 }
3958 size_t i;
3959 for (i = 0; i < mSamplingRates.size(); i++)
3960 {
3961 if (mSamplingRates[i] == samplingRate) {
3962 break;
3963 }
3964 }
3965 if (i == mSamplingRates.size()) {
3966 return false;
3967 }
3968 for (i = 0; i < mFormats.size(); i++)
3969 {
3970 if (mFormats[i] == format) {
3971 break;
3972 }
3973 }
3974 if (i == mFormats.size()) {
3975 return false;
3976 }
3977 for (i = 0; i < mChannelMasks.size(); i++)
3978 {
3979 if (mChannelMasks[i] == channelMask) {
3980 break;
3981 }
3982 }
3983 if (i == mChannelMasks.size()) {
3984 return false;
3985 }
3986 return true;
3987}
3988
Eric Laurente0720872014-03-11 09:30:41 -07003989void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07003990{
3991 const size_t SIZE = 256;
3992 char buffer[SIZE];
3993 String8 result;
3994
3995 snprintf(buffer, SIZE, " - sampling rates: ");
3996 result.append(buffer);
3997 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3998 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
3999 result.append(buffer);
4000 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
4001 }
4002
4003 snprintf(buffer, SIZE, " - channel masks: ");
4004 result.append(buffer);
4005 for (size_t i = 0; i < mChannelMasks.size(); i++) {
4006 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
4007 result.append(buffer);
4008 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
4009 }
4010
4011 snprintf(buffer, SIZE, " - formats: ");
4012 result.append(buffer);
4013 for (size_t i = 0; i < mFormats.size(); i++) {
4014 snprintf(buffer, SIZE, "0x%08x", mFormats[i]);
4015 result.append(buffer);
4016 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
4017 }
4018
Eric Laurent3a4311c2014-03-17 12:00:47 -07004019 snprintf(buffer, SIZE, " - devices:\n");
Eric Laurente552edb2014-03-10 17:42:56 -07004020 result.append(buffer);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004021 write(fd, result.string(), result.size());
4022 DeviceDescriptor::dumpHeader(fd, 6);
4023 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
4024 mSupportedDevices[i]->dump(fd, 6);
4025 }
4026
Eric Laurente552edb2014-03-10 17:42:56 -07004027 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
4028 result.append(buffer);
4029
4030 write(fd, result.string(), result.size());
4031}
4032
Eric Laurentd4692962014-05-05 18:13:44 -07004033void AudioPolicyManager::IOProfile::log()
4034{
4035 const size_t SIZE = 256;
4036 char buffer[SIZE];
4037 String8 result;
4038
4039 ALOGV(" - sampling rates: ");
4040 for (size_t i = 0; i < mSamplingRates.size(); i++) {
4041 ALOGV(" %d", mSamplingRates[i]);
4042 }
4043
4044 ALOGV(" - channel masks: ");
4045 for (size_t i = 0; i < mChannelMasks.size(); i++) {
4046 ALOGV(" 0x%04x", mChannelMasks[i]);
4047 }
4048
4049 ALOGV(" - formats: ");
4050 for (size_t i = 0; i < mFormats.size(); i++) {
4051 ALOGV(" 0x%08x", mFormats[i]);
4052 }
4053
4054 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
4055 ALOGV(" - flags: 0x%04x\n", mFlags);
4056}
4057
4058
Eric Laurent3a4311c2014-03-17 12:00:47 -07004059// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07004060
Eric Laurent3a4311c2014-03-17 12:00:47 -07004061bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07004062{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004063 // Devices are considered equal if they:
4064 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
4065 // - have the same address or one device does not specify the address
4066 // - have the same channel mask or one device does not specify the channel mask
4067 return (mType == other->mType) &&
4068 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07004069 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07004070 mChannelMask == other->mChannelMask);
4071}
4072
4073void AudioPolicyManager::DeviceVector::refreshTypes()
4074{
4075 mTypes = AUDIO_DEVICE_NONE;
4076 for(size_t i = 0; i < size(); i++) {
4077 mTypes |= itemAt(i)->mType;
4078 }
4079 ALOGV("DeviceVector::refreshTypes() mTypes %08x", mTypes);
4080}
4081
4082ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
4083{
4084 for(size_t i = 0; i < size(); i++) {
4085 if (item->equals(itemAt(i))) {
4086 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07004087 }
4088 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004089 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07004090}
4091
Eric Laurent3a4311c2014-03-17 12:00:47 -07004092ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07004093{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004094 ssize_t ret = indexOf(item);
4095
4096 if (ret < 0) {
4097 ret = SortedVector::add(item);
4098 if (ret >= 0) {
4099 refreshTypes();
4100 }
4101 } else {
4102 ALOGW("DeviceVector::add device %08x already in", item->mType);
4103 ret = -1;
4104 }
4105 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07004106}
4107
Eric Laurent3a4311c2014-03-17 12:00:47 -07004108ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
4109{
4110 size_t i;
4111 ssize_t ret = indexOf(item);
4112
4113 if (ret < 0) {
4114 ALOGW("DeviceVector::remove device %08x not in", item->mType);
4115 } else {
4116 ret = SortedVector::removeAt(ret);
4117 if (ret >= 0) {
4118 refreshTypes();
4119 }
4120 }
4121 return ret;
4122}
4123
4124void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
4125{
4126 DeviceVector deviceList;
4127
4128 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
4129 types &= ~role_bit;
4130
4131 while (types) {
4132 uint32_t i = 31 - __builtin_clz(types);
4133 uint32_t type = 1 << i;
4134 types &= ~type;
4135 add(new DeviceDescriptor(type | role_bit));
4136 }
4137}
4138
4139void AudioPolicyManager::DeviceDescriptor::dumpHeader(int fd, int spaces)
4140{
4141 const size_t SIZE = 256;
4142 char buffer[SIZE];
4143
4144 snprintf(buffer, SIZE, "%*s%-48s %-2s %-8s %-32s \n",
4145 spaces, "", "Type", "ID", "Cnl Mask", "Address");
4146 write(fd, buffer, strlen(buffer));
4147}
4148
4149status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces) const
4150{
4151 const size_t SIZE = 256;
4152 char buffer[SIZE];
4153
4154 snprintf(buffer, SIZE, "%*s%-48s %2d %08x %-32s \n",
4155 spaces, "",
4156 enumToString(sDeviceNameToEnumTable,
4157 ARRAY_SIZE(sDeviceNameToEnumTable),
4158 mType),
4159 mId, mChannelMask, mAddress.string());
4160 write(fd, buffer, strlen(buffer));
4161
4162 return NO_ERROR;
4163}
4164
4165
4166// --- audio_policy.conf file parsing
4167
Eric Laurente0720872014-03-11 09:30:41 -07004168audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07004169{
4170 uint32_t flag = 0;
4171
4172 // it is OK to cast name to non const here as we are not going to use it after
4173 // strtok() modifies it
4174 char *flagName = strtok(name, "|");
4175 while (flagName != NULL) {
4176 if (strlen(flagName) != 0) {
4177 flag |= stringToEnum(sFlagNameToEnumTable,
4178 ARRAY_SIZE(sFlagNameToEnumTable),
4179 flagName);
4180 }
4181 flagName = strtok(NULL, "|");
4182 }
4183 //force direct flag if offload flag is set: offloading implies a direct output stream
4184 // and all common behaviors are driven by checking only the direct flag
4185 // this should normally be set appropriately in the policy configuration file
4186 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
4187 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
4188 }
4189
4190 return (audio_output_flags_t)flag;
4191}
4192
Eric Laurente0720872014-03-11 09:30:41 -07004193audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07004194{
4195 uint32_t device = 0;
4196
4197 char *devName = strtok(name, "|");
4198 while (devName != NULL) {
4199 if (strlen(devName) != 0) {
4200 device |= stringToEnum(sDeviceNameToEnumTable,
4201 ARRAY_SIZE(sDeviceNameToEnumTable),
4202 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004203 }
Eric Laurente552edb2014-03-10 17:42:56 -07004204 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07004205 }
Eric Laurente552edb2014-03-10 17:42:56 -07004206 return device;
4207}
4208
Eric Laurente0720872014-03-11 09:30:41 -07004209void AudioPolicyManager::loadSamplingRates(char *name, IOProfile *profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004210{
4211 char *str = strtok(name, "|");
4212
4213 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
4214 // rates should be read from the output stream after it is opened for the first time
4215 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4216 profile->mSamplingRates.add(0);
4217 return;
4218 }
4219
4220 while (str != NULL) {
4221 uint32_t rate = atoi(str);
4222 if (rate != 0) {
4223 ALOGV("loadSamplingRates() adding rate %d", rate);
4224 profile->mSamplingRates.add(rate);
4225 }
4226 str = strtok(NULL, "|");
4227 }
4228 return;
4229}
4230
Eric Laurente0720872014-03-11 09:30:41 -07004231void AudioPolicyManager::loadFormats(char *name, IOProfile *profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004232{
4233 char *str = strtok(name, "|");
4234
4235 // by convention, "0' in the first entry in mFormats indicates the supported formats
4236 // should be read from the output stream after it is opened for the first time
4237 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4238 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
4239 return;
4240 }
4241
4242 while (str != NULL) {
4243 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
4244 ARRAY_SIZE(sFormatNameToEnumTable),
4245 str);
4246 if (format != AUDIO_FORMAT_DEFAULT) {
4247 profile->mFormats.add(format);
4248 }
4249 str = strtok(NULL, "|");
4250 }
4251 return;
4252}
4253
Eric Laurente0720872014-03-11 09:30:41 -07004254void AudioPolicyManager::loadInChannels(char *name, IOProfile *profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004255{
4256 const char *str = strtok(name, "|");
4257
4258 ALOGV("loadInChannels() %s", name);
4259
4260 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4261 profile->mChannelMasks.add(0);
4262 return;
4263 }
4264
4265 while (str != NULL) {
4266 audio_channel_mask_t channelMask =
4267 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
4268 ARRAY_SIZE(sInChannelsNameToEnumTable),
4269 str);
4270 if (channelMask != 0) {
4271 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
4272 profile->mChannelMasks.add(channelMask);
4273 }
4274 str = strtok(NULL, "|");
4275 }
4276 return;
4277}
4278
Eric Laurente0720872014-03-11 09:30:41 -07004279void AudioPolicyManager::loadOutChannels(char *name, IOProfile *profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004280{
4281 const char *str = strtok(name, "|");
4282
4283 ALOGV("loadOutChannels() %s", name);
4284
4285 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
4286 // masks should be read from the output stream after it is opened for the first time
4287 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4288 profile->mChannelMasks.add(0);
4289 return;
4290 }
4291
4292 while (str != NULL) {
4293 audio_channel_mask_t channelMask =
4294 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
4295 ARRAY_SIZE(sOutChannelsNameToEnumTable),
4296 str);
4297 if (channelMask != 0) {
4298 profile->mChannelMasks.add(channelMask);
4299 }
4300 str = strtok(NULL, "|");
4301 }
4302 return;
4303}
4304
Eric Laurente0720872014-03-11 09:30:41 -07004305status_t AudioPolicyManager::loadInput(cnode *root, HwModule *module)
Eric Laurente552edb2014-03-10 17:42:56 -07004306{
4307 cnode *node = root->first_child;
4308
4309 IOProfile *profile = new IOProfile(module);
4310
4311 while (node) {
4312 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4313 loadSamplingRates((char *)node->value, profile);
4314 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4315 loadFormats((char *)node->value, profile);
4316 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4317 loadInChannels((char *)node->value, profile);
4318 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004319 profile->mSupportedDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
Eric Laurente552edb2014-03-10 17:42:56 -07004320 }
4321 node = node->next;
4322 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004323 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
Eric Laurente552edb2014-03-10 17:42:56 -07004324 "loadInput() invalid supported devices");
4325 ALOGW_IF(profile->mChannelMasks.size() == 0,
4326 "loadInput() invalid supported channel masks");
4327 ALOGW_IF(profile->mSamplingRates.size() == 0,
4328 "loadInput() invalid supported sampling rates");
4329 ALOGW_IF(profile->mFormats.size() == 0,
4330 "loadInput() invalid supported formats");
Eric Laurent3a4311c2014-03-17 12:00:47 -07004331 if (!profile->mSupportedDevices.isEmpty() &&
Eric Laurente552edb2014-03-10 17:42:56 -07004332 (profile->mChannelMasks.size() != 0) &&
4333 (profile->mSamplingRates.size() != 0) &&
4334 (profile->mFormats.size() != 0)) {
4335
Eric Laurent3a4311c2014-03-17 12:00:47 -07004336 ALOGV("loadInput() adding input Supported Devices %04x",
4337 profile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004338
4339 module->mInputProfiles.add(profile);
4340 return NO_ERROR;
4341 } else {
4342 delete profile;
4343 return BAD_VALUE;
4344 }
4345}
4346
Eric Laurente0720872014-03-11 09:30:41 -07004347status_t AudioPolicyManager::loadOutput(cnode *root, HwModule *module)
Eric Laurente552edb2014-03-10 17:42:56 -07004348{
4349 cnode *node = root->first_child;
4350
4351 IOProfile *profile = new IOProfile(module);
4352
4353 while (node) {
4354 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4355 loadSamplingRates((char *)node->value, profile);
4356 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4357 loadFormats((char *)node->value, profile);
4358 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4359 loadOutChannels((char *)node->value, profile);
4360 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004361 profile->mSupportedDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
Eric Laurente552edb2014-03-10 17:42:56 -07004362 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
4363 profile->mFlags = parseFlagNames((char *)node->value);
4364 }
4365 node = node->next;
4366 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004367 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
Eric Laurente552edb2014-03-10 17:42:56 -07004368 "loadOutput() invalid supported devices");
4369 ALOGW_IF(profile->mChannelMasks.size() == 0,
4370 "loadOutput() invalid supported channel masks");
4371 ALOGW_IF(profile->mSamplingRates.size() == 0,
4372 "loadOutput() invalid supported sampling rates");
4373 ALOGW_IF(profile->mFormats.size() == 0,
4374 "loadOutput() invalid supported formats");
Eric Laurent3a4311c2014-03-17 12:00:47 -07004375 if (!profile->mSupportedDevices.isEmpty() &&
Eric Laurente552edb2014-03-10 17:42:56 -07004376 (profile->mChannelMasks.size() != 0) &&
4377 (profile->mSamplingRates.size() != 0) &&
4378 (profile->mFormats.size() != 0)) {
4379
Eric Laurent3a4311c2014-03-17 12:00:47 -07004380 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
4381 profile->mSupportedDevices.types(), profile->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07004382
4383 module->mOutputProfiles.add(profile);
4384 return NO_ERROR;
4385 } else {
4386 delete profile;
4387 return BAD_VALUE;
4388 }
4389}
4390
Eric Laurente0720872014-03-11 09:30:41 -07004391void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07004392{
4393 cnode *node = config_find(root, OUTPUTS_TAG);
4394 status_t status = NAME_NOT_FOUND;
4395
4396 HwModule *module = new HwModule(root->name);
4397
4398 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004399 node = node->first_child;
4400 while (node) {
4401 ALOGV("loadHwModule() loading output %s", node->name);
4402 status_t tmpStatus = loadOutput(node, module);
4403 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
4404 status = tmpStatus;
4405 }
4406 node = node->next;
4407 }
4408 }
4409 node = config_find(root, INPUTS_TAG);
4410 if (node != NULL) {
4411 node = node->first_child;
4412 while (node) {
4413 ALOGV("loadHwModule() loading input %s", node->name);
4414 status_t tmpStatus = loadInput(node, module);
4415 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
4416 status = tmpStatus;
4417 }
4418 node = node->next;
4419 }
4420 }
4421 if (status == NO_ERROR) {
4422 mHwModules.add(module);
4423 } else {
4424 delete module;
4425 }
4426}
4427
Eric Laurente0720872014-03-11 09:30:41 -07004428void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07004429{
4430 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
4431 if (node == NULL) {
4432 return;
4433 }
4434
4435 node = node->first_child;
4436 while (node) {
4437 ALOGV("loadHwModules() loading module %s", node->name);
4438 loadHwModule(node);
4439 node = node->next;
4440 }
4441}
4442
Eric Laurente0720872014-03-11 09:30:41 -07004443void AudioPolicyManager::loadGlobalConfig(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07004444{
4445 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
4446 if (node == NULL) {
4447 return;
4448 }
4449 node = node->first_child;
4450 while (node) {
4451 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004452 mAvailableOutputDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
4453 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
4454 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004455 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004456 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07004457 ARRAY_SIZE(sDeviceNameToEnumTable),
4458 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004459 if (device != AUDIO_DEVICE_NONE) {
4460 mDefaultOutputDevice = new DeviceDescriptor(device);
4461 } else {
4462 ALOGW("loadGlobalConfig() default device not specified");
4463 }
4464 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mType);
Eric Laurente552edb2014-03-10 17:42:56 -07004465 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004466 mAvailableInputDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
4467 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004468 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
4469 mSpeakerDrcEnabled = stringToBool((char *)node->value);
4470 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
4471 }
4472 node = node->next;
4473 }
4474}
4475
Eric Laurente0720872014-03-11 09:30:41 -07004476status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07004477{
4478 cnode *root;
4479 char *data;
4480
4481 data = (char *)load_file(path, NULL);
4482 if (data == NULL) {
4483 return -ENODEV;
4484 }
4485 root = config_node("", "");
4486 config_load(root, data);
4487
4488 loadGlobalConfig(root);
4489 loadHwModules(root);
4490
4491 config_free(root);
4492 free(root);
4493 free(data);
4494
4495 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
4496
4497 return NO_ERROR;
4498}
4499
Eric Laurente0720872014-03-11 09:30:41 -07004500void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07004501{
4502 HwModule *module;
4503 IOProfile *profile;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004504 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(AUDIO_DEVICE_IN_BUILTIN_MIC);
4505 mAvailableOutputDevices.add(mDefaultOutputDevice);
4506 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004507
4508 module = new HwModule("primary");
4509
4510 profile = new IOProfile(module);
4511 profile->mSamplingRates.add(44100);
4512 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4513 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004514 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004515 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
4516 module->mOutputProfiles.add(profile);
4517
4518 profile = new IOProfile(module);
4519 profile->mSamplingRates.add(8000);
4520 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4521 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004522 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004523 module->mInputProfiles.add(profile);
4524
4525 mHwModules.add(module);
4526}
4527
4528}; // namespace android