blob: 09595ffe99144d99b5aef4dd5bfdb5c5c91a6547 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Eric Laurente0720872014-03-11 09:30:41 -070017#define LOG_TAG "AudioPolicyManager"
Eric Laurente552edb2014-03-10 17:42:56 -070018//#define LOG_NDEBUG 0
19
20//#define VERY_VERBOSE_LOGGING
21#ifdef VERY_VERBOSE_LOGGING
22#define ALOGVV ALOGV
23#else
24#define ALOGVV(a...) do { } while(0)
25#endif
26
27// A device mask for all audio input devices that are considered "virtual" when evaluating
28// active inputs in getActiveInput()
29#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL AUDIO_DEVICE_IN_REMOTE_SUBMIX
30// A device mask for all audio output devices that are considered "remote" when evaluating
31// active output devices in isStreamActiveRemotely()
32#define APM_AUDIO_OUT_DEVICE_REMOTE_ALL AUDIO_DEVICE_OUT_REMOTE_SUBMIX
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -070033// A device mask for all audio input and output devices where matching inputs/outputs on device
34// type alone is not enough: the address must match too
35#define APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX | \
36 AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
Eric Laurente552edb2014-03-10 17:42:56 -070037
Eric Laurentd4692962014-05-05 18:13:44 -070038#include <inttypes.h>
Eric Laurente552edb2014-03-10 17:42:56 -070039#include <math.h>
Eric Laurentd4692962014-05-05 18:13:44 -070040
Eric Laurente552edb2014-03-10 17:42:56 -070041#include <cutils/properties.h>
Eric Laurentd4692962014-05-05 18:13:44 -070042#include <utils/Log.h>
43#include <hardware/audio.h>
44#include <hardware/audio_effect.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070045#include <media/AudioParameter.h>
Eric Laurentd4692962014-05-05 18:13:44 -070046#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070047#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070048
Eric Laurent3b73df72014-03-11 09:06:29 -070049namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070050
51// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070052// Definitions for audio_policy.conf file parsing
53// ----------------------------------------------------------------------------
54
55struct StringToEnum {
56 const char *name;
57 uint32_t value;
58};
59
60#define STRING_TO_ENUM(string) { #string, string }
61#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
62
63const StringToEnum sDeviceNameToEnumTable[] = {
64 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
65 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
68 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
69 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070077 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070078 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
80 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
81 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070084 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
85 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
86 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
87 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurente1d37b72014-07-29 10:26:26 -070089 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
Eric Laurent3a4311c2014-03-17 12:00:47 -070090 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
91 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
92 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
93 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
94 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070095 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070096 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent1b776232014-05-19 17:26:41 -070097 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurent3a4311c2014-03-17 12:00:47 -070098 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
99 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
100 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
101 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
102 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700103 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700104 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
105 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
106 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
107 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700108 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900109 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700110};
111
112const StringToEnum sFlagNameToEnumTable[] = {
113 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
114 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
115 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
116 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
119};
120
121const StringToEnum sFormatNameToEnumTable[] = {
122 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
123 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
124 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
125 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
126 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
127 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
128 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
129 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530130 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
131 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
132 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
133 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
134 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
135 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
136 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
137 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
138 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
139 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700140 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700141 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
142 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
143 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
144 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
145 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700146};
147
148const StringToEnum sOutChannelsNameToEnumTable[] = {
149 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
150 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700151 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700152 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
153 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
154};
155
156const StringToEnum sInChannelsNameToEnumTable[] = {
157 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
158 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
159 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
160};
161
Eric Laurent1afeecb2014-05-14 08:52:28 -0700162const StringToEnum sGainModeNameToEnumTable[] = {
163 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
164 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
165 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
166};
167
Eric Laurent3a4311c2014-03-17 12:00:47 -0700168
169uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
170 size_t size,
171 const char *name)
172{
173 for (size_t i = 0; i < size; i++) {
174 if (strcmp(table[i].name, name) == 0) {
175 ALOGV("stringToEnum() found %s", table[i].name);
176 return table[i].value;
177 }
178 }
179 return 0;
180}
181
182const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
183 size_t size,
184 uint32_t value)
185{
186 for (size_t i = 0; i < size; i++) {
187 if (table[i].value == value) {
188 return table[i].name;
189 }
190 }
191 return "";
192}
193
194bool AudioPolicyManager::stringToBool(const char *value)
195{
196 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
197}
198
199
200// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700201// AudioPolicyInterface implementation
202// ----------------------------------------------------------------------------
203
204
Eric Laurente0720872014-03-11 09:30:41 -0700205status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700206 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700207 const char *device_address)
208{
Eric Laurent22226012014-08-01 17:00:54 -0700209 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurente552edb2014-03-10 17:42:56 -0700210
Eric Laurent22226012014-08-01 17:00:54 -0700211 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
212 device, state, address.string());
Eric Laurente552edb2014-03-10 17:42:56 -0700213
214 // connect/disconnect only 1 device at a time
215 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
216
Eric Laurente552edb2014-03-10 17:42:56 -0700217 // handle output devices
218 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700219 SortedVector <audio_io_handle_t> outputs;
220
Eric Laurent1afeecb2014-05-14 08:52:28 -0700221 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
222 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700223 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
224
Eric Laurente552edb2014-03-10 17:42:56 -0700225 // save a copy of the opened output descriptors before any output is opened or closed
226 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
227 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700228 switch (state)
229 {
230 // handle output device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700231 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE:
Eric Laurent3a4311c2014-03-17 12:00:47 -0700232 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700233 ALOGW("setDeviceConnectionState() device already connected: %x", device);
234 return INVALID_OPERATION;
235 }
236 ALOGV("setDeviceConnectionState() connecting device %x", device);
237
Eric Laurente552edb2014-03-10 17:42:56 -0700238 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700239 index = mAvailableOutputDevices.add(devDesc);
240 if (index >= 0) {
241 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent1f2f2232014-06-02 12:01:23 -0700242 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700243 ALOG_ASSERT(module != NULL, "setDeviceConnectionState():"
244 "could not find HW module for device %08x", device);
245 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700246 } else {
247 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700248 }
249
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700250 if (checkOutputsForDevice(device, state, outputs, address) != NO_ERROR) {
251 mAvailableOutputDevices.remove(devDesc);
252 return INVALID_OPERATION;
253 }
254 // outputs should never be empty here
255 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
256 "checkOutputsForDevice() returned no outputs but status OK");
257 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
258 outputs.size());
Eric Laurente552edb2014-03-10 17:42:56 -0700259 break;
260 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700261 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700262 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700263 ALOGW("setDeviceConnectionState() device not connected: %x", device);
264 return INVALID_OPERATION;
265 }
266
267 ALOGV("setDeviceConnectionState() disconnecting device %x", device);
268 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700269 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700270
Eric Laurent3a4311c2014-03-17 12:00:47 -0700271 checkOutputsForDevice(device, state, outputs, address);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 } break;
273
274 default:
275 ALOGE("setDeviceConnectionState() invalid state: %x", state);
276 return BAD_VALUE;
277 }
278
Eric Laurent3a4311c2014-03-17 12:00:47 -0700279 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
280 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700281 checkA2dpSuspend();
282 checkOutputForAllStrategies();
283 // outputs must be closed after checkOutputForAllStrategies() is executed
284 if (!outputs.isEmpty()) {
285 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700286 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700287 // close unused outputs after device disconnection or direct outputs that have been
288 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700289 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700290 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
291 (desc->mDirectOpenCount == 0))) {
292 closeOutput(outputs[i]);
293 }
294 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700295 // check again after closing A2DP output to reset mA2dpSuspended if needed
296 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700297 }
298
299 updateDevicesAndOutputs();
300 for (size_t i = 0; i < mOutputs.size(); i++) {
301 // do not force device change on duplicated output because if device is 0, it will
302 // also force a device 0 for the two outputs it is duplicated to which may override
303 // a valid device selection on those outputs.
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700304 bool force = !mOutputs.valueAt(i)->isDuplicated()
305 && (!deviceDistinguishesOnAddress(device)
306 // always force when disconnecting (a non-duplicated device)
307 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
Eric Laurente552edb2014-03-10 17:42:56 -0700308 setOutputDevice(mOutputs.keyAt(i),
Eric Laurent1c333e22014-05-20 10:48:17 -0700309 getNewOutputDevice(mOutputs.keyAt(i), true /*fromCache*/),
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700310 force, 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700311 }
312
Eric Laurent72aa32f2014-05-30 18:51:48 -0700313 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700314 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700315 } // end if is output device
316
Eric Laurente552edb2014-03-10 17:42:56 -0700317 // handle input devices
318 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700319 SortedVector <audio_io_handle_t> inputs;
320
Eric Laurent1afeecb2014-05-14 08:52:28 -0700321 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
322 devDesc->mAddress = address;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700323 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700324 switch (state)
325 {
326 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700327 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700328 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700329 ALOGW("setDeviceConnectionState() device already connected: %d", device);
330 return INVALID_OPERATION;
331 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700332 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700333 if (module == NULL) {
334 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
335 device);
336 return INVALID_OPERATION;
337 }
Eric Laurentd4692962014-05-05 18:13:44 -0700338 if (checkInputsForDevice(device, state, inputs, address) != NO_ERROR) {
339 return INVALID_OPERATION;
340 }
341
Eric Laurent3a4311c2014-03-17 12:00:47 -0700342 index = mAvailableInputDevices.add(devDesc);
343 if (index >= 0) {
344 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700345 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700346 } else {
347 return NO_MEMORY;
348 }
Eric Laurentd4692962014-05-05 18:13:44 -0700349 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700350
351 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700352 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700353 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700354 ALOGW("setDeviceConnectionState() device not connected: %d", device);
355 return INVALID_OPERATION;
356 }
Eric Laurentd4692962014-05-05 18:13:44 -0700357 checkInputsForDevice(device, state, inputs, address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700358 mAvailableInputDevices.remove(devDesc);
Eric Laurentd4692962014-05-05 18:13:44 -0700359 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700360
361 default:
362 ALOGE("setDeviceConnectionState() invalid state: %x", state);
363 return BAD_VALUE;
364 }
365
Eric Laurentd4692962014-05-05 18:13:44 -0700366 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700367
Eric Laurentb52c1522014-05-20 11:27:36 -0700368 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700369 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700370 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700371
372 ALOGW("setDeviceConnectionState() invalid device: %x", device);
373 return BAD_VALUE;
374}
375
Eric Laurente0720872014-03-11 09:30:41 -0700376audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700377 const char *device_address)
378{
Eric Laurent3b73df72014-03-11 09:06:29 -0700379 audio_policy_dev_state_t state = AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurent1afeecb2014-05-14 08:52:28 -0700380 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
Eric Laurent22226012014-08-01 17:00:54 -0700381 devDesc->mAddress = (device_address == NULL) ? String8("") : String8(device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700382 ssize_t index;
383 DeviceVector *deviceVector;
384
Eric Laurente552edb2014-03-10 17:42:56 -0700385 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700386 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700387 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700388 deviceVector = &mAvailableInputDevices;
389 } else {
390 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
391 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700392 }
393
Eric Laurent3a4311c2014-03-17 12:00:47 -0700394 index = deviceVector->indexOf(devDesc);
395 if (index >= 0) {
396 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
397 } else {
398 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
399 }
Eric Laurente552edb2014-03-10 17:42:56 -0700400}
401
Eric Laurente0720872014-03-11 09:30:41 -0700402void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700403{
404 ALOGV("setPhoneState() state %d", state);
405 audio_devices_t newDevice = AUDIO_DEVICE_NONE;
Eric Laurent3b73df72014-03-11 09:06:29 -0700406 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700407 ALOGW("setPhoneState() invalid state %d", state);
408 return;
409 }
410
411 if (state == mPhoneState ) {
412 ALOGW("setPhoneState() setting same state %d", state);
413 return;
414 }
415
416 // if leaving call state, handle special case of active streams
417 // pertaining to sonification strategy see handleIncallSonification()
418 if (isInCall()) {
419 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700420 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
421 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700422 }
423 }
424
425 // store previous phone state for management of sonification strategy below
426 int oldState = mPhoneState;
427 mPhoneState = state;
428 bool force = false;
429
430 // are we entering or starting a call
431 if (!isStateInCall(oldState) && isStateInCall(state)) {
432 ALOGV(" Entering call in setPhoneState()");
433 // force routing command to audio hardware when starting a call
434 // even if no device change is needed
435 force = true;
436 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
437 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
438 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
439 }
440 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
441 ALOGV(" Exiting call in setPhoneState()");
442 // force routing command to audio hardware when exiting a call
443 // even if no device change is needed
444 force = true;
445 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
446 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
447 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
448 }
449 } else if (isStateInCall(state) && (state != oldState)) {
450 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
451 // force routing command to audio hardware when switching between telephony and VoIP
452 // even if no device change is needed
453 force = true;
454 }
455
456 // check for device and output changes triggered by new phone state
Eric Laurent1c333e22014-05-20 10:48:17 -0700457 newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700458 checkA2dpSuspend();
459 checkOutputForAllStrategies();
460 updateDevicesAndOutputs();
461
Eric Laurent1f2f2232014-06-02 12:01:23 -0700462 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700463
464 // force routing command to audio hardware when ending call
465 // even if no device change is needed
466 if (isStateInCall(oldState) && newDevice == AUDIO_DEVICE_NONE) {
467 newDevice = hwOutputDesc->device();
468 }
469
470 int delayMs = 0;
471 if (isStateInCall(state)) {
472 nsecs_t sysTime = systemTime();
473 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700474 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700475 // mute media and sonification strategies and delay device switch by the largest
476 // latency of any output where either strategy is active.
477 // This avoid sending the ring tone or music tail into the earpiece or headset.
478 if ((desc->isStrategyActive(STRATEGY_MEDIA,
479 SONIFICATION_HEADSET_MUSIC_DELAY,
480 sysTime) ||
481 desc->isStrategyActive(STRATEGY_SONIFICATION,
482 SONIFICATION_HEADSET_MUSIC_DELAY,
483 sysTime)) &&
484 (delayMs < (int)desc->mLatency*2)) {
485 delayMs = desc->mLatency*2;
486 }
487 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
488 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
489 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
490 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
491 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
492 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
493 }
494 }
495
496 // change routing is necessary
497 setOutputDevice(mPrimaryOutput, newDevice, force, delayMs);
498
499 // if entering in call state, handle special case of active streams
500 // pertaining to sonification strategy see handleIncallSonification()
501 if (isStateInCall(state)) {
502 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700503 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
504 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700505 }
506 }
507
508 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700509 if (state == AUDIO_MODE_RINGTONE &&
510 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700511 mLimitRingtoneVolume = true;
512 } else {
513 mLimitRingtoneVolume = false;
514 }
515}
516
Eric Laurente0720872014-03-11 09:30:41 -0700517void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700518 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700519{
520 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
521
522 bool forceVolumeReeval = false;
523 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700524 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
525 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
526 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700527 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
528 return;
529 }
530 forceVolumeReeval = true;
531 mForceUse[usage] = config;
532 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700533 case AUDIO_POLICY_FORCE_FOR_MEDIA:
534 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
535 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
536 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
537 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Jungshik Jang0c943092014-07-08 22:11:24 +0900538 config != AUDIO_POLICY_FORCE_NO_BT_A2DP) {
Eric Laurente552edb2014-03-10 17:42:56 -0700539 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
540 return;
541 }
542 mForceUse[usage] = config;
543 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700544 case AUDIO_POLICY_FORCE_FOR_RECORD:
545 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
546 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700547 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
548 return;
549 }
550 mForceUse[usage] = config;
551 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700552 case AUDIO_POLICY_FORCE_FOR_DOCK:
553 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
554 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
555 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
556 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
557 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700558 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
559 }
560 forceVolumeReeval = true;
561 mForceUse[usage] = config;
562 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700563 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
564 if (config != AUDIO_POLICY_FORCE_NONE &&
565 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700566 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
567 }
568 forceVolumeReeval = true;
569 mForceUse[usage] = config;
570 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900571 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
572 if (config != AUDIO_POLICY_FORCE_NONE &&
573 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
574 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
575 }
576 mForceUse[usage] = config;
577 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700578 default:
579 ALOGW("setForceUse() invalid usage %d", usage);
580 break;
581 }
582
583 // check for device and output changes triggered by new force usage
584 checkA2dpSuspend();
585 checkOutputForAllStrategies();
586 updateDevicesAndOutputs();
587 for (size_t i = 0; i < mOutputs.size(); i++) {
588 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700589 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700590 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
591 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
592 applyStreamVolumes(output, newDevice, 0, true);
593 }
594 }
595
596 audio_io_handle_t activeInput = getActiveInput();
597 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700598 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700599 }
600
601}
602
Eric Laurente0720872014-03-11 09:30:41 -0700603audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700604{
605 return mForceUse[usage];
606}
607
Eric Laurente0720872014-03-11 09:30:41 -0700608void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700609{
610 ALOGV("setSystemProperty() property %s, value %s", property, value);
611}
612
613// Find a direct output profile compatible with the parameters passed, even if the input flags do
614// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700615sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700616 audio_devices_t device,
617 uint32_t samplingRate,
618 audio_format_t format,
619 audio_channel_mask_t channelMask,
620 audio_output_flags_t flags)
621{
622 for (size_t i = 0; i < mHwModules.size(); i++) {
623 if (mHwModules[i]->mHandle == 0) {
624 continue;
625 }
626 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700627 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Glenn Kastencbd48022014-07-24 13:46:44 -0700628 bool found = profile->isCompatibleProfile(device, samplingRate,
629 NULL /*updatedSamplingRate*/, format, channelMask,
630 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
631 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700632 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
633 return profile;
634 }
Eric Laurente552edb2014-03-10 17:42:56 -0700635 }
636 }
637 return 0;
638}
639
Eric Laurente0720872014-03-11 09:30:41 -0700640audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700641 uint32_t samplingRate,
642 audio_format_t format,
643 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700644 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700645 const audio_offload_info_t *offloadInfo)
646{
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700647
Eric Laurent3b73df72014-03-11 09:06:29 -0700648 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700649 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
650 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
651 device, stream, samplingRate, format, channelMask, flags);
652
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700653 return getOutputForDevice(device, stream, samplingRate,format, channelMask, flags,
654 offloadInfo);
655}
656
657audio_io_handle_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
658 uint32_t samplingRate,
659 audio_format_t format,
660 audio_channel_mask_t channelMask,
661 audio_output_flags_t flags,
662 const audio_offload_info_t *offloadInfo)
663{
664 if (attr == NULL) {
665 ALOGE("getOutputForAttr() called with NULL audio attributes");
666 return 0;
667 }
668 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s",
669 attr->usage, attr->content_type, attr->tags);
670
671 // TODO this is where filtering for custom policies (rerouting, dynamic sources) will go
672 routing_strategy strategy = (routing_strategy) getStrategyForAttr(attr);
673 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
674 ALOGV("getOutputForAttr() device %d, samplingRate %d, format %x, channelMask %x, flags %x",
675 device, samplingRate, format, channelMask, flags);
676
677 audio_stream_type_t stream = streamTypefromAttributesInt(attr);
678 return getOutputForDevice(device, stream, samplingRate, format, channelMask, flags,
679 offloadInfo);
680}
681
682audio_io_handle_t AudioPolicyManager::getOutputForDevice(
683 audio_devices_t device,
684 audio_stream_type_t stream,
685 uint32_t samplingRate,
686 audio_format_t format,
687 audio_channel_mask_t channelMask,
688 audio_output_flags_t flags,
689 const audio_offload_info_t *offloadInfo)
690{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700691 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700692 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700693 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700694
Eric Laurente552edb2014-03-10 17:42:56 -0700695#ifdef AUDIO_POLICY_TEST
696 if (mCurOutput != 0) {
697 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
698 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
699
700 if (mTestOutputs[mCurOutput] == 0) {
701 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -0700702 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -0700703 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -0700704 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -0700705 outputDesc->mFlags =
706 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -0700707 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700708 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
709 config.sample_rate = mTestSamplingRate;
710 config.channel_mask = mTestChannels;
711 config.format = mTestFormat;
712 config.offload_info = *offloadInfo;
713 status = mpClientInterface->openOutput(0,
714 &mTestOutputs[mCurOutput],
715 &config,
716 &outputDesc->mDevice,
717 String8(""),
718 &outputDesc->mLatency,
719 outputDesc->mFlags);
720 if (status == NO_ERROR) {
721 outputDesc->mSamplingRate = config.sample_rate;
722 outputDesc->mFormat = config.format;
723 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -0700724 AudioParameter outputCmd = AudioParameter();
725 outputCmd.addInt(String8("set_id"),mCurOutput);
726 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
727 addOutput(mTestOutputs[mCurOutput], outputDesc);
728 }
729 }
730 return mTestOutputs[mCurOutput];
731 }
732#endif //AUDIO_POLICY_TEST
733
734 // open a direct output if required by specified parameters
735 //force direct flag if offload flag is set: offloading implies a direct output stream
736 // and all common behaviors are driven by checking only the direct flag
737 // this should normally be set appropriately in the policy configuration file
738 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700739 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -0700740 }
741
742 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
743 // creating an offloaded track and tearing it down immediately after start when audioflinger
744 // detects there is an active non offloadable effect.
745 // FIXME: We should check the audio session here but we do not have it in this context.
746 // This may prevent offloading in rare situations where effects are left active by apps
747 // in the background.
Eric Laurent1c333e22014-05-20 10:48:17 -0700748 sp<IOProfile> profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700749 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
750 !isNonOffloadableEffectEnabled()) {
751 profile = getProfileForDirectOutput(device,
752 samplingRate,
753 format,
754 channelMask,
755 (audio_output_flags_t)flags);
756 }
757
Eric Laurent1c333e22014-05-20 10:48:17 -0700758 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700759 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -0700760
761 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700762 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700763 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
764 outputDesc = desc;
765 // reuse direct output if currently open and configured with same parameters
766 if ((samplingRate == outputDesc->mSamplingRate) &&
767 (format == outputDesc->mFormat) &&
768 (channelMask == outputDesc->mChannelMask)) {
769 outputDesc->mDirectOpenCount++;
770 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
771 return mOutputs.keyAt(i);
772 }
773 }
774 }
775 // close direct output if currently open and configured with different parameters
776 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700777 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -0700778 }
779 outputDesc = new AudioOutputDescriptor(profile);
780 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -0700781 outputDesc->mLatency = 0;
782 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700783 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
784 config.sample_rate = samplingRate;
785 config.channel_mask = channelMask;
786 config.format = format;
787 config.offload_info = *offloadInfo;
788 status = mpClientInterface->openOutput(profile->mModule->mHandle,
789 &output,
790 &config,
791 &outputDesc->mDevice,
792 String8(""),
793 &outputDesc->mLatency,
794 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -0700795
796 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -0700797 if (status != NO_ERROR ||
798 (samplingRate != 0 && samplingRate != config.sample_rate) ||
799 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
800 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700801 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
802 "format %d %d, channelMask %04x %04x", output, samplingRate,
803 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
804 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -0700805 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700806 mpClientInterface->closeOutput(output);
807 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700808 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -0700809 }
Eric Laurentcf2c0212014-07-25 16:20:43 -0700810 outputDesc->mSamplingRate = config.sample_rate;
811 outputDesc->mChannelMask = config.channel_mask;
812 outputDesc->mFormat = config.format;
813 outputDesc->mRefCount[stream] = 0;
814 outputDesc->mStopTime[stream] = 0;
815 outputDesc->mDirectOpenCount = 1;
816
Eric Laurente552edb2014-03-10 17:42:56 -0700817 audio_io_handle_t srcOutput = getOutputForEffect();
818 addOutput(output, outputDesc);
819 audio_io_handle_t dstOutput = getOutputForEffect();
820 if (dstOutput == output) {
821 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
822 }
823 mPreviousOutputs = mOutputs;
824 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -0700825 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700826 return output;
827 }
828
829 // ignoring channel mask due to downmix capability in mixer
830
831 // open a non direct output
832
833 // for non direct outputs, only PCM is supported
834 if (audio_is_linear_pcm(format)) {
835 // get which output is suitable for the specified stream. The actual
836 // routing change will happen when startOutput() will be called
837 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
838
839 output = selectOutput(outputs, flags);
840 }
841 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
842 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
843
844 ALOGV("getOutput() returns output %d", output);
845
846 return output;
847}
848
Eric Laurente0720872014-03-11 09:30:41 -0700849audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3b73df72014-03-11 09:06:29 -0700850 audio_output_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -0700851{
852 // select one output among several that provide a path to a particular device or set of
853 // devices (the list was previously build by getOutputsForDevice()).
854 // The priority is as follows:
855 // 1: the output with the highest number of requested policy flags
856 // 2: the primary output
857 // 3: the first output in the list
858
859 if (outputs.size() == 0) {
860 return 0;
861 }
862 if (outputs.size() == 1) {
863 return outputs[0];
864 }
865
866 int maxCommonFlags = 0;
867 audio_io_handle_t outputFlags = 0;
868 audio_io_handle_t outputPrimary = 0;
869
870 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700871 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700872 if (!outputDesc->isDuplicated()) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700873 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -0700874 if (commonFlags > maxCommonFlags) {
875 outputFlags = outputs[i];
876 maxCommonFlags = commonFlags;
877 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
878 }
879 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
880 outputPrimary = outputs[i];
881 }
882 }
883 }
884
885 if (outputFlags != 0) {
886 return outputFlags;
887 }
888 if (outputPrimary != 0) {
889 return outputPrimary;
890 }
891
892 return outputs[0];
893}
894
Eric Laurente0720872014-03-11 09:30:41 -0700895status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700896 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700897 int session)
898{
899 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
900 ssize_t index = mOutputs.indexOfKey(output);
901 if (index < 0) {
902 ALOGW("startOutput() unknown output %d", output);
903 return BAD_VALUE;
904 }
905
Eric Laurent1f2f2232014-06-02 12:01:23 -0700906 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700907
908 // increment usage count for this stream on the requested output:
909 // NOTE that the usage count is the same for duplicated output and hardware output which is
910 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
911 outputDesc->changeRefCount(stream, 1);
912
913 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700914 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700915 routing_strategy strategy = getStrategy(stream);
916 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
917 (strategy == STRATEGY_SONIFICATION_RESPECTFUL);
918 uint32_t waitMs = 0;
919 bool force = false;
920 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700921 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700922 if (desc != outputDesc) {
923 // force a device change if any other output is managed by the same hw
924 // module and has a current device selection that differs from selected device.
925 // In this case, the audio HAL must receive the new device selection so that it can
926 // change the device currently selected by the other active output.
927 if (outputDesc->sharesHwModuleWith(desc) &&
928 desc->device() != newDevice) {
929 force = true;
930 }
931 // wait for audio on other active outputs to be presented when starting
932 // a notification so that audio focus effect can propagate.
933 uint32_t latency = desc->latency();
934 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
935 waitMs = latency;
936 }
937 }
938 }
939 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
940
941 // handle special case for sonification while in call
942 if (isInCall()) {
943 handleIncallSonification(stream, true, false);
944 }
945
946 // apply volume rules for current stream and device if necessary
947 checkAndSetVolume(stream,
948 mStreams[stream].getVolumeIndex(newDevice),
949 output,
950 newDevice);
951
952 // update the outputs if starting an output with a stream that can affect notification
953 // routing
954 handleNotificationRoutingForStream(stream);
955 if (waitMs > muteWaitMs) {
956 usleep((waitMs - muteWaitMs) * 2 * 1000);
957 }
958 }
959 return NO_ERROR;
960}
961
962
Eric Laurente0720872014-03-11 09:30:41 -0700963status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -0700964 audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700965 int session)
966{
967 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
968 ssize_t index = mOutputs.indexOfKey(output);
969 if (index < 0) {
970 ALOGW("stopOutput() unknown output %d", output);
971 return BAD_VALUE;
972 }
973
Eric Laurent1f2f2232014-06-02 12:01:23 -0700974 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -0700975
976 // handle special case for sonification while in call
977 if (isInCall()) {
978 handleIncallSonification(stream, false, false);
979 }
980
981 if (outputDesc->mRefCount[stream] > 0) {
982 // decrement usage count of this stream on the output
983 outputDesc->changeRefCount(stream, -1);
984 // store time at which the stream was stopped - see isStreamActive()
985 if (outputDesc->mRefCount[stream] == 0) {
986 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -0700987 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -0700988 // delay the device switch by twice the latency because stopOutput() is executed when
989 // the track stop() command is received and at that time the audio track buffer can
990 // still contain data that needs to be drained. The latency only covers the audio HAL
991 // and kernel buffers. Also the latency does not always include additional delay in the
992 // audio path (audio DSP, CODEC ...)
993 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
994
995 // force restoring the device selection on other active outputs if it differs from the
996 // one being selected for this output
997 for (size_t i = 0; i < mOutputs.size(); i++) {
998 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -0700999 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001000 if (curOutput != output &&
1001 desc->isActive() &&
1002 outputDesc->sharesHwModuleWith(desc) &&
1003 (newDevice != desc->device())) {
1004 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001005 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001006 true,
1007 outputDesc->mLatency*2);
1008 }
1009 }
1010 // update the outputs if stopping one with a stream that can affect notification routing
1011 handleNotificationRoutingForStream(stream);
1012 }
1013 return NO_ERROR;
1014 } else {
1015 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1016 return INVALID_OPERATION;
1017 }
1018}
1019
Eric Laurente0720872014-03-11 09:30:41 -07001020void AudioPolicyManager::releaseOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07001021{
1022 ALOGV("releaseOutput() %d", output);
1023 ssize_t index = mOutputs.indexOfKey(output);
1024 if (index < 0) {
1025 ALOGW("releaseOutput() releasing unknown output %d", output);
1026 return;
1027 }
1028
1029#ifdef AUDIO_POLICY_TEST
1030 int testIndex = testOutputIndex(output);
1031 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001032 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001033 if (outputDesc->isActive()) {
1034 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001035 mOutputs.removeItem(output);
1036 mTestOutputs[testIndex] = 0;
1037 }
1038 return;
1039 }
1040#endif //AUDIO_POLICY_TEST
1041
Eric Laurent1f2f2232014-06-02 12:01:23 -07001042 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001043 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001044 if (desc->mDirectOpenCount <= 0) {
1045 ALOGW("releaseOutput() invalid open count %d for output %d",
1046 desc->mDirectOpenCount, output);
1047 return;
1048 }
1049 if (--desc->mDirectOpenCount == 0) {
1050 closeOutput(output);
1051 // If effects where present on the output, audioflinger moved them to the primary
1052 // output by default: move them back to the appropriate output.
1053 audio_io_handle_t dstOutput = getOutputForEffect();
1054 if (dstOutput != mPrimaryOutput) {
1055 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1056 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001057 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001058 }
1059 }
1060}
1061
1062
Eric Laurente0720872014-03-11 09:30:41 -07001063audio_io_handle_t AudioPolicyManager::getInput(audio_source_t inputSource,
Eric Laurente552edb2014-03-10 17:42:56 -07001064 uint32_t samplingRate,
1065 audio_format_t format,
1066 audio_channel_mask_t channelMask,
Eric Laurent4dc68062014-07-28 17:26:49 -07001067 audio_session_t session,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001068 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07001069{
Eric Laurent4dc68062014-07-28 17:26:49 -07001070 ALOGV("getInput() inputSource %d, samplingRate %d, format %d, channelMask %x, session %d, "
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001071 "flags %#x",
Eric Laurent4dc68062014-07-28 17:26:49 -07001072 inputSource, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001073
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001074 audio_devices_t device = getDeviceForInputSource(inputSource);
Eric Laurente552edb2014-03-10 17:42:56 -07001075
1076 if (device == AUDIO_DEVICE_NONE) {
1077 ALOGW("getInput() could not find device for inputSource %d", inputSource);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001078 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001079 }
1080
1081 // adapt channel selection to input source
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001082 switch (inputSource) {
Eric Laurente552edb2014-03-10 17:42:56 -07001083 case AUDIO_SOURCE_VOICE_UPLINK:
1084 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1085 break;
1086 case AUDIO_SOURCE_VOICE_DOWNLINK:
1087 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1088 break;
1089 case AUDIO_SOURCE_VOICE_CALL:
1090 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1091 break;
1092 default:
1093 break;
1094 }
1095
Eric Laurent1c333e22014-05-20 10:48:17 -07001096 sp<IOProfile> profile = getInputProfile(device,
Eric Laurente552edb2014-03-10 17:42:56 -07001097 samplingRate,
1098 format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001099 channelMask,
1100 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001101 if (profile == 0) {
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001102 ALOGW("getInput() could not find profile for device 0x%X, samplingRate %u, format %#x, "
1103 "channelMask 0x%X, flags %#x",
1104 device, samplingRate, format, channelMask, flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001105 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001106 }
1107
1108 if (profile->mModule->mHandle == 0) {
1109 ALOGE("getInput(): HW module %s not opened", profile->mModule->mName);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001110 return AUDIO_IO_HANDLE_NONE;
1111 }
1112
1113 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1114 config.sample_rate = samplingRate;
1115 config.channel_mask = channelMask;
1116 config.format = format;
1117 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
1118 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
1119 &input,
1120 &config,
1121 &device,
1122 String8(""),
1123 inputSource,
1124 flags);
1125
1126 // only accept input with the exact requested set of parameters
1127 if (status != NO_ERROR ||
1128 (samplingRate != config.sample_rate) ||
1129 (format != config.format) ||
1130 (channelMask != config.channel_mask)) {
1131 ALOGW("getInput() failed opening input: samplingRate %d, format %d, channelMask %x",
1132 samplingRate, format, channelMask);
1133 if (input != AUDIO_IO_HANDLE_NONE) {
1134 mpClientInterface->closeInput(input);
1135 }
1136 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001137 }
1138
Eric Laurent1f2f2232014-06-02 12:01:23 -07001139 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07001140 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001141 inputDesc->mRefCount = 0;
1142 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001143 inputDesc->mSamplingRate = samplingRate;
1144 inputDesc->mFormat = format;
1145 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001146 inputDesc->mDevice = device;
Eric Laurent4dc68062014-07-28 17:26:49 -07001147 inputDesc->mSessions.add(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001148
Eric Laurentd4692962014-05-05 18:13:44 -07001149 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001150 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001151 return input;
1152}
1153
Eric Laurent4dc68062014-07-28 17:26:49 -07001154status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1155 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001156{
1157 ALOGV("startInput() input %d", input);
1158 ssize_t index = mInputs.indexOfKey(input);
1159 if (index < 0) {
1160 ALOGW("startInput() unknown input %d", input);
1161 return BAD_VALUE;
1162 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001163 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001164
Eric Laurent4dc68062014-07-28 17:26:49 -07001165 index = inputDesc->mSessions.indexOf(session);
1166 if (index < 0) {
1167 ALOGW("startInput() unknown session %d on input %d", session, input);
1168 return BAD_VALUE;
1169 }
1170
Glenn Kasten74a8e252014-07-24 14:09:55 -07001171 // virtual input devices are compatible with other input devices
1172 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1173
1174 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001175 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001176 if (activeInput != 0 && activeInput != input) {
1177
1178 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1179 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001180 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001181 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001182 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurent4dc68062014-07-28 17:26:49 -07001183 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1184 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001185 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001186 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001187 return INVALID_OPERATION;
1188 }
1189 }
1190 }
1191
Glenn Kasten74a8e252014-07-24 14:09:55 -07001192 if (inputDesc->mRefCount == 0) {
1193 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001194
Glenn Kasten74a8e252014-07-24 14:09:55 -07001195 // Automatically enable the remote submix output when input is started.
1196 // For remote submix (a virtual device), we open only one input per capture request.
1197 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1198 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
1199 AUDIO_POLICY_DEVICE_STATE_AVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
1200 }
Eric Laurente552edb2014-03-10 17:42:56 -07001201 }
1202
Eric Laurente552edb2014-03-10 17:42:56 -07001203 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1204
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001205 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001206 return NO_ERROR;
1207}
1208
Eric Laurent4dc68062014-07-28 17:26:49 -07001209status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1210 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001211{
1212 ALOGV("stopInput() input %d", input);
1213 ssize_t index = mInputs.indexOfKey(input);
1214 if (index < 0) {
1215 ALOGW("stopInput() unknown input %d", input);
1216 return BAD_VALUE;
1217 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001218 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001219
Eric Laurent4dc68062014-07-28 17:26:49 -07001220 index = inputDesc->mSessions.indexOf(session);
1221 if (index < 0) {
1222 ALOGW("stopInput() unknown session %d on input %d", session, input);
1223 return BAD_VALUE;
1224 }
1225
Eric Laurente552edb2014-03-10 17:42:56 -07001226 if (inputDesc->mRefCount == 0) {
1227 ALOGW("stopInput() input %d already stopped", input);
1228 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001229 }
1230
1231 inputDesc->mRefCount--;
1232 if (inputDesc->mRefCount == 0) {
1233
Eric Laurente552edb2014-03-10 17:42:56 -07001234 // automatically disable the remote submix output when input is stopped
1235 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
1236 setDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent3b73df72014-03-11 09:06:29 -07001237 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE, AUDIO_REMOTE_SUBMIX_DEVICE_ADDRESS);
Eric Laurente552edb2014-03-10 17:42:56 -07001238 }
1239
Eric Laurent1c333e22014-05-20 10:48:17 -07001240 resetInputDevice(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001241 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001242 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001243}
1244
Eric Laurent4dc68062014-07-28 17:26:49 -07001245void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1246 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001247{
1248 ALOGV("releaseInput() %d", input);
1249 ssize_t index = mInputs.indexOfKey(input);
1250 if (index < 0) {
1251 ALOGW("releaseInput() releasing unknown input %d", input);
1252 return;
1253 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001254 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1255 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001256
1257 index = inputDesc->mSessions.indexOf(session);
1258 if (index < 0) {
1259 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1260 return;
1261 }
1262 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001263 if (inputDesc->mOpenRefCount == 0) {
1264 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1265 return;
1266 }
1267 inputDesc->mOpenRefCount--;
1268 if (inputDesc->mOpenRefCount > 0) {
1269 ALOGV("releaseInput() exit > 0");
1270 return;
1271 }
1272
Eric Laurente552edb2014-03-10 17:42:56 -07001273 mpClientInterface->closeInput(input);
Eric Laurente552edb2014-03-10 17:42:56 -07001274 mInputs.removeItem(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07001275 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07001276 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001277 ALOGV("releaseInput() exit");
1278}
1279
Eric Laurentd4692962014-05-05 18:13:44 -07001280void AudioPolicyManager::closeAllInputs() {
1281 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
1282 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1283 }
1284 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001285 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07001286}
1287
Eric Laurente0720872014-03-11 09:30:41 -07001288void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001289 int indexMin,
1290 int indexMax)
1291{
1292 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1293 if (indexMin < 0 || indexMin >= indexMax) {
1294 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1295 return;
1296 }
1297 mStreams[stream].mIndexMin = indexMin;
1298 mStreams[stream].mIndexMax = indexMax;
1299}
1300
Eric Laurente0720872014-03-11 09:30:41 -07001301status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001302 int index,
1303 audio_devices_t device)
1304{
1305
1306 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1307 return BAD_VALUE;
1308 }
1309 if (!audio_is_output_device(device)) {
1310 return BAD_VALUE;
1311 }
1312
1313 // Force max volume if stream cannot be muted
1314 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1315
1316 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1317 stream, device, index);
1318
1319 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1320 // clear all device specific values
1321 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1322 mStreams[stream].mIndexCur.clear();
1323 }
1324 mStreams[stream].mIndexCur.add(device, index);
1325
1326 // compute and apply stream volume on all outputs according to connected device
1327 status_t status = NO_ERROR;
1328 for (size_t i = 0; i < mOutputs.size(); i++) {
1329 audio_devices_t curDevice =
1330 getDeviceForVolume(mOutputs.valueAt(i)->device());
1331 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || (device == curDevice)) {
1332 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1333 if (volStatus != NO_ERROR) {
1334 status = volStatus;
1335 }
1336 }
1337 }
1338 return status;
1339}
1340
Eric Laurente0720872014-03-11 09:30:41 -07001341status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001342 int *index,
1343 audio_devices_t device)
1344{
1345 if (index == NULL) {
1346 return BAD_VALUE;
1347 }
1348 if (!audio_is_output_device(device)) {
1349 return BAD_VALUE;
1350 }
1351 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1352 // the strategy the stream belongs to.
1353 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1354 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1355 }
1356 device = getDeviceForVolume(device);
1357
1358 *index = mStreams[stream].getVolumeIndex(device);
1359 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1360 return NO_ERROR;
1361}
1362
Eric Laurente0720872014-03-11 09:30:41 -07001363audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001364 const SortedVector<audio_io_handle_t>& outputs)
1365{
1366 // select one output among several suitable for global effects.
1367 // The priority is as follows:
1368 // 1: An offloaded output. If the effect ends up not being offloadable,
1369 // AudioFlinger will invalidate the track and the offloaded output
1370 // will be closed causing the effect to be moved to a PCM output.
1371 // 2: A deep buffer output
1372 // 3: the first output in the list
1373
1374 if (outputs.size() == 0) {
1375 return 0;
1376 }
1377
1378 audio_io_handle_t outputOffloaded = 0;
1379 audio_io_handle_t outputDeepBuffer = 0;
1380
1381 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001382 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001383 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001384 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1385 outputOffloaded = outputs[i];
1386 }
1387 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1388 outputDeepBuffer = outputs[i];
1389 }
1390 }
1391
1392 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1393 outputOffloaded, outputDeepBuffer);
1394 if (outputOffloaded != 0) {
1395 return outputOffloaded;
1396 }
1397 if (outputDeepBuffer != 0) {
1398 return outputDeepBuffer;
1399 }
1400
1401 return outputs[0];
1402}
1403
Eric Laurente0720872014-03-11 09:30:41 -07001404audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001405{
1406 // apply simple rule where global effects are attached to the same output as MUSIC streams
1407
Eric Laurent3b73df72014-03-11 09:06:29 -07001408 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001409 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1410 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1411
1412 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1413 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1414 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1415
1416 return output;
1417}
1418
Eric Laurente0720872014-03-11 09:30:41 -07001419status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001420 audio_io_handle_t io,
1421 uint32_t strategy,
1422 int session,
1423 int id)
1424{
1425 ssize_t index = mOutputs.indexOfKey(io);
1426 if (index < 0) {
1427 index = mInputs.indexOfKey(io);
1428 if (index < 0) {
1429 ALOGW("registerEffect() unknown io %d", io);
1430 return INVALID_OPERATION;
1431 }
1432 }
1433
1434 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1435 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1436 desc->name, desc->memoryUsage);
1437 return INVALID_OPERATION;
1438 }
1439 mTotalEffectsMemory += desc->memoryUsage;
1440 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1441 desc->name, io, strategy, session, id);
1442 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1443
Eric Laurent1f2f2232014-06-02 12:01:23 -07001444 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1445 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1446 effectDesc->mIo = io;
1447 effectDesc->mStrategy = (routing_strategy)strategy;
1448 effectDesc->mSession = session;
1449 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001450
Eric Laurent1f2f2232014-06-02 12:01:23 -07001451 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001452
1453 return NO_ERROR;
1454}
1455
Eric Laurente0720872014-03-11 09:30:41 -07001456status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001457{
1458 ssize_t index = mEffects.indexOfKey(id);
1459 if (index < 0) {
1460 ALOGW("unregisterEffect() unknown effect ID %d", id);
1461 return INVALID_OPERATION;
1462 }
1463
Eric Laurent1f2f2232014-06-02 12:01:23 -07001464 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001465
Eric Laurent1f2f2232014-06-02 12:01:23 -07001466 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001467
Eric Laurent1f2f2232014-06-02 12:01:23 -07001468 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001469 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001470 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1471 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001472 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001473 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07001474 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001475 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07001476
1477 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07001478
1479 return NO_ERROR;
1480}
1481
Eric Laurente0720872014-03-11 09:30:41 -07001482status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001483{
1484 ssize_t index = mEffects.indexOfKey(id);
1485 if (index < 0) {
1486 ALOGW("unregisterEffect() unknown effect ID %d", id);
1487 return INVALID_OPERATION;
1488 }
1489
1490 return setEffectEnabled(mEffects.valueAt(index), enabled);
1491}
1492
Eric Laurent1f2f2232014-06-02 12:01:23 -07001493status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07001494{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001495 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07001496 ALOGV("setEffectEnabled(%s) effect already %s",
1497 enabled?"true":"false", enabled?"enabled":"disabled");
1498 return INVALID_OPERATION;
1499 }
1500
1501 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001502 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07001503 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001504 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07001505 return INVALID_OPERATION;
1506 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001507 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001508 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
1509 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001510 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07001511 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001512 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
1513 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001514 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001515 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07001516 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
1517 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001518 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07001519 return NO_ERROR;
1520}
1521
Eric Laurente0720872014-03-11 09:30:41 -07001522bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07001523{
1524 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001525 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
1526 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
1527 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001528 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001529 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07001530 return true;
1531 }
1532 }
1533 return false;
1534}
1535
Eric Laurente0720872014-03-11 09:30:41 -07001536bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001537{
1538 nsecs_t sysTime = systemTime();
1539 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001540 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07001541 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001542 return true;
1543 }
1544 }
1545 return false;
1546}
1547
Eric Laurente0720872014-03-11 09:30:41 -07001548bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07001549 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07001550{
1551 nsecs_t sysTime = systemTime();
1552 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001553 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001554 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07001555 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001556 return true;
1557 }
1558 }
1559 return false;
1560}
1561
Eric Laurente0720872014-03-11 09:30:41 -07001562bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07001563{
1564 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001565 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001566 if ((inputDescriptor->mInputSource == (int)source ||
Eric Laurent3b73df72014-03-11 09:06:29 -07001567 (source == AUDIO_SOURCE_VOICE_RECOGNITION &&
Eric Laurente552edb2014-03-10 17:42:56 -07001568 inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD))
1569 && (inputDescriptor->mRefCount > 0)) {
1570 return true;
1571 }
1572 }
1573 return false;
1574}
1575
1576
Eric Laurente0720872014-03-11 09:30:41 -07001577status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07001578{
1579 const size_t SIZE = 256;
1580 char buffer[SIZE];
1581 String8 result;
1582
1583 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
1584 result.append(buffer);
1585
1586 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
1587 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001588 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
1589 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001590 snprintf(buffer, SIZE, " Force use for communications %d\n",
1591 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07001592 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001593 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07001594 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001595 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07001596 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001597 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07001598 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07001599 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07001600 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09001601 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
1602 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
1603 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07001604
Eric Laurent3a4311c2014-03-17 12:00:47 -07001605 snprintf(buffer, SIZE, " Available output devices:\n");
1606 result.append(buffer);
1607 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07001608 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001609 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001610 }
1611 snprintf(buffer, SIZE, "\n Available input devices:\n");
1612 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07001613 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07001614 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07001615 }
Eric Laurente552edb2014-03-10 17:42:56 -07001616
1617 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
1618 write(fd, buffer, strlen(buffer));
1619 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001620 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07001621 write(fd, buffer, strlen(buffer));
1622 mHwModules[i]->dump(fd);
1623 }
1624
1625 snprintf(buffer, SIZE, "\nOutputs dump:\n");
1626 write(fd, buffer, strlen(buffer));
1627 for (size_t i = 0; i < mOutputs.size(); i++) {
1628 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
1629 write(fd, buffer, strlen(buffer));
1630 mOutputs.valueAt(i)->dump(fd);
1631 }
1632
1633 snprintf(buffer, SIZE, "\nInputs dump:\n");
1634 write(fd, buffer, strlen(buffer));
1635 for (size_t i = 0; i < mInputs.size(); i++) {
1636 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
1637 write(fd, buffer, strlen(buffer));
1638 mInputs.valueAt(i)->dump(fd);
1639 }
1640
1641 snprintf(buffer, SIZE, "\nStreams dump:\n");
1642 write(fd, buffer, strlen(buffer));
1643 snprintf(buffer, SIZE,
1644 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
1645 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001646 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07001647 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07001648 write(fd, buffer, strlen(buffer));
1649 mStreams[i].dump(fd);
1650 }
1651
1652 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
1653 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
1654 write(fd, buffer, strlen(buffer));
1655
1656 snprintf(buffer, SIZE, "Registered effects:\n");
1657 write(fd, buffer, strlen(buffer));
1658 for (size_t i = 0; i < mEffects.size(); i++) {
1659 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
1660 write(fd, buffer, strlen(buffer));
1661 mEffects.valueAt(i)->dump(fd);
1662 }
1663
1664
1665 return NO_ERROR;
1666}
1667
1668// This function checks for the parameters which can be offloaded.
1669// This can be enhanced depending on the capability of the DSP and policy
1670// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07001671bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07001672{
1673 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07001674 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07001675 offloadInfo.sample_rate, offloadInfo.channel_mask,
1676 offloadInfo.format,
1677 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
1678 offloadInfo.has_video);
1679
1680 // Check if offload has been disabled
1681 char propValue[PROPERTY_VALUE_MAX];
1682 if (property_get("audio.offload.disable", propValue, "0")) {
1683 if (atoi(propValue) != 0) {
1684 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
1685 return false;
1686 }
1687 }
1688
1689 // Check if stream type is music, then only allow offload as of now.
1690 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
1691 {
1692 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
1693 return false;
1694 }
1695
1696 //TODO: enable audio offloading with video when ready
1697 if (offloadInfo.has_video)
1698 {
1699 ALOGV("isOffloadSupported: has_video == true, returning false");
1700 return false;
1701 }
1702
1703 //If duration is less than minimum value defined in property, return false
1704 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
1705 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
1706 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
1707 return false;
1708 }
1709 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
1710 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
1711 return false;
1712 }
1713
1714 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1715 // creating an offloaded track and tearing it down immediately after start when audioflinger
1716 // detects there is an active non offloadable effect.
1717 // FIXME: We should check the audio session here but we do not have it in this context.
1718 // This may prevent offloading in rare situations where effects are left active by apps
1719 // in the background.
1720 if (isNonOffloadableEffectEnabled()) {
1721 return false;
1722 }
1723
1724 // See if there is a profile to support this.
1725 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07001726 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07001727 offloadInfo.sample_rate,
1728 offloadInfo.format,
1729 offloadInfo.channel_mask,
1730 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07001731 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
1732 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001733}
1734
Eric Laurent6a94d692014-05-20 11:18:06 -07001735status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
1736 audio_port_type_t type,
1737 unsigned int *num_ports,
1738 struct audio_port *ports,
1739 unsigned int *generation)
1740{
1741 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
1742 generation == NULL) {
1743 return BAD_VALUE;
1744 }
1745 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
1746 if (ports == NULL) {
1747 *num_ports = 0;
1748 }
1749
1750 size_t portsWritten = 0;
1751 size_t portsMax = *num_ports;
1752 *num_ports = 0;
1753 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
1754 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1755 for (size_t i = 0;
1756 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
1757 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
1758 }
1759 *num_ports += mAvailableOutputDevices.size();
1760 }
1761 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
1762 for (size_t i = 0;
1763 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
1764 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
1765 }
1766 *num_ports += mAvailableInputDevices.size();
1767 }
1768 }
1769 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
1770 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
1771 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
1772 mInputs[i]->toAudioPort(&ports[portsWritten++]);
1773 }
1774 *num_ports += mInputs.size();
1775 }
1776 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07001777 size_t numOutputs = 0;
1778 for (size_t i = 0; i < mOutputs.size(); i++) {
1779 if (!mOutputs[i]->isDuplicated()) {
1780 numOutputs++;
1781 if (portsWritten < portsMax) {
1782 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
1783 }
1784 }
Eric Laurent6a94d692014-05-20 11:18:06 -07001785 }
Eric Laurent84c70242014-06-23 08:46:27 -07001786 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07001787 }
1788 }
1789 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07001790 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07001791 return NO_ERROR;
1792}
1793
1794status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
1795{
1796 return NO_ERROR;
1797}
1798
Eric Laurent1f2f2232014-06-02 12:01:23 -07001799sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001800 audio_port_handle_t id) const
1801{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001802 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001803 for (size_t i = 0; i < mOutputs.size(); i++) {
1804 outputDesc = mOutputs.valueAt(i);
1805 if (outputDesc->mId == id) {
1806 break;
1807 }
1808 }
1809 return outputDesc;
1810}
1811
Eric Laurent1f2f2232014-06-02 12:01:23 -07001812sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07001813 audio_port_handle_t id) const
1814{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001815 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07001816 for (size_t i = 0; i < mInputs.size(); i++) {
1817 inputDesc = mInputs.valueAt(i);
1818 if (inputDesc->mId == id) {
1819 break;
1820 }
1821 }
1822 return inputDesc;
1823}
1824
Eric Laurent1f2f2232014-06-02 12:01:23 -07001825sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
1826 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07001827{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001828 sp <HwModule> module;
1829
Eric Laurent6a94d692014-05-20 11:18:06 -07001830 for (size_t i = 0; i < mHwModules.size(); i++) {
1831 if (mHwModules[i]->mHandle == 0) {
1832 continue;
1833 }
1834 if (audio_is_output_device(device)) {
1835 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
1836 {
1837 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
1838 return mHwModules[i];
1839 }
1840 }
1841 } else {
1842 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
1843 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
1844 device & ~AUDIO_DEVICE_BIT_IN) {
1845 return mHwModules[i];
1846 }
1847 }
1848 }
1849 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001850 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07001851}
1852
Eric Laurent1f2f2232014-06-02 12:01:23 -07001853sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07001854{
Eric Laurent1f2f2232014-06-02 12:01:23 -07001855 sp <HwModule> module;
1856
Eric Laurent1afeecb2014-05-14 08:52:28 -07001857 for (size_t i = 0; i < mHwModules.size(); i++)
1858 {
1859 if (strcmp(mHwModules[i]->mName, name) == 0) {
1860 return mHwModules[i];
1861 }
1862 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001863 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07001864}
1865
1866
Eric Laurent6a94d692014-05-20 11:18:06 -07001867status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
1868 audio_patch_handle_t *handle,
1869 uid_t uid)
1870{
1871 ALOGV("createAudioPatch()");
1872
1873 if (handle == NULL || patch == NULL) {
1874 return BAD_VALUE;
1875 }
1876 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
1877
1878 if (patch->num_sources > 1 || patch->num_sinks > 1) {
1879 return INVALID_OPERATION;
1880 }
1881 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE ||
1882 patch->sinks[0].role != AUDIO_PORT_ROLE_SINK) {
1883 return INVALID_OPERATION;
1884 }
1885
1886 sp<AudioPatch> patchDesc;
1887 ssize_t index = mAudioPatches.indexOfKey(*handle);
1888
1889 ALOGV("createAudioPatch sink id %d role %d type %d", patch->sinks[0].id, patch->sinks[0].role,
1890 patch->sinks[0].type);
1891 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
1892 patch->sources[0].role,
1893 patch->sources[0].type);
1894
1895 if (index >= 0) {
1896 patchDesc = mAudioPatches.valueAt(index);
1897 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
1898 mUidCached, patchDesc->mUid, uid);
1899 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
1900 return INVALID_OPERATION;
1901 }
1902 } else {
1903 *handle = 0;
1904 }
1905
1906 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
1907 // TODO add support for mix to mix connection
1908 if (patch->sinks[0].type != AUDIO_PORT_TYPE_DEVICE) {
1909 ALOGV("createAudioPatch() source mix sink not device");
1910 return BAD_VALUE;
1911 }
1912 // output mix to output device connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001913 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001914 if (outputDesc == NULL) {
1915 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
1916 return BAD_VALUE;
1917 }
Eric Laurent84c70242014-06-23 08:46:27 -07001918 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
1919 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001920 if (patchDesc != 0) {
1921 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
1922 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
1923 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
1924 return BAD_VALUE;
1925 }
1926 }
1927 sp<DeviceDescriptor> devDesc =
1928 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
1929 if (devDesc == 0) {
1930 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[0].id);
1931 return BAD_VALUE;
1932 }
1933
Eric Laurent84c70242014-06-23 08:46:27 -07001934 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001935 patch->sources[0].sample_rate,
Glenn Kastencbd48022014-07-24 13:46:44 -07001936 NULL, // updatedSamplingRate
Eric Laurent6a94d692014-05-20 11:18:06 -07001937 patch->sources[0].format,
1938 patch->sources[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001939 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
Eric Laurent83b88082014-06-20 18:31:16 -07001940 ALOGV("createAudioPatch() profile not supported");
Eric Laurent6a94d692014-05-20 11:18:06 -07001941 return INVALID_OPERATION;
1942 }
1943 // TODO: reconfigure output format and channels here
1944 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001945 devDesc->mDeviceType, outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001946 setOutputDevice(outputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001947 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001948 true,
1949 0,
1950 handle);
1951 index = mAudioPatches.indexOfKey(*handle);
1952 if (index >= 0) {
1953 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
1954 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
1955 }
1956 patchDesc = mAudioPatches.valueAt(index);
1957 patchDesc->mUid = uid;
1958 ALOGV("createAudioPatch() success");
1959 } else {
1960 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
1961 return INVALID_OPERATION;
1962 }
1963 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
1964 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
1965 // input device to input mix connection
Eric Laurent1f2f2232014-06-02 12:01:23 -07001966 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07001967 if (inputDesc == NULL) {
1968 return BAD_VALUE;
1969 }
1970 if (patchDesc != 0) {
1971 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
1972 return BAD_VALUE;
1973 }
1974 }
1975 sp<DeviceDescriptor> devDesc =
1976 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
1977 if (devDesc == 0) {
1978 return BAD_VALUE;
1979 }
1980
Eric Laurent84c70242014-06-23 08:46:27 -07001981 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Glenn Kastencbd48022014-07-24 13:46:44 -07001982 patch->sinks[0].sample_rate,
1983 NULL, /*updatedSampleRate*/
Eric Laurent6a94d692014-05-20 11:18:06 -07001984 patch->sinks[0].format,
1985 patch->sinks[0].channel_mask,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001986 // FIXME for the parameter type,
1987 // and the NONE
1988 (audio_output_flags_t)
1989 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07001990 return INVALID_OPERATION;
1991 }
1992 // TODO: reconfigure output format and channels here
1993 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07001994 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07001995 setInputDevice(inputDesc->mIoHandle,
Eric Laurent84c70242014-06-23 08:46:27 -07001996 devDesc->mDeviceType,
Eric Laurent6a94d692014-05-20 11:18:06 -07001997 true,
1998 handle);
1999 index = mAudioPatches.indexOfKey(*handle);
2000 if (index >= 0) {
2001 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2002 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2003 }
2004 patchDesc = mAudioPatches.valueAt(index);
2005 patchDesc->mUid = uid;
2006 ALOGV("createAudioPatch() success");
2007 } else {
2008 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2009 return INVALID_OPERATION;
2010 }
2011 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2012 // device to device connection
2013 if (patchDesc != 0) {
2014 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id &&
2015 patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2016 return BAD_VALUE;
2017 }
2018 }
2019
2020 sp<DeviceDescriptor> srcDeviceDesc =
2021 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2022 sp<DeviceDescriptor> sinkDeviceDesc =
2023 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
2024 if (srcDeviceDesc == 0 || sinkDeviceDesc == 0) {
2025 return BAD_VALUE;
2026 }
2027 //update source and sink with our own data as the data passed in the patch may
2028 // be incomplete.
2029 struct audio_patch newPatch = *patch;
2030 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
2031 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[0], &patch->sinks[0]);
2032
Eric Laurent6a94d692014-05-20 11:18:06 -07002033 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
Eric Laurent83b88082014-06-20 18:31:16 -07002034 SortedVector<audio_io_handle_t> outputs =
2035 getOutputsForDevice(sinkDeviceDesc->mDeviceType, mOutputs);
2036 // if the sink device is reachable via an opened output stream, request to go via
2037 // this output stream by adding a second source to the patch description
2038 audio_io_handle_t output = selectOutput(outputs, AUDIO_OUTPUT_FLAG_NONE);
2039 if (output != AUDIO_IO_HANDLE_NONE) {
2040 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2041 if (outputDesc->isDuplicated()) {
2042 return INVALID_OPERATION;
2043 }
2044 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2045 newPatch.num_sources = 2;
2046 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002047 }
2048 // TODO: check from routing capabilities in config file and other conflicting patches
2049
2050 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2051 if (index >= 0) {
2052 afPatchHandle = patchDesc->mAfPatchHandle;
2053 }
2054
2055 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2056 &afPatchHandle,
2057 0);
2058 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2059 status, afPatchHandle);
2060 if (status == NO_ERROR) {
2061 if (index < 0) {
2062 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2063 &newPatch, uid);
2064 addAudioPatch(patchDesc->mHandle, patchDesc);
2065 } else {
2066 patchDesc->mPatch = newPatch;
2067 }
2068 patchDesc->mAfPatchHandle = afPatchHandle;
2069 *handle = patchDesc->mHandle;
2070 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002071 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002072 } else {
2073 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2074 status);
2075 return INVALID_OPERATION;
2076 }
2077 } else {
2078 return BAD_VALUE;
2079 }
2080 } else {
2081 return BAD_VALUE;
2082 }
2083 return NO_ERROR;
2084}
2085
2086status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2087 uid_t uid)
2088{
2089 ALOGV("releaseAudioPatch() patch %d", handle);
2090
2091 ssize_t index = mAudioPatches.indexOfKey(handle);
2092
2093 if (index < 0) {
2094 return BAD_VALUE;
2095 }
2096 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2097 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2098 mUidCached, patchDesc->mUid, uid);
2099 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2100 return INVALID_OPERATION;
2101 }
2102
2103 struct audio_patch *patch = &patchDesc->mPatch;
2104 patchDesc->mUid = mUidCached;
2105 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002106 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002107 if (outputDesc == NULL) {
2108 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2109 return BAD_VALUE;
2110 }
2111
2112 setOutputDevice(outputDesc->mIoHandle,
2113 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2114 true,
2115 0,
2116 NULL);
2117 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2118 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002119 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002120 if (inputDesc == NULL) {
2121 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2122 return BAD_VALUE;
2123 }
2124 setInputDevice(inputDesc->mIoHandle,
2125 getNewInputDevice(inputDesc->mIoHandle),
2126 true,
2127 NULL);
2128 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2129 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2130 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2131 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2132 status, patchDesc->mAfPatchHandle);
2133 removeAudioPatch(patchDesc->mHandle);
2134 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002135 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002136 } else {
2137 return BAD_VALUE;
2138 }
2139 } else {
2140 return BAD_VALUE;
2141 }
2142 return NO_ERROR;
2143}
2144
2145status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2146 struct audio_patch *patches,
2147 unsigned int *generation)
2148{
2149 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2150 generation == NULL) {
2151 return BAD_VALUE;
2152 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002153 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002154 *num_patches, patches, mAudioPatches.size());
2155 if (patches == NULL) {
2156 *num_patches = 0;
2157 }
2158
2159 size_t patchesWritten = 0;
2160 size_t patchesMax = *num_patches;
2161 for (size_t i = 0;
2162 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2163 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2164 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002165 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002166 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2167 }
2168 *num_patches = mAudioPatches.size();
2169
2170 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002171 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002172 return NO_ERROR;
2173}
2174
Eric Laurente1715a42014-05-20 11:30:42 -07002175status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002176{
Eric Laurente1715a42014-05-20 11:30:42 -07002177 ALOGV("setAudioPortConfig()");
2178
2179 if (config == NULL) {
2180 return BAD_VALUE;
2181 }
2182 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2183 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002184 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2185 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002186 }
2187
Eric Laurenta121f902014-06-03 13:32:54 -07002188 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002189 if (config->type == AUDIO_PORT_TYPE_MIX) {
2190 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002191 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002192 if (outputDesc == NULL) {
2193 return BAD_VALUE;
2194 }
Eric Laurent84c70242014-06-23 08:46:27 -07002195 ALOG_ASSERT(!outputDesc->isDuplicated(),
2196 "setAudioPortConfig() called on duplicated output %d",
2197 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002198 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002199 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002200 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002201 if (inputDesc == NULL) {
2202 return BAD_VALUE;
2203 }
Eric Laurenta121f902014-06-03 13:32:54 -07002204 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002205 } else {
2206 return BAD_VALUE;
2207 }
2208 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2209 sp<DeviceDescriptor> deviceDesc;
2210 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2211 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2212 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2213 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2214 } else {
2215 return BAD_VALUE;
2216 }
2217 if (deviceDesc == NULL) {
2218 return BAD_VALUE;
2219 }
Eric Laurenta121f902014-06-03 13:32:54 -07002220 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002221 } else {
2222 return BAD_VALUE;
2223 }
2224
Eric Laurenta121f902014-06-03 13:32:54 -07002225 struct audio_port_config backupConfig;
2226 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2227 if (status == NO_ERROR) {
2228 struct audio_port_config newConfig;
2229 audioPortConfig->toAudioPortConfig(&newConfig, config);
2230 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002231 }
Eric Laurenta121f902014-06-03 13:32:54 -07002232 if (status != NO_ERROR) {
2233 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002234 }
Eric Laurente1715a42014-05-20 11:30:42 -07002235
2236 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002237}
2238
2239void AudioPolicyManager::clearAudioPatches(uid_t uid)
2240{
2241 for (ssize_t i = 0; i < (ssize_t)mAudioPatches.size(); i++) {
2242 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2243 if (patchDesc->mUid == uid) {
2244 // releaseAudioPatch() removes the patch from mAudioPatches
2245 if (releaseAudioPatch(mAudioPatches.keyAt(i), uid) == NO_ERROR) {
2246 i--;
2247 }
2248 }
2249 }
2250}
2251
2252status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
2253 const sp<AudioPatch>& patch)
2254{
2255 ssize_t index = mAudioPatches.indexOfKey(handle);
2256
2257 if (index >= 0) {
2258 ALOGW("addAudioPatch() patch %d already in", handle);
2259 return ALREADY_EXISTS;
2260 }
2261 mAudioPatches.add(handle, patch);
2262 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
2263 "sink handle %d",
2264 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
2265 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
2266 return NO_ERROR;
2267}
2268
2269status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
2270{
2271 ssize_t index = mAudioPatches.indexOfKey(handle);
2272
2273 if (index < 0) {
2274 ALOGW("removeAudioPatch() patch %d not in", handle);
2275 return ALREADY_EXISTS;
2276 }
2277 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
2278 mAudioPatches.valueAt(index)->mAfPatchHandle);
2279 mAudioPatches.removeItemsAt(index);
2280 return NO_ERROR;
2281}
2282
Eric Laurente552edb2014-03-10 17:42:56 -07002283// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07002284// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07002285// ----------------------------------------------------------------------------
2286
Eric Laurent3a4311c2014-03-17 12:00:47 -07002287uint32_t AudioPolicyManager::nextUniqueId()
2288{
2289 return android_atomic_inc(&mNextUniqueId);
2290}
2291
Eric Laurent6a94d692014-05-20 11:18:06 -07002292uint32_t AudioPolicyManager::nextAudioPortGeneration()
2293{
2294 return android_atomic_inc(&mAudioPortGeneration);
2295}
2296
Eric Laurente0720872014-03-11 09:30:41 -07002297AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07002298 :
2299#ifdef AUDIO_POLICY_TEST
2300 Thread(false),
2301#endif //AUDIO_POLICY_TEST
2302 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07002303 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07002304 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
2305 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07002306 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07002307 mSpeakerDrcEnabled(false), mNextUniqueId(1),
2308 mAudioPortGeneration(1)
Eric Laurente552edb2014-03-10 17:42:56 -07002309{
Eric Laurent6a94d692014-05-20 11:18:06 -07002310 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07002311 mpClientInterface = clientInterface;
2312
Eric Laurent3b73df72014-03-11 09:06:29 -07002313 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
2314 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002315 }
2316
Eric Laurent1afeecb2014-05-14 08:52:28 -07002317 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07002318 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
2319 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
2320 ALOGE("could not load audio policy configuration file, setting defaults");
2321 defaultAudioPolicyConfig();
2322 }
2323 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002324 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07002325
2326 // must be done after reading the policy
2327 initializeVolumeCurves();
2328
2329 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07002330 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
2331 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07002332 for (size_t i = 0; i < mHwModules.size(); i++) {
2333 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
2334 if (mHwModules[i]->mHandle == 0) {
2335 ALOGW("could not open HW module %s", mHwModules[i]->mName);
2336 continue;
2337 }
2338 // open all output streams needed to access attached devices
2339 // except for direct output streams that are only opened when they are actually
2340 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07002341 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07002342 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2343 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002344 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002345
Eric Laurent3a4311c2014-03-17 12:00:47 -07002346 if (outProfile->mSupportedDevices.isEmpty()) {
2347 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
2348 continue;
2349 }
2350
Eric Laurent83b88082014-06-20 18:31:16 -07002351 audio_devices_t profileType = outProfile->mSupportedDevices.types();
2352 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
2353 profileType = mDefaultOutputDevice->mDeviceType;
2354 } else {
2355 profileType = outProfile->mSupportedDevices[0]->mDeviceType;
2356 }
2357 if ((profileType & outputDeviceTypes) &&
Eric Laurente552edb2014-03-10 17:42:56 -07002358 ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002359 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002360
Eric Laurent83b88082014-06-20 18:31:16 -07002361 outputDesc->mDevice = profileType;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002362 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2363 config.sample_rate = outputDesc->mSamplingRate;
2364 config.channel_mask = outputDesc->mChannelMask;
2365 config.format = outputDesc->mFormat;
2366 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2367 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
2368 &output,
2369 &config,
2370 &outputDesc->mDevice,
2371 String8(""),
2372 &outputDesc->mLatency,
2373 outputDesc->mFlags);
2374
2375 if (status != NO_ERROR) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002376 ALOGW("Cannot open output stream for device %08x on hw module %s",
2377 outputDesc->mDevice,
2378 mHwModules[i]->mName);
Eric Laurente552edb2014-03-10 17:42:56 -07002379 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002380 outputDesc->mSamplingRate = config.sample_rate;
2381 outputDesc->mChannelMask = config.channel_mask;
2382 outputDesc->mFormat = config.format;
2383
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002384 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002385 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002386 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002387 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002388 // give a valid ID to an attached device once confirmed it is reachable
2389 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
2390 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002391 mAvailableOutputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002392 }
2393 }
Eric Laurente552edb2014-03-10 17:42:56 -07002394 if (mPrimaryOutput == 0 &&
2395 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
2396 mPrimaryOutput = output;
2397 }
2398 addOutput(output, outputDesc);
2399 setOutputDevice(output,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002400 outputDesc->mDevice,
Eric Laurente552edb2014-03-10 17:42:56 -07002401 true);
2402 }
2403 }
2404 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002405 // open input streams needed to access attached devices to validate
2406 // mAvailableInputDevices list
2407 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
2408 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002409 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07002410
Eric Laurent3a4311c2014-03-17 12:00:47 -07002411 if (inProfile->mSupportedDevices.isEmpty()) {
2412 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
2413 continue;
2414 }
2415
Eric Laurent83b88082014-06-20 18:31:16 -07002416 audio_devices_t profileType = inProfile->mSupportedDevices[0]->mDeviceType;
2417 if (profileType & inputDeviceTypes) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002418 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002419
2420 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
Eric Laurent83b88082014-06-20 18:31:16 -07002421 inputDesc->mDevice = profileType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002422
Eric Laurentcf2c0212014-07-25 16:20:43 -07002423 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2424 config.sample_rate = inputDesc->mSamplingRate;
2425 config.channel_mask = inputDesc->mChannelMask;
2426 config.format = inputDesc->mFormat;
2427 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
2428 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
2429 &input,
2430 &config,
2431 &inputDesc->mDevice,
2432 String8(""),
2433 AUDIO_SOURCE_MIC,
2434 AUDIO_INPUT_FLAG_NONE);
2435
2436 if (status == NO_ERROR) {
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002437 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002438 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07002439 ssize_t index =
Eric Laurent5b61ddd2014-05-07 09:10:01 -07002440 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002441 // give a valid ID to an attached device once confirmed it is reachable
2442 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
2443 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -07002444 mAvailableInputDevices[index]->mModule = mHwModules[i];
Eric Laurent3a4311c2014-03-17 12:00:47 -07002445 }
2446 }
2447 mpClientInterface->closeInput(input);
2448 } else {
2449 ALOGW("Cannot open input stream for device %08x on hw module %s",
2450 inputDesc->mDevice,
2451 mHwModules[i]->mName);
2452 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002453 }
2454 }
2455 }
2456 // make sure all attached devices have been allocated a unique ID
2457 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
2458 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002459 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002460 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
2461 continue;
2462 }
2463 i++;
2464 }
2465 for (size_t i = 0; i < mAvailableInputDevices.size();) {
2466 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002467 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002468 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
2469 continue;
2470 }
2471 i++;
2472 }
2473 // make sure default device is reachable
2474 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002475 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002476 }
Eric Laurente552edb2014-03-10 17:42:56 -07002477
2478 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
2479
2480 updateDevicesAndOutputs();
2481
2482#ifdef AUDIO_POLICY_TEST
2483 if (mPrimaryOutput != 0) {
2484 AudioParameter outputCmd = AudioParameter();
2485 outputCmd.addInt(String8("set_id"), 0);
2486 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2487
2488 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
2489 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07002490 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
2491 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002492 mTestLatencyMs = 0;
2493 mCurOutput = 0;
2494 mDirectOutput = false;
2495 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2496 mTestOutputs[i] = 0;
2497 }
2498
2499 const size_t SIZE = 256;
2500 char buffer[SIZE];
2501 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
2502 run(buffer, ANDROID_PRIORITY_AUDIO);
2503 }
2504#endif //AUDIO_POLICY_TEST
2505}
2506
Eric Laurente0720872014-03-11 09:30:41 -07002507AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07002508{
2509#ifdef AUDIO_POLICY_TEST
2510 exit();
2511#endif //AUDIO_POLICY_TEST
2512 for (size_t i = 0; i < mOutputs.size(); i++) {
2513 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002514 }
2515 for (size_t i = 0; i < mInputs.size(); i++) {
2516 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07002517 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07002518 mAvailableOutputDevices.clear();
2519 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07002520 mOutputs.clear();
2521 mInputs.clear();
2522 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07002523}
2524
Eric Laurente0720872014-03-11 09:30:41 -07002525status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07002526{
2527 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
2528}
2529
2530#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07002531bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07002532{
2533 ALOGV("entering threadLoop()");
2534 while (!exitPending())
2535 {
2536 String8 command;
2537 int valueInt;
2538 String8 value;
2539
2540 Mutex::Autolock _l(mLock);
2541 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
2542
2543 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
2544 AudioParameter param = AudioParameter(command);
2545
2546 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
2547 valueInt != 0) {
2548 ALOGV("Test command %s received", command.string());
2549 String8 target;
2550 if (param.get(String8("target"), target) != NO_ERROR) {
2551 target = "Manager";
2552 }
2553 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
2554 param.remove(String8("test_cmd_policy_output"));
2555 mCurOutput = valueInt;
2556 }
2557 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
2558 param.remove(String8("test_cmd_policy_direct"));
2559 if (value == "false") {
2560 mDirectOutput = false;
2561 } else if (value == "true") {
2562 mDirectOutput = true;
2563 }
2564 }
2565 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
2566 param.remove(String8("test_cmd_policy_input"));
2567 mTestInput = valueInt;
2568 }
2569
2570 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
2571 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07002572 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07002573 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002574 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002575 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002576 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07002577 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002578 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07002579 }
Eric Laurent3b73df72014-03-11 09:06:29 -07002580 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07002581 if (target == "Manager") {
2582 mTestFormat = format;
2583 } else if (mTestOutputs[mCurOutput] != 0) {
2584 AudioParameter outputParam = AudioParameter();
2585 outputParam.addInt(String8("format"), format);
2586 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2587 }
2588 }
2589 }
2590 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
2591 param.remove(String8("test_cmd_policy_channels"));
2592 int channels = 0;
2593
2594 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002595 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07002596 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07002597 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07002598 }
2599 if (channels != 0) {
2600 if (target == "Manager") {
2601 mTestChannels = channels;
2602 } else if (mTestOutputs[mCurOutput] != 0) {
2603 AudioParameter outputParam = AudioParameter();
2604 outputParam.addInt(String8("channels"), channels);
2605 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2606 }
2607 }
2608 }
2609 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
2610 param.remove(String8("test_cmd_policy_sampleRate"));
2611 if (valueInt >= 0 && valueInt <= 96000) {
2612 int samplingRate = valueInt;
2613 if (target == "Manager") {
2614 mTestSamplingRate = samplingRate;
2615 } else if (mTestOutputs[mCurOutput] != 0) {
2616 AudioParameter outputParam = AudioParameter();
2617 outputParam.addInt(String8("sampling_rate"), samplingRate);
2618 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
2619 }
2620 }
2621 }
2622
2623 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
2624 param.remove(String8("test_cmd_policy_reopen"));
2625
Eric Laurent1f2f2232014-06-02 12:01:23 -07002626 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07002627 mpClientInterface->closeOutput(mPrimaryOutput);
2628
2629 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
2630
Eric Laurente552edb2014-03-10 17:42:56 -07002631 mOutputs.removeItem(mPrimaryOutput);
2632
Eric Laurent1f2f2232014-06-02 12:01:23 -07002633 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07002634 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002635 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2636 config.sample_rate = outputDesc->mSamplingRate;
2637 config.channel_mask = outputDesc->mChannelMask;
2638 config.format = outputDesc->mFormat;
2639 status_t status = mpClientInterface->openOutput(moduleHandle,
2640 &mPrimaryOutput,
2641 &config,
2642 &outputDesc->mDevice,
2643 String8(""),
2644 &outputDesc->mLatency,
2645 outputDesc->mFlags);
2646 if (status != NO_ERROR) {
2647 ALOGE("Failed to reopen hardware output stream, "
2648 "samplingRate: %d, format %d, channels %d",
2649 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07002650 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002651 outputDesc->mSamplingRate = config.sample_rate;
2652 outputDesc->mChannelMask = config.channel_mask;
2653 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07002654 AudioParameter outputCmd = AudioParameter();
2655 outputCmd.addInt(String8("set_id"), 0);
2656 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
2657 addOutput(mPrimaryOutput, outputDesc);
2658 }
2659 }
2660
2661
2662 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
2663 }
2664 }
2665 return false;
2666}
2667
Eric Laurente0720872014-03-11 09:30:41 -07002668void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07002669{
2670 {
2671 AutoMutex _l(mLock);
2672 requestExit();
2673 mWaitWorkCV.signal();
2674 }
2675 requestExitAndWait();
2676}
2677
Eric Laurente0720872014-03-11 09:30:41 -07002678int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07002679{
2680 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
2681 if (output == mTestOutputs[i]) return i;
2682 }
2683 return 0;
2684}
2685#endif //AUDIO_POLICY_TEST
2686
2687// ---
2688
Eric Laurent1f2f2232014-06-02 12:01:23 -07002689void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07002690{
Eric Laurent1c333e22014-05-20 10:48:17 -07002691 outputDesc->mIoHandle = output;
2692 outputDesc->mId = nextUniqueId();
2693 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002694 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07002695}
2696
Eric Laurent1f2f2232014-06-02 12:01:23 -07002697void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07002698{
Eric Laurent1c333e22014-05-20 10:48:17 -07002699 inputDesc->mIoHandle = input;
2700 inputDesc->mId = nextUniqueId();
2701 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07002702 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07002703}
Eric Laurente552edb2014-03-10 17:42:56 -07002704
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002705void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
2706 const String8 address /*in*/,
2707 SortedVector<audio_io_handle_t>& outputs /*out*/) {
2708 // look for a match on the given address on the addresses of the outputs:
2709 // find the address by finding the patch that maps to this output
2710 ssize_t patchIdx = mAudioPatches.indexOfKey(desc->mPatchHandle);
2711 //ALOGV(" inspecting output %d (patch %d) for supported device=0x%x",
2712 // outputIdx, patchIdx, desc->mProfile->mSupportedDevices.types());
2713 if (patchIdx >= 0) {
2714 const sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patchIdx);
2715 const int numSinks = patchDesc->mPatch.num_sinks;
2716 for (ssize_t j=0; j < numSinks; j++) {
2717 if (patchDesc->mPatch.sinks[j].type == AUDIO_PORT_TYPE_DEVICE) {
2718 const char* patchAddr =
2719 patchDesc->mPatch.sinks[j].ext.device.address;
2720 if (strncmp(patchAddr,
2721 address.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0) {
2722 ALOGV("checkOutputsForDevice(): adding opened output %d on same address %s",
2723 desc->mIoHandle, patchDesc->mPatch.sinks[j].ext.device.address);
2724 outputs.add(desc->mIoHandle);
2725 break;
2726 }
2727 }
2728 }
2729 }
2730}
2731
Eric Laurente0720872014-03-11 09:30:41 -07002732status_t AudioPolicyManager::checkOutputsForDevice(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -07002733 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07002734 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07002735 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07002736{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002737 sp<AudioOutputDescriptor> desc;
Eric Laurente552edb2014-03-10 17:42:56 -07002738
Eric Laurent3b73df72014-03-11 09:06:29 -07002739 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002740 // first list already open outputs that can be routed to this device
2741 for (size_t i = 0; i < mOutputs.size(); i++) {
2742 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002743 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002744 if (!deviceDistinguishesOnAddress(device)) {
2745 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
2746 outputs.add(mOutputs.keyAt(i));
2747 } else {
2748 ALOGV(" checking address match due to device 0x%x", device);
2749 findIoHandlesByAddress(desc, address, outputs);
2750 }
Eric Laurente552edb2014-03-10 17:42:56 -07002751 }
2752 }
2753 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07002754 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07002755 for (size_t i = 0; i < mHwModules.size(); i++)
2756 {
2757 if (mHwModules[i]->mHandle == 0) {
2758 continue;
2759 }
2760 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2761 {
Eric Laurent3a4311c2014-03-17 12:00:47 -07002762 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
Eric Laurentd4692962014-05-05 18:13:44 -07002763 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002764 profiles.add(mHwModules[i]->mOutputProfiles[j]);
2765 }
2766 }
2767 }
2768
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002769 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
2770
Eric Laurente552edb2014-03-10 17:42:56 -07002771 if (profiles.isEmpty() && outputs.isEmpty()) {
2772 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2773 return BAD_VALUE;
2774 }
2775
2776 // open outputs for matching profiles if needed. Direct outputs are also opened to
2777 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
2778 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002779 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07002780
2781 // nothing to do if one output is already opened for this profile
2782 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002783 for (j = 0; j < outputs.size(); j++) {
2784 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07002785 if (!desc->isDuplicated() && desc->mProfile == profile) {
2786 break;
2787 }
2788 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002789 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002790 continue;
2791 }
2792
Eric Laurent83b88082014-06-20 18:31:16 -07002793 ALOGV("opening output for device %08x with params %s profile %p",
2794 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07002795 desc = new AudioOutputDescriptor(profile);
2796 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002797 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2798 config.sample_rate = desc->mSamplingRate;
2799 config.channel_mask = desc->mChannelMask;
2800 config.format = desc->mFormat;
2801 config.offload_info.sample_rate = desc->mSamplingRate;
2802 config.offload_info.channel_mask = desc->mChannelMask;
2803 config.offload_info.format = desc->mFormat;
2804 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
2805 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
2806 &output,
2807 &config,
2808 &desc->mDevice,
2809 address,
2810 &desc->mLatency,
2811 desc->mFlags);
2812 if (status == NO_ERROR) {
2813 desc->mSamplingRate = config.sample_rate;
2814 desc->mChannelMask = config.channel_mask;
2815 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07002816
Eric Laurentd4692962014-05-05 18:13:44 -07002817 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07002818 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002819 char *param = audio_device_address_to_parameter(device, address);
2820 mpClientInterface->setParameters(output, String8(param));
2821 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07002822 }
2823
Eric Laurentd4692962014-05-05 18:13:44 -07002824 // Here is where we step through and resolve any "dynamic" fields
2825 String8 reply;
2826 char *value;
2827 if (profile->mSamplingRates[0] == 0) {
2828 reply = mpClientInterface->getParameters(output,
2829 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002830 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002831 reply.string());
2832 value = strpbrk((char *)reply.string(), "=");
2833 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002834 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002835 }
Eric Laurentd4692962014-05-05 18:13:44 -07002836 }
2837 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2838 reply = mpClientInterface->getParameters(output,
2839 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002840 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002841 reply.string());
2842 value = strpbrk((char *)reply.string(), "=");
2843 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002844 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002845 }
Eric Laurentd4692962014-05-05 18:13:44 -07002846 }
2847 if (profile->mChannelMasks[0] == 0) {
2848 reply = mpClientInterface->getParameters(output,
2849 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002850 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07002851 reply.string());
2852 value = strpbrk((char *)reply.string(), "=");
2853 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07002854 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002855 }
Eric Laurentd4692962014-05-05 18:13:44 -07002856 }
2857 if (((profile->mSamplingRates[0] == 0) &&
2858 (profile->mSamplingRates.size() < 2)) ||
2859 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
2860 (profile->mFormats.size() < 2)) ||
2861 ((profile->mChannelMasks[0] == 0) &&
2862 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002863 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07002864 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002865 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07002866 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
2867 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07002868 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002869 config.sample_rate = profile->pickSamplingRate();
2870 config.channel_mask = profile->pickChannelMask();
2871 config.format = profile->pickFormat();
2872 config.offload_info.sample_rate = config.sample_rate;
2873 config.offload_info.channel_mask = config.channel_mask;
2874 config.offload_info.format = config.format;
2875 status = mpClientInterface->openOutput(profile->mModule->mHandle,
2876 &output,
2877 &config,
2878 &desc->mDevice,
2879 address,
2880 &desc->mLatency,
2881 desc->mFlags);
2882 if (status == NO_ERROR) {
2883 desc->mSamplingRate = config.sample_rate;
2884 desc->mChannelMask = config.channel_mask;
2885 desc->mFormat = config.format;
2886 } else {
2887 output = AUDIO_IO_HANDLE_NONE;
2888 }
Eric Laurentd4692962014-05-05 18:13:44 -07002889 }
2890
Eric Laurentcf2c0212014-07-25 16:20:43 -07002891 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002892 addOutput(output, desc);
Eric Laurentd4692962014-05-05 18:13:44 -07002893 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07002894 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002895
Eric Laurentd4692962014-05-05 18:13:44 -07002896 // set initial stream volume for device
2897 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07002898
Eric Laurentd4692962014-05-05 18:13:44 -07002899 //TODO: configure audio effect output stage here
2900
2901 // open a duplicating output thread for the new output and the primary output
2902 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
2903 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002904 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07002905 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07002906 sp<AudioOutputDescriptor> dupOutputDesc =
2907 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07002908 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
2909 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
2910 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
2911 dupOutputDesc->mFormat = desc->mFormat;
2912 dupOutputDesc->mChannelMask = desc->mChannelMask;
2913 dupOutputDesc->mLatency = desc->mLatency;
2914 addOutput(duplicatedOutput, dupOutputDesc);
2915 applyStreamVolumes(duplicatedOutput, device, 0, true);
2916 } else {
2917 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
2918 mPrimaryOutput, output);
2919 mpClientInterface->closeOutput(output);
2920 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07002921 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002922 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07002923 }
Eric Laurente552edb2014-03-10 17:42:56 -07002924 }
2925 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002926 } else {
2927 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002928 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07002929 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002930 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07002931 profiles.removeAt(profile_index);
2932 profile_index--;
2933 } else {
2934 outputs.add(output);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002935 if (deviceDistinguishesOnAddress(device)) {
2936 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
2937 device, address.string());
2938 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
2939 NULL/*patch handle*/, address.string());
2940 }
Eric Laurente552edb2014-03-10 17:42:56 -07002941 ALOGV("checkOutputsForDevice(): adding output %d", output);
2942 }
2943 }
2944
2945 if (profiles.isEmpty()) {
2946 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
2947 return BAD_VALUE;
2948 }
Eric Laurentd4692962014-05-05 18:13:44 -07002949 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07002950 // check if one opened output is not needed any more after disconnecting one device
2951 for (size_t i = 0; i < mOutputs.size(); i++) {
2952 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07002953 if (!desc->isDuplicated()) {
2954 if (!(desc->mProfile->mSupportedDevices.types()
2955 & mAvailableOutputDevices.types())) {
2956 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
2957 mOutputs.keyAt(i));
2958 outputs.add(mOutputs.keyAt(i));
2959 } else if (deviceDistinguishesOnAddress(device) &&
2960 // exact match on device
2961 (desc->mProfile->mSupportedDevices.types() == device)) {
2962 findIoHandlesByAddress(desc, address, outputs);
2963 }
Eric Laurente552edb2014-03-10 17:42:56 -07002964 }
2965 }
Eric Laurentd4692962014-05-05 18:13:44 -07002966 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07002967 for (size_t i = 0; i < mHwModules.size(); i++)
2968 {
2969 if (mHwModules[i]->mHandle == 0) {
2970 continue;
2971 }
2972 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2973 {
Eric Laurent1c333e22014-05-20 10:48:17 -07002974 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07002975 if (profile->mSupportedDevices.types() & device) {
2976 ALOGV("checkOutputsForDevice(): "
2977 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07002978 if (profile->mSamplingRates[0] == 0) {
2979 profile->mSamplingRates.clear();
2980 profile->mSamplingRates.add(0);
2981 }
2982 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
2983 profile->mFormats.clear();
2984 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
2985 }
2986 if (profile->mChannelMasks[0] == 0) {
2987 profile->mChannelMasks.clear();
2988 profile->mChannelMasks.add(0);
2989 }
2990 }
2991 }
2992 }
2993 }
2994 return NO_ERROR;
2995}
2996
Eric Laurentd4692962014-05-05 18:13:44 -07002997status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
2998 audio_policy_dev_state_t state,
2999 SortedVector<audio_io_handle_t>& inputs,
3000 const String8 address)
3001{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003002 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003003 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3004 // first list already open inputs that can be routed to this device
3005 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3006 desc = mInputs.valueAt(input_index);
3007 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3008 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3009 inputs.add(mInputs.keyAt(input_index));
3010 }
3011 }
3012
3013 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003014 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003015 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3016 {
3017 if (mHwModules[module_idx]->mHandle == 0) {
3018 continue;
3019 }
3020 for (size_t profile_index = 0;
3021 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3022 profile_index++)
3023 {
3024 if (mHwModules[module_idx]->mInputProfiles[profile_index]->mSupportedDevices.types()
3025 & (device & ~AUDIO_DEVICE_BIT_IN)) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003026 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003027 profile_index, module_idx);
3028 profiles.add(mHwModules[module_idx]->mInputProfiles[profile_index]);
3029 }
3030 }
3031 }
3032
3033 if (profiles.isEmpty() && inputs.isEmpty()) {
3034 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3035 return BAD_VALUE;
3036 }
3037
3038 // open inputs for matching profiles if needed. Direct inputs are also opened to
3039 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3040 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3041
Eric Laurent1c333e22014-05-20 10:48:17 -07003042 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003043 // nothing to do if one input is already opened for this profile
3044 size_t input_index;
3045 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3046 desc = mInputs.valueAt(input_index);
3047 if (desc->mProfile == profile) {
3048 break;
3049 }
3050 }
3051 if (input_index != mInputs.size()) {
3052 continue;
3053 }
3054
3055 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3056 desc = new AudioInputDescriptor(profile);
3057 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003058 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3059 config.sample_rate = desc->mSamplingRate;
3060 config.channel_mask = desc->mChannelMask;
3061 config.format = desc->mFormat;
3062 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3063 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3064 &input,
3065 &config,
3066 &desc->mDevice,
3067 address,
3068 AUDIO_SOURCE_MIC,
3069 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003070
Eric Laurentcf2c0212014-07-25 16:20:43 -07003071 if (status == NO_ERROR) {
3072 desc->mSamplingRate = config.sample_rate;
3073 desc->mChannelMask = config.channel_mask;
3074 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003075
Eric Laurentd4692962014-05-05 18:13:44 -07003076 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003077 char *param = audio_device_address_to_parameter(device, address);
3078 mpClientInterface->setParameters(input, String8(param));
3079 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003080 }
3081
3082 // Here is where we step through and resolve any "dynamic" fields
3083 String8 reply;
3084 char *value;
3085 if (profile->mSamplingRates[0] == 0) {
3086 reply = mpClientInterface->getParameters(input,
3087 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3088 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3089 reply.string());
3090 value = strpbrk((char *)reply.string(), "=");
3091 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003092 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003093 }
3094 }
3095 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3096 reply = mpClientInterface->getParameters(input,
3097 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3098 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3099 value = strpbrk((char *)reply.string(), "=");
3100 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003101 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003102 }
3103 }
3104 if (profile->mChannelMasks[0] == 0) {
3105 reply = mpClientInterface->getParameters(input,
3106 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3107 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3108 reply.string());
3109 value = strpbrk((char *)reply.string(), "=");
3110 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003111 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003112 }
3113 }
3114 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3115 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3116 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3117 ALOGW("checkInputsForDevice() direct input missing param");
3118 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003119 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003120 }
3121
3122 if (input != 0) {
3123 addInput(input, desc);
3124 }
3125 } // endif input != 0
3126
Eric Laurentcf2c0212014-07-25 16:20:43 -07003127 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003128 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003129 profiles.removeAt(profile_index);
3130 profile_index--;
3131 } else {
3132 inputs.add(input);
3133 ALOGV("checkInputsForDevice(): adding input %d", input);
3134 }
3135 } // end scan profiles
3136
3137 if (profiles.isEmpty()) {
3138 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3139 return BAD_VALUE;
3140 }
3141 } else {
3142 // Disconnect
3143 // check if one opened input is not needed any more after disconnecting one device
3144 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3145 desc = mInputs.valueAt(input_index);
3146 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types())) {
3147 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3148 mInputs.keyAt(input_index));
3149 inputs.add(mInputs.keyAt(input_index));
3150 }
3151 }
3152 // Clear any profiles associated with the disconnected device.
3153 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3154 if (mHwModules[module_index]->mHandle == 0) {
3155 continue;
3156 }
3157 for (size_t profile_index = 0;
3158 profile_index < mHwModules[module_index]->mInputProfiles.size();
3159 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003160 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003161 if (profile->mSupportedDevices.types() & device) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003162 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003163 profile_index, module_index);
3164 if (profile->mSamplingRates[0] == 0) {
3165 profile->mSamplingRates.clear();
3166 profile->mSamplingRates.add(0);
3167 }
3168 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3169 profile->mFormats.clear();
3170 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3171 }
3172 if (profile->mChannelMasks[0] == 0) {
3173 profile->mChannelMasks.clear();
3174 profile->mChannelMasks.add(0);
3175 }
3176 }
3177 }
3178 }
3179 } // end disconnect
3180
3181 return NO_ERROR;
3182}
3183
3184
Eric Laurente0720872014-03-11 09:30:41 -07003185void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003186{
3187 ALOGV("closeOutput(%d)", output);
3188
Eric Laurent1f2f2232014-06-02 12:01:23 -07003189 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003190 if (outputDesc == NULL) {
3191 ALOGW("closeOutput() unknown output %d", output);
3192 return;
3193 }
3194
3195 // look for duplicated outputs connected to the output being removed.
3196 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003197 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003198 if (dupOutputDesc->isDuplicated() &&
3199 (dupOutputDesc->mOutput1 == outputDesc ||
3200 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003201 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003202 if (dupOutputDesc->mOutput1 == outputDesc) {
3203 outputDesc2 = dupOutputDesc->mOutput2;
3204 } else {
3205 outputDesc2 = dupOutputDesc->mOutput1;
3206 }
3207 // As all active tracks on duplicated output will be deleted,
3208 // and as they were also referenced on the other output, the reference
3209 // count for their stream type must be adjusted accordingly on
3210 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07003211 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07003212 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07003213 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07003214 }
3215 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
3216 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
3217
3218 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003219 mOutputs.removeItem(duplicatedOutput);
3220 }
3221 }
3222
3223 AudioParameter param;
3224 param.add(String8("closing"), String8("true"));
3225 mpClientInterface->setParameters(output, param.toString());
3226
3227 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003228 mOutputs.removeItem(output);
3229 mPreviousOutputs = mOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07003230 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003231}
3232
Eric Laurente0720872014-03-11 09:30:41 -07003233SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07003234 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07003235{
3236 SortedVector<audio_io_handle_t> outputs;
3237
3238 ALOGVV("getOutputsForDevice() device %04x", device);
3239 for (size_t i = 0; i < openOutputs.size(); i++) {
3240 ALOGVV("output %d isDuplicated=%d device=%04x",
3241 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
3242 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
3243 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
3244 outputs.add(openOutputs.keyAt(i));
3245 }
3246 }
3247 return outputs;
3248}
3249
Eric Laurente0720872014-03-11 09:30:41 -07003250bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07003251 SortedVector<audio_io_handle_t>& outputs2)
3252{
3253 if (outputs1.size() != outputs2.size()) {
3254 return false;
3255 }
3256 for (size_t i = 0; i < outputs1.size(); i++) {
3257 if (outputs1[i] != outputs2[i]) {
3258 return false;
3259 }
3260 }
3261 return true;
3262}
3263
Eric Laurente0720872014-03-11 09:30:41 -07003264void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07003265{
3266 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
3267 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
3268 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
3269 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
3270
3271 if (!vectorsEqual(srcOutputs,dstOutputs)) {
3272 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
3273 strategy, srcOutputs[0], dstOutputs[0]);
3274 // mute strategy while moving tracks from one output to another
3275 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003276 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07003277 if (desc->isStrategyActive(strategy)) {
3278 setStrategyMute(strategy, true, srcOutputs[i]);
3279 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
3280 }
3281 }
3282
3283 // Move effects associated to this strategy from previous output to new output
3284 if (strategy == STRATEGY_MEDIA) {
3285 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
3286 SortedVector<audio_io_handle_t> moved;
3287 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003288 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
3289 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
3290 effectDesc->mIo != fxOutput) {
3291 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07003292 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
3293 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003294 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07003295 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003296 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07003297 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07003298 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07003299 }
3300 }
3301 }
3302 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07003303 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
3304 if (getStrategy((audio_stream_type_t)i) == strategy) {
3305 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07003306 }
3307 }
3308 }
3309}
3310
Eric Laurente0720872014-03-11 09:30:41 -07003311void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07003312{
3313 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
3314 checkOutputForStrategy(STRATEGY_PHONE);
3315 checkOutputForStrategy(STRATEGY_SONIFICATION);
3316 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3317 checkOutputForStrategy(STRATEGY_MEDIA);
3318 checkOutputForStrategy(STRATEGY_DTMF);
3319}
3320
Eric Laurente0720872014-03-11 09:30:41 -07003321audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07003322{
Eric Laurente552edb2014-03-10 17:42:56 -07003323 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003324 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003325 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
3326 return mOutputs.keyAt(i);
3327 }
3328 }
3329
3330 return 0;
3331}
3332
Eric Laurente0720872014-03-11 09:30:41 -07003333void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07003334{
Eric Laurente552edb2014-03-10 17:42:56 -07003335 audio_io_handle_t a2dpOutput = getA2dpOutput();
3336 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003337 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07003338 return;
3339 }
3340
Eric Laurent3a4311c2014-03-17 12:00:47 -07003341 bool isScoConnected =
3342 (mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0;
Eric Laurente552edb2014-03-10 17:42:56 -07003343 // suspend A2DP output if:
3344 // (NOT already suspended) &&
3345 // ((SCO device is connected &&
3346 // (forced usage for communication || for record is SCO))) ||
3347 // (phone state is ringing || in call)
3348 //
3349 // restore A2DP output if:
3350 // (Already suspended) &&
3351 // ((SCO device is NOT connected ||
3352 // (forced usage NOT for communication && NOT for record is SCO))) &&
3353 // (phone state is NOT ringing && NOT in call)
3354 //
3355 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003356 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003357 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
3358 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
3359 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
3360 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003361
3362 mpClientInterface->restoreOutput(a2dpOutput);
3363 mA2dpSuspended = false;
3364 }
3365 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003366 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003367 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
3368 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
3369 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
3370 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07003371
3372 mpClientInterface->suspendOutput(a2dpOutput);
3373 mA2dpSuspended = true;
3374 }
3375 }
3376}
3377
Eric Laurent1c333e22014-05-20 10:48:17 -07003378audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07003379{
3380 audio_devices_t device = AUDIO_DEVICE_NONE;
3381
Eric Laurent1f2f2232014-06-02 12:01:23 -07003382 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003383
3384 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3385 if (index >= 0) {
3386 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3387 if (patchDesc->mUid != mUidCached) {
3388 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
3389 outputDesc->device(), outputDesc->mPatchHandle);
3390 return outputDesc->device();
3391 }
3392 }
3393
Eric Laurente552edb2014-03-10 17:42:56 -07003394 // check the following by order of priority to request a routing change if necessary:
3395 // 1: the strategy enforced audible is active on the output:
3396 // use device for strategy enforced audible
3397 // 2: we are in call or the strategy phone is active on the output:
3398 // use device for strategy phone
3399 // 3: the strategy sonification is active on the output:
3400 // use device for strategy sonification
3401 // 4: the strategy "respectful" sonification is active on the output:
3402 // use device for strategy "respectful" sonification
3403 // 5: the strategy media is active on the output:
3404 // use device for strategy media
3405 // 6: the strategy DTMF is active on the output:
3406 // use device for strategy DTMF
3407 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
3408 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
3409 } else if (isInCall() ||
3410 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
3411 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
3412 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
3413 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
3414 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
3415 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
3416 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
3417 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
3418 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
3419 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
3420 }
3421
Eric Laurent1c333e22014-05-20 10:48:17 -07003422 ALOGV("getNewOutputDevice() selected device %x", device);
3423 return device;
3424}
3425
3426audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
3427{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003428 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07003429
3430 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
3431 if (index >= 0) {
3432 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3433 if (patchDesc->mUid != mUidCached) {
3434 ALOGV("getNewInputDevice() device %08x forced by patch %d",
3435 inputDesc->mDevice, inputDesc->mPatchHandle);
3436 return inputDesc->mDevice;
3437 }
3438 }
3439
Eric Laurent1c333e22014-05-20 10:48:17 -07003440 audio_devices_t device = getDeviceForInputSource(inputDesc->mInputSource);
3441
3442 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003443 return device;
3444}
3445
Eric Laurente0720872014-03-11 09:30:41 -07003446uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003447 return (uint32_t)getStrategy(stream);
3448}
3449
Eric Laurente0720872014-03-11 09:30:41 -07003450audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003451 // By checking the range of stream before calling getStrategy, we avoid
3452 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
3453 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent3b73df72014-03-11 09:06:29 -07003454 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003455 return AUDIO_DEVICE_NONE;
3456 }
3457 audio_devices_t devices;
3458 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
3459 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
3460 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
3461 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003462 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07003463 if (outputDesc->isStrategyActive(strategy)) {
3464 devices = outputDesc->device();
3465 break;
3466 }
Eric Laurente552edb2014-03-10 17:42:56 -07003467 }
3468 return devices;
3469}
3470
Eric Laurente0720872014-03-11 09:30:41 -07003471AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07003472 audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003473 // stream to strategy mapping
3474 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003475 case AUDIO_STREAM_VOICE_CALL:
3476 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003477 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07003478 case AUDIO_STREAM_RING:
3479 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07003480 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07003481 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07003482 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07003483 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07003484 return STRATEGY_DTMF;
3485 default:
3486 ALOGE("unknown stream type");
Eric Laurent3b73df72014-03-11 09:06:29 -07003487 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07003488 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
3489 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07003490 case AUDIO_STREAM_TTS:
3491 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003492 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07003493 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07003494 return STRATEGY_ENFORCED_AUDIBLE;
3495 }
3496}
3497
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07003498uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
3499 // flags to strategy mapping
3500 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
3501 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
3502 }
3503
3504 // usage to strategy mapping
3505 switch (attr->usage) {
3506 case AUDIO_USAGE_MEDIA:
3507 case AUDIO_USAGE_GAME:
3508 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
3509 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
3510 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
3511 return (uint32_t) STRATEGY_MEDIA;
3512
3513 case AUDIO_USAGE_VOICE_COMMUNICATION:
3514 return (uint32_t) STRATEGY_PHONE;
3515
3516 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
3517 return (uint32_t) STRATEGY_DTMF;
3518
3519 case AUDIO_USAGE_ALARM:
3520 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
3521 return (uint32_t) STRATEGY_SONIFICATION;
3522
3523 case AUDIO_USAGE_NOTIFICATION:
3524 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
3525 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
3526 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
3527 case AUDIO_USAGE_NOTIFICATION_EVENT:
3528 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
3529
3530 case AUDIO_USAGE_UNKNOWN:
3531 default:
3532 return (uint32_t) STRATEGY_MEDIA;
3533 }
3534}
3535
Eric Laurente0720872014-03-11 09:30:41 -07003536void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07003537 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07003538 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07003539 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
3540 updateDevicesAndOutputs();
3541 break;
3542 default:
3543 break;
3544 }
3545}
3546
Eric Laurente0720872014-03-11 09:30:41 -07003547audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003548 bool fromCache)
3549{
3550 uint32_t device = AUDIO_DEVICE_NONE;
3551
3552 if (fromCache) {
3553 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
3554 strategy, mDeviceForStrategy[strategy]);
3555 return mDeviceForStrategy[strategy];
3556 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003557 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07003558 switch (strategy) {
3559
3560 case STRATEGY_SONIFICATION_RESPECTFUL:
3561 if (isInCall()) {
3562 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003563 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07003564 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
3565 // while media is playing on a remote device, use the the sonification behavior.
3566 // Note that we test this usecase before testing if media is playing because
3567 // the isStreamActive() method only informs about the activity of a stream, not
3568 // if it's for local playback. Note also that we use the same delay between both tests
3569 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07003570 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003571 // while media is playing (or has recently played), use the same device
3572 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3573 } else {
3574 // when media is not playing anymore, fall back on the sonification behavior
3575 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
3576 }
3577
3578 break;
3579
3580 case STRATEGY_DTMF:
3581 if (!isInCall()) {
3582 // when off call, DTMF strategy follows the same rules as MEDIA strategy
3583 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
3584 break;
3585 }
3586 // when in call, DTMF and PHONE strategies follow the same rules
3587 // FALL THROUGH
3588
3589 case STRATEGY_PHONE:
3590 // for phone strategy, we first consider the forced use and then the available devices by order
3591 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07003592 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
3593 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07003594 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003595 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003596 if (device) break;
3597 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003598 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003599 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003600 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07003601 if (device) break;
3602 // if SCO device is requested but no SCO device is available, fall back to default case
3603 // FALL THROUGH
3604
3605 default: // FORCE_NONE
3606 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07003607 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003608 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003609 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003610 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003611 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003612 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003613 if (device) break;
3614 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003615 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003616 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003617 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003618 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07003619 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003620 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003621 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003622 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003623 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003624 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003625 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003626 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003627 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003628 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003629 if (device) break;
3630 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003631 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07003632 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003633 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003634 if (device == AUDIO_DEVICE_NONE) {
3635 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
3636 }
3637 break;
3638
Eric Laurent3b73df72014-03-11 09:06:29 -07003639 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07003640 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
3641 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07003642 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003643 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003644 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003645 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003646 if (device) break;
3647 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003648 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003649 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003650 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003651 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003652 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003653 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003654 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003655 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003656 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003657 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003658 if (device) break;
3659 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003660 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003661 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003662 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003663 if (device == AUDIO_DEVICE_NONE) {
3664 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
3665 }
3666 break;
3667 }
3668 break;
3669
3670 case STRATEGY_SONIFICATION:
3671
3672 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
3673 // handleIncallSonification().
3674 if (isInCall()) {
3675 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
3676 break;
3677 }
3678 // FALL THROUGH
3679
3680 case STRATEGY_ENFORCED_AUDIBLE:
3681 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
3682 // except:
3683 // - when in call where it doesn't default to STRATEGY_PHONE behavior
3684 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
3685
3686 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07003687 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003688 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003689 if (device == AUDIO_DEVICE_NONE) {
3690 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
3691 }
3692 }
3693 // The second device used for sonification is the same as the device used by media strategy
3694 // FALL THROUGH
3695
3696 case STRATEGY_MEDIA: {
3697 uint32_t device2 = AUDIO_DEVICE_NONE;
3698 if (strategy != STRATEGY_SONIFICATION) {
3699 // no sonification on remote submix (e.g. WFD)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003700 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurente552edb2014-03-10 17:42:56 -07003701 }
3702 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003703 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurente552edb2014-03-10 17:42:56 -07003704 (getA2dpOutput() != 0) && !mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003705 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07003706 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003707 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07003708 }
3709 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003710 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003711 }
3712 }
3713 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003714 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003715 }
3716 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003717 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003718 }
3719 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003720 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07003721 }
3722 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003723 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07003724 }
3725 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003726 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003727 }
3728 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
3729 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07003730 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07003731 }
3732 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07003733 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003734 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07003735 }
3736 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07003737 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07003738 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09003739 int device3 = AUDIO_DEVICE_NONE;
3740 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003741 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09003742 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
3743 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003744 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09003745 }
Eric Laurente552edb2014-03-10 17:42:56 -07003746
Jungshik Jang839e4f32014-06-26 17:23:40 +09003747 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07003748 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
3749 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
3750 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09003751
Jungshik Jang7b24ee32014-07-15 19:38:42 +09003752 // If hdmi system audio mode is on, remove speaker out of output list.
3753 if ((strategy == STRATEGY_MEDIA) &&
3754 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
3755 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
3756 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
3757 }
3758
Eric Laurente552edb2014-03-10 17:42:56 -07003759 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07003760 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07003761 if (device == AUDIO_DEVICE_NONE) {
3762 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
3763 }
3764 } break;
3765
3766 default:
3767 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
3768 break;
3769 }
3770
3771 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
3772 return device;
3773}
3774
Eric Laurente0720872014-03-11 09:30:41 -07003775void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07003776{
3777 for (int i = 0; i < NUM_STRATEGIES; i++) {
3778 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3779 }
3780 mPreviousOutputs = mOutputs;
3781}
3782
Eric Laurent1f2f2232014-06-02 12:01:23 -07003783uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07003784 audio_devices_t prevDevice,
3785 uint32_t delayMs)
3786{
3787 // mute/unmute strategies using an incompatible device combination
3788 // if muting, wait for the audio in pcm buffer to be drained before proceeding
3789 // if unmuting, unmute only after the specified delay
3790 if (outputDesc->isDuplicated()) {
3791 return 0;
3792 }
3793
3794 uint32_t muteWaitMs = 0;
3795 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07003796 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07003797
3798 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3799 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
3800 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
3801 bool doMute = false;
3802
3803 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
3804 doMute = true;
3805 outputDesc->mStrategyMutedByDevice[i] = true;
3806 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
3807 doMute = true;
3808 outputDesc->mStrategyMutedByDevice[i] = false;
3809 }
Eric Laurent99401132014-05-07 19:48:15 -07003810 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07003811 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003812 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07003813 // skip output if it does not share any device with current output
3814 if ((desc->supportedDevices() & outputDesc->supportedDevices())
3815 == AUDIO_DEVICE_NONE) {
3816 continue;
3817 }
3818 audio_io_handle_t curOutput = mOutputs.keyAt(j);
3819 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
3820 mute ? "muting" : "unmuting", i, curDevice, curOutput);
3821 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
3822 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07003823 if (mute) {
3824 // FIXME: should not need to double latency if volume could be applied
3825 // immediately by the audioflinger mixer. We must account for the delay
3826 // between now and the next time the audioflinger thread for this output
3827 // will process a buffer (which corresponds to one buffer size,
3828 // usually 1/2 or 1/4 of the latency).
3829 if (muteWaitMs < desc->latency() * 2) {
3830 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07003831 }
3832 }
3833 }
3834 }
3835 }
3836 }
3837
Eric Laurent99401132014-05-07 19:48:15 -07003838 // temporary mute output if device selection changes to avoid volume bursts due to
3839 // different per device volumes
3840 if (outputDesc->isActive() && (device != prevDevice)) {
3841 if (muteWaitMs < outputDesc->latency() * 2) {
3842 muteWaitMs = outputDesc->latency() * 2;
3843 }
3844 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
3845 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003846 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07003847 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07003848 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07003849 muteWaitMs *2, device);
3850 }
3851 }
3852 }
3853
Eric Laurente552edb2014-03-10 17:42:56 -07003854 // wait for the PCM output buffers to empty before proceeding with the rest of the command
3855 if (muteWaitMs > delayMs) {
3856 muteWaitMs -= delayMs;
3857 usleep(muteWaitMs * 1000);
3858 return muteWaitMs;
3859 }
3860 return 0;
3861}
3862
Eric Laurente0720872014-03-11 09:30:41 -07003863uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07003864 audio_devices_t device,
3865 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07003866 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003867 audio_patch_handle_t *patchHandle,
3868 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07003869{
3870 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07003871 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003872 AudioParameter param;
3873 uint32_t muteWaitMs;
3874
3875 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003876 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
3877 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07003878 return muteWaitMs;
3879 }
3880 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
3881 // output profile
3882 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07003883 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003884 return 0;
3885 }
3886
3887 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07003888 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07003889
3890 audio_devices_t prevDevice = outputDesc->mDevice;
3891
3892 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
3893
3894 if (device != AUDIO_DEVICE_NONE) {
3895 outputDesc->mDevice = device;
3896 }
3897 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
3898
3899 // Do not change the routing if:
3900 // - the requested device is AUDIO_DEVICE_NONE
3901 // - the requested device is the same as current device and force is not specified.
3902 // Doing this check here allows the caller to call setOutputDevice() without conditions
3903 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force) {
3904 ALOGV("setOutputDevice() setting same device %04x or null device for output %d", device, output);
3905 return muteWaitMs;
3906 }
3907
3908 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07003909
Eric Laurente552edb2014-03-10 17:42:56 -07003910 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07003911 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003912 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07003913 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003914 DeviceVector deviceList = (address == NULL) ?
3915 mAvailableOutputDevices.getDevicesFromType(device)
3916 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07003917 if (!deviceList.isEmpty()) {
3918 struct audio_patch patch;
3919 outputDesc->toAudioPortConfig(&patch.sources[0]);
3920 patch.num_sources = 1;
3921 patch.num_sinks = 0;
3922 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
3923 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07003924 patch.num_sinks++;
3925 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003926 ssize_t index;
3927 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
3928 index = mAudioPatches.indexOfKey(*patchHandle);
3929 } else {
3930 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3931 }
3932 sp< AudioPatch> patchDesc;
3933 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
3934 if (index >= 0) {
3935 patchDesc = mAudioPatches.valueAt(index);
3936 afPatchHandle = patchDesc->mAfPatchHandle;
3937 }
3938
Eric Laurent1c333e22014-05-20 10:48:17 -07003939 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07003940 &afPatchHandle,
3941 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003942 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
3943 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07003944 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07003945 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003946 if (index < 0) {
3947 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
3948 &patch, mUidCached);
3949 addAudioPatch(patchDesc->mHandle, patchDesc);
3950 } else {
3951 patchDesc->mPatch = patch;
3952 }
3953 patchDesc->mAfPatchHandle = afPatchHandle;
3954 patchDesc->mUid = mUidCached;
3955 if (patchHandle) {
3956 *patchHandle = patchDesc->mHandle;
3957 }
3958 outputDesc->mPatchHandle = patchDesc->mHandle;
3959 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003960 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003961 }
3962 }
3963 }
Eric Laurente552edb2014-03-10 17:42:56 -07003964
3965 // update stream volumes according to new device
3966 applyStreamVolumes(output, device, delayMs);
3967
3968 return muteWaitMs;
3969}
3970
Eric Laurent1c333e22014-05-20 10:48:17 -07003971status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07003972 int delayMs,
3973 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003974{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003975 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003976 ssize_t index;
3977 if (patchHandle) {
3978 index = mAudioPatches.indexOfKey(*patchHandle);
3979 } else {
3980 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
3981 }
3982 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003983 return INVALID_OPERATION;
3984 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003985 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
3986 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07003987 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
3988 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07003989 removeAudioPatch(patchDesc->mHandle);
3990 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07003991 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07003992 return status;
3993}
3994
3995status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
3996 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07003997 bool force,
3998 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07003999{
4000 status_t status = NO_ERROR;
4001
Eric Laurent1f2f2232014-06-02 12:01:23 -07004002 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07004003 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
4004 inputDesc->mDevice = device;
4005
4006 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
4007 if (!deviceList.isEmpty()) {
4008 struct audio_patch patch;
4009 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07004010 // AUDIO_SOURCE_HOTWORD is for internal use only:
4011 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
4012 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD) {
4013 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
4014 }
Eric Laurent1c333e22014-05-20 10:48:17 -07004015 patch.num_sinks = 1;
4016 //only one input device for now
4017 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004018 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07004019 ssize_t index;
4020 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4021 index = mAudioPatches.indexOfKey(*patchHandle);
4022 } else {
4023 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4024 }
4025 sp< AudioPatch> patchDesc;
4026 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4027 if (index >= 0) {
4028 patchDesc = mAudioPatches.valueAt(index);
4029 afPatchHandle = patchDesc->mAfPatchHandle;
4030 }
4031
Eric Laurent1c333e22014-05-20 10:48:17 -07004032 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004033 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07004034 0);
4035 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004036 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004037 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004038 if (index < 0) {
4039 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4040 &patch, mUidCached);
4041 addAudioPatch(patchDesc->mHandle, patchDesc);
4042 } else {
4043 patchDesc->mPatch = patch;
4044 }
4045 patchDesc->mAfPatchHandle = afPatchHandle;
4046 patchDesc->mUid = mUidCached;
4047 if (patchHandle) {
4048 *patchHandle = patchDesc->mHandle;
4049 }
4050 inputDesc->mPatchHandle = patchDesc->mHandle;
4051 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004052 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004053 }
4054 }
4055 }
4056 return status;
4057}
4058
Eric Laurent6a94d692014-05-20 11:18:06 -07004059status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
4060 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07004061{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004062 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004063 ssize_t index;
4064 if (patchHandle) {
4065 index = mAudioPatches.indexOfKey(*patchHandle);
4066 } else {
4067 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4068 }
4069 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004070 return INVALID_OPERATION;
4071 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004072 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4073 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07004074 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
4075 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07004076 removeAudioPatch(patchDesc->mHandle);
4077 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004078 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004079 return status;
4080}
4081
4082sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Glenn Kastencbd48022014-07-24 13:46:44 -07004083 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07004084 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004085 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07004086 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07004087{
4088 // Choose an input profile based on the requested capture parameters: select the first available
4089 // profile supporting all requested parameters.
4090
4091 for (size_t i = 0; i < mHwModules.size(); i++)
4092 {
4093 if (mHwModules[i]->mHandle == 0) {
4094 continue;
4095 }
4096 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
4097 {
Eric Laurent1c333e22014-05-20 10:48:17 -07004098 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07004099 // profile->log();
Glenn Kastencbd48022014-07-24 13:46:44 -07004100 if (profile->isCompatibleProfile(device, samplingRate,
4101 &samplingRate /*updatedSamplingRate*/,
4102 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004103 return profile;
4104 }
4105 }
4106 }
4107 return NULL;
4108}
4109
Eric Laurente0720872014-03-11 09:30:41 -07004110audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
Eric Laurente552edb2014-03-10 17:42:56 -07004111{
4112 uint32_t device = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004113 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
4114 ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07004115 switch (inputSource) {
4116 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004117 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004118 device = AUDIO_DEVICE_IN_VOICE_CALL;
4119 break;
4120 }
4121 // FALL THROUGH
4122
4123 case AUDIO_SOURCE_DEFAULT:
4124 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07004125 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
4126 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
4127 break;
4128 }
4129 // FALL THROUGH
4130
Eric Laurente552edb2014-03-10 17:42:56 -07004131 case AUDIO_SOURCE_VOICE_RECOGNITION:
4132 case AUDIO_SOURCE_HOTWORD:
4133 case AUDIO_SOURCE_VOICE_COMMUNICATION:
Eric Laurent3b73df72014-03-11 09:06:29 -07004134 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004135 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004136 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004137 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07004138 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07004139 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
4140 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004141 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004142 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4143 }
4144 break;
4145 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004146 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004147 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004148 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07004149 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
4150 }
4151 break;
4152 case AUDIO_SOURCE_VOICE_DOWNLINK:
4153 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004154 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004155 device = AUDIO_DEVICE_IN_VOICE_CALL;
4156 }
4157 break;
4158 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07004159 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07004160 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4161 }
4162 break;
4163 default:
4164 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
4165 break;
4166 }
4167 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
4168 return device;
4169}
4170
Eric Laurente0720872014-03-11 09:30:41 -07004171bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004172{
4173 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
4174 device &= ~AUDIO_DEVICE_BIT_IN;
4175 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
4176 return true;
4177 }
4178 return false;
4179}
4180
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004181bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
4182 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL) != 0);
4183}
4184
Eric Laurente0720872014-03-11 09:30:41 -07004185audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004186{
4187 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004188 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004189 if ((input_descriptor->mRefCount > 0)
4190 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
4191 return mInputs.keyAt(i);
4192 }
4193 }
4194 return 0;
4195}
4196
4197
Eric Laurente0720872014-03-11 09:30:41 -07004198audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004199{
4200 if (device == AUDIO_DEVICE_NONE) {
4201 // this happens when forcing a route update and no track is active on an output.
4202 // In this case the returned category is not important.
4203 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07004204 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07004205 // Multiple device selection is either:
4206 // - speaker + one other device: give priority to speaker in this case.
4207 // - one A2DP device + another device: happens with duplicated output. In this case
4208 // retain the device on the A2DP output as the other must not correspond to an active
4209 // selection if not the speaker.
4210 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
4211 device = AUDIO_DEVICE_OUT_SPEAKER;
4212 } else {
4213 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
4214 }
4215 }
4216
Eric Laurent3b73df72014-03-11 09:06:29 -07004217 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07004218 "getDeviceForVolume() invalid device combination: %08x",
4219 device);
4220
4221 return device;
4222}
4223
Eric Laurente0720872014-03-11 09:30:41 -07004224AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004225{
4226 switch(getDeviceForVolume(device)) {
4227 case AUDIO_DEVICE_OUT_EARPIECE:
4228 return DEVICE_CATEGORY_EARPIECE;
4229 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
4230 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
4231 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
4232 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
4233 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
4234 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
4235 return DEVICE_CATEGORY_HEADSET;
4236 case AUDIO_DEVICE_OUT_SPEAKER:
4237 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
4238 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
4239 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
4240 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
4241 case AUDIO_DEVICE_OUT_USB_DEVICE:
4242 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
4243 default:
4244 return DEVICE_CATEGORY_SPEAKER;
4245 }
4246}
4247
Eric Laurente0720872014-03-11 09:30:41 -07004248float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004249 int indexInUi)
4250{
4251 device_category deviceCategory = getDeviceCategory(device);
4252 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
4253
4254 // the volume index in the UI is relative to the min and max volume indices for this stream type
4255 int nbSteps = 1 + curve[VOLMAX].mIndex -
4256 curve[VOLMIN].mIndex;
4257 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
4258 (streamDesc.mIndexMax - streamDesc.mIndexMin);
4259
4260 // find what part of the curve this index volume belongs to, or if it's out of bounds
4261 int segment = 0;
4262 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
4263 return 0.0f;
4264 } else if (volIdx < curve[VOLKNEE1].mIndex) {
4265 segment = 0;
4266 } else if (volIdx < curve[VOLKNEE2].mIndex) {
4267 segment = 1;
4268 } else if (volIdx <= curve[VOLMAX].mIndex) {
4269 segment = 2;
4270 } else { // out of bounds
4271 return 1.0f;
4272 }
4273
4274 // linear interpolation in the attenuation table in dB
4275 float decibels = curve[segment].mDBAttenuation +
4276 ((float)(volIdx - curve[segment].mIndex)) *
4277 ( (curve[segment+1].mDBAttenuation -
4278 curve[segment].mDBAttenuation) /
4279 ((float)(curve[segment+1].mIndex -
4280 curve[segment].mIndex)) );
4281
4282 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
4283
4284 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
4285 curve[segment].mIndex, volIdx,
4286 curve[segment+1].mIndex,
4287 curve[segment].mDBAttenuation,
4288 decibels,
4289 curve[segment+1].mDBAttenuation,
4290 amplification);
4291
4292 return amplification;
4293}
4294
Eric Laurente0720872014-03-11 09:30:41 -07004295const AudioPolicyManager::VolumeCurvePoint
4296 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004297 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
4298};
4299
Eric Laurente0720872014-03-11 09:30:41 -07004300const AudioPolicyManager::VolumeCurvePoint
4301 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004302 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
4303};
4304
Eric Laurente0720872014-03-11 09:30:41 -07004305const AudioPolicyManager::VolumeCurvePoint
4306 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004307 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
4308};
4309
Eric Laurente0720872014-03-11 09:30:41 -07004310const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004311 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07004312 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004313};
4314
4315const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07004316 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004317 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
4318};
4319
Eric Laurente0720872014-03-11 09:30:41 -07004320const AudioPolicyManager::VolumeCurvePoint
4321 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004322 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
4323};
4324
4325// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
4326// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
4327// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
4328// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
4329
Eric Laurente0720872014-03-11 09:30:41 -07004330const AudioPolicyManager::VolumeCurvePoint
4331 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004332 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
4333};
4334
Eric Laurente0720872014-03-11 09:30:41 -07004335const AudioPolicyManager::VolumeCurvePoint
4336 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004337 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
4338};
4339
Eric Laurente0720872014-03-11 09:30:41 -07004340const AudioPolicyManager::VolumeCurvePoint
4341 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004342 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
4343};
4344
Eric Laurente0720872014-03-11 09:30:41 -07004345const AudioPolicyManager::VolumeCurvePoint
4346 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004347 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
4348};
4349
Eric Laurente0720872014-03-11 09:30:41 -07004350const AudioPolicyManager::VolumeCurvePoint
4351 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004352 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
4353};
4354
Eric Laurente0720872014-03-11 09:30:41 -07004355const AudioPolicyManager::VolumeCurvePoint
4356 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
4357 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07004358 { // AUDIO_STREAM_VOICE_CALL
4359 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4360 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4361 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4362 },
4363 { // AUDIO_STREAM_SYSTEM
4364 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4365 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4366 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4367 },
4368 { // AUDIO_STREAM_RING
4369 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4370 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4371 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4372 },
4373 { // AUDIO_STREAM_MUSIC
4374 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4375 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4376 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4377 },
4378 { // AUDIO_STREAM_ALARM
4379 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4380 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4381 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4382 },
4383 { // AUDIO_STREAM_NOTIFICATION
4384 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
4385 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4386 sDefaultVolumeCurve // DEVICE_CATEGORY_EARPIECE
4387 },
4388 { // AUDIO_STREAM_BLUETOOTH_SCO
4389 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
4390 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4391 sDefaultVoiceVolumeCurve // DEVICE_CATEGORY_EARPIECE
4392 },
4393 { // AUDIO_STREAM_ENFORCED_AUDIBLE
4394 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4395 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4396 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4397 },
4398 { // AUDIO_STREAM_DTMF
4399 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
4400 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4401 sDefaultSystemVolumeCurve // DEVICE_CATEGORY_EARPIECE
4402 },
4403 { // AUDIO_STREAM_TTS
4404 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
4405 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
4406 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EARPIECE
4407 },
4408};
4409
Eric Laurente0720872014-03-11 09:30:41 -07004410void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07004411{
4412 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
4413 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
4414 mStreams[i].mVolumeCurve[j] =
4415 sVolumeProfiles[i][j];
4416 }
4417 }
4418
4419 // Check availability of DRC on speaker path: if available, override some of the speaker curves
4420 if (mSpeakerDrcEnabled) {
4421 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4422 sDefaultSystemVolumeCurveDrc;
4423 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4424 sSpeakerSonificationVolumeCurveDrc;
4425 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4426 sSpeakerSonificationVolumeCurveDrc;
4427 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4428 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07004429 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
4430 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07004431 }
4432}
4433
Eric Laurente0720872014-03-11 09:30:41 -07004434float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004435 int index,
4436 audio_io_handle_t output,
4437 audio_devices_t device)
4438{
4439 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004440 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004441 StreamDescriptor &streamDesc = mStreams[stream];
4442
4443 if (device == AUDIO_DEVICE_NONE) {
4444 device = outputDesc->device();
4445 }
4446
Eric Laurente552edb2014-03-10 17:42:56 -07004447 volume = volIndexToAmpl(device, streamDesc, index);
4448
4449 // if a headset is connected, apply the following rules to ring tones and notifications
4450 // to avoid sound level bursts in user's ears:
4451 // - always attenuate ring tones and notifications volume by 6dB
4452 // - if music is playing, always limit the volume to current music volume,
4453 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07004454 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004455 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
4456 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
4457 AUDIO_DEVICE_OUT_WIRED_HEADSET |
4458 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
4459 ((stream_strategy == STRATEGY_SONIFICATION)
4460 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07004461 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07004462 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004463 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07004464 streamDesc.mCanBeMuted) {
4465 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
4466 // when the phone is ringing we must consider that music could have been paused just before
4467 // by the music application and behave as if music was active if the last music track was
4468 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07004469 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004470 mLimitRingtoneVolume) {
4471 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004472 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
4473 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07004474 output,
4475 musicDevice);
4476 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
4477 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
4478 if (volume > minVol) {
4479 volume = minVol;
4480 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
4481 }
4482 }
4483 }
4484
4485 return volume;
4486}
4487
Eric Laurente0720872014-03-11 09:30:41 -07004488status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004489 int index,
4490 audio_io_handle_t output,
4491 audio_devices_t device,
4492 int delayMs,
4493 bool force)
4494{
4495
4496 // do not change actual stream volume if the stream is muted
4497 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
4498 ALOGVV("checkAndSetVolume() stream %d muted count %d",
4499 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
4500 return NO_ERROR;
4501 }
4502
4503 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07004504 if ((stream == AUDIO_STREAM_VOICE_CALL &&
4505 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4506 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
4507 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004508 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07004509 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07004510 return INVALID_OPERATION;
4511 }
4512
4513 float volume = computeVolume(stream, index, output, device);
4514 // We actually change the volume if:
4515 // - the float value returned by computeVolume() changed
4516 // - the force flag is set
4517 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
4518 force) {
4519 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
4520 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
4521 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
4522 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07004523 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
4524 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004525 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004526 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004527 }
4528
Eric Laurent3b73df72014-03-11 09:06:29 -07004529 if (stream == AUDIO_STREAM_VOICE_CALL ||
4530 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07004531 float voiceVolume;
4532 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07004533 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07004534 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
4535 } else {
4536 voiceVolume = 1.0;
4537 }
4538
4539 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
4540 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
4541 mLastVoiceVolume = voiceVolume;
4542 }
4543 }
4544
4545 return NO_ERROR;
4546}
4547
Eric Laurente0720872014-03-11 09:30:41 -07004548void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004549 audio_devices_t device,
4550 int delayMs,
4551 bool force)
4552{
4553 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
4554
Eric Laurent3b73df72014-03-11 09:06:29 -07004555 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4556 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004557 mStreams[stream].getVolumeIndex(device),
4558 output,
4559 device,
4560 delayMs,
4561 force);
4562 }
4563}
4564
Eric Laurente0720872014-03-11 09:30:41 -07004565void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004566 bool on,
4567 audio_io_handle_t output,
4568 int delayMs,
4569 audio_devices_t device)
4570{
4571 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07004572 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
4573 if (getStrategy((audio_stream_type_t)stream) == strategy) {
4574 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07004575 }
4576 }
4577}
4578
Eric Laurente0720872014-03-11 09:30:41 -07004579void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004580 bool on,
4581 audio_io_handle_t output,
4582 int delayMs,
4583 audio_devices_t device)
4584{
4585 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07004586 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004587 if (device == AUDIO_DEVICE_NONE) {
4588 device = outputDesc->device();
4589 }
4590
4591 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
4592 stream, on, output, outputDesc->mMuteCount[stream], device);
4593
4594 if (on) {
4595 if (outputDesc->mMuteCount[stream] == 0) {
4596 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004597 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
4598 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004599 checkAndSetVolume(stream, 0, output, device, delayMs);
4600 }
4601 }
4602 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
4603 outputDesc->mMuteCount[stream]++;
4604 } else {
4605 if (outputDesc->mMuteCount[stream] == 0) {
4606 ALOGV("setStreamMute() unmuting non muted stream!");
4607 return;
4608 }
4609 if (--outputDesc->mMuteCount[stream] == 0) {
4610 checkAndSetVolume(stream,
4611 streamDesc.getVolumeIndex(device),
4612 output,
4613 device,
4614 delayMs);
4615 }
4616 }
4617}
4618
Eric Laurente0720872014-03-11 09:30:41 -07004619void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004620 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07004621{
4622 // if the stream pertains to sonification strategy and we are in call we must
4623 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
4624 // in the device used for phone strategy and play the tone if the selected device does not
4625 // interfere with the device used for phone strategy
4626 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
4627 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07004628 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07004629 if ((stream_strategy == STRATEGY_SONIFICATION) ||
4630 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004631 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004632 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
4633 stream, starting, outputDesc->mDevice, stateChange);
4634 if (outputDesc->mRefCount[stream]) {
4635 int muteCount = 1;
4636 if (stateChange) {
4637 muteCount = outputDesc->mRefCount[stream];
4638 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004639 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004640 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
4641 for (int i = 0; i < muteCount; i++) {
4642 setStreamMute(stream, starting, mPrimaryOutput);
4643 }
4644 } else {
4645 ALOGV("handleIncallSonification() high visibility");
4646 if (outputDesc->device() &
4647 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
4648 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
4649 for (int i = 0; i < muteCount; i++) {
4650 setStreamMute(stream, starting, mPrimaryOutput);
4651 }
4652 }
4653 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004654 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
4655 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07004656 } else {
4657 mpClientInterface->stopTone();
4658 }
4659 }
4660 }
4661 }
4662}
4663
Eric Laurente0720872014-03-11 09:30:41 -07004664bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07004665{
4666 return isStateInCall(mPhoneState);
4667}
4668
Eric Laurente0720872014-03-11 09:30:41 -07004669bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004670 return ((state == AUDIO_MODE_IN_CALL) ||
4671 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07004672}
4673
Eric Laurente0720872014-03-11 09:30:41 -07004674uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07004675{
4676 return MAX_EFFECTS_CPU_LOAD;
4677}
4678
Eric Laurente0720872014-03-11 09:30:41 -07004679uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07004680{
4681 return MAX_EFFECTS_MEMORY;
4682}
4683
Eric Laurent6a94d692014-05-20 11:18:06 -07004684
Eric Laurente552edb2014-03-10 17:42:56 -07004685// --- AudioOutputDescriptor class implementation
4686
Eric Laurente0720872014-03-11 09:30:41 -07004687AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07004688 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004689 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004690 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07004691 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
4692{
4693 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07004694 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004695 mRefCount[i] = 0;
4696 mCurVolume[i] = -1.0;
4697 mMuteCount[i] = 0;
4698 mStopTime[i] = 0;
4699 }
4700 for (int i = 0; i < NUM_STRATEGIES; i++) {
4701 mStrategyMutedByDevice[i] = false;
4702 }
4703 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004704 mAudioPort = profile;
Eric Laurentd8622372014-07-27 13:47:31 -07004705 mFlags = profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07004706 mSamplingRate = profile->pickSamplingRate();
4707 mFormat = profile->pickFormat();
4708 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07004709 if (profile->mGains.size() > 0) {
4710 profile->mGains[0]->getDefaultConfig(&mGain);
4711 }
Eric Laurente552edb2014-03-10 17:42:56 -07004712 }
4713}
4714
Eric Laurente0720872014-03-11 09:30:41 -07004715audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07004716{
4717 if (isDuplicated()) {
4718 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
4719 } else {
4720 return mDevice;
4721 }
4722}
4723
Eric Laurente0720872014-03-11 09:30:41 -07004724uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07004725{
4726 if (isDuplicated()) {
4727 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
4728 } else {
4729 return mLatency;
4730 }
4731}
4732
Eric Laurente0720872014-03-11 09:30:41 -07004733bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07004734 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07004735{
4736 if (isDuplicated()) {
4737 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
4738 } else if (outputDesc->isDuplicated()){
4739 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
4740 } else {
4741 return (mProfile->mModule == outputDesc->mProfile->mModule);
4742 }
4743}
4744
Eric Laurente0720872014-03-11 09:30:41 -07004745void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07004746 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07004747{
4748 // forward usage count change to attached outputs
4749 if (isDuplicated()) {
4750 mOutput1->changeRefCount(stream, delta);
4751 mOutput2->changeRefCount(stream, delta);
4752 }
4753 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004754 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
4755 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07004756 mRefCount[stream] = 0;
4757 return;
4758 }
4759 mRefCount[stream] += delta;
4760 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
4761}
4762
Eric Laurente0720872014-03-11 09:30:41 -07004763audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07004764{
4765 if (isDuplicated()) {
4766 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
4767 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004768 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07004769 }
4770}
4771
Eric Laurente0720872014-03-11 09:30:41 -07004772bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07004773{
4774 return isStrategyActive(NUM_STRATEGIES, inPastMs);
4775}
4776
Eric Laurente0720872014-03-11 09:30:41 -07004777bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004778 uint32_t inPastMs,
4779 nsecs_t sysTime) const
4780{
4781 if ((sysTime == 0) && (inPastMs != 0)) {
4782 sysTime = systemTime();
4783 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004784 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4785 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07004786 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004787 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004788 return true;
4789 }
4790 }
4791 return false;
4792}
4793
Eric Laurente0720872014-03-11 09:30:41 -07004794bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07004795 uint32_t inPastMs,
4796 nsecs_t sysTime) const
4797{
4798 if (mRefCount[stream] != 0) {
4799 return true;
4800 }
4801 if (inPastMs == 0) {
4802 return false;
4803 }
4804 if (sysTime == 0) {
4805 sysTime = systemTime();
4806 }
4807 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
4808 return true;
4809 }
4810 return false;
4811}
4812
Eric Laurent1c333e22014-05-20 10:48:17 -07004813void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004814 struct audio_port_config *dstConfig,
4815 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004816{
Eric Laurent84c70242014-06-23 08:46:27 -07004817 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
4818
Eric Laurent1f2f2232014-06-02 12:01:23 -07004819 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4820 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4821 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004822 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004823 }
4824 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4825
Eric Laurent6a94d692014-05-20 11:18:06 -07004826 dstConfig->id = mId;
4827 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
4828 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07004829 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4830 dstConfig->ext.mix.handle = mIoHandle;
4831 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07004832}
4833
4834void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
4835 struct audio_port *port) const
4836{
Eric Laurent84c70242014-06-23 08:46:27 -07004837 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07004838 mProfile->toAudioPort(port);
4839 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004840 toAudioPortConfig(&port->active_config);
4841 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004842 port->ext.mix.handle = mIoHandle;
4843 port->ext.mix.latency_class =
4844 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
4845}
Eric Laurente552edb2014-03-10 17:42:56 -07004846
Eric Laurente0720872014-03-11 09:30:41 -07004847status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004848{
4849 const size_t SIZE = 256;
4850 char buffer[SIZE];
4851 String8 result;
4852
4853 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4854 result.append(buffer);
4855 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
4856 result.append(buffer);
4857 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4858 result.append(buffer);
4859 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
4860 result.append(buffer);
4861 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
4862 result.append(buffer);
4863 snprintf(buffer, SIZE, " Devices %08x\n", device());
4864 result.append(buffer);
4865 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
4866 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07004867 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
4868 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
4869 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004870 result.append(buffer);
4871 }
4872 write(fd, result.string(), result.size());
4873
4874 return NO_ERROR;
4875}
4876
4877// --- AudioInputDescriptor class implementation
4878
Eric Laurent1c333e22014-05-20 10:48:17 -07004879AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07004880 : mId(0), mIoHandle(0),
Eric Laurent1c333e22014-05-20 10:48:17 -07004881 mDevice(AUDIO_DEVICE_NONE), mPatchHandle(0), mRefCount(0),
Eric Laurent3b73df72014-03-11 09:06:29 -07004882 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile)
Eric Laurente552edb2014-03-10 17:42:56 -07004883{
Eric Laurent3a4311c2014-03-17 12:00:47 -07004884 if (profile != NULL) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004885 mAudioPort = profile;
Eric Laurent1e693b52014-07-09 15:03:28 -07004886 mSamplingRate = profile->pickSamplingRate();
4887 mFormat = profile->pickFormat();
4888 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07004889 if (profile->mGains.size() > 0) {
4890 profile->mGains[0]->getDefaultConfig(&mGain);
4891 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004892 }
Eric Laurente552edb2014-03-10 17:42:56 -07004893}
4894
Eric Laurent1c333e22014-05-20 10:48:17 -07004895void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07004896 struct audio_port_config *dstConfig,
4897 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07004898{
Eric Laurent84c70242014-06-23 08:46:27 -07004899 ALOG_ASSERT(mProfile != 0,
4900 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004901 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
4902 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
4903 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07004904 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07004905 }
4906
4907 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
4908
Eric Laurent6a94d692014-05-20 11:18:06 -07004909 dstConfig->id = mId;
4910 dstConfig->role = AUDIO_PORT_ROLE_SINK;
4911 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07004912 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
4913 dstConfig->ext.mix.handle = mIoHandle;
4914 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07004915}
4916
4917void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
4918 struct audio_port *port) const
4919{
Eric Laurent84c70242014-06-23 08:46:27 -07004920 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
4921
Eric Laurent1c333e22014-05-20 10:48:17 -07004922 mProfile->toAudioPort(port);
4923 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07004924 toAudioPortConfig(&port->active_config);
4925 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07004926 port->ext.mix.handle = mIoHandle;
4927 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
4928}
4929
Eric Laurente0720872014-03-11 09:30:41 -07004930status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004931{
4932 const size_t SIZE = 256;
4933 char buffer[SIZE];
4934 String8 result;
4935
4936 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
4937 result.append(buffer);
4938 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
4939 result.append(buffer);
4940 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
4941 result.append(buffer);
4942 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
4943 result.append(buffer);
4944 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
4945 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004946 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
4947 result.append(buffer);
4948
Eric Laurente552edb2014-03-10 17:42:56 -07004949 write(fd, result.string(), result.size());
4950
4951 return NO_ERROR;
4952}
4953
4954// --- StreamDescriptor class implementation
4955
Eric Laurente0720872014-03-11 09:30:41 -07004956AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07004957 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
4958{
4959 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
4960}
4961
Eric Laurente0720872014-03-11 09:30:41 -07004962int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07004963{
Eric Laurente0720872014-03-11 09:30:41 -07004964 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07004965 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
4966 if (mIndexCur.indexOfKey(device) < 0) {
4967 device = AUDIO_DEVICE_OUT_DEFAULT;
4968 }
4969 return mIndexCur.valueFor(device);
4970}
4971
Eric Laurente0720872014-03-11 09:30:41 -07004972void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004973{
4974 const size_t SIZE = 256;
4975 char buffer[SIZE];
4976 String8 result;
4977
4978 snprintf(buffer, SIZE, "%s %02d %02d ",
4979 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
4980 result.append(buffer);
4981 for (size_t i = 0; i < mIndexCur.size(); i++) {
4982 snprintf(buffer, SIZE, "%04x : %02d, ",
4983 mIndexCur.keyAt(i),
4984 mIndexCur.valueAt(i));
4985 result.append(buffer);
4986 }
4987 result.append("\n");
4988
4989 write(fd, result.string(), result.size());
4990}
4991
4992// --- EffectDescriptor class implementation
4993
Eric Laurente0720872014-03-11 09:30:41 -07004994status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07004995{
4996 const size_t SIZE = 256;
4997 char buffer[SIZE];
4998 String8 result;
4999
5000 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
5001 result.append(buffer);
5002 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
5003 result.append(buffer);
5004 snprintf(buffer, SIZE, " Session: %d\n", mSession);
5005 result.append(buffer);
5006 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
5007 result.append(buffer);
5008 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
5009 result.append(buffer);
5010 write(fd, result.string(), result.size());
5011
5012 return NO_ERROR;
5013}
5014
Eric Laurent1c333e22014-05-20 10:48:17 -07005015// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07005016
Eric Laurente0720872014-03-11 09:30:41 -07005017AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07005018 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
5019 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07005020{
5021}
5022
Eric Laurente0720872014-03-11 09:30:41 -07005023AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07005024{
5025 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005026 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005027 }
5028 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005029 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005030 }
5031 free((void *)mName);
5032}
5033
Eric Laurent1afeecb2014-05-14 08:52:28 -07005034status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
5035{
5036 cnode *node = root->first_child;
5037
5038 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
5039
5040 while (node) {
5041 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5042 profile->loadSamplingRates((char *)node->value);
5043 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5044 profile->loadFormats((char *)node->value);
5045 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5046 profile->loadInChannels((char *)node->value);
5047 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5048 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5049 mDeclaredDevices);
5050 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5051 profile->loadGains(node);
5052 }
5053 node = node->next;
5054 }
5055 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5056 "loadInput() invalid supported devices");
5057 ALOGW_IF(profile->mChannelMasks.size() == 0,
5058 "loadInput() invalid supported channel masks");
5059 ALOGW_IF(profile->mSamplingRates.size() == 0,
5060 "loadInput() invalid supported sampling rates");
5061 ALOGW_IF(profile->mFormats.size() == 0,
5062 "loadInput() invalid supported formats");
5063 if (!profile->mSupportedDevices.isEmpty() &&
5064 (profile->mChannelMasks.size() != 0) &&
5065 (profile->mSamplingRates.size() != 0) &&
5066 (profile->mFormats.size() != 0)) {
5067
5068 ALOGV("loadInput() adding input Supported Devices %04x",
5069 profile->mSupportedDevices.types());
5070
5071 mInputProfiles.add(profile);
5072 return NO_ERROR;
5073 } else {
5074 return BAD_VALUE;
5075 }
5076}
5077
5078status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
5079{
5080 cnode *node = root->first_child;
5081
5082 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
5083
5084 while (node) {
5085 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
5086 profile->loadSamplingRates((char *)node->value);
5087 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
5088 profile->loadFormats((char *)node->value);
5089 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5090 profile->loadOutChannels((char *)node->value);
5091 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
5092 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
5093 mDeclaredDevices);
5094 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
5095 profile->mFlags = parseFlagNames((char *)node->value);
5096 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5097 profile->loadGains(node);
5098 }
5099 node = node->next;
5100 }
5101 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
5102 "loadOutput() invalid supported devices");
5103 ALOGW_IF(profile->mChannelMasks.size() == 0,
5104 "loadOutput() invalid supported channel masks");
5105 ALOGW_IF(profile->mSamplingRates.size() == 0,
5106 "loadOutput() invalid supported sampling rates");
5107 ALOGW_IF(profile->mFormats.size() == 0,
5108 "loadOutput() invalid supported formats");
5109 if (!profile->mSupportedDevices.isEmpty() &&
5110 (profile->mChannelMasks.size() != 0) &&
5111 (profile->mSamplingRates.size() != 0) &&
5112 (profile->mFormats.size() != 0)) {
5113
5114 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
5115 profile->mSupportedDevices.types(), profile->mFlags);
5116
5117 mOutputProfiles.add(profile);
5118 return NO_ERROR;
5119 } else {
5120 return BAD_VALUE;
5121 }
5122}
5123
5124status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
5125{
5126 cnode *node = root->first_child;
5127
5128 audio_devices_t type = AUDIO_DEVICE_NONE;
5129 while (node) {
5130 if (strcmp(node->name, DEVICE_TYPE) == 0) {
5131 type = parseDeviceNames((char *)node->value);
5132 break;
5133 }
5134 node = node->next;
5135 }
5136 if (type == AUDIO_DEVICE_NONE ||
5137 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
5138 ALOGW("loadDevice() bad type %08x", type);
5139 return BAD_VALUE;
5140 }
5141 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
5142 deviceDesc->mModule = this;
5143
5144 node = root->first_child;
5145 while (node) {
5146 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
5147 deviceDesc->mAddress = String8((char *)node->value);
5148 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
5149 if (audio_is_input_device(type)) {
5150 deviceDesc->loadInChannels((char *)node->value);
5151 } else {
5152 deviceDesc->loadOutChannels((char *)node->value);
5153 }
5154 } else if (strcmp(node->name, GAINS_TAG) == 0) {
5155 deviceDesc->loadGains(node);
5156 }
5157 node = node->next;
5158 }
5159
5160 ALOGV("loadDevice() adding device name %s type %08x address %s",
5161 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
5162
5163 mDeclaredDevices.add(deviceDesc);
5164
5165 return NO_ERROR;
5166}
5167
Eric Laurente0720872014-03-11 09:30:41 -07005168void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07005169{
5170 const size_t SIZE = 256;
5171 char buffer[SIZE];
5172 String8 result;
5173
5174 snprintf(buffer, SIZE, " - name: %s\n", mName);
5175 result.append(buffer);
5176 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
5177 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07005178 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
5179 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07005180 write(fd, result.string(), result.size());
5181 if (mOutputProfiles.size()) {
5182 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
5183 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005184 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005185 write(fd, buffer, strlen(buffer));
5186 mOutputProfiles[i]->dump(fd);
5187 }
5188 }
5189 if (mInputProfiles.size()) {
5190 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
5191 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07005192 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07005193 write(fd, buffer, strlen(buffer));
5194 mInputProfiles[i]->dump(fd);
5195 }
5196 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005197 if (mDeclaredDevices.size()) {
5198 write(fd, " - devices:\n", strlen(" - devices:\n"));
5199 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
5200 mDeclaredDevices[i]->dump(fd, 4, i);
5201 }
5202 }
Eric Laurente552edb2014-03-10 17:42:56 -07005203}
5204
Eric Laurent1c333e22014-05-20 10:48:17 -07005205// --- AudioPort class implementation
5206
Eric Laurenta121f902014-06-03 13:32:54 -07005207
5208AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
5209 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent1e693b52014-07-09 15:03:28 -07005210 mName(name), mType(type), mRole(role), mModule(module), mFlags((audio_output_flags_t)0)
Eric Laurenta121f902014-06-03 13:32:54 -07005211{
5212 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
5213 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
5214}
5215
Eric Laurent1c333e22014-05-20 10:48:17 -07005216void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
5217{
5218 port->role = mRole;
5219 port->type = mType;
5220 unsigned int i;
5221 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
5222 port->sample_rates[i] = mSamplingRates[i];
5223 }
5224 port->num_sample_rates = i;
5225 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
5226 port->channel_masks[i] = mChannelMasks[i];
5227 }
5228 port->num_channel_masks = i;
5229 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
5230 port->formats[i] = mFormats[i];
5231 }
5232 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07005233
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005234 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07005235
5236 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
5237 port->gains[i] = mGains[i]->mGain;
5238 }
5239 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07005240}
5241
5242
5243void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
5244{
5245 char *str = strtok(name, "|");
5246
5247 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
5248 // rates should be read from the output stream after it is opened for the first time
5249 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5250 mSamplingRates.add(0);
5251 return;
5252 }
5253
5254 while (str != NULL) {
5255 uint32_t rate = atoi(str);
5256 if (rate != 0) {
5257 ALOGV("loadSamplingRates() adding rate %d", rate);
5258 mSamplingRates.add(rate);
5259 }
5260 str = strtok(NULL, "|");
5261 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005262}
5263
5264void AudioPolicyManager::AudioPort::loadFormats(char *name)
5265{
5266 char *str = strtok(name, "|");
5267
5268 // by convention, "0' in the first entry in mFormats indicates the supported formats
5269 // should be read from the output stream after it is opened for the first time
5270 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5271 mFormats.add(AUDIO_FORMAT_DEFAULT);
5272 return;
5273 }
5274
5275 while (str != NULL) {
5276 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
5277 ARRAY_SIZE(sFormatNameToEnumTable),
5278 str);
5279 if (format != AUDIO_FORMAT_DEFAULT) {
5280 mFormats.add(format);
5281 }
5282 str = strtok(NULL, "|");
5283 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005284}
5285
5286void AudioPolicyManager::AudioPort::loadInChannels(char *name)
5287{
5288 const char *str = strtok(name, "|");
5289
5290 ALOGV("loadInChannels() %s", name);
5291
5292 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5293 mChannelMasks.add(0);
5294 return;
5295 }
5296
5297 while (str != NULL) {
5298 audio_channel_mask_t channelMask =
5299 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5300 ARRAY_SIZE(sInChannelsNameToEnumTable),
5301 str);
5302 if (channelMask != 0) {
5303 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
5304 mChannelMasks.add(channelMask);
5305 }
5306 str = strtok(NULL, "|");
5307 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005308}
5309
5310void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
5311{
5312 const char *str = strtok(name, "|");
5313
5314 ALOGV("loadOutChannels() %s", name);
5315
5316 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
5317 // masks should be read from the output stream after it is opened for the first time
5318 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
5319 mChannelMasks.add(0);
5320 return;
5321 }
5322
5323 while (str != NULL) {
5324 audio_channel_mask_t channelMask =
5325 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5326 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5327 str);
5328 if (channelMask != 0) {
5329 mChannelMasks.add(channelMask);
5330 }
5331 str = strtok(NULL, "|");
5332 }
5333 return;
5334}
5335
Eric Laurent1afeecb2014-05-14 08:52:28 -07005336audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
5337{
5338 const char *str = strtok(name, "|");
5339
5340 ALOGV("loadGainMode() %s", name);
5341 audio_gain_mode_t mode = 0;
5342 while (str != NULL) {
5343 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
5344 ARRAY_SIZE(sGainModeNameToEnumTable),
5345 str);
5346 str = strtok(NULL, "|");
5347 }
5348 return mode;
5349}
5350
Eric Laurenta121f902014-06-03 13:32:54 -07005351void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005352{
5353 cnode *node = root->first_child;
5354
Eric Laurenta121f902014-06-03 13:32:54 -07005355 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005356
5357 while (node) {
5358 if (strcmp(node->name, GAIN_MODE) == 0) {
5359 gain->mGain.mode = loadGainMode((char *)node->value);
5360 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07005361 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07005362 gain->mGain.channel_mask =
5363 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
5364 ARRAY_SIZE(sInChannelsNameToEnumTable),
5365 (char *)node->value);
5366 } else {
5367 gain->mGain.channel_mask =
5368 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
5369 ARRAY_SIZE(sOutChannelsNameToEnumTable),
5370 (char *)node->value);
5371 }
5372 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
5373 gain->mGain.min_value = atoi((char *)node->value);
5374 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
5375 gain->mGain.max_value = atoi((char *)node->value);
5376 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
5377 gain->mGain.default_value = atoi((char *)node->value);
5378 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
5379 gain->mGain.step_value = atoi((char *)node->value);
5380 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
5381 gain->mGain.min_ramp_ms = atoi((char *)node->value);
5382 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
5383 gain->mGain.max_ramp_ms = atoi((char *)node->value);
5384 }
5385 node = node->next;
5386 }
5387
5388 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
5389 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
5390
5391 if (gain->mGain.mode == 0) {
5392 return;
5393 }
5394 mGains.add(gain);
5395}
5396
5397void AudioPolicyManager::AudioPort::loadGains(cnode *root)
5398{
5399 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07005400 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005401 while (node) {
5402 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07005403 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07005404 node = node->next;
5405 }
5406}
5407
Glenn Kastencbd48022014-07-24 13:46:44 -07005408status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005409{
5410 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5411 if (mSamplingRates[i] == samplingRate) {
5412 return NO_ERROR;
5413 }
5414 }
5415 return BAD_VALUE;
5416}
5417
Glenn Kastencbd48022014-07-24 13:46:44 -07005418status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
5419 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07005420{
Glenn Kastencbd48022014-07-24 13:46:44 -07005421 // Search for the closest supported sampling rate that is above (preferred)
5422 // or below (acceptable) the desired sampling rate, within a permitted ratio.
5423 // The sampling rates do not need to be sorted in ascending order.
5424 ssize_t maxBelow = -1;
5425 ssize_t minAbove = -1;
5426 uint32_t candidate;
5427 for (size_t i = 0; i < mSamplingRates.size(); i++) {
5428 candidate = mSamplingRates[i];
5429 if (candidate == samplingRate) {
5430 if (updatedSamplingRate != NULL) {
5431 *updatedSamplingRate = candidate;
5432 }
5433 return NO_ERROR;
5434 }
5435 // candidate < desired
5436 if (candidate < samplingRate) {
5437 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
5438 maxBelow = i;
5439 }
5440 // candidate > desired
5441 } else {
5442 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
5443 minAbove = i;
5444 }
5445 }
5446 }
5447 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
5448 // TODO Move these assumptions out.
5449 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
5450 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
5451 // due to approximation by an int32_t of the
5452 // phase increments
5453 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
5454 if (minAbove >= 0) {
5455 candidate = mSamplingRates[minAbove];
5456 if (candidate / kMaxDownSampleRatio <= samplingRate) {
5457 if (updatedSamplingRate != NULL) {
5458 *updatedSamplingRate = candidate;
5459 }
5460 return NO_ERROR;
5461 }
5462 }
5463 // But if we have to up-sample from a lower sampling rate, that's OK.
5464 if (maxBelow >= 0) {
5465 candidate = mSamplingRates[maxBelow];
5466 if (candidate * kMaxUpSampleRatio >= samplingRate) {
5467 if (updatedSamplingRate != NULL) {
5468 *updatedSamplingRate = candidate;
5469 }
5470 return NO_ERROR;
5471 }
5472 }
5473 // leave updatedSamplingRate unmodified
5474 return BAD_VALUE;
5475}
5476
5477status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
5478{
5479 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07005480 if (mChannelMasks[i] == channelMask) {
5481 return NO_ERROR;
5482 }
5483 }
5484 return BAD_VALUE;
5485}
5486
Glenn Kastencbd48022014-07-24 13:46:44 -07005487status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
5488 const
5489{
5490 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
5491 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5492 // FIXME Does not handle multi-channel automatic conversions yet
5493 audio_channel_mask_t supported = mChannelMasks[i];
5494 if (supported == channelMask) {
5495 return NO_ERROR;
5496 }
5497 if (isRecordThread) {
5498 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
5499 // FIXME Abstract this out to a table.
5500 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
5501 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
5502 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
5503 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
5504 return NO_ERROR;
5505 }
5506 }
5507 }
5508 return BAD_VALUE;
5509}
5510
Eric Laurenta121f902014-06-03 13:32:54 -07005511status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
5512{
5513 for (size_t i = 0; i < mFormats.size(); i ++) {
5514 if (mFormats[i] == format) {
5515 return NO_ERROR;
5516 }
5517 }
5518 return BAD_VALUE;
5519}
5520
Eric Laurent1e693b52014-07-09 15:03:28 -07005521
5522uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
5523{
5524 // special case for uninitialized dynamic profile
5525 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
5526 return 0;
5527 }
5528
5529 uint32_t samplingRate = 0;
5530 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
5531
5532 // For mixed output and inputs, use max mixer sampling rates. Do not
5533 // limit sampling rate otherwise
5534 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5535 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5536 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5537 maxRate = UINT_MAX;
5538 }
5539 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
5540 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
5541 samplingRate = mSamplingRates[i];
5542 }
5543 }
5544 return samplingRate;
5545}
5546
5547audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
5548{
5549 // special case for uninitialized dynamic profile
5550 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
5551 return AUDIO_CHANNEL_NONE;
5552 }
5553
5554 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
5555 uint32_t channelCount = 0;
5556 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
5557
5558 // For mixed output and inputs, use max mixer channel count. Do not
5559 // limit channel count otherwise
5560 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5561 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
5562 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)))) {
5563 maxCount = UINT_MAX;
5564 }
5565 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
5566 uint32_t cnlCount;
5567 if (mUseInChannelMask) {
5568 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
5569 } else {
5570 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
5571 }
5572 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
5573 channelMask = mChannelMasks[i];
5574 }
5575 }
5576 return channelMask;
5577}
5578
Andy Hung9a605382014-07-28 16:16:31 -07005579/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07005580const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
5581 AUDIO_FORMAT_DEFAULT,
5582 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07005583 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005584 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07005585 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07005586 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07005587};
5588
5589int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
5590 audio_format_t format2)
5591{
5592 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
5593 // compressed format and better than any PCM format. This is by design of pickFormat()
5594 if (!audio_is_linear_pcm(format1)) {
5595 if (!audio_is_linear_pcm(format2)) {
5596 return 0;
5597 }
5598 return 1;
5599 }
5600 if (!audio_is_linear_pcm(format2)) {
5601 return -1;
5602 }
5603
5604 int index1 = -1, index2 = -1;
5605 for (size_t i = 0;
5606 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
5607 i ++) {
5608 if (sPcmFormatCompareTable[i] == format1) {
5609 index1 = i;
5610 }
5611 if (sPcmFormatCompareTable[i] == format2) {
5612 index2 = i;
5613 }
5614 }
5615 // format1 not found => index1 < 0 => format2 > format1
5616 // format2 not found => index2 < 0 => format2 < format1
5617 return index1 - index2;
5618}
5619
5620audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
5621{
5622 // special case for uninitialized dynamic profile
5623 if (mFormats.size() == 1 && mFormats[0] == 0) {
5624 return AUDIO_FORMAT_DEFAULT;
5625 }
5626
5627 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07005628 audio_format_t bestFormat =
5629 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
5630 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07005631 // For mixed output and inputs, use best mixer output format. Do not
5632 // limit format otherwise
5633 if ((mType != AUDIO_PORT_TYPE_MIX) ||
5634 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07005635 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005636 bestFormat = AUDIO_FORMAT_INVALID;
5637 }
5638
5639 for (size_t i = 0; i < mFormats.size(); i ++) {
5640 if ((compareFormats(mFormats[i], format) > 0) &&
5641 (compareFormats(mFormats[i], bestFormat) <= 0)) {
5642 format = mFormats[i];
5643 }
5644 }
5645 return format;
5646}
5647
Eric Laurenta121f902014-06-03 13:32:54 -07005648status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
5649 int index) const
5650{
5651 if (index < 0 || (size_t)index >= mGains.size()) {
5652 return BAD_VALUE;
5653 }
5654 return mGains[index]->checkConfig(gainConfig);
5655}
5656
Eric Laurent1afeecb2014-05-14 08:52:28 -07005657void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
5658{
5659 const size_t SIZE = 256;
5660 char buffer[SIZE];
5661 String8 result;
5662
5663 if (mName.size() != 0) {
5664 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
5665 result.append(buffer);
5666 }
5667
5668 if (mSamplingRates.size() != 0) {
5669 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
5670 result.append(buffer);
5671 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005672 if (i == 0 && mSamplingRates[i] == 0) {
5673 snprintf(buffer, SIZE, "Dynamic");
5674 } else {
5675 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
5676 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005677 result.append(buffer);
5678 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
5679 }
5680 result.append("\n");
5681 }
5682
5683 if (mChannelMasks.size() != 0) {
5684 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
5685 result.append(buffer);
5686 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005687 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
5688
5689 if (i == 0 && mChannelMasks[i] == 0) {
5690 snprintf(buffer, SIZE, "Dynamic");
5691 } else {
5692 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
5693 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005694 result.append(buffer);
5695 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
5696 }
5697 result.append("\n");
5698 }
5699
5700 if (mFormats.size() != 0) {
5701 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
5702 result.append(buffer);
5703 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07005704 const char *formatStr = enumToString(sFormatNameToEnumTable,
5705 ARRAY_SIZE(sFormatNameToEnumTable),
5706 mFormats[i]);
5707 if (i == 0 && strcmp(formatStr, "") == 0) {
5708 snprintf(buffer, SIZE, "Dynamic");
5709 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07005710 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07005711 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07005712 result.append(buffer);
5713 result.append(i == (mFormats.size() - 1) ? "" : ", ");
5714 }
5715 result.append("\n");
5716 }
5717 write(fd, result.string(), result.size());
5718 if (mGains.size() != 0) {
5719 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
5720 write(fd, buffer, strlen(buffer) + 1);
5721 result.append(buffer);
5722 for (size_t i = 0; i < mGains.size(); i++) {
5723 mGains[i]->dump(fd, spaces + 2, i);
5724 }
5725 }
5726}
5727
5728// --- AudioGain class implementation
5729
Eric Laurenta121f902014-06-03 13:32:54 -07005730AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07005731{
Eric Laurenta121f902014-06-03 13:32:54 -07005732 mIndex = index;
5733 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07005734 memset(&mGain, 0, sizeof(struct audio_gain));
5735}
5736
Eric Laurenta121f902014-06-03 13:32:54 -07005737void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
5738{
5739 config->index = mIndex;
5740 config->mode = mGain.mode;
5741 config->channel_mask = mGain.channel_mask;
5742 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5743 config->values[0] = mGain.default_value;
5744 } else {
5745 uint32_t numValues;
5746 if (mUseInChannelMask) {
5747 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
5748 } else {
5749 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
5750 }
5751 for (size_t i = 0; i < numValues; i++) {
5752 config->values[i] = mGain.default_value;
5753 }
5754 }
5755 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5756 config->ramp_duration_ms = mGain.min_ramp_ms;
5757 }
5758}
5759
5760status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
5761{
5762 if ((config->mode & ~mGain.mode) != 0) {
5763 return BAD_VALUE;
5764 }
5765 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
5766 if ((config->values[0] < mGain.min_value) ||
5767 (config->values[0] > mGain.max_value)) {
5768 return BAD_VALUE;
5769 }
5770 } else {
5771 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
5772 return BAD_VALUE;
5773 }
5774 uint32_t numValues;
5775 if (mUseInChannelMask) {
5776 numValues = audio_channel_count_from_in_mask(config->channel_mask);
5777 } else {
5778 numValues = audio_channel_count_from_out_mask(config->channel_mask);
5779 }
5780 for (size_t i = 0; i < numValues; i++) {
5781 if ((config->values[i] < mGain.min_value) ||
5782 (config->values[i] > mGain.max_value)) {
5783 return BAD_VALUE;
5784 }
5785 }
5786 }
5787 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
5788 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
5789 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
5790 return BAD_VALUE;
5791 }
5792 }
5793 return NO_ERROR;
5794}
5795
Eric Laurent1afeecb2014-05-14 08:52:28 -07005796void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
5797{
5798 const size_t SIZE = 256;
5799 char buffer[SIZE];
5800 String8 result;
5801
5802 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
5803 result.append(buffer);
5804 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
5805 result.append(buffer);
5806 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
5807 result.append(buffer);
5808 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
5809 result.append(buffer);
5810 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
5811 result.append(buffer);
5812 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
5813 result.append(buffer);
5814 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
5815 result.append(buffer);
5816 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
5817 result.append(buffer);
5818 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
5819 result.append(buffer);
5820
5821 write(fd, result.string(), result.size());
5822}
5823
Eric Laurent1f2f2232014-06-02 12:01:23 -07005824// --- AudioPortConfig class implementation
5825
5826AudioPolicyManager::AudioPortConfig::AudioPortConfig()
5827{
5828 mSamplingRate = 0;
5829 mChannelMask = AUDIO_CHANNEL_NONE;
5830 mFormat = AUDIO_FORMAT_INVALID;
5831 mGain.index = -1;
5832}
5833
Eric Laurenta121f902014-06-03 13:32:54 -07005834status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
5835 const struct audio_port_config *config,
5836 struct audio_port_config *backupConfig)
5837{
5838 struct audio_port_config localBackupConfig;
5839 status_t status = NO_ERROR;
5840
5841 localBackupConfig.config_mask = config->config_mask;
5842 toAudioPortConfig(&localBackupConfig);
5843
5844 if (mAudioPort == 0) {
5845 status = NO_INIT;
5846 goto exit;
5847 }
5848 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Glenn Kastencbd48022014-07-24 13:46:44 -07005849 status = mAudioPort->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07005850 if (status != NO_ERROR) {
5851 goto exit;
5852 }
5853 mSamplingRate = config->sample_rate;
5854 }
5855 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Glenn Kastencbd48022014-07-24 13:46:44 -07005856 status = mAudioPort->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07005857 if (status != NO_ERROR) {
5858 goto exit;
5859 }
5860 mChannelMask = config->channel_mask;
5861 }
5862 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5863 status = mAudioPort->checkFormat(config->format);
5864 if (status != NO_ERROR) {
5865 goto exit;
5866 }
5867 mFormat = config->format;
5868 }
5869 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5870 status = mAudioPort->checkGain(&config->gain, config->gain.index);
5871 if (status != NO_ERROR) {
5872 goto exit;
5873 }
5874 mGain = config->gain;
5875 }
5876
5877exit:
5878 if (status != NO_ERROR) {
5879 applyAudioPortConfig(&localBackupConfig);
5880 }
5881 if (backupConfig != NULL) {
5882 *backupConfig = localBackupConfig;
5883 }
5884 return status;
5885}
5886
Eric Laurent1f2f2232014-06-02 12:01:23 -07005887void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
5888 struct audio_port_config *dstConfig,
5889 const struct audio_port_config *srcConfig) const
5890{
5891 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
5892 dstConfig->sample_rate = mSamplingRate;
5893 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
5894 dstConfig->sample_rate = srcConfig->sample_rate;
5895 }
5896 } else {
5897 dstConfig->sample_rate = 0;
5898 }
5899 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
5900 dstConfig->channel_mask = mChannelMask;
5901 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
5902 dstConfig->channel_mask = srcConfig->channel_mask;
5903 }
5904 } else {
5905 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
5906 }
5907 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
5908 dstConfig->format = mFormat;
5909 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
5910 dstConfig->format = srcConfig->format;
5911 }
5912 } else {
5913 dstConfig->format = AUDIO_FORMAT_INVALID;
5914 }
5915 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
5916 dstConfig->gain = mGain;
5917 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
5918 dstConfig->gain = srcConfig->gain;
5919 }
5920 } else {
5921 dstConfig->gain.index = -1;
5922 }
5923 if (dstConfig->gain.index != -1) {
5924 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
5925 } else {
5926 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
5927 }
5928}
5929
Eric Laurent1c333e22014-05-20 10:48:17 -07005930// --- IOProfile class implementation
5931
Eric Laurent1afeecb2014-05-14 08:52:28 -07005932AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07005933 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07005934 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07005935{
5936}
5937
Eric Laurente0720872014-03-11 09:30:41 -07005938AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07005939{
5940}
5941
5942// checks if the IO profile is compatible with specified parameters.
5943// Sampling rate, format and channel mask must be specified in order to
5944// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07005945bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -07005946 uint32_t samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005947 uint32_t *updatedSamplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07005948 audio_format_t format,
5949 audio_channel_mask_t channelMask,
5950 audio_output_flags_t flags) const
5951{
Glenn Kastencbd48022014-07-24 13:46:44 -07005952 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
5953 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
5954 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07005955
Glenn Kastencbd48022014-07-24 13:46:44 -07005956 if ((mSupportedDevices.types() & device) != device) {
5957 return false;
5958 }
5959
5960 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07005961 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07005962 }
5963 uint32_t myUpdatedSamplingRate = samplingRate;
5964 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005965 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07005966 }
5967 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
5968 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07005969 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07005970 }
5971
5972 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
5973 return false;
5974 }
5975
5976 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
5977 checkExactChannelMask(channelMask) != NO_ERROR)) {
5978 return false;
5979 }
5980 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
5981 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
5982 return false;
5983 }
5984
5985 if (isPlaybackThread && (mFlags & flags) != flags) {
5986 return false;
5987 }
5988 // The only input flag that is allowed to be different is the fast flag.
5989 // An existing fast stream is compatible with a normal track request.
5990 // An existing normal stream is compatible with a fast track request,
5991 // but the fast request will be denied by AudioFlinger and converted to normal track.
5992 if (isRecordThread && (((audio_input_flags_t) mFlags ^ (audio_input_flags_t) flags) &
5993 ~AUDIO_INPUT_FLAG_FAST)) {
5994 return false;
5995 }
5996
5997 if (updatedSamplingRate != NULL) {
5998 *updatedSamplingRate = myUpdatedSamplingRate;
5999 }
6000 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07006001}
6002
Eric Laurente0720872014-03-11 09:30:41 -07006003void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006004{
6005 const size_t SIZE = 256;
6006 char buffer[SIZE];
6007 String8 result;
6008
Eric Laurent1afeecb2014-05-14 08:52:28 -07006009 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006010
Eric Laurente552edb2014-03-10 17:42:56 -07006011 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
6012 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006013 snprintf(buffer, SIZE, " - devices:\n");
6014 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006015 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07006016 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
6017 mSupportedDevices[i]->dump(fd, 6, i);
6018 }
Eric Laurente552edb2014-03-10 17:42:56 -07006019}
6020
Eric Laurentd4692962014-05-05 18:13:44 -07006021void AudioPolicyManager::IOProfile::log()
6022{
6023 const size_t SIZE = 256;
6024 char buffer[SIZE];
6025 String8 result;
6026
6027 ALOGV(" - sampling rates: ");
6028 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6029 ALOGV(" %d", mSamplingRates[i]);
6030 }
6031
6032 ALOGV(" - channel masks: ");
6033 for (size_t i = 0; i < mChannelMasks.size(); i++) {
6034 ALOGV(" 0x%04x", mChannelMasks[i]);
6035 }
6036
6037 ALOGV(" - formats: ");
6038 for (size_t i = 0; i < mFormats.size(); i++) {
6039 ALOGV(" 0x%08x", mFormats[i]);
6040 }
6041
6042 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
6043 ALOGV(" - flags: 0x%04x\n", mFlags);
6044}
6045
6046
Eric Laurent3a4311c2014-03-17 12:00:47 -07006047// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006048
Eric Laurent1f2f2232014-06-02 12:01:23 -07006049
6050AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
6051 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
6052 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
6053 AUDIO_PORT_ROLE_SOURCE,
6054 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07006055 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006056{
6057 mAudioPort = this;
Eric Laurenta121f902014-06-03 13:32:54 -07006058 if (mGains.size() > 0) {
6059 mGains[0]->getDefaultConfig(&mGain);
6060 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07006061}
6062
Eric Laurent3a4311c2014-03-17 12:00:47 -07006063bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07006064{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006065 // Devices are considered equal if they:
6066 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
6067 // - have the same address or one device does not specify the address
6068 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07006069 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07006070 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07006071 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07006072 mChannelMask == other->mChannelMask);
6073}
6074
6075void AudioPolicyManager::DeviceVector::refreshTypes()
6076{
Eric Laurent1c333e22014-05-20 10:48:17 -07006077 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006078 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006079 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006080 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006081 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006082}
6083
6084ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
6085{
6086 for(size_t i = 0; i < size(); i++) {
6087 if (item->equals(itemAt(i))) {
6088 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07006089 }
6090 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006091 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07006092}
6093
Eric Laurent3a4311c2014-03-17 12:00:47 -07006094ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07006095{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006096 ssize_t ret = indexOf(item);
6097
6098 if (ret < 0) {
6099 ret = SortedVector::add(item);
6100 if (ret >= 0) {
6101 refreshTypes();
6102 }
6103 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07006104 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006105 ret = -1;
6106 }
6107 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07006108}
6109
Eric Laurent3a4311c2014-03-17 12:00:47 -07006110ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
6111{
6112 size_t i;
6113 ssize_t ret = indexOf(item);
6114
6115 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006116 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006117 } else {
6118 ret = SortedVector::removeAt(ret);
6119 if (ret >= 0) {
6120 refreshTypes();
6121 }
6122 }
6123 return ret;
6124}
6125
6126void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
6127{
6128 DeviceVector deviceList;
6129
6130 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
6131 types &= ~role_bit;
6132
6133 while (types) {
6134 uint32_t i = 31 - __builtin_clz(types);
6135 uint32_t type = 1 << i;
6136 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006137 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07006138 }
6139}
6140
Eric Laurent1afeecb2014-05-14 08:52:28 -07006141void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
6142 const DeviceVector& declaredDevices)
6143{
6144 char *devName = strtok(name, "|");
6145 while (devName != NULL) {
6146 if (strlen(devName) != 0) {
6147 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
6148 ARRAY_SIZE(sDeviceNameToEnumTable),
6149 devName);
6150 if (type != AUDIO_DEVICE_NONE) {
6151 add(new DeviceDescriptor(String8(""), type));
6152 } else {
6153 sp<DeviceDescriptor> deviceDesc =
6154 declaredDevices.getDeviceFromName(String8(devName));
6155 if (deviceDesc != 0) {
6156 add(deviceDesc);
6157 }
6158 }
6159 }
6160 devName = strtok(NULL, "|");
6161 }
6162}
6163
Eric Laurent1c333e22014-05-20 10:48:17 -07006164sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
6165 audio_devices_t type, String8 address) const
6166{
6167 sp<DeviceDescriptor> device;
6168 for (size_t i = 0; i < size(); i++) {
6169 if (itemAt(i)->mDeviceType == type) {
6170 device = itemAt(i);
6171 if (itemAt(i)->mAddress = address) {
6172 break;
6173 }
6174 }
6175 }
6176 ALOGV("DeviceVector::getDevice() for type %d address %s found %p",
6177 type, address.string(), device.get());
6178 return device;
6179}
6180
Eric Laurent6a94d692014-05-20 11:18:06 -07006181sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
6182 audio_port_handle_t id) const
6183{
6184 sp<DeviceDescriptor> device;
6185 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006186 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07006187 if (itemAt(i)->mId == id) {
6188 device = itemAt(i);
6189 break;
6190 }
6191 }
6192 return device;
6193}
6194
Eric Laurent1c333e22014-05-20 10:48:17 -07006195AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
6196 audio_devices_t type) const
6197{
6198 DeviceVector devices;
6199 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
6200 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
6201 devices.add(itemAt(i));
6202 type &= ~itemAt(i)->mDeviceType;
6203 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
6204 itemAt(i)->mDeviceType, itemAt(i).get());
6205 }
6206 }
6207 return devices;
6208}
6209
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006210AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
6211 audio_devices_t type, String8 address) const
6212{
6213 DeviceVector devices;
6214 //ALOGV(" looking for device=%x, addr=%s", type, address.string());
6215 for (size_t i = 0; i < size(); i++) {
6216 //ALOGV(" at i=%d: device=%x, addr=%s",
6217 // i, itemAt(i)->mDeviceType, itemAt(i)->mAddress.string());
6218 if (itemAt(i)->mDeviceType == type) {
6219 if (itemAt(i)->mAddress == address) {
6220 //ALOGV(" found matching address %s", address.string());
6221 devices.add(itemAt(i));
6222 }
6223 }
6224 }
6225 return devices;
6226}
6227
Eric Laurent1afeecb2014-05-14 08:52:28 -07006228sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
6229 const String8& name) const
6230{
6231 sp<DeviceDescriptor> device;
6232 for (size_t i = 0; i < size(); i++) {
6233 if (itemAt(i)->mName == name) {
6234 device = itemAt(i);
6235 break;
6236 }
6237 }
6238 return device;
6239}
6240
Eric Laurent6a94d692014-05-20 11:18:06 -07006241void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
6242 struct audio_port_config *dstConfig,
6243 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006244{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006245 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
6246 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006247 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006248 }
6249
6250 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6251
Eric Laurent6a94d692014-05-20 11:18:06 -07006252 dstConfig->id = mId;
6253 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07006254 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006255 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07006256 dstConfig->ext.device.type = mDeviceType;
6257 dstConfig->ext.device.hw_module = mModule->mHandle;
6258 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07006259}
6260
6261void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
6262{
Eric Laurent83b88082014-06-20 18:31:16 -07006263 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07006264 AudioPort::toAudioPort(port);
6265 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006266 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07006267 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07006268 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006269 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
6270}
6271
Eric Laurent1afeecb2014-05-14 08:52:28 -07006272status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07006273{
6274 const size_t SIZE = 256;
6275 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07006276 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006277
Eric Laurent1afeecb2014-05-14 08:52:28 -07006278 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
6279 result.append(buffer);
6280 if (mId != 0) {
6281 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
6282 result.append(buffer);
6283 }
6284 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
6285 enumToString(sDeviceNameToEnumTable,
6286 ARRAY_SIZE(sDeviceNameToEnumTable),
6287 mDeviceType));
6288 result.append(buffer);
6289 if (mAddress.size() != 0) {
6290 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
6291 result.append(buffer);
6292 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006293 write(fd, result.string(), result.size());
6294 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006295
6296 return NO_ERROR;
6297}
6298
6299
6300// --- audio_policy.conf file parsing
6301
Eric Laurente0720872014-03-11 09:30:41 -07006302audio_output_flags_t AudioPolicyManager::parseFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006303{
6304 uint32_t flag = 0;
6305
6306 // it is OK to cast name to non const here as we are not going to use it after
6307 // strtok() modifies it
6308 char *flagName = strtok(name, "|");
6309 while (flagName != NULL) {
6310 if (strlen(flagName) != 0) {
6311 flag |= stringToEnum(sFlagNameToEnumTable,
6312 ARRAY_SIZE(sFlagNameToEnumTable),
6313 flagName);
6314 }
6315 flagName = strtok(NULL, "|");
6316 }
6317 //force direct flag if offload flag is set: offloading implies a direct output stream
6318 // and all common behaviors are driven by checking only the direct flag
6319 // this should normally be set appropriately in the policy configuration file
6320 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
6321 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
6322 }
6323
6324 return (audio_output_flags_t)flag;
6325}
6326
Eric Laurente0720872014-03-11 09:30:41 -07006327audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07006328{
6329 uint32_t device = 0;
6330
6331 char *devName = strtok(name, "|");
6332 while (devName != NULL) {
6333 if (strlen(devName) != 0) {
6334 device |= stringToEnum(sDeviceNameToEnumTable,
6335 ARRAY_SIZE(sDeviceNameToEnumTable),
6336 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006337 }
Eric Laurente552edb2014-03-10 17:42:56 -07006338 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07006339 }
Eric Laurente552edb2014-03-10 17:42:56 -07006340 return device;
6341}
6342
Eric Laurente0720872014-03-11 09:30:41 -07006343void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006344{
Eric Laurente552edb2014-03-10 17:42:56 -07006345 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006346 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006347 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07006348
Eric Laurent1afeecb2014-05-14 08:52:28 -07006349 node = config_find(root, DEVICES_TAG);
6350 if (node != NULL) {
6351 node = node->first_child;
6352 while (node) {
6353 ALOGV("loadHwModule() loading device %s", node->name);
6354 status_t tmpStatus = module->loadDevice(node);
6355 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6356 status = tmpStatus;
6357 }
6358 node = node->next;
6359 }
6360 }
6361 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07006362 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006363 node = node->first_child;
6364 while (node) {
6365 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006366 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006367 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6368 status = tmpStatus;
6369 }
6370 node = node->next;
6371 }
6372 }
6373 node = config_find(root, INPUTS_TAG);
6374 if (node != NULL) {
6375 node = node->first_child;
6376 while (node) {
6377 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006378 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07006379 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
6380 status = tmpStatus;
6381 }
6382 node = node->next;
6383 }
6384 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006385 loadGlobalConfig(root, module);
6386
Eric Laurente552edb2014-03-10 17:42:56 -07006387 if (status == NO_ERROR) {
6388 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07006389 }
6390}
6391
Eric Laurente0720872014-03-11 09:30:41 -07006392void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07006393{
6394 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
6395 if (node == NULL) {
6396 return;
6397 }
6398
6399 node = node->first_child;
6400 while (node) {
6401 ALOGV("loadHwModules() loading module %s", node->name);
6402 loadHwModule(node);
6403 node = node->next;
6404 }
6405}
6406
Eric Laurent1f2f2232014-06-02 12:01:23 -07006407void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07006408{
6409 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07006410
Eric Laurente552edb2014-03-10 17:42:56 -07006411 if (node == NULL) {
6412 return;
6413 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006414 DeviceVector declaredDevices;
6415 if (module != NULL) {
6416 declaredDevices = module->mDeclaredDevices;
6417 }
6418
Eric Laurente552edb2014-03-10 17:42:56 -07006419 node = node->first_child;
6420 while (node) {
6421 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006422 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
6423 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006424 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
6425 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006426 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006427 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07006428 ARRAY_SIZE(sDeviceNameToEnumTable),
6429 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006430 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006431 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006432 } else {
6433 ALOGW("loadGlobalConfig() default device not specified");
6434 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006435 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006436 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006437 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
6438 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006439 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006440 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
6441 mSpeakerDrcEnabled = stringToBool((char *)node->value);
6442 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07006443 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
6444 uint32_t major, minor;
6445 sscanf((char *)node->value, "%u.%u", &major, &minor);
6446 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
6447 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
6448 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07006449 }
6450 node = node->next;
6451 }
6452}
6453
Eric Laurente0720872014-03-11 09:30:41 -07006454status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07006455{
6456 cnode *root;
6457 char *data;
6458
6459 data = (char *)load_file(path, NULL);
6460 if (data == NULL) {
6461 return -ENODEV;
6462 }
6463 root = config_node("", "");
6464 config_load(root, data);
6465
Eric Laurente552edb2014-03-10 17:42:56 -07006466 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006467 // legacy audio_policy.conf files have one global_configuration section
6468 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07006469 config_free(root);
6470 free(root);
6471 free(data);
6472
6473 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
6474
6475 return NO_ERROR;
6476}
6477
Eric Laurente0720872014-03-11 09:30:41 -07006478void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07006479{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006480 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07006481 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006482 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
6483 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006484 mAvailableOutputDevices.add(mDefaultOutputDevice);
6485 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006486
6487 module = new HwModule("primary");
6488
Eric Laurent1afeecb2014-05-14 08:52:28 -07006489 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006490 profile->mSamplingRates.add(44100);
6491 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6492 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006493 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006494 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
6495 module->mOutputProfiles.add(profile);
6496
Eric Laurent1afeecb2014-05-14 08:52:28 -07006497 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07006498 profile->mSamplingRates.add(8000);
6499 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
6500 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07006501 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07006502 module->mInputProfiles.add(profile);
6503
6504 mHwModules.add(module);
6505}
6506
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07006507audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
6508{
6509 // flags to stream type mapping
6510 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
6511 return AUDIO_STREAM_ENFORCED_AUDIBLE;
6512 }
6513 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
6514 return AUDIO_STREAM_BLUETOOTH_SCO;
6515 }
6516
6517 // usage to stream type mapping
6518 switch (attr->usage) {
6519 case AUDIO_USAGE_MEDIA:
6520 case AUDIO_USAGE_GAME:
6521 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
6522 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
6523 return AUDIO_STREAM_MUSIC;
6524 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
6525 return AUDIO_STREAM_SYSTEM;
6526 case AUDIO_USAGE_VOICE_COMMUNICATION:
6527 return AUDIO_STREAM_VOICE_CALL;
6528
6529 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
6530 return AUDIO_STREAM_DTMF;
6531
6532 case AUDIO_USAGE_ALARM:
6533 return AUDIO_STREAM_ALARM;
6534 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
6535 return AUDIO_STREAM_RING;
6536
6537 case AUDIO_USAGE_NOTIFICATION:
6538 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
6539 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
6540 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
6541 case AUDIO_USAGE_NOTIFICATION_EVENT:
6542 return AUDIO_STREAM_NOTIFICATION;
6543
6544 case AUDIO_USAGE_UNKNOWN:
6545 default:
6546 return AUDIO_STREAM_MUSIC;
6547 }
6548}
Eric Laurente552edb2014-03-10 17:42:56 -07006549}; // namespace android