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