blob: 7f27659bc6f10ec549bd1456dbb7b5006af27bc8 [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()
Hochi Huang327cb702014-09-21 09:47:31 +080029#define APM_AUDIO_IN_DEVICE_VIRTUAL_ALL (AUDIO_DEVICE_IN_REMOTE_SUBMIX|AUDIO_DEVICE_IN_FM_TUNER)
Eric Laurente552edb2014-03-10 17:42:56 -070030// 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 Laurente83b55d2014-11-14 10:06:21 -080046#include <media/AudioPolicyHelper.h>
Eric Laurentdf3dc7e2014-07-27 18:39:40 -070047#include <soundtrigger/SoundTrigger.h>
Eric Laurentd4692962014-05-05 18:13:44 -070048#include "AudioPolicyManager.h"
Eric Laurent1afeecb2014-05-14 08:52:28 -070049#include "audio_policy_conf.h"
Eric Laurente552edb2014-03-10 17:42:56 -070050
Eric Laurent3b73df72014-03-11 09:06:29 -070051namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070052
53// ----------------------------------------------------------------------------
Eric Laurent3a4311c2014-03-17 12:00:47 -070054// Definitions for audio_policy.conf file parsing
55// ----------------------------------------------------------------------------
56
57struct StringToEnum {
58 const char *name;
59 uint32_t value;
60};
61
62#define STRING_TO_ENUM(string) { #string, string }
63#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
64
65const StringToEnum sDeviceNameToEnumTable[] = {
66 STRING_TO_ENUM(AUDIO_DEVICE_OUT_EARPIECE),
67 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER),
Jon Eklund11c9fb12014-06-23 14:47:03 -050068 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPEAKER_SAFE),
Eric Laurent3a4311c2014-03-17 12:00:47 -070069 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADSET),
70 STRING_TO_ENUM(AUDIO_DEVICE_OUT_WIRED_HEADPHONE),
71 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO),
72 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET),
73 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT),
74 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_SCO),
75 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP),
76 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES),
77 STRING_TO_ENUM(AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER),
78 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_A2DP),
79 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070080 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI),
Eric Laurent3a4311c2014-03-17 12:00:47 -070081 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET),
82 STRING_TO_ENUM(AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET),
83 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_ACCESSORY),
84 STRING_TO_ENUM(AUDIO_DEVICE_OUT_USB_DEVICE),
85 STRING_TO_ENUM(AUDIO_DEVICE_OUT_ALL_USB),
86 STRING_TO_ENUM(AUDIO_DEVICE_OUT_REMOTE_SUBMIX),
Eric Laurent1b776232014-05-19 17:26:41 -070087 STRING_TO_ENUM(AUDIO_DEVICE_OUT_TELEPHONY_TX),
88 STRING_TO_ENUM(AUDIO_DEVICE_OUT_LINE),
89 STRING_TO_ENUM(AUDIO_DEVICE_OUT_HDMI_ARC),
90 STRING_TO_ENUM(AUDIO_DEVICE_OUT_SPDIF),
91 STRING_TO_ENUM(AUDIO_DEVICE_OUT_FM),
Eric Laurente1d37b72014-07-29 10:26:26 -070092 STRING_TO_ENUM(AUDIO_DEVICE_OUT_AUX_LINE),
Eric Laurenta57ab8d2014-07-30 10:01:42 -050093 STRING_TO_ENUM(AUDIO_DEVICE_IN_AMBIENT),
Eric Laurent3a4311c2014-03-17 12:00:47 -070094 STRING_TO_ENUM(AUDIO_DEVICE_IN_BUILTIN_MIC),
95 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET),
96 STRING_TO_ENUM(AUDIO_DEVICE_IN_ALL_SCO),
97 STRING_TO_ENUM(AUDIO_DEVICE_IN_WIRED_HEADSET),
98 STRING_TO_ENUM(AUDIO_DEVICE_IN_AUX_DIGITAL),
Eric Laurent1b776232014-05-19 17:26:41 -070099 STRING_TO_ENUM(AUDIO_DEVICE_IN_HDMI),
Eric Laurent1b776232014-05-19 17:26:41 -0700100 STRING_TO_ENUM(AUDIO_DEVICE_IN_TELEPHONY_RX),
Eric Laurentc2730ba2014-07-20 15:47:07 -0700101 STRING_TO_ENUM(AUDIO_DEVICE_IN_VOICE_CALL),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700102 STRING_TO_ENUM(AUDIO_DEVICE_IN_BACK_MIC),
103 STRING_TO_ENUM(AUDIO_DEVICE_IN_REMOTE_SUBMIX),
104 STRING_TO_ENUM(AUDIO_DEVICE_IN_ANLG_DOCK_HEADSET),
105 STRING_TO_ENUM(AUDIO_DEVICE_IN_DGTL_DOCK_HEADSET),
106 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_ACCESSORY),
Eric Laurentd4692962014-05-05 18:13:44 -0700107 STRING_TO_ENUM(AUDIO_DEVICE_IN_USB_DEVICE),
Eric Laurent1b776232014-05-19 17:26:41 -0700108 STRING_TO_ENUM(AUDIO_DEVICE_IN_FM_TUNER),
109 STRING_TO_ENUM(AUDIO_DEVICE_IN_TV_TUNER),
110 STRING_TO_ENUM(AUDIO_DEVICE_IN_LINE),
111 STRING_TO_ENUM(AUDIO_DEVICE_IN_SPDIF),
Mike Lockwood41b0e242014-05-13 15:23:35 -0700112 STRING_TO_ENUM(AUDIO_DEVICE_IN_BLUETOOTH_A2DP),
Terry Heo7999a222014-06-27 15:23:36 +0900113 STRING_TO_ENUM(AUDIO_DEVICE_IN_LOOPBACK),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700114};
115
Eric Laurent5dbe4712014-09-19 19:04:57 -0700116const StringToEnum sOutputFlagNameToEnumTable[] = {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700117 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DIRECT),
118 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_PRIMARY),
119 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_FAST),
120 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_DEEP_BUFFER),
121 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD),
122 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_NON_BLOCKING),
Eric Laurent93c3d412014-08-01 14:48:35 -0700123 STRING_TO_ENUM(AUDIO_OUTPUT_FLAG_HW_AV_SYNC),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700124};
125
Eric Laurent5dbe4712014-09-19 19:04:57 -0700126const StringToEnum sInputFlagNameToEnumTable[] = {
127 STRING_TO_ENUM(AUDIO_INPUT_FLAG_FAST),
128 STRING_TO_ENUM(AUDIO_INPUT_FLAG_HW_HOTWORD),
129};
130
Eric Laurent3a4311c2014-03-17 12:00:47 -0700131const StringToEnum sFormatNameToEnumTable[] = {
132 STRING_TO_ENUM(AUDIO_FORMAT_PCM_16_BIT),
133 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_BIT),
134 STRING_TO_ENUM(AUDIO_FORMAT_PCM_32_BIT),
135 STRING_TO_ENUM(AUDIO_FORMAT_PCM_8_24_BIT),
136 STRING_TO_ENUM(AUDIO_FORMAT_PCM_FLOAT),
137 STRING_TO_ENUM(AUDIO_FORMAT_PCM_24_BIT_PACKED),
138 STRING_TO_ENUM(AUDIO_FORMAT_MP3),
139 STRING_TO_ENUM(AUDIO_FORMAT_AAC),
aarti jadhav-gaikwad2829edc2014-06-18 15:25:26 +0530140 STRING_TO_ENUM(AUDIO_FORMAT_AAC_MAIN),
141 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LC),
142 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SSR),
143 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LTP),
144 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V1),
145 STRING_TO_ENUM(AUDIO_FORMAT_AAC_SCALABLE),
146 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ERLC),
147 STRING_TO_ENUM(AUDIO_FORMAT_AAC_LD),
148 STRING_TO_ENUM(AUDIO_FORMAT_AAC_HE_V2),
149 STRING_TO_ENUM(AUDIO_FORMAT_AAC_ELD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700150 STRING_TO_ENUM(AUDIO_FORMAT_VORBIS),
Eric Laurentab5cdba2014-06-09 17:22:27 -0700151 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V1),
152 STRING_TO_ENUM(AUDIO_FORMAT_HE_AAC_V2),
153 STRING_TO_ENUM(AUDIO_FORMAT_OPUS),
154 STRING_TO_ENUM(AUDIO_FORMAT_AC3),
155 STRING_TO_ENUM(AUDIO_FORMAT_E_AC3),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700156};
157
158const StringToEnum sOutChannelsNameToEnumTable[] = {
159 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_MONO),
160 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_STEREO),
Andy Hung3a0fe122014-07-29 17:56:46 -0700161 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_QUAD),
Eric Laurent3a4311c2014-03-17 12:00:47 -0700162 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_5POINT1),
163 STRING_TO_ENUM(AUDIO_CHANNEL_OUT_7POINT1),
164};
165
166const StringToEnum sInChannelsNameToEnumTable[] = {
167 STRING_TO_ENUM(AUDIO_CHANNEL_IN_MONO),
168 STRING_TO_ENUM(AUDIO_CHANNEL_IN_STEREO),
169 STRING_TO_ENUM(AUDIO_CHANNEL_IN_FRONT_BACK),
170};
171
Eric Laurent1afeecb2014-05-14 08:52:28 -0700172const StringToEnum sGainModeNameToEnumTable[] = {
173 STRING_TO_ENUM(AUDIO_GAIN_MODE_JOINT),
174 STRING_TO_ENUM(AUDIO_GAIN_MODE_CHANNELS),
175 STRING_TO_ENUM(AUDIO_GAIN_MODE_RAMP),
176};
177
Eric Laurent3a4311c2014-03-17 12:00:47 -0700178
179uint32_t AudioPolicyManager::stringToEnum(const struct StringToEnum *table,
180 size_t size,
181 const char *name)
182{
183 for (size_t i = 0; i < size; i++) {
184 if (strcmp(table[i].name, name) == 0) {
185 ALOGV("stringToEnum() found %s", table[i].name);
186 return table[i].value;
187 }
188 }
189 return 0;
190}
191
192const char *AudioPolicyManager::enumToString(const struct StringToEnum *table,
193 size_t size,
194 uint32_t value)
195{
196 for (size_t i = 0; i < size; i++) {
197 if (table[i].value == value) {
198 return table[i].name;
199 }
200 }
201 return "";
202}
203
204bool AudioPolicyManager::stringToBool(const char *value)
205{
206 return ((strcasecmp("true", value) == 0) || (strcmp("1", value) == 0));
207}
208
209
210// ----------------------------------------------------------------------------
Eric Laurente552edb2014-03-10 17:42:56 -0700211// AudioPolicyInterface implementation
212// ----------------------------------------------------------------------------
213
Eric Laurente0720872014-03-11 09:30:41 -0700214status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
Eric Laurent3b73df72014-03-11 09:06:29 -0700215 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -0700216 const char *device_address)
217{
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800218 return setDeviceConnectionStateInt(device, state, device_address);
219}
220
221status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t device,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800222 audio_policy_dev_state_t state,
223 const char *device_address)
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800224{
Eric Laurent22226012014-08-01 17:00:54 -0700225 ALOGV("setDeviceConnectionState() device: %x, state %d, address %s",
Eric Laurenta1d525f2015-01-29 13:36:45 -0800226 device, state, device_address != NULL ? device_address : "");
Eric Laurente552edb2014-03-10 17:42:56 -0700227
228 // connect/disconnect only 1 device at a time
229 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
230
Eric Laurenta1d525f2015-01-29 13:36:45 -0800231 sp<DeviceDescriptor> devDesc = getDeviceDescriptor(device, device_address);
232
Eric Laurente552edb2014-03-10 17:42:56 -0700233 // handle output devices
234 if (audio_is_output_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700235 SortedVector <audio_io_handle_t> outputs;
236
Eric Laurent3a4311c2014-03-17 12:00:47 -0700237 ssize_t index = mAvailableOutputDevices.indexOf(devDesc);
238
Eric Laurente552edb2014-03-10 17:42:56 -0700239 // save a copy of the opened output descriptors before any output is opened or closed
240 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
241 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700242 switch (state)
243 {
244 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800245 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700246 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700247 ALOGW("setDeviceConnectionState() device already connected: %x", device);
248 return INVALID_OPERATION;
249 }
250 ALOGV("setDeviceConnectionState() connecting device %x", device);
251
Eric Laurente552edb2014-03-10 17:42:56 -0700252 // register new device as available
Eric Laurent3a4311c2014-03-17 12:00:47 -0700253 index = mAvailableOutputDevices.add(devDesc);
254 if (index >= 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700255 sp<HwModule> module = getModuleForDevice(device);
Eric Laurentcf817a22014-08-04 20:36:31 -0700256 if (module == 0) {
257 ALOGD("setDeviceConnectionState() could not find HW module for device %08x",
258 device);
259 mAvailableOutputDevices.remove(devDesc);
260 return INVALID_OPERATION;
261 }
262 mAvailableOutputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700263 mAvailableOutputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700264 } else {
265 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700266 }
267
Eric Laurenta1d525f2015-01-29 13:36:45 -0800268 if (checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress) != NO_ERROR) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700269 mAvailableOutputDevices.remove(devDesc);
270 return INVALID_OPERATION;
271 }
272 // outputs should never be empty here
273 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
274 "checkOutputsForDevice() returned no outputs but status OK");
275 ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %zu outputs",
276 outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800277
278
279 // Set connect to HALs
280 AudioParameter param = AudioParameter(devDesc->mAddress);
281 param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
282 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
283
284 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700285 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700286 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700287 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700288 ALOGW("setDeviceConnectionState() device not connected: %x", device);
289 return INVALID_OPERATION;
290 }
291
Paul McLean5c477aa2014-08-20 16:47:57 -0700292 ALOGV("setDeviceConnectionState() disconnecting output device %x", device);
293
294 // Set Disconnect to HALs
Eric Laurenta1d525f2015-01-29 13:36:45 -0800295 AudioParameter param = AudioParameter(devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700296 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
297 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
298
Eric Laurente552edb2014-03-10 17:42:56 -0700299 // remove device from available output devices
Eric Laurent3a4311c2014-03-17 12:00:47 -0700300 mAvailableOutputDevices.remove(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700301
Eric Laurenta1d525f2015-01-29 13:36:45 -0800302 checkOutputsForDevice(devDesc, state, outputs, devDesc->mAddress);
Eric Laurente552edb2014-03-10 17:42:56 -0700303 } break;
304
305 default:
306 ALOGE("setDeviceConnectionState() invalid state: %x", state);
307 return BAD_VALUE;
308 }
309
Eric Laurent3a4311c2014-03-17 12:00:47 -0700310 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
311 // output is suspended before any tracks are moved to it
Eric Laurente552edb2014-03-10 17:42:56 -0700312 checkA2dpSuspend();
313 checkOutputForAllStrategies();
314 // outputs must be closed after checkOutputForAllStrategies() is executed
315 if (!outputs.isEmpty()) {
316 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700317 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -0700318 // close unused outputs after device disconnection or direct outputs that have been
319 // opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurent3b73df72014-03-11 09:06:29 -0700320 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) ||
Eric Laurente552edb2014-03-10 17:42:56 -0700321 (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
322 (desc->mDirectOpenCount == 0))) {
323 closeOutput(outputs[i]);
324 }
325 }
Eric Laurent3a4311c2014-03-17 12:00:47 -0700326 // check again after closing A2DP output to reset mA2dpSuspended if needed
327 checkA2dpSuspend();
Eric Laurente552edb2014-03-10 17:42:56 -0700328 }
329
330 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700331 if (mPhoneState == AUDIO_MODE_IN_CALL) {
332 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
333 updateCallRouting(newDevice);
334 }
Eric Laurente552edb2014-03-10 17:42:56 -0700335 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc2730ba2014-07-20 15:47:07 -0700336 audio_io_handle_t output = mOutputs.keyAt(i);
337 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
338 audio_devices_t newDevice = getNewOutputDevice(mOutputs.keyAt(i),
339 true /*fromCache*/);
340 // do not force device change on duplicated output because if device is 0, it will
341 // also force a device 0 for the two outputs it is duplicated to which may override
342 // a valid device selection on those outputs.
343 bool force = !mOutputs.valueAt(i)->isDuplicated()
344 && (!deviceDistinguishesOnAddress(device)
345 // always force when disconnecting (a non-duplicated device)
346 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
347 setOutputDevice(output, newDevice, force, 0);
348 }
Eric Laurente552edb2014-03-10 17:42:56 -0700349 }
350
Eric Laurent72aa32f2014-05-30 18:51:48 -0700351 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700352 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700353 } // end if is output device
354
Eric Laurente552edb2014-03-10 17:42:56 -0700355 // handle input devices
356 if (audio_is_input_device(device)) {
Eric Laurentd4692962014-05-05 18:13:44 -0700357 SortedVector <audio_io_handle_t> inputs;
358
Eric Laurent3a4311c2014-03-17 12:00:47 -0700359 ssize_t index = mAvailableInputDevices.indexOf(devDesc);
Eric Laurente552edb2014-03-10 17:42:56 -0700360 switch (state)
361 {
362 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700363 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700364 if (index >= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700365 ALOGW("setDeviceConnectionState() device already connected: %d", device);
366 return INVALID_OPERATION;
367 }
Eric Laurent1f2f2232014-06-02 12:01:23 -0700368 sp<HwModule> module = getModuleForDevice(device);
Eric Laurent6a94d692014-05-20 11:18:06 -0700369 if (module == NULL) {
370 ALOGW("setDeviceConnectionState(): could not find HW module for device %08x",
371 device);
372 return INVALID_OPERATION;
373 }
Eric Laurenta1d525f2015-01-29 13:36:45 -0800374 if (checkInputsForDevice(device, state, inputs, devDesc->mAddress) != NO_ERROR) {
Eric Laurentd4692962014-05-05 18:13:44 -0700375 return INVALID_OPERATION;
376 }
377
Eric Laurent3a4311c2014-03-17 12:00:47 -0700378 index = mAvailableInputDevices.add(devDesc);
379 if (index >= 0) {
380 mAvailableInputDevices[index]->mId = nextUniqueId();
Eric Laurent6a94d692014-05-20 11:18:06 -0700381 mAvailableInputDevices[index]->mModule = module;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700382 } else {
383 return NO_MEMORY;
384 }
Eric Laurent3ae5f312015-02-03 17:12:08 -0800385
386 // Set connect to HALs
387 AudioParameter param = AudioParameter(devDesc->mAddress);
388 param.addInt(String8(AUDIO_PARAMETER_DEVICE_CONNECT), device);
389 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
390
Eric Laurentd4692962014-05-05 18:13:44 -0700391 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700392
393 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700394 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700395 if (index < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -0700396 ALOGW("setDeviceConnectionState() device not connected: %d", device);
397 return INVALID_OPERATION;
398 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700399
400 ALOGV("setDeviceConnectionState() disconnecting input device %x", device);
401
402 // Set Disconnect to HALs
Eric Laurenta1d525f2015-01-29 13:36:45 -0800403 AudioParameter param = AudioParameter(devDesc->mAddress);
Paul McLean5c477aa2014-08-20 16:47:57 -0700404 param.addInt(String8(AUDIO_PARAMETER_DEVICE_DISCONNECT), device);
405 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
406
Eric Laurenta1d525f2015-01-29 13:36:45 -0800407 checkInputsForDevice(device, state, inputs, devDesc->mAddress);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700408 mAvailableInputDevices.remove(devDesc);
Paul McLean5c477aa2014-08-20 16:47:57 -0700409
Eric Laurentd4692962014-05-05 18:13:44 -0700410 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700411
412 default:
413 ALOGE("setDeviceConnectionState() invalid state: %x", state);
414 return BAD_VALUE;
415 }
416
Eric Laurentd4692962014-05-05 18:13:44 -0700417 closeAllInputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700418
Eric Laurentc2730ba2014-07-20 15:47:07 -0700419 if (mPhoneState == AUDIO_MODE_IN_CALL) {
420 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
421 updateCallRouting(newDevice);
422 }
423
Eric Laurentb52c1522014-05-20 11:27:36 -0700424 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700425 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700426 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700427
428 ALOGW("setDeviceConnectionState() invalid device: %x", device);
429 return BAD_VALUE;
430}
431
Eric Laurente0720872014-03-11 09:30:41 -0700432audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
Eric Laurente552edb2014-03-10 17:42:56 -0700433 const char *device_address)
434{
Eric Laurenta1d525f2015-01-29 13:36:45 -0800435 sp<DeviceDescriptor> devDesc = getDeviceDescriptor(device, device_address);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700436 DeviceVector *deviceVector;
437
Eric Laurente552edb2014-03-10 17:42:56 -0700438 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700439 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700440 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700441 deviceVector = &mAvailableInputDevices;
442 } else {
443 ALOGW("getDeviceConnectionState() invalid device type %08x", device);
444 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700445 }
446
Eric Laurenta1d525f2015-01-29 13:36:45 -0800447 ssize_t index = deviceVector->indexOf(devDesc);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700448 if (index >= 0) {
449 return AUDIO_POLICY_DEVICE_STATE_AVAILABLE;
450 } else {
451 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
452 }
Eric Laurente552edb2014-03-10 17:42:56 -0700453}
454
Eric Laurenta1d525f2015-01-29 13:36:45 -0800455sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::getDeviceDescriptor(
456 const audio_devices_t device,
457 const char *device_address)
458{
459 String8 address = (device_address == NULL) ? String8("") : String8(device_address);
460 // handle legacy remote submix case where the address was not always specified
461 if (deviceDistinguishesOnAddress(device) && (address.length() == 0)) {
462 address = String8("0");
463 }
464
465 for (size_t i = 0; i < mHwModules.size(); i++) {
466 if (mHwModules[i]->mHandle == 0) {
467 continue;
468 }
469 DeviceVector deviceList =
470 mHwModules[i]->mDeclaredDevices.getDevicesFromTypeAddr(device, address);
471 if (!deviceList.isEmpty()) {
472 return deviceList.itemAt(0);
473 }
474 deviceList = mHwModules[i]->mDeclaredDevices.getDevicesFromType(device);
475 if (!deviceList.isEmpty()) {
476 return deviceList.itemAt(0);
477 }
478 }
479
480 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
481 devDesc->mAddress = address;
482 return devDesc;
483}
484
Eric Laurentc2730ba2014-07-20 15:47:07 -0700485void AudioPolicyManager::updateCallRouting(audio_devices_t rxDevice, int delayMs)
486{
487 bool createTxPatch = false;
488 struct audio_patch patch;
489 patch.num_sources = 1;
490 patch.num_sinks = 1;
491 status_t status;
492 audio_patch_handle_t afPatchHandle;
493 DeviceVector deviceList;
494
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800495 audio_devices_t txDevice = getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700496 ALOGV("updateCallRouting device rxDevice %08x txDevice %08x", rxDevice, txDevice);
497
498 // release existing RX patch if any
499 if (mCallRxPatch != 0) {
500 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
501 mCallRxPatch.clear();
502 }
503 // release TX patch if any
504 if (mCallTxPatch != 0) {
505 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
506 mCallTxPatch.clear();
507 }
508
509 // If the RX device is on the primary HW module, then use legacy routing method for voice calls
510 // via setOutputDevice() on primary output.
511 // Otherwise, create two audio patches for TX and RX path.
512 if (availablePrimaryOutputDevices() & rxDevice) {
513 setOutputDevice(mPrimaryOutput, rxDevice, true, delayMs);
514 // If the TX device is also on the primary HW module, setOutputDevice() will take care
515 // of it due to legacy implementation. If not, create a patch.
516 if ((availablePrimaryInputDevices() & txDevice & ~AUDIO_DEVICE_BIT_IN)
517 == AUDIO_DEVICE_NONE) {
518 createTxPatch = true;
519 }
520 } else {
521 // create RX path audio patch
522 deviceList = mAvailableOutputDevices.getDevicesFromType(rxDevice);
523 ALOG_ASSERT(!deviceList.isEmpty(),
524 "updateCallRouting() selected device not in output device list");
525 sp<DeviceDescriptor> rxSinkDeviceDesc = deviceList.itemAt(0);
526 deviceList = mAvailableInputDevices.getDevicesFromType(AUDIO_DEVICE_IN_TELEPHONY_RX);
527 ALOG_ASSERT(!deviceList.isEmpty(),
528 "updateCallRouting() no telephony RX device");
529 sp<DeviceDescriptor> rxSourceDeviceDesc = deviceList.itemAt(0);
530
531 rxSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
532 rxSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
533
534 // request to reuse existing output stream if one is already opened to reach the RX device
535 SortedVector<audio_io_handle_t> outputs =
536 getOutputsForDevice(rxDevice, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700537 audio_io_handle_t output = selectOutput(outputs,
538 AUDIO_OUTPUT_FLAG_NONE,
539 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700540 if (output != AUDIO_IO_HANDLE_NONE) {
541 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
542 ALOG_ASSERT(!outputDesc->isDuplicated(),
543 "updateCallRouting() RX device output is duplicated");
544 outputDesc->toAudioPortConfig(&patch.sources[1]);
545 patch.num_sources = 2;
546 }
547
548 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
549 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
550 ALOGW_IF(status != NO_ERROR, "updateCallRouting() error %d creating RX audio patch",
551 status);
552 if (status == NO_ERROR) {
553 mCallRxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
554 &patch, mUidCached);
555 mCallRxPatch->mAfPatchHandle = afPatchHandle;
556 mCallRxPatch->mUid = mUidCached;
557 }
558 createTxPatch = true;
559 }
560 if (createTxPatch) {
561
562 struct audio_patch patch;
563 patch.num_sources = 1;
564 patch.num_sinks = 1;
565 deviceList = mAvailableInputDevices.getDevicesFromType(txDevice);
566 ALOG_ASSERT(!deviceList.isEmpty(),
567 "updateCallRouting() selected device not in input device list");
568 sp<DeviceDescriptor> txSourceDeviceDesc = deviceList.itemAt(0);
569 txSourceDeviceDesc->toAudioPortConfig(&patch.sources[0]);
570 deviceList = mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_TELEPHONY_TX);
571 ALOG_ASSERT(!deviceList.isEmpty(),
572 "updateCallRouting() no telephony TX device");
573 sp<DeviceDescriptor> txSinkDeviceDesc = deviceList.itemAt(0);
574 txSinkDeviceDesc->toAudioPortConfig(&patch.sinks[0]);
575
576 SortedVector<audio_io_handle_t> outputs =
577 getOutputsForDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX, mOutputs);
Eric Laurent8838a382014-09-08 16:44:28 -0700578 audio_io_handle_t output = selectOutput(outputs,
579 AUDIO_OUTPUT_FLAG_NONE,
580 AUDIO_FORMAT_INVALID);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700581 // request to reuse existing output stream if one is already opened to reach the TX
582 // path output device
583 if (output != AUDIO_IO_HANDLE_NONE) {
584 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
585 ALOG_ASSERT(!outputDesc->isDuplicated(),
586 "updateCallRouting() RX device output is duplicated");
587 outputDesc->toAudioPortConfig(&patch.sources[1]);
588 patch.num_sources = 2;
589 }
590
591 afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
592 status = mpClientInterface->createAudioPatch(&patch, &afPatchHandle, 0);
593 ALOGW_IF(status != NO_ERROR, "setPhoneState() error %d creating TX audio patch",
594 status);
595 if (status == NO_ERROR) {
596 mCallTxPatch = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
597 &patch, mUidCached);
598 mCallTxPatch->mAfPatchHandle = afPatchHandle;
599 mCallTxPatch->mUid = mUidCached;
600 }
601 }
602}
603
Eric Laurente0720872014-03-11 09:30:41 -0700604void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700605{
606 ALOGV("setPhoneState() state %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700607 if (state < 0 || state >= AUDIO_MODE_CNT) {
Eric Laurente552edb2014-03-10 17:42:56 -0700608 ALOGW("setPhoneState() invalid state %d", state);
609 return;
610 }
611
612 if (state == mPhoneState ) {
613 ALOGW("setPhoneState() setting same state %d", state);
614 return;
615 }
616
617 // if leaving call state, handle special case of active streams
618 // pertaining to sonification strategy see handleIncallSonification()
619 if (isInCall()) {
620 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700621 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800622 if (stream == AUDIO_STREAM_PATCH) {
623 continue;
624 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700625 handleIncallSonification((audio_stream_type_t)stream, false, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700626 }
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800627
628 // force reevaluating accessibility routing when call starts
629 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700630 }
631
632 // store previous phone state for management of sonification strategy below
633 int oldState = mPhoneState;
634 mPhoneState = state;
635 bool force = false;
636
637 // are we entering or starting a call
638 if (!isStateInCall(oldState) && isStateInCall(state)) {
639 ALOGV(" Entering call in setPhoneState()");
640 // force routing command to audio hardware when starting a call
641 // even if no device change is needed
642 force = true;
643 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
644 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
645 sVolumeProfiles[AUDIO_STREAM_VOICE_CALL][j];
646 }
647 } else if (isStateInCall(oldState) && !isStateInCall(state)) {
648 ALOGV(" Exiting call in setPhoneState()");
649 // force routing command to audio hardware when exiting a call
650 // even if no device change is needed
651 force = true;
652 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
653 mStreams[AUDIO_STREAM_DTMF].mVolumeCurve[j] =
654 sVolumeProfiles[AUDIO_STREAM_DTMF][j];
655 }
656 } else if (isStateInCall(state) && (state != oldState)) {
657 ALOGV(" Switching between telephony and VoIP in setPhoneState()");
658 // force routing command to audio hardware when switching between telephony and VoIP
659 // even if no device change is needed
660 force = true;
661 }
662
663 // check for device and output changes triggered by new phone state
Eric Laurente552edb2014-03-10 17:42:56 -0700664 checkA2dpSuspend();
665 checkOutputForAllStrategies();
666 updateDevicesAndOutputs();
667
Eric Laurent1f2f2232014-06-02 12:01:23 -0700668 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -0700669
Eric Laurente552edb2014-03-10 17:42:56 -0700670 int delayMs = 0;
671 if (isStateInCall(state)) {
672 nsecs_t sysTime = systemTime();
673 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -0700674 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700675 // mute media and sonification strategies and delay device switch by the largest
676 // latency of any output where either strategy is active.
677 // This avoid sending the ring tone or music tail into the earpiece or headset.
678 if ((desc->isStrategyActive(STRATEGY_MEDIA,
679 SONIFICATION_HEADSET_MUSIC_DELAY,
680 sysTime) ||
681 desc->isStrategyActive(STRATEGY_SONIFICATION,
682 SONIFICATION_HEADSET_MUSIC_DELAY,
683 sysTime)) &&
684 (delayMs < (int)desc->mLatency*2)) {
685 delayMs = desc->mLatency*2;
686 }
687 setStrategyMute(STRATEGY_MEDIA, true, mOutputs.keyAt(i));
688 setStrategyMute(STRATEGY_MEDIA, false, mOutputs.keyAt(i), MUTE_TIME_MS,
689 getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/));
690 setStrategyMute(STRATEGY_SONIFICATION, true, mOutputs.keyAt(i));
691 setStrategyMute(STRATEGY_SONIFICATION, false, mOutputs.keyAt(i), MUTE_TIME_MS,
692 getDeviceForStrategy(STRATEGY_SONIFICATION, true /*fromCache*/));
693 }
694 }
695
Eric Laurentc2730ba2014-07-20 15:47:07 -0700696 // Note that despite the fact that getNewOutputDevice() is called on the primary output,
697 // the device returned is not necessarily reachable via this output
698 audio_devices_t rxDevice = getNewOutputDevice(mPrimaryOutput, false /*fromCache*/);
699 // force routing command to audio hardware when ending call
700 // even if no device change is needed
701 if (isStateInCall(oldState) && rxDevice == AUDIO_DEVICE_NONE) {
702 rxDevice = hwOutputDesc->device();
703 }
Eric Laurente552edb2014-03-10 17:42:56 -0700704
Eric Laurentc2730ba2014-07-20 15:47:07 -0700705 if (state == AUDIO_MODE_IN_CALL) {
706 updateCallRouting(rxDevice, delayMs);
707 } else if (oldState == AUDIO_MODE_IN_CALL) {
708 if (mCallRxPatch != 0) {
709 mpClientInterface->releaseAudioPatch(mCallRxPatch->mAfPatchHandle, 0);
710 mCallRxPatch.clear();
711 }
712 if (mCallTxPatch != 0) {
713 mpClientInterface->releaseAudioPatch(mCallTxPatch->mAfPatchHandle, 0);
714 mCallTxPatch.clear();
715 }
716 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
717 } else {
718 setOutputDevice(mPrimaryOutput, rxDevice, force, 0);
719 }
Eric Laurente552edb2014-03-10 17:42:56 -0700720 // if entering in call state, handle special case of active streams
721 // pertaining to sonification strategy see handleIncallSonification()
722 if (isStateInCall(state)) {
723 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent3b73df72014-03-11 09:06:29 -0700724 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -0800725 if (stream == AUDIO_STREAM_PATCH) {
726 continue;
727 }
Eric Laurent3b73df72014-03-11 09:06:29 -0700728 handleIncallSonification((audio_stream_type_t)stream, true, true);
Eric Laurente552edb2014-03-10 17:42:56 -0700729 }
730 }
731
732 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
Eric Laurent3b73df72014-03-11 09:06:29 -0700733 if (state == AUDIO_MODE_RINGTONE &&
734 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700735 mLimitRingtoneVolume = true;
736 } else {
737 mLimitRingtoneVolume = false;
738 }
739}
740
Eric Laurente0720872014-03-11 09:30:41 -0700741void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
Eric Laurent3b73df72014-03-11 09:06:29 -0700742 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700743{
744 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mPhoneState);
745
746 bool forceVolumeReeval = false;
747 switch(usage) {
Eric Laurent3b73df72014-03-11 09:06:29 -0700748 case AUDIO_POLICY_FORCE_FOR_COMMUNICATION:
749 if (config != AUDIO_POLICY_FORCE_SPEAKER && config != AUDIO_POLICY_FORCE_BT_SCO &&
750 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700751 ALOGW("setForceUse() invalid config %d for FOR_COMMUNICATION", config);
752 return;
753 }
754 forceVolumeReeval = true;
755 mForceUse[usage] = config;
756 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700757 case AUDIO_POLICY_FORCE_FOR_MEDIA:
758 if (config != AUDIO_POLICY_FORCE_HEADPHONES && config != AUDIO_POLICY_FORCE_BT_A2DP &&
759 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
760 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
761 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK && config != AUDIO_POLICY_FORCE_NONE &&
Hochi Huang327cb702014-09-21 09:47:31 +0800762 config != AUDIO_POLICY_FORCE_NO_BT_A2DP && config != AUDIO_POLICY_FORCE_SPEAKER ) {
Eric Laurente552edb2014-03-10 17:42:56 -0700763 ALOGW("setForceUse() invalid config %d for FOR_MEDIA", config);
764 return;
765 }
766 mForceUse[usage] = config;
767 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700768 case AUDIO_POLICY_FORCE_FOR_RECORD:
769 if (config != AUDIO_POLICY_FORCE_BT_SCO && config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
770 config != AUDIO_POLICY_FORCE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -0700771 ALOGW("setForceUse() invalid config %d for FOR_RECORD", config);
772 return;
773 }
774 mForceUse[usage] = config;
775 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700776 case AUDIO_POLICY_FORCE_FOR_DOCK:
777 if (config != AUDIO_POLICY_FORCE_NONE && config != AUDIO_POLICY_FORCE_BT_CAR_DOCK &&
778 config != AUDIO_POLICY_FORCE_BT_DESK_DOCK &&
779 config != AUDIO_POLICY_FORCE_WIRED_ACCESSORY &&
780 config != AUDIO_POLICY_FORCE_ANALOG_DOCK &&
781 config != AUDIO_POLICY_FORCE_DIGITAL_DOCK) {
Eric Laurente552edb2014-03-10 17:42:56 -0700782 ALOGW("setForceUse() invalid config %d for FOR_DOCK", config);
783 }
784 forceVolumeReeval = true;
785 mForceUse[usage] = config;
786 break;
Eric Laurent3b73df72014-03-11 09:06:29 -0700787 case AUDIO_POLICY_FORCE_FOR_SYSTEM:
788 if (config != AUDIO_POLICY_FORCE_NONE &&
789 config != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -0700790 ALOGW("setForceUse() invalid config %d for FOR_SYSTEM", config);
791 }
792 forceVolumeReeval = true;
793 mForceUse[usage] = config;
794 break;
Jungshik Jang7b24ee32014-07-15 19:38:42 +0900795 case AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO:
796 if (config != AUDIO_POLICY_FORCE_NONE &&
797 config != AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED) {
798 ALOGW("setForceUse() invalid config %d forHDMI_SYSTEM_AUDIO", config);
799 }
800 mForceUse[usage] = config;
801 break;
Eric Laurente552edb2014-03-10 17:42:56 -0700802 default:
803 ALOGW("setForceUse() invalid usage %d", usage);
804 break;
805 }
806
807 // check for device and output changes triggered by new force usage
808 checkA2dpSuspend();
809 checkOutputForAllStrategies();
810 updateDevicesAndOutputs();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700811 if (mPhoneState == AUDIO_MODE_IN_CALL) {
812 audio_devices_t newDevice = getNewOutputDevice(mPrimaryOutput, true /*fromCache*/);
813 updateCallRouting(newDevice);
814 }
Eric Laurente552edb2014-03-10 17:42:56 -0700815 for (size_t i = 0; i < mOutputs.size(); i++) {
816 audio_io_handle_t output = mOutputs.keyAt(i);
Eric Laurent1c333e22014-05-20 10:48:17 -0700817 audio_devices_t newDevice = getNewOutputDevice(output, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700818 if ((mPhoneState != AUDIO_MODE_IN_CALL) || (output != mPrimaryOutput)) {
819 setOutputDevice(output, newDevice, (newDevice != AUDIO_DEVICE_NONE));
820 }
Eric Laurente552edb2014-03-10 17:42:56 -0700821 if (forceVolumeReeval && (newDevice != AUDIO_DEVICE_NONE)) {
822 applyStreamVolumes(output, newDevice, 0, true);
823 }
824 }
825
826 audio_io_handle_t activeInput = getActiveInput();
827 if (activeInput != 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700828 setInputDevice(activeInput, getNewInputDevice(activeInput));
Eric Laurente552edb2014-03-10 17:42:56 -0700829 }
830
831}
832
Eric Laurente0720872014-03-11 09:30:41 -0700833audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
Eric Laurente552edb2014-03-10 17:42:56 -0700834{
835 return mForceUse[usage];
836}
837
Eric Laurente0720872014-03-11 09:30:41 -0700838void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700839{
840 ALOGV("setSystemProperty() property %s, value %s", property, value);
841}
842
843// Find a direct output profile compatible with the parameters passed, even if the input flags do
844// not explicitly request a direct output
Eric Laurent1c333e22014-05-20 10:48:17 -0700845sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getProfileForDirectOutput(
Eric Laurente552edb2014-03-10 17:42:56 -0700846 audio_devices_t device,
847 uint32_t samplingRate,
848 audio_format_t format,
849 audio_channel_mask_t channelMask,
850 audio_output_flags_t flags)
851{
852 for (size_t i = 0; i < mHwModules.size(); i++) {
853 if (mHwModules[i]->mHandle == 0) {
854 continue;
855 }
856 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++) {
Eric Laurent1c333e22014-05-20 10:48:17 -0700857 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurent275e8e92014-11-30 15:14:47 -0800858 bool found = profile->isCompatibleProfile(device, String8(""), samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -0700859 NULL /*updatedSamplingRate*/, format, channelMask,
860 flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD ?
861 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD : AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700862 if (found && (mAvailableOutputDevices.types() & profile->mSupportedDevices.types())) {
863 return profile;
864 }
Eric Laurente552edb2014-03-10 17:42:56 -0700865 }
866 }
867 return 0;
868}
869
Eric Laurente0720872014-03-11 09:30:41 -0700870audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -0700871 uint32_t samplingRate,
872 audio_format_t format,
873 audio_channel_mask_t channelMask,
Eric Laurent3b73df72014-03-11 09:06:29 -0700874 audio_output_flags_t flags,
Eric Laurente552edb2014-03-10 17:42:56 -0700875 const audio_offload_info_t *offloadInfo)
876{
Eric Laurent3b73df72014-03-11 09:06:29 -0700877 routing_strategy strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -0700878 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
879 ALOGV("getOutput() device %d, stream %d, samplingRate %d, format %x, channelMask %x, flags %x",
880 device, stream, samplingRate, format, channelMask, flags);
881
Eric Laurente83b55d2014-11-14 10:06:21 -0800882 return getOutputForDevice(device, AUDIO_SESSION_ALLOCATE,
883 stream, samplingRate,format, channelMask,
884 flags, offloadInfo);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700885}
886
Eric Laurente83b55d2014-11-14 10:06:21 -0800887status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
888 audio_io_handle_t *output,
889 audio_session_t session,
890 audio_stream_type_t *stream,
891 uint32_t samplingRate,
892 audio_format_t format,
893 audio_channel_mask_t channelMask,
894 audio_output_flags_t flags,
895 const audio_offload_info_t *offloadInfo)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700896{
Eric Laurente83b55d2014-11-14 10:06:21 -0800897 audio_attributes_t attributes;
898 if (attr != NULL) {
899 if (!isValidAttributes(attr)) {
900 ALOGE("getOutputForAttr() invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
901 attr->usage, attr->content_type, attr->flags,
902 attr->tags);
903 return BAD_VALUE;
904 }
905 attributes = *attr;
906 } else {
907 if (*stream < AUDIO_STREAM_MIN || *stream >= AUDIO_STREAM_PUBLIC_CNT) {
908 ALOGE("getOutputForAttr(): invalid stream type");
909 return BAD_VALUE;
910 }
911 stream_type_to_audio_attributes(*stream, &attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700912 }
Eric Laurente83b55d2014-11-14 10:06:21 -0800913
Eric Laurent275e8e92014-11-30 15:14:47 -0800914 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
915 sp<AudioOutputDescriptor> desc;
916 if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_PLAYERS) {
917 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
918 if ((RULE_MATCH_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
919 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage == attributes.usage) ||
920 (RULE_EXCLUDE_ATTRIBUTE_USAGE == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
921 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mUsage != attributes.usage)) {
922 desc = mPolicyMixes[i]->mOutput;
923 break;
924 }
925 if (strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
926 strncmp(attributes.tags + strlen("addr="),
927 mPolicyMixes[i]->mMix.mRegistrationId.string(),
928 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
929 desc = mPolicyMixes[i]->mOutput;
930 break;
931 }
932 }
933 } else if (mPolicyMixes[i]->mMix.mMixType == MIX_TYPE_RECORDERS) {
934 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE &&
935 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0 &&
936 strncmp(attributes.tags + strlen("addr="),
937 mPolicyMixes[i]->mMix.mRegistrationId.string(),
938 AUDIO_ATTRIBUTES_TAGS_MAX_SIZE - strlen("addr=") - 1) == 0) {
939 desc = mPolicyMixes[i]->mOutput;
Eric Laurent275e8e92014-11-30 15:14:47 -0800940 }
941 }
942 if (desc != 0) {
943 if (!audio_is_linear_pcm(format)) {
944 return BAD_VALUE;
945 }
Eric Laurentc722f302014-12-10 11:21:49 -0800946 desc->mPolicyMix = &mPolicyMixes[i]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -0800947 *stream = streamTypefromAttributesInt(&attributes);
948 *output = desc->mIoHandle;
949 ALOGV("getOutputForAttr() returns output %d", *output);
950 return NO_ERROR;
951 }
952 }
953 if (attributes.usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
954 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
955 return BAD_VALUE;
956 }
957
Eric Laurent93c3d412014-08-01 14:48:35 -0700958 ALOGV("getOutputForAttr() usage=%d, content=%d, tag=%s flags=%08x",
Eric Laurente83b55d2014-11-14 10:06:21 -0800959 attributes.usage, attributes.content_type, attributes.tags, attributes.flags);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700960
Eric Laurente83b55d2014-11-14 10:06:21 -0800961 routing_strategy strategy = (routing_strategy) getStrategyForAttr(&attributes);
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700962 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
Eric Laurent93c3d412014-08-01 14:48:35 -0700963
Eric Laurente83b55d2014-11-14 10:06:21 -0800964 if ((attributes.flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Eric Laurent93c3d412014-08-01 14:48:35 -0700965 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
966 }
967
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -0700968 ALOGV("getOutputForAttr() device 0x%x, samplingRate %d, format %x, channelMask %x, flags %x",
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700969 device, samplingRate, format, channelMask, flags);
970
Eric Laurente83b55d2014-11-14 10:06:21 -0800971 *stream = streamTypefromAttributesInt(&attributes);
972 *output = getOutputForDevice(device, session, *stream,
973 samplingRate, format, channelMask,
974 flags, offloadInfo);
975 if (*output == AUDIO_IO_HANDLE_NONE) {
976 return INVALID_OPERATION;
977 }
978 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700979}
980
981audio_io_handle_t AudioPolicyManager::getOutputForDevice(
982 audio_devices_t device,
Eric Laurentcaf7f482014-11-25 17:50:47 -0800983 audio_session_t session __unused,
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700984 audio_stream_type_t stream,
985 uint32_t samplingRate,
986 audio_format_t format,
987 audio_channel_mask_t channelMask,
988 audio_output_flags_t flags,
989 const audio_offload_info_t *offloadInfo)
990{
Eric Laurentcf2c0212014-07-25 16:20:43 -0700991 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700992 uint32_t latency = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -0700993 status_t status;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -0700994
Eric Laurente552edb2014-03-10 17:42:56 -0700995#ifdef AUDIO_POLICY_TEST
996 if (mCurOutput != 0) {
997 ALOGV("getOutput() test output mCurOutput %d, samplingRate %d, format %d, channelMask %x, mDirectOutput %d",
998 mCurOutput, mTestSamplingRate, mTestFormat, mTestChannels, mDirectOutput);
999
1000 if (mTestOutputs[mCurOutput] == 0) {
1001 ALOGV("getOutput() opening test output");
Eric Laurent1f2f2232014-06-02 12:01:23 -07001002 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07001003 outputDesc->mDevice = mTestDevice;
Eric Laurente552edb2014-03-10 17:42:56 -07001004 outputDesc->mLatency = mTestLatencyMs;
Eric Laurent3b73df72014-03-11 09:06:29 -07001005 outputDesc->mFlags =
1006 (audio_output_flags_t)(mDirectOutput ? AUDIO_OUTPUT_FLAG_DIRECT : 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001007 outputDesc->mRefCount[stream] = 0;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001008 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1009 config.sample_rate = mTestSamplingRate;
1010 config.channel_mask = mTestChannels;
1011 config.format = mTestFormat;
Phil Burk77cce802014-08-04 16:18:15 -07001012 if (offloadInfo != NULL) {
1013 config.offload_info = *offloadInfo;
1014 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001015 status = mpClientInterface->openOutput(0,
1016 &mTestOutputs[mCurOutput],
1017 &config,
1018 &outputDesc->mDevice,
1019 String8(""),
1020 &outputDesc->mLatency,
1021 outputDesc->mFlags);
1022 if (status == NO_ERROR) {
1023 outputDesc->mSamplingRate = config.sample_rate;
1024 outputDesc->mFormat = config.format;
1025 outputDesc->mChannelMask = config.channel_mask;
Eric Laurente552edb2014-03-10 17:42:56 -07001026 AudioParameter outputCmd = AudioParameter();
1027 outputCmd.addInt(String8("set_id"),mCurOutput);
1028 mpClientInterface->setParameters(mTestOutputs[mCurOutput],outputCmd.toString());
1029 addOutput(mTestOutputs[mCurOutput], outputDesc);
1030 }
1031 }
1032 return mTestOutputs[mCurOutput];
1033 }
1034#endif //AUDIO_POLICY_TEST
1035
1036 // open a direct output if required by specified parameters
1037 //force direct flag if offload flag is set: offloading implies a direct output stream
1038 // and all common behaviors are driven by checking only the direct flag
1039 // this should normally be set appropriately in the policy configuration file
1040 if ((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07001041 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001042 }
Eric Laurent93c3d412014-08-01 14:48:35 -07001043 if ((flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1044 flags = (audio_output_flags_t)(flags | AUDIO_OUTPUT_FLAG_DIRECT);
1045 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001046 // only allow deep buffering for music stream type
1047 if (stream != AUDIO_STREAM_MUSIC) {
1048 flags = (audio_output_flags_t)(flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
1049 }
Eric Laurente552edb2014-03-10 17:42:56 -07001050
Eric Laurentb732cf52014-09-24 19:08:21 -07001051 sp<IOProfile> profile;
1052
1053 // skip direct output selection if the request can obviously be attached to a mixed output
Eric Laurentc2607842014-09-29 09:43:03 -07001054 // and not explicitly requested
1055 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1056 audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE &&
Eric Laurentb732cf52014-09-24 19:08:21 -07001057 audio_channel_count_from_out_mask(channelMask) <= 2) {
1058 goto non_direct_output;
1059 }
1060
Eric Laurente552edb2014-03-10 17:42:56 -07001061 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
1062 // creating an offloaded track and tearing it down immediately after start when audioflinger
1063 // detects there is an active non offloadable effect.
1064 // FIXME: We should check the audio session here but we do not have it in this context.
1065 // This may prevent offloading in rare situations where effects are left active by apps
1066 // in the background.
Eric Laurentb732cf52014-09-24 19:08:21 -07001067
Eric Laurente552edb2014-03-10 17:42:56 -07001068 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1069 !isNonOffloadableEffectEnabled()) {
1070 profile = getProfileForDirectOutput(device,
1071 samplingRate,
1072 format,
1073 channelMask,
1074 (audio_output_flags_t)flags);
1075 }
1076
Eric Laurent1c333e22014-05-20 10:48:17 -07001077 if (profile != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001078 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurente552edb2014-03-10 17:42:56 -07001079
1080 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001081 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001082 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1083 outputDesc = desc;
1084 // reuse direct output if currently open and configured with same parameters
1085 if ((samplingRate == outputDesc->mSamplingRate) &&
1086 (format == outputDesc->mFormat) &&
1087 (channelMask == outputDesc->mChannelMask)) {
1088 outputDesc->mDirectOpenCount++;
1089 ALOGV("getOutput() reusing direct output %d", mOutputs.keyAt(i));
1090 return mOutputs.keyAt(i);
1091 }
1092 }
1093 }
1094 // close direct output if currently open and configured with different parameters
1095 if (outputDesc != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07001096 closeOutput(outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07001097 }
1098 outputDesc = new AudioOutputDescriptor(profile);
1099 outputDesc->mDevice = device;
Eric Laurente552edb2014-03-10 17:42:56 -07001100 outputDesc->mLatency = 0;
1101 outputDesc->mFlags =(audio_output_flags_t) (outputDesc->mFlags | flags);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001102 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1103 config.sample_rate = samplingRate;
1104 config.channel_mask = channelMask;
1105 config.format = format;
Phil Burk77cce802014-08-04 16:18:15 -07001106 if (offloadInfo != NULL) {
1107 config.offload_info = *offloadInfo;
1108 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001109 status = mpClientInterface->openOutput(profile->mModule->mHandle,
1110 &output,
1111 &config,
1112 &outputDesc->mDevice,
1113 String8(""),
1114 &outputDesc->mLatency,
1115 outputDesc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001116
1117 // only accept an output with the requested parameters
Eric Laurentcf2c0212014-07-25 16:20:43 -07001118 if (status != NO_ERROR ||
1119 (samplingRate != 0 && samplingRate != config.sample_rate) ||
1120 (format != AUDIO_FORMAT_DEFAULT && format != config.format) ||
1121 (channelMask != 0 && channelMask != config.channel_mask)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001122 ALOGV("getOutput() failed opening direct output: output %d samplingRate %d %d,"
1123 "format %d %d, channelMask %04x %04x", output, samplingRate,
1124 outputDesc->mSamplingRate, format, outputDesc->mFormat, channelMask,
1125 outputDesc->mChannelMask);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001126 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07001127 mpClientInterface->closeOutput(output);
1128 }
Eric Laurenta82797f2015-01-30 11:49:43 -08001129 // fall back to mixer output if possible when the direct output could not be open
1130 if (audio_is_linear_pcm(format) && samplingRate <= MAX_MIXER_SAMPLING_RATE) {
1131 goto non_direct_output;
1132 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001133 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07001134 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07001135 outputDesc->mSamplingRate = config.sample_rate;
1136 outputDesc->mChannelMask = config.channel_mask;
1137 outputDesc->mFormat = config.format;
1138 outputDesc->mRefCount[stream] = 0;
1139 outputDesc->mStopTime[stream] = 0;
1140 outputDesc->mDirectOpenCount = 1;
1141
Eric Laurente552edb2014-03-10 17:42:56 -07001142 audio_io_handle_t srcOutput = getOutputForEffect();
1143 addOutput(output, outputDesc);
1144 audio_io_handle_t dstOutput = getOutputForEffect();
1145 if (dstOutput == output) {
1146 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, srcOutput, dstOutput);
1147 }
1148 mPreviousOutputs = mOutputs;
1149 ALOGV("getOutput() returns new direct output %d", output);
Eric Laurentb52c1522014-05-20 11:27:36 -07001150 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001151 return output;
1152 }
1153
Eric Laurentb732cf52014-09-24 19:08:21 -07001154non_direct_output:
1155
Eric Laurente552edb2014-03-10 17:42:56 -07001156 // ignoring channel mask due to downmix capability in mixer
1157
1158 // open a non direct output
1159
1160 // for non direct outputs, only PCM is supported
1161 if (audio_is_linear_pcm(format)) {
1162 // get which output is suitable for the specified stream. The actual
1163 // routing change will happen when startOutput() will be called
1164 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(device, mOutputs);
1165
Eric Laurent8838a382014-09-08 16:44:28 -07001166 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
1167 flags = (audio_output_flags_t)(flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1168 output = selectOutput(outputs, flags, format);
Eric Laurente552edb2014-03-10 17:42:56 -07001169 }
1170 ALOGW_IF((output == 0), "getOutput() could not find output for stream %d, samplingRate %d,"
1171 "format %d, channels %x, flags %x", stream, samplingRate, format, channelMask, flags);
1172
1173 ALOGV("getOutput() returns output %d", output);
1174
1175 return output;
1176}
1177
Eric Laurente0720872014-03-11 09:30:41 -07001178audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
Eric Laurent8838a382014-09-08 16:44:28 -07001179 audio_output_flags_t flags,
1180 audio_format_t format)
Eric Laurente552edb2014-03-10 17:42:56 -07001181{
1182 // select one output among several that provide a path to a particular device or set of
1183 // devices (the list was previously build by getOutputsForDevice()).
1184 // The priority is as follows:
1185 // 1: the output with the highest number of requested policy flags
1186 // 2: the primary output
1187 // 3: the first output in the list
1188
1189 if (outputs.size() == 0) {
1190 return 0;
1191 }
1192 if (outputs.size() == 1) {
1193 return outputs[0];
1194 }
1195
1196 int maxCommonFlags = 0;
1197 audio_io_handle_t outputFlags = 0;
1198 audio_io_handle_t outputPrimary = 0;
1199
1200 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001201 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07001202 if (!outputDesc->isDuplicated()) {
Eric Laurent8838a382014-09-08 16:44:28 -07001203 // if a valid format is specified, skip output if not compatible
1204 if (format != AUDIO_FORMAT_INVALID) {
1205 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
1206 if (format != outputDesc->mFormat) {
1207 continue;
1208 }
1209 } else if (!audio_is_linear_pcm(format)) {
1210 continue;
1211 }
1212 }
1213
Eric Laurent3b73df72014-03-11 09:06:29 -07001214 int commonFlags = popcount(outputDesc->mProfile->mFlags & flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001215 if (commonFlags > maxCommonFlags) {
1216 outputFlags = outputs[i];
1217 maxCommonFlags = commonFlags;
1218 ALOGV("selectOutput() commonFlags for output %d, %04x", outputs[i], commonFlags);
1219 }
1220 if (outputDesc->mProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
1221 outputPrimary = outputs[i];
1222 }
1223 }
1224 }
1225
1226 if (outputFlags != 0) {
1227 return outputFlags;
1228 }
1229 if (outputPrimary != 0) {
1230 return outputPrimary;
1231 }
1232
1233 return outputs[0];
1234}
1235
Eric Laurente0720872014-03-11 09:30:41 -07001236status_t AudioPolicyManager::startOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001237 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001238 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001239{
1240 ALOGV("startOutput() output %d, stream %d, session %d", output, stream, session);
1241 ssize_t index = mOutputs.indexOfKey(output);
1242 if (index < 0) {
1243 ALOGW("startOutput() unknown output %d", output);
1244 return BAD_VALUE;
1245 }
1246
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001247 // cannot start playback of STREAM_TTS if any other output is being used
1248 uint32_t beaconMuteLatency = 0;
1249 if (stream == AUDIO_STREAM_TTS) {
1250 ALOGV("\t found BEACON stream");
1251 if (isAnyOutputActive(AUDIO_STREAM_TTS /*streamToIgnore*/)) {
1252 return INVALID_OPERATION;
1253 } else {
1254 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1255 }
1256 } else {
1257 // some playback other than beacon starts
1258 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1259 }
1260
Eric Laurent1f2f2232014-06-02 12:01:23 -07001261 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001262
1263 // increment usage count for this stream on the requested output:
1264 // NOTE that the usage count is the same for duplicated output and hardware output which is
1265 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
1266 outputDesc->changeRefCount(stream, 1);
1267
1268 if (outputDesc->mRefCount[stream] == 1) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001269 // starting an output being rerouted?
1270 audio_devices_t newDevice;
Eric Laurentc722f302014-12-10 11:21:49 -08001271 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001272 newDevice = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
1273 } else {
1274 newDevice = getNewOutputDevice(output, false /*fromCache*/);
1275 }
Eric Laurente552edb2014-03-10 17:42:56 -07001276 routing_strategy strategy = getStrategy(stream);
1277 bool shouldWait = (strategy == STRATEGY_SONIFICATION) ||
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001278 (strategy == STRATEGY_SONIFICATION_RESPECTFUL) ||
1279 (beaconMuteLatency > 0);
1280 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07001281 bool force = false;
1282 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001283 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001284 if (desc != outputDesc) {
1285 // force a device change if any other output is managed by the same hw
1286 // module and has a current device selection that differs from selected device.
1287 // In this case, the audio HAL must receive the new device selection so that it can
1288 // change the device currently selected by the other active output.
1289 if (outputDesc->sharesHwModuleWith(desc) &&
1290 desc->device() != newDevice) {
1291 force = true;
1292 }
1293 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001294 // a notification so that audio focus effect can propagate, or that a mute/unmute
1295 // event occurred for beacon
Eric Laurente552edb2014-03-10 17:42:56 -07001296 uint32_t latency = desc->latency();
1297 if (shouldWait && desc->isActive(latency * 2) && (waitMs < latency)) {
1298 waitMs = latency;
1299 }
1300 }
1301 }
1302 uint32_t muteWaitMs = setOutputDevice(output, newDevice, force);
1303
1304 // handle special case for sonification while in call
1305 if (isInCall()) {
1306 handleIncallSonification(stream, true, false);
1307 }
1308
1309 // apply volume rules for current stream and device if necessary
1310 checkAndSetVolume(stream,
1311 mStreams[stream].getVolumeIndex(newDevice),
1312 output,
1313 newDevice);
1314
1315 // update the outputs if starting an output with a stream that can affect notification
1316 // routing
1317 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08001318
1319 // Automatically enable the remote submix input when output is started on a re routing mix
1320 // of type MIX_TYPE_RECORDERS
1321 if (audio_is_remote_submix_device(newDevice) && outputDesc->mPolicyMix != NULL &&
1322 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001323 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001324 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1325 outputDesc->mPolicyMix->mRegistrationId);
1326 }
1327
Eric Laurent2cbe89a2014-12-19 11:49:08 -08001328 // force reevaluating accessibility routing when ringtone or alarm starts
1329 if (strategy == STRATEGY_SONIFICATION) {
1330 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
1331 }
1332
Eric Laurente552edb2014-03-10 17:42:56 -07001333 if (waitMs > muteWaitMs) {
1334 usleep((waitMs - muteWaitMs) * 2 * 1000);
1335 }
1336 }
1337 return NO_ERROR;
1338}
1339
1340
Eric Laurente0720872014-03-11 09:30:41 -07001341status_t AudioPolicyManager::stopOutput(audio_io_handle_t output,
Eric Laurent3b73df72014-03-11 09:06:29 -07001342 audio_stream_type_t stream,
Eric Laurente83b55d2014-11-14 10:06:21 -08001343 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001344{
1345 ALOGV("stopOutput() output %d, stream %d, session %d", output, stream, session);
1346 ssize_t index = mOutputs.indexOfKey(output);
1347 if (index < 0) {
1348 ALOGW("stopOutput() unknown output %d", output);
1349 return BAD_VALUE;
1350 }
1351
Eric Laurent1f2f2232014-06-02 12:01:23 -07001352 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001353
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001354 // always handle stream stop, check which stream type is stopping
1355 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
1356
Eric Laurente552edb2014-03-10 17:42:56 -07001357 // handle special case for sonification while in call
1358 if (isInCall()) {
1359 handleIncallSonification(stream, false, false);
1360 }
1361
1362 if (outputDesc->mRefCount[stream] > 0) {
1363 // decrement usage count of this stream on the output
1364 outputDesc->changeRefCount(stream, -1);
1365 // store time at which the stream was stopped - see isStreamActive()
1366 if (outputDesc->mRefCount[stream] == 0) {
Eric Laurentc722f302014-12-10 11:21:49 -08001367 // Automatically disable the remote submix input when output is stopped on a
1368 // re routing mix of type MIX_TYPE_RECORDERS
1369 if (audio_is_remote_submix_device(outputDesc->mDevice) &&
1370 outputDesc->mPolicyMix != NULL &&
1371 outputDesc->mPolicyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001372 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001373 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1374 outputDesc->mPolicyMix->mRegistrationId);
1375 }
1376
Eric Laurente552edb2014-03-10 17:42:56 -07001377 outputDesc->mStopTime[stream] = systemTime();
Eric Laurent1c333e22014-05-20 10:48:17 -07001378 audio_devices_t newDevice = getNewOutputDevice(output, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07001379 // delay the device switch by twice the latency because stopOutput() is executed when
1380 // the track stop() command is received and at that time the audio track buffer can
1381 // still contain data that needs to be drained. The latency only covers the audio HAL
1382 // and kernel buffers. Also the latency does not always include additional delay in the
1383 // audio path (audio DSP, CODEC ...)
1384 setOutputDevice(output, newDevice, false, outputDesc->mLatency*2);
1385
1386 // force restoring the device selection on other active outputs if it differs from the
1387 // one being selected for this output
1388 for (size_t i = 0; i < mOutputs.size(); i++) {
1389 audio_io_handle_t curOutput = mOutputs.keyAt(i);
Eric Laurent1f2f2232014-06-02 12:01:23 -07001390 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07001391 if (curOutput != output &&
1392 desc->isActive() &&
1393 outputDesc->sharesHwModuleWith(desc) &&
1394 (newDevice != desc->device())) {
1395 setOutputDevice(curOutput,
Eric Laurent1c333e22014-05-20 10:48:17 -07001396 getNewOutputDevice(curOutput, false /*fromCache*/),
Eric Laurente552edb2014-03-10 17:42:56 -07001397 true,
1398 outputDesc->mLatency*2);
1399 }
1400 }
1401 // update the outputs if stopping one with a stream that can affect notification routing
1402 handleNotificationRoutingForStream(stream);
1403 }
1404 return NO_ERROR;
1405 } else {
1406 ALOGW("stopOutput() refcount is already 0 for output %d", output);
1407 return INVALID_OPERATION;
1408 }
1409}
1410
Eric Laurente83b55d2014-11-14 10:06:21 -08001411void AudioPolicyManager::releaseOutput(audio_io_handle_t output,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001412 audio_stream_type_t stream __unused,
1413 audio_session_t session __unused)
Eric Laurente552edb2014-03-10 17:42:56 -07001414{
1415 ALOGV("releaseOutput() %d", output);
1416 ssize_t index = mOutputs.indexOfKey(output);
1417 if (index < 0) {
1418 ALOGW("releaseOutput() releasing unknown output %d", output);
1419 return;
1420 }
1421
1422#ifdef AUDIO_POLICY_TEST
1423 int testIndex = testOutputIndex(output);
1424 if (testIndex != 0) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001425 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001426 if (outputDesc->isActive()) {
1427 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07001428 mOutputs.removeItem(output);
1429 mTestOutputs[testIndex] = 0;
1430 }
1431 return;
1432 }
1433#endif //AUDIO_POLICY_TEST
1434
Eric Laurent1f2f2232014-06-02 12:01:23 -07001435 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(index);
Eric Laurent3b73df72014-03-11 09:06:29 -07001436 if (desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
Eric Laurente552edb2014-03-10 17:42:56 -07001437 if (desc->mDirectOpenCount <= 0) {
1438 ALOGW("releaseOutput() invalid open count %d for output %d",
1439 desc->mDirectOpenCount, output);
1440 return;
1441 }
1442 if (--desc->mDirectOpenCount == 0) {
1443 closeOutput(output);
1444 // If effects where present on the output, audioflinger moved them to the primary
1445 // output by default: move them back to the appropriate output.
1446 audio_io_handle_t dstOutput = getOutputForEffect();
1447 if (dstOutput != mPrimaryOutput) {
1448 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mPrimaryOutput, dstOutput);
1449 }
Eric Laurentb52c1522014-05-20 11:27:36 -07001450 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001451 }
1452 }
1453}
1454
1455
Eric Laurentcaf7f482014-11-25 17:50:47 -08001456status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
1457 audio_io_handle_t *input,
1458 audio_session_t session,
1459 uint32_t samplingRate,
1460 audio_format_t format,
1461 audio_channel_mask_t channelMask,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001462 audio_input_flags_t flags,
1463 input_type_t *inputType)
Eric Laurente552edb2014-03-10 17:42:56 -07001464{
Eric Laurentcaf7f482014-11-25 17:50:47 -08001465 ALOGV("getInputForAttr() source %d, samplingRate %d, format %d, channelMask %x,"
1466 "session %d, flags %#x",
1467 attr->source, samplingRate, format, channelMask, session, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001468
Eric Laurentcaf7f482014-11-25 17:50:47 -08001469 *input = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001470 *inputType = API_INPUT_INVALID;
Eric Laurent275e8e92014-11-30 15:14:47 -08001471 audio_devices_t device;
1472 // handle legacy remote submix case where the address was not always specified
1473 String8 address = String8("");
Eric Laurent5dbe4712014-09-19 19:04:57 -07001474 bool isSoundTrigger = false;
Eric Laurentc447ded2015-01-06 08:47:05 -08001475 audio_source_t inputSource = attr->source;
1476 audio_source_t halInputSource;
Eric Laurentc722f302014-12-10 11:21:49 -08001477 AudioMix *policyMix = NULL;
Eric Laurent275e8e92014-11-30 15:14:47 -08001478
Eric Laurentc447ded2015-01-06 08:47:05 -08001479 if (inputSource == AUDIO_SOURCE_DEFAULT) {
1480 inputSource = AUDIO_SOURCE_MIC;
1481 }
1482 halInputSource = inputSource;
1483
1484 if (inputSource == AUDIO_SOURCE_REMOTE_SUBMIX &&
Eric Laurent275e8e92014-11-30 15:14:47 -08001485 strncmp(attr->tags, "addr=", strlen("addr=")) == 0) {
1486 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
1487 address = String8(attr->tags + strlen("addr="));
1488 ssize_t index = mPolicyMixes.indexOfKey(address);
1489 if (index < 0) {
1490 ALOGW("getInputForAttr() no policy for address %s", address.string());
1491 return BAD_VALUE;
1492 }
Eric Laurentc722f302014-12-10 11:21:49 -08001493 if (mPolicyMixes[index]->mMix.mMixType != MIX_TYPE_PLAYERS) {
1494 ALOGW("getInputForAttr() bad policy mix type for address %s", address.string());
1495 return BAD_VALUE;
1496 }
1497 policyMix = &mPolicyMixes[index]->mMix;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001498 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001499 } else {
Eric Laurentc447ded2015-01-06 08:47:05 -08001500 device = getDeviceAndMixForInputSource(inputSource, &policyMix);
Eric Laurent275e8e92014-11-30 15:14:47 -08001501 if (device == AUDIO_DEVICE_NONE) {
Eric Laurentc447ded2015-01-06 08:47:05 -08001502 ALOGW("getInputForAttr() could not find device for source %d", inputSource);
Eric Laurent275e8e92014-11-30 15:14:47 -08001503 return BAD_VALUE;
1504 }
Eric Laurentc722f302014-12-10 11:21:49 -08001505 if (policyMix != NULL) {
1506 address = policyMix->mRegistrationId;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001507 if (policyMix->mMixType == MIX_TYPE_RECORDERS) {
1508 // there is an external policy, but this input is attached to a mix of recorders,
1509 // meaning it receives audio injected into the framework, so the recorder doesn't
1510 // know about it and is therefore considered "legacy"
1511 *inputType = API_INPUT_LEGACY;
1512 } else {
1513 // recording a mix of players defined by an external policy, we're rerouting for
1514 // an external policy
1515 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
1516 }
Eric Laurentc722f302014-12-10 11:21:49 -08001517 } else if (audio_is_remote_submix_device(device)) {
1518 address = String8("0");
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001519 *inputType = API_INPUT_MIX_CAPTURE;
1520 } else {
1521 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08001522 }
Eric Laurent275e8e92014-11-30 15:14:47 -08001523 // adapt channel selection to input source
Eric Laurentc447ded2015-01-06 08:47:05 -08001524 switch (inputSource) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001525 case AUDIO_SOURCE_VOICE_UPLINK:
1526 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK;
1527 break;
1528 case AUDIO_SOURCE_VOICE_DOWNLINK:
1529 channelMask = AUDIO_CHANNEL_IN_VOICE_DNLINK;
1530 break;
1531 case AUDIO_SOURCE_VOICE_CALL:
1532 channelMask = AUDIO_CHANNEL_IN_VOICE_UPLINK | AUDIO_CHANNEL_IN_VOICE_DNLINK;
1533 break;
1534 default:
1535 break;
1536 }
Eric Laurentc447ded2015-01-06 08:47:05 -08001537 if (inputSource == AUDIO_SOURCE_HOTWORD) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001538 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
1539 if (index >= 0) {
1540 *input = mSoundTriggerSessions.valueFor(session);
1541 isSoundTrigger = true;
1542 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
1543 ALOGV("SoundTrigger capture on session %d input %d", session, *input);
1544 } else {
1545 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
1546 }
Eric Laurent5dbe4712014-09-19 19:04:57 -07001547 }
1548 }
1549
Eric Laurent275e8e92014-11-30 15:14:47 -08001550 sp<IOProfile> profile = getInputProfile(device, address,
1551 samplingRate, format, channelMask,
1552 flags);
Eric Laurent1c333e22014-05-20 10:48:17 -07001553 if (profile == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07001554 //retry without flags
1555 audio_input_flags_t log_flags = flags;
1556 flags = AUDIO_INPUT_FLAG_NONE;
Eric Laurent275e8e92014-11-30 15:14:47 -08001557 profile = getInputProfile(device, address,
1558 samplingRate, format, channelMask,
1559 flags);
Eric Laurent5dbe4712014-09-19 19:04:57 -07001560 if (profile == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001561 ALOGW("getInputForAttr() could not find profile for device 0x%X, samplingRate %u,"
1562 "format %#x, channelMask 0x%X, flags %#x",
Eric Laurent5dbe4712014-09-19 19:04:57 -07001563 device, samplingRate, format, channelMask, log_flags);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001564 return BAD_VALUE;
Eric Laurent5dbe4712014-09-19 19:04:57 -07001565 }
Eric Laurente552edb2014-03-10 17:42:56 -07001566 }
1567
1568 if (profile->mModule->mHandle == 0) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001569 ALOGE("getInputForAttr(): HW module %s not opened", profile->mModule->mName);
1570 return NO_INIT;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001571 }
1572
1573 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1574 config.sample_rate = samplingRate;
1575 config.channel_mask = channelMask;
1576 config.format = format;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001577
Eric Laurentcf2c0212014-07-25 16:20:43 -07001578 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
Eric Laurentcaf7f482014-11-25 17:50:47 -08001579 input,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001580 &config,
1581 &device,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07001582 address,
Eric Laurent1c9c2cc2014-08-28 19:37:25 -07001583 halInputSource,
Eric Laurentcf2c0212014-07-25 16:20:43 -07001584 flags);
1585
1586 // only accept input with the exact requested set of parameters
Eric Laurentcaf7f482014-11-25 17:50:47 -08001587 if (status != NO_ERROR || *input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentcf2c0212014-07-25 16:20:43 -07001588 (samplingRate != config.sample_rate) ||
1589 (format != config.format) ||
1590 (channelMask != config.channel_mask)) {
Eric Laurentcaf7f482014-11-25 17:50:47 -08001591 ALOGW("getInputForAttr() failed opening input: samplingRate %d, format %d, channelMask %x",
Eric Laurentcf2c0212014-07-25 16:20:43 -07001592 samplingRate, format, channelMask);
Eric Laurentcaf7f482014-11-25 17:50:47 -08001593 if (*input != AUDIO_IO_HANDLE_NONE) {
1594 mpClientInterface->closeInput(*input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07001595 }
Eric Laurentcaf7f482014-11-25 17:50:47 -08001596 return BAD_VALUE;
Eric Laurente552edb2014-03-10 17:42:56 -07001597 }
1598
Eric Laurent1f2f2232014-06-02 12:01:23 -07001599 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile);
Eric Laurentc447ded2015-01-06 08:47:05 -08001600 inputDesc->mInputSource = inputSource;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001601 inputDesc->mRefCount = 0;
1602 inputDesc->mOpenRefCount = 1;
Eric Laurente552edb2014-03-10 17:42:56 -07001603 inputDesc->mSamplingRate = samplingRate;
1604 inputDesc->mFormat = format;
1605 inputDesc->mChannelMask = channelMask;
Eric Laurentcf2c0212014-07-25 16:20:43 -07001606 inputDesc->mDevice = device;
Eric Laurentc722f302014-12-10 11:21:49 -08001607 inputDesc->mSessions.add(session);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001608 inputDesc->mIsSoundTrigger = isSoundTrigger;
Eric Laurentc722f302014-12-10 11:21:49 -08001609 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001610
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08001611 ALOGV("getInputForAttr() returns input type = %d", inputType);
1612
Eric Laurentcaf7f482014-11-25 17:50:47 -08001613 addInput(*input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07001614 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcaf7f482014-11-25 17:50:47 -08001615 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001616}
1617
Eric Laurent4dc68062014-07-28 17:26:49 -07001618status_t AudioPolicyManager::startInput(audio_io_handle_t input,
1619 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001620{
1621 ALOGV("startInput() input %d", input);
1622 ssize_t index = mInputs.indexOfKey(input);
1623 if (index < 0) {
1624 ALOGW("startInput() unknown input %d", input);
1625 return BAD_VALUE;
1626 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001627 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001628
Eric Laurentc722f302014-12-10 11:21:49 -08001629 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001630 if (index < 0) {
1631 ALOGW("startInput() unknown session %d on input %d", session, input);
1632 return BAD_VALUE;
1633 }
1634
Glenn Kasten74a8e252014-07-24 14:09:55 -07001635 // virtual input devices are compatible with other input devices
1636 if (!isVirtualInputDevice(inputDesc->mDevice)) {
1637
1638 // for a non-virtual input device, check if there is another (non-virtual) active input
Eric Laurente552edb2014-03-10 17:42:56 -07001639 audio_io_handle_t activeInput = getActiveInput();
Glenn Kasten74a8e252014-07-24 14:09:55 -07001640 if (activeInput != 0 && activeInput != input) {
1641
1642 // If the already active input uses AUDIO_SOURCE_HOTWORD then it is closed,
1643 // otherwise the active input continues and the new input cannot be started.
Eric Laurent1f2f2232014-06-02 12:01:23 -07001644 sp<AudioInputDescriptor> activeDesc = mInputs.valueFor(activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001645 if (activeDesc->mInputSource == AUDIO_SOURCE_HOTWORD) {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001646 ALOGW("startInput(%d) preempting low-priority input %d", input, activeInput);
Eric Laurentc722f302014-12-10 11:21:49 -08001647 stopInput(activeInput, activeDesc->mSessions.itemAt(0));
1648 releaseInput(activeInput, activeDesc->mSessions.itemAt(0));
Eric Laurente552edb2014-03-10 17:42:56 -07001649 } else {
Glenn Kasten74a8e252014-07-24 14:09:55 -07001650 ALOGE("startInput(%d) failed: other input %d already started", input, activeInput);
Eric Laurente552edb2014-03-10 17:42:56 -07001651 return INVALID_OPERATION;
1652 }
1653 }
1654 }
1655
Glenn Kasten74a8e252014-07-24 14:09:55 -07001656 if (inputDesc->mRefCount == 0) {
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001657 if (activeInputsCount() == 0) {
1658 SoundTrigger::setCaptureState(true);
1659 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001660 setInputDevice(input, getNewInputDevice(input), true /* force */);
Eric Laurente552edb2014-03-10 17:42:56 -07001661
Eric Laurentc722f302014-12-10 11:21:49 -08001662 // automatically enable the remote submix output when input is started if not
1663 // used by a policy mix of type MIX_TYPE_RECORDERS
Glenn Kasten74a8e252014-07-24 14:09:55 -07001664 // For remote submix (a virtual device), we open only one input per capture request.
1665 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001666 String8 address = String8("");
1667 if (inputDesc->mPolicyMix == NULL) {
1668 address = String8("0");
1669 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1670 address = inputDesc->mPolicyMix->mRegistrationId;
1671 }
1672 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001673 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001674 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
1675 address);
1676 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07001677 }
Eric Laurente552edb2014-03-10 17:42:56 -07001678 }
1679
Eric Laurente552edb2014-03-10 17:42:56 -07001680 ALOGV("AudioPolicyManager::startInput() input source = %d", inputDesc->mInputSource);
1681
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001682 inputDesc->mRefCount++;
Eric Laurente552edb2014-03-10 17:42:56 -07001683 return NO_ERROR;
1684}
1685
Eric Laurent4dc68062014-07-28 17:26:49 -07001686status_t AudioPolicyManager::stopInput(audio_io_handle_t input,
1687 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001688{
1689 ALOGV("stopInput() input %d", input);
1690 ssize_t index = mInputs.indexOfKey(input);
1691 if (index < 0) {
1692 ALOGW("stopInput() unknown input %d", input);
1693 return BAD_VALUE;
1694 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001695 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001696
Eric Laurentc722f302014-12-10 11:21:49 -08001697 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001698 if (index < 0) {
1699 ALOGW("stopInput() unknown session %d on input %d", session, input);
1700 return BAD_VALUE;
1701 }
1702
Eric Laurente552edb2014-03-10 17:42:56 -07001703 if (inputDesc->mRefCount == 0) {
1704 ALOGW("stopInput() input %d already stopped", input);
1705 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001706 }
1707
1708 inputDesc->mRefCount--;
1709 if (inputDesc->mRefCount == 0) {
1710
Eric Laurentc722f302014-12-10 11:21:49 -08001711 // automatically disable the remote submix output when input is stopped if not
1712 // used by a policy mix of type MIX_TYPE_RECORDERS
Eric Laurente552edb2014-03-10 17:42:56 -07001713 if (audio_is_remote_submix_device(inputDesc->mDevice)) {
Eric Laurentc722f302014-12-10 11:21:49 -08001714 String8 address = String8("");
1715 if (inputDesc->mPolicyMix == NULL) {
1716 address = String8("0");
1717 } else if (inputDesc->mPolicyMix->mMixType == MIX_TYPE_PLAYERS) {
1718 address = inputDesc->mPolicyMix->mRegistrationId;
1719 }
1720 if (address != "") {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08001721 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08001722 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
1723 address);
1724 }
Eric Laurente552edb2014-03-10 17:42:56 -07001725 }
1726
Eric Laurent1c333e22014-05-20 10:48:17 -07001727 resetInputDevice(input);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07001728
1729 if (activeInputsCount() == 0) {
1730 SoundTrigger::setCaptureState(false);
1731 }
Eric Laurente552edb2014-03-10 17:42:56 -07001732 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001733 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07001734}
1735
Eric Laurent4dc68062014-07-28 17:26:49 -07001736void AudioPolicyManager::releaseInput(audio_io_handle_t input,
1737 audio_session_t session)
Eric Laurente552edb2014-03-10 17:42:56 -07001738{
1739 ALOGV("releaseInput() %d", input);
1740 ssize_t index = mInputs.indexOfKey(input);
1741 if (index < 0) {
1742 ALOGW("releaseInput() releasing unknown input %d", input);
1743 return;
1744 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001745 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
1746 ALOG_ASSERT(inputDesc != 0);
Eric Laurent4dc68062014-07-28 17:26:49 -07001747
Eric Laurentc722f302014-12-10 11:21:49 -08001748 index = inputDesc->mSessions.indexOf(session);
Eric Laurent4dc68062014-07-28 17:26:49 -07001749 if (index < 0) {
1750 ALOGW("releaseInput() unknown session %d on input %d", session, input);
1751 return;
1752 }
Eric Laurentc722f302014-12-10 11:21:49 -08001753 inputDesc->mSessions.remove(session);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07001754 if (inputDesc->mOpenRefCount == 0) {
1755 ALOGW("releaseInput() invalid open ref count %d", inputDesc->mOpenRefCount);
1756 return;
1757 }
1758 inputDesc->mOpenRefCount--;
1759 if (inputDesc->mOpenRefCount > 0) {
1760 ALOGV("releaseInput() exit > 0");
1761 return;
1762 }
1763
Eric Laurent05b90f82014-08-27 15:32:29 -07001764 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07001765 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07001766 ALOGV("releaseInput() exit");
1767}
1768
Eric Laurentd4692962014-05-05 18:13:44 -07001769void AudioPolicyManager::closeAllInputs() {
Eric Laurent05b90f82014-08-27 15:32:29 -07001770 bool patchRemoved = false;
1771
Eric Laurentd4692962014-05-05 18:13:44 -07001772 for(size_t input_index = 0; input_index < mInputs.size(); input_index++) {
Eric Laurent05b90f82014-08-27 15:32:29 -07001773 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(input_index);
1774 ssize_t patch_index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
1775 if (patch_index >= 0) {
1776 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(patch_index);
1777 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
1778 mAudioPatches.removeItemsAt(patch_index);
1779 patchRemoved = true;
1780 }
Eric Laurentd4692962014-05-05 18:13:44 -07001781 mpClientInterface->closeInput(mInputs.keyAt(input_index));
1782 }
1783 mInputs.clear();
Eric Laurent6a94d692014-05-20 11:18:06 -07001784 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07001785
1786 if (patchRemoved) {
1787 mpClientInterface->onAudioPatchListUpdate();
1788 }
Eric Laurentd4692962014-05-05 18:13:44 -07001789}
1790
Eric Laurente0720872014-03-11 09:30:41 -07001791void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001792 int indexMin,
1793 int indexMax)
1794{
1795 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
1796 if (indexMin < 0 || indexMin >= indexMax) {
1797 ALOGW("initStreamVolume() invalid index limits for stream %d, min %d, max %d", stream , indexMin, indexMax);
1798 return;
1799 }
1800 mStreams[stream].mIndexMin = indexMin;
1801 mStreams[stream].mIndexMax = indexMax;
Eric Laurent223fd5c2014-11-11 13:43:36 -08001802 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1803 if (stream == AUDIO_STREAM_MUSIC) {
1804 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMin = indexMin;
1805 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexMax = indexMax;
1806 }
Eric Laurente552edb2014-03-10 17:42:56 -07001807}
1808
Eric Laurente0720872014-03-11 09:30:41 -07001809status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001810 int index,
1811 audio_devices_t device)
1812{
1813
1814 if ((index < mStreams[stream].mIndexMin) || (index > mStreams[stream].mIndexMax)) {
1815 return BAD_VALUE;
1816 }
1817 if (!audio_is_output_device(device)) {
1818 return BAD_VALUE;
1819 }
1820
1821 // Force max volume if stream cannot be muted
1822 if (!mStreams[stream].mCanBeMuted) index = mStreams[stream].mIndexMax;
1823
1824 ALOGV("setStreamVolumeIndex() stream %d, device %04x, index %d",
1825 stream, device, index);
1826
1827 // if device is AUDIO_DEVICE_OUT_DEFAULT set default value and
1828 // clear all device specific values
1829 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1830 mStreams[stream].mIndexCur.clear();
1831 }
1832 mStreams[stream].mIndexCur.add(device, index);
1833
Eric Laurent31551f82014-10-10 18:21:56 -07001834 // update volume on all outputs whose current device is also selected by the same
1835 // strategy as the device specified by the caller
1836 audio_devices_t strategyDevice = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
Eric Laurent223fd5c2014-11-11 13:43:36 -08001837
1838
1839 //FIXME: AUDIO_STREAM_ACCESSIBILITY volume follows AUDIO_STREAM_MUSIC for now
1840 audio_devices_t accessibilityDevice = AUDIO_DEVICE_NONE;
1841 if (stream == AUDIO_STREAM_MUSIC) {
1842 mStreams[AUDIO_STREAM_ACCESSIBILITY].mIndexCur.add(device, index);
1843 accessibilityDevice = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, true /*fromCache*/);
1844 }
1845 if ((device != AUDIO_DEVICE_OUT_DEFAULT) &&
1846 (device & (strategyDevice | accessibilityDevice)) == 0) {
Eric Laurent31551f82014-10-10 18:21:56 -07001847 return NO_ERROR;
1848 }
Eric Laurente552edb2014-03-10 17:42:56 -07001849 status_t status = NO_ERROR;
1850 for (size_t i = 0; i < mOutputs.size(); i++) {
1851 audio_devices_t curDevice =
1852 getDeviceForVolume(mOutputs.valueAt(i)->device());
Eric Laurent31551f82014-10-10 18:21:56 -07001853 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & strategyDevice) != 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001854 status_t volStatus = checkAndSetVolume(stream, index, mOutputs.keyAt(i), curDevice);
1855 if (volStatus != NO_ERROR) {
1856 status = volStatus;
1857 }
1858 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08001859 if ((device == AUDIO_DEVICE_OUT_DEFAULT) || ((curDevice & accessibilityDevice) != 0)) {
1860 status_t volStatus = checkAndSetVolume(AUDIO_STREAM_ACCESSIBILITY,
1861 index, mOutputs.keyAt(i), curDevice);
1862 }
Eric Laurente552edb2014-03-10 17:42:56 -07001863 }
1864 return status;
1865}
1866
Eric Laurente0720872014-03-11 09:30:41 -07001867status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07001868 int *index,
1869 audio_devices_t device)
1870{
1871 if (index == NULL) {
1872 return BAD_VALUE;
1873 }
1874 if (!audio_is_output_device(device)) {
1875 return BAD_VALUE;
1876 }
1877 // if device is AUDIO_DEVICE_OUT_DEFAULT, return volume for device corresponding to
1878 // the strategy the stream belongs to.
1879 if (device == AUDIO_DEVICE_OUT_DEFAULT) {
1880 device = getDeviceForStrategy(getStrategy(stream), true /*fromCache*/);
1881 }
1882 device = getDeviceForVolume(device);
1883
1884 *index = mStreams[stream].getVolumeIndex(device);
1885 ALOGV("getStreamVolumeIndex() stream %d device %08x index %d", stream, device, *index);
1886 return NO_ERROR;
1887}
1888
Eric Laurente0720872014-03-11 09:30:41 -07001889audio_io_handle_t AudioPolicyManager::selectOutputForEffects(
Eric Laurente552edb2014-03-10 17:42:56 -07001890 const SortedVector<audio_io_handle_t>& outputs)
1891{
1892 // select one output among several suitable for global effects.
1893 // The priority is as follows:
1894 // 1: An offloaded output. If the effect ends up not being offloadable,
1895 // AudioFlinger will invalidate the track and the offloaded output
1896 // will be closed causing the effect to be moved to a PCM output.
1897 // 2: A deep buffer output
1898 // 3: the first output in the list
1899
1900 if (outputs.size() == 0) {
1901 return 0;
1902 }
1903
1904 audio_io_handle_t outputOffloaded = 0;
1905 audio_io_handle_t outputDeepBuffer = 0;
1906
1907 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07001908 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(outputs[i]);
Eric Laurentd4692962014-05-05 18:13:44 -07001909 ALOGV("selectOutputForEffects outputs[%zu] flags %x", i, desc->mFlags);
Eric Laurente552edb2014-03-10 17:42:56 -07001910 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1911 outputOffloaded = outputs[i];
1912 }
1913 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1914 outputDeepBuffer = outputs[i];
1915 }
1916 }
1917
1918 ALOGV("selectOutputForEffects outputOffloaded %d outputDeepBuffer %d",
1919 outputOffloaded, outputDeepBuffer);
1920 if (outputOffloaded != 0) {
1921 return outputOffloaded;
1922 }
1923 if (outputDeepBuffer != 0) {
1924 return outputDeepBuffer;
1925 }
1926
1927 return outputs[0];
1928}
1929
Eric Laurente0720872014-03-11 09:30:41 -07001930audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc)
Eric Laurente552edb2014-03-10 17:42:56 -07001931{
1932 // apply simple rule where global effects are attached to the same output as MUSIC streams
1933
Eric Laurent3b73df72014-03-11 09:06:29 -07001934 routing_strategy strategy = getStrategy(AUDIO_STREAM_MUSIC);
Eric Laurente552edb2014-03-10 17:42:56 -07001935 audio_devices_t device = getDeviceForStrategy(strategy, false /*fromCache*/);
1936 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(device, mOutputs);
1937
1938 audio_io_handle_t output = selectOutputForEffects(dstOutputs);
1939 ALOGV("getOutputForEffect() got output %d for fx %s flags %x",
1940 output, (desc == NULL) ? "unspecified" : desc->name, (desc == NULL) ? 0 : desc->flags);
1941
1942 return output;
1943}
1944
Eric Laurente0720872014-03-11 09:30:41 -07001945status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07001946 audio_io_handle_t io,
1947 uint32_t strategy,
1948 int session,
1949 int id)
1950{
1951 ssize_t index = mOutputs.indexOfKey(io);
1952 if (index < 0) {
1953 index = mInputs.indexOfKey(io);
1954 if (index < 0) {
1955 ALOGW("registerEffect() unknown io %d", io);
1956 return INVALID_OPERATION;
1957 }
1958 }
1959
1960 if (mTotalEffectsMemory + desc->memoryUsage > getMaxEffectsMemory()) {
1961 ALOGW("registerEffect() memory limit exceeded for Fx %s, Memory %d KB",
1962 desc->name, desc->memoryUsage);
1963 return INVALID_OPERATION;
1964 }
1965 mTotalEffectsMemory += desc->memoryUsage;
1966 ALOGV("registerEffect() effect %s, io %d, strategy %d session %d id %d",
1967 desc->name, io, strategy, session, id);
1968 ALOGV("registerEffect() memory %d, total memory %d", desc->memoryUsage, mTotalEffectsMemory);
1969
Eric Laurent1f2f2232014-06-02 12:01:23 -07001970 sp<EffectDescriptor> effectDesc = new EffectDescriptor();
1971 memcpy (&effectDesc->mDesc, desc, sizeof(effect_descriptor_t));
1972 effectDesc->mIo = io;
1973 effectDesc->mStrategy = (routing_strategy)strategy;
1974 effectDesc->mSession = session;
1975 effectDesc->mEnabled = false;
Eric Laurente552edb2014-03-10 17:42:56 -07001976
Eric Laurent1f2f2232014-06-02 12:01:23 -07001977 mEffects.add(id, effectDesc);
Eric Laurente552edb2014-03-10 17:42:56 -07001978
1979 return NO_ERROR;
1980}
1981
Eric Laurente0720872014-03-11 09:30:41 -07001982status_t AudioPolicyManager::unregisterEffect(int id)
Eric Laurente552edb2014-03-10 17:42:56 -07001983{
1984 ssize_t index = mEffects.indexOfKey(id);
1985 if (index < 0) {
1986 ALOGW("unregisterEffect() unknown effect ID %d", id);
1987 return INVALID_OPERATION;
1988 }
1989
Eric Laurent1f2f2232014-06-02 12:01:23 -07001990 sp<EffectDescriptor> effectDesc = mEffects.valueAt(index);
Eric Laurente552edb2014-03-10 17:42:56 -07001991
Eric Laurent1f2f2232014-06-02 12:01:23 -07001992 setEffectEnabled(effectDesc, false);
Eric Laurente552edb2014-03-10 17:42:56 -07001993
Eric Laurent1f2f2232014-06-02 12:01:23 -07001994 if (mTotalEffectsMemory < effectDesc->mDesc.memoryUsage) {
Eric Laurente552edb2014-03-10 17:42:56 -07001995 ALOGW("unregisterEffect() memory %d too big for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07001996 effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
1997 effectDesc->mDesc.memoryUsage = mTotalEffectsMemory;
Eric Laurente552edb2014-03-10 17:42:56 -07001998 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07001999 mTotalEffectsMemory -= effectDesc->mDesc.memoryUsage;
Eric Laurente552edb2014-03-10 17:42:56 -07002000 ALOGV("unregisterEffect() effect %s, ID %d, memory %d total memory %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002001 effectDesc->mDesc.name, id, effectDesc->mDesc.memoryUsage, mTotalEffectsMemory);
Eric Laurente552edb2014-03-10 17:42:56 -07002002
2003 mEffects.removeItem(id);
Eric Laurente552edb2014-03-10 17:42:56 -07002004
2005 return NO_ERROR;
2006}
2007
Eric Laurente0720872014-03-11 09:30:41 -07002008status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07002009{
2010 ssize_t index = mEffects.indexOfKey(id);
2011 if (index < 0) {
2012 ALOGW("unregisterEffect() unknown effect ID %d", id);
2013 return INVALID_OPERATION;
2014 }
2015
2016 return setEffectEnabled(mEffects.valueAt(index), enabled);
2017}
2018
Eric Laurent1f2f2232014-06-02 12:01:23 -07002019status_t AudioPolicyManager::setEffectEnabled(const sp<EffectDescriptor>& effectDesc, bool enabled)
Eric Laurente552edb2014-03-10 17:42:56 -07002020{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002021 if (enabled == effectDesc->mEnabled) {
Eric Laurente552edb2014-03-10 17:42:56 -07002022 ALOGV("setEffectEnabled(%s) effect already %s",
2023 enabled?"true":"false", enabled?"enabled":"disabled");
2024 return INVALID_OPERATION;
2025 }
2026
2027 if (enabled) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002028 if (mTotalEffectsCpuLoad + effectDesc->mDesc.cpuLoad > getMaxEffectsCpuLoad()) {
Eric Laurente552edb2014-03-10 17:42:56 -07002029 ALOGW("setEffectEnabled(true) CPU Load limit exceeded for Fx %s, CPU %f MIPS",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002030 effectDesc->mDesc.name, (float)effectDesc->mDesc.cpuLoad/10);
Eric Laurente552edb2014-03-10 17:42:56 -07002031 return INVALID_OPERATION;
2032 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002033 mTotalEffectsCpuLoad += effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07002034 ALOGV("setEffectEnabled(true) total CPU %d", mTotalEffectsCpuLoad);
2035 } else {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002036 if (mTotalEffectsCpuLoad < effectDesc->mDesc.cpuLoad) {
Eric Laurente552edb2014-03-10 17:42:56 -07002037 ALOGW("setEffectEnabled(false) CPU load %d too high for total %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002038 effectDesc->mDesc.cpuLoad, mTotalEffectsCpuLoad);
2039 effectDesc->mDesc.cpuLoad = mTotalEffectsCpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07002040 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002041 mTotalEffectsCpuLoad -= effectDesc->mDesc.cpuLoad;
Eric Laurente552edb2014-03-10 17:42:56 -07002042 ALOGV("setEffectEnabled(false) total CPU %d", mTotalEffectsCpuLoad);
2043 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002044 effectDesc->mEnabled = enabled;
Eric Laurente552edb2014-03-10 17:42:56 -07002045 return NO_ERROR;
2046}
2047
Eric Laurente0720872014-03-11 09:30:41 -07002048bool AudioPolicyManager::isNonOffloadableEffectEnabled()
Eric Laurente552edb2014-03-10 17:42:56 -07002049{
2050 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002051 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
2052 if (effectDesc->mEnabled && (effectDesc->mStrategy == STRATEGY_MEDIA) &&
2053 ((effectDesc->mDesc.flags & EFFECT_FLAG_OFFLOAD_SUPPORTED) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002054 ALOGV("isNonOffloadableEffectEnabled() non offloadable effect %s enabled on session %d",
Eric Laurent1f2f2232014-06-02 12:01:23 -07002055 effectDesc->mDesc.name, effectDesc->mSession);
Eric Laurente552edb2014-03-10 17:42:56 -07002056 return true;
2057 }
2058 }
2059 return false;
2060}
2061
Eric Laurente0720872014-03-11 09:30:41 -07002062bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07002063{
2064 nsecs_t sysTime = systemTime();
2065 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002066 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurent3b73df72014-03-11 09:06:29 -07002067 if (outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07002068 return true;
2069 }
2070 }
2071 return false;
2072}
2073
Eric Laurente0720872014-03-11 09:30:41 -07002074bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07002075 uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07002076{
2077 nsecs_t sysTime = systemTime();
2078 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002079 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002080 if (((outputDesc->device() & APM_AUDIO_OUT_DEVICE_REMOTE_ALL) != 0) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07002081 outputDesc->isStreamActive(stream, inPastMs, sysTime)) {
Eric Laurentc722f302014-12-10 11:21:49 -08002082 // do not consider re routing (when the output is going to a dynamic policy)
2083 // as "remote playback"
2084 if (outputDesc->mPolicyMix == NULL) {
Jean-Michel Trivi1767df72014-12-09 18:11:49 -08002085 return true;
2086 }
Eric Laurente552edb2014-03-10 17:42:56 -07002087 }
2088 }
2089 return false;
2090}
2091
Eric Laurente0720872014-03-11 09:30:41 -07002092bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07002093{
2094 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002095 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurenta34c9ce2014-12-19 11:16:32 -08002096 if (inputDescriptor->mRefCount == 0) {
2097 continue;
2098 }
2099 if (inputDescriptor->mInputSource == (int)source) {
Eric Laurente552edb2014-03-10 17:42:56 -07002100 return true;
2101 }
Eric Laurenta34c9ce2014-12-19 11:16:32 -08002102 // AUDIO_SOURCE_HOTWORD is equivalent to AUDIO_SOURCE_VOICE_RECOGNITION only if it
2103 // corresponds to an active capture triggered by a hardware hotword recognition
2104 if ((source == AUDIO_SOURCE_VOICE_RECOGNITION) &&
2105 (inputDescriptor->mInputSource == AUDIO_SOURCE_HOTWORD)) {
2106 // FIXME: we should not assume that the first session is the active one and keep
2107 // activity count per session. Same in startInput().
2108 ssize_t index = mSoundTriggerSessions.indexOfKey(inputDescriptor->mSessions.itemAt(0));
2109 if (index >= 0) {
2110 return true;
2111 }
2112 }
Eric Laurente552edb2014-03-10 17:42:56 -07002113 }
2114 return false;
2115}
2116
Eric Laurent275e8e92014-11-30 15:14:47 -08002117// Register a list of custom mixes with their attributes and format.
2118// When a mix is registered, corresponding input and output profiles are
2119// added to the remote submix hw module. The profile contains only the
2120// parameters (sampling rate, format...) specified by the mix.
2121// The corresponding input remote submix device is also connected.
2122//
2123// When a remote submix device is connected, the address is checked to select the
2124// appropriate profile and the corresponding input or output stream is opened.
2125//
2126// When capture starts, getInputForAttr() will:
2127// - 1 look for a mix matching the address passed in attribtutes tags if any
2128// - 2 if none found, getDeviceForInputSource() will:
2129// - 2.1 look for a mix matching the attributes source
2130// - 2.2 if none found, default to device selection by policy rules
2131// At this time, the corresponding output remote submix device is also connected
2132// and active playback use cases can be transferred to this mix if needed when reconnecting
2133// after AudioTracks are invalidated
2134//
2135// When playback starts, getOutputForAttr() will:
2136// - 1 look for a mix matching the address passed in attribtutes tags if any
2137// - 2 if none found, look for a mix matching the attributes usage
2138// - 3 if none found, default to device and output selection by policy rules.
2139
2140status_t AudioPolicyManager::registerPolicyMixes(Vector<AudioMix> mixes)
2141{
2142 sp<HwModule> module;
2143 for (size_t i = 0; i < mHwModules.size(); i++) {
2144 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2145 mHwModules[i]->mHandle != 0) {
2146 module = mHwModules[i];
2147 break;
2148 }
2149 }
2150
2151 if (module == 0) {
2152 return INVALID_OPERATION;
2153 }
2154
2155 ALOGV("registerPolicyMixes() num mixes %d", mixes.size());
2156
2157 for (size_t i = 0; i < mixes.size(); i++) {
2158 String8 address = mixes[i].mRegistrationId;
2159 ssize_t index = mPolicyMixes.indexOfKey(address);
2160 if (index >= 0) {
2161 ALOGE("registerPolicyMixes(): mix for address %s already registered", address.string());
2162 continue;
2163 }
2164 audio_config_t outputConfig = mixes[i].mFormat;
2165 audio_config_t inputConfig = mixes[i].mFormat;
2166 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL in
2167 // stereo and let audio flinger do the channel conversion if needed.
2168 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
2169 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
2170 module->addOutputProfile(address, &outputConfig,
2171 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
2172 module->addInputProfile(address, &inputConfig,
2173 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
2174 sp<AudioPolicyMix> policyMix = new AudioPolicyMix();
2175 policyMix->mMix = mixes[i];
2176 mPolicyMixes.add(address, policyMix);
Eric Laurentc722f302014-12-10 11:21:49 -08002177 if (mixes[i].mMixType == MIX_TYPE_PLAYERS) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002178 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002179 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2180 address.string());
2181 } else {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002182 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002183 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2184 address.string());
2185 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002186 }
2187 return NO_ERROR;
2188}
2189
2190status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
2191{
2192 sp<HwModule> module;
2193 for (size_t i = 0; i < mHwModules.size(); i++) {
2194 if (strcmp(AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX, mHwModules[i]->mName) == 0 &&
2195 mHwModules[i]->mHandle != 0) {
2196 module = mHwModules[i];
2197 break;
2198 }
2199 }
2200
2201 if (module == 0) {
2202 return INVALID_OPERATION;
2203 }
2204
2205 ALOGV("unregisterPolicyMixes() num mixes %d", mixes.size());
2206
2207 for (size_t i = 0; i < mixes.size(); i++) {
2208 String8 address = mixes[i].mRegistrationId;
2209 ssize_t index = mPolicyMixes.indexOfKey(address);
2210 if (index < 0) {
2211 ALOGE("unregisterPolicyMixes(): mix for address %s not registered", address.string());
2212 continue;
2213 }
2214
2215 mPolicyMixes.removeItemsAt(index);
2216
Eric Laurentc722f302014-12-10 11:21:49 -08002217 if (getDeviceConnectionState(AUDIO_DEVICE_IN_REMOTE_SUBMIX, address.string()) ==
2218 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2219 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002220 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
Eric Laurentc722f302014-12-10 11:21:49 -08002221 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2222 address.string());
2223 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002224
2225 if (getDeviceConnectionState(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address.string()) ==
2226 AUDIO_POLICY_DEVICE_STATE_AVAILABLE)
2227 {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002228 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
Eric Laurent275e8e92014-11-30 15:14:47 -08002229 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
2230 address.string());
2231 }
2232 module->removeOutputProfile(address);
2233 module->removeInputProfile(address);
2234 }
2235 return NO_ERROR;
2236}
2237
Eric Laurente552edb2014-03-10 17:42:56 -07002238
Eric Laurente0720872014-03-11 09:30:41 -07002239status_t AudioPolicyManager::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07002240{
2241 const size_t SIZE = 256;
2242 char buffer[SIZE];
2243 String8 result;
2244
2245 snprintf(buffer, SIZE, "\nAudioPolicyManager Dump: %p\n", this);
2246 result.append(buffer);
2247
2248 snprintf(buffer, SIZE, " Primary Output: %d\n", mPrimaryOutput);
2249 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002250 snprintf(buffer, SIZE, " Phone state: %d\n", mPhoneState);
2251 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002252 snprintf(buffer, SIZE, " Force use for communications %d\n",
2253 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07002254 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002255 snprintf(buffer, SIZE, " Force use for media %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA]);
Eric Laurente552edb2014-03-10 17:42:56 -07002256 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002257 snprintf(buffer, SIZE, " Force use for record %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD]);
Eric Laurente552edb2014-03-10 17:42:56 -07002258 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002259 snprintf(buffer, SIZE, " Force use for dock %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK]);
Eric Laurente552edb2014-03-10 17:42:56 -07002260 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07002261 snprintf(buffer, SIZE, " Force use for system %d\n", mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM]);
Eric Laurente552edb2014-03-10 17:42:56 -07002262 result.append(buffer);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09002263 snprintf(buffer, SIZE, " Force use for hdmi system audio %d\n",
2264 mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO]);
2265 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07002266
Eric Laurent3a4311c2014-03-17 12:00:47 -07002267 snprintf(buffer, SIZE, " Available output devices:\n");
2268 result.append(buffer);
2269 write(fd, result.string(), result.size());
Eric Laurent3a4311c2014-03-17 12:00:47 -07002270 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002271 mAvailableOutputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002272 }
2273 snprintf(buffer, SIZE, "\n Available input devices:\n");
2274 write(fd, buffer, strlen(buffer));
Eric Laurent3a4311c2014-03-17 12:00:47 -07002275 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07002276 mAvailableInputDevices[i]->dump(fd, 2, i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07002277 }
Eric Laurente552edb2014-03-10 17:42:56 -07002278
2279 snprintf(buffer, SIZE, "\nHW Modules dump:\n");
2280 write(fd, buffer, strlen(buffer));
2281 for (size_t i = 0; i < mHwModules.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002282 snprintf(buffer, SIZE, "- HW Module %zu:\n", i + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07002283 write(fd, buffer, strlen(buffer));
2284 mHwModules[i]->dump(fd);
2285 }
2286
2287 snprintf(buffer, SIZE, "\nOutputs dump:\n");
2288 write(fd, buffer, strlen(buffer));
2289 for (size_t i = 0; i < mOutputs.size(); i++) {
2290 snprintf(buffer, SIZE, "- Output %d dump:\n", mOutputs.keyAt(i));
2291 write(fd, buffer, strlen(buffer));
2292 mOutputs.valueAt(i)->dump(fd);
2293 }
2294
2295 snprintf(buffer, SIZE, "\nInputs dump:\n");
2296 write(fd, buffer, strlen(buffer));
2297 for (size_t i = 0; i < mInputs.size(); i++) {
2298 snprintf(buffer, SIZE, "- Input %d dump:\n", mInputs.keyAt(i));
2299 write(fd, buffer, strlen(buffer));
2300 mInputs.valueAt(i)->dump(fd);
2301 }
2302
2303 snprintf(buffer, SIZE, "\nStreams dump:\n");
2304 write(fd, buffer, strlen(buffer));
2305 snprintf(buffer, SIZE,
2306 " Stream Can be muted Index Min Index Max Index Cur [device : index]...\n");
2307 write(fd, buffer, strlen(buffer));
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002308 for (size_t i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07002309 snprintf(buffer, SIZE, " %02zu ", i);
Eric Laurente552edb2014-03-10 17:42:56 -07002310 write(fd, buffer, strlen(buffer));
2311 mStreams[i].dump(fd);
2312 }
2313
2314 snprintf(buffer, SIZE, "\nTotal Effects CPU: %f MIPS, Total Effects memory: %d KB\n",
2315 (float)mTotalEffectsCpuLoad/10, mTotalEffectsMemory);
2316 write(fd, buffer, strlen(buffer));
2317
2318 snprintf(buffer, SIZE, "Registered effects:\n");
2319 write(fd, buffer, strlen(buffer));
2320 for (size_t i = 0; i < mEffects.size(); i++) {
2321 snprintf(buffer, SIZE, "- Effect %d dump:\n", mEffects.keyAt(i));
2322 write(fd, buffer, strlen(buffer));
2323 mEffects.valueAt(i)->dump(fd);
2324 }
2325
Eric Laurent4d416952014-08-10 14:07:09 -07002326 snprintf(buffer, SIZE, "\nAudio Patches:\n");
2327 write(fd, buffer, strlen(buffer));
2328 for (size_t i = 0; i < mAudioPatches.size(); i++) {
2329 mAudioPatches[i]->dump(fd, 2, i);
2330 }
Eric Laurente552edb2014-03-10 17:42:56 -07002331
2332 return NO_ERROR;
2333}
2334
2335// This function checks for the parameters which can be offloaded.
2336// This can be enhanced depending on the capability of the DSP and policy
2337// of the system.
Eric Laurente0720872014-03-11 09:30:41 -07002338bool AudioPolicyManager::isOffloadSupported(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07002339{
2340 ALOGV("isOffloadSupported: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07002341 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurente552edb2014-03-10 17:42:56 -07002342 offloadInfo.sample_rate, offloadInfo.channel_mask,
2343 offloadInfo.format,
2344 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
2345 offloadInfo.has_video);
2346
2347 // Check if offload has been disabled
2348 char propValue[PROPERTY_VALUE_MAX];
2349 if (property_get("audio.offload.disable", propValue, "0")) {
2350 if (atoi(propValue) != 0) {
2351 ALOGV("offload disabled by audio.offload.disable=%s", propValue );
2352 return false;
2353 }
2354 }
2355
2356 // Check if stream type is music, then only allow offload as of now.
2357 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
2358 {
2359 ALOGV("isOffloadSupported: stream_type != MUSIC, returning false");
2360 return false;
2361 }
2362
2363 //TODO: enable audio offloading with video when ready
2364 if (offloadInfo.has_video)
2365 {
2366 ALOGV("isOffloadSupported: has_video == true, returning false");
2367 return false;
2368 }
2369
2370 //If duration is less than minimum value defined in property, return false
2371 if (property_get("audio.offload.min.duration.secs", propValue, NULL)) {
2372 if (offloadInfo.duration_us < (atoi(propValue) * 1000000 )) {
2373 ALOGV("Offload denied by duration < audio.offload.min.duration.secs(=%s)", propValue);
2374 return false;
2375 }
2376 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
2377 ALOGV("Offload denied by duration < default min(=%u)", OFFLOAD_DEFAULT_MIN_DURATION_SECS);
2378 return false;
2379 }
2380
2381 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
2382 // creating an offloaded track and tearing it down immediately after start when audioflinger
2383 // detects there is an active non offloadable effect.
2384 // FIXME: We should check the audio session here but we do not have it in this context.
2385 // This may prevent offloading in rare situations where effects are left active by apps
2386 // in the background.
2387 if (isNonOffloadableEffectEnabled()) {
2388 return false;
2389 }
2390
2391 // See if there is a profile to support this.
2392 // AUDIO_DEVICE_NONE
Eric Laurent1c333e22014-05-20 10:48:17 -07002393 sp<IOProfile> profile = getProfileForDirectOutput(AUDIO_DEVICE_NONE /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07002394 offloadInfo.sample_rate,
2395 offloadInfo.format,
2396 offloadInfo.channel_mask,
2397 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD);
Eric Laurent1c333e22014-05-20 10:48:17 -07002398 ALOGV("isOffloadSupported() profile %sfound", profile != 0 ? "" : "NOT ");
2399 return (profile != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002400}
2401
Eric Laurent6a94d692014-05-20 11:18:06 -07002402status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
2403 audio_port_type_t type,
2404 unsigned int *num_ports,
2405 struct audio_port *ports,
2406 unsigned int *generation)
2407{
2408 if (num_ports == NULL || (*num_ports != 0 && ports == NULL) ||
2409 generation == NULL) {
2410 return BAD_VALUE;
2411 }
2412 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
2413 if (ports == NULL) {
2414 *num_ports = 0;
2415 }
2416
2417 size_t portsWritten = 0;
2418 size_t portsMax = *num_ports;
2419 *num_ports = 0;
2420 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
2421 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2422 for (size_t i = 0;
2423 i < mAvailableOutputDevices.size() && portsWritten < portsMax; i++) {
2424 mAvailableOutputDevices[i]->toAudioPort(&ports[portsWritten++]);
2425 }
2426 *num_ports += mAvailableOutputDevices.size();
2427 }
2428 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
2429 for (size_t i = 0;
2430 i < mAvailableInputDevices.size() && portsWritten < portsMax; i++) {
2431 mAvailableInputDevices[i]->toAudioPort(&ports[portsWritten++]);
2432 }
2433 *num_ports += mAvailableInputDevices.size();
2434 }
2435 }
2436 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
2437 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
2438 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
2439 mInputs[i]->toAudioPort(&ports[portsWritten++]);
2440 }
2441 *num_ports += mInputs.size();
2442 }
2443 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07002444 size_t numOutputs = 0;
2445 for (size_t i = 0; i < mOutputs.size(); i++) {
2446 if (!mOutputs[i]->isDuplicated()) {
2447 numOutputs++;
2448 if (portsWritten < portsMax) {
2449 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
2450 }
2451 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002452 }
Eric Laurent84c70242014-06-23 08:46:27 -07002453 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07002454 }
2455 }
2456 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002457 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07002458 return NO_ERROR;
2459}
2460
2461status_t AudioPolicyManager::getAudioPort(struct audio_port *port __unused)
2462{
2463 return NO_ERROR;
2464}
2465
Eric Laurent1f2f2232014-06-02 12:01:23 -07002466sp<AudioPolicyManager::AudioOutputDescriptor> AudioPolicyManager::getOutputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002467 audio_port_handle_t id) const
2468{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002469 sp<AudioOutputDescriptor> outputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002470 for (size_t i = 0; i < mOutputs.size(); i++) {
2471 outputDesc = mOutputs.valueAt(i);
2472 if (outputDesc->mId == id) {
2473 break;
2474 }
2475 }
2476 return outputDesc;
2477}
2478
Eric Laurent1f2f2232014-06-02 12:01:23 -07002479sp<AudioPolicyManager::AudioInputDescriptor> AudioPolicyManager::getInputFromId(
Eric Laurent6a94d692014-05-20 11:18:06 -07002480 audio_port_handle_t id) const
2481{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002482 sp<AudioInputDescriptor> inputDesc = NULL;
Eric Laurent6a94d692014-05-20 11:18:06 -07002483 for (size_t i = 0; i < mInputs.size(); i++) {
2484 inputDesc = mInputs.valueAt(i);
2485 if (inputDesc->mId == id) {
2486 break;
2487 }
2488 }
2489 return inputDesc;
2490}
2491
Eric Laurent1f2f2232014-06-02 12:01:23 -07002492sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleForDevice(
2493 audio_devices_t device) const
Eric Laurent6a94d692014-05-20 11:18:06 -07002494{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002495 sp <HwModule> module;
2496
Eric Laurent6a94d692014-05-20 11:18:06 -07002497 for (size_t i = 0; i < mHwModules.size(); i++) {
2498 if (mHwModules[i]->mHandle == 0) {
2499 continue;
2500 }
2501 if (audio_is_output_device(device)) {
2502 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
2503 {
2504 if (mHwModules[i]->mOutputProfiles[j]->mSupportedDevices.types() & device) {
2505 return mHwModules[i];
2506 }
2507 }
2508 } else {
2509 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++) {
2510 if (mHwModules[i]->mInputProfiles[j]->mSupportedDevices.types() &
2511 device & ~AUDIO_DEVICE_BIT_IN) {
2512 return mHwModules[i];
2513 }
2514 }
2515 }
2516 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002517 return module;
Eric Laurent6a94d692014-05-20 11:18:06 -07002518}
2519
Eric Laurent1f2f2232014-06-02 12:01:23 -07002520sp <AudioPolicyManager::HwModule> AudioPolicyManager::getModuleFromName(const char *name) const
Eric Laurent1afeecb2014-05-14 08:52:28 -07002521{
Eric Laurent1f2f2232014-06-02 12:01:23 -07002522 sp <HwModule> module;
2523
Eric Laurent1afeecb2014-05-14 08:52:28 -07002524 for (size_t i = 0; i < mHwModules.size(); i++)
2525 {
2526 if (strcmp(mHwModules[i]->mName, name) == 0) {
2527 return mHwModules[i];
2528 }
2529 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002530 return module;
Eric Laurent1afeecb2014-05-14 08:52:28 -07002531}
2532
Eric Laurentc2730ba2014-07-20 15:47:07 -07002533audio_devices_t AudioPolicyManager::availablePrimaryOutputDevices()
2534{
2535 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
2536 audio_devices_t devices = outputDesc->mProfile->mSupportedDevices.types();
2537 return devices & mAvailableOutputDevices.types();
2538}
2539
2540audio_devices_t AudioPolicyManager::availablePrimaryInputDevices()
2541{
2542 audio_module_handle_t primaryHandle =
2543 mOutputs.valueFor(mPrimaryOutput)->mProfile->mModule->mHandle;
2544 audio_devices_t devices = AUDIO_DEVICE_NONE;
2545 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
2546 if (mAvailableInputDevices[i]->mModule->mHandle == primaryHandle) {
2547 devices |= mAvailableInputDevices[i]->mDeviceType;
2548 }
2549 }
2550 return devices;
2551}
Eric Laurent1afeecb2014-05-14 08:52:28 -07002552
Eric Laurent6a94d692014-05-20 11:18:06 -07002553status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
2554 audio_patch_handle_t *handle,
2555 uid_t uid)
2556{
2557 ALOGV("createAudioPatch()");
2558
2559 if (handle == NULL || patch == NULL) {
2560 return BAD_VALUE;
2561 }
2562 ALOGV("createAudioPatch() num sources %d num sinks %d", patch->num_sources, patch->num_sinks);
2563
Eric Laurent874c42872014-08-08 15:13:39 -07002564 if (patch->num_sources == 0 || patch->num_sources > AUDIO_PATCH_PORTS_MAX ||
2565 patch->num_sinks == 0 || patch->num_sinks > AUDIO_PATCH_PORTS_MAX) {
2566 return BAD_VALUE;
2567 }
2568 // only one source per audio patch supported for now
2569 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002570 return INVALID_OPERATION;
2571 }
Eric Laurent874c42872014-08-08 15:13:39 -07002572
2573 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002574 return INVALID_OPERATION;
2575 }
Eric Laurent874c42872014-08-08 15:13:39 -07002576 for (size_t i = 0; i < patch->num_sinks; i++) {
2577 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
2578 return INVALID_OPERATION;
2579 }
2580 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002581
2582 sp<AudioPatch> patchDesc;
2583 ssize_t index = mAudioPatches.indexOfKey(*handle);
2584
Eric Laurent6a94d692014-05-20 11:18:06 -07002585 ALOGV("createAudioPatch source id %d role %d type %d", patch->sources[0].id,
2586 patch->sources[0].role,
2587 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07002588#if LOG_NDEBUG == 0
2589 for (size_t i = 0; i < patch->num_sinks; i++) {
2590 ALOGV("createAudioPatch sink %d: id %d role %d type %d", i, patch->sinks[i].id,
2591 patch->sinks[i].role,
2592 patch->sinks[i].type);
2593 }
2594#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07002595
2596 if (index >= 0) {
2597 patchDesc = mAudioPatches.valueAt(index);
2598 ALOGV("createAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2599 mUidCached, patchDesc->mUid, uid);
2600 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2601 return INVALID_OPERATION;
2602 }
2603 } else {
2604 *handle = 0;
2605 }
2606
2607 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002608 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002609 if (outputDesc == NULL) {
2610 ALOGV("createAudioPatch() output not found for id %d", patch->sources[0].id);
2611 return BAD_VALUE;
2612 }
Eric Laurent84c70242014-06-23 08:46:27 -07002613 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
2614 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002615 if (patchDesc != 0) {
2616 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
2617 ALOGV("createAudioPatch() source id differs for patch current id %d new id %d",
2618 patchDesc->mPatch.sources[0].id, patch->sources[0].id);
2619 return BAD_VALUE;
2620 }
2621 }
Eric Laurent874c42872014-08-08 15:13:39 -07002622 DeviceVector devices;
2623 for (size_t i = 0; i < patch->num_sinks; i++) {
2624 // Only support mix to devices connection
2625 // TODO add support for mix to mix connection
2626 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2627 ALOGV("createAudioPatch() source mix but sink is not a device");
2628 return INVALID_OPERATION;
2629 }
2630 sp<DeviceDescriptor> devDesc =
2631 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2632 if (devDesc == 0) {
2633 ALOGV("createAudioPatch() out device not found for id %d", patch->sinks[i].id);
2634 return BAD_VALUE;
2635 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002636
Eric Laurent874c42872014-08-08 15:13:39 -07002637 if (!outputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002638 devDesc->mAddress,
Eric Laurent874c42872014-08-08 15:13:39 -07002639 patch->sources[0].sample_rate,
2640 NULL, // updatedSamplingRate
2641 patch->sources[0].format,
2642 patch->sources[0].channel_mask,
2643 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
2644 ALOGV("createAudioPatch() profile not supported for device %08x",
2645 devDesc->mDeviceType);
2646 return INVALID_OPERATION;
2647 }
2648 devices.add(devDesc);
2649 }
2650 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002651 return INVALID_OPERATION;
2652 }
Eric Laurent874c42872014-08-08 15:13:39 -07002653
Eric Laurent6a94d692014-05-20 11:18:06 -07002654 // TODO: reconfigure output format and channels here
2655 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent874c42872014-08-08 15:13:39 -07002656 devices.types(), outputDesc->mIoHandle);
2657 setOutputDevice(outputDesc->mIoHandle, devices.types(), true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002658 index = mAudioPatches.indexOfKey(*handle);
2659 if (index >= 0) {
2660 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2661 ALOGW("createAudioPatch() setOutputDevice() did not reuse the patch provided");
2662 }
2663 patchDesc = mAudioPatches.valueAt(index);
2664 patchDesc->mUid = uid;
2665 ALOGV("createAudioPatch() success");
2666 } else {
2667 ALOGW("createAudioPatch() setOutputDevice() failed to create a patch");
2668 return INVALID_OPERATION;
2669 }
2670 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2671 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
2672 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07002673 // only one sink supported when connecting an input device to a mix
2674 if (patch->num_sinks > 1) {
2675 return INVALID_OPERATION;
2676 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07002677 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002678 if (inputDesc == NULL) {
2679 return BAD_VALUE;
2680 }
2681 if (patchDesc != 0) {
2682 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
2683 return BAD_VALUE;
2684 }
2685 }
2686 sp<DeviceDescriptor> devDesc =
2687 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
2688 if (devDesc == 0) {
2689 return BAD_VALUE;
2690 }
2691
Eric Laurent84c70242014-06-23 08:46:27 -07002692 if (!inputDesc->mProfile->isCompatibleProfile(devDesc->mDeviceType,
Eric Laurent275e8e92014-11-30 15:14:47 -08002693 devDesc->mAddress,
2694 patch->sinks[0].sample_rate,
2695 NULL, /*updatedSampleRate*/
2696 patch->sinks[0].format,
2697 patch->sinks[0].channel_mask,
2698 // FIXME for the parameter type,
2699 // and the NONE
2700 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002701 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002702 return INVALID_OPERATION;
2703 }
2704 // TODO: reconfigure output format and channels here
2705 ALOGV("createAudioPatch() setting device %08x on output %d",
Eric Laurent84c70242014-06-23 08:46:27 -07002706 devDesc->mDeviceType, inputDesc->mIoHandle);
Eric Laurent874c42872014-08-08 15:13:39 -07002707 setInputDevice(inputDesc->mIoHandle, devDesc->mDeviceType, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07002708 index = mAudioPatches.indexOfKey(*handle);
2709 if (index >= 0) {
2710 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
2711 ALOGW("createAudioPatch() setInputDevice() did not reuse the patch provided");
2712 }
2713 patchDesc = mAudioPatches.valueAt(index);
2714 patchDesc->mUid = uid;
2715 ALOGV("createAudioPatch() success");
2716 } else {
2717 ALOGW("createAudioPatch() setInputDevice() failed to create a patch");
2718 return INVALID_OPERATION;
2719 }
2720 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2721 // device to device connection
2722 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07002723 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002724 return BAD_VALUE;
2725 }
2726 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002727 sp<DeviceDescriptor> srcDeviceDesc =
2728 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
Eric Laurent58f8eb72014-09-12 16:19:41 -07002729 if (srcDeviceDesc == 0) {
2730 return BAD_VALUE;
2731 }
Eric Laurent874c42872014-08-08 15:13:39 -07002732
Eric Laurent6a94d692014-05-20 11:18:06 -07002733 //update source and sink with our own data as the data passed in the patch may
2734 // be incomplete.
2735 struct audio_patch newPatch = *patch;
2736 srcDeviceDesc->toAudioPortConfig(&newPatch.sources[0], &patch->sources[0]);
Eric Laurent6a94d692014-05-20 11:18:06 -07002737
Eric Laurent874c42872014-08-08 15:13:39 -07002738 for (size_t i = 0; i < patch->num_sinks; i++) {
2739 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
2740 ALOGV("createAudioPatch() source device but one sink is not a device");
2741 return INVALID_OPERATION;
2742 }
2743
2744 sp<DeviceDescriptor> sinkDeviceDesc =
2745 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
2746 if (sinkDeviceDesc == 0) {
2747 return BAD_VALUE;
2748 }
2749 sinkDeviceDesc->toAudioPortConfig(&newPatch.sinks[i], &patch->sinks[i]);
2750
2751 if (srcDeviceDesc->mModule != sinkDeviceDesc->mModule) {
2752 // only one sink supported when connected devices across HW modules
2753 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07002754 return INVALID_OPERATION;
2755 }
Eric Laurent874c42872014-08-08 15:13:39 -07002756 SortedVector<audio_io_handle_t> outputs =
2757 getOutputsForDevice(sinkDeviceDesc->mDeviceType,
2758 mOutputs);
2759 // if the sink device is reachable via an opened output stream, request to go via
2760 // this output stream by adding a second source to the patch description
Eric Laurent8838a382014-09-08 16:44:28 -07002761 audio_io_handle_t output = selectOutput(outputs,
2762 AUDIO_OUTPUT_FLAG_NONE,
2763 AUDIO_FORMAT_INVALID);
Eric Laurent874c42872014-08-08 15:13:39 -07002764 if (output != AUDIO_IO_HANDLE_NONE) {
2765 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
2766 if (outputDesc->isDuplicated()) {
2767 return INVALID_OPERATION;
2768 }
2769 outputDesc->toAudioPortConfig(&newPatch.sources[1], &patch->sources[0]);
2770 newPatch.num_sources = 2;
2771 }
Eric Laurent83b88082014-06-20 18:31:16 -07002772 }
Eric Laurent6a94d692014-05-20 11:18:06 -07002773 }
2774 // TODO: check from routing capabilities in config file and other conflicting patches
2775
2776 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
2777 if (index >= 0) {
2778 afPatchHandle = patchDesc->mAfPatchHandle;
2779 }
2780
2781 status_t status = mpClientInterface->createAudioPatch(&newPatch,
2782 &afPatchHandle,
2783 0);
2784 ALOGV("createAudioPatch() patch panel returned %d patchHandle %d",
2785 status, afPatchHandle);
2786 if (status == NO_ERROR) {
2787 if (index < 0) {
2788 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
2789 &newPatch, uid);
2790 addAudioPatch(patchDesc->mHandle, patchDesc);
2791 } else {
2792 patchDesc->mPatch = newPatch;
2793 }
2794 patchDesc->mAfPatchHandle = afPatchHandle;
2795 *handle = patchDesc->mHandle;
2796 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002797 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002798 } else {
2799 ALOGW("createAudioPatch() patch panel could not connect device patch, error %d",
2800 status);
2801 return INVALID_OPERATION;
2802 }
2803 } else {
2804 return BAD_VALUE;
2805 }
2806 } else {
2807 return BAD_VALUE;
2808 }
2809 return NO_ERROR;
2810}
2811
2812status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
2813 uid_t uid)
2814{
2815 ALOGV("releaseAudioPatch() patch %d", handle);
2816
2817 ssize_t index = mAudioPatches.indexOfKey(handle);
2818
2819 if (index < 0) {
2820 return BAD_VALUE;
2821 }
2822 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
2823 ALOGV("releaseAudioPatch() mUidCached %d patchDesc->mUid %d uid %d",
2824 mUidCached, patchDesc->mUid, uid);
2825 if (patchDesc->mUid != mUidCached && uid != patchDesc->mUid) {
2826 return INVALID_OPERATION;
2827 }
2828
2829 struct audio_patch *patch = &patchDesc->mPatch;
2830 patchDesc->mUid = mUidCached;
2831 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002832 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002833 if (outputDesc == NULL) {
2834 ALOGV("releaseAudioPatch() output not found for id %d", patch->sources[0].id);
2835 return BAD_VALUE;
2836 }
2837
2838 setOutputDevice(outputDesc->mIoHandle,
2839 getNewOutputDevice(outputDesc->mIoHandle, true /*fromCache*/),
2840 true,
2841 0,
2842 NULL);
2843 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
2844 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002845 sp<AudioInputDescriptor> inputDesc = getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07002846 if (inputDesc == NULL) {
2847 ALOGV("releaseAudioPatch() input not found for id %d", patch->sinks[0].id);
2848 return BAD_VALUE;
2849 }
2850 setInputDevice(inputDesc->mIoHandle,
2851 getNewInputDevice(inputDesc->mIoHandle),
2852 true,
2853 NULL);
2854 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
2855 audio_patch_handle_t afPatchHandle = patchDesc->mAfPatchHandle;
2856 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
2857 ALOGV("releaseAudioPatch() patch panel returned %d patchHandle %d",
2858 status, patchDesc->mAfPatchHandle);
2859 removeAudioPatch(patchDesc->mHandle);
2860 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07002861 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent6a94d692014-05-20 11:18:06 -07002862 } else {
2863 return BAD_VALUE;
2864 }
2865 } else {
2866 return BAD_VALUE;
2867 }
2868 return NO_ERROR;
2869}
2870
2871status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
2872 struct audio_patch *patches,
2873 unsigned int *generation)
2874{
2875 if (num_patches == NULL || (*num_patches != 0 && patches == NULL) ||
2876 generation == NULL) {
2877 return BAD_VALUE;
2878 }
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002879 ALOGV("listAudioPatches() num_patches %d patches %p available patches %zu",
Eric Laurent6a94d692014-05-20 11:18:06 -07002880 *num_patches, patches, mAudioPatches.size());
2881 if (patches == NULL) {
2882 *num_patches = 0;
2883 }
2884
2885 size_t patchesWritten = 0;
2886 size_t patchesMax = *num_patches;
2887 for (size_t i = 0;
2888 i < mAudioPatches.size() && patchesWritten < patchesMax; i++) {
2889 patches[patchesWritten] = mAudioPatches[i]->mPatch;
2890 patches[patchesWritten++].id = mAudioPatches[i]->mHandle;
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002891 ALOGV("listAudioPatches() patch %zu num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07002892 i, mAudioPatches[i]->mPatch.num_sources, mAudioPatches[i]->mPatch.num_sinks);
2893 }
2894 *num_patches = mAudioPatches.size();
2895
2896 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07002897 ALOGV("listAudioPatches() got %zu patches needed %d", patchesWritten, *num_patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07002898 return NO_ERROR;
2899}
2900
Eric Laurente1715a42014-05-20 11:30:42 -07002901status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07002902{
Eric Laurente1715a42014-05-20 11:30:42 -07002903 ALOGV("setAudioPortConfig()");
2904
2905 if (config == NULL) {
2906 return BAD_VALUE;
2907 }
2908 ALOGV("setAudioPortConfig() on port handle %d", config->id);
2909 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07002910 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
2911 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07002912 }
2913
Eric Laurenta121f902014-06-03 13:32:54 -07002914 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07002915 if (config->type == AUDIO_PORT_TYPE_MIX) {
2916 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002917 sp<AudioOutputDescriptor> outputDesc = getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002918 if (outputDesc == NULL) {
2919 return BAD_VALUE;
2920 }
Eric Laurent84c70242014-06-23 08:46:27 -07002921 ALOG_ASSERT(!outputDesc->isDuplicated(),
2922 "setAudioPortConfig() called on duplicated output %d",
2923 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07002924 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002925 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07002926 sp<AudioInputDescriptor> inputDesc = getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07002927 if (inputDesc == NULL) {
2928 return BAD_VALUE;
2929 }
Eric Laurenta121f902014-06-03 13:32:54 -07002930 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002931 } else {
2932 return BAD_VALUE;
2933 }
2934 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
2935 sp<DeviceDescriptor> deviceDesc;
2936 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
2937 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
2938 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
2939 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
2940 } else {
2941 return BAD_VALUE;
2942 }
2943 if (deviceDesc == NULL) {
2944 return BAD_VALUE;
2945 }
Eric Laurenta121f902014-06-03 13:32:54 -07002946 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07002947 } else {
2948 return BAD_VALUE;
2949 }
2950
Eric Laurenta121f902014-06-03 13:32:54 -07002951 struct audio_port_config backupConfig;
2952 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
2953 if (status == NO_ERROR) {
2954 struct audio_port_config newConfig;
2955 audioPortConfig->toAudioPortConfig(&newConfig, config);
2956 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07002957 }
Eric Laurenta121f902014-06-03 13:32:54 -07002958 if (status != NO_ERROR) {
2959 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07002960 }
Eric Laurente1715a42014-05-20 11:30:42 -07002961
2962 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07002963}
2964
2965void AudioPolicyManager::clearAudioPatches(uid_t uid)
2966{
Eric Laurent0add0fd2014-12-04 18:58:14 -08002967 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07002968 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
2969 if (patchDesc->mUid == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08002970 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07002971 }
2972 }
2973}
2974
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002975status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
2976 audio_io_handle_t *ioHandle,
2977 audio_devices_t *device)
2978{
2979 *session = (audio_session_t)mpClientInterface->newAudioUniqueId();
2980 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId();
Eric Laurentc73ca6e2014-12-12 14:34:22 -08002981 *device = getDeviceAndMixForInputSource(AUDIO_SOURCE_HOTWORD);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002982
2983 mSoundTriggerSessions.add(*session, *ioHandle);
2984
2985 return NO_ERROR;
2986}
2987
2988status_t AudioPolicyManager::releaseSoundTriggerSession(audio_session_t session)
2989{
2990 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2991 if (index < 0) {
2992 ALOGW("acquireSoundTriggerSession() session %d not registered", session);
2993 return BAD_VALUE;
2994 }
2995
2996 mSoundTriggerSessions.removeItem(session);
2997 return NO_ERROR;
2998}
2999
Eric Laurent6a94d692014-05-20 11:18:06 -07003000status_t AudioPolicyManager::addAudioPatch(audio_patch_handle_t handle,
3001 const sp<AudioPatch>& patch)
3002{
3003 ssize_t index = mAudioPatches.indexOfKey(handle);
3004
3005 if (index >= 0) {
3006 ALOGW("addAudioPatch() patch %d already in", handle);
3007 return ALREADY_EXISTS;
3008 }
3009 mAudioPatches.add(handle, patch);
3010 ALOGV("addAudioPatch() handle %d af handle %d num_sources %d num_sinks %d source handle %d"
3011 "sink handle %d",
3012 handle, patch->mAfPatchHandle, patch->mPatch.num_sources, patch->mPatch.num_sinks,
3013 patch->mPatch.sources[0].id, patch->mPatch.sinks[0].id);
3014 return NO_ERROR;
3015}
3016
3017status_t AudioPolicyManager::removeAudioPatch(audio_patch_handle_t handle)
3018{
3019 ssize_t index = mAudioPatches.indexOfKey(handle);
3020
3021 if (index < 0) {
3022 ALOGW("removeAudioPatch() patch %d not in", handle);
3023 return ALREADY_EXISTS;
3024 }
3025 ALOGV("removeAudioPatch() handle %d af handle %d", handle,
3026 mAudioPatches.valueAt(index)->mAfPatchHandle);
3027 mAudioPatches.removeItemsAt(index);
3028 return NO_ERROR;
3029}
3030
Eric Laurente552edb2014-03-10 17:42:56 -07003031// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07003032// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07003033// ----------------------------------------------------------------------------
3034
Eric Laurent3a4311c2014-03-17 12:00:47 -07003035uint32_t AudioPolicyManager::nextUniqueId()
3036{
3037 return android_atomic_inc(&mNextUniqueId);
3038}
3039
Eric Laurent6a94d692014-05-20 11:18:06 -07003040uint32_t AudioPolicyManager::nextAudioPortGeneration()
3041{
3042 return android_atomic_inc(&mAudioPortGeneration);
3043}
3044
Eric Laurente0720872014-03-11 09:30:41 -07003045AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07003046 :
3047#ifdef AUDIO_POLICY_TEST
3048 Thread(false),
3049#endif //AUDIO_POLICY_TEST
3050 mPrimaryOutput((audio_io_handle_t)0),
Eric Laurent3b73df72014-03-11 09:06:29 -07003051 mPhoneState(AUDIO_MODE_NORMAL),
Eric Laurente552edb2014-03-10 17:42:56 -07003052 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
3053 mTotalEffectsCpuLoad(0), mTotalEffectsMemory(0),
Eric Laurent3a4311c2014-03-17 12:00:47 -07003054 mA2dpSuspended(false),
Eric Laurent6a94d692014-05-20 11:18:06 -07003055 mSpeakerDrcEnabled(false), mNextUniqueId(1),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07003056 mAudioPortGeneration(1),
3057 mBeaconMuteRefCount(0),
3058 mBeaconPlayingRefCount(0),
3059 mBeaconMuted(false)
Eric Laurente552edb2014-03-10 17:42:56 -07003060{
Eric Laurent6a94d692014-05-20 11:18:06 -07003061 mUidCached = getuid();
Eric Laurente552edb2014-03-10 17:42:56 -07003062 mpClientInterface = clientInterface;
3063
Eric Laurent3b73df72014-03-11 09:06:29 -07003064 for (int i = 0; i < AUDIO_POLICY_FORCE_USE_CNT; i++) {
3065 mForceUse[i] = AUDIO_POLICY_FORCE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003066 }
3067
Eric Laurent1afeecb2014-05-14 08:52:28 -07003068 mDefaultOutputDevice = new DeviceDescriptor(String8(""), AUDIO_DEVICE_OUT_SPEAKER);
Eric Laurente552edb2014-03-10 17:42:56 -07003069 if (loadAudioPolicyConfig(AUDIO_POLICY_VENDOR_CONFIG_FILE) != NO_ERROR) {
3070 if (loadAudioPolicyConfig(AUDIO_POLICY_CONFIG_FILE) != NO_ERROR) {
3071 ALOGE("could not load audio policy configuration file, setting defaults");
3072 defaultAudioPolicyConfig();
3073 }
3074 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003075 // mAvailableOutputDevices and mAvailableInputDevices now contain all attached devices
Eric Laurente552edb2014-03-10 17:42:56 -07003076
3077 // must be done after reading the policy
3078 initializeVolumeCurves();
3079
3080 // open all output streams needed to access attached devices
Eric Laurent3a4311c2014-03-17 12:00:47 -07003081 audio_devices_t outputDeviceTypes = mAvailableOutputDevices.types();
3082 audio_devices_t inputDeviceTypes = mAvailableInputDevices.types() & ~AUDIO_DEVICE_BIT_IN;
Eric Laurente552edb2014-03-10 17:42:56 -07003083 for (size_t i = 0; i < mHwModules.size(); i++) {
3084 mHwModules[i]->mHandle = mpClientInterface->loadHwModule(mHwModules[i]->mName);
3085 if (mHwModules[i]->mHandle == 0) {
3086 ALOGW("could not open HW module %s", mHwModules[i]->mName);
3087 continue;
3088 }
3089 // open all output streams needed to access attached devices
3090 // except for direct output streams that are only opened when they are actually
3091 // required by an app.
Eric Laurent3a4311c2014-03-17 12:00:47 -07003092 // This also validates mAvailableOutputDevices list
Eric Laurente552edb2014-03-10 17:42:56 -07003093 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3094 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003095 const sp<IOProfile> outProfile = mHwModules[i]->mOutputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003096
Eric Laurent3a4311c2014-03-17 12:00:47 -07003097 if (outProfile->mSupportedDevices.isEmpty()) {
3098 ALOGW("Output profile contains no device on module %s", mHwModules[i]->mName);
3099 continue;
3100 }
3101
Eric Laurentd78f1532014-09-16 16:38:20 -07003102 if ((outProfile->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
3103 continue;
3104 }
Eric Laurent83b88082014-06-20 18:31:16 -07003105 audio_devices_t profileType = outProfile->mSupportedDevices.types();
3106 if ((profileType & mDefaultOutputDevice->mDeviceType) != AUDIO_DEVICE_NONE) {
3107 profileType = mDefaultOutputDevice->mDeviceType;
3108 } else {
Eric Laurentd78f1532014-09-16 16:38:20 -07003109 // chose first device present in mSupportedDevices also part of
3110 // outputDeviceTypes
3111 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3112 profileType = outProfile->mSupportedDevices[k]->mDeviceType;
3113 if ((profileType & outputDeviceTypes) != 0) {
3114 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003115 }
Eric Laurente552edb2014-03-10 17:42:56 -07003116 }
3117 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003118 if ((profileType & outputDeviceTypes) == 0) {
3119 continue;
3120 }
3121 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(outProfile);
3122
3123 outputDesc->mDevice = profileType;
3124 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3125 config.sample_rate = outputDesc->mSamplingRate;
3126 config.channel_mask = outputDesc->mChannelMask;
3127 config.format = outputDesc->mFormat;
3128 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3129 status_t status = mpClientInterface->openOutput(outProfile->mModule->mHandle,
3130 &output,
3131 &config,
3132 &outputDesc->mDevice,
3133 String8(""),
3134 &outputDesc->mLatency,
3135 outputDesc->mFlags);
3136
3137 if (status != NO_ERROR) {
3138 ALOGW("Cannot open output stream for device %08x on hw module %s",
3139 outputDesc->mDevice,
3140 mHwModules[i]->mName);
3141 } else {
3142 outputDesc->mSamplingRate = config.sample_rate;
3143 outputDesc->mChannelMask = config.channel_mask;
3144 outputDesc->mFormat = config.format;
3145
3146 for (size_t k = 0; k < outProfile->mSupportedDevices.size(); k++) {
3147 audio_devices_t type = outProfile->mSupportedDevices[k]->mDeviceType;
3148 ssize_t index =
3149 mAvailableOutputDevices.indexOf(outProfile->mSupportedDevices[k]);
3150 // give a valid ID to an attached device once confirmed it is reachable
3151 if ((index >= 0) && (mAvailableOutputDevices[index]->mId == 0)) {
3152 mAvailableOutputDevices[index]->mId = nextUniqueId();
3153 mAvailableOutputDevices[index]->mModule = mHwModules[i];
3154 }
3155 }
3156 if (mPrimaryOutput == 0 &&
3157 outProfile->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) {
3158 mPrimaryOutput = output;
3159 }
3160 addOutput(output, outputDesc);
3161 setOutputDevice(output,
3162 outputDesc->mDevice,
3163 true);
3164 }
Eric Laurente552edb2014-03-10 17:42:56 -07003165 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003166 // open input streams needed to access attached devices to validate
3167 // mAvailableInputDevices list
3168 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
3169 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003170 const sp<IOProfile> inProfile = mHwModules[i]->mInputProfiles[j];
Eric Laurente552edb2014-03-10 17:42:56 -07003171
Eric Laurent3a4311c2014-03-17 12:00:47 -07003172 if (inProfile->mSupportedDevices.isEmpty()) {
3173 ALOGW("Input profile contains no device on module %s", mHwModules[i]->mName);
3174 continue;
3175 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003176 // chose first device present in mSupportedDevices also part of
3177 // inputDeviceTypes
3178 audio_devices_t profileType = AUDIO_DEVICE_NONE;
3179 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3180 profileType = inProfile->mSupportedDevices[k]->mDeviceType;
3181 if (profileType & inputDeviceTypes) {
3182 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07003183 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003184 }
Eric Laurentd78f1532014-09-16 16:38:20 -07003185 if ((profileType & inputDeviceTypes) == 0) {
3186 continue;
3187 }
3188 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(inProfile);
3189
3190 inputDesc->mInputSource = AUDIO_SOURCE_MIC;
3191 inputDesc->mDevice = profileType;
3192
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003193 // find the address
3194 DeviceVector inputDevices = mAvailableInputDevices.getDevicesFromType(profileType);
3195 // the inputs vector must be of size 1, but we don't want to crash here
3196 String8 address = inputDevices.size() > 0 ? inputDevices.itemAt(0)->mAddress
3197 : String8("");
3198 ALOGV(" for input device 0x%x using address %s", profileType, address.string());
3199 ALOGE_IF(inputDevices.size() == 0, "Input device list is empty!");
3200
Eric Laurentd78f1532014-09-16 16:38:20 -07003201 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3202 config.sample_rate = inputDesc->mSamplingRate;
3203 config.channel_mask = inputDesc->mChannelMask;
3204 config.format = inputDesc->mFormat;
3205 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3206 status_t status = mpClientInterface->openInput(inProfile->mModule->mHandle,
3207 &input,
3208 &config,
3209 &inputDesc->mDevice,
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07003210 address,
Eric Laurentd78f1532014-09-16 16:38:20 -07003211 AUDIO_SOURCE_MIC,
3212 AUDIO_INPUT_FLAG_NONE);
3213
3214 if (status == NO_ERROR) {
3215 for (size_t k = 0; k < inProfile->mSupportedDevices.size(); k++) {
3216 audio_devices_t type = inProfile->mSupportedDevices[k]->mDeviceType;
3217 ssize_t index =
3218 mAvailableInputDevices.indexOf(inProfile->mSupportedDevices[k]);
3219 // give a valid ID to an attached device once confirmed it is reachable
3220 if ((index >= 0) && (mAvailableInputDevices[index]->mId == 0)) {
3221 mAvailableInputDevices[index]->mId = nextUniqueId();
3222 mAvailableInputDevices[index]->mModule = mHwModules[i];
3223 }
3224 }
3225 mpClientInterface->closeInput(input);
3226 } else {
3227 ALOGW("Cannot open input stream for device %08x on hw module %s",
3228 inputDesc->mDevice,
3229 mHwModules[i]->mName);
3230 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003231 }
3232 }
3233 // make sure all attached devices have been allocated a unique ID
3234 for (size_t i = 0; i < mAvailableOutputDevices.size();) {
3235 if (mAvailableOutputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003236 ALOGW("Input device %08x unreachable", mAvailableOutputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003237 mAvailableOutputDevices.remove(mAvailableOutputDevices[i]);
3238 continue;
3239 }
3240 i++;
3241 }
3242 for (size_t i = 0; i < mAvailableInputDevices.size();) {
3243 if (mAvailableInputDevices[i]->mId == 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003244 ALOGW("Input device %08x unreachable", mAvailableInputDevices[i]->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003245 mAvailableInputDevices.remove(mAvailableInputDevices[i]);
3246 continue;
3247 }
3248 i++;
3249 }
3250 // make sure default device is reachable
3251 if (mAvailableOutputDevices.indexOf(mDefaultOutputDevice) < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003252 ALOGE("Default device %08x is unreachable", mDefaultOutputDevice->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003253 }
Eric Laurente552edb2014-03-10 17:42:56 -07003254
3255 ALOGE_IF((mPrimaryOutput == 0), "Failed to open primary output");
3256
3257 updateDevicesAndOutputs();
3258
3259#ifdef AUDIO_POLICY_TEST
3260 if (mPrimaryOutput != 0) {
3261 AudioParameter outputCmd = AudioParameter();
3262 outputCmd.addInt(String8("set_id"), 0);
3263 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3264
3265 mTestDevice = AUDIO_DEVICE_OUT_SPEAKER;
3266 mTestSamplingRate = 44100;
Eric Laurent3b73df72014-03-11 09:06:29 -07003267 mTestFormat = AUDIO_FORMAT_PCM_16_BIT;
3268 mTestChannels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003269 mTestLatencyMs = 0;
3270 mCurOutput = 0;
3271 mDirectOutput = false;
3272 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3273 mTestOutputs[i] = 0;
3274 }
3275
3276 const size_t SIZE = 256;
3277 char buffer[SIZE];
3278 snprintf(buffer, SIZE, "AudioPolicyManagerTest");
3279 run(buffer, ANDROID_PRIORITY_AUDIO);
3280 }
3281#endif //AUDIO_POLICY_TEST
3282}
3283
Eric Laurente0720872014-03-11 09:30:41 -07003284AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07003285{
3286#ifdef AUDIO_POLICY_TEST
3287 exit();
3288#endif //AUDIO_POLICY_TEST
3289 for (size_t i = 0; i < mOutputs.size(); i++) {
3290 mpClientInterface->closeOutput(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003291 }
3292 for (size_t i = 0; i < mInputs.size(); i++) {
3293 mpClientInterface->closeInput(mInputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07003294 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07003295 mAvailableOutputDevices.clear();
3296 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07003297 mOutputs.clear();
3298 mInputs.clear();
3299 mHwModules.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07003300}
3301
Eric Laurente0720872014-03-11 09:30:41 -07003302status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07003303{
3304 return (mPrimaryOutput == 0) ? NO_INIT : NO_ERROR;
3305}
3306
3307#ifdef AUDIO_POLICY_TEST
Eric Laurente0720872014-03-11 09:30:41 -07003308bool AudioPolicyManager::threadLoop()
Eric Laurente552edb2014-03-10 17:42:56 -07003309{
3310 ALOGV("entering threadLoop()");
3311 while (!exitPending())
3312 {
3313 String8 command;
3314 int valueInt;
3315 String8 value;
3316
3317 Mutex::Autolock _l(mLock);
3318 mWaitWorkCV.waitRelative(mLock, milliseconds(50));
3319
3320 command = mpClientInterface->getParameters(0, String8("test_cmd_policy"));
3321 AudioParameter param = AudioParameter(command);
3322
3323 if (param.getInt(String8("test_cmd_policy"), valueInt) == NO_ERROR &&
3324 valueInt != 0) {
3325 ALOGV("Test command %s received", command.string());
3326 String8 target;
3327 if (param.get(String8("target"), target) != NO_ERROR) {
3328 target = "Manager";
3329 }
3330 if (param.getInt(String8("test_cmd_policy_output"), valueInt) == NO_ERROR) {
3331 param.remove(String8("test_cmd_policy_output"));
3332 mCurOutput = valueInt;
3333 }
3334 if (param.get(String8("test_cmd_policy_direct"), value) == NO_ERROR) {
3335 param.remove(String8("test_cmd_policy_direct"));
3336 if (value == "false") {
3337 mDirectOutput = false;
3338 } else if (value == "true") {
3339 mDirectOutput = true;
3340 }
3341 }
3342 if (param.getInt(String8("test_cmd_policy_input"), valueInt) == NO_ERROR) {
3343 param.remove(String8("test_cmd_policy_input"));
3344 mTestInput = valueInt;
3345 }
3346
3347 if (param.get(String8("test_cmd_policy_format"), value) == NO_ERROR) {
3348 param.remove(String8("test_cmd_policy_format"));
Eric Laurent3b73df72014-03-11 09:06:29 -07003349 int format = AUDIO_FORMAT_INVALID;
Eric Laurente552edb2014-03-10 17:42:56 -07003350 if (value == "PCM 16 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003351 format = AUDIO_FORMAT_PCM_16_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003352 } else if (value == "PCM 8 bits") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003353 format = AUDIO_FORMAT_PCM_8_BIT;
Eric Laurente552edb2014-03-10 17:42:56 -07003354 } else if (value == "Compressed MP3") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003355 format = AUDIO_FORMAT_MP3;
Eric Laurente552edb2014-03-10 17:42:56 -07003356 }
Eric Laurent3b73df72014-03-11 09:06:29 -07003357 if (format != AUDIO_FORMAT_INVALID) {
Eric Laurente552edb2014-03-10 17:42:56 -07003358 if (target == "Manager") {
3359 mTestFormat = format;
3360 } else if (mTestOutputs[mCurOutput] != 0) {
3361 AudioParameter outputParam = AudioParameter();
3362 outputParam.addInt(String8("format"), format);
3363 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3364 }
3365 }
3366 }
3367 if (param.get(String8("test_cmd_policy_channels"), value) == NO_ERROR) {
3368 param.remove(String8("test_cmd_policy_channels"));
3369 int channels = 0;
3370
3371 if (value == "Channels Stereo") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003372 channels = AUDIO_CHANNEL_OUT_STEREO;
Eric Laurente552edb2014-03-10 17:42:56 -07003373 } else if (value == "Channels Mono") {
Eric Laurent3b73df72014-03-11 09:06:29 -07003374 channels = AUDIO_CHANNEL_OUT_MONO;
Eric Laurente552edb2014-03-10 17:42:56 -07003375 }
3376 if (channels != 0) {
3377 if (target == "Manager") {
3378 mTestChannels = channels;
3379 } else if (mTestOutputs[mCurOutput] != 0) {
3380 AudioParameter outputParam = AudioParameter();
3381 outputParam.addInt(String8("channels"), channels);
3382 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3383 }
3384 }
3385 }
3386 if (param.getInt(String8("test_cmd_policy_sampleRate"), valueInt) == NO_ERROR) {
3387 param.remove(String8("test_cmd_policy_sampleRate"));
3388 if (valueInt >= 0 && valueInt <= 96000) {
3389 int samplingRate = valueInt;
3390 if (target == "Manager") {
3391 mTestSamplingRate = samplingRate;
3392 } else if (mTestOutputs[mCurOutput] != 0) {
3393 AudioParameter outputParam = AudioParameter();
3394 outputParam.addInt(String8("sampling_rate"), samplingRate);
3395 mpClientInterface->setParameters(mTestOutputs[mCurOutput], outputParam.toString());
3396 }
3397 }
3398 }
3399
3400 if (param.get(String8("test_cmd_policy_reopen"), value) == NO_ERROR) {
3401 param.remove(String8("test_cmd_policy_reopen"));
3402
Eric Laurent1f2f2232014-06-02 12:01:23 -07003403 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07003404 mpClientInterface->closeOutput(mPrimaryOutput);
3405
3406 audio_module_handle_t moduleHandle = outputDesc->mModule->mHandle;
3407
Eric Laurente552edb2014-03-10 17:42:56 -07003408 mOutputs.removeItem(mPrimaryOutput);
3409
Eric Laurent1f2f2232014-06-02 12:01:23 -07003410 sp<AudioOutputDescriptor> outputDesc = new AudioOutputDescriptor(NULL);
Eric Laurente552edb2014-03-10 17:42:56 -07003411 outputDesc->mDevice = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003412 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3413 config.sample_rate = outputDesc->mSamplingRate;
3414 config.channel_mask = outputDesc->mChannelMask;
3415 config.format = outputDesc->mFormat;
3416 status_t status = mpClientInterface->openOutput(moduleHandle,
3417 &mPrimaryOutput,
3418 &config,
3419 &outputDesc->mDevice,
3420 String8(""),
3421 &outputDesc->mLatency,
3422 outputDesc->mFlags);
3423 if (status != NO_ERROR) {
3424 ALOGE("Failed to reopen hardware output stream, "
3425 "samplingRate: %d, format %d, channels %d",
3426 outputDesc->mSamplingRate, outputDesc->mFormat, outputDesc->mChannelMask);
Eric Laurente552edb2014-03-10 17:42:56 -07003427 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003428 outputDesc->mSamplingRate = config.sample_rate;
3429 outputDesc->mChannelMask = config.channel_mask;
3430 outputDesc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003431 AudioParameter outputCmd = AudioParameter();
3432 outputCmd.addInt(String8("set_id"), 0);
3433 mpClientInterface->setParameters(mPrimaryOutput, outputCmd.toString());
3434 addOutput(mPrimaryOutput, outputDesc);
3435 }
3436 }
3437
3438
3439 mpClientInterface->setParameters(0, String8("test_cmd_policy="));
3440 }
3441 }
3442 return false;
3443}
3444
Eric Laurente0720872014-03-11 09:30:41 -07003445void AudioPolicyManager::exit()
Eric Laurente552edb2014-03-10 17:42:56 -07003446{
3447 {
3448 AutoMutex _l(mLock);
3449 requestExit();
3450 mWaitWorkCV.signal();
3451 }
3452 requestExitAndWait();
3453}
3454
Eric Laurente0720872014-03-11 09:30:41 -07003455int AudioPolicyManager::testOutputIndex(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003456{
3457 for (int i = 0; i < NUM_TEST_OUTPUTS; i++) {
3458 if (output == mTestOutputs[i]) return i;
3459 }
3460 return 0;
3461}
3462#endif //AUDIO_POLICY_TEST
3463
3464// ---
3465
Eric Laurent1f2f2232014-06-02 12:01:23 -07003466void AudioPolicyManager::addOutput(audio_io_handle_t output, sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07003467{
Eric Laurent1c333e22014-05-20 10:48:17 -07003468 outputDesc->mIoHandle = output;
3469 outputDesc->mId = nextUniqueId();
3470 mOutputs.add(output, outputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003471 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07003472}
3473
Eric Laurent1f2f2232014-06-02 12:01:23 -07003474void AudioPolicyManager::addInput(audio_io_handle_t input, sp<AudioInputDescriptor> inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07003475{
Eric Laurent1c333e22014-05-20 10:48:17 -07003476 inputDesc->mIoHandle = input;
3477 inputDesc->mId = nextUniqueId();
3478 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07003479 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07003480}
Eric Laurente552edb2014-03-10 17:42:56 -07003481
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003482void AudioPolicyManager::findIoHandlesByAddress(sp<AudioOutputDescriptor> desc /*in*/,
keunyoung3190e672014-12-30 13:00:52 -08003483 const audio_devices_t device /*in*/,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003484 const String8 address /*in*/,
3485 SortedVector<audio_io_handle_t>& outputs /*out*/) {
keunyoung3190e672014-12-30 13:00:52 -08003486 sp<DeviceDescriptor> devDesc =
3487 desc->mProfile->mSupportedDevices.getDevice(device, address);
3488 if (devDesc != 0) {
3489 ALOGV("findIoHandlesByAddress(): adding opened output %d on same address %s",
3490 desc->mIoHandle, address.string());
3491 outputs.add(desc->mIoHandle);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003492 }
3493}
3494
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003495status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor> devDesc,
Eric Laurent3b73df72014-03-11 09:06:29 -07003496 audio_policy_dev_state_t state,
Eric Laurente552edb2014-03-10 17:42:56 -07003497 SortedVector<audio_io_handle_t>& outputs,
Eric Laurent3a4311c2014-03-17 12:00:47 -07003498 const String8 address)
Eric Laurente552edb2014-03-10 17:42:56 -07003499{
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003500 audio_devices_t device = devDesc->mDeviceType;
Eric Laurent1f2f2232014-06-02 12:01:23 -07003501 sp<AudioOutputDescriptor> desc;
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003502 // erase all current sample rates, formats and channel masks
3503 devDesc->clearCapabilities();
Eric Laurente552edb2014-03-10 17:42:56 -07003504
Eric Laurent3b73df72014-03-11 09:06:29 -07003505 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003506 // first list already open outputs that can be routed to this device
3507 for (size_t i = 0; i < mOutputs.size(); i++) {
3508 desc = mOutputs.valueAt(i);
Eric Laurent3a4311c2014-03-17 12:00:47 -07003509 if (!desc->isDuplicated() && (desc->mProfile->mSupportedDevices.types() & device)) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003510 if (!deviceDistinguishesOnAddress(device)) {
3511 ALOGV("checkOutputsForDevice(): adding opened output %d", mOutputs.keyAt(i));
3512 outputs.add(mOutputs.keyAt(i));
3513 } else {
3514 ALOGV(" checking address match due to device 0x%x", device);
keunyoung3190e672014-12-30 13:00:52 -08003515 findIoHandlesByAddress(desc, device, address, outputs);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003516 }
Eric Laurente552edb2014-03-10 17:42:56 -07003517 }
3518 }
3519 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003520 SortedVector< sp<IOProfile> > profiles;
Eric Laurente552edb2014-03-10 17:42:56 -07003521 for (size_t i = 0; i < mHwModules.size(); i++)
3522 {
3523 if (mHwModules[i]->mHandle == 0) {
3524 continue;
3525 }
3526 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3527 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003528 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
3529 if (profile->mSupportedDevices.types() & device) {
3530 if (!deviceDistinguishesOnAddress(device) ||
3531 address == profile->mSupportedDevices[0]->mAddress) {
3532 profiles.add(profile);
3533 ALOGV("checkOutputsForDevice(): adding profile %zu from module %zu", j, i);
3534 }
Eric Laurente552edb2014-03-10 17:42:56 -07003535 }
3536 }
3537 }
3538
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003539 ALOGV(" found %d profiles, %d outputs", profiles.size(), outputs.size());
3540
Eric Laurente552edb2014-03-10 17:42:56 -07003541 if (profiles.isEmpty() && outputs.isEmpty()) {
3542 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3543 return BAD_VALUE;
3544 }
3545
3546 // open outputs for matching profiles if needed. Direct outputs are also opened to
3547 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3548 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003549 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07003550
3551 // nothing to do if one output is already opened for this profile
3552 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003553 for (j = 0; j < outputs.size(); j++) {
3554 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07003555 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003556 // matching profile: save the sample rates, format and channel masks supported
3557 // by the profile in our device descriptor
3558 devDesc->importAudioPort(profile);
Eric Laurente552edb2014-03-10 17:42:56 -07003559 break;
3560 }
3561 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003562 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07003563 continue;
3564 }
3565
Eric Laurent83b88082014-06-20 18:31:16 -07003566 ALOGV("opening output for device %08x with params %s profile %p",
3567 device, address.string(), profile.get());
Eric Laurente552edb2014-03-10 17:42:56 -07003568 desc = new AudioOutputDescriptor(profile);
3569 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003570 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3571 config.sample_rate = desc->mSamplingRate;
3572 config.channel_mask = desc->mChannelMask;
3573 config.format = desc->mFormat;
3574 config.offload_info.sample_rate = desc->mSamplingRate;
3575 config.offload_info.channel_mask = desc->mChannelMask;
3576 config.offload_info.format = desc->mFormat;
3577 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3578 status_t status = mpClientInterface->openOutput(profile->mModule->mHandle,
3579 &output,
3580 &config,
3581 &desc->mDevice,
3582 address,
3583 &desc->mLatency,
3584 desc->mFlags);
3585 if (status == NO_ERROR) {
3586 desc->mSamplingRate = config.sample_rate;
3587 desc->mChannelMask = config.channel_mask;
3588 desc->mFormat = config.format;
Eric Laurente552edb2014-03-10 17:42:56 -07003589
Eric Laurentd4692962014-05-05 18:13:44 -07003590 // Here is where the out_set_parameters() for card & device gets called
Eric Laurent3a4311c2014-03-17 12:00:47 -07003591 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003592 char *param = audio_device_address_to_parameter(device, address);
3593 mpClientInterface->setParameters(output, String8(param));
3594 free(param);
Eric Laurente552edb2014-03-10 17:42:56 -07003595 }
3596
Eric Laurentd4692962014-05-05 18:13:44 -07003597 // Here is where we step through and resolve any "dynamic" fields
3598 String8 reply;
3599 char *value;
3600 if (profile->mSamplingRates[0] == 0) {
3601 reply = mpClientInterface->getParameters(output,
3602 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003603 ALOGV("checkOutputsForDevice() supported sampling rates %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003604 reply.string());
3605 value = strpbrk((char *)reply.string(), "=");
3606 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003607 profile->loadSamplingRates(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003608 }
Eric Laurentd4692962014-05-05 18:13:44 -07003609 }
3610 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3611 reply = mpClientInterface->getParameters(output,
3612 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003613 ALOGV("checkOutputsForDevice() supported formats %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003614 reply.string());
3615 value = strpbrk((char *)reply.string(), "=");
3616 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003617 profile->loadFormats(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003618 }
Eric Laurentd4692962014-05-05 18:13:44 -07003619 }
3620 if (profile->mChannelMasks[0] == 0) {
3621 reply = mpClientInterface->getParameters(output,
3622 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003623 ALOGV("checkOutputsForDevice() supported channel masks %s",
Eric Laurentd4692962014-05-05 18:13:44 -07003624 reply.string());
3625 value = strpbrk((char *)reply.string(), "=");
3626 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003627 profile->loadOutChannels(value + 1);
Eric Laurente552edb2014-03-10 17:42:56 -07003628 }
Eric Laurentd4692962014-05-05 18:13:44 -07003629 }
3630 if (((profile->mSamplingRates[0] == 0) &&
3631 (profile->mSamplingRates.size() < 2)) ||
3632 ((profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) &&
3633 (profile->mFormats.size() < 2)) ||
3634 ((profile->mChannelMasks[0] == 0) &&
3635 (profile->mChannelMasks.size() < 2))) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003636 ALOGW("checkOutputsForDevice() missing param");
Eric Laurentd4692962014-05-05 18:13:44 -07003637 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003638 output = AUDIO_IO_HANDLE_NONE;
Eric Laurent1e693b52014-07-09 15:03:28 -07003639 } else if (profile->mSamplingRates[0] == 0 || profile->mFormats[0] == 0 ||
3640 profile->mChannelMasks[0] == 0) {
Eric Laurentd4692962014-05-05 18:13:44 -07003641 mpClientInterface->closeOutput(output);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003642 config.sample_rate = profile->pickSamplingRate();
3643 config.channel_mask = profile->pickChannelMask();
3644 config.format = profile->pickFormat();
3645 config.offload_info.sample_rate = config.sample_rate;
3646 config.offload_info.channel_mask = config.channel_mask;
3647 config.offload_info.format = config.format;
3648 status = mpClientInterface->openOutput(profile->mModule->mHandle,
3649 &output,
3650 &config,
3651 &desc->mDevice,
3652 address,
3653 &desc->mLatency,
3654 desc->mFlags);
3655 if (status == NO_ERROR) {
3656 desc->mSamplingRate = config.sample_rate;
3657 desc->mChannelMask = config.channel_mask;
3658 desc->mFormat = config.format;
3659 } else {
3660 output = AUDIO_IO_HANDLE_NONE;
3661 }
Eric Laurentd4692962014-05-05 18:13:44 -07003662 }
3663
Eric Laurentcf2c0212014-07-25 16:20:43 -07003664 if (output != AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003665 addOutput(output, desc);
Eric Laurent275e8e92014-11-30 15:14:47 -08003666 if (deviceDistinguishesOnAddress(device) && address != "0") {
3667 ssize_t index = mPolicyMixes.indexOfKey(address);
3668 if (index >= 0) {
3669 mPolicyMixes[index]->mOutput = desc;
Eric Laurentc722f302014-12-10 11:21:49 -08003670 desc->mPolicyMix = &mPolicyMixes[index]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08003671 } else {
3672 ALOGE("checkOutputsForDevice() cannot find policy for address %s",
3673 address.string());
3674 }
Eric Laurentc722f302014-12-10 11:21:49 -08003675 } else if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) {
3676 // no duplicated output for direct outputs and
3677 // outputs used by dynamic policy mixes
Eric Laurentcf2c0212014-07-25 16:20:43 -07003678 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003679
Eric Laurentd4692962014-05-05 18:13:44 -07003680 // set initial stream volume for device
3681 applyStreamVolumes(output, device, 0, true);
Eric Laurente552edb2014-03-10 17:42:56 -07003682
Eric Laurentd4692962014-05-05 18:13:44 -07003683 //TODO: configure audio effect output stage here
3684
3685 // open a duplicating output thread for the new output and the primary output
3686 duplicatedOutput = mpClientInterface->openDuplicateOutput(output,
3687 mPrimaryOutput);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003688 if (duplicatedOutput != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003689 // add duplicated output descriptor
Eric Laurentcf2c0212014-07-25 16:20:43 -07003690 sp<AudioOutputDescriptor> dupOutputDesc =
3691 new AudioOutputDescriptor(NULL);
Eric Laurentd4692962014-05-05 18:13:44 -07003692 dupOutputDesc->mOutput1 = mOutputs.valueFor(mPrimaryOutput);
3693 dupOutputDesc->mOutput2 = mOutputs.valueFor(output);
3694 dupOutputDesc->mSamplingRate = desc->mSamplingRate;
3695 dupOutputDesc->mFormat = desc->mFormat;
3696 dupOutputDesc->mChannelMask = desc->mChannelMask;
3697 dupOutputDesc->mLatency = desc->mLatency;
3698 addOutput(duplicatedOutput, dupOutputDesc);
3699 applyStreamVolumes(duplicatedOutput, device, 0, true);
3700 } else {
3701 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
3702 mPrimaryOutput, output);
3703 mpClientInterface->closeOutput(output);
3704 mOutputs.removeItem(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07003705 nextAudioPortGeneration();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003706 output = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003707 }
Eric Laurente552edb2014-03-10 17:42:56 -07003708 }
3709 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003710 } else {
3711 output = AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003712 }
Eric Laurentcf2c0212014-07-25 16:20:43 -07003713 if (output == AUDIO_IO_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07003714 ALOGW("checkOutputsForDevice() could not open output for device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07003715 profiles.removeAt(profile_index);
3716 profile_index--;
3717 } else {
3718 outputs.add(output);
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07003719 devDesc->importAudioPort(profile);
3720
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003721 if (deviceDistinguishesOnAddress(device)) {
3722 ALOGV("checkOutputsForDevice(): setOutputDevice(dev=0x%x, addr=%s)",
3723 device, address.string());
3724 setOutputDevice(output, device, true/*force*/, 0/*delay*/,
3725 NULL/*patch handle*/, address.string());
3726 }
Eric Laurente552edb2014-03-10 17:42:56 -07003727 ALOGV("checkOutputsForDevice(): adding output %d", output);
3728 }
3729 }
3730
3731 if (profiles.isEmpty()) {
3732 ALOGW("checkOutputsForDevice(): No output available for device %04x", device);
3733 return BAD_VALUE;
3734 }
Eric Laurentd4692962014-05-05 18:13:44 -07003735 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07003736 // check if one opened output is not needed any more after disconnecting one device
3737 for (size_t i = 0; i < mOutputs.size(); i++) {
3738 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003739 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08003740 // exact match on device
3741 if (deviceDistinguishesOnAddress(device) &&
3742 (desc->mProfile->mSupportedDevices.types() == device)) {
keunyoung3190e672014-12-30 13:00:52 -08003743 findIoHandlesByAddress(desc, device, address, outputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08003744 } else if (!(desc->mProfile->mSupportedDevices.types()
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003745 & mAvailableOutputDevices.types())) {
3746 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
3747 mOutputs.keyAt(i));
3748 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07003749 }
Eric Laurente552edb2014-03-10 17:42:56 -07003750 }
3751 }
Eric Laurentd4692962014-05-05 18:13:44 -07003752 // Clear any profiles associated with the disconnected device.
Eric Laurente552edb2014-03-10 17:42:56 -07003753 for (size_t i = 0; i < mHwModules.size(); i++)
3754 {
3755 if (mHwModules[i]->mHandle == 0) {
3756 continue;
3757 }
3758 for (size_t j = 0; j < mHwModules[i]->mOutputProfiles.size(); j++)
3759 {
Eric Laurent1c333e22014-05-20 10:48:17 -07003760 sp<IOProfile> profile = mHwModules[i]->mOutputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07003761 if (profile->mSupportedDevices.types() & device) {
3762 ALOGV("checkOutputsForDevice(): "
3763 "clearing direct output profile %zu on module %zu", j, i);
Eric Laurente552edb2014-03-10 17:42:56 -07003764 if (profile->mSamplingRates[0] == 0) {
3765 profile->mSamplingRates.clear();
3766 profile->mSamplingRates.add(0);
3767 }
3768 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3769 profile->mFormats.clear();
3770 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3771 }
3772 if (profile->mChannelMasks[0] == 0) {
3773 profile->mChannelMasks.clear();
3774 profile->mChannelMasks.add(0);
3775 }
3776 }
3777 }
3778 }
3779 }
3780 return NO_ERROR;
3781}
3782
Eric Laurentd4692962014-05-05 18:13:44 -07003783status_t AudioPolicyManager::checkInputsForDevice(audio_devices_t device,
3784 audio_policy_dev_state_t state,
3785 SortedVector<audio_io_handle_t>& inputs,
3786 const String8 address)
3787{
Eric Laurent1f2f2232014-06-02 12:01:23 -07003788 sp<AudioInputDescriptor> desc;
Eric Laurentd4692962014-05-05 18:13:44 -07003789 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3790 // first list already open inputs that can be routed to this device
3791 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3792 desc = mInputs.valueAt(input_index);
3793 if (desc->mProfile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3794 ALOGV("checkInputsForDevice(): adding opened input %d", mInputs.keyAt(input_index));
3795 inputs.add(mInputs.keyAt(input_index));
3796 }
3797 }
3798
3799 // then look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07003800 SortedVector< sp<IOProfile> > profiles;
Eric Laurentd4692962014-05-05 18:13:44 -07003801 for (size_t module_idx = 0; module_idx < mHwModules.size(); module_idx++)
3802 {
3803 if (mHwModules[module_idx]->mHandle == 0) {
3804 continue;
3805 }
3806 for (size_t profile_index = 0;
3807 profile_index < mHwModules[module_idx]->mInputProfiles.size();
3808 profile_index++)
3809 {
Eric Laurent275e8e92014-11-30 15:14:47 -08003810 sp<IOProfile> profile = mHwModules[module_idx]->mInputProfiles[profile_index];
3811
3812 if (profile->mSupportedDevices.types() & (device & ~AUDIO_DEVICE_BIT_IN)) {
3813 if (!deviceDistinguishesOnAddress(device) ||
3814 address == profile->mSupportedDevices[0]->mAddress) {
3815 profiles.add(profile);
3816 ALOGV("checkInputsForDevice(): adding profile %zu from module %zu",
3817 profile_index, module_idx);
3818 }
Eric Laurentd4692962014-05-05 18:13:44 -07003819 }
3820 }
3821 }
3822
3823 if (profiles.isEmpty() && inputs.isEmpty()) {
3824 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3825 return BAD_VALUE;
3826 }
3827
3828 // open inputs for matching profiles if needed. Direct inputs are also opened to
3829 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
3830 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
3831
Eric Laurent1c333e22014-05-20 10:48:17 -07003832 sp<IOProfile> profile = profiles[profile_index];
Eric Laurentd4692962014-05-05 18:13:44 -07003833 // nothing to do if one input is already opened for this profile
3834 size_t input_index;
3835 for (input_index = 0; input_index < mInputs.size(); input_index++) {
3836 desc = mInputs.valueAt(input_index);
3837 if (desc->mProfile == profile) {
3838 break;
3839 }
3840 }
3841 if (input_index != mInputs.size()) {
3842 continue;
3843 }
3844
3845 ALOGV("opening input for device 0x%X with params %s", device, address.string());
3846 desc = new AudioInputDescriptor(profile);
3847 desc->mDevice = device;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003848 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
3849 config.sample_rate = desc->mSamplingRate;
3850 config.channel_mask = desc->mChannelMask;
3851 config.format = desc->mFormat;
3852 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
3853 status_t status = mpClientInterface->openInput(profile->mModule->mHandle,
3854 &input,
3855 &config,
3856 &desc->mDevice,
3857 address,
3858 AUDIO_SOURCE_MIC,
3859 AUDIO_INPUT_FLAG_NONE /*FIXME*/);
Eric Laurentd4692962014-05-05 18:13:44 -07003860
Eric Laurentcf2c0212014-07-25 16:20:43 -07003861 if (status == NO_ERROR) {
3862 desc->mSamplingRate = config.sample_rate;
3863 desc->mChannelMask = config.channel_mask;
3864 desc->mFormat = config.format;
Eric Laurentd4692962014-05-05 18:13:44 -07003865
Eric Laurentd4692962014-05-05 18:13:44 -07003866 if (!address.isEmpty()) {
Eric Laurentcf2c0212014-07-25 16:20:43 -07003867 char *param = audio_device_address_to_parameter(device, address);
3868 mpClientInterface->setParameters(input, String8(param));
3869 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07003870 }
3871
3872 // Here is where we step through and resolve any "dynamic" fields
3873 String8 reply;
3874 char *value;
3875 if (profile->mSamplingRates[0] == 0) {
3876 reply = mpClientInterface->getParameters(input,
3877 String8(AUDIO_PARAMETER_STREAM_SUP_SAMPLING_RATES));
3878 ALOGV("checkInputsForDevice() direct input sup sampling rates %s",
3879 reply.string());
3880 value = strpbrk((char *)reply.string(), "=");
3881 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003882 profile->loadSamplingRates(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003883 }
3884 }
3885 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3886 reply = mpClientInterface->getParameters(input,
3887 String8(AUDIO_PARAMETER_STREAM_SUP_FORMATS));
3888 ALOGV("checkInputsForDevice() direct input sup formats %s", reply.string());
3889 value = strpbrk((char *)reply.string(), "=");
3890 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003891 profile->loadFormats(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003892 }
3893 }
3894 if (profile->mChannelMasks[0] == 0) {
3895 reply = mpClientInterface->getParameters(input,
3896 String8(AUDIO_PARAMETER_STREAM_SUP_CHANNELS));
3897 ALOGV("checkInputsForDevice() direct input sup channel masks %s",
3898 reply.string());
3899 value = strpbrk((char *)reply.string(), "=");
3900 if (value != NULL) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003901 profile->loadInChannels(value + 1);
Eric Laurentd4692962014-05-05 18:13:44 -07003902 }
3903 }
3904 if (((profile->mSamplingRates[0] == 0) && (profile->mSamplingRates.size() < 2)) ||
3905 ((profile->mFormats[0] == 0) && (profile->mFormats.size() < 2)) ||
3906 ((profile->mChannelMasks[0] == 0) && (profile->mChannelMasks.size() < 2))) {
3907 ALOGW("checkInputsForDevice() direct input missing param");
3908 mpClientInterface->closeInput(input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003909 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07003910 }
3911
3912 if (input != 0) {
3913 addInput(input, desc);
3914 }
3915 } // endif input != 0
3916
Eric Laurentcf2c0212014-07-25 16:20:43 -07003917 if (input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07003918 ALOGW("checkInputsForDevice() could not open input for device 0x%X", device);
Eric Laurentd4692962014-05-05 18:13:44 -07003919 profiles.removeAt(profile_index);
3920 profile_index--;
3921 } else {
3922 inputs.add(input);
3923 ALOGV("checkInputsForDevice(): adding input %d", input);
3924 }
3925 } // end scan profiles
3926
3927 if (profiles.isEmpty()) {
3928 ALOGW("checkInputsForDevice(): No input available for device 0x%X", device);
3929 return BAD_VALUE;
3930 }
3931 } else {
3932 // Disconnect
3933 // check if one opened input is not needed any more after disconnecting one device
3934 for (size_t input_index = 0; input_index < mInputs.size(); input_index++) {
3935 desc = mInputs.valueAt(input_index);
Eric Laurentddbc6652014-11-13 15:13:44 -08003936 if (!(desc->mProfile->mSupportedDevices.types() & mAvailableInputDevices.types() &
3937 ~AUDIO_DEVICE_BIT_IN)) {
Eric Laurentd4692962014-05-05 18:13:44 -07003938 ALOGV("checkInputsForDevice(): disconnecting adding input %d",
3939 mInputs.keyAt(input_index));
3940 inputs.add(mInputs.keyAt(input_index));
3941 }
3942 }
3943 // Clear any profiles associated with the disconnected device.
3944 for (size_t module_index = 0; module_index < mHwModules.size(); module_index++) {
3945 if (mHwModules[module_index]->mHandle == 0) {
3946 continue;
3947 }
3948 for (size_t profile_index = 0;
3949 profile_index < mHwModules[module_index]->mInputProfiles.size();
3950 profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07003951 sp<IOProfile> profile = mHwModules[module_index]->mInputProfiles[profile_index];
Eric Laurentddbc6652014-11-13 15:13:44 -08003952 if (profile->mSupportedDevices.types() & device & ~AUDIO_DEVICE_BIT_IN) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07003953 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %zu",
Eric Laurentd4692962014-05-05 18:13:44 -07003954 profile_index, module_index);
3955 if (profile->mSamplingRates[0] == 0) {
3956 profile->mSamplingRates.clear();
3957 profile->mSamplingRates.add(0);
3958 }
3959 if (profile->mFormats[0] == AUDIO_FORMAT_DEFAULT) {
3960 profile->mFormats.clear();
3961 profile->mFormats.add(AUDIO_FORMAT_DEFAULT);
3962 }
3963 if (profile->mChannelMasks[0] == 0) {
3964 profile->mChannelMasks.clear();
3965 profile->mChannelMasks.add(0);
3966 }
3967 }
3968 }
3969 }
3970 } // end disconnect
3971
3972 return NO_ERROR;
3973}
3974
3975
Eric Laurente0720872014-03-11 09:30:41 -07003976void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07003977{
3978 ALOGV("closeOutput(%d)", output);
3979
Eric Laurent1f2f2232014-06-02 12:01:23 -07003980 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07003981 if (outputDesc == NULL) {
3982 ALOGW("closeOutput() unknown output %d", output);
3983 return;
3984 }
3985
Eric Laurent275e8e92014-11-30 15:14:47 -08003986 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
3987 if (mPolicyMixes[i]->mOutput == outputDesc) {
3988 mPolicyMixes[i]->mOutput.clear();
3989 }
3990 }
3991
Eric Laurente552edb2014-03-10 17:42:56 -07003992 // look for duplicated outputs connected to the output being removed.
3993 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003994 sp<AudioOutputDescriptor> dupOutputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07003995 if (dupOutputDesc->isDuplicated() &&
3996 (dupOutputDesc->mOutput1 == outputDesc ||
3997 dupOutputDesc->mOutput2 == outputDesc)) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003998 sp<AudioOutputDescriptor> outputDesc2;
Eric Laurente552edb2014-03-10 17:42:56 -07003999 if (dupOutputDesc->mOutput1 == outputDesc) {
4000 outputDesc2 = dupOutputDesc->mOutput2;
4001 } else {
4002 outputDesc2 = dupOutputDesc->mOutput1;
4003 }
4004 // As all active tracks on duplicated output will be deleted,
4005 // and as they were also referenced on the other output, the reference
4006 // count for their stream type must be adjusted accordingly on
4007 // the other output.
Eric Laurent3b73df72014-03-11 09:06:29 -07004008 for (int j = 0; j < AUDIO_STREAM_CNT; j++) {
Eric Laurente552edb2014-03-10 17:42:56 -07004009 int refCount = dupOutputDesc->mRefCount[j];
Eric Laurent3b73df72014-03-11 09:06:29 -07004010 outputDesc2->changeRefCount((audio_stream_type_t)j,-refCount);
Eric Laurente552edb2014-03-10 17:42:56 -07004011 }
4012 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
4013 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
4014
4015 mpClientInterface->closeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07004016 mOutputs.removeItem(duplicatedOutput);
4017 }
4018 }
4019
Eric Laurent05b90f82014-08-27 15:32:29 -07004020 nextAudioPortGeneration();
4021
4022 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4023 if (index >= 0) {
4024 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4025 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4026 mAudioPatches.removeItemsAt(index);
4027 mpClientInterface->onAudioPatchListUpdate();
4028 }
4029
Eric Laurente552edb2014-03-10 17:42:56 -07004030 AudioParameter param;
4031 param.add(String8("closing"), String8("true"));
4032 mpClientInterface->setParameters(output, param.toString());
4033
4034 mpClientInterface->closeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004035 mOutputs.removeItem(output);
4036 mPreviousOutputs = mOutputs;
Eric Laurent05b90f82014-08-27 15:32:29 -07004037}
4038
4039void AudioPolicyManager::closeInput(audio_io_handle_t input)
4040{
4041 ALOGV("closeInput(%d)", input);
4042
4043 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
4044 if (inputDesc == NULL) {
4045 ALOGW("closeInput() unknown input %d", input);
4046 return;
4047 }
4048
Eric Laurent6a94d692014-05-20 11:18:06 -07004049 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07004050
4051 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4052 if (index >= 0) {
4053 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4054 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
4055 mAudioPatches.removeItemsAt(index);
4056 mpClientInterface->onAudioPatchListUpdate();
4057 }
4058
4059 mpClientInterface->closeInput(input);
4060 mInputs.removeItem(input);
Eric Laurente552edb2014-03-10 17:42:56 -07004061}
4062
Eric Laurente0720872014-03-11 09:30:41 -07004063SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevice(audio_devices_t device,
Eric Laurent1f2f2232014-06-02 12:01:23 -07004064 DefaultKeyedVector<audio_io_handle_t, sp<AudioOutputDescriptor> > openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07004065{
4066 SortedVector<audio_io_handle_t> outputs;
4067
4068 ALOGVV("getOutputsForDevice() device %04x", device);
4069 for (size_t i = 0; i < openOutputs.size(); i++) {
4070 ALOGVV("output %d isDuplicated=%d device=%04x",
4071 i, openOutputs.valueAt(i)->isDuplicated(), openOutputs.valueAt(i)->supportedDevices());
4072 if ((device & openOutputs.valueAt(i)->supportedDevices()) == device) {
4073 ALOGVV("getOutputsForDevice() found output %d", openOutputs.keyAt(i));
4074 outputs.add(openOutputs.keyAt(i));
4075 }
4076 }
4077 return outputs;
4078}
4079
Eric Laurente0720872014-03-11 09:30:41 -07004080bool AudioPolicyManager::vectorsEqual(SortedVector<audio_io_handle_t>& outputs1,
Eric Laurente552edb2014-03-10 17:42:56 -07004081 SortedVector<audio_io_handle_t>& outputs2)
4082{
4083 if (outputs1.size() != outputs2.size()) {
4084 return false;
4085 }
4086 for (size_t i = 0; i < outputs1.size(); i++) {
4087 if (outputs1[i] != outputs2[i]) {
4088 return false;
4089 }
4090 }
4091 return true;
4092}
4093
Eric Laurente0720872014-03-11 09:30:41 -07004094void AudioPolicyManager::checkOutputForStrategy(routing_strategy strategy)
Eric Laurente552edb2014-03-10 17:42:56 -07004095{
4096 audio_devices_t oldDevice = getDeviceForStrategy(strategy, true /*fromCache*/);
4097 audio_devices_t newDevice = getDeviceForStrategy(strategy, false /*fromCache*/);
4098 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevice(oldDevice, mPreviousOutputs);
4099 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevice(newDevice, mOutputs);
4100
Jean-Michel Trivife472e22014-12-16 14:23:13 -08004101 // also take into account external policy-related changes: add all outputs which are
4102 // associated with policies in the "before" and "after" output vectors
4103 ALOGVV("checkOutputForStrategy(): policy related outputs");
4104 for (size_t i = 0 ; i < mPreviousOutputs.size() ; i++) {
4105 const sp<AudioOutputDescriptor> desc = mPreviousOutputs.valueAt(i);
4106 if (desc != 0 && desc->mPolicyMix != NULL) {
4107 srcOutputs.add(desc->mIoHandle);
4108 ALOGVV(" previous outputs: adding %d", desc->mIoHandle);
4109 }
4110 }
4111 for (size_t i = 0 ; i < mOutputs.size() ; i++) {
4112 const sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4113 if (desc != 0 && desc->mPolicyMix != NULL) {
4114 dstOutputs.add(desc->mIoHandle);
4115 ALOGVV(" new outputs: adding %d", desc->mIoHandle);
4116 }
4117 }
4118
Eric Laurente552edb2014-03-10 17:42:56 -07004119 if (!vectorsEqual(srcOutputs,dstOutputs)) {
4120 ALOGV("checkOutputForStrategy() strategy %d, moving from output %d to output %d",
4121 strategy, srcOutputs[0], dstOutputs[0]);
4122 // mute strategy while moving tracks from one output to another
4123 for (size_t i = 0; i < srcOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004124 sp<AudioOutputDescriptor> desc = mOutputs.valueFor(srcOutputs[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07004125 if (desc->isStrategyActive(strategy)) {
4126 setStrategyMute(strategy, true, srcOutputs[i]);
4127 setStrategyMute(strategy, false, srcOutputs[i], MUTE_TIME_MS, newDevice);
4128 }
4129 }
4130
4131 // Move effects associated to this strategy from previous output to new output
4132 if (strategy == STRATEGY_MEDIA) {
4133 audio_io_handle_t fxOutput = selectOutputForEffects(dstOutputs);
4134 SortedVector<audio_io_handle_t> moved;
4135 for (size_t i = 0; i < mEffects.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004136 sp<EffectDescriptor> effectDesc = mEffects.valueAt(i);
4137 if (effectDesc->mSession == AUDIO_SESSION_OUTPUT_MIX &&
4138 effectDesc->mIo != fxOutput) {
4139 if (moved.indexOf(effectDesc->mIo) < 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07004140 ALOGV("checkOutputForStrategy() moving effect %d to output %d",
4141 mEffects.keyAt(i), fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004142 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, effectDesc->mIo,
Eric Laurente552edb2014-03-10 17:42:56 -07004143 fxOutput);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004144 moved.add(effectDesc->mIo);
Eric Laurente552edb2014-03-10 17:42:56 -07004145 }
Eric Laurent1f2f2232014-06-02 12:01:23 -07004146 effectDesc->mIo = fxOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07004147 }
4148 }
4149 }
4150 // Move tracks associated to this strategy from previous output to new output
Eric Laurent3b73df72014-03-11 09:06:29 -07004151 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004152 if (i == AUDIO_STREAM_PATCH) {
4153 continue;
4154 }
Eric Laurent3b73df72014-03-11 09:06:29 -07004155 if (getStrategy((audio_stream_type_t)i) == strategy) {
4156 mpClientInterface->invalidateStream((audio_stream_type_t)i);
Eric Laurente552edb2014-03-10 17:42:56 -07004157 }
4158 }
4159 }
4160}
4161
Eric Laurente0720872014-03-11 09:30:41 -07004162void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07004163{
Jon Eklund966095e2014-09-09 15:39:49 -05004164 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4165 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004166 checkOutputForStrategy(STRATEGY_PHONE);
Jon Eklund966095e2014-09-09 15:39:49 -05004167 if (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)
4168 checkOutputForStrategy(STRATEGY_ENFORCED_AUDIBLE);
Eric Laurente552edb2014-03-10 17:42:56 -07004169 checkOutputForStrategy(STRATEGY_SONIFICATION);
4170 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004171 checkOutputForStrategy(STRATEGY_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -07004172 checkOutputForStrategy(STRATEGY_MEDIA);
4173 checkOutputForStrategy(STRATEGY_DTMF);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004174 checkOutputForStrategy(STRATEGY_REROUTING);
Eric Laurente552edb2014-03-10 17:42:56 -07004175}
4176
Eric Laurente0720872014-03-11 09:30:41 -07004177audio_io_handle_t AudioPolicyManager::getA2dpOutput()
Eric Laurente552edb2014-03-10 17:42:56 -07004178{
Eric Laurente552edb2014-03-10 17:42:56 -07004179 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004180 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07004181 if (!outputDesc->isDuplicated() && outputDesc->device() & AUDIO_DEVICE_OUT_ALL_A2DP) {
4182 return mOutputs.keyAt(i);
4183 }
4184 }
4185
4186 return 0;
4187}
4188
Eric Laurente0720872014-03-11 09:30:41 -07004189void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07004190{
Eric Laurente552edb2014-03-10 17:42:56 -07004191 audio_io_handle_t a2dpOutput = getA2dpOutput();
4192 if (a2dpOutput == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004193 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07004194 return;
4195 }
4196
Eric Laurent3a4311c2014-03-17 12:00:47 -07004197 bool isScoConnected =
Eric Laurentddbc6652014-11-13 15:13:44 -08004198 ((mAvailableInputDevices.types() & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET &
4199 ~AUDIO_DEVICE_BIT_IN) != 0) ||
4200 ((mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_ALL_SCO) != 0);
Eric Laurente552edb2014-03-10 17:42:56 -07004201 // suspend A2DP output if:
4202 // (NOT already suspended) &&
4203 // ((SCO device is connected &&
4204 // (forced usage for communication || for record is SCO))) ||
4205 // (phone state is ringing || in call)
4206 //
4207 // restore A2DP output if:
4208 // (Already suspended) &&
4209 // ((SCO device is NOT connected ||
4210 // (forced usage NOT for communication && NOT for record is SCO))) &&
4211 // (phone state is NOT ringing && NOT in call)
4212 //
4213 if (mA2dpSuspended) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004214 if ((!isScoConnected ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004215 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO) &&
4216 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] != AUDIO_POLICY_FORCE_BT_SCO))) &&
4217 ((mPhoneState != AUDIO_MODE_IN_CALL) &&
4218 (mPhoneState != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004219
4220 mpClientInterface->restoreOutput(a2dpOutput);
4221 mA2dpSuspended = false;
4222 }
4223 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004224 if ((isScoConnected &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004225 ((mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
4226 (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO))) ||
4227 ((mPhoneState == AUDIO_MODE_IN_CALL) ||
4228 (mPhoneState == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07004229
4230 mpClientInterface->suspendOutput(a2dpOutput);
4231 mA2dpSuspended = true;
4232 }
4233 }
4234}
4235
Eric Laurent1c333e22014-05-20 10:48:17 -07004236audio_devices_t AudioPolicyManager::getNewOutputDevice(audio_io_handle_t output, bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07004237{
4238 audio_devices_t device = AUDIO_DEVICE_NONE;
4239
Eric Laurent1f2f2232014-06-02 12:01:23 -07004240 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07004241
4242 ssize_t index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4243 if (index >= 0) {
4244 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4245 if (patchDesc->mUid != mUidCached) {
4246 ALOGV("getNewOutputDevice() device %08x forced by patch %d",
4247 outputDesc->device(), outputDesc->mPatchHandle);
4248 return outputDesc->device();
4249 }
4250 }
4251
Eric Laurente552edb2014-03-10 17:42:56 -07004252 // check the following by order of priority to request a routing change if necessary:
Jon Eklund966095e2014-09-09 15:39:49 -05004253 // 1: the strategy enforced audible is active and enforced on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004254 // use device for strategy enforced audible
4255 // 2: we are in call or the strategy phone is active on the output:
4256 // use device for strategy phone
Jon Eklund966095e2014-09-09 15:39:49 -05004257 // 3: the strategy for enforced audible is active but not enforced on the output:
4258 // use the device for strategy enforced audible
4259 // 4: the strategy sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004260 // use device for strategy sonification
Jon Eklund966095e2014-09-09 15:39:49 -05004261 // 5: the strategy "respectful" sonification is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004262 // use device for strategy "respectful" sonification
Eric Laurent223fd5c2014-11-11 13:43:36 -08004263 // 6: the strategy accessibility is active on the output:
4264 // use device for strategy accessibility
4265 // 7: the strategy media is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004266 // use device for strategy media
Eric Laurent223fd5c2014-11-11 13:43:36 -08004267 // 8: the strategy DTMF is active on the output:
Eric Laurente552edb2014-03-10 17:42:56 -07004268 // use device for strategy DTMF
Eric Laurent223fd5c2014-11-11 13:43:36 -08004269 // 9: the strategy for beacon, a.k.a. "transmitted through speaker" is active on the output:
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004270 // use device for strategy t-t-s
Jon Eklund966095e2014-09-09 15:39:49 -05004271 if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE) &&
4272 mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Eric Laurente552edb2014-03-10 17:42:56 -07004273 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
4274 } else if (isInCall() ||
4275 outputDesc->isStrategyActive(STRATEGY_PHONE)) {
4276 device = getDeviceForStrategy(STRATEGY_PHONE, fromCache);
Jon Eklund966095e2014-09-09 15:39:49 -05004277 } else if (outputDesc->isStrategyActive(STRATEGY_ENFORCED_AUDIBLE)) {
4278 device = getDeviceForStrategy(STRATEGY_ENFORCED_AUDIBLE, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004279 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION)) {
4280 device = getDeviceForStrategy(STRATEGY_SONIFICATION, fromCache);
4281 } else if (outputDesc->isStrategyActive(STRATEGY_SONIFICATION_RESPECTFUL)) {
4282 device = getDeviceForStrategy(STRATEGY_SONIFICATION_RESPECTFUL, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004283 } else if (outputDesc->isStrategyActive(STRATEGY_ACCESSIBILITY)) {
4284 device = getDeviceForStrategy(STRATEGY_ACCESSIBILITY, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004285 } else if (outputDesc->isStrategyActive(STRATEGY_MEDIA)) {
4286 device = getDeviceForStrategy(STRATEGY_MEDIA, fromCache);
4287 } else if (outputDesc->isStrategyActive(STRATEGY_DTMF)) {
4288 device = getDeviceForStrategy(STRATEGY_DTMF, fromCache);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004289 } else if (outputDesc->isStrategyActive(STRATEGY_TRANSMITTED_THROUGH_SPEAKER)) {
4290 device = getDeviceForStrategy(STRATEGY_TRANSMITTED_THROUGH_SPEAKER, fromCache);
Eric Laurent223fd5c2014-11-11 13:43:36 -08004291 } else if (outputDesc->isStrategyActive(STRATEGY_REROUTING)) {
4292 device = getDeviceForStrategy(STRATEGY_REROUTING, fromCache);
Eric Laurente552edb2014-03-10 17:42:56 -07004293 }
4294
Eric Laurent1c333e22014-05-20 10:48:17 -07004295 ALOGV("getNewOutputDevice() selected device %x", device);
4296 return device;
4297}
4298
4299audio_devices_t AudioPolicyManager::getNewInputDevice(audio_io_handle_t input)
4300{
Eric Laurent1f2f2232014-06-02 12:01:23 -07004301 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07004302
4303 ssize_t index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
4304 if (index >= 0) {
4305 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
4306 if (patchDesc->mUid != mUidCached) {
4307 ALOGV("getNewInputDevice() device %08x forced by patch %d",
4308 inputDesc->mDevice, inputDesc->mPatchHandle);
4309 return inputDesc->mDevice;
4310 }
4311 }
4312
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004313 audio_devices_t device = getDeviceAndMixForInputSource(inputDesc->mInputSource);
Eric Laurent1c333e22014-05-20 10:48:17 -07004314
4315 ALOGV("getNewInputDevice() selected device %x", device);
Eric Laurente552edb2014-03-10 17:42:56 -07004316 return device;
4317}
4318
Eric Laurente0720872014-03-11 09:30:41 -07004319uint32_t AudioPolicyManager::getStrategyForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004320 return (uint32_t)getStrategy(stream);
4321}
4322
Eric Laurente0720872014-03-11 09:30:41 -07004323audio_devices_t AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004324 // By checking the range of stream before calling getStrategy, we avoid
4325 // getStrategy's behavior for invalid streams. getStrategy would do a ALOGE
4326 // and then return STRATEGY_MEDIA, but we want to return the empty set.
Eric Laurent223fd5c2014-11-11 13:43:36 -08004327 if (stream < (audio_stream_type_t) 0 || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004328 return AUDIO_DEVICE_NONE;
4329 }
4330 audio_devices_t devices;
4331 AudioPolicyManager::routing_strategy strategy = getStrategy(stream);
4332 devices = getDeviceForStrategy(strategy, true /*fromCache*/);
4333 SortedVector<audio_io_handle_t> outputs = getOutputsForDevice(devices, mOutputs);
4334 for (size_t i = 0; i < outputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004335 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputs[i]);
Eric Laurent6a94d692014-05-20 11:18:06 -07004336 if (outputDesc->isStrategyActive(strategy)) {
4337 devices = outputDesc->device();
4338 break;
4339 }
Eric Laurente552edb2014-03-10 17:42:56 -07004340 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05004341
4342 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
4343 and doesn't really need to.*/
4344 if (devices & AUDIO_DEVICE_OUT_SPEAKER_SAFE) {
4345 devices |= AUDIO_DEVICE_OUT_SPEAKER;
4346 devices &= ~AUDIO_DEVICE_OUT_SPEAKER_SAFE;
4347 }
4348
Eric Laurente552edb2014-03-10 17:42:56 -07004349 return devices;
4350}
4351
Eric Laurente0720872014-03-11 09:30:41 -07004352AudioPolicyManager::routing_strategy AudioPolicyManager::getStrategy(
Eric Laurent3b73df72014-03-11 09:06:29 -07004353 audio_stream_type_t stream) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08004354
4355 ALOG_ASSERT(stream != AUDIO_STREAM_PATCH,"getStrategy() called for AUDIO_STREAM_PATCH");
4356
Eric Laurente552edb2014-03-10 17:42:56 -07004357 // stream to strategy mapping
4358 switch (stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004359 case AUDIO_STREAM_VOICE_CALL:
4360 case AUDIO_STREAM_BLUETOOTH_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004361 return STRATEGY_PHONE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004362 case AUDIO_STREAM_RING:
4363 case AUDIO_STREAM_ALARM:
Eric Laurente552edb2014-03-10 17:42:56 -07004364 return STRATEGY_SONIFICATION;
Eric Laurent3b73df72014-03-11 09:06:29 -07004365 case AUDIO_STREAM_NOTIFICATION:
Eric Laurente552edb2014-03-10 17:42:56 -07004366 return STRATEGY_SONIFICATION_RESPECTFUL;
Eric Laurent3b73df72014-03-11 09:06:29 -07004367 case AUDIO_STREAM_DTMF:
Eric Laurente552edb2014-03-10 17:42:56 -07004368 return STRATEGY_DTMF;
4369 default:
Eric Laurent223fd5c2014-11-11 13:43:36 -08004370 ALOGE("unknown stream type %d", stream);
Eric Laurent3b73df72014-03-11 09:06:29 -07004371 case AUDIO_STREAM_SYSTEM:
Eric Laurente552edb2014-03-10 17:42:56 -07004372 // NOTE: SYSTEM stream uses MEDIA strategy because muting music and switching outputs
4373 // while key clicks are played produces a poor result
Eric Laurent3b73df72014-03-11 09:06:29 -07004374 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004375 return STRATEGY_MEDIA;
Eric Laurent3b73df72014-03-11 09:06:29 -07004376 case AUDIO_STREAM_ENFORCED_AUDIBLE:
Eric Laurente552edb2014-03-10 17:42:56 -07004377 return STRATEGY_ENFORCED_AUDIBLE;
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004378 case AUDIO_STREAM_TTS:
4379 return STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
Eric Laurent223fd5c2014-11-11 13:43:36 -08004380 case AUDIO_STREAM_ACCESSIBILITY:
4381 return STRATEGY_ACCESSIBILITY;
4382 case AUDIO_STREAM_REROUTING:
4383 return STRATEGY_REROUTING;
Eric Laurente552edb2014-03-10 17:42:56 -07004384 }
4385}
4386
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004387uint32_t AudioPolicyManager::getStrategyForAttr(const audio_attributes_t *attr) {
4388 // flags to strategy mapping
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004389 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
4390 return (uint32_t) STRATEGY_TRANSMITTED_THROUGH_SPEAKER;
4391 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004392 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
4393 return (uint32_t) STRATEGY_ENFORCED_AUDIBLE;
4394 }
4395
4396 // usage to strategy mapping
4397 switch (attr->usage) {
Eric Laurent29e6cec2014-11-13 18:17:55 -08004398 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
4399 if (isStreamActive(AUDIO_STREAM_RING) || isStreamActive(AUDIO_STREAM_ALARM)) {
4400 return (uint32_t) STRATEGY_SONIFICATION;
4401 }
4402 if (isInCall()) {
4403 return (uint32_t) STRATEGY_PHONE;
4404 }
Eric Laurent0f78eab2014-11-25 11:01:34 -08004405 return (uint32_t) STRATEGY_ACCESSIBILITY;
Eric Laurent29e6cec2014-11-13 18:17:55 -08004406
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004407 case AUDIO_USAGE_MEDIA:
4408 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07004409 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
4410 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
4411 return (uint32_t) STRATEGY_MEDIA;
4412
4413 case AUDIO_USAGE_VOICE_COMMUNICATION:
4414 return (uint32_t) STRATEGY_PHONE;
4415
4416 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
4417 return (uint32_t) STRATEGY_DTMF;
4418
4419 case AUDIO_USAGE_ALARM:
4420 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
4421 return (uint32_t) STRATEGY_SONIFICATION;
4422
4423 case AUDIO_USAGE_NOTIFICATION:
4424 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
4425 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
4426 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
4427 case AUDIO_USAGE_NOTIFICATION_EVENT:
4428 return (uint32_t) STRATEGY_SONIFICATION_RESPECTFUL;
4429
4430 case AUDIO_USAGE_UNKNOWN:
4431 default:
4432 return (uint32_t) STRATEGY_MEDIA;
4433 }
4434}
4435
Eric Laurente0720872014-03-11 09:30:41 -07004436void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07004437 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07004438 case AUDIO_STREAM_MUSIC:
Eric Laurente552edb2014-03-10 17:42:56 -07004439 checkOutputForStrategy(STRATEGY_SONIFICATION_RESPECTFUL);
4440 updateDevicesAndOutputs();
4441 break;
4442 default:
4443 break;
4444 }
4445}
4446
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004447bool AudioPolicyManager::isAnyOutputActive(audio_stream_type_t streamToIgnore) {
4448 for (size_t s = 0 ; s < AUDIO_STREAM_CNT ; s++) {
4449 if (s == (size_t) streamToIgnore) {
4450 continue;
4451 }
4452 for (size_t i = 0; i < mOutputs.size(); i++) {
4453 const sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4454 if (outputDesc->mRefCount[s] != 0) {
4455 return true;
4456 }
4457 }
4458 }
4459 return false;
4460}
4461
4462uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
4463 switch(event) {
4464 case STARTING_OUTPUT:
4465 mBeaconMuteRefCount++;
4466 break;
4467 case STOPPING_OUTPUT:
4468 if (mBeaconMuteRefCount > 0) {
4469 mBeaconMuteRefCount--;
4470 }
4471 break;
4472 case STARTING_BEACON:
4473 mBeaconPlayingRefCount++;
4474 break;
4475 case STOPPING_BEACON:
4476 if (mBeaconPlayingRefCount > 0) {
4477 mBeaconPlayingRefCount--;
4478 }
4479 break;
4480 }
4481
4482 if (mBeaconMuteRefCount > 0) {
4483 // any playback causes beacon to be muted
4484 return setBeaconMute(true);
4485 } else {
4486 // no other playback: unmute when beacon starts playing, mute when it stops
4487 return setBeaconMute(mBeaconPlayingRefCount == 0);
4488 }
4489}
4490
4491uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
4492 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
4493 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
4494 // keep track of muted state to avoid repeating mute/unmute operations
4495 if (mBeaconMuted != mute) {
4496 // mute/unmute AUDIO_STREAM_TTS on all outputs
4497 ALOGV("\t muting %d", mute);
4498 uint32_t maxLatency = 0;
4499 for (size_t i = 0; i < mOutputs.size(); i++) {
4500 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4501 setStreamMute(AUDIO_STREAM_TTS, mute/*on*/,
4502 desc->mIoHandle,
4503 0 /*delay*/, AUDIO_DEVICE_NONE);
4504 const uint32_t latency = desc->latency() * 2;
4505 if (latency > maxLatency) {
4506 maxLatency = latency;
4507 }
4508 }
4509 mBeaconMuted = mute;
4510 return maxLatency;
4511 }
4512 return 0;
4513}
4514
Eric Laurente0720872014-03-11 09:30:41 -07004515audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07004516 bool fromCache)
4517{
4518 uint32_t device = AUDIO_DEVICE_NONE;
4519
4520 if (fromCache) {
4521 ALOGVV("getDeviceForStrategy() from cache strategy %d, device %x",
4522 strategy, mDeviceForStrategy[strategy]);
4523 return mDeviceForStrategy[strategy];
4524 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004525 audio_devices_t availableOutputDeviceTypes = mAvailableOutputDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004526 switch (strategy) {
4527
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07004528 case STRATEGY_TRANSMITTED_THROUGH_SPEAKER:
4529 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4530 if (!device) {
4531 ALOGE("getDeviceForStrategy() no device found for "\
4532 "STRATEGY_TRANSMITTED_THROUGH_SPEAKER");
4533 }
4534 break;
4535
Eric Laurente552edb2014-03-10 17:42:56 -07004536 case STRATEGY_SONIFICATION_RESPECTFUL:
4537 if (isInCall()) {
4538 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07004539 } else if (isStreamActiveRemotely(AUDIO_STREAM_MUSIC,
Eric Laurente552edb2014-03-10 17:42:56 -07004540 SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
4541 // while media is playing on a remote device, use the the sonification behavior.
4542 // Note that we test this usecase before testing if media is playing because
4543 // the isStreamActive() method only informs about the activity of a stream, not
4544 // if it's for local playback. Note also that we use the same delay between both tests
4545 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004546 //user "safe" speaker if available instead of normal speaker to avoid triggering
4547 //other acoustic safety mechanisms for notification
4548 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4549 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurent3b73df72014-03-11 09:06:29 -07004550 } else if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004551 // while media is playing (or has recently played), use the same device
4552 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4553 } else {
4554 // when media is not playing anymore, fall back on the sonification behavior
4555 device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
Jon Eklund11c9fb12014-06-23 14:47:03 -05004556 //user "safe" speaker if available instead of normal speaker to avoid triggering
4557 //other acoustic safety mechanisms for notification
4558 if (device == AUDIO_DEVICE_OUT_SPEAKER && (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER_SAFE))
4559 device = AUDIO_DEVICE_OUT_SPEAKER_SAFE;
Eric Laurente552edb2014-03-10 17:42:56 -07004560 }
4561
4562 break;
4563
4564 case STRATEGY_DTMF:
4565 if (!isInCall()) {
4566 // when off call, DTMF strategy follows the same rules as MEDIA strategy
4567 device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
4568 break;
4569 }
4570 // when in call, DTMF and PHONE strategies follow the same rules
4571 // FALL THROUGH
4572
4573 case STRATEGY_PHONE:
Eric Laurentc2730ba2014-07-20 15:47:07 -07004574 // Force use of only devices on primary output if:
4575 // - in call AND
4576 // - cannot route from voice call RX OR
4577 // - audio HAL version is < 3.0 and TX device is on the primary HW module
4578 if (mPhoneState == AUDIO_MODE_IN_CALL) {
Eric Laurentc73ca6e2014-12-12 14:34:22 -08004579 audio_devices_t txDevice =
4580 getDeviceAndMixForInputSource(AUDIO_SOURCE_VOICE_COMMUNICATION);
Eric Laurentc2730ba2014-07-20 15:47:07 -07004581 sp<AudioOutputDescriptor> hwOutputDesc = mOutputs.valueFor(mPrimaryOutput);
4582 if (((mAvailableInputDevices.types() &
4583 AUDIO_DEVICE_IN_TELEPHONY_RX & ~AUDIO_DEVICE_BIT_IN) == 0) ||
4584 (((txDevice & availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN) != 0) &&
Marco Nelissen961ec212014-08-25 15:58:39 -07004585 (hwOutputDesc->getAudioPort()->mModule->mHalVersion <
Eric Laurentc2730ba2014-07-20 15:47:07 -07004586 AUDIO_DEVICE_API_VERSION_3_0))) {
4587 availableOutputDeviceTypes = availablePrimaryOutputDevices();
4588 }
4589 }
Eric Laurente552edb2014-03-10 17:42:56 -07004590 // for phone strategy, we first consider the forced use and then the available devices by order
4591 // of priority
Eric Laurent3b73df72014-03-11 09:06:29 -07004592 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
4593 case AUDIO_POLICY_FORCE_BT_SCO:
Eric Laurente552edb2014-03-10 17:42:56 -07004594 if (!isInCall() || strategy != STRATEGY_DTMF) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004595 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
Eric Laurente552edb2014-03-10 17:42:56 -07004596 if (device) break;
4597 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004598 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004599 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004600 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
Eric Laurente552edb2014-03-10 17:42:56 -07004601 if (device) break;
4602 // if SCO device is requested but no SCO device is available, fall back to default case
4603 // FALL THROUGH
4604
4605 default: // FORCE_NONE
4606 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
Eric Laurent3a4311c2014-03-17 12:00:47 -07004607 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004608 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004609 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004610 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004611 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004612 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004613 if (device) break;
4614 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004615 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004616 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004617 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004618 if (device) break;
Eric Laurentc2730ba2014-07-20 15:47:07 -07004619 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
4620 if (device) break;
Eric Laurent3b73df72014-03-11 09:06:29 -07004621 if (mPhoneState != AUDIO_MODE_IN_CALL) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004622 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004623 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004624 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004625 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004626 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004627 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004628 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004629 if (device) break;
4630 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07004631 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_EARPIECE;
Eric Laurente552edb2014-03-10 17:42:56 -07004632 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004633 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004634 if (device == AUDIO_DEVICE_NONE) {
4635 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE");
4636 }
4637 break;
4638
Eric Laurent3b73df72014-03-11 09:06:29 -07004639 case AUDIO_POLICY_FORCE_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07004640 // when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
4641 // A2DP speaker when forcing to speaker output
Eric Laurent3a4311c2014-03-17 12:00:47 -07004642 if (!isInCall() &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004643 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004644 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004645 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004646 if (device) break;
4647 }
Eric Laurentcd71a692014-12-16 12:01:12 -08004648 if (!isInCall()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004649 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004650 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004651 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004652 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004653 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004654 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004655 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004656 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004657 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004658 if (device) break;
4659 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004660 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4661 if (device) break;
Eric Laurent3a4311c2014-03-17 12:00:47 -07004662 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004663 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004664 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004665 if (device == AUDIO_DEVICE_NONE) {
4666 ALOGE("getDeviceForStrategy() no device found for STRATEGY_PHONE, FORCE_SPEAKER");
4667 }
4668 break;
4669 }
4670 break;
4671
4672 case STRATEGY_SONIFICATION:
4673
4674 // If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
4675 // handleIncallSonification().
4676 if (isInCall()) {
4677 device = getDeviceForStrategy(STRATEGY_PHONE, false /*fromCache*/);
4678 break;
4679 }
4680 // FALL THROUGH
4681
4682 case STRATEGY_ENFORCED_AUDIBLE:
4683 // strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
4684 // except:
4685 // - when in call where it doesn't default to STRATEGY_PHONE behavior
4686 // - in countries where not enforced in which case it follows STRATEGY_MEDIA
4687
4688 if ((strategy == STRATEGY_SONIFICATION) ||
Eric Laurent3b73df72014-03-11 09:06:29 -07004689 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004690 device = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004691 if (device == AUDIO_DEVICE_NONE) {
4692 ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
4693 }
4694 }
4695 // The second device used for sonification is the same as the device used by media strategy
4696 // FALL THROUGH
4697
Eric Laurent223fd5c2014-11-11 13:43:36 -08004698 // FIXME: STRATEGY_ACCESSIBILITY and STRATEGY_REROUTING follow STRATEGY_MEDIA for now
4699 case STRATEGY_ACCESSIBILITY:
Eric Laurent066ceec2014-11-25 12:35:01 -08004700 if (strategy == STRATEGY_ACCESSIBILITY) {
4701 // do not route accessibility prompts to a digital output currently configured with a
4702 // compressed format as they would likely not be mixed and dropped.
4703 for (size_t i = 0; i < mOutputs.size(); i++) {
4704 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(i);
4705 audio_devices_t devices = desc->device() &
4706 (AUDIO_DEVICE_OUT_HDMI | AUDIO_DEVICE_OUT_SPDIF | AUDIO_DEVICE_OUT_HDMI_ARC);
4707 if (desc->isActive() && !audio_is_linear_pcm(desc->mFormat) &&
4708 devices != AUDIO_DEVICE_NONE) {
4709 availableOutputDeviceTypes = availableOutputDeviceTypes & ~devices;
4710 }
4711 }
4712 }
4713 // FALL THROUGH
4714
Eric Laurent223fd5c2014-11-11 13:43:36 -08004715 case STRATEGY_REROUTING:
Eric Laurente552edb2014-03-10 17:42:56 -07004716 case STRATEGY_MEDIA: {
4717 uint32_t device2 = AUDIO_DEVICE_NONE;
4718 if (strategy != STRATEGY_SONIFICATION) {
4719 // no sonification on remote submix (e.g. WFD)
Eric Laurent275e8e92014-11-30 15:14:47 -08004720 if (mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_REMOTE_SUBMIX, String8("0")) != 0) {
4721 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
4722 }
Eric Laurente552edb2014-03-10 17:42:56 -07004723 }
4724 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004725 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] != AUDIO_POLICY_FORCE_NO_BT_A2DP) &&
Eric Laurent29e6cec2014-11-13 18:17:55 -08004726 (getA2dpOutput() != 0)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004727 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
Eric Laurente552edb2014-03-10 17:42:56 -07004728 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004729 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
Eric Laurente552edb2014-03-10 17:42:56 -07004730 }
4731 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004732 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004733 }
4734 }
Hochi Huang327cb702014-09-21 09:47:31 +08004735 if ((device2 == AUDIO_DEVICE_NONE) &&
4736 (mForceUse[AUDIO_POLICY_FORCE_FOR_MEDIA] == AUDIO_POLICY_FORCE_SPEAKER)) {
4737 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
4738 }
Eric Laurente552edb2014-03-10 17:42:56 -07004739 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004740 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
Eric Laurente552edb2014-03-10 17:42:56 -07004741 }
Jon Eklundac29afa2014-07-28 16:06:06 -05004742 if ((device2 == AUDIO_DEVICE_NONE)) {
4743 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_LINE;
4744 }
Eric Laurente552edb2014-03-10 17:42:56 -07004745 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004746 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_WIRED_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004747 }
4748 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004749 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_ACCESSORY;
Eric Laurente552edb2014-03-10 17:42:56 -07004750 }
4751 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004752 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_USB_DEVICE;
Eric Laurente552edb2014-03-10 17:42:56 -07004753 }
4754 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004755 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004756 }
4757 if ((device2 == AUDIO_DEVICE_NONE) && (strategy != STRATEGY_SONIFICATION)) {
4758 // no sonification on aux digital (e.g. HDMI)
Eric Laurent3a4311c2014-03-17 12:00:47 -07004759 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_DIGITAL;
Eric Laurente552edb2014-03-10 17:42:56 -07004760 }
4761 if ((device2 == AUDIO_DEVICE_NONE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07004762 (mForceUse[AUDIO_POLICY_FORCE_FOR_DOCK] == AUDIO_POLICY_FORCE_ANALOG_DOCK)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004763 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_ANLG_DOCK_HEADSET;
Eric Laurente552edb2014-03-10 17:42:56 -07004764 }
4765 if (device2 == AUDIO_DEVICE_NONE) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07004766 device2 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurente552edb2014-03-10 17:42:56 -07004767 }
Jungshik Jang839e4f32014-06-26 17:23:40 +09004768 int device3 = AUDIO_DEVICE_NONE;
4769 if (strategy == STRATEGY_MEDIA) {
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004770 // ARC, SPDIF and AUX_LINE can co-exist with others.
Jungshik Jang0c943092014-07-08 22:11:24 +09004771 device3 = availableOutputDeviceTypes & AUDIO_DEVICE_OUT_HDMI_ARC;
4772 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_SPDIF);
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004773 device3 |= (availableOutputDeviceTypes & AUDIO_DEVICE_OUT_AUX_LINE);
Jungshik Jang839e4f32014-06-26 17:23:40 +09004774 }
Eric Laurente552edb2014-03-10 17:42:56 -07004775
Jungshik Jang839e4f32014-06-26 17:23:40 +09004776 device2 |= device3;
Eric Laurente552edb2014-03-10 17:42:56 -07004777 // device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
4778 // STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
4779 device |= device2;
Jungshik Jang839e4f32014-06-26 17:23:40 +09004780
Jungshik Jang7b24ee32014-07-15 19:38:42 +09004781 // If hdmi system audio mode is on, remove speaker out of output list.
4782 if ((strategy == STRATEGY_MEDIA) &&
4783 (mForceUse[AUDIO_POLICY_FORCE_FOR_HDMI_SYSTEM_AUDIO] ==
4784 AUDIO_POLICY_FORCE_HDMI_SYSTEM_AUDIO_ENFORCED)) {
4785 device &= ~AUDIO_DEVICE_OUT_SPEAKER;
4786 }
4787
Eric Laurente552edb2014-03-10 17:42:56 -07004788 if (device) break;
Eric Laurent1c333e22014-05-20 10:48:17 -07004789 device = mDefaultOutputDevice->mDeviceType;
Eric Laurente552edb2014-03-10 17:42:56 -07004790 if (device == AUDIO_DEVICE_NONE) {
4791 ALOGE("getDeviceForStrategy() no device found for STRATEGY_MEDIA");
4792 }
4793 } break;
4794
4795 default:
4796 ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
4797 break;
4798 }
4799
4800 ALOGVV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
4801 return device;
4802}
4803
Eric Laurente0720872014-03-11 09:30:41 -07004804void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07004805{
4806 for (int i = 0; i < NUM_STRATEGIES; i++) {
4807 mDeviceForStrategy[i] = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
4808 }
4809 mPreviousOutputs = mOutputs;
4810}
4811
Eric Laurent1f2f2232014-06-02 12:01:23 -07004812uint32_t AudioPolicyManager::checkDeviceMuteStrategies(sp<AudioOutputDescriptor> outputDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07004813 audio_devices_t prevDevice,
4814 uint32_t delayMs)
4815{
4816 // mute/unmute strategies using an incompatible device combination
4817 // if muting, wait for the audio in pcm buffer to be drained before proceeding
4818 // if unmuting, unmute only after the specified delay
4819 if (outputDesc->isDuplicated()) {
4820 return 0;
4821 }
4822
4823 uint32_t muteWaitMs = 0;
4824 audio_devices_t device = outputDesc->device();
Eric Laurent3b73df72014-03-11 09:06:29 -07004825 bool shouldMute = outputDesc->isActive() && (popcount(device) >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07004826
4827 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4828 audio_devices_t curDevice = getDeviceForStrategy((routing_strategy)i, false /*fromCache*/);
Eric Laurent31551f82014-10-10 18:21:56 -07004829 curDevice = curDevice & outputDesc->mProfile->mSupportedDevices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07004830 bool mute = shouldMute && (curDevice & device) && (curDevice != device);
4831 bool doMute = false;
4832
4833 if (mute && !outputDesc->mStrategyMutedByDevice[i]) {
4834 doMute = true;
4835 outputDesc->mStrategyMutedByDevice[i] = true;
4836 } else if (!mute && outputDesc->mStrategyMutedByDevice[i]){
4837 doMute = true;
4838 outputDesc->mStrategyMutedByDevice[i] = false;
4839 }
Eric Laurent99401132014-05-07 19:48:15 -07004840 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07004841 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004842 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07004843 // skip output if it does not share any device with current output
4844 if ((desc->supportedDevices() & outputDesc->supportedDevices())
4845 == AUDIO_DEVICE_NONE) {
4846 continue;
4847 }
4848 audio_io_handle_t curOutput = mOutputs.keyAt(j);
4849 ALOGVV("checkDeviceMuteStrategies() %s strategy %d (curDevice %04x) on output %d",
4850 mute ? "muting" : "unmuting", i, curDevice, curOutput);
4851 setStrategyMute((routing_strategy)i, mute, curOutput, mute ? 0 : delayMs);
4852 if (desc->isStrategyActive((routing_strategy)i)) {
Eric Laurent99401132014-05-07 19:48:15 -07004853 if (mute) {
4854 // FIXME: should not need to double latency if volume could be applied
4855 // immediately by the audioflinger mixer. We must account for the delay
4856 // between now and the next time the audioflinger thread for this output
4857 // will process a buffer (which corresponds to one buffer size,
4858 // usually 1/2 or 1/4 of the latency).
4859 if (muteWaitMs < desc->latency() * 2) {
4860 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07004861 }
4862 }
4863 }
4864 }
4865 }
4866 }
4867
Eric Laurent99401132014-05-07 19:48:15 -07004868 // temporary mute output if device selection changes to avoid volume bursts due to
4869 // different per device volumes
4870 if (outputDesc->isActive() && (device != prevDevice)) {
4871 if (muteWaitMs < outputDesc->latency() * 2) {
4872 muteWaitMs = outputDesc->latency() * 2;
4873 }
4874 for (size_t i = 0; i < NUM_STRATEGIES; i++) {
4875 if (outputDesc->isStrategyActive((routing_strategy)i)) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004876 setStrategyMute((routing_strategy)i, true, outputDesc->mIoHandle);
Eric Laurent99401132014-05-07 19:48:15 -07004877 // do tempMute unmute after twice the mute wait time
Eric Laurent1c333e22014-05-20 10:48:17 -07004878 setStrategyMute((routing_strategy)i, false, outputDesc->mIoHandle,
Eric Laurent99401132014-05-07 19:48:15 -07004879 muteWaitMs *2, device);
4880 }
4881 }
4882 }
4883
Eric Laurente552edb2014-03-10 17:42:56 -07004884 // wait for the PCM output buffers to empty before proceeding with the rest of the command
4885 if (muteWaitMs > delayMs) {
4886 muteWaitMs -= delayMs;
4887 usleep(muteWaitMs * 1000);
4888 return muteWaitMs;
4889 }
4890 return 0;
4891}
4892
Eric Laurente0720872014-03-11 09:30:41 -07004893uint32_t AudioPolicyManager::setOutputDevice(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07004894 audio_devices_t device,
4895 bool force,
Eric Laurent6a94d692014-05-20 11:18:06 -07004896 int delayMs,
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004897 audio_patch_handle_t *patchHandle,
4898 const char* address)
Eric Laurente552edb2014-03-10 17:42:56 -07004899{
4900 ALOGV("setOutputDevice() output %d device %04x delayMs %d", output, device, delayMs);
Eric Laurent1f2f2232014-06-02 12:01:23 -07004901 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07004902 AudioParameter param;
4903 uint32_t muteWaitMs;
4904
4905 if (outputDesc->isDuplicated()) {
Eric Laurent1c333e22014-05-20 10:48:17 -07004906 muteWaitMs = setOutputDevice(outputDesc->mOutput1->mIoHandle, device, force, delayMs);
4907 muteWaitMs += setOutputDevice(outputDesc->mOutput2->mIoHandle, device, force, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07004908 return muteWaitMs;
4909 }
4910 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
4911 // output profile
4912 if ((device != AUDIO_DEVICE_NONE) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07004913 ((device & outputDesc->mProfile->mSupportedDevices.types()) == 0)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004914 return 0;
4915 }
4916
4917 // filter devices according to output selected
Eric Laurent3a4311c2014-03-17 12:00:47 -07004918 device = (audio_devices_t)(device & outputDesc->mProfile->mSupportedDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07004919
4920 audio_devices_t prevDevice = outputDesc->mDevice;
4921
4922 ALOGV("setOutputDevice() prevDevice %04x", prevDevice);
4923
4924 if (device != AUDIO_DEVICE_NONE) {
4925 outputDesc->mDevice = device;
4926 }
4927 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevice, delayMs);
4928
4929 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07004930 // the requested device is AUDIO_DEVICE_NONE
4931 // OR the requested device is the same as current device
4932 // AND force is not specified
4933 // AND the output is connected by a valid audio patch.
Eric Laurente552edb2014-03-10 17:42:56 -07004934 // Doing this check here allows the caller to call setOutputDevice() without conditions
Eric Laurentb80a2a82014-10-27 16:07:59 -07004935 if ((device == AUDIO_DEVICE_NONE || device == prevDevice) && !force &&
4936 outputDesc->mPatchHandle != 0) {
4937 ALOGV("setOutputDevice() setting same device %04x or null device for output %d",
4938 device, output);
Eric Laurente552edb2014-03-10 17:42:56 -07004939 return muteWaitMs;
4940 }
4941
4942 ALOGV("setOutputDevice() changing device");
Eric Laurent1c333e22014-05-20 10:48:17 -07004943
Eric Laurente552edb2014-03-10 17:42:56 -07004944 // do the routing
Eric Laurent1c333e22014-05-20 10:48:17 -07004945 if (device == AUDIO_DEVICE_NONE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004946 resetOutputDevice(output, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07004947 } else {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07004948 DeviceVector deviceList = (address == NULL) ?
4949 mAvailableOutputDevices.getDevicesFromType(device)
4950 : mAvailableOutputDevices.getDevicesFromTypeAddr(device, String8(address));
Eric Laurent1c333e22014-05-20 10:48:17 -07004951 if (!deviceList.isEmpty()) {
4952 struct audio_patch patch;
4953 outputDesc->toAudioPortConfig(&patch.sources[0]);
4954 patch.num_sources = 1;
4955 patch.num_sinks = 0;
4956 for (size_t i = 0; i < deviceList.size() && i < AUDIO_PATCH_PORTS_MAX; i++) {
4957 deviceList.itemAt(i)->toAudioPortConfig(&patch.sinks[i]);
Eric Laurent1c333e22014-05-20 10:48:17 -07004958 patch.num_sinks++;
4959 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004960 ssize_t index;
4961 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
4962 index = mAudioPatches.indexOfKey(*patchHandle);
4963 } else {
4964 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
4965 }
4966 sp< AudioPatch> patchDesc;
4967 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
4968 if (index >= 0) {
4969 patchDesc = mAudioPatches.valueAt(index);
4970 afPatchHandle = patchDesc->mAfPatchHandle;
4971 }
4972
Eric Laurent1c333e22014-05-20 10:48:17 -07004973 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07004974 &afPatchHandle,
4975 delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07004976 ALOGV("setOutputDevice() createAudioPatch returned %d patchHandle %d"
4977 "num_sources %d num_sinks %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07004978 status, afPatchHandle, patch.num_sources, patch.num_sinks);
Eric Laurent1c333e22014-05-20 10:48:17 -07004979 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004980 if (index < 0) {
4981 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
4982 &patch, mUidCached);
4983 addAudioPatch(patchDesc->mHandle, patchDesc);
4984 } else {
4985 patchDesc->mPatch = patch;
4986 }
4987 patchDesc->mAfPatchHandle = afPatchHandle;
4988 patchDesc->mUid = mUidCached;
4989 if (patchHandle) {
4990 *patchHandle = patchDesc->mHandle;
4991 }
4992 outputDesc->mPatchHandle = patchDesc->mHandle;
4993 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004994 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07004995 }
4996 }
bryant_liuf5e7e792014-08-19 20:07:05 +08004997
4998 // inform all input as well
4999 for (size_t i = 0; i < mInputs.size(); i++) {
5000 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
5001 if (!isVirtualInputDevice(inputDescriptor->mDevice)) {
5002 AudioParameter inputCmd = AudioParameter();
5003 ALOGV("%s: inform input %d of device:%d", __func__,
5004 inputDescriptor->mIoHandle, device);
5005 inputCmd.addInt(String8(AudioParameter::keyRouting),device);
5006 mpClientInterface->setParameters(inputDescriptor->mIoHandle,
5007 inputCmd.toString(),
5008 delayMs);
5009 }
5010 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005011 }
Eric Laurente552edb2014-03-10 17:42:56 -07005012
5013 // update stream volumes according to new device
5014 applyStreamVolumes(output, device, delayMs);
5015
5016 return muteWaitMs;
5017}
5018
Eric Laurent1c333e22014-05-20 10:48:17 -07005019status_t AudioPolicyManager::resetOutputDevice(audio_io_handle_t output,
Eric Laurent6a94d692014-05-20 11:18:06 -07005020 int delayMs,
5021 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005022{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005023 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent6a94d692014-05-20 11:18:06 -07005024 ssize_t index;
5025 if (patchHandle) {
5026 index = mAudioPatches.indexOfKey(*patchHandle);
5027 } else {
5028 index = mAudioPatches.indexOfKey(outputDesc->mPatchHandle);
5029 }
5030 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005031 return INVALID_OPERATION;
5032 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005033 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5034 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07005035 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
5036 outputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07005037 removeAudioPatch(patchDesc->mHandle);
5038 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005039 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005040 return status;
5041}
5042
5043status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
5044 audio_devices_t device,
Eric Laurent6a94d692014-05-20 11:18:06 -07005045 bool force,
5046 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005047{
5048 status_t status = NO_ERROR;
5049
Eric Laurent1f2f2232014-06-02 12:01:23 -07005050 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent1c333e22014-05-20 10:48:17 -07005051 if ((device != AUDIO_DEVICE_NONE) && ((device != inputDesc->mDevice) || force)) {
5052 inputDesc->mDevice = device;
5053
5054 DeviceVector deviceList = mAvailableInputDevices.getDevicesFromType(device);
5055 if (!deviceList.isEmpty()) {
5056 struct audio_patch patch;
5057 inputDesc->toAudioPortConfig(&patch.sinks[0]);
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005058 // AUDIO_SOURCE_HOTWORD is for internal use only:
5059 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005060 if (patch.sinks[0].ext.mix.usecase.source == AUDIO_SOURCE_HOTWORD &&
5061 !inputDesc->mIsSoundTrigger) {
Eric Laurentdaf92cc2014-07-22 15:36:10 -07005062 patch.sinks[0].ext.mix.usecase.source = AUDIO_SOURCE_VOICE_RECOGNITION;
5063 }
Eric Laurent1c333e22014-05-20 10:48:17 -07005064 patch.num_sinks = 1;
5065 //only one input device for now
5066 deviceList.itemAt(0)->toAudioPortConfig(&patch.sources[0]);
Eric Laurent1c333e22014-05-20 10:48:17 -07005067 patch.num_sources = 1;
Eric Laurent6a94d692014-05-20 11:18:06 -07005068 ssize_t index;
5069 if (patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE) {
5070 index = mAudioPatches.indexOfKey(*patchHandle);
5071 } else {
5072 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5073 }
5074 sp< AudioPatch> patchDesc;
5075 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
5076 if (index >= 0) {
5077 patchDesc = mAudioPatches.valueAt(index);
5078 afPatchHandle = patchDesc->mAfPatchHandle;
5079 }
5080
Eric Laurent1c333e22014-05-20 10:48:17 -07005081 status_t status = mpClientInterface->createAudioPatch(&patch,
Eric Laurent6a94d692014-05-20 11:18:06 -07005082 &afPatchHandle,
Eric Laurent1c333e22014-05-20 10:48:17 -07005083 0);
5084 ALOGV("setInputDevice() createAudioPatch returned %d patchHandle %d",
Eric Laurent6a94d692014-05-20 11:18:06 -07005085 status, afPatchHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07005086 if (status == NO_ERROR) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005087 if (index < 0) {
5088 patchDesc = new AudioPatch((audio_patch_handle_t)nextUniqueId(),
5089 &patch, mUidCached);
5090 addAudioPatch(patchDesc->mHandle, patchDesc);
5091 } else {
5092 patchDesc->mPatch = patch;
5093 }
5094 patchDesc->mAfPatchHandle = afPatchHandle;
5095 patchDesc->mUid = mUidCached;
5096 if (patchHandle) {
5097 *patchHandle = patchDesc->mHandle;
5098 }
5099 inputDesc->mPatchHandle = patchDesc->mHandle;
5100 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005101 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005102 }
5103 }
5104 }
5105 return status;
5106}
5107
Eric Laurent6a94d692014-05-20 11:18:06 -07005108status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
5109 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07005110{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005111 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07005112 ssize_t index;
5113 if (patchHandle) {
5114 index = mAudioPatches.indexOfKey(*patchHandle);
5115 } else {
5116 index = mAudioPatches.indexOfKey(inputDesc->mPatchHandle);
5117 }
5118 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005119 return INVALID_OPERATION;
5120 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005121 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
5122 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->mAfPatchHandle, 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07005123 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
5124 inputDesc->mPatchHandle = 0;
Eric Laurent6a94d692014-05-20 11:18:06 -07005125 removeAudioPatch(patchDesc->mHandle);
5126 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005127 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07005128 return status;
5129}
5130
5131sp<AudioPolicyManager::IOProfile> AudioPolicyManager::getInputProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08005132 String8 address,
Glenn Kastencbd48022014-07-24 13:46:44 -07005133 uint32_t& samplingRate,
Eric Laurente552edb2014-03-10 17:42:56 -07005134 audio_format_t format,
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005135 audio_channel_mask_t channelMask,
Glenn Kastencbd48022014-07-24 13:46:44 -07005136 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07005137{
5138 // Choose an input profile based on the requested capture parameters: select the first available
5139 // profile supporting all requested parameters.
5140
5141 for (size_t i = 0; i < mHwModules.size(); i++)
5142 {
5143 if (mHwModules[i]->mHandle == 0) {
5144 continue;
5145 }
5146 for (size_t j = 0; j < mHwModules[i]->mInputProfiles.size(); j++)
5147 {
Eric Laurent1c333e22014-05-20 10:48:17 -07005148 sp<IOProfile> profile = mHwModules[i]->mInputProfiles[j];
Eric Laurentd4692962014-05-05 18:13:44 -07005149 // profile->log();
Eric Laurent275e8e92014-11-30 15:14:47 -08005150 if (profile->isCompatibleProfile(device, address, samplingRate,
Glenn Kastencbd48022014-07-24 13:46:44 -07005151 &samplingRate /*updatedSamplingRate*/,
5152 format, channelMask, (audio_output_flags_t) flags)) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005153
Eric Laurente552edb2014-03-10 17:42:56 -07005154 return profile;
5155 }
5156 }
5157 }
5158 return NULL;
5159}
5160
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005161
5162audio_devices_t AudioPolicyManager::getDeviceAndMixForInputSource(audio_source_t inputSource,
Eric Laurentc722f302014-12-10 11:21:49 -08005163 AudioMix **policyMix)
Eric Laurente552edb2014-03-10 17:42:56 -07005164{
Eric Laurent3a4311c2014-03-17 12:00:47 -07005165 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5166 ~AUDIO_DEVICE_BIT_IN;
Eric Laurent275e8e92014-11-30 15:14:47 -08005167
5168 for (size_t i = 0; i < mPolicyMixes.size(); i++) {
5169 if (mPolicyMixes[i]->mMix.mMixType != MIX_TYPE_RECORDERS) {
5170 continue;
5171 }
5172 for (size_t j = 0; j < mPolicyMixes[i]->mMix.mCriteria.size(); j++) {
5173 if ((RULE_MATCH_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5174 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource == inputSource) ||
5175 (RULE_EXCLUDE_ATTRIBUTE_CAPTURE_PRESET == mPolicyMixes[i]->mMix.mCriteria[j].mRule &&
5176 mPolicyMixes[i]->mMix.mCriteria[j].mAttr.mSource != inputSource)) {
5177 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurentc722f302014-12-10 11:21:49 -08005178 if (policyMix != NULL) {
5179 *policyMix = &mPolicyMixes[i]->mMix;
Eric Laurent275e8e92014-11-30 15:14:47 -08005180 }
5181 return AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5182 }
5183 break;
5184 }
5185 }
5186 }
5187
Eric Laurentc73ca6e2014-12-12 14:34:22 -08005188 return getDeviceForInputSource(inputSource);
5189}
5190
5191audio_devices_t AudioPolicyManager::getDeviceForInputSource(audio_source_t inputSource)
5192{
5193 uint32_t device = AUDIO_DEVICE_NONE;
5194 audio_devices_t availableDeviceTypes = mAvailableInputDevices.types() &
5195 ~AUDIO_DEVICE_BIT_IN;
5196
Eric Laurente552edb2014-03-10 17:42:56 -07005197 switch (inputSource) {
5198 case AUDIO_SOURCE_VOICE_UPLINK:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005199 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005200 device = AUDIO_DEVICE_IN_VOICE_CALL;
5201 break;
5202 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005203 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005204
5205 case AUDIO_SOURCE_DEFAULT:
5206 case AUDIO_SOURCE_MIC:
Mike Lockwood41b0e242014-05-13 15:23:35 -07005207 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_A2DP) {
5208 device = AUDIO_DEVICE_IN_BLUETOOTH_A2DP;
Eric Laurentdc136ff2014-12-16 12:24:18 -08005209 } else if ((mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO) &&
5210 (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET)) {
5211 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurentc2730ba2014-07-20 15:47:07 -07005212 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5213 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5214 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5215 device = AUDIO_DEVICE_IN_USB_DEVICE;
5216 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5217 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005218 }
Eric Laurentc2730ba2014-07-20 15:47:07 -07005219 break;
5220
5221 case AUDIO_SOURCE_VOICE_COMMUNICATION:
5222 // Allow only use of devices on primary input if in call and HAL does not support routing
5223 // to voice call path.
5224 if ((mPhoneState == AUDIO_MODE_IN_CALL) &&
5225 (mAvailableOutputDevices.types() & AUDIO_DEVICE_OUT_TELEPHONY_TX) == 0) {
5226 availableDeviceTypes = availablePrimaryInputDevices() & ~AUDIO_DEVICE_BIT_IN;
5227 }
5228
5229 switch (mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]) {
5230 case AUDIO_POLICY_FORCE_BT_SCO:
5231 // if SCO device is requested but no SCO device is available, fall back to default case
5232 if (availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
5233 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
5234 break;
5235 }
5236 // FALL THROUGH
5237
5238 default: // FORCE_NONE
5239 if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
5240 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
5241 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5242 device = AUDIO_DEVICE_IN_USB_DEVICE;
5243 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5244 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5245 }
5246 break;
5247
5248 case AUDIO_POLICY_FORCE_SPEAKER:
5249 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
5250 device = AUDIO_DEVICE_IN_BACK_MIC;
5251 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
5252 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5253 }
5254 break;
5255 }
5256 break;
Mike Lockwood41b0e242014-05-13 15:23:35 -07005257
Eric Laurente552edb2014-03-10 17:42:56 -07005258 case AUDIO_SOURCE_VOICE_RECOGNITION:
5259 case AUDIO_SOURCE_HOTWORD:
Eric Laurent3b73df72014-03-11 09:06:29 -07005260 if (mForceUse[AUDIO_POLICY_FORCE_FOR_RECORD] == AUDIO_POLICY_FORCE_BT_SCO &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07005261 availableDeviceTypes & AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005262 device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005263 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_WIRED_HEADSET) {
Eric Laurente552edb2014-03-10 17:42:56 -07005264 device = AUDIO_DEVICE_IN_WIRED_HEADSET;
Eric Laurentd4692962014-05-05 18:13:44 -07005265 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_USB_DEVICE) {
5266 device = AUDIO_DEVICE_IN_USB_DEVICE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005267 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005268 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5269 }
5270 break;
5271 case AUDIO_SOURCE_CAMCORDER:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005272 if (availableDeviceTypes & AUDIO_DEVICE_IN_BACK_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005273 device = AUDIO_DEVICE_IN_BACK_MIC;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005274 } else if (availableDeviceTypes & AUDIO_DEVICE_IN_BUILTIN_MIC) {
Eric Laurente552edb2014-03-10 17:42:56 -07005275 device = AUDIO_DEVICE_IN_BUILTIN_MIC;
5276 }
5277 break;
5278 case AUDIO_SOURCE_VOICE_DOWNLINK:
5279 case AUDIO_SOURCE_VOICE_CALL:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005280 if (availableDeviceTypes & AUDIO_DEVICE_IN_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005281 device = AUDIO_DEVICE_IN_VOICE_CALL;
5282 }
5283 break;
5284 case AUDIO_SOURCE_REMOTE_SUBMIX:
Eric Laurent3a4311c2014-03-17 12:00:47 -07005285 if (availableDeviceTypes & AUDIO_DEVICE_IN_REMOTE_SUBMIX) {
Eric Laurente552edb2014-03-10 17:42:56 -07005286 device = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
5287 }
5288 break;
Hochi Huang327cb702014-09-21 09:47:31 +08005289 case AUDIO_SOURCE_FM_TUNER:
5290 if (availableDeviceTypes & AUDIO_DEVICE_IN_FM_TUNER) {
5291 device = AUDIO_DEVICE_IN_FM_TUNER;
5292 }
5293 break;
Eric Laurente552edb2014-03-10 17:42:56 -07005294 default:
5295 ALOGW("getDeviceForInputSource() invalid input source %d", inputSource);
5296 break;
5297 }
5298 ALOGV("getDeviceForInputSource()input source %d, device %08x", inputSource, device);
5299 return device;
5300}
5301
Eric Laurente0720872014-03-11 09:30:41 -07005302bool AudioPolicyManager::isVirtualInputDevice(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005303{
5304 if ((device & AUDIO_DEVICE_BIT_IN) != 0) {
5305 device &= ~AUDIO_DEVICE_BIT_IN;
5306 if ((popcount(device) == 1) && ((device & ~APM_AUDIO_IN_DEVICE_VIRTUAL_ALL) == 0))
5307 return true;
5308 }
5309 return false;
5310}
5311
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005312bool AudioPolicyManager::deviceDistinguishesOnAddress(audio_devices_t device) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005313 return ((device & APM_AUDIO_DEVICE_MATCH_ADDRESS_ALL & ~AUDIO_DEVICE_BIT_IN) != 0);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005314}
5315
Eric Laurente0720872014-03-11 09:30:41 -07005316audio_io_handle_t AudioPolicyManager::getActiveInput(bool ignoreVirtualInputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005317{
5318 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005319 const sp<AudioInputDescriptor> input_descriptor = mInputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07005320 if ((input_descriptor->mRefCount > 0)
5321 && (!ignoreVirtualInputs || !isVirtualInputDevice(input_descriptor->mDevice))) {
5322 return mInputs.keyAt(i);
5323 }
5324 }
5325 return 0;
5326}
5327
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005328uint32_t AudioPolicyManager::activeInputsCount() const
5329{
5330 uint32_t count = 0;
5331 for (size_t i = 0; i < mInputs.size(); i++) {
5332 const sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
5333 if (desc->mRefCount > 0) {
Eric Laurenta34c9ce2014-12-19 11:16:32 -08005334 count++;
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005335 }
5336 }
5337 return count;
5338}
5339
Eric Laurente552edb2014-03-10 17:42:56 -07005340
Eric Laurente0720872014-03-11 09:30:41 -07005341audio_devices_t AudioPolicyManager::getDeviceForVolume(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005342{
5343 if (device == AUDIO_DEVICE_NONE) {
5344 // this happens when forcing a route update and no track is active on an output.
5345 // In this case the returned category is not important.
5346 device = AUDIO_DEVICE_OUT_SPEAKER;
Eric Laurent3b73df72014-03-11 09:06:29 -07005347 } else if (popcount(device) > 1) {
Eric Laurente552edb2014-03-10 17:42:56 -07005348 // Multiple device selection is either:
5349 // - speaker + one other device: give priority to speaker in this case.
5350 // - one A2DP device + another device: happens with duplicated output. In this case
5351 // retain the device on the A2DP output as the other must not correspond to an active
5352 // selection if not the speaker.
Jungshik Janga1f99172014-09-05 21:25:48 +09005353 // - HDMI-CEC system audio mode only output: give priority to available item in order.
Eric Laurente552edb2014-03-10 17:42:56 -07005354 if (device & AUDIO_DEVICE_OUT_SPEAKER) {
5355 device = AUDIO_DEVICE_OUT_SPEAKER;
Jungshik Janga1f99172014-09-05 21:25:48 +09005356 } else if (device & AUDIO_DEVICE_OUT_HDMI_ARC) {
5357 device = AUDIO_DEVICE_OUT_HDMI_ARC;
5358 } else if (device & AUDIO_DEVICE_OUT_AUX_LINE) {
5359 device = AUDIO_DEVICE_OUT_AUX_LINE;
5360 } else if (device & AUDIO_DEVICE_OUT_SPDIF) {
5361 device = AUDIO_DEVICE_OUT_SPDIF;
Eric Laurente552edb2014-03-10 17:42:56 -07005362 } else {
5363 device = (audio_devices_t)(device & AUDIO_DEVICE_OUT_ALL_A2DP);
5364 }
5365 }
5366
Jon Eklund11c9fb12014-06-23 14:47:03 -05005367 /*SPEAKER_SAFE is an alias of SPEAKER for purposes of volume control*/
5368 if (device == AUDIO_DEVICE_OUT_SPEAKER_SAFE)
5369 device = AUDIO_DEVICE_OUT_SPEAKER;
5370
Eric Laurent3b73df72014-03-11 09:06:29 -07005371 ALOGW_IF(popcount(device) != 1,
Eric Laurente552edb2014-03-10 17:42:56 -07005372 "getDeviceForVolume() invalid device combination: %08x",
5373 device);
5374
5375 return device;
5376}
5377
Eric Laurente0720872014-03-11 09:30:41 -07005378AudioPolicyManager::device_category AudioPolicyManager::getDeviceCategory(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07005379{
5380 switch(getDeviceForVolume(device)) {
5381 case AUDIO_DEVICE_OUT_EARPIECE:
5382 return DEVICE_CATEGORY_EARPIECE;
5383 case AUDIO_DEVICE_OUT_WIRED_HEADSET:
5384 case AUDIO_DEVICE_OUT_WIRED_HEADPHONE:
5385 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO:
5386 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET:
5387 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
5388 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES:
5389 return DEVICE_CATEGORY_HEADSET;
Jon Eklundac29afa2014-07-28 16:06:06 -05005390 case AUDIO_DEVICE_OUT_LINE:
5391 case AUDIO_DEVICE_OUT_AUX_DIGITAL:
5392 /*USB? Remote submix?*/
5393 return DEVICE_CATEGORY_EXT_MEDIA;
Eric Laurente552edb2014-03-10 17:42:56 -07005394 case AUDIO_DEVICE_OUT_SPEAKER:
5395 case AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT:
5396 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER:
Eric Laurente552edb2014-03-10 17:42:56 -07005397 case AUDIO_DEVICE_OUT_USB_ACCESSORY:
5398 case AUDIO_DEVICE_OUT_USB_DEVICE:
5399 case AUDIO_DEVICE_OUT_REMOTE_SUBMIX:
5400 default:
5401 return DEVICE_CATEGORY_SPEAKER;
5402 }
5403}
5404
Eric Laurent223fd5c2014-11-11 13:43:36 -08005405/* static */
Eric Laurente0720872014-03-11 09:30:41 -07005406float AudioPolicyManager::volIndexToAmpl(audio_devices_t device, const StreamDescriptor& streamDesc,
Eric Laurente552edb2014-03-10 17:42:56 -07005407 int indexInUi)
5408{
5409 device_category deviceCategory = getDeviceCategory(device);
5410 const VolumeCurvePoint *curve = streamDesc.mVolumeCurve[deviceCategory];
5411
5412 // the volume index in the UI is relative to the min and max volume indices for this stream type
5413 int nbSteps = 1 + curve[VOLMAX].mIndex -
5414 curve[VOLMIN].mIndex;
5415 int volIdx = (nbSteps * (indexInUi - streamDesc.mIndexMin)) /
5416 (streamDesc.mIndexMax - streamDesc.mIndexMin);
5417
5418 // find what part of the curve this index volume belongs to, or if it's out of bounds
5419 int segment = 0;
5420 if (volIdx < curve[VOLMIN].mIndex) { // out of bounds
5421 return 0.0f;
5422 } else if (volIdx < curve[VOLKNEE1].mIndex) {
5423 segment = 0;
5424 } else if (volIdx < curve[VOLKNEE2].mIndex) {
5425 segment = 1;
5426 } else if (volIdx <= curve[VOLMAX].mIndex) {
5427 segment = 2;
5428 } else { // out of bounds
5429 return 1.0f;
5430 }
5431
5432 // linear interpolation in the attenuation table in dB
5433 float decibels = curve[segment].mDBAttenuation +
5434 ((float)(volIdx - curve[segment].mIndex)) *
5435 ( (curve[segment+1].mDBAttenuation -
5436 curve[segment].mDBAttenuation) /
5437 ((float)(curve[segment+1].mIndex -
5438 curve[segment].mIndex)) );
5439
5440 float amplification = exp( decibels * 0.115129f); // exp( dB * ln(10) / 20 )
5441
5442 ALOGVV("VOLUME vol index=[%d %d %d], dB=[%.1f %.1f %.1f] ampl=%.5f",
5443 curve[segment].mIndex, volIdx,
5444 curve[segment+1].mIndex,
5445 curve[segment].mDBAttenuation,
5446 decibels,
5447 curve[segment+1].mDBAttenuation,
5448 amplification);
5449
5450 return amplification;
5451}
5452
Eric Laurente0720872014-03-11 09:30:41 -07005453const AudioPolicyManager::VolumeCurvePoint
5454 AudioPolicyManager::sDefaultVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005455 {1, -49.5f}, {33, -33.5f}, {66, -17.0f}, {100, 0.0f}
5456};
5457
Eric Laurente0720872014-03-11 09:30:41 -07005458const AudioPolicyManager::VolumeCurvePoint
5459 AudioPolicyManager::sDefaultMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005460 {1, -58.0f}, {20, -40.0f}, {60, -17.0f}, {100, 0.0f}
5461};
5462
Eric Laurente0720872014-03-11 09:30:41 -07005463const AudioPolicyManager::VolumeCurvePoint
Jon Eklundac29afa2014-07-28 16:06:06 -05005464 AudioPolicyManager::sExtMediaSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
5465 {1, -58.0f}, {20, -40.0f}, {60, -21.0f}, {100, -10.0f}
5466};
5467
5468const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005469 AudioPolicyManager::sSpeakerMediaVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005470 {1, -56.0f}, {20, -34.0f}, {60, -11.0f}, {100, 0.0f}
5471};
5472
Eric Laurente0720872014-03-11 09:30:41 -07005473const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005474 AudioPolicyManager::sSpeakerMediaVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Jean-Michel Trivi98c60432014-07-09 08:51:34 -07005475 {1, -55.0f}, {20, -43.0f}, {86, -12.0f}, {100, 0.0f}
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005476};
5477
5478const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005479 AudioPolicyManager::sSpeakerSonificationVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005480 {1, -29.7f}, {33, -20.1f}, {66, -10.2f}, {100, 0.0f}
5481};
5482
Eric Laurente0720872014-03-11 09:30:41 -07005483const AudioPolicyManager::VolumeCurvePoint
5484 AudioPolicyManager::sSpeakerSonificationVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005485 {1, -35.7f}, {33, -26.1f}, {66, -13.2f}, {100, 0.0f}
5486};
5487
5488// AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE and AUDIO_STREAM_DTMF volume tracks
5489// AUDIO_STREAM_RING on phones and AUDIO_STREAM_MUSIC on tablets.
5490// AUDIO_STREAM_DTMF tracks AUDIO_STREAM_VOICE_CALL while in call (See AudioService.java).
5491// The range is constrained between -24dB and -6dB over speaker and -30dB and -18dB over headset.
5492
Eric Laurente0720872014-03-11 09:30:41 -07005493const AudioPolicyManager::VolumeCurvePoint
5494 AudioPolicyManager::sDefaultSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005495 {1, -24.0f}, {33, -18.0f}, {66, -12.0f}, {100, -6.0f}
5496};
5497
Eric Laurente0720872014-03-11 09:30:41 -07005498const AudioPolicyManager::VolumeCurvePoint
5499 AudioPolicyManager::sDefaultSystemVolumeCurveDrc[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005500 {1, -34.0f}, {33, -24.0f}, {66, -15.0f}, {100, -6.0f}
5501};
5502
Eric Laurente0720872014-03-11 09:30:41 -07005503const AudioPolicyManager::VolumeCurvePoint
5504 AudioPolicyManager::sHeadsetSystemVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005505 {1, -30.0f}, {33, -26.0f}, {66, -22.0f}, {100, -18.0f}
5506};
5507
Eric Laurente0720872014-03-11 09:30:41 -07005508const AudioPolicyManager::VolumeCurvePoint
5509 AudioPolicyManager::sDefaultVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005510 {0, -42.0f}, {33, -28.0f}, {66, -14.0f}, {100, 0.0f}
5511};
5512
Eric Laurente0720872014-03-11 09:30:41 -07005513const AudioPolicyManager::VolumeCurvePoint
5514 AudioPolicyManager::sSpeakerVoiceVolumeCurve[AudioPolicyManager::VOLCNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005515 {0, -24.0f}, {33, -16.0f}, {66, -8.0f}, {100, 0.0f}
5516};
5517
Eric Laurente0720872014-03-11 09:30:41 -07005518const AudioPolicyManager::VolumeCurvePoint
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005519 AudioPolicyManager::sLinearVolumeCurve[AudioPolicyManager::VOLCNT] = {
5520 {0, -96.0f}, {33, -68.0f}, {66, -34.0f}, {100, 0.0f}
5521};
5522
5523const AudioPolicyManager::VolumeCurvePoint
5524 AudioPolicyManager::sSilentVolumeCurve[AudioPolicyManager::VOLCNT] = {
5525 {0, -96.0f}, {1, -96.0f}, {2, -96.0f}, {100, -96.0f}
5526};
5527
5528const AudioPolicyManager::VolumeCurvePoint
Eric Laurent223fd5c2014-11-11 13:43:36 -08005529 AudioPolicyManager::sFullScaleVolumeCurve[AudioPolicyManager::VOLCNT] = {
5530 {0, 0.0f}, {1, 0.0f}, {2, 0.0f}, {100, 0.0f}
5531};
5532
5533const AudioPolicyManager::VolumeCurvePoint
Eric Laurente0720872014-03-11 09:30:41 -07005534 *AudioPolicyManager::sVolumeProfiles[AUDIO_STREAM_CNT]
5535 [AudioPolicyManager::DEVICE_CATEGORY_CNT] = {
Eric Laurente552edb2014-03-10 17:42:56 -07005536 { // AUDIO_STREAM_VOICE_CALL
5537 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5538 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005539 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5540 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005541 },
5542 { // AUDIO_STREAM_SYSTEM
5543 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5544 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005545 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5546 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005547 },
5548 { // AUDIO_STREAM_RING
5549 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5550 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005551 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5552 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005553 },
5554 { // AUDIO_STREAM_MUSIC
5555 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5556 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005557 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5558 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005559 },
5560 { // AUDIO_STREAM_ALARM
5561 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5562 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005563 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5564 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005565 },
5566 { // AUDIO_STREAM_NOTIFICATION
5567 sDefaultVolumeCurve, // DEVICE_CATEGORY_HEADSET
5568 sSpeakerSonificationVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005569 sDefaultVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5570 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005571 },
5572 { // AUDIO_STREAM_BLUETOOTH_SCO
5573 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_HEADSET
5574 sSpeakerVoiceVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005575 sDefaultVoiceVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5576 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005577 },
5578 { // AUDIO_STREAM_ENFORCED_AUDIBLE
5579 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5580 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005581 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5582 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005583 },
5584 { // AUDIO_STREAM_DTMF
5585 sHeadsetSystemVolumeCurve, // DEVICE_CATEGORY_HEADSET
5586 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_SPEAKER
Jon Eklundac29afa2014-07-28 16:06:06 -05005587 sDefaultSystemVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5588 sExtMediaSystemVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005589 },
5590 { // AUDIO_STREAM_TTS
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005591 // "Transmitted Through Speaker": always silent except on DEVICE_CATEGORY_SPEAKER
5592 sSilentVolumeCurve, // DEVICE_CATEGORY_HEADSET
5593 sLinearVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5594 sSilentVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5595 sSilentVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
Eric Laurente552edb2014-03-10 17:42:56 -07005596 },
Eric Laurent223fd5c2014-11-11 13:43:36 -08005597 { // AUDIO_STREAM_ACCESSIBILITY
5598 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_HEADSET
5599 sSpeakerMediaVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5600 sDefaultMediaVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5601 sDefaultMediaVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5602 },
5603 { // AUDIO_STREAM_REROUTING
5604 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5605 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5606 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5607 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5608 },
5609 { // AUDIO_STREAM_PATCH
5610 sFullScaleVolumeCurve, // DEVICE_CATEGORY_HEADSET
5611 sFullScaleVolumeCurve, // DEVICE_CATEGORY_SPEAKER
5612 sFullScaleVolumeCurve, // DEVICE_CATEGORY_EARPIECE
5613 sFullScaleVolumeCurve // DEVICE_CATEGORY_EXT_MEDIA
5614 },
Eric Laurente552edb2014-03-10 17:42:56 -07005615};
5616
Eric Laurente0720872014-03-11 09:30:41 -07005617void AudioPolicyManager::initializeVolumeCurves()
Eric Laurente552edb2014-03-10 17:42:56 -07005618{
5619 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
5620 for (int j = 0; j < DEVICE_CATEGORY_CNT; j++) {
5621 mStreams[i].mVolumeCurve[j] =
5622 sVolumeProfiles[i][j];
5623 }
5624 }
5625
5626 // Check availability of DRC on speaker path: if available, override some of the speaker curves
5627 if (mSpeakerDrcEnabled) {
5628 mStreams[AUDIO_STREAM_SYSTEM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5629 sDefaultSystemVolumeCurveDrc;
5630 mStreams[AUDIO_STREAM_RING].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5631 sSpeakerSonificationVolumeCurveDrc;
5632 mStreams[AUDIO_STREAM_ALARM].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5633 sSpeakerSonificationVolumeCurveDrc;
5634 mStreams[AUDIO_STREAM_NOTIFICATION].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5635 sSpeakerSonificationVolumeCurveDrc;
Jean-Michel Triviccd8e4a2014-06-05 15:33:20 -07005636 mStreams[AUDIO_STREAM_MUSIC].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5637 sSpeakerMediaVolumeCurveDrc;
Eric Laurent223fd5c2014-11-11 13:43:36 -08005638 mStreams[AUDIO_STREAM_ACCESSIBILITY].mVolumeCurve[DEVICE_CATEGORY_SPEAKER] =
5639 sSpeakerMediaVolumeCurveDrc;
Eric Laurente552edb2014-03-10 17:42:56 -07005640 }
5641}
5642
Eric Laurente0720872014-03-11 09:30:41 -07005643float AudioPolicyManager::computeVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005644 int index,
5645 audio_io_handle_t output,
5646 audio_devices_t device)
5647{
5648 float volume = 1.0;
Eric Laurent1f2f2232014-06-02 12:01:23 -07005649 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005650 StreamDescriptor &streamDesc = mStreams[stream];
5651
5652 if (device == AUDIO_DEVICE_NONE) {
5653 device = outputDesc->device();
5654 }
5655
Eric Laurente552edb2014-03-10 17:42:56 -07005656 volume = volIndexToAmpl(device, streamDesc, index);
5657
5658 // if a headset is connected, apply the following rules to ring tones and notifications
5659 // to avoid sound level bursts in user's ears:
5660 // - always attenuate ring tones and notifications volume by 6dB
5661 // - if music is playing, always limit the volume to current music volume,
5662 // with a minimum threshold at -36dB so that notification is always perceived.
Eric Laurent3b73df72014-03-11 09:06:29 -07005663 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005664 if ((device & (AUDIO_DEVICE_OUT_BLUETOOTH_A2DP |
5665 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES |
5666 AUDIO_DEVICE_OUT_WIRED_HEADSET |
5667 AUDIO_DEVICE_OUT_WIRED_HEADPHONE)) &&
5668 ((stream_strategy == STRATEGY_SONIFICATION)
5669 || (stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL)
Eric Laurent3b73df72014-03-11 09:06:29 -07005670 || (stream == AUDIO_STREAM_SYSTEM)
Eric Laurente552edb2014-03-10 17:42:56 -07005671 || ((stream_strategy == STRATEGY_ENFORCED_AUDIBLE) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005672 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) &&
Eric Laurente552edb2014-03-10 17:42:56 -07005673 streamDesc.mCanBeMuted) {
5674 volume *= SONIFICATION_HEADSET_VOLUME_FACTOR;
5675 // when the phone is ringing we must consider that music could have been paused just before
5676 // by the music application and behave as if music was active if the last music track was
5677 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07005678 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07005679 mLimitRingtoneVolume) {
5680 audio_devices_t musicDevice = getDeviceForStrategy(STRATEGY_MEDIA, true /*fromCache*/);
Eric Laurent3b73df72014-03-11 09:06:29 -07005681 float musicVol = computeVolume(AUDIO_STREAM_MUSIC,
5682 mStreams[AUDIO_STREAM_MUSIC].getVolumeIndex(musicDevice),
Eric Laurente552edb2014-03-10 17:42:56 -07005683 output,
5684 musicDevice);
5685 float minVol = (musicVol > SONIFICATION_HEADSET_VOLUME_MIN) ?
5686 musicVol : SONIFICATION_HEADSET_VOLUME_MIN;
5687 if (volume > minVol) {
5688 volume = minVol;
5689 ALOGV("computeVolume limiting volume to %f musicVol %f", minVol, musicVol);
5690 }
5691 }
5692 }
5693
5694 return volume;
5695}
5696
Eric Laurente0720872014-03-11 09:30:41 -07005697status_t AudioPolicyManager::checkAndSetVolume(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005698 int index,
5699 audio_io_handle_t output,
5700 audio_devices_t device,
5701 int delayMs,
5702 bool force)
5703{
5704
5705 // do not change actual stream volume if the stream is muted
5706 if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
5707 ALOGVV("checkAndSetVolume() stream %d muted count %d",
5708 stream, mOutputs.valueFor(output)->mMuteCount[stream]);
5709 return NO_ERROR;
5710 }
5711
5712 // do not change in call volume if bluetooth is connected and vice versa
Eric Laurent3b73df72014-03-11 09:06:29 -07005713 if ((stream == AUDIO_STREAM_VOICE_CALL &&
5714 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] == AUDIO_POLICY_FORCE_BT_SCO) ||
5715 (stream == AUDIO_STREAM_BLUETOOTH_SCO &&
5716 mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION] != AUDIO_POLICY_FORCE_BT_SCO)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005717 ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
Eric Laurent3b73df72014-03-11 09:06:29 -07005718 stream, mForceUse[AUDIO_POLICY_FORCE_FOR_COMMUNICATION]);
Eric Laurente552edb2014-03-10 17:42:56 -07005719 return INVALID_OPERATION;
5720 }
5721
5722 float volume = computeVolume(stream, index, output, device);
Eric Laurent275e8e92014-11-30 15:14:47 -08005723 // unit gain if rerouting to external policy
5724 if (device == AUDIO_DEVICE_OUT_REMOTE_SUBMIX) {
5725 ssize_t index = mOutputs.indexOfKey(output);
5726 if (index >= 0) {
5727 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(index);
Eric Laurentc722f302014-12-10 11:21:49 -08005728 if (outputDesc->mPolicyMix != NULL) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005729 ALOGV("max gain when rerouting for output=%d", output);
5730 volume = 1.0f;
5731 }
5732 }
5733
5734 }
Eric Laurente552edb2014-03-10 17:42:56 -07005735 // We actually change the volume if:
5736 // - the float value returned by computeVolume() changed
5737 // - the force flag is set
5738 if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
5739 force) {
5740 mOutputs.valueFor(output)->mCurVolume[stream] = volume;
5741 ALOGVV("checkAndSetVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
5742 // Force VOICE_CALL to track BLUETOOTH_SCO stream volume when bluetooth audio is
5743 // enabled
Eric Laurent3b73df72014-03-11 09:06:29 -07005744 if (stream == AUDIO_STREAM_BLUETOOTH_SCO) {
5745 mpClientInterface->setStreamVolume(AUDIO_STREAM_VOICE_CALL, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005746 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005747 mpClientInterface->setStreamVolume(stream, volume, output, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07005748 }
5749
Eric Laurent3b73df72014-03-11 09:06:29 -07005750 if (stream == AUDIO_STREAM_VOICE_CALL ||
5751 stream == AUDIO_STREAM_BLUETOOTH_SCO) {
Eric Laurente552edb2014-03-10 17:42:56 -07005752 float voiceVolume;
5753 // Force voice volume to max for bluetooth SCO as volume is managed by the headset
Eric Laurent3b73df72014-03-11 09:06:29 -07005754 if (stream == AUDIO_STREAM_VOICE_CALL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005755 voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
5756 } else {
5757 voiceVolume = 1.0;
5758 }
5759
5760 if (voiceVolume != mLastVoiceVolume && output == mPrimaryOutput) {
5761 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
5762 mLastVoiceVolume = voiceVolume;
5763 }
5764 }
5765
5766 return NO_ERROR;
5767}
5768
Eric Laurente0720872014-03-11 09:30:41 -07005769void AudioPolicyManager::applyStreamVolumes(audio_io_handle_t output,
Eric Laurente552edb2014-03-10 17:42:56 -07005770 audio_devices_t device,
5771 int delayMs,
5772 bool force)
5773{
5774 ALOGVV("applyStreamVolumes() for output %d and device %x", output, device);
5775
Eric Laurent3b73df72014-03-11 09:06:29 -07005776 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005777 if (stream == AUDIO_STREAM_PATCH) {
5778 continue;
5779 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005780 checkAndSetVolume((audio_stream_type_t)stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005781 mStreams[stream].getVolumeIndex(device),
5782 output,
5783 device,
5784 delayMs,
5785 force);
5786 }
5787}
5788
Eric Laurente0720872014-03-11 09:30:41 -07005789void AudioPolicyManager::setStrategyMute(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07005790 bool on,
5791 audio_io_handle_t output,
5792 int delayMs,
5793 audio_devices_t device)
5794{
5795 ALOGVV("setStrategyMute() strategy %d, mute %d, output %d", strategy, on, output);
Eric Laurent3b73df72014-03-11 09:06:29 -07005796 for (int stream = 0; stream < AUDIO_STREAM_CNT; stream++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08005797 if (stream == AUDIO_STREAM_PATCH) {
5798 continue;
5799 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005800 if (getStrategy((audio_stream_type_t)stream) == strategy) {
5801 setStreamMute((audio_stream_type_t)stream, on, output, delayMs, device);
Eric Laurente552edb2014-03-10 17:42:56 -07005802 }
5803 }
5804}
5805
Eric Laurente0720872014-03-11 09:30:41 -07005806void AudioPolicyManager::setStreamMute(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07005807 bool on,
5808 audio_io_handle_t output,
5809 int delayMs,
5810 audio_devices_t device)
5811{
5812 StreamDescriptor &streamDesc = mStreams[stream];
Eric Laurent1f2f2232014-06-02 12:01:23 -07005813 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005814 if (device == AUDIO_DEVICE_NONE) {
5815 device = outputDesc->device();
5816 }
5817
5818 ALOGVV("setStreamMute() stream %d, mute %d, output %d, mMuteCount %d device %04x",
5819 stream, on, output, outputDesc->mMuteCount[stream], device);
5820
5821 if (on) {
5822 if (outputDesc->mMuteCount[stream] == 0) {
5823 if (streamDesc.mCanBeMuted &&
Eric Laurent3b73df72014-03-11 09:06:29 -07005824 ((stream != AUDIO_STREAM_ENFORCED_AUDIBLE) ||
5825 (mForceUse[AUDIO_POLICY_FORCE_FOR_SYSTEM] == AUDIO_POLICY_FORCE_NONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07005826 checkAndSetVolume(stream, 0, output, device, delayMs);
5827 }
5828 }
5829 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not ignored
5830 outputDesc->mMuteCount[stream]++;
5831 } else {
5832 if (outputDesc->mMuteCount[stream] == 0) {
5833 ALOGV("setStreamMute() unmuting non muted stream!");
5834 return;
5835 }
5836 if (--outputDesc->mMuteCount[stream] == 0) {
5837 checkAndSetVolume(stream,
5838 streamDesc.getVolumeIndex(device),
5839 output,
5840 device,
5841 delayMs);
5842 }
5843 }
5844}
5845
Eric Laurente0720872014-03-11 09:30:41 -07005846void AudioPolicyManager::handleIncallSonification(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005847 bool starting, bool stateChange)
Eric Laurente552edb2014-03-10 17:42:56 -07005848{
5849 // if the stream pertains to sonification strategy and we are in call we must
5850 // mute the stream if it is low visibility. If it is high visibility, we must play a tone
5851 // in the device used for phone strategy and play the tone if the selected device does not
5852 // interfere with the device used for phone strategy
5853 // if stateChange is true, we are called from setPhoneState() and we must mute or unmute as
5854 // many times as there are active tracks on the output
Eric Laurent3b73df72014-03-11 09:06:29 -07005855 const routing_strategy stream_strategy = getStrategy(stream);
Eric Laurente552edb2014-03-10 17:42:56 -07005856 if ((stream_strategy == STRATEGY_SONIFICATION) ||
5857 ((stream_strategy == STRATEGY_SONIFICATION_RESPECTFUL))) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07005858 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(mPrimaryOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005859 ALOGV("handleIncallSonification() stream %d starting %d device %x stateChange %d",
5860 stream, starting, outputDesc->mDevice, stateChange);
5861 if (outputDesc->mRefCount[stream]) {
5862 int muteCount = 1;
5863 if (stateChange) {
5864 muteCount = outputDesc->mRefCount[stream];
5865 }
Eric Laurent3b73df72014-03-11 09:06:29 -07005866 if (audio_is_low_visibility(stream)) {
Eric Laurente552edb2014-03-10 17:42:56 -07005867 ALOGV("handleIncallSonification() low visibility, muteCount %d", muteCount);
5868 for (int i = 0; i < muteCount; i++) {
5869 setStreamMute(stream, starting, mPrimaryOutput);
5870 }
5871 } else {
5872 ALOGV("handleIncallSonification() high visibility");
5873 if (outputDesc->device() &
5874 getDeviceForStrategy(STRATEGY_PHONE, true /*fromCache*/)) {
5875 ALOGV("handleIncallSonification() high visibility muted, muteCount %d", muteCount);
5876 for (int i = 0; i < muteCount; i++) {
5877 setStreamMute(stream, starting, mPrimaryOutput);
5878 }
5879 }
5880 if (starting) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005881 mpClientInterface->startTone(AUDIO_POLICY_TONE_IN_CALL_NOTIFICATION,
5882 AUDIO_STREAM_VOICE_CALL);
Eric Laurente552edb2014-03-10 17:42:56 -07005883 } else {
5884 mpClientInterface->stopTone();
5885 }
5886 }
5887 }
5888 }
5889}
5890
Eric Laurente0720872014-03-11 09:30:41 -07005891bool AudioPolicyManager::isInCall()
Eric Laurente552edb2014-03-10 17:42:56 -07005892{
5893 return isStateInCall(mPhoneState);
5894}
5895
Eric Laurente0720872014-03-11 09:30:41 -07005896bool AudioPolicyManager::isStateInCall(int state) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005897 return ((state == AUDIO_MODE_IN_CALL) ||
5898 (state == AUDIO_MODE_IN_COMMUNICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07005899}
5900
Eric Laurente0720872014-03-11 09:30:41 -07005901uint32_t AudioPolicyManager::getMaxEffectsCpuLoad()
Eric Laurente552edb2014-03-10 17:42:56 -07005902{
5903 return MAX_EFFECTS_CPU_LOAD;
5904}
5905
Eric Laurente0720872014-03-11 09:30:41 -07005906uint32_t AudioPolicyManager::getMaxEffectsMemory()
Eric Laurente552edb2014-03-10 17:42:56 -07005907{
5908 return MAX_EFFECTS_MEMORY;
5909}
5910
Eric Laurent6a94d692014-05-20 11:18:06 -07005911
Eric Laurente552edb2014-03-10 17:42:56 -07005912// --- AudioOutputDescriptor class implementation
5913
Eric Laurente0720872014-03-11 09:30:41 -07005914AudioPolicyManager::AudioOutputDescriptor::AudioOutputDescriptor(
Eric Laurent1c333e22014-05-20 10:48:17 -07005915 const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07005916 : mId(0), mIoHandle(0), mLatency(0),
Eric Laurentc722f302014-12-10 11:21:49 -08005917 mFlags((audio_output_flags_t)0), mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL),
Eric Laurent275e8e92014-11-30 15:14:47 -08005918 mPatchHandle(0),
Eric Laurente552edb2014-03-10 17:42:56 -07005919 mOutput1(0), mOutput2(0), mProfile(profile), mDirectOpenCount(0)
5920{
5921 // clear usage count for all stream types
Eric Laurent3b73df72014-03-11 09:06:29 -07005922 for (int i = 0; i < AUDIO_STREAM_CNT; i++) {
Eric Laurente552edb2014-03-10 17:42:56 -07005923 mRefCount[i] = 0;
5924 mCurVolume[i] = -1.0;
5925 mMuteCount[i] = 0;
5926 mStopTime[i] = 0;
5927 }
5928 for (int i = 0; i < NUM_STRATEGIES; i++) {
5929 mStrategyMutedByDevice[i] = false;
5930 }
5931 if (profile != NULL) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07005932 mFlags = (audio_output_flags_t)profile->mFlags;
Eric Laurent1e693b52014-07-09 15:03:28 -07005933 mSamplingRate = profile->pickSamplingRate();
5934 mFormat = profile->pickFormat();
5935 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07005936 if (profile->mGains.size() > 0) {
5937 profile->mGains[0]->getDefaultConfig(&mGain);
5938 }
Eric Laurente552edb2014-03-10 17:42:56 -07005939 }
5940}
5941
Eric Laurente0720872014-03-11 09:30:41 -07005942audio_devices_t AudioPolicyManager::AudioOutputDescriptor::device() const
Eric Laurente552edb2014-03-10 17:42:56 -07005943{
5944 if (isDuplicated()) {
5945 return (audio_devices_t)(mOutput1->mDevice | mOutput2->mDevice);
5946 } else {
5947 return mDevice;
5948 }
5949}
5950
Eric Laurente0720872014-03-11 09:30:41 -07005951uint32_t AudioPolicyManager::AudioOutputDescriptor::latency()
Eric Laurente552edb2014-03-10 17:42:56 -07005952{
5953 if (isDuplicated()) {
5954 return (mOutput1->mLatency > mOutput2->mLatency) ? mOutput1->mLatency : mOutput2->mLatency;
5955 } else {
5956 return mLatency;
5957 }
5958}
5959
Eric Laurente0720872014-03-11 09:30:41 -07005960bool AudioPolicyManager::AudioOutputDescriptor::sharesHwModuleWith(
Eric Laurent1f2f2232014-06-02 12:01:23 -07005961 const sp<AudioOutputDescriptor> outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005962{
5963 if (isDuplicated()) {
5964 return mOutput1->sharesHwModuleWith(outputDesc) || mOutput2->sharesHwModuleWith(outputDesc);
5965 } else if (outputDesc->isDuplicated()){
5966 return sharesHwModuleWith(outputDesc->mOutput1) || sharesHwModuleWith(outputDesc->mOutput2);
5967 } else {
5968 return (mProfile->mModule == outputDesc->mProfile->mModule);
5969 }
5970}
5971
Eric Laurente0720872014-03-11 09:30:41 -07005972void AudioPolicyManager::AudioOutputDescriptor::changeRefCount(audio_stream_type_t stream,
Eric Laurent3b73df72014-03-11 09:06:29 -07005973 int delta)
Eric Laurente552edb2014-03-10 17:42:56 -07005974{
5975 // forward usage count change to attached outputs
5976 if (isDuplicated()) {
5977 mOutput1->changeRefCount(stream, delta);
5978 mOutput2->changeRefCount(stream, delta);
5979 }
5980 if ((delta + (int)mRefCount[stream]) < 0) {
Eric Laurent3b73df72014-03-11 09:06:29 -07005981 ALOGW("changeRefCount() invalid delta %d for stream %d, refCount %d",
5982 delta, stream, mRefCount[stream]);
Eric Laurente552edb2014-03-10 17:42:56 -07005983 mRefCount[stream] = 0;
5984 return;
5985 }
5986 mRefCount[stream] += delta;
5987 ALOGV("changeRefCount() stream %d, count %d", stream, mRefCount[stream]);
5988}
5989
Eric Laurente0720872014-03-11 09:30:41 -07005990audio_devices_t AudioPolicyManager::AudioOutputDescriptor::supportedDevices()
Eric Laurente552edb2014-03-10 17:42:56 -07005991{
5992 if (isDuplicated()) {
5993 return (audio_devices_t)(mOutput1->supportedDevices() | mOutput2->supportedDevices());
5994 } else {
Eric Laurent3a4311c2014-03-17 12:00:47 -07005995 return mProfile->mSupportedDevices.types() ;
Eric Laurente552edb2014-03-10 17:42:56 -07005996 }
5997}
5998
Eric Laurente0720872014-03-11 09:30:41 -07005999bool AudioPolicyManager::AudioOutputDescriptor::isActive(uint32_t inPastMs) const
Eric Laurente552edb2014-03-10 17:42:56 -07006000{
6001 return isStrategyActive(NUM_STRATEGIES, inPastMs);
6002}
6003
Eric Laurente0720872014-03-11 09:30:41 -07006004bool AudioPolicyManager::AudioOutputDescriptor::isStrategyActive(routing_strategy strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07006005 uint32_t inPastMs,
6006 nsecs_t sysTime) const
6007{
6008 if ((sysTime == 0) && (inPastMs != 0)) {
6009 sysTime = systemTime();
6010 }
Eric Laurent3b73df72014-03-11 09:06:29 -07006011 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
Eric Laurent223fd5c2014-11-11 13:43:36 -08006012 if (i == AUDIO_STREAM_PATCH) {
6013 continue;
6014 }
Eric Laurent3b73df72014-03-11 09:06:29 -07006015 if (((getStrategy((audio_stream_type_t)i) == strategy) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006016 (NUM_STRATEGIES == strategy)) &&
Eric Laurent3b73df72014-03-11 09:06:29 -07006017 isStreamActive((audio_stream_type_t)i, inPastMs, sysTime)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006018 return true;
6019 }
6020 }
6021 return false;
6022}
6023
Eric Laurente0720872014-03-11 09:30:41 -07006024bool AudioPolicyManager::AudioOutputDescriptor::isStreamActive(audio_stream_type_t stream,
Eric Laurente552edb2014-03-10 17:42:56 -07006025 uint32_t inPastMs,
6026 nsecs_t sysTime) const
6027{
6028 if (mRefCount[stream] != 0) {
6029 return true;
6030 }
6031 if (inPastMs == 0) {
6032 return false;
6033 }
6034 if (sysTime == 0) {
6035 sysTime = systemTime();
6036 }
6037 if (ns2ms(sysTime - mStopTime[stream]) < inPastMs) {
6038 return true;
6039 }
6040 return false;
6041}
6042
Eric Laurent1c333e22014-05-20 10:48:17 -07006043void AudioPolicyManager::AudioOutputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07006044 struct audio_port_config *dstConfig,
6045 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006046{
Eric Laurent84c70242014-06-23 08:46:27 -07006047 ALOG_ASSERT(!isDuplicated(), "toAudioPortConfig() called on duplicated output %d", mIoHandle);
6048
Eric Laurent1f2f2232014-06-02 12:01:23 -07006049 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
6050 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
6051 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006052 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006053 }
6054 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6055
Eric Laurent6a94d692014-05-20 11:18:06 -07006056 dstConfig->id = mId;
6057 dstConfig->role = AUDIO_PORT_ROLE_SOURCE;
6058 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent6a94d692014-05-20 11:18:06 -07006059 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
6060 dstConfig->ext.mix.handle = mIoHandle;
6061 dstConfig->ext.mix.usecase.stream = AUDIO_STREAM_DEFAULT;
Eric Laurent1c333e22014-05-20 10:48:17 -07006062}
6063
6064void AudioPolicyManager::AudioOutputDescriptor::toAudioPort(
6065 struct audio_port *port) const
6066{
Eric Laurent84c70242014-06-23 08:46:27 -07006067 ALOG_ASSERT(!isDuplicated(), "toAudioPort() called on duplicated output %d", mIoHandle);
Eric Laurent1c333e22014-05-20 10:48:17 -07006068 mProfile->toAudioPort(port);
6069 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006070 toAudioPortConfig(&port->active_config);
6071 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006072 port->ext.mix.handle = mIoHandle;
6073 port->ext.mix.latency_class =
6074 mFlags & AUDIO_OUTPUT_FLAG_FAST ? AUDIO_LATENCY_LOW : AUDIO_LATENCY_NORMAL;
6075}
Eric Laurente552edb2014-03-10 17:42:56 -07006076
Eric Laurente0720872014-03-11 09:30:41 -07006077status_t AudioPolicyManager::AudioOutputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006078{
6079 const size_t SIZE = 256;
6080 char buffer[SIZE];
6081 String8 result;
6082
Eric Laurent4d416952014-08-10 14:07:09 -07006083 snprintf(buffer, SIZE, " ID: %d\n", mId);
6084 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006085 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6086 result.append(buffer);
6087 snprintf(buffer, SIZE, " Format: %08x\n", mFormat);
6088 result.append(buffer);
6089 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6090 result.append(buffer);
6091 snprintf(buffer, SIZE, " Latency: %d\n", mLatency);
6092 result.append(buffer);
6093 snprintf(buffer, SIZE, " Flags %08x\n", mFlags);
6094 result.append(buffer);
6095 snprintf(buffer, SIZE, " Devices %08x\n", device());
6096 result.append(buffer);
6097 snprintf(buffer, SIZE, " Stream volume refCount muteCount\n");
6098 result.append(buffer);
Eric Laurent3b73df72014-03-11 09:06:29 -07006099 for (int i = 0; i < (int)AUDIO_STREAM_CNT; i++) {
6100 snprintf(buffer, SIZE, " %02d %.03f %02d %02d\n",
6101 i, mCurVolume[i], mRefCount[i], mMuteCount[i]);
Eric Laurente552edb2014-03-10 17:42:56 -07006102 result.append(buffer);
6103 }
6104 write(fd, result.string(), result.size());
6105
6106 return NO_ERROR;
6107}
6108
6109// --- AudioInputDescriptor class implementation
6110
Eric Laurent1c333e22014-05-20 10:48:17 -07006111AudioPolicyManager::AudioInputDescriptor::AudioInputDescriptor(const sp<IOProfile>& profile)
Eric Laurent1f2f2232014-06-02 12:01:23 -07006112 : mId(0), mIoHandle(0),
Eric Laurentc722f302014-12-10 11:21:49 -08006113 mDevice(AUDIO_DEVICE_NONE), mPolicyMix(NULL), mPatchHandle(0), mRefCount(0),
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006114 mInputSource(AUDIO_SOURCE_DEFAULT), mProfile(profile), mIsSoundTrigger(false)
Eric Laurente552edb2014-03-10 17:42:56 -07006115{
Eric Laurent3a4311c2014-03-17 12:00:47 -07006116 if (profile != NULL) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006117 mSamplingRate = profile->pickSamplingRate();
6118 mFormat = profile->pickFormat();
6119 mChannelMask = profile->pickChannelMask();
Eric Laurenta121f902014-06-03 13:32:54 -07006120 if (profile->mGains.size() > 0) {
6121 profile->mGains[0]->getDefaultConfig(&mGain);
6122 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006123 }
Eric Laurente552edb2014-03-10 17:42:56 -07006124}
6125
Eric Laurent1c333e22014-05-20 10:48:17 -07006126void AudioPolicyManager::AudioInputDescriptor::toAudioPortConfig(
Eric Laurent6a94d692014-05-20 11:18:06 -07006127 struct audio_port_config *dstConfig,
6128 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07006129{
Eric Laurent84c70242014-06-23 08:46:27 -07006130 ALOG_ASSERT(mProfile != 0,
6131 "toAudioPortConfig() called on input with null profile %d", mIoHandle);
Eric Laurent1f2f2232014-06-02 12:01:23 -07006132 dstConfig->config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE|AUDIO_PORT_CONFIG_CHANNEL_MASK|
6133 AUDIO_PORT_CONFIG_FORMAT|AUDIO_PORT_CONFIG_GAIN;
6134 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07006135 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07006136 }
6137
6138 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
6139
Eric Laurent6a94d692014-05-20 11:18:06 -07006140 dstConfig->id = mId;
6141 dstConfig->role = AUDIO_PORT_ROLE_SINK;
6142 dstConfig->type = AUDIO_PORT_TYPE_MIX;
Eric Laurent62aaabb2014-06-02 10:40:54 -07006143 dstConfig->ext.mix.hw_module = mProfile->mModule->mHandle;
6144 dstConfig->ext.mix.handle = mIoHandle;
6145 dstConfig->ext.mix.usecase.source = mInputSource;
Eric Laurent1c333e22014-05-20 10:48:17 -07006146}
6147
6148void AudioPolicyManager::AudioInputDescriptor::toAudioPort(
6149 struct audio_port *port) const
6150{
Eric Laurent84c70242014-06-23 08:46:27 -07006151 ALOG_ASSERT(mProfile != 0, "toAudioPort() called on input with null profile %d", mIoHandle);
6152
Eric Laurent1c333e22014-05-20 10:48:17 -07006153 mProfile->toAudioPort(port);
6154 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07006155 toAudioPortConfig(&port->active_config);
6156 port->ext.mix.hw_module = mProfile->mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07006157 port->ext.mix.handle = mIoHandle;
6158 port->ext.mix.latency_class = AUDIO_LATENCY_NORMAL;
6159}
6160
Eric Laurente0720872014-03-11 09:30:41 -07006161status_t AudioPolicyManager::AudioInputDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006162{
6163 const size_t SIZE = 256;
6164 char buffer[SIZE];
6165 String8 result;
6166
Eric Laurent4d416952014-08-10 14:07:09 -07006167 snprintf(buffer, SIZE, " ID: %d\n", mId);
6168 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006169 snprintf(buffer, SIZE, " Sampling rate: %d\n", mSamplingRate);
6170 result.append(buffer);
6171 snprintf(buffer, SIZE, " Format: %d\n", mFormat);
6172 result.append(buffer);
6173 snprintf(buffer, SIZE, " Channels: %08x\n", mChannelMask);
6174 result.append(buffer);
6175 snprintf(buffer, SIZE, " Devices %08x\n", mDevice);
6176 result.append(buffer);
6177 snprintf(buffer, SIZE, " Ref Count %d\n", mRefCount);
6178 result.append(buffer);
Glenn Kasten6a8ab052014-07-24 14:08:35 -07006179 snprintf(buffer, SIZE, " Open Ref Count %d\n", mOpenRefCount);
6180 result.append(buffer);
6181
Eric Laurente552edb2014-03-10 17:42:56 -07006182 write(fd, result.string(), result.size());
6183
6184 return NO_ERROR;
6185}
6186
6187// --- StreamDescriptor class implementation
6188
Eric Laurente0720872014-03-11 09:30:41 -07006189AudioPolicyManager::StreamDescriptor::StreamDescriptor()
Eric Laurente552edb2014-03-10 17:42:56 -07006190 : mIndexMin(0), mIndexMax(1), mCanBeMuted(true)
6191{
6192 mIndexCur.add(AUDIO_DEVICE_OUT_DEFAULT, 0);
6193}
6194
Eric Laurente0720872014-03-11 09:30:41 -07006195int AudioPolicyManager::StreamDescriptor::getVolumeIndex(audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07006196{
Eric Laurente0720872014-03-11 09:30:41 -07006197 device = AudioPolicyManager::getDeviceForVolume(device);
Eric Laurente552edb2014-03-10 17:42:56 -07006198 // there is always a valid entry for AUDIO_DEVICE_OUT_DEFAULT
6199 if (mIndexCur.indexOfKey(device) < 0) {
6200 device = AUDIO_DEVICE_OUT_DEFAULT;
6201 }
6202 return mIndexCur.valueFor(device);
6203}
6204
Eric Laurente0720872014-03-11 09:30:41 -07006205void AudioPolicyManager::StreamDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006206{
6207 const size_t SIZE = 256;
6208 char buffer[SIZE];
6209 String8 result;
6210
6211 snprintf(buffer, SIZE, "%s %02d %02d ",
6212 mCanBeMuted ? "true " : "false", mIndexMin, mIndexMax);
6213 result.append(buffer);
6214 for (size_t i = 0; i < mIndexCur.size(); i++) {
6215 snprintf(buffer, SIZE, "%04x : %02d, ",
6216 mIndexCur.keyAt(i),
6217 mIndexCur.valueAt(i));
6218 result.append(buffer);
6219 }
6220 result.append("\n");
6221
6222 write(fd, result.string(), result.size());
6223}
6224
6225// --- EffectDescriptor class implementation
6226
Eric Laurente0720872014-03-11 09:30:41 -07006227status_t AudioPolicyManager::EffectDescriptor::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006228{
6229 const size_t SIZE = 256;
6230 char buffer[SIZE];
6231 String8 result;
6232
6233 snprintf(buffer, SIZE, " I/O: %d\n", mIo);
6234 result.append(buffer);
6235 snprintf(buffer, SIZE, " Strategy: %d\n", mStrategy);
6236 result.append(buffer);
6237 snprintf(buffer, SIZE, " Session: %d\n", mSession);
6238 result.append(buffer);
6239 snprintf(buffer, SIZE, " Name: %s\n", mDesc.name);
6240 result.append(buffer);
6241 snprintf(buffer, SIZE, " %s\n", mEnabled ? "Enabled" : "Disabled");
6242 result.append(buffer);
6243 write(fd, result.string(), result.size());
6244
6245 return NO_ERROR;
6246}
6247
Eric Laurent1c333e22014-05-20 10:48:17 -07006248// --- HwModule class implementation
Eric Laurente552edb2014-03-10 17:42:56 -07006249
Eric Laurente0720872014-03-11 09:30:41 -07006250AudioPolicyManager::HwModule::HwModule(const char *name)
Eric Laurenteb108a42014-06-06 14:56:52 -07006251 : mName(strndup(name, AUDIO_HARDWARE_MODULE_ID_MAX_LEN)),
6252 mHalVersion(AUDIO_DEVICE_API_VERSION_MIN), mHandle(0)
Eric Laurente552edb2014-03-10 17:42:56 -07006253{
6254}
6255
Eric Laurente0720872014-03-11 09:30:41 -07006256AudioPolicyManager::HwModule::~HwModule()
Eric Laurente552edb2014-03-10 17:42:56 -07006257{
6258 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006259 mOutputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006260 }
6261 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006262 mInputProfiles[i]->mSupportedDevices.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006263 }
6264 free((void *)mName);
6265}
6266
Eric Laurent1afeecb2014-05-14 08:52:28 -07006267status_t AudioPolicyManager::HwModule::loadInput(cnode *root)
6268{
6269 cnode *node = root->first_child;
6270
6271 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SINK, this);
6272
6273 while (node) {
6274 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6275 profile->loadSamplingRates((char *)node->value);
6276 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6277 profile->loadFormats((char *)node->value);
6278 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6279 profile->loadInChannels((char *)node->value);
6280 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6281 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6282 mDeclaredDevices);
Eric Laurent5dbe4712014-09-19 19:04:57 -07006283 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
6284 profile->mFlags = parseInputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006285 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6286 profile->loadGains(node);
6287 }
6288 node = node->next;
6289 }
6290 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6291 "loadInput() invalid supported devices");
6292 ALOGW_IF(profile->mChannelMasks.size() == 0,
6293 "loadInput() invalid supported channel masks");
6294 ALOGW_IF(profile->mSamplingRates.size() == 0,
6295 "loadInput() invalid supported sampling rates");
6296 ALOGW_IF(profile->mFormats.size() == 0,
6297 "loadInput() invalid supported formats");
6298 if (!profile->mSupportedDevices.isEmpty() &&
6299 (profile->mChannelMasks.size() != 0) &&
6300 (profile->mSamplingRates.size() != 0) &&
6301 (profile->mFormats.size() != 0)) {
6302
6303 ALOGV("loadInput() adding input Supported Devices %04x",
6304 profile->mSupportedDevices.types());
6305
6306 mInputProfiles.add(profile);
6307 return NO_ERROR;
6308 } else {
6309 return BAD_VALUE;
6310 }
6311}
6312
6313status_t AudioPolicyManager::HwModule::loadOutput(cnode *root)
6314{
6315 cnode *node = root->first_child;
6316
6317 sp<IOProfile> profile = new IOProfile(String8(root->name), AUDIO_PORT_ROLE_SOURCE, this);
6318
6319 while (node) {
6320 if (strcmp(node->name, SAMPLING_RATES_TAG) == 0) {
6321 profile->loadSamplingRates((char *)node->value);
6322 } else if (strcmp(node->name, FORMATS_TAG) == 0) {
6323 profile->loadFormats((char *)node->value);
6324 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6325 profile->loadOutChannels((char *)node->value);
6326 } else if (strcmp(node->name, DEVICES_TAG) == 0) {
6327 profile->mSupportedDevices.loadDevicesFromName((char *)node->value,
6328 mDeclaredDevices);
6329 } else if (strcmp(node->name, FLAGS_TAG) == 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07006330 profile->mFlags = parseOutputFlagNames((char *)node->value);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006331 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6332 profile->loadGains(node);
6333 }
6334 node = node->next;
6335 }
6336 ALOGW_IF(profile->mSupportedDevices.isEmpty(),
6337 "loadOutput() invalid supported devices");
6338 ALOGW_IF(profile->mChannelMasks.size() == 0,
6339 "loadOutput() invalid supported channel masks");
6340 ALOGW_IF(profile->mSamplingRates.size() == 0,
6341 "loadOutput() invalid supported sampling rates");
6342 ALOGW_IF(profile->mFormats.size() == 0,
6343 "loadOutput() invalid supported formats");
6344 if (!profile->mSupportedDevices.isEmpty() &&
6345 (profile->mChannelMasks.size() != 0) &&
6346 (profile->mSamplingRates.size() != 0) &&
6347 (profile->mFormats.size() != 0)) {
6348
6349 ALOGV("loadOutput() adding output Supported Devices %04x, mFlags %04x",
6350 profile->mSupportedDevices.types(), profile->mFlags);
6351
6352 mOutputProfiles.add(profile);
6353 return NO_ERROR;
6354 } else {
6355 return BAD_VALUE;
6356 }
6357}
6358
6359status_t AudioPolicyManager::HwModule::loadDevice(cnode *root)
6360{
6361 cnode *node = root->first_child;
6362
6363 audio_devices_t type = AUDIO_DEVICE_NONE;
6364 while (node) {
6365 if (strcmp(node->name, DEVICE_TYPE) == 0) {
6366 type = parseDeviceNames((char *)node->value);
6367 break;
6368 }
6369 node = node->next;
6370 }
6371 if (type == AUDIO_DEVICE_NONE ||
6372 (!audio_is_input_device(type) && !audio_is_output_device(type))) {
6373 ALOGW("loadDevice() bad type %08x", type);
6374 return BAD_VALUE;
6375 }
6376 sp<DeviceDescriptor> deviceDesc = new DeviceDescriptor(String8(root->name), type);
6377 deviceDesc->mModule = this;
6378
6379 node = root->first_child;
6380 while (node) {
6381 if (strcmp(node->name, DEVICE_ADDRESS) == 0) {
6382 deviceDesc->mAddress = String8((char *)node->value);
6383 } else if (strcmp(node->name, CHANNELS_TAG) == 0) {
6384 if (audio_is_input_device(type)) {
6385 deviceDesc->loadInChannels((char *)node->value);
6386 } else {
6387 deviceDesc->loadOutChannels((char *)node->value);
6388 }
6389 } else if (strcmp(node->name, GAINS_TAG) == 0) {
6390 deviceDesc->loadGains(node);
6391 }
6392 node = node->next;
6393 }
6394
6395 ALOGV("loadDevice() adding device name %s type %08x address %s",
6396 deviceDesc->mName.string(), type, deviceDesc->mAddress.string());
6397
6398 mDeclaredDevices.add(deviceDesc);
6399
6400 return NO_ERROR;
6401}
6402
Eric Laurent275e8e92014-11-30 15:14:47 -08006403status_t AudioPolicyManager::HwModule::addOutputProfile(String8 name, const audio_config_t *config,
6404 audio_devices_t device, String8 address)
6405{
6406 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SOURCE, this);
6407
6408 profile->mSamplingRates.add(config->sample_rate);
6409 profile->mChannelMasks.add(config->channel_mask);
6410 profile->mFormats.add(config->format);
6411
6412 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6413 devDesc->mAddress = address;
6414 profile->mSupportedDevices.add(devDesc);
6415
6416 mOutputProfiles.add(profile);
6417
6418 return NO_ERROR;
6419}
6420
6421status_t AudioPolicyManager::HwModule::removeOutputProfile(String8 name)
6422{
6423 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
6424 if (mOutputProfiles[i]->mName == name) {
6425 mOutputProfiles.removeAt(i);
6426 break;
6427 }
6428 }
6429
6430 return NO_ERROR;
6431}
6432
6433status_t AudioPolicyManager::HwModule::addInputProfile(String8 name, const audio_config_t *config,
6434 audio_devices_t device, String8 address)
6435{
6436 sp<IOProfile> profile = new IOProfile(name, AUDIO_PORT_ROLE_SINK, this);
6437
6438 profile->mSamplingRates.add(config->sample_rate);
6439 profile->mChannelMasks.add(config->channel_mask);
6440 profile->mFormats.add(config->format);
6441
6442 sp<DeviceDescriptor> devDesc = new DeviceDescriptor(String8(""), device);
6443 devDesc->mAddress = address;
6444 profile->mSupportedDevices.add(devDesc);
6445
6446 ALOGV("addInputProfile() name %s rate %d mask 0x08", name.string(), config->sample_rate, config->channel_mask);
6447
6448 mInputProfiles.add(profile);
6449
6450 return NO_ERROR;
6451}
6452
6453status_t AudioPolicyManager::HwModule::removeInputProfile(String8 name)
6454{
6455 for (size_t i = 0; i < mInputProfiles.size(); i++) {
6456 if (mInputProfiles[i]->mName == name) {
6457 mInputProfiles.removeAt(i);
6458 break;
6459 }
6460 }
6461
6462 return NO_ERROR;
6463}
6464
6465
Eric Laurente0720872014-03-11 09:30:41 -07006466void AudioPolicyManager::HwModule::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07006467{
6468 const size_t SIZE = 256;
6469 char buffer[SIZE];
6470 String8 result;
6471
6472 snprintf(buffer, SIZE, " - name: %s\n", mName);
6473 result.append(buffer);
6474 snprintf(buffer, SIZE, " - handle: %d\n", mHandle);
6475 result.append(buffer);
Eric Laurenteb108a42014-06-06 14:56:52 -07006476 snprintf(buffer, SIZE, " - version: %u.%u\n", mHalVersion >> 8, mHalVersion & 0xFF);
6477 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07006478 write(fd, result.string(), result.size());
6479 if (mOutputProfiles.size()) {
6480 write(fd, " - outputs:\n", strlen(" - outputs:\n"));
6481 for (size_t i = 0; i < mOutputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006482 snprintf(buffer, SIZE, " output %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006483 write(fd, buffer, strlen(buffer));
6484 mOutputProfiles[i]->dump(fd);
6485 }
6486 }
6487 if (mInputProfiles.size()) {
6488 write(fd, " - inputs:\n", strlen(" - inputs:\n"));
6489 for (size_t i = 0; i < mInputProfiles.size(); i++) {
Eric Laurentd4692962014-05-05 18:13:44 -07006490 snprintf(buffer, SIZE, " input %zu:\n", i);
Eric Laurente552edb2014-03-10 17:42:56 -07006491 write(fd, buffer, strlen(buffer));
6492 mInputProfiles[i]->dump(fd);
6493 }
6494 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07006495 if (mDeclaredDevices.size()) {
6496 write(fd, " - devices:\n", strlen(" - devices:\n"));
6497 for (size_t i = 0; i < mDeclaredDevices.size(); i++) {
6498 mDeclaredDevices[i]->dump(fd, 4, i);
6499 }
6500 }
Eric Laurente552edb2014-03-10 17:42:56 -07006501}
6502
Eric Laurent1c333e22014-05-20 10:48:17 -07006503// --- AudioPort class implementation
6504
Eric Laurenta121f902014-06-03 13:32:54 -07006505
6506AudioPolicyManager::AudioPort::AudioPort(const String8& name, audio_port_type_t type,
6507 audio_port_role_t role, const sp<HwModule>& module) :
Eric Laurent5dbe4712014-09-19 19:04:57 -07006508 mName(name), mType(type), mRole(role), mModule(module), mFlags(0)
Eric Laurenta121f902014-06-03 13:32:54 -07006509{
6510 mUseInChannelMask = ((type == AUDIO_PORT_TYPE_DEVICE) && (role == AUDIO_PORT_ROLE_SOURCE)) ||
6511 ((type == AUDIO_PORT_TYPE_MIX) && (role == AUDIO_PORT_ROLE_SINK));
6512}
6513
Eric Laurent1c333e22014-05-20 10:48:17 -07006514void AudioPolicyManager::AudioPort::toAudioPort(struct audio_port *port) const
6515{
6516 port->role = mRole;
6517 port->type = mType;
6518 unsigned int i;
6519 for (i = 0; i < mSamplingRates.size() && i < AUDIO_PORT_MAX_SAMPLING_RATES; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006520 if (mSamplingRates[i] != 0) {
6521 port->sample_rates[i] = mSamplingRates[i];
6522 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006523 }
6524 port->num_sample_rates = i;
6525 for (i = 0; i < mChannelMasks.size() && i < AUDIO_PORT_MAX_CHANNEL_MASKS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006526 if (mChannelMasks[i] != 0) {
6527 port->channel_masks[i] = mChannelMasks[i];
6528 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006529 }
6530 port->num_channel_masks = i;
6531 for (i = 0; i < mFormats.size() && i < AUDIO_PORT_MAX_FORMATS; i++) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006532 if (mFormats[i] != 0) {
6533 port->formats[i] = mFormats[i];
6534 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006535 }
6536 port->num_formats = i;
Eric Laurente1715a42014-05-20 11:30:42 -07006537
Mark Salyzynbeb9e302014-06-18 16:33:15 -07006538 ALOGV("AudioPort::toAudioPort() num gains %zu", mGains.size());
Eric Laurente1715a42014-05-20 11:30:42 -07006539
6540 for (i = 0; i < mGains.size() && i < AUDIO_PORT_MAX_GAINS; i++) {
6541 port->gains[i] = mGains[i]->mGain;
6542 }
6543 port->num_gains = i;
Eric Laurent1c333e22014-05-20 10:48:17 -07006544}
6545
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006546void AudioPolicyManager::AudioPort::importAudioPort(const sp<AudioPort> port) {
6547 for (size_t k = 0 ; k < port->mSamplingRates.size() ; k++) {
6548 const uint32_t rate = port->mSamplingRates.itemAt(k);
6549 if (rate != 0) { // skip "dynamic" rates
6550 bool hasRate = false;
6551 for (size_t l = 0 ; l < mSamplingRates.size() ; l++) {
6552 if (rate == mSamplingRates.itemAt(l)) {
6553 hasRate = true;
6554 break;
6555 }
6556 }
6557 if (!hasRate) { // never import a sampling rate twice
6558 mSamplingRates.add(rate);
6559 }
6560 }
6561 }
6562 for (size_t k = 0 ; k < port->mChannelMasks.size() ; k++) {
6563 const audio_channel_mask_t mask = port->mChannelMasks.itemAt(k);
6564 if (mask != 0) { // skip "dynamic" masks
6565 bool hasMask = false;
6566 for (size_t l = 0 ; l < mChannelMasks.size() ; l++) {
6567 if (mask == mChannelMasks.itemAt(l)) {
6568 hasMask = true;
6569 break;
6570 }
6571 }
6572 if (!hasMask) { // never import a channel mask twice
6573 mChannelMasks.add(mask);
6574 }
6575 }
6576 }
6577 for (size_t k = 0 ; k < port->mFormats.size() ; k++) {
6578 const audio_format_t format = port->mFormats.itemAt(k);
6579 if (format != 0) { // skip "dynamic" formats
6580 bool hasFormat = false;
6581 for (size_t l = 0 ; l < mFormats.size() ; l++) {
6582 if (format == mFormats.itemAt(l)) {
6583 hasFormat = true;
6584 break;
6585 }
6586 }
6587 if (!hasFormat) { // never import a channel mask twice
6588 mFormats.add(format);
6589 }
6590 }
6591 }
Hochi Huang23fe3c02014-10-03 09:09:30 +08006592 for (size_t k = 0 ; k < port->mGains.size() ; k++) {
6593 sp<AudioGain> gain = port->mGains.itemAt(k);
6594 if (gain != 0) {
6595 bool hasGain = false;
6596 for (size_t l = 0 ; l < mGains.size() ; l++) {
6597 if (gain == mGains.itemAt(l)) {
6598 hasGain = true;
6599 break;
6600 }
6601 }
6602 if (!hasGain) { // never import a gain twice
6603 mGains.add(gain);
6604 }
6605 }
6606 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006607}
6608
6609void AudioPolicyManager::AudioPort::clearCapabilities() {
6610 mChannelMasks.clear();
6611 mFormats.clear();
6612 mSamplingRates.clear();
Hochi Huang23fe3c02014-10-03 09:09:30 +08006613 mGains.clear();
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006614}
Eric Laurent1c333e22014-05-20 10:48:17 -07006615
6616void AudioPolicyManager::AudioPort::loadSamplingRates(char *name)
6617{
6618 char *str = strtok(name, "|");
6619
6620 // by convention, "0' in the first entry in mSamplingRates indicates the supported sampling
6621 // rates should be read from the output stream after it is opened for the first time
6622 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6623 mSamplingRates.add(0);
6624 return;
6625 }
6626
6627 while (str != NULL) {
6628 uint32_t rate = atoi(str);
6629 if (rate != 0) {
6630 ALOGV("loadSamplingRates() adding rate %d", rate);
6631 mSamplingRates.add(rate);
6632 }
6633 str = strtok(NULL, "|");
6634 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006635}
6636
6637void AudioPolicyManager::AudioPort::loadFormats(char *name)
6638{
6639 char *str = strtok(name, "|");
6640
6641 // by convention, "0' in the first entry in mFormats indicates the supported formats
6642 // should be read from the output stream after it is opened for the first time
6643 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6644 mFormats.add(AUDIO_FORMAT_DEFAULT);
6645 return;
6646 }
6647
6648 while (str != NULL) {
6649 audio_format_t format = (audio_format_t)stringToEnum(sFormatNameToEnumTable,
6650 ARRAY_SIZE(sFormatNameToEnumTable),
6651 str);
6652 if (format != AUDIO_FORMAT_DEFAULT) {
6653 mFormats.add(format);
6654 }
6655 str = strtok(NULL, "|");
6656 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006657}
6658
6659void AudioPolicyManager::AudioPort::loadInChannels(char *name)
6660{
6661 const char *str = strtok(name, "|");
6662
6663 ALOGV("loadInChannels() %s", name);
6664
6665 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6666 mChannelMasks.add(0);
6667 return;
6668 }
6669
6670 while (str != NULL) {
6671 audio_channel_mask_t channelMask =
6672 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6673 ARRAY_SIZE(sInChannelsNameToEnumTable),
6674 str);
6675 if (channelMask != 0) {
6676 ALOGV("loadInChannels() adding channelMask %04x", channelMask);
6677 mChannelMasks.add(channelMask);
6678 }
6679 str = strtok(NULL, "|");
6680 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006681}
6682
6683void AudioPolicyManager::AudioPort::loadOutChannels(char *name)
6684{
6685 const char *str = strtok(name, "|");
6686
6687 ALOGV("loadOutChannels() %s", name);
6688
6689 // by convention, "0' in the first entry in mChannelMasks indicates the supported channel
6690 // masks should be read from the output stream after it is opened for the first time
6691 if (str != NULL && strcmp(str, DYNAMIC_VALUE_TAG) == 0) {
6692 mChannelMasks.add(0);
6693 return;
6694 }
6695
6696 while (str != NULL) {
6697 audio_channel_mask_t channelMask =
6698 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6699 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6700 str);
6701 if (channelMask != 0) {
6702 mChannelMasks.add(channelMask);
6703 }
6704 str = strtok(NULL, "|");
6705 }
6706 return;
6707}
6708
Eric Laurent1afeecb2014-05-14 08:52:28 -07006709audio_gain_mode_t AudioPolicyManager::AudioPort::loadGainMode(char *name)
6710{
6711 const char *str = strtok(name, "|");
6712
6713 ALOGV("loadGainMode() %s", name);
6714 audio_gain_mode_t mode = 0;
6715 while (str != NULL) {
6716 mode |= (audio_gain_mode_t)stringToEnum(sGainModeNameToEnumTable,
6717 ARRAY_SIZE(sGainModeNameToEnumTable),
6718 str);
6719 str = strtok(NULL, "|");
6720 }
6721 return mode;
6722}
6723
Eric Laurenta121f902014-06-03 13:32:54 -07006724void AudioPolicyManager::AudioPort::loadGain(cnode *root, int index)
Eric Laurent1afeecb2014-05-14 08:52:28 -07006725{
6726 cnode *node = root->first_child;
6727
Eric Laurenta121f902014-06-03 13:32:54 -07006728 sp<AudioGain> gain = new AudioGain(index, mUseInChannelMask);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006729
6730 while (node) {
6731 if (strcmp(node->name, GAIN_MODE) == 0) {
6732 gain->mGain.mode = loadGainMode((char *)node->value);
6733 } else if (strcmp(node->name, GAIN_CHANNELS) == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07006734 if (mUseInChannelMask) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07006735 gain->mGain.channel_mask =
6736 (audio_channel_mask_t)stringToEnum(sInChannelsNameToEnumTable,
6737 ARRAY_SIZE(sInChannelsNameToEnumTable),
6738 (char *)node->value);
6739 } else {
6740 gain->mGain.channel_mask =
6741 (audio_channel_mask_t)stringToEnum(sOutChannelsNameToEnumTable,
6742 ARRAY_SIZE(sOutChannelsNameToEnumTable),
6743 (char *)node->value);
6744 }
6745 } else if (strcmp(node->name, GAIN_MIN_VALUE) == 0) {
6746 gain->mGain.min_value = atoi((char *)node->value);
6747 } else if (strcmp(node->name, GAIN_MAX_VALUE) == 0) {
6748 gain->mGain.max_value = atoi((char *)node->value);
6749 } else if (strcmp(node->name, GAIN_DEFAULT_VALUE) == 0) {
6750 gain->mGain.default_value = atoi((char *)node->value);
6751 } else if (strcmp(node->name, GAIN_STEP_VALUE) == 0) {
6752 gain->mGain.step_value = atoi((char *)node->value);
6753 } else if (strcmp(node->name, GAIN_MIN_RAMP_MS) == 0) {
6754 gain->mGain.min_ramp_ms = atoi((char *)node->value);
6755 } else if (strcmp(node->name, GAIN_MAX_RAMP_MS) == 0) {
6756 gain->mGain.max_ramp_ms = atoi((char *)node->value);
6757 }
6758 node = node->next;
6759 }
6760
6761 ALOGV("loadGain() adding new gain mode %08x channel mask %08x min mB %d max mB %d",
6762 gain->mGain.mode, gain->mGain.channel_mask, gain->mGain.min_value, gain->mGain.max_value);
6763
6764 if (gain->mGain.mode == 0) {
6765 return;
6766 }
6767 mGains.add(gain);
6768}
6769
6770void AudioPolicyManager::AudioPort::loadGains(cnode *root)
6771{
6772 cnode *node = root->first_child;
Eric Laurenta121f902014-06-03 13:32:54 -07006773 int index = 0;
Eric Laurent1afeecb2014-05-14 08:52:28 -07006774 while (node) {
6775 ALOGV("loadGains() loading gain %s", node->name);
Eric Laurenta121f902014-06-03 13:32:54 -07006776 loadGain(node, index++);
Eric Laurent1afeecb2014-05-14 08:52:28 -07006777 node = node->next;
6778 }
6779}
6780
Glenn Kastencbd48022014-07-24 13:46:44 -07006781status_t AudioPolicyManager::AudioPort::checkExactSamplingRate(uint32_t samplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006782{
Eric Laurent0daea392014-12-04 19:14:54 -08006783 if (mSamplingRates.isEmpty()) {
6784 return NO_ERROR;
6785 }
6786
Eric Laurenta121f902014-06-03 13:32:54 -07006787 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6788 if (mSamplingRates[i] == samplingRate) {
6789 return NO_ERROR;
6790 }
6791 }
6792 return BAD_VALUE;
6793}
6794
Glenn Kastencbd48022014-07-24 13:46:44 -07006795status_t AudioPolicyManager::AudioPort::checkCompatibleSamplingRate(uint32_t samplingRate,
6796 uint32_t *updatedSamplingRate) const
Eric Laurenta121f902014-06-03 13:32:54 -07006797{
Eric Laurent0daea392014-12-04 19:14:54 -08006798 if (mSamplingRates.isEmpty()) {
6799 return NO_ERROR;
6800 }
6801
Glenn Kastencbd48022014-07-24 13:46:44 -07006802 // Search for the closest supported sampling rate that is above (preferred)
6803 // or below (acceptable) the desired sampling rate, within a permitted ratio.
6804 // The sampling rates do not need to be sorted in ascending order.
6805 ssize_t maxBelow = -1;
6806 ssize_t minAbove = -1;
6807 uint32_t candidate;
6808 for (size_t i = 0; i < mSamplingRates.size(); i++) {
6809 candidate = mSamplingRates[i];
6810 if (candidate == samplingRate) {
6811 if (updatedSamplingRate != NULL) {
6812 *updatedSamplingRate = candidate;
6813 }
6814 return NO_ERROR;
6815 }
6816 // candidate < desired
6817 if (candidate < samplingRate) {
6818 if (maxBelow < 0 || candidate > mSamplingRates[maxBelow]) {
6819 maxBelow = i;
6820 }
6821 // candidate > desired
6822 } else {
6823 if (minAbove < 0 || candidate < mSamplingRates[minAbove]) {
6824 minAbove = i;
6825 }
6826 }
6827 }
6828 // This uses hard-coded knowledge about AudioFlinger resampling ratios.
6829 // TODO Move these assumptions out.
6830 static const uint32_t kMaxDownSampleRatio = 6; // beyond this aliasing occurs
6831 static const uint32_t kMaxUpSampleRatio = 256; // beyond this sample rate inaccuracies occur
6832 // due to approximation by an int32_t of the
6833 // phase increments
6834 // Prefer to down-sample from a higher sampling rate, as we get the desired frequency spectrum.
6835 if (minAbove >= 0) {
6836 candidate = mSamplingRates[minAbove];
6837 if (candidate / kMaxDownSampleRatio <= samplingRate) {
6838 if (updatedSamplingRate != NULL) {
6839 *updatedSamplingRate = candidate;
6840 }
6841 return NO_ERROR;
6842 }
6843 }
6844 // But if we have to up-sample from a lower sampling rate, that's OK.
6845 if (maxBelow >= 0) {
6846 candidate = mSamplingRates[maxBelow];
6847 if (candidate * kMaxUpSampleRatio >= samplingRate) {
6848 if (updatedSamplingRate != NULL) {
6849 *updatedSamplingRate = candidate;
6850 }
6851 return NO_ERROR;
6852 }
6853 }
6854 // leave updatedSamplingRate unmodified
6855 return BAD_VALUE;
6856}
6857
6858status_t AudioPolicyManager::AudioPort::checkExactChannelMask(audio_channel_mask_t channelMask) const
6859{
Eric Laurent0daea392014-12-04 19:14:54 -08006860 if (mChannelMasks.isEmpty()) {
6861 return NO_ERROR;
6862 }
6863
Glenn Kastencbd48022014-07-24 13:46:44 -07006864 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurenta121f902014-06-03 13:32:54 -07006865 if (mChannelMasks[i] == channelMask) {
6866 return NO_ERROR;
6867 }
6868 }
6869 return BAD_VALUE;
6870}
6871
Glenn Kastencbd48022014-07-24 13:46:44 -07006872status_t AudioPolicyManager::AudioPort::checkCompatibleChannelMask(audio_channel_mask_t channelMask)
6873 const
6874{
Eric Laurent0daea392014-12-04 19:14:54 -08006875 if (mChannelMasks.isEmpty()) {
6876 return NO_ERROR;
6877 }
6878
Glenn Kastencbd48022014-07-24 13:46:44 -07006879 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
6880 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6881 // FIXME Does not handle multi-channel automatic conversions yet
6882 audio_channel_mask_t supported = mChannelMasks[i];
6883 if (supported == channelMask) {
6884 return NO_ERROR;
6885 }
6886 if (isRecordThread) {
6887 // This uses hard-coded knowledge that AudioFlinger can silently down-mix and up-mix.
6888 // FIXME Abstract this out to a table.
6889 if (((supported == AUDIO_CHANNEL_IN_FRONT_BACK || supported == AUDIO_CHANNEL_IN_STEREO)
6890 && channelMask == AUDIO_CHANNEL_IN_MONO) ||
6891 (supported == AUDIO_CHANNEL_IN_MONO && (channelMask == AUDIO_CHANNEL_IN_FRONT_BACK
6892 || channelMask == AUDIO_CHANNEL_IN_STEREO))) {
6893 return NO_ERROR;
6894 }
6895 }
6896 }
6897 return BAD_VALUE;
6898}
6899
Eric Laurenta121f902014-06-03 13:32:54 -07006900status_t AudioPolicyManager::AudioPort::checkFormat(audio_format_t format) const
6901{
Eric Laurent0daea392014-12-04 19:14:54 -08006902 if (mFormats.isEmpty()) {
6903 return NO_ERROR;
6904 }
6905
Eric Laurenta121f902014-06-03 13:32:54 -07006906 for (size_t i = 0; i < mFormats.size(); i ++) {
6907 if (mFormats[i] == format) {
6908 return NO_ERROR;
6909 }
6910 }
6911 return BAD_VALUE;
6912}
6913
Eric Laurent1e693b52014-07-09 15:03:28 -07006914
6915uint32_t AudioPolicyManager::AudioPort::pickSamplingRate() const
6916{
6917 // special case for uninitialized dynamic profile
6918 if (mSamplingRates.size() == 1 && mSamplingRates[0] == 0) {
6919 return 0;
6920 }
6921
Eric Laurent828bcff2014-09-07 12:26:06 -07006922 // For direct outputs, pick minimum sampling rate: this helps ensuring that the
6923 // channel count / sampling rate combination chosen will be supported by the connected
6924 // sink
6925 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6926 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6927 uint32_t samplingRate = UINT_MAX;
6928 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6929 if ((mSamplingRates[i] < samplingRate) && (mSamplingRates[i] > 0)) {
6930 samplingRate = mSamplingRates[i];
6931 }
6932 }
6933 return (samplingRate == UINT_MAX) ? 0 : samplingRate;
6934 }
6935
Eric Laurent1e693b52014-07-09 15:03:28 -07006936 uint32_t samplingRate = 0;
6937 uint32_t maxRate = MAX_MIXER_SAMPLING_RATE;
6938
6939 // For mixed output and inputs, use max mixer sampling rates. Do not
6940 // limit sampling rate otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006941 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006942 maxRate = UINT_MAX;
6943 }
6944 for (size_t i = 0; i < mSamplingRates.size(); i ++) {
6945 if ((mSamplingRates[i] > samplingRate) && (mSamplingRates[i] <= maxRate)) {
6946 samplingRate = mSamplingRates[i];
6947 }
6948 }
6949 return samplingRate;
6950}
6951
6952audio_channel_mask_t AudioPolicyManager::AudioPort::pickChannelMask() const
6953{
6954 // special case for uninitialized dynamic profile
6955 if (mChannelMasks.size() == 1 && mChannelMasks[0] == 0) {
6956 return AUDIO_CHANNEL_NONE;
6957 }
Eric Laurent1e693b52014-07-09 15:03:28 -07006958 audio_channel_mask_t channelMask = AUDIO_CHANNEL_NONE;
Eric Laurent828bcff2014-09-07 12:26:06 -07006959
6960 // For direct outputs, pick minimum channel count: this helps ensuring that the
6961 // channel count / sampling rate combination chosen will be supported by the connected
6962 // sink
6963 if ((mType == AUDIO_PORT_TYPE_MIX) && (mRole == AUDIO_PORT_ROLE_SOURCE) &&
6964 (mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD))) {
6965 uint32_t channelCount = UINT_MAX;
6966 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6967 uint32_t cnlCount;
6968 if (mUseInChannelMask) {
6969 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6970 } else {
6971 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6972 }
6973 if ((cnlCount < channelCount) && (cnlCount > 0)) {
6974 channelMask = mChannelMasks[i];
6975 channelCount = cnlCount;
6976 }
6977 }
6978 return channelMask;
6979 }
6980
Eric Laurent1e693b52014-07-09 15:03:28 -07006981 uint32_t channelCount = 0;
6982 uint32_t maxCount = MAX_MIXER_CHANNEL_COUNT;
6983
6984 // For mixed output and inputs, use max mixer channel count. Do not
6985 // limit channel count otherwise
Eric Laurent828bcff2014-09-07 12:26:06 -07006986 if (mType != AUDIO_PORT_TYPE_MIX) {
Eric Laurent1e693b52014-07-09 15:03:28 -07006987 maxCount = UINT_MAX;
6988 }
6989 for (size_t i = 0; i < mChannelMasks.size(); i ++) {
6990 uint32_t cnlCount;
6991 if (mUseInChannelMask) {
6992 cnlCount = audio_channel_count_from_in_mask(mChannelMasks[i]);
6993 } else {
6994 cnlCount = audio_channel_count_from_out_mask(mChannelMasks[i]);
6995 }
6996 if ((cnlCount > channelCount) && (cnlCount <= maxCount)) {
6997 channelMask = mChannelMasks[i];
Eric Laurent828bcff2014-09-07 12:26:06 -07006998 channelCount = cnlCount;
Eric Laurent1e693b52014-07-09 15:03:28 -07006999 }
7000 }
7001 return channelMask;
7002}
7003
Andy Hung9a605382014-07-28 16:16:31 -07007004/* format in order of increasing preference */
Eric Laurent1e693b52014-07-09 15:03:28 -07007005const audio_format_t AudioPolicyManager::AudioPort::sPcmFormatCompareTable[] = {
7006 AUDIO_FORMAT_DEFAULT,
7007 AUDIO_FORMAT_PCM_16_BIT,
Eric Laurenta2049942014-07-21 17:49:25 -07007008 AUDIO_FORMAT_PCM_8_24_BIT,
Eric Laurent1e693b52014-07-09 15:03:28 -07007009 AUDIO_FORMAT_PCM_24_BIT_PACKED,
Eric Laurenta2049942014-07-21 17:49:25 -07007010 AUDIO_FORMAT_PCM_32_BIT,
Andy Hung9a605382014-07-28 16:16:31 -07007011 AUDIO_FORMAT_PCM_FLOAT,
Eric Laurent1e693b52014-07-09 15:03:28 -07007012};
7013
7014int AudioPolicyManager::AudioPort::compareFormats(audio_format_t format1,
7015 audio_format_t format2)
7016{
7017 // NOTE: AUDIO_FORMAT_INVALID is also considered not PCM and will be compared equal to any
7018 // compressed format and better than any PCM format. This is by design of pickFormat()
7019 if (!audio_is_linear_pcm(format1)) {
7020 if (!audio_is_linear_pcm(format2)) {
7021 return 0;
7022 }
7023 return 1;
7024 }
7025 if (!audio_is_linear_pcm(format2)) {
7026 return -1;
7027 }
7028
7029 int index1 = -1, index2 = -1;
7030 for (size_t i = 0;
7031 (i < ARRAY_SIZE(sPcmFormatCompareTable)) && ((index1 == -1) || (index2 == -1));
7032 i ++) {
7033 if (sPcmFormatCompareTable[i] == format1) {
7034 index1 = i;
7035 }
7036 if (sPcmFormatCompareTable[i] == format2) {
7037 index2 = i;
7038 }
7039 }
7040 // format1 not found => index1 < 0 => format2 > format1
7041 // format2 not found => index2 < 0 => format2 < format1
7042 return index1 - index2;
7043}
7044
7045audio_format_t AudioPolicyManager::AudioPort::pickFormat() const
7046{
7047 // special case for uninitialized dynamic profile
7048 if (mFormats.size() == 1 && mFormats[0] == 0) {
7049 return AUDIO_FORMAT_DEFAULT;
7050 }
7051
7052 audio_format_t format = AUDIO_FORMAT_DEFAULT;
Andy Hung9a605382014-07-28 16:16:31 -07007053 audio_format_t bestFormat =
7054 AudioPolicyManager::AudioPort::sPcmFormatCompareTable[
7055 ARRAY_SIZE(AudioPolicyManager::AudioPort::sPcmFormatCompareTable) - 1];
Eric Laurent1e693b52014-07-09 15:03:28 -07007056 // For mixed output and inputs, use best mixer output format. Do not
7057 // limit format otherwise
7058 if ((mType != AUDIO_PORT_TYPE_MIX) ||
7059 ((mRole == AUDIO_PORT_ROLE_SOURCE) &&
Eric Laurentd8622372014-07-27 13:47:31 -07007060 (((mFlags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) != 0)))) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007061 bestFormat = AUDIO_FORMAT_INVALID;
7062 }
7063
7064 for (size_t i = 0; i < mFormats.size(); i ++) {
7065 if ((compareFormats(mFormats[i], format) > 0) &&
7066 (compareFormats(mFormats[i], bestFormat) <= 0)) {
7067 format = mFormats[i];
7068 }
7069 }
7070 return format;
7071}
7072
Eric Laurenta121f902014-06-03 13:32:54 -07007073status_t AudioPolicyManager::AudioPort::checkGain(const struct audio_gain_config *gainConfig,
7074 int index) const
7075{
7076 if (index < 0 || (size_t)index >= mGains.size()) {
7077 return BAD_VALUE;
7078 }
7079 return mGains[index]->checkConfig(gainConfig);
7080}
7081
Eric Laurent1afeecb2014-05-14 08:52:28 -07007082void AudioPolicyManager::AudioPort::dump(int fd, int spaces) const
7083{
7084 const size_t SIZE = 256;
7085 char buffer[SIZE];
7086 String8 result;
7087
7088 if (mName.size() != 0) {
7089 snprintf(buffer, SIZE, "%*s- name: %s\n", spaces, "", mName.string());
7090 result.append(buffer);
7091 }
7092
7093 if (mSamplingRates.size() != 0) {
7094 snprintf(buffer, SIZE, "%*s- sampling rates: ", spaces, "");
7095 result.append(buffer);
7096 for (size_t i = 0; i < mSamplingRates.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007097 if (i == 0 && mSamplingRates[i] == 0) {
7098 snprintf(buffer, SIZE, "Dynamic");
7099 } else {
7100 snprintf(buffer, SIZE, "%d", mSamplingRates[i]);
7101 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007102 result.append(buffer);
7103 result.append(i == (mSamplingRates.size() - 1) ? "" : ", ");
7104 }
7105 result.append("\n");
7106 }
7107
7108 if (mChannelMasks.size() != 0) {
7109 snprintf(buffer, SIZE, "%*s- channel masks: ", spaces, "");
7110 result.append(buffer);
7111 for (size_t i = 0; i < mChannelMasks.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007112 ALOGV("AudioPort::dump mChannelMasks %zu %08x", i, mChannelMasks[i]);
7113
7114 if (i == 0 && mChannelMasks[i] == 0) {
7115 snprintf(buffer, SIZE, "Dynamic");
7116 } else {
7117 snprintf(buffer, SIZE, "0x%04x", mChannelMasks[i]);
7118 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007119 result.append(buffer);
7120 result.append(i == (mChannelMasks.size() - 1) ? "" : ", ");
7121 }
7122 result.append("\n");
7123 }
7124
7125 if (mFormats.size() != 0) {
7126 snprintf(buffer, SIZE, "%*s- formats: ", spaces, "");
7127 result.append(buffer);
7128 for (size_t i = 0; i < mFormats.size(); i++) {
Eric Laurent1e693b52014-07-09 15:03:28 -07007129 const char *formatStr = enumToString(sFormatNameToEnumTable,
7130 ARRAY_SIZE(sFormatNameToEnumTable),
7131 mFormats[i]);
7132 if (i == 0 && strcmp(formatStr, "") == 0) {
7133 snprintf(buffer, SIZE, "Dynamic");
7134 } else {
Eric Laurentcf2c0212014-07-25 16:20:43 -07007135 snprintf(buffer, SIZE, "%s", formatStr);
Eric Laurent1e693b52014-07-09 15:03:28 -07007136 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007137 result.append(buffer);
7138 result.append(i == (mFormats.size() - 1) ? "" : ", ");
7139 }
7140 result.append("\n");
7141 }
7142 write(fd, result.string(), result.size());
7143 if (mGains.size() != 0) {
7144 snprintf(buffer, SIZE, "%*s- gains:\n", spaces, "");
7145 write(fd, buffer, strlen(buffer) + 1);
7146 result.append(buffer);
7147 for (size_t i = 0; i < mGains.size(); i++) {
7148 mGains[i]->dump(fd, spaces + 2, i);
7149 }
7150 }
7151}
7152
7153// --- AudioGain class implementation
7154
Eric Laurenta121f902014-06-03 13:32:54 -07007155AudioPolicyManager::AudioGain::AudioGain(int index, bool useInChannelMask)
Eric Laurent1afeecb2014-05-14 08:52:28 -07007156{
Eric Laurenta121f902014-06-03 13:32:54 -07007157 mIndex = index;
7158 mUseInChannelMask = useInChannelMask;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007159 memset(&mGain, 0, sizeof(struct audio_gain));
7160}
7161
Eric Laurenta121f902014-06-03 13:32:54 -07007162void AudioPolicyManager::AudioGain::getDefaultConfig(struct audio_gain_config *config)
7163{
7164 config->index = mIndex;
7165 config->mode = mGain.mode;
7166 config->channel_mask = mGain.channel_mask;
7167 if ((mGain.mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7168 config->values[0] = mGain.default_value;
7169 } else {
7170 uint32_t numValues;
7171 if (mUseInChannelMask) {
7172 numValues = audio_channel_count_from_in_mask(mGain.channel_mask);
7173 } else {
7174 numValues = audio_channel_count_from_out_mask(mGain.channel_mask);
7175 }
7176 for (size_t i = 0; i < numValues; i++) {
7177 config->values[i] = mGain.default_value;
7178 }
7179 }
7180 if ((mGain.mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7181 config->ramp_duration_ms = mGain.min_ramp_ms;
7182 }
7183}
7184
7185status_t AudioPolicyManager::AudioGain::checkConfig(const struct audio_gain_config *config)
7186{
7187 if ((config->mode & ~mGain.mode) != 0) {
7188 return BAD_VALUE;
7189 }
7190 if ((config->mode & AUDIO_GAIN_MODE_JOINT) == AUDIO_GAIN_MODE_JOINT) {
7191 if ((config->values[0] < mGain.min_value) ||
7192 (config->values[0] > mGain.max_value)) {
7193 return BAD_VALUE;
7194 }
7195 } else {
7196 if ((config->channel_mask & ~mGain.channel_mask) != 0) {
7197 return BAD_VALUE;
7198 }
7199 uint32_t numValues;
7200 if (mUseInChannelMask) {
7201 numValues = audio_channel_count_from_in_mask(config->channel_mask);
7202 } else {
7203 numValues = audio_channel_count_from_out_mask(config->channel_mask);
7204 }
7205 for (size_t i = 0; i < numValues; i++) {
7206 if ((config->values[i] < mGain.min_value) ||
7207 (config->values[i] > mGain.max_value)) {
7208 return BAD_VALUE;
7209 }
7210 }
7211 }
7212 if ((config->mode & AUDIO_GAIN_MODE_RAMP) == AUDIO_GAIN_MODE_RAMP) {
7213 if ((config->ramp_duration_ms < mGain.min_ramp_ms) ||
7214 (config->ramp_duration_ms > mGain.max_ramp_ms)) {
7215 return BAD_VALUE;
7216 }
7217 }
7218 return NO_ERROR;
7219}
7220
Eric Laurent1afeecb2014-05-14 08:52:28 -07007221void AudioPolicyManager::AudioGain::dump(int fd, int spaces, int index) const
7222{
7223 const size_t SIZE = 256;
7224 char buffer[SIZE];
7225 String8 result;
7226
7227 snprintf(buffer, SIZE, "%*sGain %d:\n", spaces, "", index+1);
7228 result.append(buffer);
7229 snprintf(buffer, SIZE, "%*s- mode: %08x\n", spaces, "", mGain.mode);
7230 result.append(buffer);
7231 snprintf(buffer, SIZE, "%*s- channel_mask: %08x\n", spaces, "", mGain.channel_mask);
7232 result.append(buffer);
7233 snprintf(buffer, SIZE, "%*s- min_value: %d mB\n", spaces, "", mGain.min_value);
7234 result.append(buffer);
7235 snprintf(buffer, SIZE, "%*s- max_value: %d mB\n", spaces, "", mGain.max_value);
7236 result.append(buffer);
7237 snprintf(buffer, SIZE, "%*s- default_value: %d mB\n", spaces, "", mGain.default_value);
7238 result.append(buffer);
7239 snprintf(buffer, SIZE, "%*s- step_value: %d mB\n", spaces, "", mGain.step_value);
7240 result.append(buffer);
7241 snprintf(buffer, SIZE, "%*s- min_ramp_ms: %d ms\n", spaces, "", mGain.min_ramp_ms);
7242 result.append(buffer);
7243 snprintf(buffer, SIZE, "%*s- max_ramp_ms: %d ms\n", spaces, "", mGain.max_ramp_ms);
7244 result.append(buffer);
7245
7246 write(fd, result.string(), result.size());
7247}
7248
Eric Laurent1f2f2232014-06-02 12:01:23 -07007249// --- AudioPortConfig class implementation
7250
7251AudioPolicyManager::AudioPortConfig::AudioPortConfig()
7252{
7253 mSamplingRate = 0;
7254 mChannelMask = AUDIO_CHANNEL_NONE;
7255 mFormat = AUDIO_FORMAT_INVALID;
7256 mGain.index = -1;
7257}
7258
Eric Laurenta121f902014-06-03 13:32:54 -07007259status_t AudioPolicyManager::AudioPortConfig::applyAudioPortConfig(
7260 const struct audio_port_config *config,
7261 struct audio_port_config *backupConfig)
7262{
7263 struct audio_port_config localBackupConfig;
7264 status_t status = NO_ERROR;
7265
7266 localBackupConfig.config_mask = config->config_mask;
7267 toAudioPortConfig(&localBackupConfig);
7268
Marco Nelissen961ec212014-08-25 15:58:39 -07007269 sp<AudioPort> audioport = getAudioPort();
7270 if (audioport == 0) {
Eric Laurenta121f902014-06-03 13:32:54 -07007271 status = NO_INIT;
7272 goto exit;
7273 }
7274 if (config->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007275 status = audioport->checkExactSamplingRate(config->sample_rate);
Eric Laurenta121f902014-06-03 13:32:54 -07007276 if (status != NO_ERROR) {
7277 goto exit;
7278 }
7279 mSamplingRate = config->sample_rate;
7280 }
7281 if (config->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007282 status = audioport->checkExactChannelMask(config->channel_mask);
Eric Laurenta121f902014-06-03 13:32:54 -07007283 if (status != NO_ERROR) {
7284 goto exit;
7285 }
7286 mChannelMask = config->channel_mask;
7287 }
7288 if (config->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007289 status = audioport->checkFormat(config->format);
Eric Laurenta121f902014-06-03 13:32:54 -07007290 if (status != NO_ERROR) {
7291 goto exit;
7292 }
7293 mFormat = config->format;
7294 }
7295 if (config->config_mask & AUDIO_PORT_CONFIG_GAIN) {
Marco Nelissen961ec212014-08-25 15:58:39 -07007296 status = audioport->checkGain(&config->gain, config->gain.index);
Eric Laurenta121f902014-06-03 13:32:54 -07007297 if (status != NO_ERROR) {
7298 goto exit;
7299 }
7300 mGain = config->gain;
7301 }
7302
7303exit:
7304 if (status != NO_ERROR) {
7305 applyAudioPortConfig(&localBackupConfig);
7306 }
7307 if (backupConfig != NULL) {
7308 *backupConfig = localBackupConfig;
7309 }
7310 return status;
7311}
7312
Eric Laurent1f2f2232014-06-02 12:01:23 -07007313void AudioPolicyManager::AudioPortConfig::toAudioPortConfig(
7314 struct audio_port_config *dstConfig,
7315 const struct audio_port_config *srcConfig) const
7316{
7317 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE) {
7318 dstConfig->sample_rate = mSamplingRate;
7319 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_SAMPLE_RATE)) {
7320 dstConfig->sample_rate = srcConfig->sample_rate;
7321 }
7322 } else {
7323 dstConfig->sample_rate = 0;
7324 }
7325 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK) {
7326 dstConfig->channel_mask = mChannelMask;
7327 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_CHANNEL_MASK)) {
7328 dstConfig->channel_mask = srcConfig->channel_mask;
7329 }
7330 } else {
7331 dstConfig->channel_mask = AUDIO_CHANNEL_NONE;
7332 }
7333 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT) {
7334 dstConfig->format = mFormat;
7335 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_FORMAT)) {
7336 dstConfig->format = srcConfig->format;
7337 }
7338 } else {
7339 dstConfig->format = AUDIO_FORMAT_INVALID;
7340 }
7341 if (dstConfig->config_mask & AUDIO_PORT_CONFIG_GAIN) {
7342 dstConfig->gain = mGain;
7343 if ((srcConfig != NULL) && (srcConfig->config_mask & AUDIO_PORT_CONFIG_GAIN)) {
7344 dstConfig->gain = srcConfig->gain;
7345 }
7346 } else {
7347 dstConfig->gain.index = -1;
7348 }
7349 if (dstConfig->gain.index != -1) {
7350 dstConfig->config_mask |= AUDIO_PORT_CONFIG_GAIN;
7351 } else {
7352 dstConfig->config_mask &= ~AUDIO_PORT_CONFIG_GAIN;
7353 }
7354}
7355
Eric Laurent1c333e22014-05-20 10:48:17 -07007356// --- IOProfile class implementation
7357
Eric Laurent1afeecb2014-05-14 08:52:28 -07007358AudioPolicyManager::IOProfile::IOProfile(const String8& name, audio_port_role_t role,
Eric Laurent1f2f2232014-06-02 12:01:23 -07007359 const sp<HwModule>& module)
Eric Laurent1e693b52014-07-09 15:03:28 -07007360 : AudioPort(name, AUDIO_PORT_TYPE_MIX, role, module)
Eric Laurente552edb2014-03-10 17:42:56 -07007361{
7362}
7363
Eric Laurente0720872014-03-11 09:30:41 -07007364AudioPolicyManager::IOProfile::~IOProfile()
Eric Laurente552edb2014-03-10 17:42:56 -07007365{
7366}
7367
7368// checks if the IO profile is compatible with specified parameters.
7369// Sampling rate, format and channel mask must be specified in order to
7370// get a valid a match
Eric Laurente0720872014-03-11 09:30:41 -07007371bool AudioPolicyManager::IOProfile::isCompatibleProfile(audio_devices_t device,
Eric Laurent275e8e92014-11-30 15:14:47 -08007372 String8 address,
7373 uint32_t samplingRate,
7374 uint32_t *updatedSamplingRate,
7375 audio_format_t format,
7376 audio_channel_mask_t channelMask,
7377 uint32_t flags) const
Eric Laurente552edb2014-03-10 17:42:56 -07007378{
Glenn Kastencbd48022014-07-24 13:46:44 -07007379 const bool isPlaybackThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SOURCE;
7380 const bool isRecordThread = mType == AUDIO_PORT_TYPE_MIX && mRole == AUDIO_PORT_ROLE_SINK;
7381 ALOG_ASSERT(isPlaybackThread != isRecordThread);
Eric Laurente552edb2014-03-10 17:42:56 -07007382
Eric Laurent275e8e92014-11-30 15:14:47 -08007383 if (device != AUDIO_DEVICE_NONE && mSupportedDevices.getDevice(device, address) == 0) {
Glenn Kastencbd48022014-07-24 13:46:44 -07007384 return false;
7385 }
7386
7387 if (samplingRate == 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07007388 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007389 }
7390 uint32_t myUpdatedSamplingRate = samplingRate;
7391 if (isPlaybackThread && checkExactSamplingRate(samplingRate) != NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007392 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007393 }
7394 if (isRecordThread && checkCompatibleSamplingRate(samplingRate, &myUpdatedSamplingRate) !=
7395 NO_ERROR) {
Eric Laurente552edb2014-03-10 17:42:56 -07007396 return false;
Glenn Kastencbd48022014-07-24 13:46:44 -07007397 }
7398
7399 if (!audio_is_valid_format(format) || checkFormat(format) != NO_ERROR) {
7400 return false;
7401 }
7402
7403 if (isPlaybackThread && (!audio_is_output_channel(channelMask) ||
7404 checkExactChannelMask(channelMask) != NO_ERROR)) {
7405 return false;
7406 }
7407 if (isRecordThread && (!audio_is_input_channel(channelMask) ||
7408 checkCompatibleChannelMask(channelMask) != NO_ERROR)) {
7409 return false;
7410 }
7411
7412 if (isPlaybackThread && (mFlags & flags) != flags) {
7413 return false;
7414 }
7415 // The only input flag that is allowed to be different is the fast flag.
7416 // An existing fast stream is compatible with a normal track request.
7417 // An existing normal stream is compatible with a fast track request,
7418 // but the fast request will be denied by AudioFlinger and converted to normal track.
Eric Laurent5dbe4712014-09-19 19:04:57 -07007419 if (isRecordThread && ((mFlags ^ flags) &
Glenn Kastencbd48022014-07-24 13:46:44 -07007420 ~AUDIO_INPUT_FLAG_FAST)) {
7421 return false;
7422 }
7423
7424 if (updatedSamplingRate != NULL) {
7425 *updatedSamplingRate = myUpdatedSamplingRate;
7426 }
7427 return true;
Eric Laurente552edb2014-03-10 17:42:56 -07007428}
7429
Eric Laurente0720872014-03-11 09:30:41 -07007430void AudioPolicyManager::IOProfile::dump(int fd)
Eric Laurente552edb2014-03-10 17:42:56 -07007431{
7432 const size_t SIZE = 256;
7433 char buffer[SIZE];
7434 String8 result;
7435
Eric Laurent1afeecb2014-05-14 08:52:28 -07007436 AudioPort::dump(fd, 4);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007437
Eric Laurente552edb2014-03-10 17:42:56 -07007438 snprintf(buffer, SIZE, " - flags: 0x%04x\n", mFlags);
7439 result.append(buffer);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007440 snprintf(buffer, SIZE, " - devices:\n");
7441 result.append(buffer);
Eric Laurente552edb2014-03-10 17:42:56 -07007442 write(fd, result.string(), result.size());
Eric Laurent1afeecb2014-05-14 08:52:28 -07007443 for (size_t i = 0; i < mSupportedDevices.size(); i++) {
7444 mSupportedDevices[i]->dump(fd, 6, i);
7445 }
Eric Laurente552edb2014-03-10 17:42:56 -07007446}
7447
Eric Laurentd4692962014-05-05 18:13:44 -07007448void AudioPolicyManager::IOProfile::log()
7449{
7450 const size_t SIZE = 256;
7451 char buffer[SIZE];
7452 String8 result;
7453
7454 ALOGV(" - sampling rates: ");
7455 for (size_t i = 0; i < mSamplingRates.size(); i++) {
7456 ALOGV(" %d", mSamplingRates[i]);
7457 }
7458
7459 ALOGV(" - channel masks: ");
7460 for (size_t i = 0; i < mChannelMasks.size(); i++) {
7461 ALOGV(" 0x%04x", mChannelMasks[i]);
7462 }
7463
7464 ALOGV(" - formats: ");
7465 for (size_t i = 0; i < mFormats.size(); i++) {
7466 ALOGV(" 0x%08x", mFormats[i]);
7467 }
7468
7469 ALOGV(" - devices: 0x%04x\n", mSupportedDevices.types());
7470 ALOGV(" - flags: 0x%04x\n", mFlags);
7471}
7472
7473
Eric Laurent3a4311c2014-03-17 12:00:47 -07007474// --- DeviceDescriptor implementation
Eric Laurente552edb2014-03-10 17:42:56 -07007475
Eric Laurent1f2f2232014-06-02 12:01:23 -07007476
7477AudioPolicyManager::DeviceDescriptor::DeviceDescriptor(const String8& name, audio_devices_t type) :
7478 AudioPort(name, AUDIO_PORT_TYPE_DEVICE,
7479 audio_is_output_device(type) ? AUDIO_PORT_ROLE_SINK :
7480 AUDIO_PORT_ROLE_SOURCE,
7481 NULL),
Eric Laurent1e693b52014-07-09 15:03:28 -07007482 mDeviceType(type), mAddress(""), mId(0)
Eric Laurent1f2f2232014-06-02 12:01:23 -07007483{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007484}
7485
Eric Laurent3a4311c2014-03-17 12:00:47 -07007486bool AudioPolicyManager::DeviceDescriptor::equals(const sp<DeviceDescriptor>& other) const
Eric Laurente552edb2014-03-10 17:42:56 -07007487{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007488 // Devices are considered equal if they:
7489 // - are of the same type (a device type cannot be AUDIO_DEVICE_NONE)
7490 // - have the same address or one device does not specify the address
7491 // - have the same channel mask or one device does not specify the channel mask
Eric Laurent1c333e22014-05-20 10:48:17 -07007492 return (mDeviceType == other->mDeviceType) &&
Eric Laurent3a4311c2014-03-17 12:00:47 -07007493 (mAddress == "" || other->mAddress == "" || mAddress == other->mAddress) &&
Eric Laurent2f8a36f2014-03-26 19:05:55 -07007494 (mChannelMask == 0 || other->mChannelMask == 0 ||
Eric Laurent3a4311c2014-03-17 12:00:47 -07007495 mChannelMask == other->mChannelMask);
7496}
7497
Eric Laurent1db89b92015-01-27 18:21:09 -08007498void AudioPolicyManager::DeviceDescriptor::loadGains(cnode *root)
7499{
7500 AudioPort::loadGains(root);
7501 if (mGains.size() > 0) {
7502 mGains[0]->getDefaultConfig(&mGain);
7503 }
7504}
7505
7506
Eric Laurent3a4311c2014-03-17 12:00:47 -07007507void AudioPolicyManager::DeviceVector::refreshTypes()
7508{
Eric Laurent1c333e22014-05-20 10:48:17 -07007509 mDeviceTypes = AUDIO_DEVICE_NONE;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007510 for(size_t i = 0; i < size(); i++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007511 mDeviceTypes |= itemAt(i)->mDeviceType;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007512 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007513 ALOGV("DeviceVector::refreshTypes() mDeviceTypes %08x", mDeviceTypes);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007514}
7515
7516ssize_t AudioPolicyManager::DeviceVector::indexOf(const sp<DeviceDescriptor>& item) const
7517{
7518 for(size_t i = 0; i < size(); i++) {
7519 if (item->equals(itemAt(i))) {
7520 return i;
Eric Laurente552edb2014-03-10 17:42:56 -07007521 }
7522 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07007523 return -1;
Eric Laurente552edb2014-03-10 17:42:56 -07007524}
7525
Eric Laurent3a4311c2014-03-17 12:00:47 -07007526ssize_t AudioPolicyManager::DeviceVector::add(const sp<DeviceDescriptor>& item)
Eric Laurente552edb2014-03-10 17:42:56 -07007527{
Eric Laurent3a4311c2014-03-17 12:00:47 -07007528 ssize_t ret = indexOf(item);
7529
7530 if (ret < 0) {
7531 ret = SortedVector::add(item);
7532 if (ret >= 0) {
7533 refreshTypes();
7534 }
7535 } else {
Eric Laurent1c333e22014-05-20 10:48:17 -07007536 ALOGW("DeviceVector::add device %08x already in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007537 ret = -1;
7538 }
7539 return ret;
Eric Laurente552edb2014-03-10 17:42:56 -07007540}
7541
Eric Laurent3a4311c2014-03-17 12:00:47 -07007542ssize_t AudioPolicyManager::DeviceVector::remove(const sp<DeviceDescriptor>& item)
7543{
7544 size_t i;
7545 ssize_t ret = indexOf(item);
7546
7547 if (ret < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007548 ALOGW("DeviceVector::remove device %08x not in", item->mDeviceType);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007549 } else {
7550 ret = SortedVector::removeAt(ret);
7551 if (ret >= 0) {
7552 refreshTypes();
7553 }
7554 }
7555 return ret;
7556}
7557
7558void AudioPolicyManager::DeviceVector::loadDevicesFromType(audio_devices_t types)
7559{
7560 DeviceVector deviceList;
7561
7562 uint32_t role_bit = AUDIO_DEVICE_BIT_IN & types;
7563 types &= ~role_bit;
7564
7565 while (types) {
7566 uint32_t i = 31 - __builtin_clz(types);
7567 uint32_t type = 1 << i;
7568 types &= ~type;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007569 add(new DeviceDescriptor(String8(""), type | role_bit));
Eric Laurent3a4311c2014-03-17 12:00:47 -07007570 }
7571}
7572
Eric Laurent1afeecb2014-05-14 08:52:28 -07007573void AudioPolicyManager::DeviceVector::loadDevicesFromName(char *name,
7574 const DeviceVector& declaredDevices)
7575{
7576 char *devName = strtok(name, "|");
7577 while (devName != NULL) {
7578 if (strlen(devName) != 0) {
7579 audio_devices_t type = stringToEnum(sDeviceNameToEnumTable,
7580 ARRAY_SIZE(sDeviceNameToEnumTable),
7581 devName);
7582 if (type != AUDIO_DEVICE_NONE) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007583 sp<DeviceDescriptor> dev = new DeviceDescriptor(String8(""), type);
Eric Laurent275e8e92014-11-30 15:14:47 -08007584 if (type == AUDIO_DEVICE_IN_REMOTE_SUBMIX ||
7585 type == AUDIO_DEVICE_OUT_REMOTE_SUBMIX ) {
Jean-Michel Trivifd4c1482014-08-06 16:02:28 -07007586 dev->mAddress = String8("0");
7587 }
7588 add(dev);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007589 } else {
7590 sp<DeviceDescriptor> deviceDesc =
7591 declaredDevices.getDeviceFromName(String8(devName));
7592 if (deviceDesc != 0) {
7593 add(deviceDesc);
7594 }
7595 }
7596 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007597 devName = strtok(NULL, "|");
Eric Laurent1afeecb2014-05-14 08:52:28 -07007598 }
7599}
7600
Eric Laurent1c333e22014-05-20 10:48:17 -07007601sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDevice(
7602 audio_devices_t type, String8 address) const
7603{
7604 sp<DeviceDescriptor> device;
7605 for (size_t i = 0; i < size(); i++) {
7606 if (itemAt(i)->mDeviceType == type) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007607 if (address == "" || itemAt(i)->mAddress == address) {
7608 device = itemAt(i);
7609 if (itemAt(i)->mAddress == address) {
7610 break;
7611 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007612 }
7613 }
7614 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007615 ALOGV("DeviceVector::getDevice() for type %08x address %s found %p",
Eric Laurent1c333e22014-05-20 10:48:17 -07007616 type, address.string(), device.get());
7617 return device;
7618}
7619
Eric Laurent6a94d692014-05-20 11:18:06 -07007620sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromId(
7621 audio_port_handle_t id) const
7622{
7623 sp<DeviceDescriptor> device;
7624 for (size_t i = 0; i < size(); i++) {
Mark Salyzynbeb9e302014-06-18 16:33:15 -07007625 ALOGV("DeviceVector::getDeviceFromId(%d) itemAt(%zu)->mId %d", id, i, itemAt(i)->mId);
Eric Laurent6a94d692014-05-20 11:18:06 -07007626 if (itemAt(i)->mId == id) {
7627 device = itemAt(i);
7628 break;
7629 }
7630 }
7631 return device;
7632}
7633
Eric Laurent1c333e22014-05-20 10:48:17 -07007634AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromType(
7635 audio_devices_t type) const
7636{
7637 DeviceVector devices;
7638 for (size_t i = 0; (i < size()) && (type != AUDIO_DEVICE_NONE); i++) {
7639 if (itemAt(i)->mDeviceType & type & ~AUDIO_DEVICE_BIT_IN) {
7640 devices.add(itemAt(i));
7641 type &= ~itemAt(i)->mDeviceType;
7642 ALOGV("DeviceVector::getDevicesFromType() for type %x found %p",
7643 itemAt(i)->mDeviceType, itemAt(i).get());
7644 }
7645 }
7646 return devices;
7647}
7648
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007649AudioPolicyManager::DeviceVector AudioPolicyManager::DeviceVector::getDevicesFromTypeAddr(
7650 audio_devices_t type, String8 address) const
7651{
7652 DeviceVector devices;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007653 for (size_t i = 0; i < size(); i++) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007654 if (itemAt(i)->mDeviceType == type) {
7655 if (itemAt(i)->mAddress == address) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007656 devices.add(itemAt(i));
7657 }
7658 }
7659 }
7660 return devices;
7661}
7662
Eric Laurent1afeecb2014-05-14 08:52:28 -07007663sp<AudioPolicyManager::DeviceDescriptor> AudioPolicyManager::DeviceVector::getDeviceFromName(
7664 const String8& name) const
7665{
7666 sp<DeviceDescriptor> device;
7667 for (size_t i = 0; i < size(); i++) {
7668 if (itemAt(i)->mName == name) {
7669 device = itemAt(i);
7670 break;
7671 }
7672 }
7673 return device;
7674}
7675
Eric Laurent6a94d692014-05-20 11:18:06 -07007676void AudioPolicyManager::DeviceDescriptor::toAudioPortConfig(
7677 struct audio_port_config *dstConfig,
7678 const struct audio_port_config *srcConfig) const
Eric Laurent1c333e22014-05-20 10:48:17 -07007679{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007680 dstConfig->config_mask = AUDIO_PORT_CONFIG_CHANNEL_MASK|AUDIO_PORT_CONFIG_GAIN;
7681 if (srcConfig != NULL) {
Eric Laurent84c70242014-06-23 08:46:27 -07007682 dstConfig->config_mask |= srcConfig->config_mask;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007683 }
7684
7685 AudioPortConfig::toAudioPortConfig(dstConfig, srcConfig);
7686
Eric Laurent6a94d692014-05-20 11:18:06 -07007687 dstConfig->id = mId;
7688 dstConfig->role = audio_is_output_device(mDeviceType) ?
Eric Laurent1c333e22014-05-20 10:48:17 -07007689 AUDIO_PORT_ROLE_SINK : AUDIO_PORT_ROLE_SOURCE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007690 dstConfig->type = AUDIO_PORT_TYPE_DEVICE;
Eric Laurent6a94d692014-05-20 11:18:06 -07007691 dstConfig->ext.device.type = mDeviceType;
7692 dstConfig->ext.device.hw_module = mModule->mHandle;
7693 strncpy(dstConfig->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
Eric Laurent1c333e22014-05-20 10:48:17 -07007694}
7695
7696void AudioPolicyManager::DeviceDescriptor::toAudioPort(struct audio_port *port) const
7697{
Eric Laurent83b88082014-06-20 18:31:16 -07007698 ALOGV("DeviceDescriptor::toAudioPort() handle %d type %x", mId, mDeviceType);
Eric Laurent1c333e22014-05-20 10:48:17 -07007699 AudioPort::toAudioPort(port);
7700 port->id = mId;
Eric Laurent6a94d692014-05-20 11:18:06 -07007701 toAudioPortConfig(&port->active_config);
Eric Laurent1c333e22014-05-20 10:48:17 -07007702 port->ext.device.type = mDeviceType;
Eric Laurent6a94d692014-05-20 11:18:06 -07007703 port->ext.device.hw_module = mModule->mHandle;
Eric Laurent1c333e22014-05-20 10:48:17 -07007704 strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
7705}
7706
Eric Laurent1afeecb2014-05-14 08:52:28 -07007707status_t AudioPolicyManager::DeviceDescriptor::dump(int fd, int spaces, int index) const
Eric Laurent3a4311c2014-03-17 12:00:47 -07007708{
7709 const size_t SIZE = 256;
7710 char buffer[SIZE];
Eric Laurent1afeecb2014-05-14 08:52:28 -07007711 String8 result;
Eric Laurent3a4311c2014-03-17 12:00:47 -07007712
Eric Laurent1afeecb2014-05-14 08:52:28 -07007713 snprintf(buffer, SIZE, "%*sDevice %d:\n", spaces, "", index+1);
7714 result.append(buffer);
7715 if (mId != 0) {
7716 snprintf(buffer, SIZE, "%*s- id: %2d\n", spaces, "", mId);
7717 result.append(buffer);
7718 }
7719 snprintf(buffer, SIZE, "%*s- type: %-48s\n", spaces, "",
7720 enumToString(sDeviceNameToEnumTable,
7721 ARRAY_SIZE(sDeviceNameToEnumTable),
7722 mDeviceType));
7723 result.append(buffer);
7724 if (mAddress.size() != 0) {
7725 snprintf(buffer, SIZE, "%*s- address: %-32s\n", spaces, "", mAddress.string());
7726 result.append(buffer);
7727 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007728 write(fd, result.string(), result.size());
7729 AudioPort::dump(fd, spaces);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007730
7731 return NO_ERROR;
7732}
7733
Eric Laurent4d416952014-08-10 14:07:09 -07007734status_t AudioPolicyManager::AudioPatch::dump(int fd, int spaces, int index) const
7735{
7736 const size_t SIZE = 256;
7737 char buffer[SIZE];
7738 String8 result;
7739
7740
7741 snprintf(buffer, SIZE, "%*sAudio patch %d:\n", spaces, "", index+1);
7742 result.append(buffer);
7743 snprintf(buffer, SIZE, "%*s- handle: %2d\n", spaces, "", mHandle);
7744 result.append(buffer);
7745 snprintf(buffer, SIZE, "%*s- audio flinger handle: %2d\n", spaces, "", mAfPatchHandle);
7746 result.append(buffer);
7747 snprintf(buffer, SIZE, "%*s- owner uid: %2d\n", spaces, "", mUid);
7748 result.append(buffer);
7749 snprintf(buffer, SIZE, "%*s- %d sources:\n", spaces, "", mPatch.num_sources);
7750 result.append(buffer);
7751 for (size_t i = 0; i < mPatch.num_sources; i++) {
7752 if (mPatch.sources[i].type == AUDIO_PORT_TYPE_DEVICE) {
7753 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7754 mPatch.sources[i].id, enumToString(sDeviceNameToEnumTable,
7755 ARRAY_SIZE(sDeviceNameToEnumTable),
7756 mPatch.sources[i].ext.device.type));
7757 } else {
7758 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7759 mPatch.sources[i].id, mPatch.sources[i].ext.mix.handle);
7760 }
7761 result.append(buffer);
7762 }
7763 snprintf(buffer, SIZE, "%*s- %d sinks:\n", spaces, "", mPatch.num_sinks);
7764 result.append(buffer);
7765 for (size_t i = 0; i < mPatch.num_sinks; i++) {
7766 if (mPatch.sinks[i].type == AUDIO_PORT_TYPE_DEVICE) {
7767 snprintf(buffer, SIZE, "%*s- Device ID %d %s\n", spaces + 2, "",
7768 mPatch.sinks[i].id, enumToString(sDeviceNameToEnumTable,
7769 ARRAY_SIZE(sDeviceNameToEnumTable),
7770 mPatch.sinks[i].ext.device.type));
7771 } else {
7772 snprintf(buffer, SIZE, "%*s- Mix ID %d I/O handle %d\n", spaces + 2, "",
7773 mPatch.sinks[i].id, mPatch.sinks[i].ext.mix.handle);
7774 }
7775 result.append(buffer);
7776 }
7777
7778 write(fd, result.string(), result.size());
7779 return NO_ERROR;
7780}
Eric Laurent3a4311c2014-03-17 12:00:47 -07007781
7782// --- audio_policy.conf file parsing
7783
Eric Laurent5dbe4712014-09-19 19:04:57 -07007784uint32_t AudioPolicyManager::parseOutputFlagNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007785{
7786 uint32_t flag = 0;
7787
7788 // it is OK to cast name to non const here as we are not going to use it after
7789 // strtok() modifies it
7790 char *flagName = strtok(name, "|");
7791 while (flagName != NULL) {
7792 if (strlen(flagName) != 0) {
Eric Laurent5dbe4712014-09-19 19:04:57 -07007793 flag |= stringToEnum(sOutputFlagNameToEnumTable,
7794 ARRAY_SIZE(sOutputFlagNameToEnumTable),
Eric Laurente552edb2014-03-10 17:42:56 -07007795 flagName);
7796 }
7797 flagName = strtok(NULL, "|");
7798 }
7799 //force direct flag if offload flag is set: offloading implies a direct output stream
7800 // and all common behaviors are driven by checking only the direct flag
7801 // this should normally be set appropriately in the policy configuration file
7802 if ((flag & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
7803 flag |= AUDIO_OUTPUT_FLAG_DIRECT;
7804 }
7805
Eric Laurent5dbe4712014-09-19 19:04:57 -07007806 return flag;
7807}
7808
7809uint32_t AudioPolicyManager::parseInputFlagNames(char *name)
7810{
7811 uint32_t flag = 0;
7812
7813 // it is OK to cast name to non const here as we are not going to use it after
7814 // strtok() modifies it
7815 char *flagName = strtok(name, "|");
7816 while (flagName != NULL) {
7817 if (strlen(flagName) != 0) {
7818 flag |= stringToEnum(sInputFlagNameToEnumTable,
7819 ARRAY_SIZE(sInputFlagNameToEnumTable),
7820 flagName);
7821 }
7822 flagName = strtok(NULL, "|");
7823 }
7824 return flag;
Eric Laurente552edb2014-03-10 17:42:56 -07007825}
7826
Eric Laurente0720872014-03-11 09:30:41 -07007827audio_devices_t AudioPolicyManager::parseDeviceNames(char *name)
Eric Laurente552edb2014-03-10 17:42:56 -07007828{
7829 uint32_t device = 0;
7830
7831 char *devName = strtok(name, "|");
7832 while (devName != NULL) {
7833 if (strlen(devName) != 0) {
7834 device |= stringToEnum(sDeviceNameToEnumTable,
7835 ARRAY_SIZE(sDeviceNameToEnumTable),
7836 devName);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007837 }
Eric Laurente552edb2014-03-10 17:42:56 -07007838 devName = strtok(NULL, "|");
Eric Laurent3a4311c2014-03-17 12:00:47 -07007839 }
Eric Laurente552edb2014-03-10 17:42:56 -07007840 return device;
7841}
7842
Eric Laurente0720872014-03-11 09:30:41 -07007843void AudioPolicyManager::loadHwModule(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007844{
Eric Laurente552edb2014-03-10 17:42:56 -07007845 status_t status = NAME_NOT_FOUND;
Eric Laurent1afeecb2014-05-14 08:52:28 -07007846 cnode *node;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007847 sp<HwModule> module = new HwModule(root->name);
Eric Laurente552edb2014-03-10 17:42:56 -07007848
Eric Laurent1afeecb2014-05-14 08:52:28 -07007849 node = config_find(root, DEVICES_TAG);
7850 if (node != NULL) {
7851 node = node->first_child;
7852 while (node) {
7853 ALOGV("loadHwModule() loading device %s", node->name);
7854 status_t tmpStatus = module->loadDevice(node);
7855 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7856 status = tmpStatus;
7857 }
7858 node = node->next;
7859 }
7860 }
7861 node = config_find(root, OUTPUTS_TAG);
Eric Laurente552edb2014-03-10 17:42:56 -07007862 if (node != NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007863 node = node->first_child;
7864 while (node) {
7865 ALOGV("loadHwModule() loading output %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007866 status_t tmpStatus = module->loadOutput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007867 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7868 status = tmpStatus;
7869 }
7870 node = node->next;
7871 }
7872 }
7873 node = config_find(root, INPUTS_TAG);
7874 if (node != NULL) {
7875 node = node->first_child;
7876 while (node) {
7877 ALOGV("loadHwModule() loading input %s", node->name);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007878 status_t tmpStatus = module->loadInput(node);
Eric Laurente552edb2014-03-10 17:42:56 -07007879 if (status == NAME_NOT_FOUND || status == NO_ERROR) {
7880 status = tmpStatus;
7881 }
7882 node = node->next;
7883 }
7884 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007885 loadGlobalConfig(root, module);
7886
Eric Laurente552edb2014-03-10 17:42:56 -07007887 if (status == NO_ERROR) {
7888 mHwModules.add(module);
Eric Laurente552edb2014-03-10 17:42:56 -07007889 }
7890}
7891
Eric Laurente0720872014-03-11 09:30:41 -07007892void AudioPolicyManager::loadHwModules(cnode *root)
Eric Laurente552edb2014-03-10 17:42:56 -07007893{
7894 cnode *node = config_find(root, AUDIO_HW_MODULE_TAG);
7895 if (node == NULL) {
7896 return;
7897 }
7898
7899 node = node->first_child;
7900 while (node) {
7901 ALOGV("loadHwModules() loading module %s", node->name);
7902 loadHwModule(node);
7903 node = node->next;
7904 }
7905}
7906
Eric Laurent1f2f2232014-06-02 12:01:23 -07007907void AudioPolicyManager::loadGlobalConfig(cnode *root, const sp<HwModule>& module)
Eric Laurente552edb2014-03-10 17:42:56 -07007908{
7909 cnode *node = config_find(root, GLOBAL_CONFIG_TAG);
Eric Laurenteb108a42014-06-06 14:56:52 -07007910
Eric Laurente552edb2014-03-10 17:42:56 -07007911 if (node == NULL) {
7912 return;
7913 }
Eric Laurent1afeecb2014-05-14 08:52:28 -07007914 DeviceVector declaredDevices;
7915 if (module != NULL) {
7916 declaredDevices = module->mDeclaredDevices;
7917 }
7918
Eric Laurente552edb2014-03-10 17:42:56 -07007919 node = node->first_child;
7920 while (node) {
7921 if (strcmp(ATTACHED_OUTPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007922 mAvailableOutputDevices.loadDevicesFromName((char *)node->value,
7923 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007924 ALOGV("loadGlobalConfig() Attached Output Devices %08x",
7925 mAvailableOutputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007926 } else if (strcmp(DEFAULT_OUTPUT_DEVICE_TAG, node->name) == 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007927 audio_devices_t device = (audio_devices_t)stringToEnum(sDeviceNameToEnumTable,
Eric Laurente552edb2014-03-10 17:42:56 -07007928 ARRAY_SIZE(sDeviceNameToEnumTable),
7929 (char *)node->value);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007930 if (device != AUDIO_DEVICE_NONE) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007931 mDefaultOutputDevice = new DeviceDescriptor(String8(""), device);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007932 } else {
7933 ALOGW("loadGlobalConfig() default device not specified");
7934 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007935 ALOGV("loadGlobalConfig() mDefaultOutputDevice %08x", mDefaultOutputDevice->mDeviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007936 } else if (strcmp(ATTACHED_INPUT_DEVICES_TAG, node->name) == 0) {
Eric Laurent1afeecb2014-05-14 08:52:28 -07007937 mAvailableInputDevices.loadDevicesFromName((char *)node->value,
7938 declaredDevices);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007939 ALOGV("loadGlobalConfig() Available InputDevices %08x", mAvailableInputDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07007940 } else if (strcmp(SPEAKER_DRC_ENABLED_TAG, node->name) == 0) {
7941 mSpeakerDrcEnabled = stringToBool((char *)node->value);
7942 ALOGV("loadGlobalConfig() mSpeakerDrcEnabled = %d", mSpeakerDrcEnabled);
Eric Laurenteb108a42014-06-06 14:56:52 -07007943 } else if (strcmp(AUDIO_HAL_VERSION_TAG, node->name) == 0) {
7944 uint32_t major, minor;
7945 sscanf((char *)node->value, "%u.%u", &major, &minor);
7946 module->mHalVersion = HARDWARE_DEVICE_API_VERSION(major, minor);
7947 ALOGV("loadGlobalConfig() mHalVersion = %04x major %u minor %u",
7948 module->mHalVersion, major, minor);
Eric Laurente552edb2014-03-10 17:42:56 -07007949 }
7950 node = node->next;
7951 }
7952}
7953
Eric Laurente0720872014-03-11 09:30:41 -07007954status_t AudioPolicyManager::loadAudioPolicyConfig(const char *path)
Eric Laurente552edb2014-03-10 17:42:56 -07007955{
7956 cnode *root;
7957 char *data;
7958
7959 data = (char *)load_file(path, NULL);
7960 if (data == NULL) {
7961 return -ENODEV;
7962 }
7963 root = config_node("", "");
7964 config_load(root, data);
7965
Eric Laurente552edb2014-03-10 17:42:56 -07007966 loadHwModules(root);
Eric Laurent1afeecb2014-05-14 08:52:28 -07007967 // legacy audio_policy.conf files have one global_configuration section
7968 loadGlobalConfig(root, getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY));
Eric Laurente552edb2014-03-10 17:42:56 -07007969 config_free(root);
7970 free(root);
7971 free(data);
7972
7973 ALOGI("loadAudioPolicyConfig() loaded %s\n", path);
7974
7975 return NO_ERROR;
7976}
7977
Eric Laurente0720872014-03-11 09:30:41 -07007978void AudioPolicyManager::defaultAudioPolicyConfig(void)
Eric Laurente552edb2014-03-10 17:42:56 -07007979{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007980 sp<HwModule> module;
Eric Laurent1c333e22014-05-20 10:48:17 -07007981 sp<IOProfile> profile;
Eric Laurent1f2f2232014-06-02 12:01:23 -07007982 sp<DeviceDescriptor> defaultInputDevice = new DeviceDescriptor(String8(""),
7983 AUDIO_DEVICE_IN_BUILTIN_MIC);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007984 mAvailableOutputDevices.add(mDefaultOutputDevice);
7985 mAvailableInputDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007986
7987 module = new HwModule("primary");
7988
Eric Laurent1afeecb2014-05-14 08:52:28 -07007989 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SOURCE, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007990 profile->mSamplingRates.add(44100);
7991 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
7992 profile->mChannelMasks.add(AUDIO_CHANNEL_OUT_STEREO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07007993 profile->mSupportedDevices.add(mDefaultOutputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07007994 profile->mFlags = AUDIO_OUTPUT_FLAG_PRIMARY;
7995 module->mOutputProfiles.add(profile);
7996
Eric Laurent1afeecb2014-05-14 08:52:28 -07007997 profile = new IOProfile(String8("primary"), AUDIO_PORT_ROLE_SINK, module);
Eric Laurente552edb2014-03-10 17:42:56 -07007998 profile->mSamplingRates.add(8000);
7999 profile->mFormats.add(AUDIO_FORMAT_PCM_16_BIT);
8000 profile->mChannelMasks.add(AUDIO_CHANNEL_IN_MONO);
Eric Laurent3a4311c2014-03-17 12:00:47 -07008001 profile->mSupportedDevices.add(defaultInputDevice);
Eric Laurente552edb2014-03-10 17:42:56 -07008002 module->mInputProfiles.add(profile);
8003
8004 mHwModules.add(module);
8005}
8006
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07008007audio_stream_type_t AudioPolicyManager::streamTypefromAttributesInt(const audio_attributes_t *attr)
8008{
8009 // flags to stream type mapping
8010 if ((attr->flags & AUDIO_FLAG_AUDIBILITY_ENFORCED) == AUDIO_FLAG_AUDIBILITY_ENFORCED) {
8011 return AUDIO_STREAM_ENFORCED_AUDIBLE;
8012 }
8013 if ((attr->flags & AUDIO_FLAG_SCO) == AUDIO_FLAG_SCO) {
8014 return AUDIO_STREAM_BLUETOOTH_SCO;
8015 }
Jean-Michel Trivi79ad4382015-01-29 10:49:39 -08008016 if ((attr->flags & AUDIO_FLAG_BEACON) == AUDIO_FLAG_BEACON) {
8017 return AUDIO_STREAM_TTS;
8018 }
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07008019
8020 // usage to stream type mapping
8021 switch (attr->usage) {
8022 case AUDIO_USAGE_MEDIA:
8023 case AUDIO_USAGE_GAME:
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07008024 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8025 return AUDIO_STREAM_MUSIC;
Eric Laurent223fd5c2014-11-11 13:43:36 -08008026 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
Eric Laurente83b55d2014-11-14 10:06:21 -08008027 if (isStreamActive(AUDIO_STREAM_ALARM)) {
8028 return AUDIO_STREAM_ALARM;
8029 }
8030 if (isStreamActive(AUDIO_STREAM_RING)) {
8031 return AUDIO_STREAM_RING;
8032 }
8033 if (isInCall()) {
8034 return AUDIO_STREAM_VOICE_CALL;
8035 }
Eric Laurent223fd5c2014-11-11 13:43:36 -08008036 return AUDIO_STREAM_ACCESSIBILITY;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07008037 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8038 return AUDIO_STREAM_SYSTEM;
8039 case AUDIO_USAGE_VOICE_COMMUNICATION:
8040 return AUDIO_STREAM_VOICE_CALL;
8041
8042 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8043 return AUDIO_STREAM_DTMF;
8044
8045 case AUDIO_USAGE_ALARM:
8046 return AUDIO_STREAM_ALARM;
8047 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8048 return AUDIO_STREAM_RING;
8049
8050 case AUDIO_USAGE_NOTIFICATION:
8051 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8052 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8053 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8054 case AUDIO_USAGE_NOTIFICATION_EVENT:
8055 return AUDIO_STREAM_NOTIFICATION;
8056
8057 case AUDIO_USAGE_UNKNOWN:
8058 default:
8059 return AUDIO_STREAM_MUSIC;
8060 }
8061}
Eric Laurente83b55d2014-11-14 10:06:21 -08008062
8063bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa) {
8064 // has flags that map to a strategy?
8065 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8066 return true;
8067 }
8068
8069 // has known usage?
8070 switch (paa->usage) {
8071 case AUDIO_USAGE_UNKNOWN:
8072 case AUDIO_USAGE_MEDIA:
8073 case AUDIO_USAGE_VOICE_COMMUNICATION:
8074 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8075 case AUDIO_USAGE_ALARM:
8076 case AUDIO_USAGE_NOTIFICATION:
8077 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8078 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8079 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8080 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8081 case AUDIO_USAGE_NOTIFICATION_EVENT:
8082 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8083 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8084 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8085 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008086 case AUDIO_USAGE_VIRTUAL_SOURCE:
Eric Laurente83b55d2014-11-14 10:06:21 -08008087 break;
8088 default:
8089 return false;
8090 }
8091 return true;
8092}
8093
Eric Laurente552edb2014-03-10 17:42:56 -07008094}; // namespace android