blob: eeba124f60ce183c0d378699261a51162207e090 [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
34#include <utils/Log.h>
Eric Laurente0720872014-03-11 09:30:41 -070035#include "AudioPolicyManager.h"
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <hardware/audio_effect.h>
37#include <hardware/audio.h>
38#include <math.h>
39#include <hardware_legacy/audio_policy_conf.h>
40#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070041#include <media/AudioParameter.h>
Eric Laurente552edb2014-03-10 17:42:56 -070042
Eric Laurent3b73df72014-03-11 09:06:29 -070043namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070044
45// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070046// Definitions for audio_policy.conf file parsing
47// ----------------------------------------------------------------------------
48
49struct StringToEnum {
50 const char *name;
51 uint32_t value;
52};
53
54#define STRING_TO_ENUM(string) { #string, string }
55#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
56
57const StringToEnum sDeviceNameToEnumTable[] = {
58 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
59 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
60 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
61 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
62 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
63 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
64 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
68 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
77 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
78 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
79 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
80 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
81 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
82 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
83 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
84 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
85 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
86 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
87 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
88};
89
90const StringToEnum sFlagNameToEnumTable[] = {
91 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
92 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
93 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
94 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
95 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
96 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
97};
98
99const StringToEnum sFormatNameToEnumTable[] = {
100 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
101 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
102 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
103 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
104 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
105 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
106 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
107 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
108 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
109};
110
111const StringToEnum sOutChannelsNameToEnumTable[] = {
112 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
113 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
114 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
115 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
116};
117
118const StringToEnum sInChannelsNameToEnumTable[] = {
119 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
120 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
121 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
122};
123
124
125uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
126 size_t size,
127 const char *name)
128{
129 for (size_t i = 0; i < size; i++) {
130 if (strcmp(table[i].name, name) == 0) {
131 ALOGV("stringToEnum() found %s", table[i].name);
132 return table[i].value;
133 }
134 }
135 return 0;
136}
137
138const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
139 size_t size,
140 uint32_t value)
141{
142 for (size_t i = 0; i < size; i++) {
143 if (table[i].value == value) {
144 return table[i].name;
145 }
146 }
147 return "";
148}
149
150bool AudioPolicyManager::stringToBool(const char *value)
151{
152 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
153}
154
155
156// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700157// AudioPolicyInterface implementation
158// ----------------------------------------------------------------------------
159
160
Eric Laurente0720872014-03-11 09:30:41 -0700161status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700162 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700163 const char *device_address)
164{
165 SortedVector <audio_io_handle_t> outputs;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700166 String8 address = String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700167
168 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
169
170 // connect/disconnect only 1 device at a time
171 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
172
173 if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
174 ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
175 return BAD_VALUE;
176 }
177
178 // handle output devices
179 if (audio_is_output_device(device)) {
180
181 if (!mHasA2dp && audio_is_a2dp_device(device)) {
182 ALOGE("setDeviceConnectionState() invalid A2DP device: %x", device);
183 return BAD_VALUE;
184 }
185 if (!mHasUsb && audio_is_usb_device(device)) {
186 ALOGE("setDeviceConnectionState() invalid USB audio device: %x", device);
187 return BAD_VALUE;
188 }
189 if (!mHasRemoteSubmix && audio_is_remote_submix_device((audio_devices_t)device)) {
190 ALOGE("setDeviceConnectionState() invalid remote submix audio device: %x", device);
191 return BAD_VALUE;
192 }
193
Eric Laurent3a4311c2014-03-17 12:00:47 -0700194 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(device,
195 address,
196 AUDIO_CHANNEL_NONE);
197 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
198
Eric Laurente552edb2014-03-10 17:42:56 -0700199 // save a copy of the opened output descriptors before any output is opened or closed
200 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
201 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700202 switch (state)
203 {
204 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700205 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700206 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700207 ALOGW("setDeviceConnectionState() device already connected: %x", device);
208 return INVALID_OPERATION;
209 }
210 ALOGV("setDeviceConnectionState() connecting device %x", device);
211
Eric Laurent3a4311c2014-03-17 12:00:47 -0700212 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -0700213 return INVALID_OPERATION;
214 }
215 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %d outputs",
216 outputs.size());
217 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700218 index = mAvailableOutputDevices.add(devDesc);
219 if (index >= 0) {
220 mAvailableOutputDevices[index]->mId = nextUniqueId();
221 } else {
222 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700223 }
224
225 break;
226 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700227 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700228 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700229 ALOGW("setDeviceConnectionState() device not connected: %x", device);
230 return INVALID_OPERATION;
231 }
232
233 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
234 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700235 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700236
Eric Laurent3a4311c2014-03-17 12:00:47 -0700237 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700238 // not currently handling multiple simultaneous submixes: ignoring remote submix
239 // case and address
240 } break;
241
242 default:
243 ALOGE("setDeviceConnectionState() invalid state: %x", state);
244 return BAD_VALUE;
245 }
246
Eric Laurent3a4311c2014-03-17 12:00:47 -0700247 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
248 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700249 checkA2dpSuspend();
250 checkOutputForAllStrategies();
251 // outputs must be closed after checkOutputForAllStrategies() is executed
252 if (!outputs.isEmpty()) {
253 for (size_t i = 0; i < outputs.size(); i++) {
254 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
255 // close unused outputs after device disconnection or direct outputs that have been
256 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700257 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700258 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
259 (desc->mDirectOpenCount == 0))) {
260 closeOutput(outputs[i]);
261 }
262 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700263 // check again after closing A2DP output to reset mA2dpSuspended if needed
264 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700265 }
266
267 updateDevicesAndOutputs();
268 for (size_t i = 0; i < mOutputs.size(); i++) {
269 // do not force device change on duplicated output because if device is 0, it will
270 // also force a device 0 for the two outputs it is duplicated to which may override
271 // a valid device selection on those outputs.
272 setOutputDevice(mOutputs.keyAt(i),
273 getNewDevice(mOutputs.keyAt(i), true /*fromCache*/),
274 !mOutputs.valueAt(i)->isDuplicated(),
275 0);
276 }
277
278 if (device == AUDIO_DEVICE_OUT_WIRED_HEADSET) {
279 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
280 } else if (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO ||
281 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
282 device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
283 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
284 } else {
285 return NO_ERROR;
286 }
287 }
288 // handle input devices
289 if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700290 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(device,
291 address,
292 AUDIO_CHANNEL_NONE);
Eric Laurente552edb2014-03-10 17:42:56 -0700293
Eric Laurent3a4311c2014-03-17 12:00:47 -0700294 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700295 switch (state)
296 {
297 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700298 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700299 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700300 ALOGW("setDeviceConnectionState() device already connected: %d", device);
301 return INVALID_OPERATION;
302 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700303 index = mAvailableInputDevices.add(devDesc);
304 if (index >= 0) {
305 mAvailableInputDevices[index]->mId = nextUniqueId();
306 } else {
307 return NO_MEMORY;
308 }
Eric Laurente552edb2014-03-10 17:42:56 -0700309 }
310 break;
311
312 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700313 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700314 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700315 ALOGW("setDeviceConnectionState() device not connected: %d", device);
316 return INVALID_OPERATION;
317 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700318 mAvailableInputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700319 } break;
320
321 default:
322 ALOGE("setDeviceConnectionState() invalid state: %x", state);
323 return BAD_VALUE;
324 }
325
326 audio_io_handle_t activeInput = getActiveInput();
327 if (activeInput != 0) {
328 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
329 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
330 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
331 ALOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
332 inputDesc->mDevice, newDevice, activeInput);
333 inputDesc->mDevice = newDevice;
334 AudioParameter param = AudioParameter();
335 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
336 mpClientInterface->setParameters(activeInput, param.toString());
337 }
338 }
339
340 return NO_ERROR;
341 }
342
343 ALOGW("setDeviceConnectionState() invalid device: %x", device);
344 return BAD_VALUE;
345}
346
Eric Laurente0720872014-03-11 09:30:41 -0700347audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700348 const char *device_address)
349{
Eric Laurent3b73df72014-03-11 09:06:29 -0700350 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700351 String8 address = String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700352 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(device,
353 String8(device_address),
354 AUDIO_CHANNEL_NONE);
355 ssize_t index;
356 DeviceVector *deviceVector;
357
Eric Laurente552edb2014-03-10 17:42:56 -0700358 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700359 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700360 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700361 deviceVector = &mAvailableInputDevices;
362 } else {
363 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
364 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700365 }
366
Eric Laurent3a4311c2014-03-17 12:00:47 -0700367 index = deviceVector->indexOf(devDesc);
368 if (index >= 0) {
369 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
370 } else {
371 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
372 }
Eric Laurente552edb2014-03-10 17:42:56 -0700373}
374
Eric Laurente0720872014-03-11 09:30:41 -0700375void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700376{
377 ALOGV("setPhoneState() state %d", state);
378 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
Eric Laurent3b73df72014-03-11 09:06:29 -0700379 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700380 ALOGW("setPhoneState() invalid state %d", state);
381 return;
382 }
383
384 if (state == mPhoneState ) {
385 ALOGW("setPhoneState() setting same state %d", state);
386 return;
387 }
388
389 // if leaving call state, handle special case of active streams
390 // pertaining to sonification strategy see handleIncallSonification()
391 if (isInCall()) {
392 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700393 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
394 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700395 }
396 }
397
398 // store previous phone state for management of sonification strategy below
399 int oldState = mPhoneState;
400 mPhoneState = state;
401 bool force = false;
402
403 // are we entering or starting a call
404 if (!isStateInCall(oldState) && isStateInCall(state)) {
405 ALOGV(" Entering call in setPhoneState()");
406 // force routing command to audio hardware when starting a call
407 // even if no device change is needed
408 force = true;
409 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
410 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
411 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
412 }
413 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
414 ALOGV(" Exiting call in setPhoneState()");
415 // force routing command to audio hardware when exiting a call
416 // even if no device change is needed
417 force = true;
418 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
419 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
420 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
421 }
422 } else if (isStateInCall(state) && (state != oldState)) {
423 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
424 // force routing command to audio hardware when switching between telephony and VoIP
425 // even if no device change is needed
426 force = true;
427 }
428
429 // check for device and output changes triggered by new phone state
430 newDevice = getNewDevice(mPrimaryOutput, false /*fromCache*/);
431 checkA2dpSuspend();
432 checkOutputForAllStrategies();
433 updateDevicesAndOutputs();
434
435 AudioOutputDescriptor *hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
436
437 // force routing command to audio hardware when ending call
438 // even if no device change is needed
439 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
440 newDevice = hwOutputDesc->device();
441 }
442
443 int delayMs = 0;
444 if (isStateInCall(state)) {
445 nsecs_t sysTime = systemTime();
446 for (size_t i = 0; i < mOutputs.size(); i++) {
447 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
448 // mute media and sonification strategies and delay device switch by the largest
449 // latency of any output where either strategy is active.
450 // This avoid sending the ring tone or music tail into the earpiece or headset.
451 if ((desc->isStrategyActive(STRATEGY_MEDIA,
452 SONIFICATION_HEADSET_MUSIC_DELAY,
453 sysTime) ||
454 desc->isStrategyActive(STRATEGY_SONIFICATION,
455 SONIFICATION_HEADSET_MUSIC_DELAY,
456 sysTime)) &&
457 (delayMs < (int)desc->mLatency*2)) {
458 delayMs = desc->mLatency*2;
459 }
460 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
461 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
462 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
463 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
464 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
465 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
466 }
467 }
468
469 // change routing is necessary
470 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
471
472 // if entering in call state, handle special case of active streams
473 // pertaining to sonification strategy see handleIncallSonification()
474 if (isStateInCall(state)) {
475 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700476 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
477 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700478 }
479 }
480
481 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700482 if (state == AUDIO_MODE_RINGTONE &&
483 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700484 mLimitRingtoneVolume = true;
485 } else {
486 mLimitRingtoneVolume = false;
487 }
488}
489
Eric Laurente0720872014-03-11 09:30:41 -0700490void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700491 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700492{
493 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
494
495 bool forceVolumeReeval = false;
496 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700497 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
498 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
499 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700500 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
501 return;
502 }
503 forceVolumeReeval = true;
504 mForceUse[usage] = config;
505 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700506 case AUDIO_POLICY_FORCE_FOR_MEDIA:
507 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
508 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
509 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
510 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
511 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700512 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
513 return;
514 }
515 mForceUse[usage] = config;
516 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700517 case AUDIO_POLICY_FORCE_FOR_RECORD:
518 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
519 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700520 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
521 return;
522 }
523 mForceUse[usage] = config;
524 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700525 case AUDIO_POLICY_FORCE_FOR_DOCK:
526 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
527 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
528 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
529 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
530 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700531 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
532 }
533 forceVolumeReeval = true;
534 mForceUse[usage] = config;
535 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700536 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
537 if (config != AUDIO_POLICY_FORCE_NONE &&
538 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700539 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
540 }
541 forceVolumeReeval = true;
542 mForceUse[usage] = config;
543 break;
544 default:
545 ALOGW("setForceUse() invalid usage %d", usage);
546 break;
547 }
548
549 // check for device and output changes triggered by new force usage
550 checkA2dpSuspend();
551 checkOutputForAllStrategies();
552 updateDevicesAndOutputs();
553 for (size_t i = 0; i < mOutputs.size(); i++) {
554 audio_io_handle_t output = mOutputs.keyAt(i);
555 audio_devices_t newDevice = getNewDevice(output, true /*fromCache*/);
556 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
557 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
558 applyStreamVolumes(output, newDevice, 0, true);
559 }
560 }
561
562 audio_io_handle_t activeInput = getActiveInput();
563 if (activeInput != 0) {
564 AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
565 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
566 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
567 ALOGV("setForceUse() changing device from %x to %x for input %d",
568 inputDesc->mDevice, newDevice, activeInput);
569 inputDesc->mDevice = newDevice;
570 AudioParameter param = AudioParameter();
571 param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
572 mpClientInterface->setParameters(activeInput, param.toString());
573 }
574 }
575
576}
577
Eric Laurente0720872014-03-11 09:30:41 -0700578audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700579{
580 return mForceUse[usage];
581}
582
Eric Laurente0720872014-03-11 09:30:41 -0700583void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700584{
585 ALOGV("setSystemProperty() property %s, value %s", property, value);
586}
587
588// Find a direct output profile compatible with the parameters passed, even if the input flags do
589// not explicitly request a direct output
Eric Laurente0720872014-03-11 09:30:41 -0700590AudioPolicyManager::IOProfile *AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700591 audio_devices_t device,
592 uint32_t samplingRate,
593 audio_format_t format,
594 audio_channel_mask_t channelMask,
595 audio_output_flags_t flags)
596{
597 for (size_t i = 0; i < mHwModules.size(); i++) {
598 if (mHwModules[i]->mHandle == 0) {
599 continue;
600 }
601 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
602 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent3a4311c2014-03-17 12:00:47 -0700603 bool found = false;
Eric Laurente552edb2014-03-10 17:42:56 -0700604 if (flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
605 if (profile->isCompatibleProfile(device, samplingRate, format,
606 channelMask,
607 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700608 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700609 }
610 } else {
611 if (profile->isCompatibleProfile(device, samplingRate, format,
612 channelMask,
613 AUDIO_OUTPUT_FLAG_DIRECT)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700614 found = true;
Eric Laurente552edb2014-03-10 17:42:56 -0700615 }
616 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700617 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
618 return profile;
619 }
Eric Laurente552edb2014-03-10 17:42:56 -0700620 }
621 }
622 return 0;
623}
624
Eric Laurente0720872014-03-11 09:30:41 -0700625audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700626 uint32_t samplingRate,
627 audio_format_t format,
628 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700629 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700630 const audio_offload_info_t *offloadInfo)
631{
632 audio_io_handle_t output = 0;
633 uint32_t latency = 0;
Eric Laurent3b73df72014-03-11 09:06:29 -0700634 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700635 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
636 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
637 device, stream, samplingRate, format, channelMask, flags);
638
639#ifdef AUDIO_POLICY_TEST
640 if (mCurOutput != 0) {
641 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
642 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
643
644 if (mTestOutputs[mCurOutput] == 0) {
645 ALOGV("getOutput() opening test output");
646 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
647 outputDesc->mDevice = mTestDevice;
648 outputDesc->mSamplingRate = mTestSamplingRate;
649 outputDesc->mFormat = mTestFormat;
650 outputDesc->mChannelMask = mTestChannels;
651 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700652 outputDesc->mFlags =
653 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700654 outputDesc->mRefCount[stream] = 0;
655 mTestOutputs[mCurOutput] = mpClientInterface->openOutput(0, &outputDesc->mDevice,
656 &outputDesc->mSamplingRate,
657 &outputDesc->mFormat,
658 &outputDesc->mChannelMask,
659 &outputDesc->mLatency,
660 outputDesc->mFlags,
661 offloadInfo);
662 if (mTestOutputs[mCurOutput]) {
663 AudioParameter outputCmd = AudioParameter();
664 outputCmd.addInt(String8("set_id"),mCurOutput);
665 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
666 addOutput(mTestOutputs[mCurOutput], outputDesc);
667 }
668 }
669 return mTestOutputs[mCurOutput];
670 }
671#endif //AUDIO_POLICY_TEST
672
673 // open a direct output if required by specified parameters
674 //force direct flag if offload flag is set: offloading implies a direct output stream
675 // and all common behaviors are driven by checking only the direct flag
676 // this should normally be set appropriately in the policy configuration file
677 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700678 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700679 }
680
681 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
682 // creating an offloaded track and tearing it down immediately after start when audioflinger
683 // detects there is an active non offloadable effect.
684 // FIXME: We should check the audio session here but we do not have it in this context.
685 // This may prevent offloading in rare situations where effects are left active by apps
686 // in the background.
687 IOProfile *profile = NULL;
688 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
689 !isNonOffloadableEffectEnabled()) {
690 profile = getProfileForDirectOutput(device,
691 samplingRate,
692 format,
693 channelMask,
694 (audio_output_flags_t)flags);
695 }
696
697 if (profile != NULL) {
698 AudioOutputDescriptor *outputDesc = NULL;
699
700 for (size_t i = 0; i < mOutputs.size(); i++) {
701 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
702 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
703 outputDesc = desc;
704 // reuse direct output if currently open and configured with same parameters
705 if ((samplingRate == outputDesc->mSamplingRate) &&
706 (format == outputDesc->mFormat) &&
707 (channelMask == outputDesc->mChannelMask)) {
708 outputDesc->mDirectOpenCount++;
709 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
710 return mOutputs.keyAt(i);
711 }
712 }
713 }
714 // close direct output if currently open and configured with different parameters
715 if (outputDesc != NULL) {
716 closeOutput(outputDesc->mId);
717 }
718 outputDesc = new AudioOutputDescriptor(profile);
719 outputDesc->mDevice = device;
720 outputDesc->mSamplingRate = samplingRate;
721 outputDesc->mFormat = format;
722 outputDesc->mChannelMask = channelMask;
723 outputDesc->mLatency = 0;
724 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
725 outputDesc->mRefCount[stream] = 0;
726 outputDesc->mStopTime[stream] = 0;
727 outputDesc->mDirectOpenCount = 1;
728 output = mpClientInterface->openOutput(profile->mModule->mHandle,
729 &outputDesc->mDevice,
730 &outputDesc->mSamplingRate,
731 &outputDesc->mFormat,
732 &outputDesc->mChannelMask,
733 &outputDesc->mLatency,
734 outputDesc->mFlags,
735 offloadInfo);
736
737 // only accept an output with the requested parameters
738 if (output == 0 ||
739 (samplingRate != 0 && samplingRate != outputDesc->mSamplingRate) ||
740 (format != AUDIO_FORMAT_DEFAULT && format != outputDesc->mFormat) ||
741 (channelMask != 0 && channelMask != outputDesc->mChannelMask)) {
742 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
743 "format %d %d, channelMask %04x %04x", output, samplingRate,
744 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
745 outputDesc->mChannelMask);
746 if (output != 0) {
747 mpClientInterface->closeOutput(output);
748 }
749 delete outputDesc;
750 return 0;
751 }
752 audio_io_handle_t srcOutput = getOutputForEffect();
753 addOutput(output, outputDesc);
754 audio_io_handle_t dstOutput = getOutputForEffect();
755 if (dstOutput == output) {
756 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
757 }
758 mPreviousOutputs = mOutputs;
759 ALOGV("getOutput() returns new direct output %d", output);
760 return output;
761 }
762
763 // ignoring channel mask due to downmix capability in mixer
764
765 // open a non direct output
766
767 // for non direct outputs, only PCM is supported
768 if (audio_is_linear_pcm(format)) {
769 // get which output is suitable for the specified stream. The actual
770 // routing change will happen when startOutput() will be called
771 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
772
773 output = selectOutput(outputs, flags);
774 }
775 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
776 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
777
778 ALOGV("getOutput() returns output %d", output);
779
780 return output;
781}
782
Eric Laurente0720872014-03-11 09:30:41 -0700783audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700784 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700785{
786 // select one output among several that provide a path to a particular device or set of
787 // devices (the list was previously build by getOutputsForDevice()).
788 // The priority is as follows:
789 // 1: the output with the highest number of requested policy flags
790 // 2: the primary output
791 // 3: the first output in the list
792
793 if (outputs.size() == 0) {
794 return 0;
795 }
796 if (outputs.size() == 1) {
797 return outputs[0];
798 }
799
800 int maxCommonFlags = 0;
801 audio_io_handle_t outputFlags = 0;
802 audio_io_handle_t outputPrimary = 0;
803
804 for (size_t i = 0; i < outputs.size(); i++) {
805 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(outputs[i]);
806 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700807 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700808 if (commonFlags > maxCommonFlags) {
809 outputFlags = outputs[i];
810 maxCommonFlags = commonFlags;
811 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
812 }
813 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
814 outputPrimary = outputs[i];
815 }
816 }
817 }
818
819 if (outputFlags != 0) {
820 return outputFlags;
821 }
822 if (outputPrimary != 0) {
823 return outputPrimary;
824 }
825
826 return outputs[0];
827}
828
Eric Laurente0720872014-03-11 09:30:41 -0700829status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700830 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700831 int session)
832{
833 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
834 ssize_t index = mOutputs.indexOfKey(output);
835 if (index < 0) {
836 ALOGW("startOutput() unknown output %d", output);
837 return BAD_VALUE;
838 }
839
840 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
841
842 // increment usage count for this stream on the requested output:
843 // NOTE that the usage count is the same for duplicated output and hardware output which is
844 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
845 outputDesc->changeRefCount(stream, 1);
846
847 if (outputDesc->mRefCount[stream] == 1) {
848 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
849 routing_strategy strategy = getStrategy(stream);
850 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
851 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
852 uint32_t waitMs = 0;
853 bool force = false;
854 for (size_t i = 0; i < mOutputs.size(); i++) {
855 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
856 if (desc != outputDesc) {
857 // force a device change if any other output is managed by the same hw
858 // module and has a current device selection that differs from selected device.
859 // In this case, the audio HAL must receive the new device selection so that it can
860 // change the device currently selected by the other active output.
861 if (outputDesc->sharesHwModuleWith(desc) &&
862 desc->device() != newDevice) {
863 force = true;
864 }
865 // wait for audio on other active outputs to be presented when starting
866 // a notification so that audio focus effect can propagate.
867 uint32_t latency = desc->latency();
868 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
869 waitMs = latency;
870 }
871 }
872 }
873 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
874
875 // handle special case for sonification while in call
876 if (isInCall()) {
877 handleIncallSonification(stream, true, false);
878 }
879
880 // apply volume rules for current stream and device if necessary
881 checkAndSetVolume(stream,
882 mStreams[stream].getVolumeIndex(newDevice),
883 output,
884 newDevice);
885
886 // update the outputs if starting an output with a stream that can affect notification
887 // routing
888 handleNotificationRoutingForStream(stream);
889 if (waitMs > muteWaitMs) {
890 usleep((waitMs - muteWaitMs) * 2 * 1000);
891 }
892 }
893 return NO_ERROR;
894}
895
896
Eric Laurente0720872014-03-11 09:30:41 -0700897status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700898 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700899 int session)
900{
901 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
902 ssize_t index = mOutputs.indexOfKey(output);
903 if (index < 0) {
904 ALOGW("stopOutput() unknown output %d", output);
905 return BAD_VALUE;
906 }
907
908 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
909
910 // handle special case for sonification while in call
911 if (isInCall()) {
912 handleIncallSonification(stream, false, false);
913 }
914
915 if (outputDesc->mRefCount[stream] > 0) {
916 // decrement usage count of this stream on the output
917 outputDesc->changeRefCount(stream, -1);
918 // store time at which the stream was stopped - see isStreamActive()
919 if (outputDesc->mRefCount[stream] == 0) {
920 outputDesc->mStopTime[stream] = systemTime();
921 audio_devices_t newDevice = getNewDevice(output, false /*fromCache*/);
922 // delay the device switch by twice the latency because stopOutput() is executed when
923 // the track stop() command is received and at that time the audio track buffer can
924 // still contain data that needs to be drained. The latency only covers the audio HAL
925 // and kernel buffers. Also the latency does not always include additional delay in the
926 // audio path (audio DSP, CODEC ...)
927 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
928
929 // force restoring the device selection on other active outputs if it differs from the
930 // one being selected for this output
931 for (size_t i = 0; i < mOutputs.size(); i++) {
932 audio_io_handle_t curOutput = mOutputs.keyAt(i);
933 AudioOutputDescriptor *desc = mOutputs.valueAt(i);
934 if (curOutput != output &&
935 desc->isActive() &&
936 outputDesc->sharesHwModuleWith(desc) &&
937 (newDevice != desc->device())) {
938 setOutputDevice(curOutput,
939 getNewDevice(curOutput, false /*fromCache*/),
940 true,
941 outputDesc->mLatency*2);
942 }
943 }
944 // update the outputs if stopping one with a stream that can affect notification routing
945 handleNotificationRoutingForStream(stream);
946 }
947 return NO_ERROR;
948 } else {
949 ALOGW("stopOutput() refcount is already 0 for output %d", output);
950 return INVALID_OPERATION;
951 }
952}
953
Eric Laurente0720872014-03-11 09:30:41 -0700954void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -0700955{
956 ALOGV("releaseOutput() %d", output);
957 ssize_t index = mOutputs.indexOfKey(output);
958 if (index < 0) {
959 ALOGW("releaseOutput() releasing unknown output %d", output);
960 return;
961 }
962
963#ifdef AUDIO_POLICY_TEST
964 int testIndex = testOutputIndex(output);
965 if (testIndex != 0) {
966 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(index);
967 if (outputDesc->isActive()) {
968 mpClientInterface->closeOutput(output);
969 delete mOutputs.valueAt(index);
970 mOutputs.removeItem(output);
971 mTestOutputs[testIndex] = 0;
972 }
973 return;
974 }
975#endif //AUDIO_POLICY_TEST
976
977 AudioOutputDescriptor *desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -0700978 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700979 if (desc->mDirectOpenCount <= 0) {
980 ALOGW("releaseOutput() invalid open count %d for output %d",
981 desc->mDirectOpenCount, output);
982 return;
983 }
984 if (--desc->mDirectOpenCount == 0) {
985 closeOutput(output);
986 // If effects where present on the output, audioflinger moved them to the primary
987 // output by default: move them back to the appropriate output.
988 audio_io_handle_t dstOutput = getOutputForEffect();
989 if (dstOutput != mPrimaryOutput) {
990 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
991 }
992 }
993 }
994}
995
996
Eric Laurente0720872014-03-11 09:30:41 -0700997audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -0700998 uint32_t samplingRate,
999 audio_format_t format,
1000 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -07001001 audio_in_acoustics_t acoustics)
Eric Laurente552edb2014-03-10 17:42:56 -07001002{
1003 audio_io_handle_t input = 0;
1004 audio_devices_t device = getDeviceForInputSource(inputSource);
1005
1006 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, acoustics %x",
1007 inputSource, samplingRate, format, channelMask, acoustics);
1008
1009 if (device == AUDIO_DEVICE_NONE) {
1010 ALOGW("getInput() could not find device for inputSource %d", inputSource);
1011 return 0;
1012 }
1013
1014 // adapt channel selection to input source
1015 switch(inputSource) {
1016 case AUDIO_SOURCE_VOICE_UPLINK:
1017 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1018 break;
1019 case AUDIO_SOURCE_VOICE_DOWNLINK:
1020 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1021 break;
1022 case AUDIO_SOURCE_VOICE_CALL:
1023 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1024 break;
1025 default:
1026 break;
1027 }
1028
1029 IOProfile *profile = getInputProfile(device,
1030 samplingRate,
1031 format,
1032 channelMask);
1033 if (profile == NULL) {
1034 ALOGW("getInput() could not find profile for device %04x, samplingRate %d, format %d, "
1035 "channelMask %04x",
1036 device, samplingRate, format, channelMask);
1037 return 0;
1038 }
1039
1040 if (profile->mModule->mHandle == 0) {
1041 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
1042 return 0;
1043 }
1044
1045 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(profile);
1046
1047 inputDesc->mInputSource = inputSource;
1048 inputDesc->mDevice = device;
1049 inputDesc->mSamplingRate = samplingRate;
1050 inputDesc->mFormat = format;
1051 inputDesc->mChannelMask = channelMask;
1052 inputDesc->mRefCount = 0;
1053 input = mpClientInterface->openInput(profile->mModule->mHandle,
1054 &inputDesc->mDevice,
1055 &inputDesc->mSamplingRate,
1056 &inputDesc->mFormat,
1057 &inputDesc->mChannelMask);
1058
1059 // only accept input with the exact requested set of parameters
1060 if (input == 0 ||
1061 (samplingRate != inputDesc->mSamplingRate) ||
1062 (format != inputDesc->mFormat) ||
1063 (channelMask != inputDesc->mChannelMask)) {
1064 ALOGI("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1065 samplingRate, format, channelMask);
1066 if (input != 0) {
1067 mpClientInterface->closeInput(input);
1068 }
1069 delete inputDesc;
1070 return 0;
1071 }
1072 mInputs.add(input, inputDesc);
1073 return input;
1074}
1075
Eric Laurente0720872014-03-11 09:30:41 -07001076status_t AudioPolicyManager::startInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001077{
1078 ALOGV("startInput() input %d", input);
1079 ssize_t index = mInputs.indexOfKey(input);
1080 if (index < 0) {
1081 ALOGW("startInput() unknown input %d", input);
1082 return BAD_VALUE;
1083 }
1084 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1085
1086#ifdef AUDIO_POLICY_TEST
1087 if (mTestInput == 0)
1088#endif //AUDIO_POLICY_TEST
1089 {
1090 // refuse 2 active AudioRecord clients at the same time except if the active input
1091 // uses AUDIO_SOURCE_HOTWORD in which case it is closed.
1092 audio_io_handle_t activeInput = getActiveInput();
1093 if (!isVirtualInputDevice(inputDesc->mDevice) && activeInput != 0) {
1094 AudioInputDescriptor *activeDesc = mInputs.valueFor(activeInput);
1095 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
1096 ALOGW("startInput() preempting already started low-priority input %d", activeInput);
1097 stopInput(activeInput);
1098 releaseInput(activeInput);
1099 } else {
1100 ALOGW("startInput() input %d failed: other input already started", input);
1101 return INVALID_OPERATION;
1102 }
1103 }
1104 }
1105
1106 audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
1107 if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
1108 inputDesc->mDevice = newDevice;
1109 }
1110
1111 // automatically enable the remote submix output when input is started
1112 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1113 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001114 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001115 }
1116
1117 AudioParameter param = AudioParameter();
1118 param.addInt(String8(AudioParameter::keyRouting), (int)inputDesc->mDevice);
1119
1120 int aliasSource = (inputDesc->mInputSource == AUDIO_SOURCE_HOTWORD) ?
1121 AUDIO_SOURCE_VOICE_RECOGNITION : inputDesc->mInputSource;
1122
1123 param.addInt(String8(AudioParameter::keyInputSource), aliasSource);
1124 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1125
1126 mpClientInterface->setParameters(input, param.toString());
1127
1128 inputDesc->mRefCount = 1;
1129 return NO_ERROR;
1130}
1131
Eric Laurente0720872014-03-11 09:30:41 -07001132status_t AudioPolicyManager::stopInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001133{
1134 ALOGV("stopInput() input %d", input);
1135 ssize_t index = mInputs.indexOfKey(input);
1136 if (index < 0) {
1137 ALOGW("stopInput() unknown input %d", input);
1138 return BAD_VALUE;
1139 }
1140 AudioInputDescriptor *inputDesc = mInputs.valueAt(index);
1141
1142 if (inputDesc->mRefCount == 0) {
1143 ALOGW("stopInput() input %d already stopped", input);
1144 return INVALID_OPERATION;
1145 } else {
1146 // automatically disable the remote submix output when input is stopped
1147 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1148 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001149 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001150 }
1151
1152 AudioParameter param = AudioParameter();
1153 param.addInt(String8(AudioParameter::keyRouting), 0);
1154 mpClientInterface->setParameters(input, param.toString());
1155 inputDesc->mRefCount = 0;
1156 return NO_ERROR;
1157 }
1158}
1159
Eric Laurente0720872014-03-11 09:30:41 -07001160void AudioPolicyManager::releaseInput(audio_io_handle_t input)
Eric Laurente552edb2014-03-10 17:42:56 -07001161{
1162 ALOGV("releaseInput() %d", input);
1163 ssize_t index = mInputs.indexOfKey(input);
1164 if (index < 0) {
1165 ALOGW("releaseInput() releasing unknown input %d", input);
1166 return;
1167 }
1168 mpClientInterface->closeInput(input);
1169 delete mInputs.valueAt(index);
1170 mInputs.removeItem(input);
1171 ALOGV("releaseInput() exit");
1172}
1173
Eric Laurente0720872014-03-11 09:30:41 -07001174void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001175 int indexMin,
1176 int indexMax)
1177{
1178 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1179 if (indexMin < 0 || indexMin >= indexMax) {
1180 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1181 return;
1182 }
1183 mStreams[stream].mIndexMin = indexMin;
1184 mStreams[stream].mIndexMax = indexMax;
1185}
1186
Eric Laurente0720872014-03-11 09:30:41 -07001187status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001188 int index,
1189 audio_devices_t device)
1190{
1191
1192 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1193 return BAD_VALUE;
1194 }
1195 if (!audio_is_output_device(device)) {
1196 return BAD_VALUE;
1197 }
1198
1199 // Force max volume if stream cannot be muted
1200 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1201
1202 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1203 stream, device, index);
1204
1205 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1206 // clear all device specific values
1207 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1208 mStreams[stream].mIndexCur.clear();
1209 }
1210 mStreams[stream].mIndexCur.add(device, index);
1211
1212 // compute and apply stream volume on all outputs according to connected device
1213 status_t status = NO_ERROR;
1214 for (size_t i = 0; i < mOutputs.size(); i++) {
1215 audio_devices_t curDevice =
1216 getDeviceForVolume(mOutputs.valueAt(i)->device());
1217 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1218 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1219 if (volStatus != NO_ERROR) {
1220 status = volStatus;
1221 }
1222 }
1223 }
1224 return status;
1225}
1226
Eric Laurente0720872014-03-11 09:30:41 -07001227status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001228 int *index,
1229 audio_devices_t device)
1230{
1231 if (index == NULL) {
1232 return BAD_VALUE;
1233 }
1234 if (!audio_is_output_device(device)) {
1235 return BAD_VALUE;
1236 }
1237 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1238 // the strategy the stream belongs to.
1239 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1240 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1241 }
1242 device = getDeviceForVolume(device);
1243
1244 *index = mStreams[stream].getVolumeIndex(device);
1245 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1246 return NO_ERROR;
1247}
1248
Eric Laurente0720872014-03-11 09:30:41 -07001249audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001250 const SortedVector<audio_io_handle_t>& outputs)
1251{
1252 // select one output among several suitable for global effects.
1253 // The priority is as follows:
1254 // 1: An offloaded output. If the effect ends up not being offloadable,
1255 // AudioFlinger will invalidate the track and the offloaded output
1256 // will be closed causing the effect to be moved to a PCM output.
1257 // 2: A deep buffer output
1258 // 3: the first output in the list
1259
1260 if (outputs.size() == 0) {
1261 return 0;
1262 }
1263
1264 audio_io_handle_t outputOffloaded = 0;
1265 audio_io_handle_t outputDeepBuffer = 0;
1266
1267 for (size_t i = 0; i < outputs.size(); i++) {
1268 AudioOutputDescriptor *desc = mOutputs.valueFor(outputs[i]);
1269 ALOGV("selectOutputForEffects outputs[%d] flags %x", i, desc->mFlags);
1270 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1271 outputOffloaded = outputs[i];
1272 }
1273 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1274 outputDeepBuffer = outputs[i];
1275 }
1276 }
1277
1278 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1279 outputOffloaded, outputDeepBuffer);
1280 if (outputOffloaded != 0) {
1281 return outputOffloaded;
1282 }
1283 if (outputDeepBuffer != 0) {
1284 return outputDeepBuffer;
1285 }
1286
1287 return outputs[0];
1288}
1289
Eric Laurente0720872014-03-11 09:30:41 -07001290audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001291{
1292 // apply simple rule where global effects are attached to the same output as MUSIC streams
1293
Eric Laurent3b73df72014-03-11 09:06:29 -07001294 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001295 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1296 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1297
1298 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1299 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1300 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1301
1302 return output;
1303}
1304
Eric Laurente0720872014-03-11 09:30:41 -07001305status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001306 audio_io_handle_t io,
1307 uint32_t strategy,
1308 int session,
1309 int id)
1310{
1311 ssize_t index = mOutputs.indexOfKey(io);
1312 if (index < 0) {
1313 index = mInputs.indexOfKey(io);
1314 if (index < 0) {
1315 ALOGW("registerEffect() unknown io %d", io);
1316 return INVALID_OPERATION;
1317 }
1318 }
1319
1320 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1321 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1322 desc->name, desc->memoryUsage);
1323 return INVALID_OPERATION;
1324 }
1325 mTotalEffectsMemory += desc->memoryUsage;
1326 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1327 desc->name, io, strategy, session, id);
1328 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1329
1330 EffectDescriptor *pDesc = new EffectDescriptor();
1331 memcpy (&pDesc->mDesc, desc, sizeof(effect_descriptor_t));
1332 pDesc->mIo = io;
1333 pDesc->mStrategy = (routing_strategy)strategy;
1334 pDesc->mSession = session;
1335 pDesc->mEnabled = false;
1336
1337 mEffects.add(id, pDesc);
1338
1339 return NO_ERROR;
1340}
1341
Eric Laurente0720872014-03-11 09:30:41 -07001342status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001343{
1344 ssize_t index = mEffects.indexOfKey(id);
1345 if (index < 0) {
1346 ALOGW("unregisterEffect() unknown effect ID %d", id);
1347 return INVALID_OPERATION;
1348 }
1349
1350 EffectDescriptor *pDesc = mEffects.valueAt(index);
1351
1352 setEffectEnabled(pDesc, false);
1353
1354 if (mTotalEffectsMemory < pDesc->mDesc.memoryUsage) {
1355 ALOGW("unregisterEffect() memory %d too big for total %d",
1356 pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1357 pDesc->mDesc.memoryUsage = mTotalEffectsMemory;
1358 }
1359 mTotalEffectsMemory -= pDesc->mDesc.memoryUsage;
1360 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
1361 pDesc->mDesc.name, id, pDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1362
1363 mEffects.removeItem(id);
1364 delete pDesc;
1365
1366 return NO_ERROR;
1367}
1368
Eric Laurente0720872014-03-11 09:30:41 -07001369status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001370{
1371 ssize_t index = mEffects.indexOfKey(id);
1372 if (index < 0) {
1373 ALOGW("unregisterEffect() unknown effect ID %d", id);
1374 return INVALID_OPERATION;
1375 }
1376
1377 return setEffectEnabled(mEffects.valueAt(index), enabled);
1378}
1379
Eric Laurente0720872014-03-11 09:30:41 -07001380status_t AudioPolicyManager::setEffectEnabled(EffectDescriptor *pDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001381{
1382 if (enabled == pDesc->mEnabled) {
1383 ALOGV("setEffectEnabled(%s) effect already %s",
1384 enabled?"true":"false", enabled?"enabled":"disabled");
1385 return INVALID_OPERATION;
1386 }
1387
1388 if (enabled) {
1389 if (mTotalEffectsCpuLoad + pDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
1390 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
1391 pDesc->mDesc.name, (float)pDesc->mDesc.cpuLoad/10);
1392 return INVALID_OPERATION;
1393 }
1394 mTotalEffectsCpuLoad += pDesc->mDesc.cpuLoad;
1395 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1396 } else {
1397 if (mTotalEffectsCpuLoad < pDesc->mDesc.cpuLoad) {
1398 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
1399 pDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1400 pDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
1401 }
1402 mTotalEffectsCpuLoad -= pDesc->mDesc.cpuLoad;
1403 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1404 }
1405 pDesc->mEnabled = enabled;
1406 return NO_ERROR;
1407}
1408
Eric Laurente0720872014-03-11 09:30:41 -07001409bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001410{
1411 for (size_t i = 0; i < mEffects.size(); i++) {
1412 const EffectDescriptor * const pDesc = mEffects.valueAt(i);
1413 if (pDesc->mEnabled && (pDesc->mStrategy == STRATEGY_MEDIA) &&
1414 ((pDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
1415 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
1416 pDesc->mDesc.name, pDesc->mSession);
1417 return true;
1418 }
1419 }
1420 return false;
1421}
1422
Eric Laurente0720872014-03-11 09:30:41 -07001423bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, 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);
Eric Laurent3b73df72014-03-11 09:06:29 -07001428 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001429 return true;
1430 }
1431 }
1432 return false;
1433}
1434
Eric Laurente0720872014-03-11 09:30:41 -07001435bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001436 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001437{
1438 nsecs_t sysTime = systemTime();
1439 for (size_t i = 0; i < mOutputs.size(); i++) {
1440 const AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
1441 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001442 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001443 return true;
1444 }
1445 }
1446 return false;
1447}
1448
Eric Laurente0720872014-03-11 09:30:41 -07001449bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001450{
1451 for (size_t i = 0; i < mInputs.size(); i++) {
1452 const AudioInputDescriptor * inputDescriptor = mInputs.valueAt(i);
1453 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001454 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001455 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1456 && (inputDescriptor->mRefCount > 0)) {
1457 return true;
1458 }
1459 }
1460 return false;
1461}
1462
1463
Eric Laurente0720872014-03-11 09:30:41 -07001464status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001465{
1466 const size_t SIZE = 256;
1467 char buffer[SIZE];
1468 String8 result;
1469
1470 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1471 result.append(buffer);
1472
1473 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1474 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001475 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1476 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001477 snprintf(buffer, SIZE, " Force use for communications %d\n",
1478 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001479 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001480 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001481 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001482 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001483 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001484 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001485 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001486 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001487 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001488
Eric Laurent3a4311c2014-03-17 12:00:47 -07001489 snprintf(buffer, SIZE, " Available output devices:\n");
1490 result.append(buffer);
1491 write(fd, result.string(), result.size());
1492 DeviceDescriptor::dumpHeader(fd, 2);
1493 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
1494 mAvailableOutputDevices[i]->dump(fd, 2);
1495 }
1496 snprintf(buffer, SIZE, "\n Available input devices:\n");
1497 write(fd, buffer, strlen(buffer));
1498 DeviceDescriptor::dumpHeader(fd, 2);
1499 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
1500 mAvailableInputDevices[i]->dump(fd, 2);
1501 }
Eric Laurente552edb2014-03-10 17:42:56 -07001502
1503 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1504 write(fd, buffer, strlen(buffer));
1505 for (size_t i = 0; i < mHwModules.size(); i++) {
1506 snprintf(buffer, SIZE, "- HW Module %d:\n", i + 1);
1507 write(fd, buffer, strlen(buffer));
1508 mHwModules[i]->dump(fd);
1509 }
1510
1511 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1512 write(fd, buffer, strlen(buffer));
1513 for (size_t i = 0; i < mOutputs.size(); i++) {
1514 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1515 write(fd, buffer, strlen(buffer));
1516 mOutputs.valueAt(i)->dump(fd);
1517 }
1518
1519 snprintf(buffer, SIZE, "\nInputs dump:\n");
1520 write(fd, buffer, strlen(buffer));
1521 for (size_t i = 0; i < mInputs.size(); i++) {
1522 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1523 write(fd, buffer, strlen(buffer));
1524 mInputs.valueAt(i)->dump(fd);
1525 }
1526
1527 snprintf(buffer, SIZE, "\nStreams dump:\n");
1528 write(fd, buffer, strlen(buffer));
1529 snprintf(buffer, SIZE,
1530 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1531 write(fd, buffer, strlen(buffer));
Eric Laurent3b73df72014-03-11 09:06:29 -07001532 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07001533 snprintf(buffer, SIZE, " %02d ", i);
1534 write(fd, buffer, strlen(buffer));
1535 mStreams[i].dump(fd);
1536 }
1537
1538 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1539 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1540 write(fd, buffer, strlen(buffer));
1541
1542 snprintf(buffer, SIZE, "Registered effects:\n");
1543 write(fd, buffer, strlen(buffer));
1544 for (size_t i = 0; i < mEffects.size(); i++) {
1545 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1546 write(fd, buffer, strlen(buffer));
1547 mEffects.valueAt(i)->dump(fd);
1548 }
1549
1550
1551 return NO_ERROR;
1552}
1553
1554// This function checks for the parameters which can be offloaded.
1555// This can be enhanced depending on the capability of the DSP and policy
1556// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001557bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001558{
1559 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
1560 " BitRate=%u, duration=%lld us, has_video=%d",
1561 offloadInfo.sample_rate, offloadInfo.channel_mask,
1562 offloadInfo.format,
1563 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1564 offloadInfo.has_video);
1565
1566 // Check if offload has been disabled
1567 char propValue[PROPERTY_VALUE_MAX];
1568 if (property_get("audio.offload.disable", propValue, "0")) {
1569 if (atoi(propValue) != 0) {
1570 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1571 return false;
1572 }
1573 }
1574
1575 // Check if stream type is music, then only allow offload as of now.
1576 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1577 {
1578 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1579 return false;
1580 }
1581
1582 //TODO: enable audio offloading with video when ready
1583 if (offloadInfo.has_video)
1584 {
1585 ALOGV("isOffloadSupported: has_video == true, returning false");
1586 return false;
1587 }
1588
1589 //If duration is less than minimum value defined in property, return false
1590 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1591 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1592 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1593 return false;
1594 }
1595 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1596 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1597 return false;
1598 }
1599
1600 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1601 // creating an offloaded track and tearing it down immediately after start when audioflinger
1602 // detects there is an active non offloadable effect.
1603 // FIXME: We should check the audio session here but we do not have it in this context.
1604 // This may prevent offloading in rare situations where effects are left active by apps
1605 // in the background.
1606 if (isNonOffloadableEffectEnabled()) {
1607 return false;
1608 }
1609
1610 // See if there is a profile to support this.
1611 // AUDIO_DEVICE_NONE
1612 IOProfile *profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
1613 offloadInfo.sample_rate,
1614 offloadInfo.format,
1615 offloadInfo.channel_mask,
1616 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
1617 ALOGV("isOffloadSupported() profile %sfound", profile != NULL ? "" : "NOT ");
1618 return (profile != NULL);
1619}
1620
1621// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07001622// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07001623// ----------------------------------------------------------------------------
1624
Eric Laurent3a4311c2014-03-17 12:00:47 -07001625uint32_t AudioPolicyManager::nextUniqueId()
1626{
1627 return android_atomic_inc(&mNextUniqueId);
1628}
1629
Eric Laurente0720872014-03-11 09:30:41 -07001630AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07001631 :
1632#ifdef AUDIO_POLICY_TEST
1633 Thread(false),
1634#endif //AUDIO_POLICY_TEST
1635 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07001636 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07001637 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
1638 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07001639 mA2dpSuspended(false),
1640 mSpeakerDrcEnabled(false), mNextUniqueId(0)
Eric Laurente552edb2014-03-10 17:42:56 -07001641{
1642 mpClientInterface = clientInterface;
1643
Eric Laurent3b73df72014-03-11 09:06:29 -07001644 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
1645 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001646 }
1647
Eric Laurent3a4311c2014-03-17 12:00:47 -07001648 mDefaultOutputDevice = new DeviceDescriptor(AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07001649 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
1650 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
1651 ALOGE("could not load audio policy configuration file, setting defaults");
1652 defaultAudioPolicyConfig();
1653 }
1654 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07001655 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07001656
1657 // must be done after reading the policy
1658 initializeVolumeCurves();
1659
1660 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07001661 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
1662 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07001663 for (size_t i = 0; i < mHwModules.size(); i++) {
1664 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
1665 if (mHwModules[i]->mHandle == 0) {
1666 ALOGW("could not open HW module %s", mHwModules[i]->mName);
1667 continue;
1668 }
1669 // open all output streams needed to access attached devices
1670 // except for direct output streams that are only opened when they are actually
1671 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07001672 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07001673 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1674 {
1675 const IOProfile *outProfile = mHwModules[i]->mOutputProfiles[j];
1676
Eric Laurent3a4311c2014-03-17 12:00:47 -07001677 if (outProfile->mSupportedDevices.isEmpty()) {
1678 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
1679 continue;
1680 }
1681
1682 audio_devices_t profileTypes = outProfile->mSupportedDevices.types();
1683 if ((profileTypes & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07001684 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
1685 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001686
1687 outputDesc->mDevice = (audio_devices_t)(mDefaultOutputDevice->mType & profileTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07001688 audio_io_handle_t output = mpClientInterface->openOutput(
1689 outProfile->mModule->mHandle,
1690 &outputDesc->mDevice,
1691 &outputDesc->mSamplingRate,
1692 &outputDesc->mFormat,
1693 &outputDesc->mChannelMask,
1694 &outputDesc->mLatency,
1695 outputDesc->mFlags);
1696 if (output == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07001697 ALOGW("Cannot open output stream for device %08x on hw module %s",
1698 outputDesc->mDevice,
1699 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07001700 delete outputDesc;
1701 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07001702 for (size_t i = 0; i < outProfile->mSupportedDevices.size(); i++) {
1703 audio_devices_t type = outProfile->mSupportedDevices[i]->mType;
1704 ssize_t index =
1705 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[i]);
1706 // give a valid ID to an attached device once confirmed it is reachable
1707 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
1708 mAvailableOutputDevices[index]->mId = nextUniqueId();
1709 }
1710 }
Eric Laurente552edb2014-03-10 17:42:56 -07001711 if (mPrimaryOutput == 0 &&
1712 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1713 mPrimaryOutput = output;
1714 }
1715 addOutput(output, outputDesc);
1716 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07001717 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07001718 true);
1719 }
1720 }
1721 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07001722 // open input streams needed to access attached devices to validate
1723 // mAvailableInputDevices list
1724 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
1725 {
1726 const IOProfile *inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07001727
Eric Laurent3a4311c2014-03-17 12:00:47 -07001728 if (inProfile->mSupportedDevices.isEmpty()) {
1729 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
1730 continue;
1731 }
1732
1733 audio_devices_t profileTypes = inProfile->mSupportedDevices.types();
1734 if (profileTypes & inputDeviceTypes) {
1735 AudioInputDescriptor *inputDesc = new AudioInputDescriptor(inProfile);
1736
1737 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
1738 inputDesc->mDevice = inProfile->mSupportedDevices[0]->mType;
1739 audio_io_handle_t input = mpClientInterface->openInput(
1740 inProfile->mModule->mHandle,
1741 &inputDesc->mDevice,
1742 &inputDesc->mSamplingRate,
1743 &inputDesc->mFormat,
1744 &inputDesc->mChannelMask);
1745
1746 if (input != 0) {
1747 for (size_t i = 0; i < inProfile->mSupportedDevices.size(); i++) {
1748 audio_devices_t type = inProfile->mSupportedDevices[i]->mType;
1749 ssize_t index =
1750 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[i]);
1751 // give a valid ID to an attached device once confirmed it is reachable
1752 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
1753 mAvailableInputDevices[index]->mId = nextUniqueId();
1754 }
1755 }
1756 mpClientInterface->closeInput(input);
1757 } else {
1758 ALOGW("Cannot open input stream for device %08x on hw module %s",
1759 inputDesc->mDevice,
1760 mHwModules[i]->mName);
1761 }
1762 delete inputDesc;
1763 }
1764 }
1765 }
1766 // make sure all attached devices have been allocated a unique ID
1767 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
1768 if (mAvailableOutputDevices[i]->mId == 0) {
1769 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mType);
1770 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
1771 continue;
1772 }
1773 i++;
1774 }
1775 for (size_t i = 0; i < mAvailableInputDevices.size();) {
1776 if (mAvailableInputDevices[i]->mId == 0) {
1777 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mType);
1778 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
1779 continue;
1780 }
1781 i++;
1782 }
1783 // make sure default device is reachable
1784 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
1785 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mType);
1786 }
Eric Laurente552edb2014-03-10 17:42:56 -07001787
1788 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
1789
1790 updateDevicesAndOutputs();
1791
1792#ifdef AUDIO_POLICY_TEST
1793 if (mPrimaryOutput != 0) {
1794 AudioParameter outputCmd = AudioParameter();
1795 outputCmd.addInt(String8("set_id"), 0);
1796 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1797
1798 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
1799 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07001800 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
1801 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07001802 mTestLatencyMs = 0;
1803 mCurOutput = 0;
1804 mDirectOutput = false;
1805 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1806 mTestOutputs[i] = 0;
1807 }
1808
1809 const size_t SIZE = 256;
1810 char buffer[SIZE];
1811 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
1812 run(buffer, ANDROID_PRIORITY_AUDIO);
1813 }
1814#endif //AUDIO_POLICY_TEST
1815}
1816
Eric Laurente0720872014-03-11 09:30:41 -07001817AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07001818{
1819#ifdef AUDIO_POLICY_TEST
1820 exit();
1821#endif //AUDIO_POLICY_TEST
1822 for (size_t i = 0; i < mOutputs.size(); i++) {
1823 mpClientInterface->closeOutput(mOutputs.keyAt(i));
1824 delete mOutputs.valueAt(i);
1825 }
1826 for (size_t i = 0; i < mInputs.size(); i++) {
1827 mpClientInterface->closeInput(mInputs.keyAt(i));
1828 delete mInputs.valueAt(i);
1829 }
1830 for (size_t i = 0; i < mHwModules.size(); i++) {
1831 delete mHwModules[i];
1832 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07001833 mAvailableOutputDevices.clear();
1834 mAvailableInputDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07001835}
1836
Eric Laurente0720872014-03-11 09:30:41 -07001837status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07001838{
1839 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
1840}
1841
1842#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07001843bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07001844{
1845 ALOGV("entering threadLoop()");
1846 while (!exitPending())
1847 {
1848 String8 command;
1849 int valueInt;
1850 String8 value;
1851
1852 Mutex::Autolock _l(mLock);
1853 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
1854
1855 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
1856 AudioParameter param = AudioParameter(command);
1857
1858 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
1859 valueInt != 0) {
1860 ALOGV("Test command %s received", command.string());
1861 String8 target;
1862 if (param.get(String8("target"), target) != NO_ERROR) {
1863 target = "Manager";
1864 }
1865 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
1866 param.remove(String8("test_cmd_policy_output"));
1867 mCurOutput = valueInt;
1868 }
1869 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
1870 param.remove(String8("test_cmd_policy_direct"));
1871 if (value == "false") {
1872 mDirectOutput = false;
1873 } else if (value == "true") {
1874 mDirectOutput = true;
1875 }
1876 }
1877 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
1878 param.remove(String8("test_cmd_policy_input"));
1879 mTestInput = valueInt;
1880 }
1881
1882 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
1883 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07001884 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07001885 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07001886 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07001887 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07001888 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07001889 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07001890 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07001891 }
Eric Laurent3b73df72014-03-11 09:06:29 -07001892 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07001893 if (target == "Manager") {
1894 mTestFormat = format;
1895 } else if (mTestOutputs[mCurOutput] != 0) {
1896 AudioParameter outputParam = AudioParameter();
1897 outputParam.addInt(String8("format"), format);
1898 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1899 }
1900 }
1901 }
1902 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
1903 param.remove(String8("test_cmd_policy_channels"));
1904 int channels = 0;
1905
1906 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07001907 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07001908 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07001909 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07001910 }
1911 if (channels != 0) {
1912 if (target == "Manager") {
1913 mTestChannels = channels;
1914 } else if (mTestOutputs[mCurOutput] != 0) {
1915 AudioParameter outputParam = AudioParameter();
1916 outputParam.addInt(String8("channels"), channels);
1917 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1918 }
1919 }
1920 }
1921 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
1922 param.remove(String8("test_cmd_policy_sampleRate"));
1923 if (valueInt >= 0 && valueInt <= 96000) {
1924 int samplingRate = valueInt;
1925 if (target == "Manager") {
1926 mTestSamplingRate = samplingRate;
1927 } else if (mTestOutputs[mCurOutput] != 0) {
1928 AudioParameter outputParam = AudioParameter();
1929 outputParam.addInt(String8("sampling_rate"), samplingRate);
1930 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
1931 }
1932 }
1933 }
1934
1935 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
1936 param.remove(String8("test_cmd_policy_reopen"));
1937
1938 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
1939 mpClientInterface->closeOutput(mPrimaryOutput);
1940
1941 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
1942
1943 delete mOutputs.valueFor(mPrimaryOutput);
1944 mOutputs.removeItem(mPrimaryOutput);
1945
1946 AudioOutputDescriptor *outputDesc = new AudioOutputDescriptor(NULL);
1947 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
1948 mPrimaryOutput = mpClientInterface->openOutput(moduleHandle,
1949 &outputDesc->mDevice,
1950 &outputDesc->mSamplingRate,
1951 &outputDesc->mFormat,
1952 &outputDesc->mChannelMask,
1953 &outputDesc->mLatency,
1954 outputDesc->mFlags);
1955 if (mPrimaryOutput == 0) {
1956 ALOGE("Failed to reopen hardware output stream, samplingRate: %d, format %d, channels %d",
1957 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
1958 } else {
1959 AudioParameter outputCmd = AudioParameter();
1960 outputCmd.addInt(String8("set_id"), 0);
1961 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
1962 addOutput(mPrimaryOutput, outputDesc);
1963 }
1964 }
1965
1966
1967 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
1968 }
1969 }
1970 return false;
1971}
1972
Eric Laurente0720872014-03-11 09:30:41 -07001973void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07001974{
1975 {
1976 AutoMutex _l(mLock);
1977 requestExit();
1978 mWaitWorkCV.signal();
1979 }
1980 requestExitAndWait();
1981}
1982
Eric Laurente0720872014-03-11 09:30:41 -07001983int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001984{
1985 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
1986 if (output == mTestOutputs[i]) return i;
1987 }
1988 return 0;
1989}
1990#endif //AUDIO_POLICY_TEST
1991
1992// ---
1993
Eric Laurente0720872014-03-11 09:30:41 -07001994void AudioPolicyManager::addOutput(audio_io_handle_t id, AudioOutputDescriptor *outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07001995{
1996 outputDesc->mId = id;
1997 mOutputs.add(id, outputDesc);
1998}
1999
2000
Eric Laurent3a4311c2014-03-17 12:00:47 -07002001String8 AudioPolicyManager::addressToParameter(audio_devices_t device, const String8 address)
2002{
2003 if (device & AUDIO_DEVICE_OUT_ALL_A2DP) {
2004 return String8("a2dp_sink_address=")+address;
2005 }
2006 return address;
2007}
2008
Eric Laurente0720872014-03-11 09:30:41 -07002009status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002010 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002011 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002012 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002013{
2014 AudioOutputDescriptor *desc;
2015
Eric Laurent3b73df72014-03-11 09:06:29 -07002016 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002017 // first list already open outputs that can be routed to this device
2018 for (size_t i = 0; i < mOutputs.size(); i++) {
2019 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002020 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002021 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2022 outputs.add(mOutputs.keyAt(i));
2023 }
2024 }
2025 // then look for output profiles that can be routed to this device
2026 SortedVector<IOProfile *> profiles;
2027 for (size_t i = 0; i < mHwModules.size(); i++)
2028 {
2029 if (mHwModules[i]->mHandle == 0) {
2030 continue;
2031 }
2032 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2033 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002034 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurente552edb2014-03-10 17:42:56 -07002035 ALOGV("checkOutputsForDevice(): adding profile %d from module %d", j, i);
2036 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2037 }
2038 }
2039 }
2040
2041 if (profiles.isEmpty() && outputs.isEmpty()) {
2042 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2043 return BAD_VALUE;
2044 }
2045
2046 // open outputs for matching profiles if needed. Direct outputs are also opened to
2047 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2048 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
2049 IOProfile *profile = profiles[profile_index];
2050
2051 // nothing to do if one output is already opened for this profile
2052 size_t j;
2053 for (j = 0; j < mOutputs.size(); j++) {
2054 desc = mOutputs.valueAt(j);
2055 if (!desc->isDuplicated() && desc->mProfile == profile) {
2056 break;
2057 }
2058 }
2059 if (j != mOutputs.size()) {
2060 continue;
2061 }
2062
Eric Laurent3a4311c2014-03-17 12:00:47 -07002063 ALOGV("opening output for device %08x with params %s", device, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -07002064 desc = new AudioOutputDescriptor(profile);
2065 desc->mDevice = device;
2066 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
2067 offloadInfo.sample_rate = desc->mSamplingRate;
2068 offloadInfo.format = desc->mFormat;
2069 offloadInfo.channel_mask = desc->mChannelMask;
2070
2071 audio_io_handle_t output = mpClientInterface->openOutput(profile->mModule->mHandle,
2072 &desc->mDevice,
2073 &desc->mSamplingRate,
2074 &desc->mFormat,
2075 &desc->mChannelMask,
2076 &desc->mLatency,
2077 desc->mFlags,
2078 &offloadInfo);
2079 if (output != 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002080 if (!address.isEmpty()) {
2081 mpClientInterface->setParameters(output, addressToParameter(device, address));
Eric Laurente552edb2014-03-10 17:42:56 -07002082 }
2083
2084 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2085 String8 reply;
2086 char *value;
2087 if (profile->mSamplingRates[0] == 0) {
2088 reply = mpClientInterface->getParameters(output,
2089 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
2090 ALOGV("checkOutputsForDevice() direct output sup sampling rates %s",
2091 reply.string());
2092 value = strpbrk((char *)reply.string(), "=");
2093 if (value != NULL) {
2094 loadSamplingRates(value + 1, profile);
2095 }
2096 }
2097 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2098 reply = mpClientInterface->getParameters(output,
2099 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
2100 ALOGV("checkOutputsForDevice() direct output sup formats %s",
2101 reply.string());
2102 value = strpbrk((char *)reply.string(), "=");
2103 if (value != NULL) {
2104 loadFormats(value + 1, profile);
2105 }
2106 }
2107 if (profile->mChannelMasks[0] == 0) {
2108 reply = mpClientInterface->getParameters(output,
2109 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
2110 ALOGV("checkOutputsForDevice() direct output sup channel masks %s",
2111 reply.string());
2112 value = strpbrk((char *)reply.string(), "=");
2113 if (value != NULL) {
2114 loadOutChannels(value + 1, profile);
2115 }
2116 }
2117 if (((profile->mSamplingRates[0] == 0) &&
2118 (profile->mSamplingRates.size() < 2)) ||
2119 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2120 (profile->mFormats.size() < 2)) ||
2121 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2122 (profile->mChannelMasks.size() < 2))) {
2123 ALOGW("checkOutputsForDevice() direct output missing param");
2124 mpClientInterface->closeOutput(output);
2125 output = 0;
2126 } else {
2127 addOutput(output, desc);
2128 }
2129 } else {
2130 audio_io_handle_t duplicatedOutput = 0;
2131 // add output descriptor
2132 addOutput(output, desc);
2133 // set initial stream volume for device
2134 applyStreamVolumes(output, device, 0, true);
2135
2136 //TODO: configure audio effect output stage here
2137
2138 // open a duplicating output thread for the new output and the primary output
2139 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2140 mPrimaryOutput);
2141 if (duplicatedOutput != 0) {
2142 // add duplicated output descriptor
2143 AudioOutputDescriptor *dupOutputDesc = new AudioOutputDescriptor(NULL);
2144 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2145 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2146 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2147 dupOutputDesc->mFormat = desc->mFormat;
2148 dupOutputDesc->mChannelMask = desc->mChannelMask;
2149 dupOutputDesc->mLatency = desc->mLatency;
2150 addOutput(duplicatedOutput, dupOutputDesc);
2151 applyStreamVolumes(duplicatedOutput, device, 0, true);
2152 } else {
2153 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2154 mPrimaryOutput, output);
2155 mpClientInterface->closeOutput(output);
2156 mOutputs.removeItem(output);
2157 output = 0;
2158 }
2159 }
2160 }
2161 if (output == 0) {
2162 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
2163 delete desc;
2164 profiles.removeAt(profile_index);
2165 profile_index--;
2166 } else {
2167 outputs.add(output);
2168 ALOGV("checkOutputsForDevice(): adding output %d", output);
2169 }
2170 }
2171
2172 if (profiles.isEmpty()) {
2173 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2174 return BAD_VALUE;
2175 }
2176 } else {
2177 // check if one opened output is not needed any more after disconnecting one device
2178 for (size_t i = 0; i < mOutputs.size(); i++) {
2179 desc = mOutputs.valueAt(i);
2180 if (!desc->isDuplicated() &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07002181 !(desc->mProfile->mSupportedDevices.types() &
2182 mAvailableOutputDevices.types())) {
Eric Laurente552edb2014-03-10 17:42:56 -07002183 ALOGV("checkOutputsForDevice(): disconnecting adding output %d", mOutputs.keyAt(i));
2184 outputs.add(mOutputs.keyAt(i));
2185 }
2186 }
2187 for (size_t i = 0; i < mHwModules.size(); i++)
2188 {
2189 if (mHwModules[i]->mHandle == 0) {
2190 continue;
2191 }
2192 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2193 {
2194 IOProfile *profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002195 if ((profile->mSupportedDevices.types() & device) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002196 (profile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT)) {
2197 ALOGV("checkOutputsForDevice(): clearing direct output profile %d on module %d",
2198 j, i);
2199 if (profile->mSamplingRates[0] == 0) {
2200 profile->mSamplingRates.clear();
2201 profile->mSamplingRates.add(0);
2202 }
2203 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2204 profile->mFormats.clear();
2205 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2206 }
2207 if (profile->mChannelMasks[0] == 0) {
2208 profile->mChannelMasks.clear();
2209 profile->mChannelMasks.add(0);
2210 }
2211 }
2212 }
2213 }
2214 }
2215 return NO_ERROR;
2216}
2217
Eric Laurente0720872014-03-11 09:30:41 -07002218void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002219{
2220 ALOGV("closeOutput(%d)", output);
2221
2222 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2223 if (outputDesc == NULL) {
2224 ALOGW("closeOutput() unknown output %d", output);
2225 return;
2226 }
2227
2228 // look for duplicated outputs connected to the output being removed.
2229 for (size_t i = 0; i < mOutputs.size(); i++) {
2230 AudioOutputDescriptor *dupOutputDesc = mOutputs.valueAt(i);
2231 if (dupOutputDesc->isDuplicated() &&
2232 (dupOutputDesc->mOutput1 == outputDesc ||
2233 dupOutputDesc->mOutput2 == outputDesc)) {
2234 AudioOutputDescriptor *outputDesc2;
2235 if (dupOutputDesc->mOutput1 == outputDesc) {
2236 outputDesc2 = dupOutputDesc->mOutput2;
2237 } else {
2238 outputDesc2 = dupOutputDesc->mOutput1;
2239 }
2240 // As all active tracks on duplicated output will be deleted,
2241 // and as they were also referenced on the other output, the reference
2242 // count for their stream type must be adjusted accordingly on
2243 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07002244 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07002245 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07002246 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07002247 }
2248 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
2249 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
2250
2251 mpClientInterface->closeOutput(duplicatedOutput);
2252 delete mOutputs.valueFor(duplicatedOutput);
2253 mOutputs.removeItem(duplicatedOutput);
2254 }
2255 }
2256
2257 AudioParameter param;
2258 param.add(String8("closing"), String8("true"));
2259 mpClientInterface->setParameters(output, param.toString());
2260
2261 mpClientInterface->closeOutput(output);
2262 delete outputDesc;
2263 mOutputs.removeItem(output);
2264 mPreviousOutputs = mOutputs;
2265}
2266
Eric Laurente0720872014-03-11 09:30:41 -07002267SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07002268 DefaultKeyedVector<audio_io_handle_t, AudioOutputDescriptor *> openOutputs)
2269{
2270 SortedVector<audio_io_handle_t> outputs;
2271
2272 ALOGVV("getOutputsForDevice() device %04x", device);
2273 for (size_t i = 0; i < openOutputs.size(); i++) {
2274 ALOGVV("output %d isDuplicated=%d device=%04x",
2275 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
2276 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
2277 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
2278 outputs.add(openOutputs.keyAt(i));
2279 }
2280 }
2281 return outputs;
2282}
2283
Eric Laurente0720872014-03-11 09:30:41 -07002284bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07002285 SortedVector<audio_io_handle_t>& outputs2)
2286{
2287 if (outputs1.size() != outputs2.size()) {
2288 return false;
2289 }
2290 for (size_t i = 0; i < outputs1.size(); i++) {
2291 if (outputs1[i] != outputs2[i]) {
2292 return false;
2293 }
2294 }
2295 return true;
2296}
2297
Eric Laurente0720872014-03-11 09:30:41 -07002298void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07002299{
2300 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
2301 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
2302 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
2303 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
2304
2305 if (!vectorsEqual(srcOutputs,dstOutputs)) {
2306 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
2307 strategy, srcOutputs[0], dstOutputs[0]);
2308 // mute strategy while moving tracks from one output to another
2309 for (size_t i = 0; i < srcOutputs.size(); i++) {
2310 AudioOutputDescriptor *desc = mOutputs.valueFor(srcOutputs[i]);
2311 if (desc->isStrategyActive(strategy)) {
2312 setStrategyMute(strategy, true, srcOutputs[i]);
2313 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
2314 }
2315 }
2316
2317 // Move effects associated to this strategy from previous output to new output
2318 if (strategy == STRATEGY_MEDIA) {
2319 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
2320 SortedVector<audio_io_handle_t> moved;
2321 for (size_t i = 0; i < mEffects.size(); i++) {
2322 EffectDescriptor *desc = mEffects.valueAt(i);
2323 if (desc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
2324 desc->mIo != fxOutput) {
2325 if (moved.indexOf(desc->mIo) < 0) {
2326 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
2327 mEffects.keyAt(i), fxOutput);
2328 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, desc->mIo,
2329 fxOutput);
2330 moved.add(desc->mIo);
2331 }
2332 desc->mIo = fxOutput;
2333 }
2334 }
2335 }
2336 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07002337 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
2338 if (getStrategy((audio_stream_type_t)i) == strategy) {
2339 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07002340 }
2341 }
2342 }
2343}
2344
Eric Laurente0720872014-03-11 09:30:41 -07002345void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07002346{
2347 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
2348 checkOutputForStrategy(STRATEGY_PHONE);
2349 checkOutputForStrategy(STRATEGY_SONIFICATION);
2350 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2351 checkOutputForStrategy(STRATEGY_MEDIA);
2352 checkOutputForStrategy(STRATEGY_DTMF);
2353}
2354
Eric Laurente0720872014-03-11 09:30:41 -07002355audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07002356{
2357 if (!mHasA2dp) {
2358 return 0;
2359 }
2360
2361 for (size_t i = 0; i < mOutputs.size(); i++) {
2362 AudioOutputDescriptor *outputDesc = mOutputs.valueAt(i);
2363 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
2364 return mOutputs.keyAt(i);
2365 }
2366 }
2367
2368 return 0;
2369}
2370
Eric Laurente0720872014-03-11 09:30:41 -07002371void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07002372{
2373 if (!mHasA2dp) {
2374 return;
2375 }
2376 audio_io_handle_t a2dpOutput = getA2dpOutput();
2377 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002378 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07002379 return;
2380 }
2381
Eric Laurent3a4311c2014-03-17 12:00:47 -07002382 bool isScoConnected =
2383 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07002384 // suspend A2DP output if:
2385 // (NOT already suspended) &&
2386 // ((SCO device is connected &&
2387 // (forced usage for communication || for record is SCO))) ||
2388 // (phone state is ringing || in call)
2389 //
2390 // restore A2DP output if:
2391 // (Already suspended) &&
2392 // ((SCO device is NOT connected ||
2393 // (forced usage NOT for communication && NOT for record is SCO))) &&
2394 // (phone state is NOT ringing && NOT in call)
2395 //
2396 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002397 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07002398 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
2399 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
2400 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
2401 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002402
2403 mpClientInterface->restoreOutput(a2dpOutput);
2404 mA2dpSuspended = false;
2405 }
2406 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002407 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07002408 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
2409 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
2410 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
2411 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07002412
2413 mpClientInterface->suspendOutput(a2dpOutput);
2414 mA2dpSuspended = true;
2415 }
2416 }
2417}
2418
Eric Laurente0720872014-03-11 09:30:41 -07002419audio_devices_t AudioPolicyManager::getNewDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07002420{
2421 audio_devices_t device = AUDIO_DEVICE_NONE;
2422
2423 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2424 // check the following by order of priority to request a routing change if necessary:
2425 // 1: the strategy enforced audible is active on the output:
2426 // use device for strategy enforced audible
2427 // 2: we are in call or the strategy phone is active on the output:
2428 // use device for strategy phone
2429 // 3: the strategy sonification is active on the output:
2430 // use device for strategy sonification
2431 // 4: the strategy "respectful" sonification is active on the output:
2432 // use device for strategy "respectful" sonification
2433 // 5: the strategy media is active on the output:
2434 // use device for strategy media
2435 // 6: the strategy DTMF is active on the output:
2436 // use device for strategy DTMF
2437 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
2438 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
2439 } else if (isInCall() ||
2440 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
2441 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
2442 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
2443 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
2444 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
2445 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
2446 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
2447 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
2448 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
2449 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
2450 }
2451
2452 ALOGV("getNewDevice() selected device %x", device);
2453 return device;
2454}
2455
Eric Laurente0720872014-03-11 09:30:41 -07002456uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07002457 return (uint32_t)getStrategy(stream);
2458}
2459
Eric Laurente0720872014-03-11 09:30:41 -07002460audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07002461 audio_devices_t devices;
2462 // By checking the range of stream before calling getStrategy, we avoid
2463 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
2464 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07002465 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -07002466 devices = AUDIO_DEVICE_NONE;
2467 } else {
Eric Laurente0720872014-03-11 09:30:41 -07002468 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07002469 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
2470 }
2471 return devices;
2472}
2473
Eric Laurente0720872014-03-11 09:30:41 -07002474AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07002475 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07002476 // stream to strategy mapping
2477 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07002478 case AUDIO_STREAM_VOICE_CALL:
2479 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07002480 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07002481 case AUDIO_STREAM_RING:
2482 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07002483 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07002484 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07002485 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07002486 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07002487 return STRATEGY_DTMF;
2488 default:
2489 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07002490 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07002491 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
2492 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07002493 case AUDIO_STREAM_TTS:
2494 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07002495 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07002496 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07002497 return STRATEGY_ENFORCED_AUDIBLE;
2498 }
2499}
2500
Eric Laurente0720872014-03-11 09:30:41 -07002501void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07002502 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07002503 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07002504 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
2505 updateDevicesAndOutputs();
2506 break;
2507 default:
2508 break;
2509 }
2510}
2511
Eric Laurente0720872014-03-11 09:30:41 -07002512audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07002513 bool fromCache)
2514{
2515 uint32_t device = AUDIO_DEVICE_NONE;
2516
2517 if (fromCache) {
2518 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
2519 strategy, mDeviceForStrategy[strategy]);
2520 return mDeviceForStrategy[strategy];
2521 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002522 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07002523 switch (strategy) {
2524
2525 case STRATEGY_SONIFICATION_RESPECTFUL:
2526 if (isInCall()) {
2527 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07002528 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07002529 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
2530 // while media is playing on a remote device, use the the sonification behavior.
2531 // Note that we test this usecase before testing if media is playing because
2532 // the isStreamActive() method only informs about the activity of a stream, not
2533 // if it's for local playback. Note also that we use the same delay between both tests
2534 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07002535 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002536 // while media is playing (or has recently played), use the same device
2537 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2538 } else {
2539 // when media is not playing anymore, fall back on the sonification behavior
2540 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
2541 }
2542
2543 break;
2544
2545 case STRATEGY_DTMF:
2546 if (!isInCall()) {
2547 // when off call, DTMF strategy follows the same rules as MEDIA strategy
2548 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
2549 break;
2550 }
2551 // when in call, DTMF and PHONE strategies follow the same rules
2552 // FALL THROUGH
2553
2554 case STRATEGY_PHONE:
2555 // for phone strategy, we first consider the forced use and then the available devices by order
2556 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07002557 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
2558 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07002559 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002560 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002561 if (device) break;
2562 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002563 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07002564 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002565 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07002566 if (device) break;
2567 // if SCO device is requested but no SCO device is available, fall back to default case
2568 // FALL THROUGH
2569
2570 default: // FORCE_NONE
2571 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07002572 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07002573 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002574 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002575 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07002576 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002577 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07002578 if (device) break;
2579 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002580 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002581 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002582 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07002583 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07002584 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002585 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07002586 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002587 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07002588 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002589 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07002590 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002591 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07002592 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002593 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07002594 if (device) break;
2595 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002596 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07002597 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002598 device = mDefaultOutputDevice->mType;
Eric Laurente552edb2014-03-10 17:42:56 -07002599 if (device == AUDIO_DEVICE_NONE) {
2600 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
2601 }
2602 break;
2603
Eric Laurent3b73df72014-03-11 09:06:29 -07002604 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07002605 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
2606 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07002607 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07002608 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002609 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002610 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07002611 if (device) break;
2612 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002613 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002614 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07002615 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002616 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07002617 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002618 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07002619 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002620 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07002621 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002622 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07002623 if (device) break;
2624 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002625 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07002626 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002627 device = mDefaultOutputDevice->mType;
Eric Laurente552edb2014-03-10 17:42:56 -07002628 if (device == AUDIO_DEVICE_NONE) {
2629 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
2630 }
2631 break;
2632 }
2633 break;
2634
2635 case STRATEGY_SONIFICATION:
2636
2637 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
2638 // handleIncallSonification().
2639 if (isInCall()) {
2640 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
2641 break;
2642 }
2643 // FALL THROUGH
2644
2645 case STRATEGY_ENFORCED_AUDIBLE:
2646 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
2647 // except:
2648 // - when in call where it doesn't default to STRATEGY_PHONE behavior
2649 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
2650
2651 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07002652 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002653 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07002654 if (device == AUDIO_DEVICE_NONE) {
2655 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
2656 }
2657 }
2658 // The second device used for sonification is the same as the device used by media strategy
2659 // FALL THROUGH
2660
2661 case STRATEGY_MEDIA: {
2662 uint32_t device2 = AUDIO_DEVICE_NONE;
2663 if (strategy != STRATEGY_SONIFICATION) {
2664 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07002665 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07002666 }
2667 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07002668 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002669 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002670 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07002671 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002672 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07002673 }
2674 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002675 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07002676 }
2677 }
2678 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002679 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002680 }
2681 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002682 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07002683 }
2684 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002685 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07002686 }
2687 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002688 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07002689 }
2690 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002691 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07002692 }
2693 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
2694 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07002695 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07002696 }
2697 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07002698 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002699 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07002700 }
2701 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002702 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07002703 }
2704
2705 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
2706 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
2707 device |= device2;
2708 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002709 device = mDefaultOutputDevice->mType;
Eric Laurente552edb2014-03-10 17:42:56 -07002710 if (device == AUDIO_DEVICE_NONE) {
2711 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
2712 }
2713 } break;
2714
2715 default:
2716 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
2717 break;
2718 }
2719
2720 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
2721 return device;
2722}
2723
Eric Laurente0720872014-03-11 09:30:41 -07002724void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07002725{
2726 for (int i = 0; i < NUM_STRATEGIES; i++) {
2727 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2728 }
2729 mPreviousOutputs = mOutputs;
2730}
2731
Eric Laurente0720872014-03-11 09:30:41 -07002732uint32_t AudioPolicyManager::checkDeviceMuteStrategies(AudioOutputDescriptor *outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07002733 audio_devices_t prevDevice,
2734 uint32_t delayMs)
2735{
2736 // mute/unmute strategies using an incompatible device combination
2737 // if muting, wait for the audio in pcm buffer to be drained before proceeding
2738 // if unmuting, unmute only after the specified delay
2739 if (outputDesc->isDuplicated()) {
2740 return 0;
2741 }
2742
2743 uint32_t muteWaitMs = 0;
2744 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07002745 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07002746 // temporary mute output if device selection changes to avoid volume bursts due to
2747 // different per device volumes
2748 bool tempMute = outputDesc->isActive() && (device != prevDevice);
2749
2750 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
2751 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
2752 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
2753 bool doMute = false;
2754
2755 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
2756 doMute = true;
2757 outputDesc->mStrategyMutedByDevice[i] = true;
2758 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
2759 doMute = true;
2760 outputDesc->mStrategyMutedByDevice[i] = false;
2761 }
2762 if (doMute || tempMute) {
2763 for (size_t j = 0; j < mOutputs.size(); j++) {
2764 AudioOutputDescriptor *desc = mOutputs.valueAt(j);
2765 // skip output if it does not share any device with current output
2766 if ((desc->supportedDevices() & outputDesc->supportedDevices())
2767 == AUDIO_DEVICE_NONE) {
2768 continue;
2769 }
2770 audio_io_handle_t curOutput = mOutputs.keyAt(j);
2771 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
2772 mute ? "muting" : "unmuting", i, curDevice, curOutput);
2773 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
2774 if (desc->isStrategyActive((routing_strategy)i)) {
2775 // do tempMute only for current output
2776 if (tempMute && (desc == outputDesc)) {
2777 setStrategyMute((routing_strategy)i, true, curOutput);
2778 setStrategyMute((routing_strategy)i, false, curOutput,
2779 desc->latency() * 2, device);
2780 }
2781 if ((tempMute && (desc == outputDesc)) || mute) {
2782 if (muteWaitMs < desc->latency()) {
2783 muteWaitMs = desc->latency();
2784 }
2785 }
2786 }
2787 }
2788 }
2789 }
2790
2791 // FIXME: should not need to double latency if volume could be applied immediately by the
2792 // audioflinger mixer. We must account for the delay between now and the next time
2793 // the audioflinger thread for this output will process a buffer (which corresponds to
2794 // one buffer size, usually 1/2 or 1/4 of the latency).
2795 muteWaitMs *= 2;
2796 // wait for the PCM output buffers to empty before proceeding with the rest of the command
2797 if (muteWaitMs > delayMs) {
2798 muteWaitMs -= delayMs;
2799 usleep(muteWaitMs * 1000);
2800 return muteWaitMs;
2801 }
2802 return 0;
2803}
2804
Eric Laurente0720872014-03-11 09:30:41 -07002805uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07002806 audio_devices_t device,
2807 bool force,
2808 int delayMs)
2809{
2810 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
2811 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
2812 AudioParameter param;
2813 uint32_t muteWaitMs;
2814
2815 if (outputDesc->isDuplicated()) {
2816 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mId, device, force, delayMs);
2817 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mId, device, force, delayMs);
2818 return muteWaitMs;
2819 }
2820 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
2821 // output profile
2822 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07002823 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002824 return 0;
2825 }
2826
2827 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07002828 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07002829
2830 audio_devices_t prevDevice = outputDesc->mDevice;
2831
2832 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
2833
2834 if (device != AUDIO_DEVICE_NONE) {
2835 outputDesc->mDevice = device;
2836 }
2837 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
2838
2839 // Do not change the routing if:
2840 // - the requested device is AUDIO_DEVICE_NONE
2841 // - the requested device is the same as current device and force is not specified.
2842 // Doing this check here allows the caller to call setOutputDevice() without conditions
2843 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
2844 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
2845 return muteWaitMs;
2846 }
2847
2848 ALOGV("setOutputDevice() changing device");
2849 // do the routing
2850 param.addInt(String8(AudioParameter::keyRouting), (int)device);
2851 mpClientInterface->setParameters(output, param.toString(), delayMs);
2852
2853 // update stream volumes according to new device
2854 applyStreamVolumes(output, device, delayMs);
2855
2856 return muteWaitMs;
2857}
2858
Eric Laurente0720872014-03-11 09:30:41 -07002859AudioPolicyManager::IOProfile *AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07002860 uint32_t samplingRate,
2861 audio_format_t format,
2862 audio_channel_mask_t channelMask)
2863{
2864 // Choose an input profile based on the requested capture parameters: select the first available
2865 // profile supporting all requested parameters.
2866
2867 for (size_t i = 0; i < mHwModules.size(); i++)
2868 {
2869 if (mHwModules[i]->mHandle == 0) {
2870 continue;
2871 }
2872 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2873 {
2874 IOProfile *profile = mHwModules[i]->mInputProfiles[j];
2875 if (profile->isCompatibleProfile(device, samplingRate, format,
2876 channelMask, AUDIO_OUTPUT_FLAG_NONE)) {
2877 return profile;
2878 }
2879 }
2880 }
2881 return NULL;
2882}
2883
Eric Laurente0720872014-03-11 09:30:41 -07002884audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07002885{
2886 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002887 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
2888 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002889 switch (inputSource) {
2890 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07002891 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07002892 device = AUDIO_DEVICE_IN_VOICE_CALL;
2893 break;
2894 }
2895 // FALL THROUGH
2896
2897 case AUDIO_SOURCE_DEFAULT:
2898 case AUDIO_SOURCE_MIC:
2899 case AUDIO_SOURCE_VOICE_RECOGNITION:
2900 case AUDIO_SOURCE_HOTWORD:
2901 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07002902 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07002903 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07002904 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002905 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07002906 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002907 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07002908 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2909 }
2910 break;
2911 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07002912 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07002913 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002914 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07002915 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
2916 }
2917 break;
2918 case AUDIO_SOURCE_VOICE_DOWNLINK:
2919 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07002920 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07002921 device = AUDIO_DEVICE_IN_VOICE_CALL;
2922 }
2923 break;
2924 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07002925 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07002926 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
2927 }
2928 break;
2929 default:
2930 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
2931 break;
2932 }
2933 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
2934 return device;
2935}
2936
Eric Laurente0720872014-03-11 09:30:41 -07002937bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002938{
2939 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
2940 device &= ~AUDIO_DEVICE_BIT_IN;
2941 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
2942 return true;
2943 }
2944 return false;
2945}
2946
Eric Laurente0720872014-03-11 09:30:41 -07002947audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07002948{
2949 for (size_t i = 0; i < mInputs.size(); i++) {
2950 const AudioInputDescriptor * input_descriptor = mInputs.valueAt(i);
2951 if ((input_descriptor->mRefCount > 0)
2952 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
2953 return mInputs.keyAt(i);
2954 }
2955 }
2956 return 0;
2957}
2958
2959
Eric Laurente0720872014-03-11 09:30:41 -07002960audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002961{
2962 if (device == AUDIO_DEVICE_NONE) {
2963 // this happens when forcing a route update and no track is active on an output.
2964 // In this case the returned category is not important.
2965 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07002966 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07002967 // Multiple device selection is either:
2968 // - speaker + one other device: give priority to speaker in this case.
2969 // - one A2DP device + another device: happens with duplicated output. In this case
2970 // retain the device on the A2DP output as the other must not correspond to an active
2971 // selection if not the speaker.
2972 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
2973 device = AUDIO_DEVICE_OUT_SPEAKER;
2974 } else {
2975 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
2976 }
2977 }
2978
Eric Laurent3b73df72014-03-11 09:06:29 -07002979 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07002980 "getDeviceForVolume() invalid device combination: %08x",
2981 device);
2982
2983 return device;
2984}
2985
Eric Laurente0720872014-03-11 09:30:41 -07002986AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002987{
2988 switch(getDeviceForVolume(device)) {
2989 case AUDIO_DEVICE_OUT_EARPIECE:
2990 return DEVICE_CATEGORY_EARPIECE;
2991 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
2992 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
2993 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
2994 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
2995 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
2996 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
2997 return DEVICE_CATEGORY_HEADSET;
2998 case AUDIO_DEVICE_OUT_SPEAKER:
2999 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
3000 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
3001 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
3002 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
3003 case AUDIO_DEVICE_OUT_USB_DEVICE:
3004 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
3005 default:
3006 return DEVICE_CATEGORY_SPEAKER;
3007 }
3008}
3009
Eric Laurente0720872014-03-11 09:30:41 -07003010float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003011 int indexInUi)
3012{
3013 device_category deviceCategory = getDeviceCategory(device);
3014 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
3015
3016 // the volume index in the UI is relative to the min and max volume indices for this stream type
3017 int nbSteps = 1 + curve[VOLMAX].mIndex -
3018 curve[VOLMIN].mIndex;
3019 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
3020 (streamDesc.mIndexMax - streamDesc.mIndexMin);
3021
3022 // find what part of the curve this index volume belongs to, or if it's out of bounds
3023 int segment = 0;
3024 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
3025 return 0.0f;
3026 } else if (volIdx < curve[VOLKNEE1].mIndex) {
3027 segment = 0;
3028 } else if (volIdx < curve[VOLKNEE2].mIndex) {
3029 segment = 1;
3030 } else if (volIdx <= curve[VOLMAX].mIndex) {
3031 segment = 2;
3032 } else { // out of bounds
3033 return 1.0f;
3034 }
3035
3036 // linear interpolation in the attenuation table in dB
3037 float decibels = curve[segment].mDBAttenuation +
3038 ((float)(volIdx - curve[segment].mIndex)) *
3039 ( (curve[segment+1].mDBAttenuation -
3040 curve[segment].mDBAttenuation) /
3041 ((float)(curve[segment+1].mIndex -
3042 curve[segment].mIndex)) );
3043
3044 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
3045
3046 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
3047 curve[segment].mIndex, volIdx,
3048 curve[segment+1].mIndex,
3049 curve[segment].mDBAttenuation,
3050 decibels,
3051 curve[segment+1].mDBAttenuation,
3052 amplification);
3053
3054 return amplification;
3055}
3056
Eric Laurente0720872014-03-11 09:30:41 -07003057const AudioPolicyManager::VolumeCurvePoint
3058 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003059 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
3060};
3061
Eric Laurente0720872014-03-11 09:30:41 -07003062const AudioPolicyManager::VolumeCurvePoint
3063 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003064 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
3065};
3066
Eric Laurente0720872014-03-11 09:30:41 -07003067const AudioPolicyManager::VolumeCurvePoint
3068 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003069 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
3070};
3071
Eric Laurente0720872014-03-11 09:30:41 -07003072const AudioPolicyManager::VolumeCurvePoint
3073 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003074 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
3075};
3076
Eric Laurente0720872014-03-11 09:30:41 -07003077const AudioPolicyManager::VolumeCurvePoint
3078 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003079 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
3080};
3081
3082// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
3083// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
3084// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
3085// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
3086
Eric Laurente0720872014-03-11 09:30:41 -07003087const AudioPolicyManager::VolumeCurvePoint
3088 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003089 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
3090};
3091
Eric Laurente0720872014-03-11 09:30:41 -07003092const AudioPolicyManager::VolumeCurvePoint
3093 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003094 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
3095};
3096
Eric Laurente0720872014-03-11 09:30:41 -07003097const AudioPolicyManager::VolumeCurvePoint
3098 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003099 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
3100};
3101
Eric Laurente0720872014-03-11 09:30:41 -07003102const AudioPolicyManager::VolumeCurvePoint
3103 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003104 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
3105};
3106
Eric Laurente0720872014-03-11 09:30:41 -07003107const AudioPolicyManager::VolumeCurvePoint
3108 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003109 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
3110};
3111
Eric Laurente0720872014-03-11 09:30:41 -07003112const AudioPolicyManager::VolumeCurvePoint
3113 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
3114 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07003115 { // AUDIO_STREAM_VOICE_CALL
3116 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
3117 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3118 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
3119 },
3120 { // AUDIO_STREAM_SYSTEM
3121 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3122 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3123 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
3124 },
3125 { // AUDIO_STREAM_RING
3126 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3127 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3128 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3129 },
3130 { // AUDIO_STREAM_MUSIC
3131 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
3132 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3133 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
3134 },
3135 { // AUDIO_STREAM_ALARM
3136 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3137 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3138 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3139 },
3140 { // AUDIO_STREAM_NOTIFICATION
3141 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
3142 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3143 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
3144 },
3145 { // AUDIO_STREAM_BLUETOOTH_SCO
3146 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
3147 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3148 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
3149 },
3150 { // AUDIO_STREAM_ENFORCED_AUDIBLE
3151 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3152 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3153 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
3154 },
3155 { // AUDIO_STREAM_DTMF
3156 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
3157 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3158 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
3159 },
3160 { // AUDIO_STREAM_TTS
3161 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
3162 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
3163 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
3164 },
3165};
3166
Eric Laurente0720872014-03-11 09:30:41 -07003167void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07003168{
3169 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3170 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
3171 mStreams[i].mVolumeCurve[j] =
3172 sVolumeProfiles[i][j];
3173 }
3174 }
3175
3176 // Check availability of DRC on speaker path: if available, override some of the speaker curves
3177 if (mSpeakerDrcEnabled) {
3178 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3179 sDefaultSystemVolumeCurveDrc;
3180 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3181 sSpeakerSonificationVolumeCurveDrc;
3182 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3183 sSpeakerSonificationVolumeCurveDrc;
3184 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
3185 sSpeakerSonificationVolumeCurveDrc;
3186 }
3187}
3188
Eric Laurente0720872014-03-11 09:30:41 -07003189float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07003190 int index,
3191 audio_io_handle_t output,
3192 audio_devices_t device)
3193{
3194 float volume = 1.0;
3195 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3196 StreamDescriptor &streamDesc = mStreams[stream];
3197
3198 if (device == AUDIO_DEVICE_NONE) {
3199 device = outputDesc->device();
3200 }
3201
3202 // if volume is not 0 (not muted), force media volume to max on digital output
Eric Laurent3b73df72014-03-11 09:06:29 -07003203 if (stream == AUDIO_STREAM_MUSIC &&
Eric Laurente552edb2014-03-10 17:42:56 -07003204 index != mStreams[stream].mIndexMin &&
3205 (device == AUDIO_DEVICE_OUT_AUX_DIGITAL ||
3206 device == AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET ||
3207 device == AUDIO_DEVICE_OUT_USB_ACCESSORY ||
3208 device == AUDIO_DEVICE_OUT_USB_DEVICE)) {
3209 return 1.0;
3210 }
3211
3212 volume = volIndexToAmpl(device, streamDesc, index);
3213
3214 // if a headset is connected, apply the following rules to ring tones and notifications
3215 // to avoid sound level bursts in user's ears:
3216 // - always attenuate ring tones and notifications volume by 6dB
3217 // - if music is playing, always limit the volume to current music volume,
3218 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07003219 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07003220 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
3221 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
3222 AUDIO_DEVICE_OUT_WIRED_HEADSET |
3223 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
3224 ((stream_strategy == STRATEGY_SONIFICATION)
3225 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07003226 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07003227 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003228 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003229 streamDesc.mCanBeMuted) {
3230 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
3231 // when the phone is ringing we must consider that music could have been paused just before
3232 // by the music application and behave as if music was active if the last music track was
3233 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07003234 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07003235 mLimitRingtoneVolume) {
3236 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003237 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
3238 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07003239 output,
3240 musicDevice);
3241 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
3242 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
3243 if (volume > minVol) {
3244 volume = minVol;
3245 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
3246 }
3247 }
3248 }
3249
3250 return volume;
3251}
3252
Eric Laurente0720872014-03-11 09:30:41 -07003253status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07003254 int index,
3255 audio_io_handle_t output,
3256 audio_devices_t device,
3257 int delayMs,
3258 bool force)
3259{
3260
3261 // do not change actual stream volume if the stream is muted
3262 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
3263 ALOGVV("checkAndSetVolume() stream %d muted count %d",
3264 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
3265 return NO_ERROR;
3266 }
3267
3268 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07003269 if ((stream == AUDIO_STREAM_VOICE_CALL &&
3270 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3271 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
3272 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003273 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07003274 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07003275 return INVALID_OPERATION;
3276 }
3277
3278 float volume = computeVolume(stream, index, output, device);
3279 // We actually change the volume if:
3280 // - the float value returned by computeVolume() changed
3281 // - the force flag is set
3282 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
3283 force) {
3284 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
3285 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
3286 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
3287 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07003288 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
3289 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003290 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003291 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003292 }
3293
Eric Laurent3b73df72014-03-11 09:06:29 -07003294 if (stream == AUDIO_STREAM_VOICE_CALL ||
3295 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07003296 float voiceVolume;
3297 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07003298 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07003299 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
3300 } else {
3301 voiceVolume = 1.0;
3302 }
3303
3304 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
3305 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
3306 mLastVoiceVolume = voiceVolume;
3307 }
3308 }
3309
3310 return NO_ERROR;
3311}
3312
Eric Laurente0720872014-03-11 09:30:41 -07003313void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003314 audio_devices_t device,
3315 int delayMs,
3316 bool force)
3317{
3318 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
3319
Eric Laurent3b73df72014-03-11 09:06:29 -07003320 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
3321 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07003322 mStreams[stream].getVolumeIndex(device),
3323 output,
3324 device,
3325 delayMs,
3326 force);
3327 }
3328}
3329
Eric Laurente0720872014-03-11 09:30:41 -07003330void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003331 bool on,
3332 audio_io_handle_t output,
3333 int delayMs,
3334 audio_devices_t device)
3335{
3336 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07003337 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
3338 if (getStrategy((audio_stream_type_t)stream) == strategy) {
3339 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003340 }
3341 }
3342}
3343
Eric Laurente0720872014-03-11 09:30:41 -07003344void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07003345 bool on,
3346 audio_io_handle_t output,
3347 int delayMs,
3348 audio_devices_t device)
3349{
3350 StreamDescriptor &streamDesc = mStreams[stream];
3351 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(output);
3352 if (device == AUDIO_DEVICE_NONE) {
3353 device = outputDesc->device();
3354 }
3355
3356 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
3357 stream, on, output, outputDesc->mMuteCount[stream], device);
3358
3359 if (on) {
3360 if (outputDesc->mMuteCount[stream] == 0) {
3361 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003362 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
3363 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003364 checkAndSetVolume(stream, 0, output, device, delayMs);
3365 }
3366 }
3367 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
3368 outputDesc->mMuteCount[stream]++;
3369 } else {
3370 if (outputDesc->mMuteCount[stream] == 0) {
3371 ALOGV("setStreamMute() unmuting non muted stream!");
3372 return;
3373 }
3374 if (--outputDesc->mMuteCount[stream] == 0) {
3375 checkAndSetVolume(stream,
3376 streamDesc.getVolumeIndex(device),
3377 output,
3378 device,
3379 delayMs);
3380 }
3381 }
3382}
3383
Eric Laurente0720872014-03-11 09:30:41 -07003384void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07003385 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07003386{
3387 // if the stream pertains to sonification strategy and we are in call we must
3388 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
3389 // in the device used for phone strategy and play the tone if the selected device does not
3390 // interfere with the device used for phone strategy
3391 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
3392 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07003393 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07003394 if ((stream_strategy == STRATEGY_SONIFICATION) ||
3395 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
3396 AudioOutputDescriptor *outputDesc = mOutputs.valueFor(mPrimaryOutput);
3397 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
3398 stream, starting, outputDesc->mDevice, stateChange);
3399 if (outputDesc->mRefCount[stream]) {
3400 int muteCount = 1;
3401 if (stateChange) {
3402 muteCount = outputDesc->mRefCount[stream];
3403 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003404 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003405 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
3406 for (int i = 0; i < muteCount; i++) {
3407 setStreamMute(stream, starting, mPrimaryOutput);
3408 }
3409 } else {
3410 ALOGV("handleIncallSonification() high visibility");
3411 if (outputDesc->device() &
3412 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
3413 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
3414 for (int i = 0; i < muteCount; i++) {
3415 setStreamMute(stream, starting, mPrimaryOutput);
3416 }
3417 }
3418 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003419 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
3420 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07003421 } else {
3422 mpClientInterface->stopTone();
3423 }
3424 }
3425 }
3426 }
3427}
3428
Eric Laurente0720872014-03-11 09:30:41 -07003429bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07003430{
3431 return isStateInCall(mPhoneState);
3432}
3433
Eric Laurente0720872014-03-11 09:30:41 -07003434bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003435 return ((state == AUDIO_MODE_IN_CALL) ||
3436 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07003437}
3438
Eric Laurente0720872014-03-11 09:30:41 -07003439uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07003440{
3441 return MAX_EFFECTS_CPU_LOAD;
3442}
3443
Eric Laurente0720872014-03-11 09:30:41 -07003444uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07003445{
3446 return MAX_EFFECTS_MEMORY;
3447}
3448
3449// --- AudioOutputDescriptor class implementation
3450
Eric Laurente0720872014-03-11 09:30:41 -07003451AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurente552edb2014-03-10 17:42:56 -07003452 const IOProfile *profile)
3453 : mId(0), mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT),
3454 mChannelMask(0), mLatency(0),
3455 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE),
3456 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
3457{
3458 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07003459 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003460 mRefCount[i] = 0;
3461 mCurVolume[i] = -1.0;
3462 mMuteCount[i] = 0;
3463 mStopTime[i] = 0;
3464 }
3465 for (int i = 0; i < NUM_STRATEGIES; i++) {
3466 mStrategyMutedByDevice[i] = false;
3467 }
3468 if (profile != NULL) {
3469 mSamplingRate = profile->mSamplingRates[0];
3470 mFormat = profile->mFormats[0];
3471 mChannelMask = profile->mChannelMasks[0];
3472 mFlags = profile->mFlags;
3473 }
3474}
3475
Eric Laurente0720872014-03-11 09:30:41 -07003476audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07003477{
3478 if (isDuplicated()) {
3479 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
3480 } else {
3481 return mDevice;
3482 }
3483}
3484
Eric Laurente0720872014-03-11 09:30:41 -07003485uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07003486{
3487 if (isDuplicated()) {
3488 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
3489 } else {
3490 return mLatency;
3491 }
3492}
3493
Eric Laurente0720872014-03-11 09:30:41 -07003494bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurente552edb2014-03-10 17:42:56 -07003495 const AudioOutputDescriptor *outputDesc)
3496{
3497 if (isDuplicated()) {
3498 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
3499 } else if (outputDesc->isDuplicated()){
3500 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
3501 } else {
3502 return (mProfile->mModule == outputDesc->mProfile->mModule);
3503 }
3504}
3505
Eric Laurente0720872014-03-11 09:30:41 -07003506void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07003507 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07003508{
3509 // forward usage count change to attached outputs
3510 if (isDuplicated()) {
3511 mOutput1->changeRefCount(stream, delta);
3512 mOutput2->changeRefCount(stream, delta);
3513 }
3514 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003515 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
3516 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07003517 mRefCount[stream] = 0;
3518 return;
3519 }
3520 mRefCount[stream] += delta;
3521 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
3522}
3523
Eric Laurente0720872014-03-11 09:30:41 -07003524audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07003525{
3526 if (isDuplicated()) {
3527 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
3528 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003529 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07003530 }
3531}
3532
Eric Laurente0720872014-03-11 09:30:41 -07003533bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07003534{
3535 return isStrategyActive(NUM_STRATEGIES, inPastMs);
3536}
3537
Eric Laurente0720872014-03-11 09:30:41 -07003538bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003539 uint32_t inPastMs,
3540 nsecs_t sysTime) const
3541{
3542 if ((sysTime == 0) && (inPastMs != 0)) {
3543 sysTime = systemTime();
3544 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003545 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
3546 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07003547 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003548 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003549 return true;
3550 }
3551 }
3552 return false;
3553}
3554
Eric Laurente0720872014-03-11 09:30:41 -07003555bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07003556 uint32_t inPastMs,
3557 nsecs_t sysTime) const
3558{
3559 if (mRefCount[stream] != 0) {
3560 return true;
3561 }
3562 if (inPastMs == 0) {
3563 return false;
3564 }
3565 if (sysTime == 0) {
3566 sysTime = systemTime();
3567 }
3568 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
3569 return true;
3570 }
3571 return false;
3572}
3573
3574
Eric Laurente0720872014-03-11 09:30:41 -07003575status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07003576{
3577 const size_t SIZE = 256;
3578 char buffer[SIZE];
3579 String8 result;
3580
3581 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3582 result.append(buffer);
3583 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
3584 result.append(buffer);
3585 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3586 result.append(buffer);
3587 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
3588 result.append(buffer);
3589 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
3590 result.append(buffer);
3591 snprintf(buffer, SIZE, " Devices %08x\n", device());
3592 result.append(buffer);
3593 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
3594 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07003595 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
3596 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
3597 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003598 result.append(buffer);
3599 }
3600 write(fd, result.string(), result.size());
3601
3602 return NO_ERROR;
3603}
3604
3605// --- AudioInputDescriptor class implementation
3606
Eric Laurente0720872014-03-11 09:30:41 -07003607AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const IOProfile *profile)
Eric Laurente552edb2014-03-10 17:42:56 -07003608 : mSamplingRate(0), mFormat(AUDIO_FORMAT_DEFAULT), mChannelMask(0),
3609 mDevice(AUDIO_DEVICE_NONE), mRefCount(0),
Eric Laurent3b73df72014-03-11 09:06:29 -07003610 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile)
Eric Laurente552edb2014-03-10 17:42:56 -07003611{
Eric Laurent3a4311c2014-03-17 12:00:47 -07003612 if (profile != NULL) {
3613 mSamplingRate = profile->mSamplingRates[0];
3614 mFormat = profile->mFormats[0];
3615 mChannelMask = profile->mChannelMasks[0];
3616 }
Eric Laurente552edb2014-03-10 17:42:56 -07003617}
3618
Eric Laurente0720872014-03-11 09:30:41 -07003619status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07003620{
3621 const size_t SIZE = 256;
3622 char buffer[SIZE];
3623 String8 result;
3624
3625 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
3626 result.append(buffer);
3627 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
3628 result.append(buffer);
3629 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
3630 result.append(buffer);
3631 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
3632 result.append(buffer);
3633 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
3634 result.append(buffer);
3635 write(fd, result.string(), result.size());
3636
3637 return NO_ERROR;
3638}
3639
3640// --- StreamDescriptor class implementation
3641
Eric Laurente0720872014-03-11 09:30:41 -07003642AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07003643 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
3644{
3645 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
3646}
3647
Eric Laurente0720872014-03-11 09:30:41 -07003648int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003649{
Eric Laurente0720872014-03-11 09:30:41 -07003650 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07003651 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
3652 if (mIndexCur.indexOfKey(device) < 0) {
3653 device = AUDIO_DEVICE_OUT_DEFAULT;
3654 }
3655 return mIndexCur.valueFor(device);
3656}
3657
Eric Laurente0720872014-03-11 09:30:41 -07003658void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07003659{
3660 const size_t SIZE = 256;
3661 char buffer[SIZE];
3662 String8 result;
3663
3664 snprintf(buffer, SIZE, "%s %02d %02d ",
3665 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
3666 result.append(buffer);
3667 for (size_t i = 0; i < mIndexCur.size(); i++) {
3668 snprintf(buffer, SIZE, "%04x : %02d, ",
3669 mIndexCur.keyAt(i),
3670 mIndexCur.valueAt(i));
3671 result.append(buffer);
3672 }
3673 result.append("\n");
3674
3675 write(fd, result.string(), result.size());
3676}
3677
3678// --- EffectDescriptor class implementation
3679
Eric Laurente0720872014-03-11 09:30:41 -07003680status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07003681{
3682 const size_t SIZE = 256;
3683 char buffer[SIZE];
3684 String8 result;
3685
3686 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
3687 result.append(buffer);
3688 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
3689 result.append(buffer);
3690 snprintf(buffer, SIZE, " Session: %d\n", mSession);
3691 result.append(buffer);
3692 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
3693 result.append(buffer);
3694 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
3695 result.append(buffer);
3696 write(fd, result.string(), result.size());
3697
3698 return NO_ERROR;
3699}
3700
3701// --- IOProfile class implementation
3702
Eric Laurente0720872014-03-11 09:30:41 -07003703AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07003704 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)), mHandle(0)
3705{
3706}
3707
Eric Laurente0720872014-03-11 09:30:41 -07003708AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07003709{
3710 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003711 mOutputProfiles[i]->mSupportedDevices.clear();
3712 delete mOutputProfiles[i];
Eric Laurente552edb2014-03-10 17:42:56 -07003713 }
3714 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003715 mInputProfiles[i]->mSupportedDevices.clear();
3716 delete mInputProfiles[i];
Eric Laurente552edb2014-03-10 17:42:56 -07003717 }
3718 free((void *)mName);
3719}
3720
Eric Laurente0720872014-03-11 09:30:41 -07003721void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07003722{
3723 const size_t SIZE = 256;
3724 char buffer[SIZE];
3725 String8 result;
3726
3727 snprintf(buffer, SIZE, " - name: %s\n", mName);
3728 result.append(buffer);
3729 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
3730 result.append(buffer);
3731 write(fd, result.string(), result.size());
3732 if (mOutputProfiles.size()) {
3733 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
3734 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
3735 snprintf(buffer, SIZE, " output %d:\n", i);
3736 write(fd, buffer, strlen(buffer));
3737 mOutputProfiles[i]->dump(fd);
3738 }
3739 }
3740 if (mInputProfiles.size()) {
3741 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
3742 for (size_t i = 0; i < mInputProfiles.size(); i++) {
3743 snprintf(buffer, SIZE, " input %d:\n", i);
3744 write(fd, buffer, strlen(buffer));
3745 mInputProfiles[i]->dump(fd);
3746 }
3747 }
3748}
3749
Eric Laurente0720872014-03-11 09:30:41 -07003750AudioPolicyManager::IOProfile::IOProfile(HwModule *module)
Eric Laurente552edb2014-03-10 17:42:56 -07003751 : mFlags((audio_output_flags_t)0), mModule(module)
3752{
3753}
3754
Eric Laurente0720872014-03-11 09:30:41 -07003755AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07003756{
3757}
3758
3759// checks if the IO profile is compatible with specified parameters.
3760// Sampling rate, format and channel mask must be specified in order to
3761// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07003762bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07003763 uint32_t samplingRate,
3764 audio_format_t format,
3765 audio_channel_mask_t channelMask,
3766 audio_output_flags_t flags) const
3767{
3768 if (samplingRate == 0 || !audio_is_valid_format(format) || channelMask == 0) {
3769 return false;
3770 }
3771
Eric Laurent3a4311c2014-03-17 12:00:47 -07003772 if ((mSupportedDevices.types() & device) != device) {
Eric Laurente552edb2014-03-10 17:42:56 -07003773 return false;
3774 }
3775 if ((mFlags & flags) != flags) {
3776 return false;
3777 }
3778 size_t i;
3779 for (i = 0; i < mSamplingRates.size(); i++)
3780 {
3781 if (mSamplingRates[i] == samplingRate) {
3782 break;
3783 }
3784 }
3785 if (i == mSamplingRates.size()) {
3786 return false;
3787 }
3788 for (i = 0; i < mFormats.size(); i++)
3789 {
3790 if (mFormats[i] == format) {
3791 break;
3792 }
3793 }
3794 if (i == mFormats.size()) {
3795 return false;
3796 }
3797 for (i = 0; i < mChannelMasks.size(); i++)
3798 {
3799 if (mChannelMasks[i] == channelMask) {
3800 break;
3801 }
3802 }
3803 if (i == mChannelMasks.size()) {
3804 return false;
3805 }
3806 return true;
3807}
3808
Eric Laurente0720872014-03-11 09:30:41 -07003809void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07003810{
3811 const size_t SIZE = 256;
3812 char buffer[SIZE];
3813 String8 result;
3814
3815 snprintf(buffer, SIZE, " - sampling rates: ");
3816 result.append(buffer);
3817 for (size_t i = 0; i < mSamplingRates.size(); i++) {
3818 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
3819 result.append(buffer);
3820 result.append(i == (mSamplingRates.size() - 1) ? "\n" : ", ");
3821 }
3822
3823 snprintf(buffer, SIZE, " - channel masks: ");
3824 result.append(buffer);
3825 for (size_t i = 0; i < mChannelMasks.size(); i++) {
3826 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
3827 result.append(buffer);
3828 result.append(i == (mChannelMasks.size() - 1) ? "\n" : ", ");
3829 }
3830
3831 snprintf(buffer, SIZE, " - formats: ");
3832 result.append(buffer);
3833 for (size_t i = 0; i < mFormats.size(); i++) {
3834 snprintf(buffer, SIZE, "0x%08x", mFormats[i]);
3835 result.append(buffer);
3836 result.append(i == (mFormats.size() - 1) ? "\n" : ", ");
3837 }
3838
Eric Laurent3a4311c2014-03-17 12:00:47 -07003839 snprintf(buffer, SIZE, " - devices:\n");
Eric Laurente552edb2014-03-10 17:42:56 -07003840 result.append(buffer);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003841 write(fd, result.string(), result.size());
3842 DeviceDescriptor::dumpHeader(fd, 6);
3843 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
3844 mSupportedDevices[i]->dump(fd, 6);
3845 }
3846
Eric Laurente552edb2014-03-10 17:42:56 -07003847 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
3848 result.append(buffer);
3849
3850 write(fd, result.string(), result.size());
3851}
3852
Eric Laurent3a4311c2014-03-17 12:00:47 -07003853// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07003854
Eric Laurent3a4311c2014-03-17 12:00:47 -07003855bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07003856{
Eric Laurent3a4311c2014-03-17 12:00:47 -07003857 // Devices are considered equal if they:
3858 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
3859 // - have the same address or one device does not specify the address
3860 // - have the same channel mask or one device does not specify the channel mask
3861 return (mType == other->mType) &&
3862 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
3863 (mChannelMask == AUDIO_CHANNEL_NONE || other->mChannelMask == AUDIO_CHANNEL_NONE ||
3864 mChannelMask == other->mChannelMask);
3865}
3866
3867void AudioPolicyManager::DeviceVector::refreshTypes()
3868{
3869 mTypes = AUDIO_DEVICE_NONE;
3870 for(size_t i = 0; i < size(); i++) {
3871 mTypes |= itemAt(i)->mType;
3872 }
3873 ALOGV("DeviceVector::refreshTypes() mTypes %08x", mTypes);
3874}
3875
3876ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
3877{
3878 for(size_t i = 0; i < size(); i++) {
3879 if (item->equals(itemAt(i))) {
3880 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07003881 }
3882 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003883 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07003884}
3885
Eric Laurent3a4311c2014-03-17 12:00:47 -07003886ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07003887{
Eric Laurent3a4311c2014-03-17 12:00:47 -07003888 ssize_t ret = indexOf(item);
3889
3890 if (ret < 0) {
3891 ret = SortedVector::add(item);
3892 if (ret >= 0) {
3893 refreshTypes();
3894 }
3895 } else {
3896 ALOGW("DeviceVector::add device %08x already in", item->mType);
3897 ret = -1;
3898 }
3899 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07003900}
3901
Eric Laurent3a4311c2014-03-17 12:00:47 -07003902ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
3903{
3904 size_t i;
3905 ssize_t ret = indexOf(item);
3906
3907 if (ret < 0) {
3908 ALOGW("DeviceVector::remove device %08x not in", item->mType);
3909 } else {
3910 ret = SortedVector::removeAt(ret);
3911 if (ret >= 0) {
3912 refreshTypes();
3913 }
3914 }
3915 return ret;
3916}
3917
3918void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
3919{
3920 DeviceVector deviceList;
3921
3922 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
3923 types &= ~role_bit;
3924
3925 while (types) {
3926 uint32_t i = 31 - __builtin_clz(types);
3927 uint32_t type = 1 << i;
3928 types &= ~type;
3929 add(new DeviceDescriptor(type | role_bit));
3930 }
3931}
3932
3933void AudioPolicyManager::DeviceDescriptor::dumpHeader(int fd, int spaces)
3934{
3935 const size_t SIZE = 256;
3936 char buffer[SIZE];
3937
3938 snprintf(buffer, SIZE, "%*s%-48s %-2s %-8s %-32s \n",
3939 spaces, "", "Type", "ID", "Cnl Mask", "Address");
3940 write(fd, buffer, strlen(buffer));
3941}
3942
3943status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces) const
3944{
3945 const size_t SIZE = 256;
3946 char buffer[SIZE];
3947
3948 snprintf(buffer, SIZE, "%*s%-48s %2d %08x %-32s \n",
3949 spaces, "",
3950 enumToString(sDeviceNameToEnumTable,
3951 ARRAY_SIZE(sDeviceNameToEnumTable),
3952 mType),
3953 mId, mChannelMask, mAddress.string());
3954 write(fd, buffer, strlen(buffer));
3955
3956 return NO_ERROR;
3957}
3958
3959
3960// --- audio_policy.conf file parsing
3961
Eric Laurente0720872014-03-11 09:30:41 -07003962audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07003963{
3964 uint32_t flag = 0;
3965
3966 // it is OK to cast name to non const here as we are not going to use it after
3967 // strtok() modifies it
3968 char *flagName = strtok(name, "|");
3969 while (flagName != NULL) {
3970 if (strlen(flagName) != 0) {
3971 flag |= stringToEnum(sFlagNameToEnumTable,
3972 ARRAY_SIZE(sFlagNameToEnumTable),
3973 flagName);
3974 }
3975 flagName = strtok(NULL, "|");
3976 }
3977 //force direct flag if offload flag is set: offloading implies a direct output stream
3978 // and all common behaviors are driven by checking only the direct flag
3979 // this should normally be set appropriately in the policy configuration file
3980 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
3981 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
3982 }
3983
3984 return (audio_output_flags_t)flag;
3985}
3986
Eric Laurente0720872014-03-11 09:30:41 -07003987audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07003988{
3989 uint32_t device = 0;
3990
3991 char *devName = strtok(name, "|");
3992 while (devName != NULL) {
3993 if (strlen(devName) != 0) {
3994 device |= stringToEnum(sDeviceNameToEnumTable,
3995 ARRAY_SIZE(sDeviceNameToEnumTable),
3996 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003997 }
Eric Laurente552edb2014-03-10 17:42:56 -07003998 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07003999 }
Eric Laurente552edb2014-03-10 17:42:56 -07004000 return device;
4001}
4002
Eric Laurente0720872014-03-11 09:30:41 -07004003void AudioPolicyManager::loadSamplingRates(char *name, IOProfile *profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004004{
4005 char *str = strtok(name, "|");
4006
4007 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
4008 // rates should be read from the output stream after it is opened for the first time
4009 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4010 profile->mSamplingRates.add(0);
4011 return;
4012 }
4013
4014 while (str != NULL) {
4015 uint32_t rate = atoi(str);
4016 if (rate != 0) {
4017 ALOGV("loadSamplingRates() adding rate %d", rate);
4018 profile->mSamplingRates.add(rate);
4019 }
4020 str = strtok(NULL, "|");
4021 }
4022 return;
4023}
4024
Eric Laurente0720872014-03-11 09:30:41 -07004025void AudioPolicyManager::loadFormats(char *name, IOProfile *profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004026{
4027 char *str = strtok(name, "|");
4028
4029 // by convention, "0' in the first entry in mFormats indicates the supported formats
4030 // should be read from the output stream after it is opened for the first time
4031 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4032 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
4033 return;
4034 }
4035
4036 while (str != NULL) {
4037 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
4038 ARRAY_SIZE(sFormatNameToEnumTable),
4039 str);
4040 if (format != AUDIO_FORMAT_DEFAULT) {
4041 profile->mFormats.add(format);
4042 }
4043 str = strtok(NULL, "|");
4044 }
4045 return;
4046}
4047
Eric Laurente0720872014-03-11 09:30:41 -07004048void AudioPolicyManager::loadInChannels(char *name, IOProfile *profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004049{
4050 const char *str = strtok(name, "|");
4051
4052 ALOGV("loadInChannels() %s", name);
4053
4054 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4055 profile->mChannelMasks.add(0);
4056 return;
4057 }
4058
4059 while (str != NULL) {
4060 audio_channel_mask_t channelMask =
4061 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
4062 ARRAY_SIZE(sInChannelsNameToEnumTable),
4063 str);
4064 if (channelMask != 0) {
4065 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
4066 profile->mChannelMasks.add(channelMask);
4067 }
4068 str = strtok(NULL, "|");
4069 }
4070 return;
4071}
4072
Eric Laurente0720872014-03-11 09:30:41 -07004073void AudioPolicyManager::loadOutChannels(char *name, IOProfile *profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004074{
4075 const char *str = strtok(name, "|");
4076
4077 ALOGV("loadOutChannels() %s", name);
4078
4079 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
4080 // masks should be read from the output stream after it is opened for the first time
4081 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
4082 profile->mChannelMasks.add(0);
4083 return;
4084 }
4085
4086 while (str != NULL) {
4087 audio_channel_mask_t channelMask =
4088 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
4089 ARRAY_SIZE(sOutChannelsNameToEnumTable),
4090 str);
4091 if (channelMask != 0) {
4092 profile->mChannelMasks.add(channelMask);
4093 }
4094 str = strtok(NULL, "|");
4095 }
4096 return;
4097}
4098
Eric Laurente0720872014-03-11 09:30:41 -07004099status_t AudioPolicyManager::loadInput(cnode *root, HwModule *module)
Eric Laurente552edb2014-03-10 17:42:56 -07004100{
4101 cnode *node = root->first_child;
4102
4103 IOProfile *profile = new IOProfile(module);
4104
4105 while (node) {
4106 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4107 loadSamplingRates((char *)node->value, profile);
4108 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4109 loadFormats((char *)node->value, profile);
4110 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4111 loadInChannels((char *)node->value, profile);
4112 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004113 profile->mSupportedDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
Eric Laurente552edb2014-03-10 17:42:56 -07004114 }
4115 node = node->next;
4116 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004117 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
Eric Laurente552edb2014-03-10 17:42:56 -07004118 "loadInput() invalid supported devices");
4119 ALOGW_IF(profile->mChannelMasks.size() == 0,
4120 "loadInput() invalid supported channel masks");
4121 ALOGW_IF(profile->mSamplingRates.size() == 0,
4122 "loadInput() invalid supported sampling rates");
4123 ALOGW_IF(profile->mFormats.size() == 0,
4124 "loadInput() invalid supported formats");
Eric Laurent3a4311c2014-03-17 12:00:47 -07004125 if (!profile->mSupportedDevices.isEmpty() &&
Eric Laurente552edb2014-03-10 17:42:56 -07004126 (profile->mChannelMasks.size() != 0) &&
4127 (profile->mSamplingRates.size() != 0) &&
4128 (profile->mFormats.size() != 0)) {
4129
Eric Laurent3a4311c2014-03-17 12:00:47 -07004130 ALOGV("loadInput() adding input Supported Devices %04x",
4131 profile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004132
4133 module->mInputProfiles.add(profile);
4134 return NO_ERROR;
4135 } else {
4136 delete profile;
4137 return BAD_VALUE;
4138 }
4139}
4140
Eric Laurente0720872014-03-11 09:30:41 -07004141status_t AudioPolicyManager::loadOutput(cnode *root, HwModule *module)
Eric Laurente552edb2014-03-10 17:42:56 -07004142{
4143 cnode *node = root->first_child;
4144
4145 IOProfile *profile = new IOProfile(module);
4146
4147 while (node) {
4148 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
4149 loadSamplingRates((char *)node->value, profile);
4150 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
4151 loadFormats((char *)node->value, profile);
4152 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
4153 loadOutChannels((char *)node->value, profile);
4154 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004155 profile->mSupportedDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
Eric Laurente552edb2014-03-10 17:42:56 -07004156 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
4157 profile->mFlags = parseFlagNames((char *)node->value);
4158 }
4159 node = node->next;
4160 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004161 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
Eric Laurente552edb2014-03-10 17:42:56 -07004162 "loadOutput() invalid supported devices");
4163 ALOGW_IF(profile->mChannelMasks.size() == 0,
4164 "loadOutput() invalid supported channel masks");
4165 ALOGW_IF(profile->mSamplingRates.size() == 0,
4166 "loadOutput() invalid supported sampling rates");
4167 ALOGW_IF(profile->mFormats.size() == 0,
4168 "loadOutput() invalid supported formats");
Eric Laurent3a4311c2014-03-17 12:00:47 -07004169 if (!profile->mSupportedDevices.isEmpty() &&
Eric Laurente552edb2014-03-10 17:42:56 -07004170 (profile->mChannelMasks.size() != 0) &&
4171 (profile->mSamplingRates.size() != 0) &&
4172 (profile->mFormats.size() != 0)) {
4173
Eric Laurent3a4311c2014-03-17 12:00:47 -07004174 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
4175 profile->mSupportedDevices.types(), profile->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07004176
4177 module->mOutputProfiles.add(profile);
4178 return NO_ERROR;
4179 } else {
4180 delete profile;
4181 return BAD_VALUE;
4182 }
4183}
4184
Eric Laurente0720872014-03-11 09:30:41 -07004185void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07004186{
4187 cnode *node = config_find(root, OUTPUTS_TAG);
4188 status_t status = NAME_NOT_FOUND;
4189
4190 HwModule *module = new HwModule(root->name);
4191
4192 if (node != NULL) {
4193 if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_A2DP) == 0) {
4194 mHasA2dp = true;
4195 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_USB) == 0) {
4196 mHasUsb = true;
4197 } else if (strcmp(root->name, AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX) == 0) {
4198 mHasRemoteSubmix = true;
4199 }
4200
4201 node = node->first_child;
4202 while (node) {
4203 ALOGV("loadHwModule() loading output %s", node->name);
4204 status_t tmpStatus = loadOutput(node, module);
4205 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
4206 status = tmpStatus;
4207 }
4208 node = node->next;
4209 }
4210 }
4211 node = config_find(root, INPUTS_TAG);
4212 if (node != NULL) {
4213 node = node->first_child;
4214 while (node) {
4215 ALOGV("loadHwModule() loading input %s", node->name);
4216 status_t tmpStatus = loadInput(node, module);
4217 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
4218 status = tmpStatus;
4219 }
4220 node = node->next;
4221 }
4222 }
4223 if (status == NO_ERROR) {
4224 mHwModules.add(module);
4225 } else {
4226 delete module;
4227 }
4228}
4229
Eric Laurente0720872014-03-11 09:30:41 -07004230void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07004231{
4232 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
4233 if (node == NULL) {
4234 return;
4235 }
4236
4237 node = node->first_child;
4238 while (node) {
4239 ALOGV("loadHwModules() loading module %s", node->name);
4240 loadHwModule(node);
4241 node = node->next;
4242 }
4243}
4244
Eric Laurente0720872014-03-11 09:30:41 -07004245void AudioPolicyManager::loadGlobalConfig(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07004246{
4247 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
4248 if (node == NULL) {
4249 return;
4250 }
4251 node = node->first_child;
4252 while (node) {
4253 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004254 mAvailableOutputDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
4255 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
4256 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004257 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004258 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07004259 ARRAY_SIZE(sDeviceNameToEnumTable),
4260 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004261 if (device != AUDIO_DEVICE_NONE) {
4262 mDefaultOutputDevice = new DeviceDescriptor(device);
4263 } else {
4264 ALOGW("loadGlobalConfig() default device not specified");
4265 }
4266 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mType);
Eric Laurente552edb2014-03-10 17:42:56 -07004267 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004268 mAvailableInputDevices.loadDevicesFromType(parseDeviceNames((char *)node->value));
4269 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004270 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
4271 mSpeakerDrcEnabled = stringToBool((char *)node->value);
4272 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
4273 }
4274 node = node->next;
4275 }
4276}
4277
Eric Laurente0720872014-03-11 09:30:41 -07004278status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07004279{
4280 cnode *root;
4281 char *data;
4282
4283 data = (char *)load_file(path, NULL);
4284 if (data == NULL) {
4285 return -ENODEV;
4286 }
4287 root = config_node("", "");
4288 config_load(root, data);
4289
4290 loadGlobalConfig(root);
4291 loadHwModules(root);
4292
4293 config_free(root);
4294 free(root);
4295 free(data);
4296
4297 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
4298
4299 return NO_ERROR;
4300}
4301
Eric Laurente0720872014-03-11 09:30:41 -07004302void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07004303{
4304 HwModule *module;
4305 IOProfile *profile;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004306 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(AUDIO_DEVICE_IN_BUILTIN_MIC);
4307 mAvailableOutputDevices.add(mDefaultOutputDevice);
4308 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004309
4310 module = new HwModule("primary");
4311
4312 profile = new IOProfile(module);
4313 profile->mSamplingRates.add(44100);
4314 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4315 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004316 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004317 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
4318 module->mOutputProfiles.add(profile);
4319
4320 profile = new IOProfile(module);
4321 profile->mSamplingRates.add(8000);
4322 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
4323 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07004324 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07004325 module->mInputProfiles.add(profile);
4326
4327 mHwModules.add(module);
4328}
4329
4330}; // namespace android