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